0
0
LangChainframework~5 mins

PromptTemplate basics in LangChain

Choose your learning style9 modes available
Introduction
A PromptTemplate helps you create messages with blanks that you fill in later. It makes writing prompts easier and less error-prone.
When you want to reuse a message format but change some details each time.
When you need to build prompts dynamically based on user input.
When you want to keep your prompt code clean and organized.
When you want to avoid repeating the same text in multiple places.
When you want to separate the prompt design from the data you insert.
Syntax
LangChain
from langchain.prompts import PromptTemplate

prompt = PromptTemplate(
    input_variables=["name"],
    template="Hello, {name}! Welcome to LangChain."
)
Use curly braces { } to mark where variables go in the template.
input_variables is a list of names you will fill in later.
Examples
This template asks about weather in a city you provide.
LangChain
prompt = PromptTemplate(
    input_variables=["city"],
    template="Tell me about the weather in {city}."
)
This template uses two variables to create a sentence.
LangChain
prompt = PromptTemplate(
    input_variables=["food", "drink"],
    template="I like {food} with a glass of {drink}."
)
You can have a template with no variables for fixed text.
LangChain
prompt = PromptTemplate(
    input_variables=[],
    template="Hello! This is a fixed message."
)
Sample Program
This program creates a prompt template that greets a person by name. It then fills in the name 'Alice' and prints the full message.
LangChain
from langchain.prompts import PromptTemplate

# Create a prompt template with one variable
prompt = PromptTemplate(
    input_variables=["name"],
    template="Hello, {name}! How are you today?"
)

# Fill in the variable to get the final prompt
final_prompt = prompt.format(name="Alice")
print(final_prompt)
OutputSuccess
Important Notes
Always list all variable names in input_variables to avoid errors.
Use the format() method to fill in variables and get the final prompt string.
PromptTemplate helps keep your code clean and easy to update.
Summary
PromptTemplate lets you create message templates with placeholders.
You fill in placeholders later using the format() method.
It helps reuse and organize prompts in your code.