Lesson 3 of 9 · Core
Prompt Templates
Build reusable prompts with LangChain's ChatPromptTemplate: variables, MessagesPlaceholder for history, partials, few-shot examples, escaping braces and piping.
- 7 min read
- Intermediate
- Reviewed
- Create chat prompt templates with variables
- Insert conversation history with MessagesPlaceholder
- Fill some variables early with partial
- Add few-shot examples as message pairs
- Avoid the common brace and missing-variable mistakes
Prompts with blanks
Most applications send the same kind of prompt again and again with different details: a different product, customer or question. A template keeps the fixed wording in one place and fills in the blanks.
ChatPromptTemplate
Build a template from (role, text) pairs. Variables go in braces, and a MessagesPlaceholder marks where a whole list of messages, such as the conversation so far, will be inserted:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
prompt = ChatPromptTemplate.from_messages([
("system", "You are the assistant for {company}. Answer in {language}, in at most two sentences."),
MessagesPlaceholder("history"), # earlier messages go here
("human", "{question}"),
])
print(prompt.input_variables)
value = prompt.invoke({
"company": "Velamuvi Bikes",
"language": "English",
"history": [("human", "Hi! Are you open on Saturday?"), ("ai", "Yes, from 9am to 1pm.")],
"question": "Do you repair e-bikes?",
})
for m in value.to_messages():
print(f"{m.type}: {m.content}")['company', 'history', 'language', 'question'] system: You are the assistant for Velamuvi Bikes. Answer in English, in at most two sentences. human: Hi! Are you open on Saturday? ai: Yes, from 9am to 1pm. human: Do you repair e-bikes?
The template knows its input variables. Calling invoke with a dictionary of values returns a prompt value, and to_messages() shows the exact messages the model will receive. Printing them like this is the quickest way to debug a prompt.
What a template does, in plain Python
Here's a tiny version of the same idea. It finds the variables, refuses to run if any are missing, fills in the text and splices in the history:
import re
# A tiny prompt template, to see what LangChain's ChatPromptTemplate does for you
class TinyChatPrompt:
def __init__(self, messages):
self.messages = messages # (role, template) pairs, or ("placeholder", name)
self.variables = sorted({v for role, t in messages if role != "placeholder"
for v in re.findall(r"\{(\w+)\}", t)}
| {t for role, t in messages if role == "placeholder"})
def invoke(self, values):
missing = [v for v in self.variables if v not in values]
if missing:
raise KeyError(f"missing variables: {missing}") # fail loudly, never send a half-filled prompt
out = []
for role, t in self.messages:
if role == "placeholder":
out.extend(values[t]) # a list of messages is spliced in
else:
out.append((role, t.format(**values)))
return out
prompt = TinyChatPrompt([
("system", "You are the assistant for {company}. Answer in {language}."),
("placeholder", "history"),
("human", "{question}"),
])
print("Variables:", prompt.variables)
for role, text in prompt.invoke({"company": "Velamuvi Bikes", "language": "English",
"history": [("human", "Open Saturday?"), ("ai", "Yes, 9 to 1.")],
"question": "Do you repair e-bikes?"}):
print(f" {role}: {text}")
try:
prompt.invoke({"company": "Velamuvi Bikes", "question": "Hi"})
except KeyError as e:
print("Error:", e)Failing loudly on a missing variable matters. A prompt sent with a blank where the customer's name should be produces a confident, wrong answer, not an error.
Partial templates and chaining
Some variables are known early (the company name), others only at request time (the product). partial fills the early ones and returns a new template. And because templates are Runnables, you can pipe a template straight into a model:
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "You write product descriptions for {company}. Keep them under {max_words} words."),
("human", "Describe: {product}"),
])
shop_prompt = prompt.partial(company="Velamuvi Bikes", max_words="25") # fix some variables now
model = init_chat_model("anthropic:MODEL_NAME")
chain = shop_prompt | model # the prompt's output feeds the model (lesson 5)
print(chain.invoke({"product": "a folding city e-bike"}).content)Fold it, ride it, park it anywhere: a light city e-bike with a 60 km range that fits under your desk.
The | operator connects components into a chain: the template's messages flow into the model. Lesson 5 covers chains in depth.
Few-shot examples
Showing the model a few examples of input and correct output is one of the most effective prompting techniques (see the Prompt Engineering course). FewShotChatMessagePromptTemplate turns a list of examples into real human and AI message pairs:
from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate
examples = [
{"review": "Arrived broken, nobody answers my emails.", "label": "negative"},
{"review": "Fast delivery and the bike is great!", "label": "positive"},
]
example_prompt = ChatPromptTemplate.from_messages([("human", "{review}"), ("ai", "{label}")])
few_shot = FewShotChatMessagePromptTemplate(examples=examples, example_prompt=example_prompt)
prompt = ChatPromptTemplate.from_messages([
("system", "Label each review as positive, negative or mixed. Reply with the label only."),
few_shot, # the examples become real message pairs
("human", "{review}"),
])
for m in prompt.invoke({"review": "Good bike, but the delivery was late."}).to_messages():
print(f"{m.type}: {m.content}")system: Label each review as positive, negative or mixed. Reply with the label only. human: Arrived broken, nobody answers my emails. ai: negative human: Fast delivery and the bike is great! ai: positive human: Good bike, but the delivery was late.
The model sees the examples as earlier turns of the conversation, so it copies their format closely: just the label.
Common mistakes
Find the variables in a prompt template, the first thing ChatPromptTemplate does with your text.
import re
template = "Write a {tone} email to {customer} about order {order_id}. Sign it from {agent} at {company}. Mention {order_id} twice."
# Print the template's variable names: each name once, in alphabetical order, as a list.
What does MessagesPlaceholder do in a ChatPromptTemplate?
Summary
- A ChatPromptTemplate turns (role, text) pairs with variables into chat messages.
- MessagesPlaceholder inserts a list of messages, such as history.
- partial fills some variables early; templates pipe into models with
|. - Few-shot templates turn examples into real message pairs.
- Double literal braces, and keep user input out of system messages.
Next: output parsers, turning replies into data.
Finished reading? Tick it off to track your progress.