feat: Add Batch Processing API with OpenAI, Anthropic & Google support

Draft
SA
8mo ago
+8342-11

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 threshold
  • should_submit - custom callback for submit logic
  • submit() - 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

ProviderStatusNotes
OpenAI✅ Supported50% discount, 24-hour processing window
Anthropic✅ Supported50% discount, 24-hour expiration
Google✅ SupportedBatch prediction API

Provider Differences

CapabilityOpenAIAnthropicGoogle
Different model per request❌✅❌
Different tools per request✅✅✅
Different temperature per request✅✅✅

Architecture

This PR includes shared utilities for extensibility:

  • BatchCapable protocol - Type-safe interface for batch-capable models
  • supports_batch() function - Runtime check for batch support
  • _batch_utils.py module - Shared utilities:
    • extract_batch_error - Handles error extraction from various provider formats
    • parse_batch_datetime - Handles Unix timestamps, ISO strings, datetime objects
    • BatchResultBuilder - Tracks processed IDs to prevent duplicates
  • Implementer guide - docs/adding-batch-support.md for adding new providers

Changes

New Files

  • docs/batch-processing.md - Dedicated documentation page
  • docs/adding-batch-support.md - Guide for implementing batch support in new providers
  • pydantic_ai_slim/pydantic_ai/models/_batch_utils.py - Shared batch utilities
  • pydantic_ai_slim/pydantic_ai/models/batch.py - BatchModel for agent integration
  • tests/models/test_batch_utils.py - Utility tests (37 tests)
  • tests/models/test_openai_batch.py - OpenAI batch tests
  • tests/models/test_anthropic_batch.py - Anthropic batch tests
  • tests/models/test_google_batch.py - Google batch tests
  • tests/models/test_batch_model.py - BatchModel tests

Modified Files

  • pydantic_ai_slim/pydantic_ai/__init__.py - Export BatchCapable, supports_batch
  • pydantic_ai_slim/pydantic_ai/models/__init__.py - Batch abstractions, BatchCapable protocol
  • pydantic_ai_slim/pydantic_ai/models/openai.py - OpenAI batch implementation
  • pydantic_ai_slim/pydantic_ai/models/anthropic.py - Anthropic batch implementation
  • pydantic_ai_slim/pydantic_ai/models/google.py - Google batch implementation
  • pydantic_ai_slim/pydantic_ai/models/wrapper.py - Batch method forwarding
  • pydantic_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