Skip to content

Prompt templates

A prompt template formats named inputs into a prompt value. ChatPromptTemplate preserves message roles instead of building one large string by hand.

from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "Answer only from this policy:\n{policy}"),
("human", "Order {order_id}: {question}"),
])
messages = prompt.invoke({
"policy": "Returns are accepted for 30 days.",
"order_id": "A-19",
"question": "Can I return it after 45 days?",
})
  1. Write stable instructions once.
  2. Name each changing value.
  3. Format with a dictionary.
  4. Pass the result to a model or compose it with |.

Templates format text; they do not make untrusted text safe. Retrieved pages and user input can contain instructions. Keep authorization outside the prompt, mark data clearly, and test prompt-injection cases.

Messages · Runnables and LCEL · Structured output