Bird
Raised Fist0
LangChainframework~20 mins

Prompt composition and chaining in LangChain - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Langchain Prompt Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this chained prompt?
Consider a Langchain prompt chain where the first prompt extracts a user's name, and the second prompt generates a greeting using that name. What will be the final output if the input is 'Alice'?
LangChain
from langchain.prompts import PromptTemplate
from langchain.chains import SimpleSequentialChain

name_prompt = PromptTemplate(input_variables=["user_input"], template="Extract the name from: {user_input}")
greet_prompt = PromptTemplate(input_variables=["name"], template="Say hello to {name}!")

class NameExtractor:
    def run(self, user_input):
        # Simulate extraction by returning the input directly
        return user_input

class Greeter:
    def run(self, name):
        return f"Hello, {name}!"

extractor = NameExtractor()
greeter = Greeter()

# Simulate chaining
name = extractor.run("Alice")
output = greeter.run(name)
print(output)
AHello, Alice!
BHello, user_input!
CSay hello to Alice!
DExtract the name from: Alice
Attempts:
2 left
💡 Hint
Think about how the output of the first prompt is used as input for the second.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this prompt chain setup
Which option contains the syntax error when defining a Langchain prompt template with multiple input variables?
LangChain
from langchain.prompts import PromptTemplate

# Intended to have two input variables: 'name' and 'age'

# Option A
prompt_a = PromptTemplate(input_variables=["name", "age"], template="Name: {name}, Age: {age}")

# Option B
prompt_b = PromptTemplate(input_variables=["name", "age"], template="Name: {name}, Age: {age}")

# Option C
prompt_c = PromptTemplate(input_variables=["name", "age"], template="Name: {name}, Age: {age}")

# Option D
prompt_d = PromptTemplate(input_variables=["name", "age"], template="Name: {name}, Age: {age}")
ANo syntax error
Brorre xatnys oN
CSyntax error due to missing closing brace in template
Do syntax error
Attempts:
2 left
💡 Hint
Check the template string for balanced braces.
state_output
advanced
2:00remaining
What is the final output after chaining these prompts with state passing?
Given two prompt templates chained where the first extracts a city from input text and the second generates a weather report for that city, what is the output if the input is 'Weather in Paris'?
LangChain
from langchain.prompts import PromptTemplate

extract_city = PromptTemplate(input_variables=["text"], template="Extract city from: {text}")
weather_report = PromptTemplate(input_variables=["city"], template="The weather in {city} is sunny.")

class CityExtractor:
    def run(self, text):
        # Extract city by splitting
        return text.split()[-1]

class WeatherReporter:
    def run(self, city):
        return f"The weather in {city} is sunny."

extractor = CityExtractor()
reporter = WeatherReporter()

city = extractor.run("Weather in Paris")
result = reporter.run(city)
print(result)
AThe weather in Paris
BExtract city from: Weather in Paris
CThe weather in text is sunny.
DThe weather in Paris is sunny.
Attempts:
2 left
💡 Hint
Look at how the city is extracted and passed to the weather report prompt.
🔧 Debug
advanced
2:00remaining
Why does this chained prompt raise a KeyError?
This Langchain prompt chain raises a KeyError when running. What is the cause?
LangChain
from langchain.prompts import PromptTemplate

prompt1 = PromptTemplate(input_variables=["input_text"], template="Extract keyword from: {input_text}")
prompt2 = PromptTemplate(input_variables=["keyword"], template="Define {keyword}.")

class Chain:
    def run(self, text):
        # Incorrectly passing variable name
        extracted = prompt1.format(input_text=text)
        # Here, 'extracted' is a string, but prompt2 expects 'keyword'
        return prompt2.format(keyword=extracted)

chain = Chain()
output = chain.run("Explain recursion")
print(output)
ATypeError because extracted is not a dict
BKeyError because prompt2 expects 'keyword' but got 'input_text'
CNo error, outputs 'Define Explain recursion.'
DSyntaxError due to missing colon
Attempts:
2 left
💡 Hint
Check the variable names used in prompt2.format() call.
🧠 Conceptual
expert
2:00remaining
Which option best describes prompt chaining in Langchain?
Select the most accurate description of prompt chaining in Langchain.
APrompt chaining connects multiple prompts so the output of one becomes the input of the next, enabling complex workflows.
BPrompt chaining runs multiple prompts independently and combines their outputs without passing data between them.
CPrompt chaining is a method to run a single prompt multiple times with different inputs simultaneously.
DPrompt chaining automatically corrects syntax errors in prompt templates during runtime.
Attempts:
2 left
💡 Hint
Think about how data flows between prompts in a chain.

Practice

(1/5)
1. What is the main purpose of prompt composition in Langchain?
easy
A. To run multiple AI models simultaneously
B. To break a big task into smaller, manageable prompts
C. To store data in a database
D. To create user interfaces for AI

Solution

  1. Step 1: Understand prompt composition

    Prompt composition means dividing a large task into smaller prompts to handle each part separately.
  2. Step 2: Identify the main purpose

    This helps make complex AI tasks easier to manage and understand by working on smaller pieces.
  3. Final Answer:

    To break a big task into smaller, manageable prompts -> Option B
  4. Quick Check:

    Prompt composition = breaking big tasks [OK]
Hint: Think of splitting a big job into small steps [OK]
Common Mistakes:
  • Confusing prompt composition with running multiple models
  • Thinking it stores data instead of organizing prompts
  • Assuming it builds user interfaces
2. Which of the following is the correct way to chain two prompts in Langchain?
easy
A. chain = Chain([prompt1, prompt2])
B. chain = Chain(prompt1, prompt2)
C. chain = Chain.compose(prompt1, prompt2)
D. chain = Chain().add(prompt1).add(prompt2)

Solution

  1. Step 1: Recall chaining syntax

    In Langchain, chaining prompts is done by creating a Chain object and adding prompts step-by-step.
  2. Step 2: Identify correct method

    The method .add() is used to add prompts to the chain, so chaining looks like Chain().add(prompt1).add(prompt2).
  3. Final Answer:

    chain = Chain().add(prompt1).add(prompt2) -> Option D
  4. Quick Check:

    Use .add() to chain prompts [OK]
Hint: Look for method chaining with .add() calls [OK]
Common Mistakes:
  • Passing prompts as a list directly to Chain
  • Using Chain(prompt1, prompt2) without .add()
  • Assuming a compose method exists
3. Given the code below, what will be the output of final_output?
prompt1 = Prompt(template="Hello, {name}!")
prompt2 = Prompt(template="How can I help you today?")
chain = Chain().add(prompt1).add(prompt2)
final_output = chain.run({"name": "Alice"})
medium
A. "Hello, Alice! How can I help you today?"
B. "Hello, {name}! How can I help you today?"
C. "Hello, Alice!"
D. Error: Missing input for prompt2

Solution

  1. Step 1: Understand prompt templates and chaining

    Prompt1 uses the variable {name} which is replaced by "Alice". Prompt2 is a fixed string without variables.
  2. Step 2: Analyze chain.run behavior

    Running the chain passes the input to prompt1, producing "Hello, Alice!" then continues to prompt2, appending "How can I help you today?".
  3. Final Answer:

    "Hello, Alice! How can I help you today?" -> Option A
  4. Quick Check:

    Chained prompts combine outputs [OK]
Hint: Chained prompts concatenate outputs with variables replaced [OK]
Common Mistakes:
  • Thinking prompt2 needs input variables
  • Expecting placeholders to remain unreplaced
  • Assuming only first prompt output is returned
4. What is the error in the following code snippet?
prompt1 = Prompt(template="What is your name?")
chain = Chain()
chain.add(prompt1)
chain.run()
medium
A. Missing input arguments for run()
B. Chain object cannot be empty
C. Prompt template syntax is incorrect
D. add() method does not exist on Chain

Solution

  1. Step 1: Check run() method usage

    The run() method requires input arguments matching prompt variables. Here, run() is called without arguments.
  2. Step 2: Confirm prompt template variables

    Prompt1 has no variables, so no input is needed. But if prompt1 expected variables, missing inputs cause error.
  3. Final Answer:

    Missing input arguments for run() -> Option A
  4. Quick Check:

    run() needs inputs if prompts have variables [OK]
Hint: Check if run() has required inputs for prompts [OK]
Common Mistakes:
  • Assuming run() works without inputs always
  • Thinking add() method is missing
  • Believing prompt syntax is wrong without variables
5. You want to create a chain where the output of the first prompt is used as input for the second prompt. Which approach correctly achieves this in Langchain?
hard
A. Create two independent chains and merge their results after running
B. Run prompt1 and prompt2 separately and concatenate their outputs manually
C. Use a chain that passes output variables from prompt1 to prompt2 as input
D. Use prompt2 with fixed text ignoring prompt1 output

Solution

  1. Step 1: Understand chaining with variable passing

    To pass output from one prompt to another, the chain must connect outputs as inputs for the next prompt.
  2. Step 2: Identify correct chaining method

    Langchain supports chaining where prompt2 receives variables produced by prompt1 automatically within the chain.
  3. Final Answer:

    Use a chain that passes output variables from prompt1 to prompt2 as input -> Option C
  4. Quick Check:

    Chaining passes outputs as inputs between prompts [OK]
Hint: Chain outputs flow as inputs to next prompt [OK]
Common Mistakes:
  • Running prompts separately without chaining
  • Merging results manually instead of chaining
  • Ignoring output-input flow in chains