Variables let you store and reuse information easily. Dynamic content means your program can change what it shows based on those variables.
0
0
Variables and dynamic content in LangChain
Introduction
You want to remember user input and use it later in a conversation.
You need to customize responses based on different situations.
You want to build a chatbot that adapts answers depending on previous messages.
You want to insert changing data like dates or names into your text.
You want to create templates that fill in details automatically.
Syntax
LangChain
from langchain import PromptTemplate # Define a template with variables inside curly braces template = "Hello, {name}! Today is {day}." # Create a PromptTemplate object prompt = PromptTemplate(template=template, input_variables=["name", "day"]) # Fill variables with actual values filled_prompt = prompt.format(name="Alice", day="Monday")
Variables are placed inside curly braces {} in the template string.
You must list all variable names in input_variables when creating the PromptTemplate.
Examples
This example shows a simple template with one variable
color. It prints a sentence with the color filled in.LangChain
template = "My favorite color is {color}." prompt = PromptTemplate(template=template, input_variables=["color"]) print(prompt.format(color="blue"))
Here, two variables
greeting and name are used to create a friendly message.LangChain
template = "{greeting}, {name}!" prompt = PromptTemplate(template=template, input_variables=["greeting", "name"]) print(prompt.format(greeting="Hi", name="Bob"))
This example shows how to insert a single dynamic value like the day of the week.
LangChain
template = "Today is {day}." prompt = PromptTemplate(template=template, input_variables=["day"]) print(prompt.format(day="Friday"))
Sample Program
This program creates a message template for appointment reminders. It fills in the title, last name, and date dynamically.
LangChain
from langchain import PromptTemplate # Create a template with variables template = "Dear {title} {last_name}, your appointment is on {date}." prompt = PromptTemplate(template=template, input_variables=["title", "last_name", "date"]) # Fill variables with actual data message = prompt.format(title="Dr.", last_name="Smith", date="June 10th") print(message)
OutputSuccess
Important Notes
Always list all variables you want to use in the input_variables list.
If you forget to provide a variable value when calling format, it will raise an error.
Using variables makes your prompts flexible and reusable for many situations.
Summary
Variables let you insert changing information into text templates.
Use PromptTemplate with input_variables to define which parts change.
Fill variables with format to get the final text with dynamic content.