0
0
LangChainframework~5 mins

Chat history management in LangChain

Choose your learning style9 modes available
Introduction

Chat history management helps keep track of past messages in a conversation. It makes chats feel natural and remembers what was said before.

When building a chatbot that needs to remember previous user questions.
When you want to show past messages in a chat interface.
When you want to improve responses by using earlier conversation context.
When saving chat logs for review or analysis.
When handling multi-turn conversations that depend on history.
Syntax
LangChain
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory()
memory.chat_memory.add_user_message("Hello!")
memory.chat_memory.add_ai_message("Hi there! How can I help?")

history = memory.load_memory_variables({})

ConversationBufferMemory stores chat messages in order.

Use add_user_message and add_ai_message to add messages.

Examples
This example adds a user and AI message, then prints the chat history.
LangChain
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory()
memory.chat_memory.add_user_message("What's the weather?")
memory.chat_memory.add_ai_message("It's sunny today.")

print(memory.load_memory_variables({}))
Here, we set a custom key for the memory and retrieve the stored chat history.
LangChain
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(memory_key="chat_history")

# Add messages
memory.chat_memory.add_user_message("Hello!")
memory.chat_memory.add_ai_message("Hello! How can I assist?")

history = memory.load_memory_variables({})
print(history)
Sample Program

This program shows how to add user and AI messages to the chat memory. Then it loads and prints the full chat history as a dictionary.

LangChain
from langchain.memory import ConversationBufferMemory

# Create memory to store chat history
memory = ConversationBufferMemory()

# Simulate a chat
memory.chat_memory.add_user_message("Hi, who won the game?")
memory.chat_memory.add_ai_message("The home team won 3-1.")
memory.chat_memory.add_user_message("Thanks!")
memory.chat_memory.add_ai_message("You're welcome!")

# Load and print chat history
history = memory.load_memory_variables({})
print(history)
OutputSuccess
Important Notes

Chat history is stored as a simple text string with 'Human:' and 'AI:' labels.

You can customize memory behavior by using different memory classes in Langchain.

Remember to clear or reset memory if you want to start a new conversation.

Summary

Chat history management keeps track of past messages to make conversations smoother.

Use ConversationBufferMemory to store and retrieve chat messages easily.

Adding messages and loading history helps your app remember what was said before.