When you pass memory= to an Agent, the agent automatically injects stored conversation history before each model call and stores new messages after each response. When the session grows beyond max_messages, older messages are automatically summarized.
Setup
There are two ways to add memory to an agent:
1. Memory instance (recommended):
2. memory=True — ephemeral in-memory store, useful for testing:
Execution Flow
- Recall — Before calling the model, the agent loads the session’s conversation history from the store and injects it as context in the system prompt.
- Model call — The model receives the conversation plus any injected memory context.
- Store — After the response, the agent stores the new user and assistant messages. If the total entry count exceeds
max_messages, the SummarizeStrategy runs: it pins the first few messages, summarizes the middle section, and keeps the most recent messages intact. This runs as a background task.
Auto-Summarization
When conversation history exceeds max_messages, the SummarizeStrategy compresses it:
Configure the summarization behavior:
The summarization is tool-call-aware — it respects tool call boundaries so that tool requests and their results stay together in the same section.
Multi-User Scoping
Pass user_id to scope memory per user:
The user_id flows through RunContext and is used for both recall and storage. Each user’s conversation history is fully isolated.
Multi-Turn Conversations
Memory works alongside session-based multi-turn conversations. Pass previous messages to maintain conversation continuity, while memory handles long-term history:
session_id alone does NOT maintain conversation history. You must pass messages=r1.messages for multi-turn context, or use Memory for long-term recall across sessions.
Direct Memory Operations
You can interact with the memory system directly, outside of agent runs:
Non-Fatal Behavior
All memory operations are designed to be non-fatal. If the memory store is unavailable or a memory operation fails, the agent logs a warning and continues normally without memory context: