InMemoryChatMessageHistory
The last lesson kept history in a plain list and appended HumanMessage / AIMessage by hand. InMemoryChatMessageHistory does the same job with simpler calls: add_user_message and add_ai_message. Pass chat_history.messages to format_messages — same steps as ChatPromptTemplate, less code.
Plain list vs helper
The prompt template and model call do not change. You only replace how you save each turn.
Previous lesson — plain list
history = [] history.append(HumanMessage(...)) history.append(AIMessage(...))
InMemoryChatMessageHistory
chat_history = InMemoryChatMessageHistory() chat_history.add_user_message(...) chat_history.add_ai_message(...)
InMemoryChatMessageHistory gives you helper methods instead of building message objects yourself. Later lessons swap in Redis or SQL with the same API.Set it up
Import from langchain_core.chat_history. One object is enough for this demo.
from langchain_core.chat_history import InMemoryChatMessageHistory
chat_history = InMemoryChatMessageHistory()Methods you will use most:
.messages holds the same HumanMessage and AIMessage objects the template expects.Each turn
Read chat_history.messages, call the model, then save the question and reply. Same four steps as the previous lesson.
messages = prompt.format_messages(
history=chat_history.messages,
input=question,
)
reply = model.invoke(messages)
chat_history.add_user_message(question)
chat_history.add_ai_message(reply.content)The demo script
chat_message_history_demo.py runs the same two HTML <a> questions — now with InMemoryChatMessageHistory.
Download the code
chat_message_history_demo.py
Two HTML questions — uses InMemoryChatMessageHistory
langchain_core — already included with the course packages. Venv and .env from Project Setup.Run it
Activate the venv from Project Setup, then:
python chat_message_history_demo.pychat_history.messages.Quick reference
InMemoryChatMessageHistory— lives in memory for this script run. Use Redis or SQL when you need data after a restart..messages— use instead of the plainhistorylist informat_messages..clear()— empty history when starting over.- Docs: Message history · InMemoryChatMessageHistory API.
What's Next
Next: RunnableWithMessageHistory — load and save history per session_id without the manual loop.