Learning resourcesReviewed · Pydantic

Pydantic AI Harness: Media Externalization

This guide explains storage for Python developers saving Pydantic AI Harness conversations, with the catch that restoring saved histories requires a separate payload store and compatible reader. It covers hash-based references, five storage backends and helpers that move large binary and text payloads out of message histories.

Researched 24 Nov 2026

In short.

This guide shows Python developers how to shrink saved Pydantic AI Harness conversations, but restoring those conversations depends on retaining the external payloads and using a compatible reader. It documents asynchronous stores for disk, SQLite, S3-compatible services, MongoDB and PostgreSQL, together with JSON helpers for replacing large binary and text payloads with SHA-256 references. Useful operational detail includes transaction behavior, database permissions, metadata handling and reader compatibility. Exact package version, deployment costs and measured performance are unknown. No code was executed.

Researched and written by an AI model and checked by a second AI model. How it works

Coverage is the complete selected page at [https://pydantic.dev/docs/ai/harness/media/index.md], including its documentation notices, 0.x API warning, store descriptions, examples, compatibility caveats and API listing. The linked documentation index, Step Persistence guide, version policy and GitHub implementation contents are excluded. Statements about behavior come from the page; execution, performance, deployment compatibility and production suitability were not assessed. The page establishes no redistribution license.

The overview

Identity

Media Externalization is a documentation page for the pydantic_ai_harness.media module [https://pydantic.dev/docs/ai/harness/media/index.md]. It explains the storage infrastructure used by StepPersistence to keep saved agent runs smaller. These stores and helpers are supporting infrastructure; they are not capabilities mounted through Agent(capabilities=[...]).

Assessment

The guide is useful when you already use Pydantic AI Harness and repeatedly save histories containing large images, audio or text. Its strength is the integration detail: it explains storage choices, serialization requirements and several backend-specific failure conditions. It provides no benchmarks, quantified storage savings or deployment reliability results, so it does not establish whether the approach meets a particular application's performance needs.

Users

The main audience is Python developers configuring a media store or implementing custom persistence for agent conversations. Beginners need familiarity with asynchronous Python, message serialization and their chosen storage system. Developers who only want automatic externalization in saved runs are directed toward StepPersistence; that linked guide is outside the available evidence.

Capabilities

The module provides FileMediaStore, SqliteMediaStore, S3MediaStore, MongoMediaStore and PostgresMediaStore. Each implements asynchronous put, get, exists, public_url and get_metadata operations. The page lists AWS S3, Cloudflare R2, MinIO and other S3-compatible providers as compatible with its path-style URLs and SigV4 signing; compatibility with a particular deployment was not assessed.

The walkers handle large BinaryContent and eligible text, including text nested in user prompts and tool returns. For StructuredContent, rendered text can be externalized while the structured value remains inline. A public URL resolver can supply a public or signed URL for a model to fetch; without a resolver, public_url returns None.

MediaContext carries media type, filename and user metadata. Metadata retrieval excludes media_type, and replacement rules differ: a later FileMediaStore put with metadata replaces it, S3 replaces it on every put and clears it when omitted, while SQLite, MongoDB and PostgreSQL retain the first metadata. S3 lowercases metadata keys.

Using it

Requirements

Use the pydantic_ai_harness.media submodule directly; the documented helpers have no top-level pydantic_ai_harness re-export. Direct walker use requires a JSON message tree, with ModelMessagesTypeAdapter shown for conversion. The page does not specify a minimum Python version or an exact harness release.

MongoMediaStore requires the mongodb extra, documented as pip install "pydantic-ai-harness[mongodb]", which installs pymongo>=4.17.0. It accepts a shared AsyncMongoClient or its own client created from db_url, and always requires database=. Its first put or get creates a compound chunk index, so the connecting user needs index-creation privileges.

PostgresMediaStore requires an application-owned, asyncpg-compatible pool. The application installs its driver separately; the harness provides no PostgreSQL extra. Creating the media table requires schema CREATE permission. Once the table exists, the page says SELECT and INSERT permissions are sufficient.

Mechanism

Content addressing means identifying a payload by a hash of its bytes. externalize_media replaces qualifying payloads with media+sha256:// references, allowing identical bytes to share a stored payload under the default layout. restore_media retrieves the payloads and puts them back into the JSON history. Binary and text use the same threshold_bytes setting; text size is measured in UTF-8 bytes, and smaller payloads stay inline.

The walker requires a JSON tree and raises TypeError for raw message objects or bytes. BinaryContent-shaped data with noncanonical base64 stays inline. The writer also escapes reserved marker keys so ordinary caller data can survive restoration.

FileMediaStore and S3MediaStore support custom key strategies; the database stores use the digest as their primary key. If a strategy depends on media_type, reads need the same context to locate the blob. FileMediaStore rejects malformed media URIs, absolute paths and paths containing parent-directory segments.

Setup

Choose a store and supply its directory, database or bucket configuration. For direct walker use, serialize messages with ModelMessagesTypeAdapter.dump_python(messages, mode='json'), await externalize_media with a chosen threshold, and save the returned tree. To recover messages, await restore_media and pass the result to ModelMessagesTypeAdapter.validate_python.

Connection ownership matters. Close a MongoDB client owned by the store with await store.aclose(); a supplied shared client remains application-managed. PostgreSQL pool shutdown also belongs to the application. An existing PostgreSQL table with an incompatible layout is not migrated automatically, so use table= when the default name conflicts.

With SQLite connection=, put commits only when no transaction is open; otherwise the caller controls the commit. A Python 3.12+ connection using autocommit=False always has an open transaction. Initial table creation does not independently commit. Connections opened through database= wait up to 30 seconds for another writer, while supplied connections retain their configured timeout.

Example

The documented local example creates FileMediaStore(directory='./media'), converts messages to JSON and calls externalize_media with threshold_bytes=32_000. Eligible binary and text payloads of at least 32,000 bytes become references; smaller payloads remain embedded. Later, restore_media retrieves those payloads before the message adapter reconstructs the messages. This is a documentation example, not an executed result.

Assessment & evidence

Limitations

MongoDB chunking avoids the 16 MiB BSON document limit for blob data, but it does not bound process memory: put receives the whole payload and get reassembles it in memory. Its metadata manifest is not chunked, so metadata must remain small. PostgreSQL stores each blob in one BYTEA value, capped at 1 GB, and likewise provides no streaming API.

Persisted-format compatibility is upgrade-only in the cases described. Older readers cannot validate snapshots containing externalized text markers, and readers predating reserved-key escaping can leave caller values nested under reserved mappings. A reader rejects an escaped marker stamped with an unsupported format version. Restore an already externalized tree before externalizing it again, because existing markers are otherwise wrapped as literal data.

A saved history depends on continued access to its payload store. Public or signed URL resolution requires additional configuration; a media URI alone is not a fetchable web address. The page does not establish retention, garbage-collection, backup or deployment access-control guarantees.

Reasoning

The architectural tradeoff is smaller saved histories in exchange for a separate storage dependency and a restoration step. Repeated large payloads are the clearest fit because their references can share stored bytes. For small or infrequently saved histories, the extra integration may offer little benefit; that is an inference from the design, not a measured finding. Choose a threshold using representative application data rather than treating the example's 32,000 bytes as a universal recommendation.

Alternatives

Within the documented system, StepPersistence is the suggested route for automatic snapshot externalization, while direct walker calls suit applications that manage serialization themselves. The backend choices address different needs: files for local work, SQLite for a portable database, S3-compatible storage for shared deployments, and MongoDB or PostgreSQL for existing database infrastructure. Keeping payloads below the threshold inline is another supported choice. The page provides no comparison with competing libraries or persistence systems.

Evidence

The evidence is the complete Media Externalization page at [https://pydantic.dev/docs/ai/harness/media/index.md]. It contains API descriptions, configuration examples and explicit operational caveats. These establish the documented behavior, not independently observed behavior. No installation, code execution, round-trip verification, provider compatibility check or performance measurement was performed. Linked documentation and implementation files are outside the evidence.

Access & freshness

Costs

The page states no library price, subscription fee or storage-service rates, so cost is unknown. It also gives no database, request, network-transfer or URL-signing costs. Content addressing supports deduplication, but the page does not quantify financial savings, latency changes or model-token savings. Smaller saved snapshots should not be treated as evidence of lower inference bills.

Rights

The selected page does not state a license for the documentation or implementation. Rights to reuse, modify or redistribute either are therefore unknown from this evidence. It links to an implementation directory [https://github.com/pydantic/pydantic-ai/tree/main/src/pydantic_ai_harness/pydantic_ai_harness/media/], but the linked repository contents and license were not assessed.

Freshness

The page was captured at 2026-11-24T01:57:03.180Z. It warns that Pydantic AI Harness remains on 0.x releases and that minor releases may change APIs, with deprecation warnings and release-note migration guidance. The capture does not identify an exact harness release, source commit or page-update date. Compatibility with an installed release remains unverified.

Actions

Before adoption, identify and pin the harness release, choose a backend, confirm its permissions and connection ownership, and establish the applicable license and deployment costs. Decide whether StepPersistence or direct walker integration fits the application.

For an initial integration check, round-trip representative binary and text messages, structured tool returns, metadata and payloads containing reserved marker keys. Verify transaction behavior and storage failures relevant to the chosen backend. MongoDB users should account for index creation and whole-blob memory use; PostgreSQL users should check table compatibility and blob size. Check reader compatibility before upgrades, and review access and expiry when exposing payload URLs. These are recommended checks, not completed results.

Evidence for this report

selected-page.txtselected · checked 2026-11-24