Chained Prompt Template#

Sometimes, you may want to append prompt templates together. For example:

  • When you want to reuse the same chunk of templating in multiple places

  • When you are running a chain that depends on prior context

In that case, you can use the ChainedPromptTemplate to chain these templates together. (Note the possibility of intermingling PromptTemplate’s with plain strings.)

[1]:
from langchain.prompts.prompt import PromptTemplate
from langchain_contrib.chains import ChainedPromptTemplate

template = ChainedPromptTemplate([
    PromptTemplate.from_template("You have access to {tools}."),
    "Your objective is to answer the question: {question}?",
    "What is your next action?",
], joiner="\n\n")
print(template.format(tools="Search", question="how high is Everest"))
You have access to Search.

Your objective is to answer the question: how high is Everest?

What is your next action?

Chaining chat templates#

You can also chain arbitrary chat prompt templates or message prompt templates together. Plain strings are intepreted as Human messages.

[2]:
from langchain.prompts.chat import ChatPromptTemplate, SystemMessagePromptTemplate

template = ChainedPromptTemplate([
    SystemMessagePromptTemplate.from_template("You have access to {tools}."),
    ChatPromptTemplate.from_messages([
        SystemMessagePromptTemplate.from_template("Your objective is to answer human questions."),
    ]),
    "Tell me: {question}?",
])
template.format_prompt(tools="Search", question="how high is Everest")
[2]:
ChatPromptValue(messages=[SystemMessage(content='You have access to Search.', additional_kwargs={}), SystemMessage(content='Your objective is to answer human questions.', additional_kwargs={}), HumanMessage(content='Tell me: how high is Everest?', additional_kwargs={})])

Prefixing prompt templates#

If you specifically want to just prepend a prefix to the current prompt template, as opposed to the much more general capabilities that ChainedPromptTemplate offers, then head on to the next session to learn about using PrefixedTemplate to do just that.