Bird
Raised Fist0
LangChainframework~20 mins

ChatPromptTemplate for conversations 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
🎖️
ChatPromptTemplate Mastery
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 ChatPromptTemplate usage?
Given this LangChain ChatPromptTemplate code, what will be the final prompt text after formatting?

from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate

system_template = SystemMessagePromptTemplate.from_template("You are a helpful assistant.")
human_template = HumanMessagePromptTemplate.from_template("Translate this: {text}")

chat_prompt = ChatPromptTemplate.from_messages([system_template, human_template])

final_prompt = chat_prompt.format_prompt(text="Hello world")
print(final_prompt.to_string())
LangChain
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate

system_template = SystemMessagePromptTemplate.from_template("You are a helpful assistant.")
human_template = HumanMessagePromptTemplate.from_template("Translate this: {text}")

chat_prompt = ChatPromptTemplate.from_messages([system_template, human_template])

final_prompt = chat_prompt.format_prompt(text="Hello world")
print(final_prompt.to_string())
AYou are a helpful assistant.\nTranslate this: Hello world
BSystem: You are a helpful assistant.\nHuman: Translate this: {text}
CSystem: You are a helpful assistant.\nHuman: Translate this: Hello world
DSystem: You are a helpful assistant.\nHuman: Hello world
Attempts:
2 left
💡 Hint
Remember that format_prompt replaces placeholders in all message templates.
📝 Syntax
intermediate
2:00remaining
Which option causes a syntax error in ChatPromptTemplate usage?
Identify which code snippet will raise a syntax error when creating a ChatPromptTemplate with message templates.
AChatPromptTemplate.from_messages([SystemMessagePromptTemplate.from_template("Hello"), HumanMessagePromptTemplate.from_template("Say {word")])
BChatPromptTemplate.from_messages([SystemMessagePromptTemplate.from_template("Hello"), HumanMessagePromptTemplate.from_template("Say {word}")])
CChatPromptTemplate.from_messages([SystemMessagePromptTemplate.from_template("Hello"), HumanMessagePromptTemplate.from_template("Say {word}!")])
DChatPromptTemplate.from_messages([SystemMessagePromptTemplate.from_template("Hello"), HumanMessagePromptTemplate.from_template("Say {word}.")])
Attempts:
2 left
💡 Hint
Check if all curly braces are properly closed in the template strings.
state_output
advanced
2:00remaining
What is the value of 'final_prompt.messages[1].content' after formatting?
Consider this code snippet:

from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate

chat_prompt = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template("System: {system_msg}"),
    HumanMessagePromptTemplate.from_template("User says: {user_msg}")
])

final_prompt = chat_prompt.format_prompt(system_msg="Ready", user_msg="Hello")

result = final_prompt.messages[1].content
print(result)

What will be printed?
LangChain
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate

chat_prompt = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template("System: {system_msg}"),
    HumanMessagePromptTemplate.from_template("User says: {user_msg}")
])

final_prompt = chat_prompt.format_prompt(system_msg="Ready", user_msg="Hello")

result = final_prompt.messages[1].content
print(result)
ASystem: Ready
BUser says: Hello
CUser says: {user_msg}
DSystem: {system_msg}
Attempts:
2 left
💡 Hint
final_prompt.messages is a list of message objects in order of templates.
🔧 Debug
advanced
2:00remaining
Why does this ChatPromptTemplate.format_prompt call raise a KeyError?
Examine this code:

from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate

chat_prompt = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template("System: {system_msg}"),
    HumanMessagePromptTemplate.from_template("User says: {user_msg}")
])

final_prompt = chat_prompt.format_prompt(system_msg="Ready")

Why does the last line raise a KeyError?
LangChain
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate

chat_prompt = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template("System: {system_msg}"),
    HumanMessagePromptTemplate.from_template("User says: {user_msg}")
])

final_prompt = chat_prompt.format_prompt(system_msg="Ready")
ABecause the placeholder {system_msg} is missing in the template
BBecause the HumanMessagePromptTemplate is not properly imported
CBecause format_prompt requires no arguments for this template
DBecause the placeholder {user_msg} is not provided in format_prompt arguments
Attempts:
2 left
💡 Hint
Check if all placeholders in all message templates have matching arguments.
🧠 Conceptual
expert
2:00remaining
Which option best describes the role of ChatPromptTemplate in LangChain?
Select the most accurate description of what ChatPromptTemplate does in LangChain.
AIt combines multiple message templates into a single prompt that can be formatted with variables for chat models.
BIt executes chat models and returns their responses directly without formatting.
CIt stores raw text prompts without any variable placeholders or message roles.
DIt is used to train chat models by providing labeled conversation data.
Attempts:
2 left
💡 Hint
Think about how ChatPromptTemplate helps prepare prompts for chat models.

Practice

(1/5)
1. What is the main purpose of ChatPromptTemplate in Langchain conversations?
easy
A. To organize chat messages with placeholders for dynamic inputs
B. To execute database queries automatically
C. To style chat messages with CSS
D. To store user credentials securely

Solution

  1. Step 1: Understand ChatPromptTemplate role

    ChatPromptTemplate helps structure chat messages and insert dynamic user inputs using placeholders.
  2. Step 2: Eliminate unrelated options

    Options about database queries, styling, or security are unrelated to ChatPromptTemplate's purpose.
  3. Final Answer:

    To organize chat messages with placeholders for dynamic inputs -> Option A
  4. Quick Check:

    ChatPromptTemplate = Organize messages + placeholders [OK]
Hint: ChatPromptTemplate structures chat with placeholders [OK]
Common Mistakes:
  • Confusing ChatPromptTemplate with styling or security features
  • Thinking it runs queries or handles authentication
2. Which of the following is the correct way to create a ChatPromptTemplate with a user input placeholder named 'name'?
easy
A. ChatPromptTemplate.from_template('Hello {name}!')
B. ChatPromptTemplate('Hello $name!')
C. ChatPromptTemplate.create('Hello {{name}}!')
D. ChatPromptTemplate.new('Hello %name%!')

Solution

  1. Step 1: Recall correct placeholder syntax

    Langchain uses curly braces {name} inside from_template method to define placeholders.
  2. Step 2: Check method and syntax correctness

    Only ChatPromptTemplate.from_template('Hello {name}!') uses from_template and correct {name} placeholder syntax.
  3. Final Answer:

    ChatPromptTemplate.from_template('Hello {name}!') -> Option A
  4. Quick Check:

    Use from_template with {placeholder} [OK]
Hint: Use from_template and {placeholder} syntax [OK]
Common Mistakes:
  • Using wrong placeholder symbols like $ or % or double braces
  • Using non-existent methods like create or new
3. Given this code snippet:
from langchain.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_template('Hi {user}! How can I help you today?')
message = prompt.format_prompt(user='Alice').to_messages()
print(message[0].content)

What will be printed?
medium
A. Hi {user}! How can I help you today?
B. Hi Alice! How can I help you today?
C. Hi ! How can I help you today?
D. Error: format_prompt missing argument

Solution

  1. Step 1: Understand placeholder replacement

    The placeholder {user} is replaced by the value 'Alice' passed to format_prompt.
  2. Step 2: Check printed message content

    message[0].content contains the formatted string with 'Alice' inserted.
  3. Final Answer:

    Hi Alice! How can I help you today? -> Option B
  4. Quick Check:

    Placeholder replaced with 'Alice' in output [OK]
Hint: format_prompt replaces placeholders with given values [OK]
Common Mistakes:
  • Thinking placeholders remain unreplaced in output
  • Assuming missing argument error without passing user
  • Confusing message object with string directly
4. What is wrong with this code snippet?
from langchain.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_template('Hello {name}!')
message = prompt.format_prompt().to_messages()
medium
A. Placeholder syntax should use $name instead of {name}
B. Incorrect method name 'from_template'
C. Missing argument for placeholder 'name' in format_prompt
D. to_messages() is not a valid method

Solution

  1. Step 1: Identify placeholder usage

    The template has a placeholder {name} that requires a value when formatting.
  2. Step 2: Check format_prompt call

    format_prompt() is called without providing the required 'name' argument, causing an error.
  3. Final Answer:

    Missing argument for placeholder 'name' in format_prompt -> Option C
  4. Quick Check:

    Placeholder needs matching argument in format_prompt [OK]
Hint: Always pass all placeholders to format_prompt [OK]
Common Mistakes:
  • Forgetting to pass required placeholder arguments
  • Thinking method names or syntax are incorrect
  • Assuming to_messages() doesn't exist
5. You want to create a conversation prompt that greets the user by name and asks their favorite color, then stores both inputs dynamically. Which approach using ChatPromptTemplate is correct?
hard
A. Use a template 'Hello {name}! What is your favorite color?' and call format_prompt(name='Bob') only
B. Use two separate ChatPromptTemplates, one for name and one for color, then combine messages manually
C. Use a template 'Hello $name, favorite color $color?' and call format_prompt(name='Bob', color='blue')
D. Use a template like 'Hello {name}, what is your favorite color {color}?' and call format_prompt(name='Bob', color='blue')

Solution

  1. Step 1: Understand placeholder usage for multiple inputs

    ChatPromptTemplate supports multiple placeholders in one template string, e.g., {name} and {color}.
  2. Step 2: Check correct syntax and method usage

    Use a template like 'Hello {name}, what is your favorite color {color}?' and call format_prompt(name='Bob', color='blue') uses correct curly brace placeholders and passes both arguments in format_prompt.
  3. Step 3: Evaluate other options

    Use two separate ChatPromptTemplates, one for name and one for color, then combine messages manually is more complex than needed; Use a template 'Hello {name}! What is your favorite color?' and call format_prompt(name='Bob') only misses the color input; Use a template 'Hello $name, favorite color $color?' and call format_prompt(name='Bob', color='blue') uses wrong placeholder syntax.
  4. Final Answer:

    Use a template like 'Hello {name}, what is your favorite color {color}?' and call format_prompt(name='Bob', color='blue') -> Option D
  5. Quick Check:

    Multiple placeholders with format_prompt arguments [OK]
Hint: Use {placeholder} for each input and pass all in format_prompt [OK]
Common Mistakes:
  • Using wrong placeholder syntax like $name
  • Splitting conversation unnecessarily into multiple templates
  • Not passing all required inputs to format_prompt