Using Memory in Agents
Learn how to add memory and context to your agents across multiple interactions.
Agent memory lets your agent remember past conversations and context. This works by saving the conversation history with a state saver. Without a state saver, the agent starts fresh every time and can't recall previous interactions.
State Savers
State savers are responsible for persisting the agent's state across multiple interactions. They store snapshots of the agent's state, including:
- Input/output messages
- Memory content
- Run metadata (timestamps, usage statistics)
- Error information (if any)
The most basic state saver is the InMemorySaver
, which stores everything in memory. Here's how to use it:
Run Context and Memory Chain
Memory is maintained through a chain of run contexts, where each interaction is linked to its previous one through a parent_id
. This creates a traceable history of conversations.
Here's a complete example showing how memory works:
The agent responded with "Your name is David" because it has access to the previous context.
Let's take a closer look at the registers:
StartEvent(..., path='agent', ...)
StartEvent(..., path='agent.llm-0', ...)
OutputEvent(..., path='agent.llm-0', ...)
OutputEvent(..., path='agent', ...)
StartEvent(..., path='agent', ...')
StartEvent(..., path='agent.llm-0', ...')
OutputEvent(..., path='agent.llm-0', ...)
OutputEvent(..., path='agent', ...)
How Memory Works
-
Run ID: Each interaction gets a unique
run_id
that identifies that specific interaction. -
Parent ID: When you want to maintain context, you create a new
RunContext
with theparent_id
set to the previous interaction'srun_id
. This creates a chain of memory. -
Memory Loading: When an agent receives a request with a
parent_id
, it:- Loads the previous state from the state saver
- Includes that context in the current interaction
- Maintains the conversation history
Memory Chain Visualization
Each interaction maintains its connection to the previous one through the parent_id
, creating a chain of memory that allows the agent to maintain context throughout the conversation.
For more information about different types of state savers and their implementations, check out the [State documentation].