LangChain Hands-on · Module 1 · Lab 02

Prompt Templates

⏱ 20 min + hands-on🎯 Beginner🖼 2 diagrams🧪 3 live demos🐍 Python code

Writing prompts with f-strings works for one demo, but breaks in real apps: a missing variable silently sends a broken prompt, and the same prompt gets copied everywhere. Prompt templates are reusable prompts with blanks, roles and validation. In this lab you build them for emails, translation, chat history and few-shot fraud checks.

In this session

  • Why templates beat f-strings
  • PromptTemplate and from_template
  • partial: fix some variables in advance
  • ChatPromptTemplate with system and human roles
  • MessagesPlaceholder for chat history
  • Few-shot templates and LengthBasedExampleSelector

01The big idea: a form with blanks

📝

Think of a bank deposit slip. The slip is printed once with blanks for name, account number and amount. Every customer fills their own values. A prompt template is that slip: "Write a {tone} email to {customer_name} about {issue}". Write it once, fill it a thousand times, and the bank (LangChain) refuses a slip with an empty blank.

f-string• variables inserted by hand• typo or missing value → silent bug• no roles (system / human)• copied and pasted everywherePromptTemplate• variables detected automatically• missing variable → clear KeyError• roles with ChatPromptTemplate• reusable and plugs into chains
Same prompt, two ways. Templates are safer and reusable.
Demo · Fill the template (try clearing a box)

02Chat templates, history and few-shot

ChatPromptTemplate builds a list of messages with roles. MessagesPlaceholder("history") is a slot where past messages get inserted, which is how chatbots remember (Lab 05):

Demo · ChatPromptTemplate with roles
("human", "{question}")the new questionMessagesPlaceholder("history")all old messages go here("system", "You are a helpful travel assistant.")rules first
How the final prompt is stacked: rules, then history, then the new question.
TemplateUse it for
PromptTemplatesingle-shot text tasks: summarise, classify, generate
ChatPromptTemplatechat models with system / human / ai roles
MessagesPlaceholderinsert chat history or agent scratchpad
.partial(language="Hindi")fix some variables early (company name, language)
FewShotPromptTemplateteach by examples (text models)
FewShotChatMessagePromptTemplateteach by examples as human/ai turns
LengthBasedExampleSelectorfewer examples for long inputs, so the prompt stays short

03Hands-on: run it here

Templates need no LLM at all, so this whole script runs exactly as in Colab. Notice the clear error for a missing variable, and the few-shot chat prompt: 2 examples become 4 messages before the real question.

lab02_prompts.py
from langchain_core.prompts import (PromptTemplate, ChatPromptTemplate, MessagesPlaceholder,
                                    FewShotPromptTemplate, FewShotChatMessagePromptTemplate)
from langchain.messages import HumanMessage, AIMessage

# PromptTemplate + from_template
template = PromptTemplate.from_template("Explain {topic} to a {audience} in 3 bullet points")
print("variables:", template.input_variables)
print(template.format(topic="cloud computing", audience="10 year old kid"))

# missing variable -> clear error (no silent bug like f-strings)
try:
    template.format(topic="UPI")
except KeyError as e:
    print("error: missing variable", e)

# partial
hindi = PromptTemplate.from_template("Translate '{text}' into {language}").partial(language="Hindi")
print(hindi.format(text="Good morning, how are you?"))

# ChatPromptTemplate with roles + history
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful travel assistant."),
    MessagesPlaceholder("history"),
    ("human", "{question}"),
])
history = [HumanMessage("Hi, I am Ajeet. I am planning a trip to Goa."), AIMessage("Nice! How many days is your trip?")]
for m in prompt.format_messages(history=history, question="3 days. What is my name and where am I going?"):
    print(f"  {m.type:6s}: {m.content}")

# few-shot for chat models
examples = [{"input": "Rs 250 grocery, usual city", "output": "LOW"},
            {"input": "Rs 95,000 crypto, new device, 3 AM", "output": "HIGH"}]
few = FewShotChatMessagePromptTemplate(examples=examples,
        example_prompt=ChatPromptTemplate.from_messages([("human", "{input}"), ("ai", "{output}")]))
final = ChatPromptTemplate.from_messages([("system", "Classify transaction fraud risk as LOW, MEDIUM or HIGH. One word."), few, ("human", "{input}")])
print("\nfew-shot chat prompt has", len(final.format_messages(input="Rs 12,000 electronics")), "messages:")
for m in final.format_messages(input="Rs 12,000 electronics, other state, known device"):
    print(f"  {m.type:6s}: {m.content}")
variables: ['audience', 'topic'] Explain cloud computing to a 10 year old kid in 3 bullet points error: missing variable 'audience' Translate 'Good morning, how are you?' into Hindi system: You are a helpful travel assistant. human : Hi, I am Ajeet. I am planning a trip to Goa. ai : Nice! How many days is your trip? human : 3 days. What is my name and where am I going? few-shot chat prompt has 6 messages: system: Classify transaction fraud risk as LOW, MEDIUM or HIGH. One word. human : Rs 250 grocery, usual city ai : LOW human : Rs 95,000 crypto, new device, 3 AM ai : HIGH human : Rs 12,000 electronics, other state, known device

04Hands-on: Ajeetkumar’s Colab notebook

Colab setup (same in every notebook): click 🔑 Secrets in the Colab sidebar, add groq_key with your free key from console.groq.com, switch on Notebook access, then run the cells from the top.
Demo · Notebook player · Lab 02

Most cells in this notebook format prompts, so they run here with real output. Only the llm.invoke(...) cells need your Groq key.

05Tips and common mistakes

MistakeFix
Putting user text inside the system messagekeep rules in system, user data in human: safer against prompt injection
Curly braces in JSON examples break the templateescape them as {{ }}
20 few-shot examples in every calluse an example selector, or 2–3 good examples
Formatting with .format() then building a chainin chains pass the template itself: prompt | llm (Lab 04)

06Practice tasks

  1. Make a ChatPromptTemplate "You are a {role}" and test with role = doctor, lawyer, chef.
  2. Build a few-shot prompt that converts English sentences to SQL.
  3. Use partial to fix company_name in an HR email template.

Try these in the same Colab notebook after you finish the lab. Change one thing at a time and look at the output again.

07Summary

08Quick quiz

1. What happens if you forget a variable in template.format()?

2. Which part inserts chat history into a prompt?

3. Best way to fix language="Hindi" for all calls?

4. Where should user-provided text go?

5. Why use LengthBasedExampleSelector?

09References

Created by Ajeetkumar