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

MessagesPlaceholder

Room for history.

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

A chatbot's prompt has a fixed system message, then a history that keeps growing, then the new question. Messages placeholder is a slot in the template where a whole list of messages goes.

MessagesPlaceholder
From the video: MessagesPlaceholder
  • Fixed system message
  • A growing history
  • A slot for many messages

A slot for the history

The placeholder is named history. When we invoke the template, we pass a list of earlier messages under that name. Run it. The final prompt has the system message, the two history messages, and the new question, four messages in all.

placeholder.pypython
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

prompt = ChatPromptTemplate.from_messages([
    ("system", "You help customers of Riverside Books."),
    MessagesPlaceholder("history"),
    ("human", "{question}"),
])

history = [("human", "Hi, I'm Priya."), ("ai", "Hello Priya! How can I help?")]
value = prompt.invoke({"history": history, "question": "What's my name?"})
for m in value.messages:
    print(f"{m.type:>6}: {m.content}")
Output
system: You help customers of Riverside Books.
 human: Hi, I'm Priya.
    ai: Hello Priya! How can I help?
 human: What's my name?

Where placeholders are used

You'll use placeholders often. For chat history, as here. For tool results, inside agents. And for examples, when you want to show the model several sample conversations. Anywhere a prompt needs a list of messages of varying length.

keyvalue
Chat historymost common
Agent stepstool calls and results
Examplessample conversations
Any length0 to many messages

Summary

Messages placeholder reserves a slot for a list of messages, like chat history. Next, teaching the model by showing it examples.

Key takeaways
  • MessagesPlaceholder('history')
  • Pass a list
  • Varying length
Next up: Few-Shot Prompts — teaching by example