Implementing Memory Systems in LangChain
You'll learn how to build practical agent memory using LangChain's built-in memory classes and custom implementations.
The Core Idea
LangChain provides ready-to-use memory components that handle the storage, retrieval, and management of conversation context. Instead of manually tracking chat history or implementing vector search from scratch, you can plug in ConversationBufferMemory, VectorStoreMemory, or build custom memory classes that fit your agent's specific needs.
Think of these as modular memory modules—like choosing between a notebook (buffer), a searchable database (vector store), or a custom filing system (your own implementation).
ConversationBufferMemory
This stores the complete conversation history as a simple list. Perfect for short interactions where you need full context without complexity:
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
memory.save_context({"input": "What's the weather?"}, {"output": "It's sunny"})
memory.save_context({"input": "Should I bring an umbrella?"}, {"output": "No need today"})
print(memory.load_memory_variables({}))
# Returns full conversation history
VectorStoreMemory
Semantic memory using embeddings—retrieves only relevant past exchanges based on similarity to the current query:
from langchain.memory import VectorStoreMemory
from langchain.vectorstores import FAISS
from langchain.embeddings import OpenAIEmbeddings
memory = VectorStoreMemory(
vectorstore=FAISS.from_texts([], OpenAIEmbeddings()),
k=2 # Retrieve top 2 relevant memories
)
memory.save_context({"input": "My name is Alice"}, {"output": "Nice to meet you!"})
# Later retrieves this when input mentions names
Custom Memory
Extend BaseMemory to implement specialized logic—entity tracking, importance scoring, or hybrid strategies combining buffer and semantic approaches.
Key Takeaway: LangChain's memory components turn complex memory management into simple plug-and-play modules, letting you choose between complete history tracking, semantic retrieval, or custom logic based on your agent's requirements.