Learning resourcesReviewed · Pydantic

Pydantic AI Batch Processing

Pydantic AI Batch Processing is a guide for Python developers running bulk AI tasks, where results may take hours to arrive. It explains agent batching, direct batch requests and resumable jobs for specific Anthropic, OpenAI and Google APIs, including failure handling and the risk of duplicate submissions.

Researched 23 Nov 2026

In short.

Pydantic AI Batch Processing is a guide for Python developers processing AI work in bulk, with results that can take hours and support restricted to specific provider APIs. It documents three approaches: batching existing agent runs, sending independent requests through a direct helper, and managing provider jobs through low-level methods. Its strongest practical material covers concurrent submission, saving message histories for later collection, transient failures, cancellation and recovery. The page describes batch prices as about half standard prices, but supplies no exact model rates or measured savings. Interactive applications and agents requiring many model turns are poor fits because each request adds another batch round trip. Runtime correctness, performance and actual costs were not assessed.

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

Covers the complete selected Batch Processing page at [https://pydantic.dev/docs/ai/core-concepts/batch/index.md], including its examples, documentation notices, provider support, configuration, deferred collection, durable execution, errors, credentials, cancellation, tracing and retention. All linked pages are excluded. Claims about external providers and integrations are limited to statements on this page. No examples or APIs were executed; current pricing, compatibility and production behavior were not independently verified.

The overview

Resource

This is the Batch Processing chapter of Pydantic AI's documentation at [https://pydantic.dev/docs/ai/core-concepts/batch/index.md]. It teaches how Python applications can submit model requests for delayed provider processing, either through agents or directly through model APIs.

The chapter includes Python and YAML examples, configuration defaults, provider compatibility, recovery behavior and operational caveats. The supplied page does not identify the Pydantic AI release needed to use these features.

Practical assessment

The guide is useful for deciding whether an existing Pydantic AI workload can exchange immediate responses for lower documented provider prices. It goes beyond submission examples by explaining how work is grouped, when retries happen, how results survive process boundaries and where recovery can create duplicate jobs.

The main trade-off is latency. The page gives Anthropic and OpenAI a 24-hour processing window; Google targets 24 hours and expires a job after 48 hours. These windows are not completion guarantees. No measurements establish actual turnaround, throughput, output quality or savings.

Who it suits

The intended users are Python developers running evaluations, classifying many records, extracting structured information or generating data offline. Existing Pydantic AI users can start with the agent capability; developers who only need independent requests can use the direct helper.

Beginners need familiarity with asynchronous Python and Pydantic models to follow the examples. Experienced developers will find details about persistent histories, workflow engines, request accounting and custom transports. Work that must answer a person immediately, or requires many sequential tool calls, is a poor fit.

What it teaches

BatchModelRequests routes an agent's model calls through provider batches while retaining tools, structured output, validation and retries. Sharing one capability instance lets several agents collect compatible requests together. PendingModelResponse lets a run finish after submission and resume later from stored message history.

For independent requests, model_request_batch returns responses or request-specific errors in input order and handles provider grouping and size limits. Infrastructure failures instead raise an error and trigger cancellation of unfinished batches created by the call. The low-level batch_* methods expose encoding, creation, status, result retrieval, decoding and cancellation for applications that manage jobs themselves.

Using it

Requirements

Agent batching requires an asyncio event loop; Trio is unsupported. Provider processing requires direct provider access and an API key because batching is not available through Pydantic AI Gateway on this page. Minimum Python and Pydantic AI versions, installation commands and complete dependency requirements are not supplied.

Supported adapters are AnthropicModel through Claude's Message Batches, OpenAIResponsesModel through OpenAI's Batch API, and GoogleModel through Gemini's Batch Mode. The page excludes Anthropic access through Bedrock, Vertex AI or Microsoft Foundry; OpenAIChatModel and Azure OpenAI; and Google access through Vertex AI. Individual model eligibility and batch limits remain provider-dependent.

Credentials must be visible and stable for grouping requests. The page rejects OpenAI API-key callbacks, workload identity, HTTP-client authentication and per-request extra_headers for batching. Credentials should instead be configured on the provider client.

How batching works

BatchModelRequests collects requests until a batch fills or its oldest request reaches max_wait. Defaults are 1,000 requests and 30 seconds, subject to provider count and byte limits. Polling starts after 30 seconds, grows by half after each check and stops growing at a 10-minute interval. Sequentially awaited runs generally form separate batches; concurrent runs can share them.

Compatible requests are grouped by provider requirements, including credentials and endpoints. OpenAI and Google also separate models; Anthropic can mix models but separates incompatible beta flags. Tools or validation retries generate additional model requests, each requiring another batch round trip.

The agent capability and direct helper resubmit eligible transient failures in up to two new batches by default. Invalid requests, context overflow, exhausted quota and cancelled batches fail immediately. Low-level API users must implement their own resubmission and missing-result handling.

Setup approach

For agent batching, configure a supported provider model, add BatchModelRequests to the agent's capabilities and start independent runs together, as the page demonstrates with asyncio.gather. Using return_exceptions=True allows each run's result or failure to be handled separately. Reuse one capability instance when compatible requests from different agents should share batches.

For later collection, include PendingModelResponse in output_type, save the returned message history and restore it with ModelMessagesTypeAdapter. Resume with BatchModelRequests enabled. If the submitting model was selected dynamically, save its name and pass that model when resuming; omitting the required capability or model raises UserError.

With max_wait=None, submission waits for a full batch or an explicit flush(). The page advises against this setting for durable execution because workflow code cannot call flush(); a finite max_wait should also remain well below the durable step's timeout.

Illustrative use

The support-ticket example defines a Pydantic Triage object containing a category of billing, bug, account or other, plus an urgent boolean. It starts classification runs together so their requests can share a provider batch, then handles each result independently.

A second version adds PendingModelResponse, saves each run's history as JSON and collects results later. If a result is still pending, the new history replaces the previous one before another collection attempt. This illustrates an offline ticket-processing job; the displayed outputs are documentation examples, not observed results.

Assessment & evidence

Operational limits

Batch responses arrive all at once. Streaming APIs wait for the batch and then emit response parts, so they do not provide incremental generation during processing. The direct helper rejects per-request request_timeout; its whole wait can instead be limited through cancellation. For agent runs, request_timeout covers queueing through result arrival.

Durable execution does not guarantee a single submission. A crash after provider creation but before the submitting step completes can cause another batch on retry. Temporal and DBOS preserve waits; some other integrations require the process to remain alive during waits. Restate and Airflow do not record these batched calls through their model wrappers, so recovery submits another billed batch.

Retrying HTTP transports can also repeat batch-creation requests even though SDK retries are disabled. The page shows how to exempt batch-creation error responses from transport retries. A failed creation is not automatically resubmitted because a batch may already exist.

Results expire. The page states 30 days after completion for OpenAI output files, 29 days after creation for Anthropic results, and six weeks by default for Google results. Expired results raise SuspendedResponseExpired rather than automatically repeating potentially billed work. Direct batch calls and low-level methods are not traced; instrumented agent batches use separate linked traces.

How to judge fit

The best fit is a large set of independent requests with flexible completion times. This follows from the documented pricing trade-off and the ability to collect concurrent requests into shared jobs. A workflow with many sequential model turns accumulates provider waiting time, queueing delays and polling delays at each turn.

PendingModelResponse is useful when a process should stop while the provider works, provided the application stores histories and schedules collection. A durable engine can manage parts of recovery, but its specific guarantees still matter. The guide supports these architectural choices; it does not establish a workload size at which batching becomes worthwhile.

Other approaches

Ordinary live agent requests are the relevant alternative when response time matters more than the documented batch discount. Within batching, BatchModelRequests suits existing agent workflows, model_request_batch suits independent request lists, and the low-level methods suit applications owning job storage and lifecycle management.

The page also describes TestModel and FunctionModel as immediate, in-memory batch implementations for development testing. They cannot establish real provider latency, billing or failure behavior. No comparison with other batching libraries or frameworks is supplied.

Evidence and confidence

The evidence is Pydantic's complete Batch Processing documentation page at [https://pydantic.dev/docs/ai/core-concepts/batch/index.md]. It provides detailed API descriptions and illustrative examples, supporting conclusions about documented interfaces and intended behavior.

Linked provider documentation, API references and integration guides are outside the supplied evidence. No code or provider API was executed. Runtime correctness, model availability, successful recovery, throughput, output quality and actual bills remain unassessed.

Access & freshness

Costs and accounting

The page describes provider batch prices as about half standard prices. This is an approximate relative claim: exact model rates, currency and total workload cost are unknown. Responses carry provider_details['processing'] == 'batch', allowing ModelResponse.cost(), usage.cost and usage limits to use batch prices from genai-prices.

In submit-and-collect cycles, usage.requests counts the waiting request in each run, while tokens and cost are counted only by the run receiving its result. Summing request counts across resumptions therefore overcounts unique requests.

Cancellation can still leave charges for completed requests. Duplicate submissions caused by transport retries or interrupted durable steps can create additional bills. Actual savings and total costs were not measured.

Licensing and data terms

The supplied page does not state a license for its documentation, examples or the Pydantic AI library. Reuse and redistribution permissions are therefore unknown from this evidence. Provider contract terms and rights governing submitted data or generated outputs are also not established.

The page says OpenAI stores batched responses by default and documents openai_store=False to opt out of stored responses. That setting alone does not establish broader privacy, training-use or data-residency terms.

Freshness

The page was captured on 23 November 2026 at 12:05:54 UTC. It does not identify a library release, minimum compatible version or publication date. Provider compatibility, available models, prices and retention policies may change; applicability beyond the captured documentation is unknown.

Before adoption

Confirm that the installed Pydantic AI release exposes the documented interfaces and that the intended provider endpoint and model support batching. Obtain current rates, count and size limits, retention terms and applicable licenses before committing a workload.

Choose the agent capability, direct helper or low-level API according to how much lifecycle management the application needs. For deferred collection, persist histories and any dynamically selected model name, then schedule collection before results expire.

Evaluate a small representative workload for elapsed time, billed cost, output validity and failure handling. Include cancellation and process-restart cases, and inspect custom HTTP retries for duplicate-submission risks before increasing volume.

Evidence for this report

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