Batch API¶
The Batch API sends requests in bulk at 50% cost compared to realtime API calls. Use it for large enrichment jobs where latency is not critical.
Supported providers: OpenAI and Anthropic. Google is not yet supported.
Minimal example¶
from accrue import Pipeline, LLMStep
pipeline = Pipeline([
LLMStep("analyze",
fields={"market_size": "Estimate TAM"},
batch=True,
),
])
result = pipeline.run(data)
Or use the for_batch() config preset, which also enables caching and checkpointing:
from accrue import EnrichmentConfig
config = EnrichmentConfig.for_batch()
result = pipeline.run(data, config=config)
How it works¶
- Cache check -- only uncached rows are sent to the batch job.
- Build request payload --
build_messages()is called for each uncached row. - Auto-chunk -- if the batch exceeds
batch_max_requests(default 50,000) orbatch_max_bytes(default: the provider's per-batch cap), it is split into multiple submissions. A row whose request alone exceeds the per-request or per-batch cap fails on its own and is not submitted -- see attachments limits. - Submit batch job -- the provider's batch API receives the payload.
- Poll until complete -- status is checked every
batch_poll_intervalseconds. - Parse results and cache -- responses are parsed with
parse_response()and cached for future runs. - Realtime fallback -- any rows that fail in the batch are automatically retried via the realtime API. A batch answer that was billed but could not be used (cut off, or the wrong shape) is counted in
result.costas well as the realtime calls that replaced it.
Configuration¶
from accrue import EnrichmentConfig
config = EnrichmentConfig(
batch_poll_interval=60.0, # Seconds between status checks (default: 60)
batch_timeout=86400.0, # Max wait time in seconds (default: 24h)
batch_max_requests=50000, # Auto-chunk threshold (default: 50,000)
batch_max_bytes=None, # Byte threshold (default: provider cap)
)
All three values must be positive. The defaults work well for most workloads.
Custom batch-capable providers¶
Accrue exposes the batch protocol types from the top-level package so custom provider adapters can integrate with the same execution path as the built-in OpenAI and Anthropic adapters:
BatchRequestrepresents one row request in a batch submission. It carries the rowcustom_id, chatmessages, model settings, optional structured output format, tool definitions, andprovider_kwargs.BatchResultis returned after polling finishes. It maps each successfulcustom_idto anLLMResponse, records failed request IDs, and keeps the provider batch ID for debugging or dashboard lookup.BatchCapableLLMClientextends the regularLLMClientprotocol withsubmit_batch(),poll_batch(), andcancel_batch(). A custom client that implements these methods can runLLMStep(batch=True)through the batch path; otherwise Accrue falls back to realtime calls.is_batch_capable(client)is the check Accrue actually uses. It combines theisinstancetest with an optionalsupports_batchproperty, so an adapter whose batch support depends on how it was built can opt out at runtime:
Clients that omit supports_batch are treated as capable, so existing custom
adapters need no changes.
Monitoring batch runs¶
from accrue import EnrichmentConfig
result = pipeline.run(data, config=EnrichmentConfig.for_batch())
usage = result.cost.steps["analyze"]
print(usage.execution_mode) # "batch"
print(usage.batch_id) # "batch_abc123" (the first batch)
print(usage.batch_ids) # Every batch, more than one if auto-chunked
print(usage.cache_hits) # Rows served from cache
print(usage.cache_misses) # Rows sent to batch
print(usage.cache_hit_rate) # Float between 0.0 and 1.0
Using with Anthropic¶
from accrue import Pipeline, LLMStep
pipeline = Pipeline([
LLMStep("analyze",
fields={"market_size": "Estimate TAM"},
model="claude-sonnet-5-5",
batch=True,
),
])
The Anthropic provider is auto-detected from the claude- model prefix. Requires pip install "accrue[anthropic]".
The Anthropic adapter uses the Message Batches API. System messages automatically get cache_control annotations for prompt caching savings.
Constraints and gotchas¶
- Incompatible with
grounding. Accrue's batch path sends no tools, so setting bothbatch=Trueandgrounding=Trueraises aPipelineErrorat construction time. Search in aweb_search()step first, then batch the analysis. - Client must be batch-capable. The built-in OpenAI and Anthropic adapters are. Clients that only implement
LLMClientfall back to realtime execution with a logged warning. base_urldisables batch. OpenAI-compatible gateways (OpenRouter, Groq, Together, vLLM, Ollama) implement chat completions but not the batch endpoints, soOpenAIClientwith abase_urlset reports itself as not batch-capable. A step combiningbatch=Truewithbase_urlruns in realtime at standard pricing and warns; callingsubmit_batch()on such a client directly raises aStepError.- Long-running. Batches can take minutes to hours depending on provider load and batch size. The
batch_timeoutconfig (default 24 hours) controls the maximum wait. - Enable caching. Without caching, re-running a pipeline resubmits all rows. The
for_batch()preset enables caching by default. - Enable checkpointing. If the process crashes mid-poll, checkpointing lets you resume without resubmitting completed steps. The
for_batch()preset enables this too. - Tokens are not split by price. A step's usage adds its batch attempts and its realtime fallbacks together under
execution_mode="batch", and the two are priced differently. If rows fell back, pricing it all at the batch rate is too low. - OpenAI settings work in either spelling. Batch uses Chat Completions and realtime uses Responses.
reasoning_effort/reasoning.effort,verbosity/text.verbosity,response_format/text.formatand the token limits (max_tokens,max_completion_tokens,max_output_tokens) are converted to what each route takes. Two different values for one setting raise an error before anything is sent. This covers top-level keys, notextra_body. Settings only one route has, such asseedorreasoning.summary, are passed on as they are and fail on the other. provider_kwargsare part of the cache key. Changingprovider_kwargsbetween runs re-runs (and resubmits) the step.