> ## Documentation Index
> Fetch the complete documentation index at: https://docs.memanto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Pydantic AI

> Give your Pydantic AI agent long-term memory: automatic recall plus drop-in tools, backed by Memanto.

# Pydantic AI + Memanto

<img src="https://mintcdn.com/memanto/Fy1FqOw4PjMCeKzK/logo/integrations/pydantic-ai-light.svg?fit=max&auto=format&n=Fy1FqOw4PjMCeKzK&q=85&s=175f2510a80a419199dff5def29df5e5" alt="Pydantic AI" width="64" style={{marginBottom: "1.5rem"}} className="block dark:hidden" data-path="logo/integrations/pydantic-ai-light.svg" />

<img src="https://mintcdn.com/memanto/Fy1FqOw4PjMCeKzK/logo/integrations/pydantic-ai-dark.svg?fit=max&auto=format&n=Fy1FqOw4PjMCeKzK&q=85&s=fc72d289d2234da3228a95537546ca1b" alt="Pydantic AI" width="64" style={{marginBottom: "1.5rem"}} className="hidden dark:block" data-path="logo/integrations/pydantic-ai-dark.svg" />

A [Pydantic AI](https://ai.pydantic.dev) agent has no memory of its own. Every run starts fresh, with nothing carried over from earlier conversations.

**`memanto-pydantic-ai`** connects a Pydantic AI agent to Memanto in two complementary ways: relevant memories are recalled and added to the agent's instructions automatically on every run, and three tools let the model save a structured memory, search stored memories, or get a synthesized answer from everything it's learned.

<CardGroup cols={2}>
  <Card title="Automatic recall" icon="wand-magic-sparkles">
    `memory_instructions` recalls the memories most relevant to the user's prompt before each run and adds them to the agent's instructions, so the agent uses its memory even when the model doesn't think to look.
  </Card>

  <Card title="Works with Pydantic AI's own primitives" icon="plug">
    The tools drop into `Agent(tools=...)` and the recall into `Agent(instructions=...)`. No custom agent class, no extra wiring.
  </Card>

  <Card title="Typed memories, not transcripts" icon="brain">
    Saved memories go through Memanto's typed model (13 categories, including fact, preference, decision, goal, and learning), not raw conversation logs.
  </Card>

  <Card title="Fails safe" icon="shield-check">
    Invalid tool calls go back to the model as retries, a memory outage never takes your agent down, and misconfiguration fails at startup with a clear error.
  </Card>
</CardGroup>

## How It Works

```text theme={null}
agent.run("Book me a flight to Tokyo")
        │
        ├─ memory_instructions: recall memories relevant to the prompt
        │    → adds "- [preference] Home airport: User always flies out of LAX"
        │      to the agent's instructions (once per run)
        ▼
Pydantic AI's model reads the instructions, the conversation, and the tool descriptions
        │
        └─ may call a tool when it needs to
             ┌──────────────────────────┼──────────────────────────┐
             ▼                          ▼                          ▼
      memanto_remember            memanto_recall            memanto_answer
             └──────────────────────────┼──────────────────────────┘
                                        ▼
                  Memanto's SdkClient (Python, same process)
                                        ▼
                     Moorcheh API (or your on-prem backend)
```

There's no Memanto server to run: Pydantic AI and Memanto are both Python, so everything calls Memanto's client in-process. Memory lives in a Memanto agent, so you can read, correct, and audit what your Pydantic AI agent knows with the [CLI](/cli/overview) or the web UI, same as any other integration.

## Prerequisites

* Python **3.10+**
* `pydantic-ai-slim` **2.0+** (installed automatically) plus the extra for your model provider, or the full `pydantic-ai` package
* Memanto **0.2.21+** (installed automatically) and a [Moorcheh API key](https://console.moorcheh.ai/api-keys) (or an [on-prem](/on-prem/overview) Memanto backend)
* Credentials for the model your agent uses (the example below uses OpenAI `gpt-4o`, so set `OPENAI_API_KEY`)

## Install

```bash theme={null}
pip install memanto-pydantic-ai "pydantic-ai-slim[openai]"
export MOORCHEH_API_KEY=your_key_xxxxxxxxxxxxxxxxxx
export OPENAI_API_KEY=sk-...
```

Swap `[openai]` for your provider's extra (`[anthropic]`, `[google]`, ...), or install the full `pydantic-ai` package.

## Use it

```python theme={null}
from pydantic_ai import Agent
from memanto_pydantic_ai import MemantoSetup, create_memanto_tools, memory_instructions

setup = MemantoSetup()  # reads MOORCHEH_API_KEY
client = setup.setup(agent_id="travel-agent", description="Travel planning assistant")

agent = Agent(
    "openai:gpt-4o",
    instructions=[
        "You have long-term memory. Use memanto_remember to save durable facts, "
        "preferences, and decisions the user shares.",
        memory_instructions(client, agent_id="travel-agent"),
    ],
    tools=create_memanto_tools(client, agent_id="travel-agent"),
)

result = agent.run_sync("I always fly out of LAX, remember that for future trips.")
print(result.output)

# In a later session, the LAX preference is recalled and injected automatically:
result = agent.run_sync("Book me a flight to Tokyo.")
print(result.output)

setup.teardown("travel-agent")
```

* **`MemantoSetup.setup`** creates the Memanto agent on first use (and reuses it after that), then activates a session. Sessions renew automatically while in use.
* **`memory_instructions`** recalls the memories most relevant to each run's prompt and adds them to the agent's instructions.
* **`create_memanto_tools`** binds the client and agent id when the tools are created, so the model's only inputs are the memory content or query it's reasoning about.

Either piece works on its own: tools only (the model decides when to read memory), or `memory_instructions` only (read-only, automatic recall).

## Automatic recall

`memory_instructions` turns each run's user prompt into a recall query and adds the matches to the agent's instructions, most relevant first:

```text theme={null}
Relevant memories from long-term memory (most relevant first; they may be outdated, so prefer what the user says in this conversation):
- [preference] Home airport (saved 2026-10-02): User always flies out of LAX
```

* **Once per run.** Pydantic AI re-evaluates instructions before every model request, so the recall result is cached for the rest of the run instead of repeating it after each tool call.
* **Only current memories.** Expired memories are never injected.
* **The prompt is the query.** Only text parts of the prompt are used (images and files are skipped), truncated to 1000 characters. If there are no matches, nothing is added.
* **Outages degrade, not fail.** If the recall fails (network, auth, backend), a warning is logged and the run continues without injected memories.

## Available Tools

| Tool | Backed by | Description |
| - | - | - |
| `memanto_remember` | [Remember](/api-reference/data/remember) | Store a structured memory. `memory_type` (required, one of the 13 [memory types](/reference/memory-types)), `title` (required, 1–100 chars), `content` (required, 1–10000 chars), `confidence` (required, 0.0–1.0), `tags` (optional, comma-separated). |
| `memanto_recall` | [Recall](/api-reference/search/recall) | Semantic search over stored memories. `query` (required, up to 1000 chars), `limit` (1–100, default 10), `memory_types` (optional, comma-separated filter), `min_similarity` (optional, 0.0–1.0). Results show when each memory was saved and mark ones that are no longer current as `(expired)`. |
| `memanto_answer` | [Generate AI Answer](/api-reference/ai/generate-ai-answer) | RAG-synthesized answer over stored memories, using Memanto's configured LLM. `question` (required). |

Memories saved through `memanto_remember` are tagged with source `pydantic-ai-agent` and provenance `explicit_statement`. Pass `include_remember=False` (or `include_recall` / `include_answer`) to `create_memanto_tools` to expose a subset, for example for a read-only agent.

### Invalid tool calls are retried, not fatal

The limits above are part of each tool's schema, so the model sees them up front. If it still sends a bad call (an unknown memory type, a confidence of `85` instead of `0.85`, a recall `limit` over 100, an over-long title), Pydantic AI returns the validation error to the model as a retry prompt and the model corrects the call. The agent run keeps going. Network, auth, and backend errors from the tools still raise normally.

## Memory per user

A Memanto client holds one session for one agent. To give each end user their own memory, use one Memanto agent per user, each with its own `MemantoSetup`:

```python theme={null}
def agent_for(user_id: str) -> Agent:
    agent_id = f"travel-{user_id}"
    client = MemantoSetup().setup(agent_id)
    return Agent(
        "openai:gpt-4o",
        instructions=memory_instructions(client, agent_id=agent_id),
        tools=create_memanto_tools(client, agent_id=agent_id),
    )
```

Cache the result per user in a long-running app rather than calling `setup` on every request.

`create_memanto_tools` and `memory_instructions` check the client when they're created: if it has no active session, or its session is for a different agent, they raise a `ValueError` explaining the fix, instead of failing on the model's first tool call.

<Note>
  **One session per agent.** Activating a session invalidates any other session for the same Memanto agent, including one opened by the `memanto` CLI. Give each running app its own `agent_id`.
</Note>

## API

| | |
| - | - |
| `MemantoSetup(api_key=None)` | Wraps a Memanto `SdkClient` and manages the agent's lifecycle. Reads `MOORCHEH_API_KEY` when `api_key` is omitted. Use one per Memanto agent. |
| `.setup(agent_id, pattern="tool", description=None, duration_hours=6)` | Creates the agent if it doesn't exist, activates a session, and returns the client ready to use. |
| `.teardown(agent_id)` | Deactivates the session. |
| `create_memanto_tools(client, agent_id, *, include_remember=True, include_recall=True, include_answer=True) → list[Tool]` | The memory tools, ready to pass into `Agent(tools=...)`. |
| `memory_instructions(client, agent_id, *, limit=5, min_similarity=None, prefix=...)` | A dynamic instruction for `Agent(instructions=...)`. `limit`: memories to inject (1–100). `min_similarity`: 0.0–1.0, defaults to Memanto's configured recall threshold. `prefix`: text placed before the memories. |

## Shared memory across integrations

All Memanto integration packages use the same Moorcheh-backed agents when they share an `agent_id`:

| Integration | Package | What it does |
| - | - | - |
| **Pydantic AI** | `memanto-pydantic-ai` | Automatic recall into instructions, plus tools for remember, recall, and answer. |
| [`integrations/eve`](/integrations/eve) | `@moorcheh-ai/memanto/eve` | Eve tools for recall, remember, and answer. |
| [`integrations/google-adk`](/integrations/google-adk) | `memanto-google-adk` | ADK `BaseMemoryService` plus a remember tool. |
| [`integrations/mcp`](/integrations/mcp) | `memanto-mcp` | MCP server for Claude Desktop, Cursor, etc. |
| [`integrations/vapi`](/integrations/vapi) | `memanto-vapi` | Webhook giving a Vapi voice agent knowledge and memory. |
| [`integrations/crewai`](/integrations/crewai) | `crewai-memanto` | CrewAI tools for multi-agent memory. |
| [`integrations/langgraph`](/integrations/langgraph) | `langgraph-memanto` | LangGraph `BaseStore`, nodes, and tools. |

## Next Steps

* [Pydantic AI integration source & README](https://github.com/moorcheh-ai/memanto/tree/main/integrations/pydantic-ai)
* [Pydantic AI documentation](https://ai.pydantic.dev)
* [Remember API](/api-reference/data/remember)
* [Recall API](/api-reference/search/recall)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.