feat: Add Batch Processing API with OpenAI, Anthropic & Google support
Draft
SA
8mo ago+8342+8342+0123456789012345678901234567890123456789-11-11-01234567890123456789
Summary
Add batch processing support to pydantic-ai for OpenAI, Anthropic, and Google providers. This enables users to submit multiple LLM requests as a single job for asynchronous processing, achieving 50% cost savings on API calls.
Partially addresses #1771 - implements core batch infrastructure, BatchModel wrapper, and shared utilities.
Key Features
High-Level API (Recommended)
from pydantic_ai import ModelRequest
from pydantic_ai.direct import model_request_batch
results = await model_request_batch(
'openai:gpt-4o-mini',
[
('q1', [ModelRequest.user_text_prompt('What is 2+2?')]),
('q2', [ModelRequest.user_text_prompt('What is 3+3?')]),
],
poll_interval=60.0, # Auto-polls until complete
)
for result in results:
if result.is_successful:
print(f'{result.custom_id}: {result.response.parts[0].content}')
BatchModel for Agent Integration
from pydantic_ai import Agent
from pydantic_ai.models.batch import BatchModel
async with BatchModel('openai:gpt-4o-mini', batch_size=100) as batch_model:
agent = Agent(model=batch_model)
tasks = [agent.run(prompt) for prompt in prompts]
await batch_model.submit() # Or auto-submits at batch_size
results = await asyncio.gather(*tasks)
BatchModel features:
batch_size- auto-submit thresholdshould_submit- custom callback for submit logicsubmit()- manual submission- Context manager support
Check Batch Capability
from pydantic_ai.models import supports_batch
from pydantic_ai.models.openai import OpenAIChatModel
model = OpenAIChatModel('gpt-4o-mini')
if supports_batch(model):
batch = await model.batch_create(requests)
Low-Level API (Advanced)
For custom polling logic or long-running jobs:
from pydantic_ai.direct import batch_create, batch_status, batch_results
batch = await batch_create('openai:gpt-4o-mini', requests)
# ... store batch.id, resume later ...
batch = await batch_status('openai:gpt-4o-mini', batch)
results = await batch_results('openai:gpt-4o-mini', batch)
Provider Support
| Provider | Status | Notes |
|---|---|---|
| OpenAI | ✅ Supported | 50% discount, 24-hour processing window |
| Anthropic | ✅ Supported | 50% discount, 24-hour expiration |
| ✅ Supported | Batch prediction API |
Provider Differences
| Capability | OpenAI | Anthropic | |
|---|---|---|---|
| Different model per request | ❌ | ✅ | ❌ |
| Different tools per request | ✅ | ✅ | ✅ |
| Different temperature per request | ✅ | ✅ | ✅ |
Architecture
This PR includes shared utilities for extensibility:
BatchCapableprotocol - Type-safe interface for batch-capable modelssupports_batch()function - Runtime check for batch support_batch_utils.pymodule - Shared utilities:extract_batch_error- Handles error extraction from various provider formatsparse_batch_datetime- Handles Unix timestamps, ISO strings, datetime objectsBatchResultBuilder- Tracks processed IDs to prevent duplicates
- Implementer guide -
docs/adding-batch-support.mdfor adding new providers
Changes
New Files
docs/batch-processing.md- Dedicated documentation pagedocs/adding-batch-support.md- Guide for implementing batch support in new providerspydantic_ai_slim/pydantic_ai/models/_batch_utils.py- Shared batch utilitiespydantic_ai_slim/pydantic_ai/models/batch.py- BatchModel for agent integrationtests/models/test_batch_utils.py- Utility tests (37 tests)tests/models/test_openai_batch.py- OpenAI batch teststests/models/test_anthropic_batch.py- Anthropic batch teststests/models/test_google_batch.py- Google batch teststests/models/test_batch_model.py- BatchModel tests
Modified Files
pydantic_ai_slim/pydantic_ai/__init__.py- Export BatchCapable, supports_batchpydantic_ai_slim/pydantic_ai/models/__init__.py- Batch abstractions, BatchCapable protocolpydantic_ai_slim/pydantic_ai/models/openai.py- OpenAI batch implementationpydantic_ai_slim/pydantic_ai/models/anthropic.py- Anthropic batch implementationpydantic_ai_slim/pydantic_ai/models/google.py- Google batch implementationpydantic_ai_slim/pydantic_ai/models/wrapper.py- Batch method forwardingpydantic_ai_slim/pydantic_ai/direct.py- High-level and low-level batch functions
Future Roadmap
Items not yet implemented (potential follow-up PRs):
- Cost tracking/limits - Per-batch and per-request cost estimation
- Dry-run mode - Preview costs before submitting
- State persistence - Resume interrupted batches from stored batch IDs
- Progress callbacks - Real-time status updates during polling
Test Plan
- 153 tests covering all batch functionality
- Unit tests for Batch/BatchStatus/BatchResult/BatchError
- Shared utilities tests (37 tests)
- OpenAI batch implementation with mock client
- Anthropic batch implementation with mock client
- Google batch implementation with mock client
- BatchModel wrapper tests
- Direct API functions (async and sync variants)
- Wrapper model forwarding (InstrumentedModel, WrapperModel)
- Error handling (API errors, validation errors, timeout)
- Documentation examples tested via pytest-examples
🤖 Generated with Claude Code