Working through this module?
Module 08 · Page 9 of 20 · 8 sections
Memory in LangChain
Why memory matters, the memory types and their use cases, how ConversationBufferMemory works and examples for buffer, window and summary memory.
What is Memory?
- Memory allows LLMs to remember previous interactions.
- It helps maintain conversation context across multiple turns.
- Without memory, each request is treated independently and the model forgets previous messages.
- LangChain provides different types of memory based on the use case.
Why Use Memory?
- Maintain conversation history.
- Provide contextual responses.
- Useful for chatbots, virtual assistants and agents.
- Improves user experience.
- Supports short-term and long-term memory.
- Helps in building more human-like conversations.
Types of Memory in LangChain
| Memory Type | Description | Use Case |
|---|---|---|
| ConversationBufferMemory | Stores full conversation history in memory. | Simple chat applications. |
| ConversationBufferWindowMemory | Stores last k messages. | Limit memory size. |
| ConversationSummaryMemory | Summarizes old messages. | Long conversations. |
| EntityMemory | Remembers important entities (e.g., names, facts). | Personalized assistants. |
| VectorStoreRetrieverMemory | Stores conversation history in a vector store. | Long-term memory with retrieval. |
ConversationBufferMemory
python
from langchain_openai import ChatOpenAI from langchain.memory import ConversationBufferMemory from langchain.chains import ConversationChain llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7) memory = ConversationBufferMemory() conversation = ConversationChain( llm=llm, memory=memory, verbose=True ) # First message response1 = conversation.predict(input="Hi, my name is Rahul.") print(response1) # Second message (model remembers previous message) response2 = conversation.predict(input="What is my name?") print(response2)
How ConversationBufferMemory Works
User InputNew message
Load Previous MessagesFrom memory
Pass Full ConversationAs context to LLM
Get Response
Save Current MessageTo memory
ConversationBufferWindowMemory
python
from langchain.memory import ConversationBufferWindowMemory from langchain.chains import ConversationChain memory = ConversationBufferWindowMemory(k=3) conversation = ConversationChain( llm=llm, memory=memory, verbose=True ) # This will keep only last 3 messages in memory
ConversationSummaryMemory
python
from langchain.memory import ConversationSummaryMemory memory = ConversationSummaryMemory(llm=llm) conversation = ConversationChain( llm=llm, memory=memory, verbose=True )
Key Takeaways
- Memory helps in maintaining context in conversations.
- Choose the right memory type based on your use case.
- Use summary memory for long conversations.
- Vector store memory is useful for long-term storage.
- Memory can also be used with agents and chains.