How to Create Prompt Template in Langchain: Simple Guide
In Langchain, create a prompt template using the
PromptTemplate class by defining a template string with placeholders and specifying input variables. This lets you easily generate dynamic prompts by filling in values for those variables.Syntax
The PromptTemplate class requires two main parts: a template string with placeholders wrapped in curly braces, and a list of input_variables that match those placeholders. When you call format() on the template, you provide values for these variables to create the final prompt string.
python
from langchain.prompts import PromptTemplate prompt = PromptTemplate( input_variables=["name", "age"], template="Hello, my name is {name} and I am {age} years old." ) final_prompt = prompt.format(name="Alice", age=30) print(final_prompt)
Output
Hello, my name is Alice and I am 30 years old.
Example
This example shows how to create a prompt template that asks for a user's favorite color and hobby. It then formats the prompt by filling in those values.
python
from langchain.prompts import PromptTemplate # Define the prompt template with placeholders prompt = PromptTemplate( input_variables=["color", "hobby"], template="What do you think about the color {color} when you are {hobby}?" ) # Fill in the placeholders with actual values filled_prompt = prompt.format(color="blue", hobby="painting") print(filled_prompt)
Output
What do you think about the color blue when you are painting?
Common Pitfalls
Common mistakes include:
- Not matching
input_variablesnames exactly with placeholders in the template string. - Forgetting to provide all required variables when calling
format(). - Using incorrect placeholder syntax (must be
{variable}).
Here is an example of a wrong and right way:
python
# Wrong: variable name mismatch from langchain.prompts import PromptTemplate try: prompt_wrong = PromptTemplate( input_variables=["username"], template="Hello, {name}!" ) prompt_wrong.format(username="Bob") except KeyError as e: print(f"Error: {e}") # Right: matching variable names prompt_right = PromptTemplate( input_variables=["name"], template="Hello, {name}!" ) print(prompt_right.format(name="Bob"))
Output
Error: 'name'
Hello, Bob!
Quick Reference
Remember these key points when creating prompt templates in Langchain:
- Use
PromptTemplatewithtemplateandinput_variables. - Placeholders in the template must be wrapped in curly braces
{}. - Call
format()with all required variables to get the final prompt string.
Key Takeaways
Use PromptTemplate with matching input_variables and placeholders to create dynamic prompts.
Always wrap placeholders in curly braces {} inside the template string.
Provide all required variables when calling format() to avoid errors.
Check variable names carefully to prevent KeyError exceptions.
PromptTemplate helps keep prompt creation clean and reusable.