Add provider batch API support with a `BatchModelRequests` capability and a `get_wrapper_model` capability hook
- Closes #1771
Anthropic, OpenAI and Gemini offer batch APIs at about half price, which suit evals, extraction and other offline agent runs, but Pydantic AI can't use them today. This adds a BatchModelRequests capability that sends an agent's model requests through the provider's batch API, built on a new generic get_wrapper_model hook, plus the lower-level model_request_batch and batch_* model methods. It supersedes #10187 (closed), whose batch machinery it builds on.
BatchModelRequests wraps whichever model serves each request, so it also batches a run's model=, a SelectModel choice or a hook's swap, and can be added per run with capabilities=. One instance is one pool: the concurrent runs it serves share batches. It lives in core because it needs the new hook and model-level batch support. Under Temporal, DBOS and Prefect it goes on the agent next to the durability capability.
New public surface
pydantic_ai.capabilities.BatchModelRequests(max_requests=1000,max_wait,max_resubmissions=2,poll_interval,max_poll_interval;flush(); async context manager)AbstractCapability.get_wrapper_model(model): wraps the model serving each request, after thebefore_model_requesthooks; first capability outermost, likeget_wrapper_toolset; the returned model is entered around each request it servespydantic_ai.direct.model_request_batch,PendingModelResponse, and thebatch_*methods (batch_max_requests,batch_max_bytes,batch_request_size,batch_encode,batch_create,batch_status,batch_results,batch_decode,batch_cancel) and types inpydantic_ai.models.batch
User-visible behavior
One agent over a list of items, in a script that waits for the results. Runs started together go into one batch:
import asyncio
from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_ai.capabilities import BatchModelRequests
class Extraction(BaseModel):
remote: bool
countries: list[str]
seniority: str
agent = Agent(
'google:gemini-3.8-flash',
output_type=Extraction,
instructions='Extract the remote-work details from this job posting.',
capabilities=[BatchModelRequests(max_requests=10_000)],
)
async def extract_all(postings: list[str]) -> list[Extraction | BaseException]:
results = await asyncio.gather(*(agent.run(posting) for posting in postings), return_exceptions=True)
return [result if isinstance(result, BaseException) else result.output for result in results]
Submit now, collect in a later process
Add PendingModelResponse to the output type, and a run ends once its request is submitted. Store its message history and run the agent with it later; each run checks its batch once.
from pydantic_ai import ModelMessagesTypeAdapter, PendingModelResponse
agent = Agent(
'google:gemini-3.8-flash',
output_type=[Extraction, PendingModelResponse],
instructions='Extract the remote-work details from this job posting.',
capabilities=[BatchModelRequests(max_requests=10_000)],
)
async def submit(postings: dict[str, str]) -> dict[str, bytes]:
results = await asyncio.gather(*(agent.run(posting) for posting in postings.values()))
return {key: result.all_messages_json() for key, result in zip(postings, results)}
async def collect(stored: dict[str, bytes]) -> tuple[dict[str, Extraction], dict[str, bytes]]:
done: dict[str, Extraction] = {}
pending: dict[str, bytes] = {}
for key, messages in stored.items():
result = await agent.run(message_history=ModelMessagesTypeAdapter.validate_json(messages))
if isinstance(result.output, PendingModelResponse):
pending[key] = result.all_messages_json() # not done yet: store again
else:
done[key] = result.output
return done, pending
Durable execution (Temporal)
Each posting is its own workflow. Their requests share batches on the worker, and the waits between batch checks are durable timers, so no worker is tied up while a batch runs and a restart picks up the same batch.
from temporalio import workflow
from pydantic_ai.durable_exec.temporal import PydanticAIWorkflow, TemporalDurability
agent = Agent(
'google:gemini-3.8-flash',
name='extractor',
output_type=Extraction,
instructions='Extract the remote-work details from this job posting.',
capabilities=[BatchModelRequests(max_requests=10_000), TemporalDurability()],
)
@workflow.defn
class ExtractPosting(PydanticAIWorkflow):
__pydantic_ai_agents__ = [agent]
@workflow.run
async def run(self, posting: str) -> Extraction:
result = await agent.run(posting)
return result.output
One pool shared by several agents
batching = BatchModelRequests()
writer = Agent('anthropic:claude-sonnet-5-5', capabilities=[batching])
reviewer = Agent('anthropic:claude-sonnet-5-5', capabilities=[batching]) # shares writer's batches
other = Agent('openai:gpt-6.1-sol')
await other.run(prompt, capabilities=[batching]) # batched for this run only
Verification
- Capability, pooling, grouping, cancellation, tracing:
test_batch.py,test_batch_runs.py(resubmission, size splits, 1,050 concurrent runs, tool loops, validation retries,UsageLimits, threads) - Submit in one process, collect in another, including with a rotated key and after retention:
test_batch_resume.py - Providers, recorded and mocked (every result type and job state, error categories, beta grouping, refusals,
pause_turn, cache and thinking usage at batch prices):tests/models/test_{openai,anthropic,google}_batch{,_vcr}.py - Stress-tested in-process (cancellation and timeouts mid-wait, 5,000 concurrent runs, mixed workloads, interleaved resumes, tampered histories, every error category) and live against all three batch APIs: 20 concurrent structured-output runs in one batch, submit and collect in separate processes, and two-round tool and output-retry runs sharing batches, all valid at half price.
- Durable: Temporal
test_durability.py(-k batch: shared batches across workflows, replay, retried submission), DBOS and Prefect-k batchintests/durable_exec/
What changes for existing users
Nothing for agents that don't add BatchModelRequests (or another capability using the new hook). The deprecated TemporalAgent, DBOSAgent and PrefectAgent refuse such capabilities with a UserError, since they send requests without them.
Traces
Traces for N parallel runs: each run's chat span (under Temporal, the model activity's span) records pydantic_ai.batch.id and links to the batch; the batch is one trace of its own instead of hanging under whichever run started it.
invoke_agent (run 1..N)
└─ chat <model> pydantic_ai.batch.id=…, link → batch
batch <model> (own trace) links → N chat spans; batch.id, request_count, status
├─ POST /batches
├─ batch check <model> status=in_progress
│ └─ GET /batches/…
└─ batch check <model> status=ended
└─ GET …/results
A run resumed from history (another process) finds the batch's trace context in the pending response, so its checks join the same trace.
Design notes
- Hook placement. Applied in the core right after the
before_model_requestchain, so it wraps the model that actually serves the attempt, including one a hook swapped in; with #9348's per-attemptprepare_model_requestit would apply per attempt in the same way. A privateModel._with_serving_wrapperletsDurableModeltake the wrapper inside itself: in the workflow the wrapper only answerscontinuation_delay(batch poll intervals become durable timers), and_durable_model_scopere-appliesroot_capability.get_wrapper_modelto the model rebuilt in the activity/step/task, which sends the request. The hook doesn't receive aRunContext(likeget_wrapper_toolset), and deferred capabilities don't contribute. - Runtime capabilities under durable execution. Temporal and DBOS keep rejecting
capabilities=inside a workflow; the worker's capabilities come from the agent, so a run-onlyBatchModelRequestswould be silently dropped. Prefect allows it, and it works there. - Naming. VerbNoun per the capability naming rule (it changes execution mechanics);
Batchis already the batch handle type. - Shared tasks' context. Submissions and checks still copy the starting request's context (Prefect task context etc.), but set its OpenTelemetry context aside.
- In-memory batches (
TestModel/FunctionModel) now use a group per instance, since one pool can see several instances. - Temporal and
for_run. In a Temporal activity the hook runs on the agent's own capabilities, not onesfor_runreturned (the same asresolve_model_idthere); documented on the hook. - Pool state is keyed by provider and group (queues) and provider, group and batch ID (checks, results, cancellation), since one instance can batch several providers.
- Cancelling shared batches. Only the pool that submitted a batch cancels it, once every request it recorded in that batch has been abandoned, and only once. A pending response resumed from a message history, which the caller may control, can't cancel a batch: its ticket can't be trusted to say which other requests share the batch, so the batch is left running.
- Batch groups and credentials. Requests only share a batch when they authenticate the same way. For Gemini that means the credential headers the client sends (
x-goog-api-key,authorization, includinghttp_options.headersoverrides), not the client'sapi_key. - Harness sub-agents. Adds
PendingModelResponseto the sub-agent outputs that #10497 treats likeDeferredToolRequests. A sub-agent run that ends pending has its provider request cancelled through the model that served it (best effort), so a shared batch is only cancelled once nobody else waits on it. - Wrappers inside batching. Batching sends requests through the
batch_*methods, so a model wrapper inside it (from a later capability) never has itsrequest()called; documented, withwrap_model_requestas the place for once-per-request behavior. - Continuation limits. A batch request waiting for its batch is a poll, not a generation continuation, even when it was resubmitted under a new ID, and it isn't capped by
MAX_BACKGROUND_POLLS: the provider's batch window andSuspendedResponseExpiredbound it. Other models' continuation limits are unchanged. - Streaming.
run_stream,run_stream_events,event_stream_handler,node.streamand UI adapters work: a batched request waits for its batch, then its response is replayed as stream events at once. - Pending responses and hooks. A pending batch request is left running for a later run only once the run ends with it, after
wrap_model_requestandafter_model_request; one a hook rejects (raising, replacing it, or dropping its ticket) is withdrawn throughcancel_suspended_response, which cancels the batch only when no other request this pool recorded still waits on it. Other models' suspended jobs are unaffected. - Wrapper lifecycle. A model returned from
get_wrapper_modelis entered around each request it serves (and in the durable unit), without entering or exiting the model it wraps, whose owner manages it; its exit is shielded from cancellation. - Failed requests. Requests a batch didn't run (expired, missing) and transient failures (rate limit, overload, server error) are resubmitted in a new batch up to
max_resubmissions=2, the provider SDKs' default retry count; the count travels in the ticket, so a resumed history resubmits instead of re-reading the error. Canceled requests raise: providers don't cancel on their own. Quota, context-window and other 4xx errors raise with the sameModelHTTPErrorcategories as unbatched requests. - Collecting with another key. Submitting needs one credential per batch (pooling isolation); checking, collecting and cancelling an existing batch work with any credential the provider accepts, and caches and shared checks are keyed by the collecting credential so the provider always decides access. Clients whose credential can't be told apart (API-key callbacks, workload identity, HTTP client
auth) are refused. - Limits and cleanup. Batches split by request count and by size (
batch_max_bytes: OpenAI 200 MB, Anthropic 256 MB, Gemini 2 GB). Input files this process uploaded are deleted once the provider reports the batch ended; files named by a stored history are never deleted. - OpenAI stored responses. Live probes confirmed
previous_response_id,store, hosted tools and encrypted reasoning work in batch lines;streamandbackgroundfail the whole batch, so they're refused at encode time. - Fallback. Left out on purpose:
FallbackModelwon't support batching, and composing with #9348'sModelFallbackneeds the wrapper per attempt and a failed continuation to move on to the next model (noted on #9348).
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
- PR title is fit for the release changelog.
🤖 Generated with Claude Code