How MemoryTool Works in Pydantic AI
The MemoryTool in Pydantic AI is a built-in tool that enables agents to persist information across conversations. Here's how it works:
Architecture
- Pydantic AI Side: The MemoryTool class (builtin_tools.py:336-345) is a simple marker that tells Anthropic's API to enable the memory capability:
@dataclass(kw_only=True) class MemoryTool(AbstractBuiltinTool): kind: str = 'memory'
- Your Responsibility: You must implement a memory tool that handles the actual storage. The Anthropic SDK provides BetaAbstractMemoryTool as a base class.
The Command System
The memory tool uses 6 commands (like a mini file system):
| Command | Purpose |
|---|---|
| view | Read memory contents at a path |
| create | Create a new memory file |
| str_replace | Replace text in a file (must be unique) |
| insert | Insert text at a specific line |
| delete | Delete a file/directory |
| rename | Rename/move a file |
Usage Pattern
from anthropic.lib.tools import BetaAbstractMemoryTool from pydantic_ai import Agent, MemoryTool
class MyMemoryTool(BetaAbstractMemoryTool): def view(self, command): ... def create(self, command): ... def str_replace(self, command): ... def insert(self, command): ... def delete(self, command): ... def rename(self, command): ...
memory_impl = MyMemoryTool()
agent = Agent('anthropic:claude-sonnet-4-5', builtin_tools=[MemoryTool()])
@agent.tool_plain def memory(**command): return memory_impl.call(command)
How It Works at Runtime
- Claude decides it needs to remember/recall something
- It calls the memory tool with a command (e.g., {"command": "create", "path": "/memories/user.txt", "file_text": "User likes coffee"})
- Your implementation handles the storage
- Claude continues the conversation with the memory context
Key Point
The MemoryTool built-in just tells Anthropic's API that memory is available - you provide the actual storage (filesystem, database, cloud storage, etc.). The example in context/anthropic-sdk-python/examples/memory/basic.py shows a LocalFilesystemMemoryTool that stores memories as files in a ./memory/memories/ directory.