Bird
Raised Fist0
LangChainframework~10 mins

Variables and dynamic content in LangChain - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Variables and dynamic content
Define Variables
Insert Variables into Template
Generate Dynamic Content
Use Output in Chain or App
Update Variables if Needed
Back to Insert Variables
This flow shows how variables are defined, inserted into templates, and used to generate dynamic content in LangChain.
Execution Sample
LangChain
from langchain import PromptTemplate

template = "Hello, {name}!"
prompt = PromptTemplate(template=template, input_variables=["name"])
output = prompt.format(name="Alice")
This code defines a template with a variable and generates a greeting by filling in the variable.
Execution Table
StepActionVariable StateOutput
1Define template with variable {name}template='Hello, {name}!'
2Create PromptTemplate with input_variables=['name']input_variables=['name']
3Call prompt.format(name='Alice')name='Alice'Hello, Alice!
4Output generatedname='Alice'Hello, Alice!
💡 Variables inserted and dynamic content generated successfully.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
templateundefinedHello, {name}!Hello, {name}!Hello, {name}!
input_variablesundefined['name']['name']['name']
nameundefinedundefinedAliceAlice
outputundefinedundefinedHello, Alice!Hello, Alice!
Key Moments - 2 Insights
Why do we need to specify input_variables when creating a PromptTemplate?
Specifying input_variables tells LangChain which parts of the template are dynamic placeholders to replace. See execution_table step 2 where input_variables=['name'] enables substitution.
What happens if we call prompt.format() without providing a variable value?
LangChain will raise an error because the template expects a value for 'name'. This is shown in execution_table step 3 where 'name' must be provided to generate output.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the value of 'output'?
AHello, {name}!
BHello, Alice!
Cname='Alice'
Dundefined
💡 Hint
Check the 'Output' column in execution_table row with Step 3.
At which step is the variable 'name' assigned the value 'Alice'?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Variable State' column in execution_table to see when 'name' changes.
If we change the template to "Hi, {user}!", what else must we update to generate output?
ANo changes needed, just call format(name='Alice')
BRemove input_variables list
CChange input_variables to ['user'] and provide user='value' in format()
DChange output variable name
💡 Hint
Refer to key_moments about input_variables and variable substitution.
Concept Snapshot
Variables and dynamic content in LangChain:
- Define a template string with placeholders like {name}
- Specify input_variables list matching placeholders
- Use PromptTemplate.format() with variable values
- Output is the template with variables replaced
- Missing variables cause errors
- Update variables and template together for dynamic content
Full Transcript
In LangChain, variables let you create templates with placeholders that you fill dynamically. First, you define a template string with placeholders inside curly braces, like {name}. Then, you tell LangChain which variables to expect by listing them in input_variables. When you call the format method on the PromptTemplate, you provide actual values for these variables. LangChain replaces the placeholders with the values and generates the final output string. If you forget to provide a variable, LangChain will raise an error. This process allows you to create flexible prompts and content that change based on input values.

Practice

(1/5)
1. What is the main purpose of using variables in a Langchain PromptTemplate?
easy
A. To create multiple templates at once
B. To insert changing information into the text dynamically
C. To store the final output text permanently
D. To make the template text static and unchangeable

Solution

  1. Step 1: Understand the role of variables in templates

    Variables are placeholders that allow parts of the text to change based on input.
  2. Step 2: Connect variables to dynamic content

    Using variables lets you insert different values each time you use the template, making it dynamic.
  3. Final Answer:

    To insert changing information into the text dynamically -> Option B
  4. Quick Check:

    Variables = dynamic content insertion [OK]
Hint: Variables let text change based on input values [OK]
Common Mistakes:
  • Thinking variables make text static
  • Confusing variables with final output storage
  • Believing variables create multiple templates automatically
2. Which of the following is the correct way to define a PromptTemplate with variables in Langchain?
easy
A. PromptTemplate(template="Hello {name}", input_variables=name)
B. PromptTemplate(template="Hello name", input_variables=[name])
C. PromptTemplate(template="Hello {name}", input_variables=["name"])
D. PromptTemplate(template="Hello {name}", variables=["name"])

Solution

  1. Step 1: Check the syntax for defining variables

    The input_variables parameter must be a list of strings naming the variables used in the template.
  2. Step 2: Match the template placeholders with variable names

    The template uses curly braces around variable names like {name} to mark where to insert values.
  3. Final Answer:

    PromptTemplate(template="Hello {name}", input_variables=["name"]) -> Option C
  4. Quick Check:

    Correct syntax = PromptTemplate(template="Hello {name}", input_variables=["name"]) [OK]
Hint: Use curly braces and list of strings for variables [OK]
Common Mistakes:
  • Forgetting quotes around variable names
  • Using wrong parameter name like variables instead of input_variables
  • Not using curly braces in template
3. Given the code:
template = PromptTemplate(template="Hello {user}, today is {day}.", input_variables=["user", "day"])
result = template.format(user="Alice", day="Monday")
print(result)

What will be printed?
medium
A. Hello Alice, today is Monday.
B. Hello {user}, today is {day}.
C. Hello user, today is day.
D. Error: Missing variables

Solution

  1. Step 1: Understand how format fills variables

    The format method replaces {user} with "Alice" and {day} with "Monday".
  2. Step 2: Predict the final string after formatting

    The placeholders are replaced, so the printed string is "Hello Alice, today is Monday."
  3. Final Answer:

    Hello Alice, today is Monday. -> Option A
  4. Quick Check:

    format replaces variables correctly = Hello Alice, today is Monday. [OK]
Hint: format() replaces placeholders with given values [OK]
Common Mistakes:
  • Printing template string without formatting
  • Confusing variable names with values
  • Expecting an error when variables are provided
4. What is wrong with this code snippet?
template = PromptTemplate(template="Hi {name}", input_variables=["name"])
result = template.format(nam="Bob")
print(result)
medium
A. input_variables should be a string, not a list
B. The template string is missing curly braces
C. format method cannot be used with PromptTemplate
D. The variable name in format is misspelled, causing a KeyError

Solution

  1. Step 1: Compare variable names in template and format call

    The template expects variable "name" but format uses "nam" which is incorrect.
  2. Step 2: Understand the error caused by mismatch

    This mismatch causes a KeyError because "name" is not provided in format arguments.
  3. Final Answer:

    The variable name in format is misspelled, causing a KeyError -> Option D
  4. Quick Check:

    Variable name mismatch = KeyError [OK]
Hint: Check variable names match exactly in template and format [OK]
Common Mistakes:
  • Assuming format ignores missing variables
  • Thinking input_variables must be a string
  • Believing format method is invalid here
5. You want to create a PromptTemplate that dynamically inserts a user's name and their favorite color, but if the color is not provided, it should default to "blue". Which approach correctly handles this dynamic content with a default value?
hard
A. Use input_variables=["name", "color"] and call format with color="blue" if missing
B. Define template with {name} and {color}, but omit color from input_variables to default it
C. Use input_variables=["name"] only and write template as "Hello {name}, your color is blue"
D. Set input_variables=["name", "color"] and use a conditional expression inside template like {color or 'blue'}

Solution

  1. Step 1: Understand how to provide default values

    Langchain's PromptTemplate requires all variables listed in input_variables to be provided when formatting.
  2. Step 2: Provide default value in code when calling format

    By including color in input_variables and passing color="blue" if missing, you ensure the template fills correctly.
  3. Final Answer:

    Use input_variables=["name", "color"] and call format with color="blue" if missing -> Option A
  4. Quick Check:

    Default values handled in format call = Use input_variables=["name", "color"] and call format with color="blue" if missing [OK]
Hint: Provide all variables; set defaults when calling format [OK]
Common Mistakes:
  • Omitting variables from input_variables to default
  • Trying to use Python expressions inside template strings
  • Hardcoding default text instead of using variables