...
/Prompting Strategies: Prompt Templates
Prompting Strategies: Prompt Templates
Learn how to implement LangChain prompt templates.
We'll cover the following...
LangChain facilitates the use of model-agnostic templates, allowing for the ease of use of existing templates across various language models.
The PromptTemplate utilizes Python’s str.format method for its templating mechanism: str.format(*args, **kwargs). This method is invoked on a string that can contain plain text with replacement fields enclosed within braces {}. These fields can specify either the numeric index of a positional argument or the name of a keyword argument. The method produces a new string where each replacement field is substituted with the string representation of the corresponding argument.
Example:
print("The sum of 1 + 2 is {0}".format(1+2))
PromptTemplate
We use PromptTemplate to create a template for a string prompt.
from langchain_core.prompts import PromptTemplateprompt = "I need you to book a reservation for me tonight at {time} at {place}"prompt_template = PromptTemplate.from_template(prompt)# Print the formatted promptprint(prompt_template.format(time="9:00 PM", place="LaVie restaurant"))
In this code, we perform the following steps:
Line 1: We import the
PromptTemplatefrom thelangchain_core.promptsmodule.Line 3: A prompt string is defined with placeholders for time and place.
Line 4: We create an instance of
PromptTemplateusing thefrom_templateclass method, passing the previously defined prompt string.Lines 6–7: We use the format method of the
prompt_templateobject to insert specific details into the prompt. In this case, the placeholderstimeandplaceare replaced with "9:00 PM" and "LaVie restaurant", respectively. This demonstrates how the prompt can be customized dynamically, and then we print it.
Zero-shot ChatPromptTemplate
This template effectively handles the dynamic creation of conversational content, enabling developers to build more engaging and contextually aware chatbots and AI assistants that can adapt to user inputs seamlessly.