Skip to content

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

  1. Cache check -- only uncached rows are sent to the batch job.
  2. Build request payload -- build_messages() is called for each uncached row.
  3. Auto-chunk -- if the batch exceeds batch_max_requests (default 50,000) or batch_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.
  4. Submit batch job -- the provider's batch API receives the payload.
  5. Poll until complete -- status is checked every batch_poll_interval seconds.
  6. Parse results and cache -- responses are parsed with parse_response() and cached for future runs.
  7. 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.cost as 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:

from accrue import BatchCapableLLMClient, BatchRequest, BatchResult
  • BatchRequest represents one row request in a batch submission. It carries the row custom_id, chat messages, model settings, optional structured output format, tool definitions, and provider_kwargs.
  • BatchResult is returned after polling finishes. It maps each successful custom_id to an LLMResponse, records failed request IDs, and keeps the provider batch ID for debugging or dashboard lookup.
  • BatchCapableLLMClient extends the regular LLMClient protocol with submit_batch(), poll_batch(), and cancel_batch(). A custom client that implements these methods can run LLMStep(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 the isinstance test with an optional supports_batch property, so an adapter whose batch support depends on how it was built can opt out at runtime:
class MyClient:
    @property
    def supports_batch(self) -> bool:
        return self._endpoint_has_batch_api

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 both batch=True and grounding=True raises a PipelineError at construction time. Search in a web_search() step first, then batch the analysis.
  • Client must be batch-capable. The built-in OpenAI and Anthropic adapters are. Clients that only implement LLMClient fall back to realtime execution with a logged warning.
  • base_url disables batch. OpenAI-compatible gateways (OpenRouter, Groq, Together, vLLM, Ollama) implement chat completions but not the batch endpoints, so OpenAIClient with a base_url set reports itself as not batch-capable. A step combining batch=True with base_url runs in realtime at standard pricing and warns; calling submit_batch() on such a client directly raises a StepError.
  • Long-running. Batches can take minutes to hours depending on provider load and batch size. The batch_timeout config (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.format and 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, not extra_body. Settings only one route has, such as seed or reasoning.summary, are passed on as they are and fail on the other.
  • provider_kwargs are part of the cache key. Changing provider_kwargs between runs re-runs (and resubmits) the step.