Sahaj.blogs
7 Apr 2026 · StudyPhase 13 · LangChain

LangChain · Prompt templates

ChatPromptTemplate for reusable prompts with variables, message placeholders for history, and few-shot examples, all producing message lists ready for any chat model.

Hard-coding prompts as f-strings gets messy quickly. ChatPromptTemplate keeps the structure separate from the values:

  • each message is a (role, template) pair with {variables}
  • .invoke({...}) fills the variables and returns a ChatPromptValue (a list of messages)
  • MessagesPlaceholder marks where a list of messages (chat history) goes
  • FewShotChatMessagePromptTemplate expands example pairs into user/assistant turns, the few-shot idea from my prompting post

Templates are Runnables, so they compose with models using |. That’s the next post.

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder, FewShotChatMessagePromptTemplate
from langchain_core.messages import HumanMessage, AIMessage

tutor = ChatPromptTemplate.from_messages([
    ("system", "You are a patient tutor for {subject}. Answer in at most {n} sentences."),
    MessagesPlaceholder("history"),
    ("human", "{question}"),
])
value = tutor.invoke({
    "subject": "Python", "n": 2,
    "history": [HumanMessage("What is a list?"), AIMessage("An ordered, mutable collection.")],
    "question": "And a tuple?",
})
for m in value.to_messages():
    print(f"{m.type:>6}: {m.content}")
print("variables:", sorted(tutor.input_variables))

examples = [{"q": "2+2", "a": "4"}, {"q": "3*5", "a": "15"}]
few = FewShotChatMessagePromptTemplate(
    examples=examples, example_prompt=ChatPromptTemplate.from_messages([("human", "{q}"), ("ai", "{a}")]))
calc = ChatPromptTemplate.from_messages([("system", "Reply with the number only."), few, ("human", "{q}")])
print([f"{m.type}:{m.content}" for m in calc.invoke({"q": "7-4"}).to_messages()])

Output:

system: You are a patient tutor for Python. Answer in at most 2 sentences.
 human: What is a list?
    ai: An ordered, mutable collection.
 human: And a tuple?
variables: ['history', 'n', 'question', 'subject']
['system:Reply with the number only.', 'human:2+2', 'ai:4', 'human:3*5', 'ai:15', 'human:7-4']

#langchain#prompting

Sources

  1. LangChain reference: ChatPromptTemplate — LangChain
  2. LangChain reference: MessagesPlaceholder — LangChain
  3. LangChain reference: FewShotChatMessagePromptTemplate — LangChain