Media Externalization
Content-addressed stores and walker helpers for moving large binary and text payloads out of Pydantic AI message history and replacing them with short media+sha256:// URIs. This package is supporting infrastructure, not an agent capability: nothing on this page mounts on Agent(capabilities=[...]). If you want snapshots that externalize large payloads automatically, start with Step Persistence; read this page when you configure a store yourself or call the walker helpers directly.
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: Media Externalization: store large payloads once, keep a URI in the history
accDescr: externalize_media takes binary and text payloads at or above threshold_bytes out of a message history and puts each, once per hash, in a MediaStore on disk, SQLite, S3, MongoDB or PostgreSQL. A media+sha256:// URI replaces each payload, leaving a lean history. From it, restore_media gets the payloads from the MediaStore and puts them back in place in the message history.
history["message history<br/>binary and text payloads"]
ext["externalize_media<br/>payloads at or above<br/>threshold_bytes"]:::capability
store[("MediaStore<br/>disk, SQLite, S3,<br/>MongoDB or PostgreSQL")]:::external
lean["lean history<br/>media+sha256:// URIs"]
restore["restore_media"]:::capability
history --> ext
ext -->|"put, once per hash"| store
ext -->|"URI replaces payload"| lean
lean --> restore
restore <-->|"get"| store
restore -->|"payloads back in place"| history
classDef capability stroke:#E520E9,stroke-width:2px
classDef external stroke:#0E9C86,stroke-width:2px
StepPersistence uses these stores to externalize large BinaryContent and text parts in run snapshots through its file, sqlite, mongo, and postgres backends (see Persisting media).
A conversation that carries images, audio, other BinaryContent, or large text parts (such as large tool returns) inlines those payloads into every persisted snapshot. Content-addressed stores key each payload by its SHA-256 hash and store a media+sha256:// URI in its place, so identical bytes are written once regardless of how many messages or snapshots reference them. Moving to another storage backend is a one-line swap because the URI does not change.
Every store implements the MediaStore protocol (put, get, exists, public_url, and get_metadata), all async and content-addressed.
| Store | Backed by | Use when |
|---|---|---|
FileMediaStore(directory=...) | A directory on disk | Local runs and tests |
SqliteMediaStore(database=...) | A SQLite database | A single-file store that travels with the data |
S3MediaStore(bucket=, endpoint=, region=, ...) | S3 or an S3-compatible bucket | Shared or production storage |
MongoMediaStore(client= or db_url=, database=, ...) | MongoDB (sha256-addressed chunking) | A MongoDB deployment; blobs larger than one BSON document |
PostgresMediaStore(pool, table=...) | PostgreSQL (one BYTEA row per blob) | A PostgreSQL deployment; blobs up to 1 GB |
S3MediaStore uses path-style URLs plus handrolled SigV4, so it is compatible with AWS S3, Cloudflare R2 (region='auto'), MinIO, and other S3-compatible providers. It uses PUT/GET/HEAD only: no multipart, lifecycle, or listing. SqliteMediaStore also accepts connection= instead of database= to share a sqlite3.Connection. On that connection, put commits its insert when no transaction is open and otherwise leaves the commit to you; a Python 3.12+ autocommit=False connection always has one open. The store’s first call creates its table without committing, so inside your transaction the table lands when you commit. A connection the store opens from database= waits up to 30 seconds for another writer before raising database is locked; a connection= keeps whatever timeout the caller set.
MongoMediaStore requires the mongodb extra (pymongo>=4.17.0). Pass a shared AsyncMongoClient via client= or a connection string via db_url=; database= is always required. When using db_url=, the store owns the client and adds pydantic-ai-harness and its version to the MongoDB connection handshake metadata; call await store.aclose() to release it. A caller-provided client= is left as configured.
Each blob is stored as SHA-256-addressed chunks in a <collection>_chunks collection with a manifest document (_id = <digest>) in <collection>, allowing blobs larger than MongoDB’s 16 MiB BSON document limit. Chunks are keyed by chunk size, so writers using different chunk_size_bytes (a retry after a crash, or two processes at once) do not overwrite each other’s chunks. get verifies reassembled bytes against the URI’s SHA-256 digest and raises ValueError on missing or corrupt chunks.
There is no streaming API: put accepts the full payload as bytes and get reassembles all chunks into a single bytearray, so blobs must fit in process memory. MediaContext.metadata is stored inline in the manifest document without chunking, so keep per-blob metadata small.
pip install "pydantic-ai-harness[mongodb]"
uv add "pydantic-ai-harness[mongodb]"
Two constructor parameters configure the collection layout: collection= (default 'media', validated against A-Za-z_*) names the manifest collection and derives <collection>_chunks, and chunk_size_bytes= (default 8 MiB) sets the split size (valid from 1 byte up to 16 MiB minus 64 KiB of headroom for chunk document fields).
On its first put or get, the store calls createIndex for a compound (files_id, n) index on the chunk collection, which avoids collection scans during reassembly. The connecting database user needs index-creation privileges (a restricted Atlas role may lack this), and pointing the store at an already-populated collection pays the index build on that first call.
from pymongo import AsyncMongoClient
from pydantic_ai_harness.media import MongoMediaStore
client = AsyncMongoClient('mongodb://localhost:27017')
store = MongoMediaStore(client=client, database='agent_media')
PostgresMediaStore takes a caller-owned asyncpg-compatible pool, described by the PostgresPool protocol exported from this package. The harness imports no driver and defines no extra for it: the application installs the driver and owns the pool, and the store does not close it. Each blob is one row in the media table (table= renames it; names outside a-z_* or longer than 63 characters are rejected, lowercase because PostgreSQL folds unquoted identifiers and 'Media' would share a table with 'media'), keyed by its sha256 digest, so a second put of the same bytes is a no-op (ON CONFLICT (sha256) DO NOTHING). The bytes are one BYTEA value, which PostgreSQL caps at 1 GB, and there is no streaming API, so a blob has to fit in process memory in both directions.
pip install asyncpg
uv add asyncpg
On its first operation the store issues CREATE TABLE IF NOT EXISTS in a transaction that first takes pg_advisory_xact_lock on a hash of the table name, so processes that start together do not collide. It skips that statement when the table already exists, so only the call that creates it needs CREATE on the schema: after that, a role granted SELECT and INSERT on the table is enough. There is no migration step: an existing media table with a different layout is left as it is and the first put or get fails on a missing column, so pass table= when the database already has a table of that name.
import asyncpg
from pydantic_ai_harness.media import PostgresMediaStore
async def build_media_store() -> tuple[PostgresMediaStore, asyncpg.Pool]:
pool = await asyncpg.create_pool('postgres://localhost/app')
return PostgresMediaStore(pool), pool
Close the returned pool during application shutdown. The store does not manage it.
externalize_media and restore_media walk the JSON form of a message history and swap payloads for URIs and back. externalize_media raises TypeError for anything that is not a JSON tree, such as a message object or bytes:
from pydantic_ai import ModelMessagesTypeAdapter
from pydantic_ai_harness.media import FileMediaStore, externalize_media, restore_media
store = FileMediaStore(directory='./media')
# Replace binary and text payloads at or above the threshold with media+sha256:// URIs.
tree = ModelMessagesTypeAdapter.dump_python(messages, mode='json')
lean = await externalize_media(tree, media_store=store, threshold_bytes=32_000)
# Later, rehydrate the URIs back into the original parts.
messages = ModelMessagesTypeAdapter.validate_python(await restore_media(lean, media_store=store))
externalize_media externalizes both large BinaryContent and large text: any message part whose string content reaches threshold_bytes UTF-8 bytes (TextPart, ThinkingPart, a string-returning ToolReturnPart, a string-valued UserPromptPart), plus any TextContent element travelling inside a UserPromptPart.content sequence or a ToolReturn, including a StructuredContent, whose rendered text is externalized while its structured value stays inline. The same threshold_bytes governs binary and text, and payloads below it stay inline. Round-trip is transparent: restore_media re-inlines binary bytes and text symmetrically. BinaryContent data that is not canonical base64 stays inline, since a tool can return a dict of the same shape. If you need to key media yourself, media_uri_for and parse_media_uri give you the raw URI round-trip.
Compatibility is upgrade-only: the current restore_media reads snapshots written by earlier releases. Older releases cannot validate externalized text markers and do not restore escaped caller keys. A current reader raises ValueError when encountering a marker format version newer than itself. Keep a current reader for persisted snapshots.
Payloads (such as tool returns) that contain keys colliding with the internal marker format are escaped on write and restored transparently on read. Restore an already-externalized tree before passing it to externalize_media again; otherwise existing markers are treated as literal data and wrapped.
When a store is fronted by a CDN, a local HTTP server, or a signed-URL service, pass a public_url= resolver (or use make_static_public_url) to turn a stored media+sha256:// URI into a URL the model can fetch directly. Without a resolver, public_url(...) returns None. If the target model doesn’t accept that URL type, Pydantic AI providers download the bytes, so a URL costs a download, not a failed request.
A static base URL, for a public bucket or CDN:
from pydantic_ai_harness.media import S3MediaStore, make_static_public_url
store = S3MediaStore(
bucket='my-bucket',
endpoint='https://<acc>.r2.cloudflarestorage.com',
region='auto',
access_key_id=..., secret_access_key=...,
key_prefix='media/',
public_url=make_static_public_url('https://pub-abc.r2.dev', key_prefix='media/'),
)
A presigned or rotating-signature URL: pass any async callable that takes (uri, MediaContext):
from pydantic_ai_harness.media import MediaContext, S3MediaStore
async def presign(uri: str, ctx: MediaContext) -> str:
key = 'media/' + uri.removeprefix('media+sha256://') + '.bin'
return await my_signer.generate(key, ttl=3600, content_type=ctx.media_type)
store = S3MediaStore(..., public_url=presign)
Every store method and both user-supplied callables (PublicUrlResolver, KeyStrategy) accept a MediaContext with per-operation metadata:
from collections.abc import Mapping
from dataclasses import dataclass, field
@dataclass(frozen=True, kw_only=True)
class MediaContext:
media_type: str | None = None # e.g. 'image/png'
filename: str | None = None # original filename, when known
metadata: Mapping[str, str] = field(default_factory=dict) # user-supplied tags
All fields default, so you pass what you have and ignore the rest; new fields are added non-breakingly as use cases emerge. get_metadata(uri) round-trips the user-supplied metadata mapping on all five stores (S3 sends metadata as signed x-amz-meta-* headers read back from HEAD; keys must match [A-Za-z0-9-]+ and come back lowercased) and raises FileNotFoundError for a blob that was never stored. On FileMediaStore a later put of the same bytes with metadata replaces it; on S3MediaStore every put replaces it, so one without metadata clears it; the SQLite, MongoDB, and PostgreSQL stores keep the first. On Disk and S3 this holds for puts that resolve to the same key, which a custom key_strategy may not. get_metadata never returns media_type, which S3 sends as Content-Type and the database stores keep in a column.
The default on-store key layout is <sha256>.bin. FileMediaStore and S3MediaStore accept a key_strategy= override to fit an existing layout. SqliteMediaStore, MongoMediaStore, and PostgresMediaStore do not, since the digest is their primary key; use table= or collection= to move the rows or documents instead:
from pydantic_ai_harness.media import FileMediaStore, MediaContext
def by_media_type(uri: str, ctx: MediaContext) -> str:
digest = uri.removeprefix('media+sha256://')
ext = {'image/png': '.png', 'image/jpeg': '.jpg'}.get(ctx.media_type or '', '.bin')
return f'images/{digest}{ext}'
store = FileMediaStore('runs', key_strategy=by_media_type)
If your strategy depends on ctx.media_type, the same context must be supplied at read time for get/exists to find the blob. FileMediaStore rejects a URI that is not media+sha256://<hex> before calling the strategy, and strategies that produce absolute paths or .. segments, to keep reads and writes inside the store directory. default_key_strategy is exported if you want to build on it.
| Symbol | Purpose |
|---|---|
MediaStore | Async content-addressed store protocol (put / get / exists / public_url / get_metadata) |
FileMediaStore, SqliteMediaStore, S3MediaStore, MongoMediaStore, PostgresMediaStore | Concrete stores (MongoMediaStore needs the mongodb extra) |
PostgresPool, PostgresConnection | The asyncpg-compatible pool and connection protocols PostgresMediaStore accepts |
MediaContext | Per-operation context (media type, filename, tags) threaded through store operations |
KeyStrategy, default_key_strategy | On-store key layout |
PublicUrlResolver, make_static_public_url | Resolve a stored URI to a public URL |
externalize_media, restore_media | Walk a JSON message tree to externalize / rehydrate large binary and text payloads |
media_uri_for, parse_media_uri | Compute and parse a media+sha256:// URI |
Source: pydantic_ai_harness/media/.
- Step Persistence: the first consumer of these stores, externalizing large
BinaryContentand text parts in run snapshots.