Prompt Templates
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.
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):
| Template | Use it for |
|---|---|
PromptTemplate | single-shot text tasks: summarise, classify, generate |
ChatPromptTemplate | chat models with system / human / ai roles |
MessagesPlaceholder | insert chat history or agent scratchpad |
.partial(language="Hindi") | fix some variables early (company name, language) |
FewShotPromptTemplate | teach by examples (text models) |
FewShotChatMessagePromptTemplate | teach by examples as human/ai turns |
LengthBasedExampleSelector | fewer 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.
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}")04Hands-on: Ajeetkumar’s Colab notebook
groq_key with your free key from console.groq.com, switch on Notebook access, then run the cells from the top.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
| Mistake | Fix |
|---|---|
| Putting user text inside the system message | keep rules in system, user data in human: safer against prompt injection |
| Curly braces in JSON examples break the template | escape them as {{ }} |
| 20 few-shot examples in every call | use an example selector, or 2–3 good examples |
Formatting with .format() then building a chain | in chains pass the template itself: prompt | llm (Lab 04) |
06Practice tasks
- Make a ChatPromptTemplate
"You are a {role}"and test with role = doctor, lawyer, chef. - Build a few-shot prompt that converts English sentences to SQL.
- Use
partialto fixcompany_namein 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
- Templates are reusable prompts with
{blanks}; LangChain finds the variables and errors on missing ones. ChatPromptTemplateadds roles;MessagesPlaceholderinserts history.partialfixes some variables early.- Few-shot templates teach by examples; selectors keep prompts short.
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
- LangChain: Prompt templates
- Few-shot prompting
- Ajeetkumar’s notebook: LC_02_Prompt_Templates.ipynb (download)