Skip to main content

pydantic-ai-memorysync

Long-term memory for Pydantic AI, backed by MemorySync — one capability in the Agent(...) constructor gives every run recalled context and automatic turn persistence.

  • MemorySyncCapability — injects what MemorySync knows about the user before every run and persists completed turns after it, through the framework's own capability channels.
  • Five agent tools — add, search, list, update, delete; they never raise.
  • create_memory_search_tool — memory search returning typed list[MemoryResult] Pydantic models.
  • Async helpersget_memory_context, search_memories, save_turn.
pip install pydantic-ai-memorysync

Set MEMORYSYNC_API_KEY in the environment (create a key at app.memorysync.io), or pass api_key explicitly. Python 3.10+, pydantic-ai 2.x.

The capability

from pydantic_ai import Agent
from pydantic_ai_memorysync import MemorySyncCapability

agent = Agent(
    "openai:gpt-5",
    instructions="You are a helpful assistant.",
    capabilities=[MemorySyncCapability(user_id="customer-7")],
)

result = await agent.run("What should I cook tonight?")
# The model saw "Relevant memories about this user..." — and this
# exchange is now remembered for every future run.

Recall rides the instructions channel. The capability contributes a dynamic instruction (the framework's get_instructions channel), so recalled memory lands in ModelRequest.instructions — visible to the model, but never a conversation part. Replaying result.all_messages() into the next run can never stack stale memory blocks into the transcript, the classic failure mode of message-mutation integrations. One recall per run, replayed identically across however many model requests a tool-calling run makes.

Persistence is success-only, by construction. Turns persist in after_run, which Pydantic AI fires only when the run succeeds — a failed run leaves no half-turn behind (no remembered question with no answer), with zero custom guard code to get wrong. Tool calls, retry prompts and thinking parts never persist; streaming runs persist the final streamed text.

Identity comes from your deps. In order: user_id_resolver(ctx) when provided, the static user_id, then a user_id attribute on ctx.deps:

from dataclasses import dataclass

@dataclass
class MyDeps:
    user_id: str

agent = Agent(
    "openai:gpt-5",
    deps_type=MyDeps,
    capabilities=[MemorySyncCapability()],  # reads ctx.deps.user_id per run
)
await agent.run("hi", deps=MyDeps(user_id="customer-7"))

Without an identity the run proceeds memoryless and the miss is reported through on_error — guessing a shared namespace would mix users' memories, the one unforgivable failure for a memory layer.

Failure discipline: recall failures degrade to the agent's base instructions; persistence failures leave the run result untouched. Both report through on_error (default: a logging warning); neither ever breaks a run the model completed. persist=False gives read-only memory.

Conversations group themselves. Turns are keyed by the run's conversation_id, which Pydantic AI carries across message_history continuations — one conversation stays one conversation across processes and deploys. Pass session_id="..." to pin the grouping yourself.

Agent tools

from pydantic_ai import Agent
from pydantic_ai_memorysync import create_memorysync_tools

agent = Agent(
    "openai:gpt-5",
    instructions="Use the memory tools to remember durable facts.",
    tools=create_memorysync_tools(user_id="customer-7"),
)

# Untrusted agents: search + list only.
create_memorysync_tools(user_id="customer-7", read_only=True)

add_memory, search_memory, list_memories, update_memory, delete_memory — the same five operations, same response strings as the MemorySync LangChain, AI SDK, CrewAI, Mastra, OpenAI Agents, LlamaIndex and Google ADK tool sets. Plain async callables; failures return short readable strings, never exceptions — in Pydantic AI a tool exception fails the whole run, and a memory lookup is never worth that.

Typed search results

from pydantic_ai_memorysync import create_memory_search_tool, MemoryResult

agent = Agent(
    "openai:gpt-5",
    tools=[create_memory_search_tool(user_id="customer-7")],
)
# The tool returns list[MemoryResult]: validated id / text / score fields.

Helpers

from pydantic_ai_memorysync import get_memory_context, save_turn, search_memories

context = await get_memory_context("what should I cook?", user_id="customer-7")
hits = await search_memories("dietary preferences", user_id="customer-7")
await save_turn(user_id="customer-7", user="I'm vegetarian", assistant="Noted!")

All surfaces share the same idempotency seeds, so mixing styles cannot double-store a turn. save_turn raises on failure — an explicit persist call is owed the truth.

Version support

Package Requires Runtime
pydantic-ai-memorysync 1.0.0 pydantic-ai (or -slim) >=2,<3 Python 3.10+

CI drives REAL agents — instruction-channel injection, replay safety, success-only persistence, streaming, typed tool results — against the latest pydantic-ai 2.x release on every push.

Documentation

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pydantic_ai_memorysync-1.0.0.tar.gz (15.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydantic_ai_memorysync-1.0.0-py3-none-any.whl (18.4 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_ai_memorysync-1.0.0.tar.gz.

File metadata

  • Download URL: pydantic_ai_memorysync-1.0.0.tar.gz
  • Upload date:
  • Size: 15.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.11.9

File hashes

Hashes for pydantic_ai_memorysync-1.0.0.tar.gz
Algorithm Hash digest
SHA256 384f59afbec9aa901f549b594eec0b6f4d7e7862d3e644ea3ab8e199de78e9b5
MD5 9699374df51b088fddb8e1fd02df7394
BLAKE2b-256 6a00412cd3964dc00dc113c45fd4b51cb9bc273452b20219fac689c733fb2159

See more details on using hashes here.

File details

Details for the file pydantic_ai_memorysync-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_ai_memorysync-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 cddf519301d3cdabdf89a998516eb1438a25a9828ad613b8015c523c68be1900
MD5 10977507700ec6369898ba37d0bd041f
BLAKE2b-256 5fcd45c421e83053ff33c5b66b71b1a023fe45f2c6712a794d9ea3352ace31ac

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page