Prefixed Prompt Templates#

Say you have a chain with the following prompt template:

[1]:
from langchain.prompts.prompt import PromptTemplate

shell_template = PromptTemplate.from_template("Enter in the {shell} command you want to run: ")
shell_template.format(shell="bash")
[1]:
'Enter in the bash command you want to run: '

Unfortunately, the LLM won’t know how to complete this prompt without context. At the same time, if you’ve figured out a good prompt for the LLM to complete shell commands for you, you’d want to be able to easily compose this with arbitrary prior contexts.

Enter the PrefixedTemplate:

[2]:
from langchain_contrib.prompts import PrefixedTemplate

get_shell_template = PrefixedTemplate(shell_template)

Now you can define a new template that adds prior context to the current one:

[3]:
complete_task_template = get_shell_template(prefix="Your task is to {task}.", joiner=" ")
complete_task_template.format(task="delete asdf.txt", shell="bash")
[3]:
'Your task is to delete asdf.txt. Enter in the bash command you want to run: '

And you can reuse shell_template for a different prior context:

[4]:
redo_command_template = get_shell_template(
    prefix="Your previous command `{command}` resulted in `{output}`. Please try again.",
    joiner="\n\n",
)
print(redo_command_template.format(command="rm asdf.txt", output="Permission denied.", shell="bash"))
Your previous command `rm asdf.txt` resulted in `Permission denied.`. Please try again.

Enter in the bash command you want to run:

Prefixing chat prompts#

This also works automatically with adding context to chat prompts:

[5]:
from langchain.prompts.chat import SystemMessagePromptTemplate

complete_task_chat_template = get_shell_template(
    prefix=SystemMessagePromptTemplate.from_template("Your task is to {task}."),
)
complete_task_chat_template.format_prompt(task="delete asdf.txt", shell="bash")
[5]:
ChatPromptValue(messages=[SystemMessage(content='Your task is to delete asdf.txt.', additional_kwargs={}), HumanMessage(content='Enter in the bash command you want to run: ', additional_kwargs={})])