Bird
Raised Fist0
LangChainframework~20 mins

Context formatting and injection in LangChain - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Context Injection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does context injection affect prompt output?
Given a LangChain prompt template that injects user context, what will be the output when the user input is "weather"?
LangChain
from langchain.prompts import PromptTemplate

context = "Today is sunny."
prompt = PromptTemplate(
    input_variables=["context", "query"],
    template="Context: {context}\nUser Query: {query}\nAnswer:"  
)

formatted_prompt = prompt.format(context=context, query="weather")
print(formatted_prompt)
A
Context: Today is sunny.
User Query: weather
Answer:
B
Context: weather
User Query: Today is sunny.
Answer:
C
User Query: weather
Answer: Today is sunny.
DAnswer: Context: Today is sunny. User Query: weather
Attempts:
2 left
💡 Hint
Look at how the variables are mapped in the template and what values are passed to format().
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in context injection
Which option contains a syntax error when defining a LangChain prompt template with context injection?
LangChain
from langchain.prompts import PromptTemplate

# Template with context and query variables
APromptTemplate(input_variables=["context", "query"], template="Context: {context}\nQuery: {query}\nAnswer:"
BPromptTemplate(input_variables=["context", "query"], template="Context: {context}\nQuery: {query}\nAnswer:")
C)":rewsnAn\}yreuq{ :yreuQn\}txetnoc{ :txetnoC"=etalpmet ,]"yreuq" ,"txetnoc"[=selbairav_tupni(etalpmeTtpmorP
DromptTemplate(input_variables=["context", "query"], template="Context: {context}\nQuery: {query}\nAnswer:")
Attempts:
2 left
💡 Hint
Check for missing closing parentheses or quotes.
❓ state_output
advanced
2:00remaining
What is the final prompt string after context injection?
Given this code, what is the printed prompt string?
LangChain
from langchain.prompts import PromptTemplate

context = "User is interested in AI."
query = "Explain transformers."
prompt = PromptTemplate(
    input_variables=["context", "query"],
    template="Context info: {context}\nQuestion: {query}\nResponse:"
)

result = prompt.format(context=context, query=query)
print(result)
AResponse: Context info: User is interested in AI. Question: Explain transformers.
B
Context info: Explain transformers.
Question: User is interested in AI.
Response:
C
User is interested in AI.
Explain transformers.
Response:
D
Context info: User is interested in AI.
Question: Explain transformers.
Response:
Attempts:
2 left
💡 Hint
Match the variables in the template with the arguments passed to format().
🔧 Debug
advanced
2:00remaining
Why does this context injection raise a KeyError?
What causes the KeyError in this LangChain prompt formatting?
LangChain
from langchain.prompts import PromptTemplate

context = "Data science"
prompt = PromptTemplate(
    input_variables=["context", "query"],
    template="Topic: {context}\nQuestion: {query}\nAnswer:"
)

# Missing 'query' variable in format
result = prompt.format(context=context)
print(result)
ABecause the template string is invalid syntax
BBecause 'context' variable is missing in the template
CBecause 'query' variable is not provided in prompt.format() call
DBecause prompt.format() does not accept keyword arguments
Attempts:
2 left
💡 Hint
Check which variables the template expects and which are passed.
🧠 Conceptual
expert
2:00remaining
What is the main benefit of context injection in LangChain prompts?
Why do we inject context into LangChain prompt templates before sending to a language model?
ATo reduce the size of the prompt for faster processing
BTo provide relevant background information that guides the model's response
CTo encrypt the user input for security reasons
DTo automatically generate code without user input
Attempts:
2 left
💡 Hint
Think about how context helps the model understand the question better.

Practice

(1/5)
1. What is the main purpose of context formatting in Langchain?
easy
A. To create database connections
B. To execute code asynchronously
C. To prepare prompts with placeholders for dynamic data
D. To store user credentials securely

Solution

  1. Step 1: Understand context formatting

    Context formatting is about creating prompt templates with placeholders that can be filled later.
  2. Step 2: Identify the purpose

    This allows dynamic injection of data into prompts, making AI responses relevant.
  3. Final Answer:

    To prepare prompts with placeholders for dynamic data -> Option C
  4. Quick Check:

    Context formatting = placeholders in prompts [OK]
Hint: Think of placeholders as empty boxes to fill later [OK]
Common Mistakes:
  • Confusing context formatting with code execution
  • Thinking it stores credentials
  • Mixing it with database operations
2. Which of the following is the correct way to inject a variable user_name into a Langchain prompt template?
easy
A. prompt_template.inject(user_name)
B. prompt_template.append(user_name)
C. prompt_template.fill(user_name)
D. prompt_template.format(user_name=user_name)

Solution

  1. Step 1: Recall Langchain prompt syntax

    Langchain uses the format() method to fill placeholders in prompt templates.
  2. Step 2: Match method to injection

    Only format(user_name=user_name) correctly injects the variable into the placeholder.
  3. Final Answer:

    prompt_template.format(user_name=user_name) -> Option D
  4. Quick Check:

    Use format() to inject variables [OK]
Hint: Use .format() to fill placeholders in templates [OK]
Common Mistakes:
  • Using non-existent methods like inject() or fill()
  • Trying to append variables instead of formatting
  • Forgetting to name the variable in format()
3. Given this code snippet:
template = "Hello, {name}! Today is {day}."
prompt = template.format(name="Alice", day="Monday")
print(prompt)

What will be the output?
medium
A. Hello, Alice! Today is Monday.
B. Hello, name! Today is day.
C. Hello, {name}! Today is {day}.
D. Error: Missing placeholders

Solution

  1. Step 1: Understand the template string

    The template has placeholders {name} and {day} to be replaced by actual values.
  2. Step 2: Apply the format method

    Calling format(name="Alice", day="Monday") replaces placeholders with given values.
  3. Final Answer:

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

    Placeholders replaced by values = output string [OK]
Hint: format() replaces placeholders with given values [OK]
Common Mistakes:
  • Printing the template without formatting
  • Confusing placeholder names with literal text
  • Expecting an error when placeholders are correctly filled
4. Identify the error in this Langchain prompt injection code:
template = "Welcome, {user}!"
prompt = template.format(user)
print(prompt)
medium
A. Incorrect placeholder syntax in template
B. Missing variable name in format() call
C. Using print() instead of return
D. Template string should use double braces {{}}

Solution

  1. Step 1: Check format() usage

    The format method requires named arguments matching placeholders or positional arguments in order.
  2. Step 2: Identify missing variable name

    Here, format(user) passes a positional argument but the placeholder expects a named argument {user}.
  3. Final Answer:

    Missing variable name in format() call -> Option B
  4. Quick Check:

    Named placeholders need named arguments in format() [OK]
Hint: Match placeholder names with named format() arguments [OK]
Common Mistakes:
  • Passing positional argument without naming it
  • Thinking placeholder syntax is wrong
  • Confusing print() with return statements
5. You want to create a prompt that greets a user and mentions their favorite color using Langchain. Which code correctly formats and injects the context for user_name = "Bob" and color = "blue"?
hard
A. template = "Hi {user_name}, your favorite color is {color}." prompt = template.format(user_name=user_name, color=color)
B. template = "Hi {user}, your favorite color is {color}." prompt = template.format(user_name=user_name, color=color)
C. template = "Hi {user_name}, your favorite color is {color}." prompt = template.format(user=user_name, color=color)
D. template = "Hi {user_name}, your favorite color is {color}." prompt = template.fill(user_name, color)

Solution

  1. Step 1: Match placeholders with variable names

    The template uses placeholders {user_name} and {color}, so format() must use these exact names.
  2. Step 2: Check format() arguments

    template = "Hi {user_name}, your favorite color is {color}." prompt = template.format(user_name=user_name, color=color) correctly passes named arguments matching placeholders: user_name=user_name, color=color.
  3. Step 3: Eliminate incorrect options

    template = "Hi {user}, your favorite color is {color}." prompt = template.format(user_name=user_name, color=color) uses {user} placeholder mismatching the user_name= argument. template = "Hi {user_name}, your favorite color is {color}." prompt = template.format(user=user_name, color=color) mismatches placeholder and argument names. template = "Hi {user_name}, your favorite color is {color}." prompt = template.fill(user_name, color) uses non-existent fill() method.
  4. Final Answer:

    template = "Hi {user_name}, your favorite color is {color}." prompt = template.format(user_name=user_name, color=color) -> Option A
  5. Quick Check:

    Placeholder names must match format() argument names [OK]
Hint: Keep placeholder and format() argument names identical [OK]
Common Mistakes:
  • Mismatching placeholder and argument names
  • Using wrong method like fill()
  • Ignoring placeholder names in template
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard