tutorialintermediate
Memory & context management with Claude Sonnet 4.6 May 2025 • Tools Agent Patterns Build AI agents with persistent memory using Claude's memory tool and context editing.
cookbook
View original on cookbookThis cookbook demonstrates how to build AI agents with persistent memory using Claude's memory tool and context editing capabilities. It addresses challenges of long-running agents losing learned patterns between sessions and context window overflow by implementing cross-conversation learning and automatic context management. The guide covers practical implementations for use cases like code review assistants, research assistants, and customer support bots, with setup instructions and best practices for memory security and organization.
Key Points
- •Implement the memory tool (memory_20250818) to enable cross-conversation learning where Claude writes down patterns and applies them in future sessions
- •Use context editing with two strategies: tool use clearing (clear_tool_uses_20250919) to remove old tool results and thinking management (clear_thinking_20251015) to handle extended thinking blocks
- •Configure memory as a file-based system under /memories directory with client-side implementation for full control over agent learning
- •Apply memory to practical workflows: code review assistants learning debugging patterns, research assistants accumulating knowledge, support bots remembering user preferences, and data analysis helpers storing techniques
- •Manage finite context windows (200k tokens for Claude 4) by clearing old tool results and thinking blocks when context grows large, preventing information loss and reducing computational costs
- •Set up Python environment with Anthropic SDK, configure API keys via .env file, and use Claude Sonnet 4.6 or compatible models (Opus 4.1, Haiku 4.5) that support memory features
- •Build agents that improve over time: Session 1 learns and documents patterns, Session 2 applies learned patterns immediately for faster performance
- •Implement best practices for memory security, organization, and retention policies to ensure agents maintain reliable and relevant knowledge across sessions
Found this useful? Add it to a playbook for a step-by-step implementation guide.
Workflow Diagram
Start Process
Step A
Step B
Step C
Complete
Concepts
Artifacts (3)
Environment Setup Scriptbashscript
# 1. Create virtual environment
python -m venv .venv
# 2. Activate it
source .venv/bin/activate # macOS/Linux
# or: .venv\Scripts\activate # Windows
# 3. Install dependencies
pip install -r requirements.txt
# 4. Configure API Key
cp .env.example .env
# Edit .env and add your ANTHROPIC_API_KEYEnvironment Configuration Templateenvconfig
# .env file
ANTHROPIC_API_KEY=your_api_key_here
ANTHROPIC_MODEL=claude-sonnet-4-6Python Client Initializationpythonscript
import os
from typing import cast
from anthropic import Anthropic
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Model configuration - use alias for automatic updates
MODEL = "claude-sonnet-4-6"
API_KEY = os.getenv("ANTHROPIC_API_KEY")
# Can override via ANTHROPIC_MODEL env var
if os.getenv("ANTHROPIC_MODEL"):
MODEL = os.getenv("ANTHROPIC_MODEL")
if not API_KEY:
raise ValueError("ANTHROPIC_API_KEY not found. Copy .env.example to .env and add your API key.")
if not MODEL:
raise ValueError("ANTHROPIC_MODEL not found. Copy .env.example to .env and set the model.")
MODEL = cast(str, MODEL)
client = Anthropic(api_key=API_KEY)
print("✓ API key loaded")
print(f"✓ Using model: {MODEL}")