Lesson 5 / 31

Prompt Templates and Messages

Build reusable prompts with variables.

Templates with named slots

A ChatPromptTemplate builds a list of role-tagged messages (system, human, AI) from a template with {variables}. Invoking it with a dict of values returns a prompt value you can turn into messages. Templates make prompts reusable, versionable and testable, and the template knows its input variables, so a missing value fails early with a clear error instead of sending a half-filled prompt. Use MessagesPlaceholder for chat history and FewShotChatMessagePromptTemplate to inject examples. Keep prompt text in files or constants, not scattered across code.

Compose with the pipe

Runnables share one interface, so prompts, models and parsers can be piped together.

Four pieces: prompt, model, parser, pipe.
Figure 2.1 — Prompt, model, parser and pipe.

A chat prompt template, run

I ran this offline in a Python virtual environment with langchain-core 1.6.6, langchain-text-splitters 1.1.2 and llama-index-core 0.14.25. No API key or network call is needed because a fake model or a toy embedding stands in for the real one. The template produces a SystemMessage and a HumanMessage with the variables filled in, and reports that it needs the inputs question and role.

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a {role}. Answer in one sentence."),
    ("human", "{question}"),
])
value = prompt.invoke({"role": "geography teacher", "question": "What is the capital of India?"})
for m in value.to_messages():
    print(type(m).__name__, "|", m.content)
print(prompt.input_variables)

Output:

SystemMessage | You are a geography teacher. Answer in one sentence.
HumanMessage | What is the capital of India?
['question', 'role']

Escape literal braces

If your prompt contains JSON braces, write {{ and }} so the template does not treat them as variables.

Quick check: What is an advantage of prompt templates?

  • They make the model free
  • Reusable prompts that fail early when a variable is missing
  • They hide the prompt from the model
  • They replace parsers
Answer

Reusable prompts that fail early when a variable is missing — Templates give structure and validation to prompt building.