Skip to content

Instantly share code, notes, and snippets.

@roninjin10
Created December 15, 2025 16:13
Show Gist options
  • Select an option

  • Save roninjin10/9fb6cbc51d76710dc87ce1ff74f2bdc1 to your computer and use it in GitHub Desktop.

Select an option

Save roninjin10/9fb6cbc51d76710dc87ce1ff74f2bdc1 to your computer and use it in GitHub Desktop.
memory tool

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

  1. 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'

  1. 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

1. Implement your storage backend

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()

2. Create agent with MemoryTool builtin

agent = Agent('anthropic:claude-sonnet-4-5', builtin_tools=[MemoryTool()])

3. Register a tool that forwards to your implementation

@agent.tool_plain def memory(**command): return memory_impl.call(command)

How It Works at Runtime

  1. Claude decides it needs to remember/recall something
  2. It calls the memory tool with a command (e.g., {"command": "create", "path": "/memories/user.txt", "file_text": "User likes coffee"})
  3. Your implementation handles the storage
  4. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment