What is Prompt Template in Langchain: Simple Explanation and Example
PromptTemplate in Langchain is a way to create reusable text patterns with placeholders that you fill with specific values before sending to a language model. It helps you organize and customize prompts easily by separating fixed text from dynamic parts.How It Works
Think of a PromptTemplate like a fill-in-the-blank worksheet. You write a sentence with blanks (placeholders) where you want to insert different words or phrases later. When you want to use the prompt, you fill those blanks with actual values.
This makes it easy to reuse the same prompt structure for different questions or tasks without rewriting the whole text. Langchain takes your template and the values you provide, then combines them into a complete prompt to send to the language model.
Example
This example shows how to create a prompt template with a placeholder for a person's name and then fill it to generate a greeting prompt.
from langchain.prompts import PromptTemplate # Define a prompt template with a placeholder {name} prompt = PromptTemplate( input_variables=["name"], template="Hello, {name}! How can I help you today?" ) # Fill the template with a specific name filled_prompt = prompt.format(name="Alice") print(filled_prompt)
When to Use
Use PromptTemplate when you want to create flexible prompts that change based on input data. It is helpful when you have many similar prompts that differ only in some details, like names, topics, or questions.
For example, customer support bots can use prompt templates to personalize messages for each user. Or, in content generation, you can create templates for different article topics and fill them dynamically.
Key Points
- Reusable: Write prompt patterns once and reuse with different inputs.
- Clear structure: Separates fixed text from dynamic parts.
- Easy to maintain: Change the template without touching the code that fills it.
- Supports multiple variables: You can have many placeholders in one template.