翻篇收录说明
翻篇网页快照

Memory | Pydantic Docs

https://pydantic.dev/docs/ai/harness/memory/

最近抓取:2026-12-03 23:36:27(北京时间)

最近内容变化:2026-12-03 23:36:27(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Give a Pydantic AI agent long-term memory across runs: a Markdown notebook it writes and searches, per-user namespaces, and file, SQLite, or Postgres stores.

正文摘录

Memory Give an agent a persistent notebook that it can update, search, and reuse across runs without loading every stored file into every prompt. While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy. flowchart TB accTitle: Memory: a notebook the agent keeps across runs accDescr: Your code gives Memory a namespace, such as from ctx.deps. The model calls Memory's four tools, such as write_memory, which read and make compare-and-swap writes in a store, such as FileMemoryStore, with alice/main/MEMORY.md and auth-notes.md. On the first request of each run, Memory sends the model a memory block (MEMORY.md excerpt, names of other files) before the user's prompt. model(["model"]) code["your code"] memory["Memory()<br/>four tools, such as<br/>write_memory"]:::capability store[("store, such as FileMemoryStore<br/>alice/main/MEMORY.md,<br/>auth-notes.md")]:::external snapshot["&lt;memory&gt; block<br/>MEMORY.md excerpt,<br/>names of other files"]:::capability code -->|"namespace, such as<br/>from ctx.deps"| memory model <-->|"tool call, result"| memory memory <-->|"reads,<br/>compare-and-swap<br/>writes"| store memory -->|"first request of each run"| snapshot snapshot -->|"before the user's prompt"| model classDef capability stroke:#E520E9,stroke-width:2px classDef external stroke:#0E9C86,stroke-width:2px Notebook model Memory gives each agent a notebook made of Markdown files: MEMORY.md is the main notebook. By default, a bounded excerpt and the names of other files are recorded before the user’s prompt as delimited user-role context, once per run in which they changed. Other files hold longer or focused notes. The model reads them on demand or finds them with bounded text search. The model gets four tools: ToolPurposewrite_memoryAppend to a file or replace one unique text fragment. In a file with \r\n line endings, an old_text with \n line endings, as the injected snapshot shows them, matches too. Writes use optimistic concurrency and an idempotency identifier derived from the run, its step, and the tool call.read_memoryRead a bounded prefix of one memory file. Left out when FileSystem can read the files (Reading memory with FileSystem).delete_memoryDelete a file. The main notebook is protected.search_memorySearch across notebook files, subject to configured result, character, and file-scan limits. from pydantic_ai import Agent from pydantic_ai.capabilities import LocalWorkspace from pydantic_ai_harness import Memory from pydantic_ai_harness.memory import FileMemoryStore agent = Agent( 'anthropic:claude-opus-5-5', capabilities=[LocalWorkspace('.'), Memory(FileMemoryStore('.agent-memory'))], defer_model_check=True, ) FileMemoryStore keeps the notes as Markdown files in the run’s workspace, so the model can also open them with its file tools. A run without a workspace fails at its start. With a read-only run workspace, the write and delete tools are hidden; a store with its own workspace follows that workspace’s permissions instead. Workspace refusals during mutations become tool failures. To keep them on your machine while the agent works in a sandbox, pass a backend: FileMemoryStore('.', workspace=LocalWorkspaceBackend('/var/lib/myapp/memory')). The namespace is resolved by application code, not supplied to the tools. The model therefore cannot select another user’s namespace in a tool call. Reading memory with FileSystem When the store is a FileMemoryStore that keeps its files in the run’s workspace (no workspace= of its own, and a relative directory inside the working directory) and FileSystem is on the agent, read_memory steps aside for FileSystem’s read_file. The tool is marked with unless_tool_kind set to READ_FILE_KIND, so it is left out of every run step that has a tool of that kind. With a store_resolver, the store it returns for the run decides. An instruction block named directory tells the model where this scope’s files are (for example, “Memory files are in .agent-memory/main/ in the workspace; read them with the file-reading tool.”), so the model knows even in a run that records no snapshot. The block is present from the first request, empty while no file reader is on the run, and appended to the history when one joins. The usage guidance does not name a reader, so it stays unchanged across runs in the cached prefix. The directory block shares max_tokens with the guidance and the snapshot. When it does not fit, the block is empty and read_memory stays. While a file reader is on the run, the injected <memory> block also names the files’ directory, and notices that would point at read_memory (lines left out of the injected notebook, or an old_text that was not found) name a read_file call on the file’s path instead. InMemoryMemoryStore, SqliteMemoryStore, PostgresMemoryStore and a FileMemoryStore with a workspace= of its own keep their files where FileSystem cannot see them, so with those read_memory stays. With inject_memory=False, or when the guidance alone fills max_tokens so no snapshot fits, read_memory stays too: the injected <memory> block is where the model learns the files’ directory. The decision is made from the store, not from FileSystem’s access rules. A FileSystem whose denied_patterns cover the memory directory, or whose allowed_patterns leave it out, still replaces read_memory but cannot open the files. Give the store a workspace= of its own to keep read_memory in that setup. The directory includes the namespace. With file tools over the run’s workspace, the model can read every namespace’s files under directory, whether or not read_memory is offered, so give the store a workspace= of its own when namespaces separate users who must not see each other’s memory. Injection modes and limits Automatic injection is on by default. The usage guidance goes in the model instructions, and stored memory goes in a <memory> block, a user-role part recorded before the user’s prompt. The guidance, MEMORY.md, and the list of other files share max_tokens (default 2,000, estimated at four characters per token); the default guidance alone uses about 200 of them. max_lines also caps the MEMORY.md lines shown, and max_memory_size caps each backend read. The file listing is bounded by the same budget, so the capability never requests an unbounded file or listing. Whatever does not fit is left out, with a note pointing the model to read_memory (or read_file, where it replaces read_memory) or search_memory. When the guidance alone fills the budget, nothing is injected and the memory.inject span records memory.outcome='budget_exhausted'. When heading is set, the same ## {heading} labels both the trusted guidance and the user-role memory block. from pydantic_ai_harness import Memory from pydantic_ai_harness.memory import FileMemoryStore memory = Memory( FileMemoryStore('.agent-memory'), max_tokens=2_000, max_lines=200, ) The snapshot is added to the conversation’s message history, so every later request sends it unchanged and the cached prompt prefix holds. Memory adds one on the first request of a run, before the user’s prompt in the same request, so the question comes last, and only when memory changed since the latest snapshot in the history (or there is none yet). A conversation therefore carries one snapshot per run in which memory changed; earlier ones stay where they were sent, and the default guidance tells the model that a later <memory> block for the same memory supersedes its earlier ones. When memory is emptied, the new snapshot says so, under the memory’s heading. An empty snapshot is skipped only in a fresh conversation, whose history is just the current prompt: anything earlier, such as an older snapshot a provider still sends after another provider’s compaction or a summary that kept memory’s facts, could still show what was deleted. A snapshot before the latest compaction boundary no longer counts, so the next run records the current memory again. New or changed memory is not added after tool results, where a model could read it as a new message from the user. The one exception is restoring the run’s own snapshot when compaction drops it mid-loop, described below. Memory that changes during a run, through write_memory or an external update, reaches the model with the next user prompt; the model’s own writes are already in the conversation as its tool calls. A snapshot is only added before the model has responded in the run: A run with no prompt and no tool results, such as agent.run() on an empty history, gets its snapshot on its first request. A run that resumes without a new prompt from history ending in tool results or a response (such as after a deferred tool approval or a provider-suspended response) adds no new snapshot, even if a hook retries its first request. A Memory capability loaded mid-run with defer_loading=True adds none either. In both cases, updated memory reaches the model with the next user prompt. If an earlier capability’s before_model_request retries the run’s first request, the request holds the retry feedback rather than the prompt, so the snapshot follows the feedback, still ahead of any response. Every snapshot is enqueued, so UI adapters stream it as an EnqueuedMessagesEvent. Stored memory and the listed file names go into the snapshot as data, with a note in the application’s voice that the agent wrote it in an earlier run, not the user or the application. They go in as stored: text in them that looks like the framework’s framing tags, such as <system>, or opens or closes <memory> itself, gets a further note saying the agent wrote it, so memory can’t close its block or read as the application speaking. Each snapshot is a MemorySnapshotPart, a capability part holding data the agent wrote in an earlier run, never trusted, and recognized by its type and its scope_hash and memory_id fields (the hashed