AI Hints
Home›LangChain Tutorial›Prompt Templates
LangChain · Lesson 14 of 120

Chat Prompt Templates

Roles in templates.

⏱ 2 min read▶ Video at 14:07🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Chat models take lists of messages, so we usually want a template that makes messages, with roles. That's a chat prompt template.

Chat Prompt Templates
From the video: Chat Prompt Templates
  • Chat models want messages
  • Templates with roles
  • ChatPromptTemplate

A chat prompt template

From messages takes a list of role and text pairs. The system message sets the tone, with a blank for the shop name. The human message has a blank for the question. Run it. Invoking the template gives two real message objects, ready for the model.

chat_template.pypython
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a friendly assistant for {shop}. Answer in one sentence."),
    ("human", "{question}"),
])

value = prompt.invoke({"shop": "Riverside Books", "question": "Do you sell maps?"})
for m in value.messages:
    print(type(m).__name__, "->", m.content)
Output
SystemMessage -> You are a friendly assistant for Riverside Books. Answer in one
sentence.
HumanMessage -> Do you sell maps?

Template plus model

Now we send the filled template to a model. Run it. The model answers as the Riverside Books assistant, in a single friendly sentence, because the system message says so. Next lesson, we'll make room in the template for a whole conversation.

template_model.pypython
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a friendly assistant for {shop}. Answer in one sentence."),
    ("human", "{question}"),
])

messages = prompt.invoke({"shop": "Riverside Books", "question": "Do you sell maps?"})
print(model.invoke(messages).text)
Output
Yes, we carry a lovely selection of local and regional maps at Riverside Books!

Summary

Chat prompt templates build role tagged messages from your data. Fill them with invoke, and pass them to the model. Next, a placeholder for chat history.

Key takeaways
  • from_messages([...])
  • (role, text) pairs
  • Fill, then call the model
Next up: MessagesPlaceholder — room for history