Adding Memory to Chains and Agents
Relevant source files
The following files were used as context for generating this wiki page:
Memory is a critical component in LangChain for building stateful applications like chatbots and agents. It allows a Chain or Agent to remember information about its past interactions and use that information as context for future executions. This capability is essential for creating coherent, conversational experiences where the model's responses are informed by the ongoing dialogue.
LangChain provides a flexible framework for managing memory. The core concept revolves around loading historical context before a chain executes and saving the context of the current run after it completes. There are multiple strategies for implementing memory, from simple buffers of the last few messages to more complex systems that summarize conversations or store information in a vector database for semantic retrieval. While there is a legacy BaseMemory system, the modern approach leverages BaseChatMessageHistory for better integration with the LangChain Expression Language (LCEL).
Sources: libs/core/langchain_core/memory.py:23-31, libs/langchain/langchain/chains/base.py:72-78, cookbook/README.md:3
Core Memory Abstractions
LangChain's memory system is built on a set of abstractions that define how state is loaded, saved, and cleared.
BaseChatMessageHistory (Modern Approach)
The current standard for managing conversational history is the BaseChatMessageHistory class. This interface is designed to store a sequence of messages (BaseMessage objects). It is a simpler, more direct abstraction for chat-based applications and integrates seamlessly with the LangChain Expression Language (LCEL), particularly with runnables that manage history.
Sources: libs/langchain/langchain/schema/init.py:6
BaseMemory (Legacy System)
The BaseMemory class is the legacy abstract base class for memory in Chains. It defines a more general-purpose interface for loading and saving arbitrary key-value data, not just chat messages.
Deprecation Notice: The BaseMemory class and its associated components are deprecated as of version 0.3.3 and will be removed in 1.0.0. Users are encouraged to migrate to the BaseChatMessageHistory approach.
Sources: libs/core/langchain_core/memory.py:18-22
The diagram below shows the structure of the BaseMemory abstract class.
This diagram illustrates the abstract methods that any concrete memory implementation must provide.
Key Methods
| Method | Description |
|---|---|
memory_variables | A property that returns a list of string keys that the memory class will add to the chain's inputs. |
load_memory_variables(inputs) | Returns a dictionary of key-value pairs to be injected into the chain's context. It is called at the beginning of a chain run. |
save_context(inputs, outputs) | Saves the context of the current chain run to memory. It is called at the end of a chain run. |
clear() | Clears the memory contents. |
Sources: libs/core/langchain_core/memory.py:53-102
Integration with Chains (Legacy)
In the legacy system, a Chain object can be configured with a memory attribute, which should be an instance of a BaseMemory subclass. The chain automatically interacts with the memory object during its execution lifecycle.
The interaction flow is as follows:
- Before the chain's primary logic (
_callmethod) is executed, the chain callsprep_inputs. prep_inputsinvokes the memory'sload_memory_variablesmethod to fetch relevant context from the past.- This context is merged with the user's current inputs.
- The chain's logic is executed with the combined inputs.
- After execution, the chain calls
prep_outputs. prep_outputsinvokes the memory'ssave_contextmethod, passing the inputs and outputs of the current run to be stored.
Sources: libs/langchain/langchain/chains/base.py:72-78, libs/langchain/langchain/chains/base.py:469-477, libs/langchain/langchain/chains/base.py:530-541
This sequence diagram shows the interaction between a user, a Chain, and a BaseMemory object.
This diagram illustrates the lifecycle of a call to a chain that is configured with memory.
Memory Implementations (Legacy)
LangChain provides several concrete implementations of the BaseMemory interface, each with a different strategy for storing and retrieving information.
VectorStoreRetrieverMemory
This implementation stores conversation history in a vector store and uses a retriever to fetch the most relevant parts of the conversation based on the current input. This is useful for long conversations where not all of the history is relevant at any given moment.
Core Logic:
- Saving Context: When
save_contextis called, the inputs and outputs of the current turn are formatted into a singleDocumentand added to the vector store viaretriever.add_documents. - Loading Context: When
load_memory_variablesis called, the current user input is used as a query to theretriever.invokemethod. The retrieved documents are then formatted and returned as thehistoryvariable.
Sources: libs/langchain/langchain/memory/vectorstore.py
The following flowchart shows the data flow for VectorStoreRetrieverMemory.
This diagram shows the process of saving a new conversation turn and loading relevant history using VectorStoreRetrieverMemory.
Prompt-Based Memory Strategies
Several memory types are implemented not as distinct classes but through specialized PromptTemplate objects that guide an LLM to manage memory. These prompts are found in langchain.memory.prompt.
| Prompt Template | Purpose | Description |
|---|---|---|
ENTITY_MEMORY_CONVERSATION_TEMPLATE | Conversation | Injects extracted entity summaries into the main conversation prompt under a "Context" section. |
ENTITY_EXTRACTION_PROMPT | Entity Extraction | Instructs an LLM to extract proper nouns (names, places) from the last line of a conversation. |
ENTITY_SUMMARIZATION_PROMPT | Entity Summarization | Instructs an LLM to update a summary for a specific entity based on new information from the latest conversation turn. |
SUMMARY_PROMPT | Conversation Summary | Guides an LLM to progressively summarize a conversation by taking an existing summary and new lines of dialogue. |
KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT | Knowledge Graph | Instructs an LLM to extract knowledge triples (subject, predicate, object) from the conversation to build a knowledge graph. |
Sources: libs/langchain/langchain/memory/prompt.py
These prompts are used within more complex memory classes (like EntityMemory or ConversationSummaryBufferMemory, which are not detailed in the provided files but whose functionality can be inferred) to create sophisticated, LLM-managed memory systems. For example, an agent might use ENTITY_EXTRACTION_PROMPT to identify key entities and then use ENTITY_SUMMARIZATION_PROMPT to maintain a running profile of each one.
Conclusion
Memory is a fundamental feature for creating advanced, stateful LLM applications in LangChain. It enables chains and agents to maintain context over multiple turns, leading to more natural and intelligent interactions. The framework has evolved from a legacy BaseMemory system, which offered powerful but complex abstractions like VectorStoreRetrieverMemory, to a more streamlined BaseChatMessageHistory interface that aligns better with modern, runnable-based architectures. Understanding these patterns is key to building robust conversational AI.