03.9 Async, Concurrency and Batch Processing

Understand LLMsLesson 9 of 1334,495 words14 parts
Module 03 · 0 of 13 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13

One LLM call takes seconds, and most of those seconds are spent waiting. So the moment you have more than a handful of calls to make (classify 20,000 support tickets, summarize a folder of contracts, run an evaluation set, embed a knowledge base), the way you schedule the calls matters more than the calls themselves. This lesson teaches the three tools for that job and when to use each: async concurrency (many calls in flight at once, with a limit), cheaper slower tiers such as OpenAI's flex processing, and the Batch APIs (submit a file of requests, collect the results later, pay about half). You'll learn each one for OpenAI, Anthropic, Gemini and OpenRouter, in code you can run: bounded concurrency that keeps every success when some calls fail, a rate-aware version that reacts to 429s, the complete batch lifecycle on each provider (build the file, submit, poll, download, match results to inputs, retry only what failed), a resumable job that survives a crash, background mode and webhooks for single long tasks, and a calculator that compares the options for a worked example.

What you'll learn

  • Why LLM work is I/O-bound, what concurrency buys (throughput) and what it doesn't (the latency of one call), and a decision table: async, flex, Batch API or background mode
  • The async clients of all four providers (AsyncOpenAI, AsyncAnthropic, genai.Client().aio, and OpenRouter through AsyncOpenAI), how to open and close them, the optional aiohttp backends, and the notebook trap
  • Bounded concurrency with asyncio.Semaphore; asyncio.gather(return_exceptions=True) versus asyncio.TaskGroup (what each does to the other calls when one fails); keeping partial results; progress reporting; and how your semaphore interacts with the HTTP connection pool
  • Per-provider concurrency budgets, threads for codebases that aren't async, and a worker pool for inputs too big to hold in memory
  • Rate-aware throughput: a semaphore plus the token-bucket limiter from 03.8, adaptation to 429s, how it fits with 03.8's areliable_call(), and a deadline for a whole job
  • The Batch APIs end to end for OpenAI, Anthropic and Gemini (and what OpenRouter offers instead): input formats, limits, statuses, results, expiry, and the traps (results in any order, files that expire, errors that arrive late)
  • How to design a batch job that doesn't hurt: deterministic IDs, a local checkpoint, validating every result (with a schema, if you can), splitting under the limits and under a queue cap, estimating cost before you submit, reporting what the job cost, resuming after a crash, and resubmitting only the failures
  • Flex and priority (fast) tiers as a throughput choice, and how to read the tier that actually served a request
  • Background mode (OpenAI Responses, Gemini Interactions), polling done right, and webhooks, including a FastAPI receiver that verifies signatures and refuses everything when its secret is missing
  • A worked example (20,000 tickets, three ways) with a calculator for wall time, cost and failure handling

What you don't need

  • Any API key. Everything that talks to a provider is run against mock servers that return each provider's documented shapes, or against the free local stand-in from lesson 03.1. Gemini has no local stand-in at all (Ollama doesn't speak Gemini's API: 03.1, 12.4), so every google-genai sample is hosted-only. The Batch APIs, background polling and service-tier results can't run on the local stand-in either, so those samples are marked as provider samples with illustrative output, and each of them also has a mocked run that shows the real SDK doing the real work.
  • Async/await knowledge beyond the basics. Module 01B owns async Python; Part 2 gives you a short refresher and then applies it to LLM clients.
  • Queue systems, workers or schedulers. Orchestrating jobs at scale (Celery, SQS, Temporal, Airflow) belongs to Module 11C. This lesson is about getting one job right in one process, with the state saved so a second process can pick it up.

Setup

The samples need Python 3.11 or later (asyncio.TaskGroup, asyncio.timeout and except* arrived in 3.11) and the three official SDKs. The samples were written and checked against openai 3.42.1, anthropic 2.4.0 and google-genai 2.34.0 as of November 2026; the commands below install the newest releases, so a newer major version may change names or defaults (check the SDK's changelog if a sample does not match). Lessons 03.1 to 03.9 share one project folder, llm-apis (03.1's project setup); if you have it, add the two web libraries used by the local mock server and the webhook receiver, plus pydantic (the structured-output example) and pyyaml (03.7's price table, which prices the batch results):

bash
uv add openai anthropic google-genai python-dotenv fastapi uvicorn pydantic pyyaml httpx
# or: pip install openai anthropic google-genai python-dotenv fastapi uvicorn pydantic pyyaml httpx

First time? Run uv init llm-apis --bare --python 3.13 && cd llm-apis first, then the uv add line, then run each sample with uv run python file.py. Two optional extras are used in 2.4: uv add "openai[aiohttp]" "anthropic[aiohttp]" "google-genai[aiohttp]".

The provider samples read keys from a .env file (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY), as set up in 03.1. Samples that are marked "mock" need no .env at all.

Several samples import small modules built in this lesson. Keep them in one folder: tickets.py (6.6), poller.py (6.4), mock_llm.py (3.1), bounded.py (4.4), local_http_mock.py (4.6), openai_batch_io.py (7.1), mock_openai_batch.py (7.5), anthropic_batch_io.py (8.1), mock_anthropic_batch.py (8.4), gemini_batch_io.py (9.1), mock_gemini_batch.py (9.4), structured.py (11.3b), chunking.py (11.4), job_calc.py (11.5), batch_cost.py (7.1), batch_runner.py (11.6), mock_background.py (13.4) and webhook_receiver.py (13.7). Modules from earlier lessons are copied, not rebuilt: from 03.8, rate_limiter.py (9.5), llm_errors.py with retry_after.py (4.4, 7.3), check_response.py (10.2) and production_call.py with areliable_call() (13.4); from 03.7, cost_calc.py (3.6) with prices.py and prices.yaml (4.2). Copy the current versions: this lesson depends on their names and signatures, not on a particular copy. Each module of this lesson is given in full where it is introduced.

Names that look alike but are different things. Several samples sit in one folder next to the copied 03.8 and 03.7 modules, so a few names are chosen not to collide: bounded.ItemResult (one item's value or error) is not check_response.Outcome (03.8's verdict on one response); the ticket coroutines in the samples are called classify_ticket, while classify() always means llm_errors.classify (03.8's error classifier). If you edit a sample, keep the imports as written.


What you must be able to do after this lesson#

  • Run LLM calls concurrently with async clients
  • Bound concurrency with a semaphore
  • Submit and collect a batch job
  • Design a batch job that survives failures
  • Choose between sync, async and batch for a workload

Why this matters for an AI engineer#

The first version of every AI feature calls the model once per request and works fine. The second version has to process a backlog, and the naive for loop takes eight hours and a first 429 crashes it at item 11,000. The engineers who ship bulk LLM work know which tool fits, and they write jobs that can be killed and restarted.

You'll hear... You'll understand it after...
"Just asyncio.gather all of them." Part 4: Bounded concurrency
"My notebook says asyncio.run() cannot be called from a running event loop." 2.5 Notebooks
"Our async endpoint is slow, even though we use async def." 2.6 A sync call inside async code
"gather lost the results when one request failed." 4.3 gather or TaskGroup
"We ran out of sockets / got a 429 storm." 4.1, 4.6 The connection pool
"Use a token bucket and a semaphore." Part 5: Rate-aware throughput
"Use the Batch API, it's half price." Part 6, then OpenAI, Anthropic, Gemini
"Batch results came back in a different order." 6.3 custom_id
"Does OpenRouter have a batch API?" Part 10
"Our batch job died halfway. Do we pay twice?" 11.6 Resumable jobs
"Use flex for the overnight job." Part 12: Flex and priority tiers
"Run it in background mode and wait for the webhook." Part 13
"Is it cheaper to batch, or to run flex with a hundred workers?" Part 14: Choosing

Part 1: Why concurrency matters for LLM work#

1.1 A call is mostly waiting#

Think about what your program does during one LLM call. It builds a small JSON body (microseconds), sends it over the network (milliseconds), and then waits: the provider queues the request, reads your prompt, and generates tokens one at a time. A short classification takes about a second; a long answer or a reasoning model takes tens of seconds (Module 02.5 measured this). While it waits, your CPU does nothing. Work like this is called I/O-bound: the time is spent waiting for something outside your program.

The arithmetic is unforgiving. Classifying 20,000 tickets at 1.5 seconds each, one after another, takes 20,000 × 1.5 s = 30,000 s, about 8 hours and 20 minutes. Twenty requests in flight at the same time do the same work in about 25 minutes, with the same code per request and the same bill.

1.2 Throughput, latency and cost#

Three numbers describe any LLM workload, and each tool in this lesson moves a different one:

Dial Meaning Unit
Latency How long one call takes, from sending to receiving the last token seconds per call
Throughput How many calls (or tokens) you finish per unit of time, across all calls calls or tokens per minute
Cost What you pay for the same work dollars per million tokens

Concurrency raises throughput and leaves the latency of each individual call exactly where it was (20 parallel calls don't make any one call faster; they make the whole pile finish sooner). A faster tier such as fast mode lowers latency and raises the price. A slower tier such as flex or a Batch API lowers the price and raises latency, sometimes enormously. So the real question for a job is rarely "how do I make it fast?" It is "what is the cheapest way to finish by the time somebody needs the result?"

1.3 The tools, and when to use each#

Situation Tool Why Where
A user or a live process is waiting (a chat reply, an API endpoint, an agent step) Async + bounded concurrency, usually with streaming Lowest latency; you pay the standard price Parts 2 to 5, 03.3
A bulk job whose results are needed soon (minutes to a few hours) Flex tier + async, falling back to standard when flex is busy About half price, still synchronous, so you control the pace Part 12
A bulk job with no urgency (nightly classification, evaluation runs, backfills, embeddings) A Batch API About half price, its own and larger rate-limit pool, nothing for you to keep running Parts 6 to 11
One very long task (deep research, a huge generation) that must outlive an HTTP connection Background mode with polling or a webhook The connection can drop and the job continues Part 13
Many small items that each need a fraction of a call Pack several items into one request Fewer requests and a shared instruction prefix, at some risk to accuracy 1.4
flowchart TD
    start(["A pile of LLM requests"]) --> q1{"Is a person or a<br/>live process waiting?"}
    q1 -- "Yes, seconds matter" --> a1["Async + bounded concurrency<br/>(Parts 3 to 5)"]
    q1 -- "No" --> q2{"Can it wait<br/>up to 24 hours?"}
    q2 -- "Yes" --> b1["Batch API<br/>(Parts 6 to 11)"]
    q2 -- "No, needed within<br/>minutes to hours" --> f1["Flex tier + async<br/>(Part 12)"]
    start --> q3{"One huge single task<br/>that outlives an HTTP connection?"}
    q3 -- "Yes" --> bg["Background mode + webhook or polling<br/>(Part 13)"]
    a1 --> rl["Add a rate limiter and a deadline"]
    f1 --> rl

These tools combine. A 20,000-ticket backfill might be a Batch API job, with the 40 tickets that failed re-run through async + flex the next morning. A user-facing endpoint is async, rate-limited, and has a flex-tier overnight sibling for its analytics. The worked example in Part 14 puts numbers on the choice.

1.4 Three things that are also called "batching"#

The word is overloaded, and mixing the meanings up causes confusing conversations:

Meaning What it is Who does it Covered in
Server-side batching (continuous batching) The provider's GPUs process many users' requests together in one forward pass. It explains why speed varies with load and why batch discounts exist. You never see it. The provider 02.5, 11.2
Batch APIs A job interface: you submit many complete requests, the provider runs them whenever it has spare capacity (within a window, normally 24 hours), and you collect the results. About half price. The provider schedules; you build and collect This lesson, Parts 6 to 11
Request packing You put several items into one request ("classify these 20 tickets and return a JSON array") or send an array to an endpoint that accepts one, such as an embeddings endpoint. You Below

Request packing is a legitimate fourth lever, and it stacks with the others. It amortizes the instruction tokens (a 300-token instruction sent once for 20 tickets instead of 20 times), cuts the number of requests (which helps a requests-per-minute limit), and works with every provider. The costs: one malformed answer ruins 20 items; the model can drift or mix up items late in a long list; output is longer, so each call is slower; and you need custom_id-style discipline inside the JSON so you can tell which answer belongs to which ticket. Try it only after you've measured accuracy on your own data (Module 10A covers how), and keep packs small (5 to 20 items). Prompt caching (03.7) often gives the instruction-sharing benefit without the accuracy risk.

1.5 What each provider offers#

As of November 2026, in the order used throughout Module 03:

OpenAI Anthropic
Async client AsyncOpenAI AsyncAnthropic
Batch API Yes: Files API + batches.create, 50% off (Part 7) Yes: messages.batches, 50% off (Part 8)
Flex (cheaper, slower, synchronous) service_tier="flex" No
Faster, dearer tier service_tier="fast" (alias priority) speed="fast" on Claude Fable 5.2 and Opus 5.5; the older Priority Tier is no longer sold
Background mode background=True on Responses None on the Messages API
Webhooks batch.*, response.* events None for Message Batches. Managed Agents webhooks exist (beta, not for batches); organization webhooks are an admin beta that doesn't send events yet (13.6)
Gemini OpenRouter
Async client genai.Client().aio AsyncOpenAI(base_url=...)
Batch API Yes: client.batches, 50% off, generateContent only (Part 9) Yes, its own /api/v1/batches (not OpenAI's format), typically 50% off (Part 10)
Flex (cheaper, slower, synchronous) service_tier flex (preview) service_tier: "flex" or the :floor variant
Faster, dearer tier service_tier priority (preview) service_tier: "priority" / "fast" or the :nitro variant
Background mode background=True on Interactions Not documented
Webhooks batch.*, interaction.* events (preview) batch.* events through callback_url

Sources and the details behind each cell are in the part that owns it. Prices and discounts live in 02.9, 6.5 and are applied in code in 03.7; this lesson only uses them.


Part 2: Async clients#

2.1 A 60-second async refresher#

Module 01B teaches async Python properly. What you need here:

  • async def defines a coroutine function. Calling it doesn't run it; it returns a coroutine object, a paused piece of work.
  • await something means "pause me here, let other tasks run, and wake me when something is done". Only code inside an async def can await.
  • The event loop is the scheduler that runs the paused pieces. asyncio.run(main()) starts a loop, runs main() to the end, and closes the loop. Call it once, at the top of your program.
  • A task is a coroutine that the loop is running on its own schedule (asyncio.create_task(...), or tg.create_task(...) inside a TaskGroup). While one task waits on the network, the loop runs the others, so hundreds of tasks can wait at the same time on one thread.
  • Nothing runs in parallel on several cores here. It is cooperative: a task gives up control only at an await. That is perfect for waiting on the network and a trap for anything that blocks (2.6).

2.2 The four async clients#

Every SDK ships an async twin of its client. The methods have the same names and arguments; you await them:

Provider Sync client Async client Close it with
OpenAI OpenAI AsyncOpenAI async with AsyncOpenAI() as client: or await client.close()
Anthropic Anthropic AsyncAnthropic async with or await client.close()
Provider Sync client Async client Close it with
Gemini genai.Client client.aio (the same Client; async methods live under .aio) await client.aio.aclose(), plus client.close() for the sync side. async with client.aio: also works
OpenRouter OpenAI(base_url=...) AsyncOpenAI(base_url=...) as OpenAI

Here is one call to each provider, all four running at the same time with asyncio.gather:

python
"""s2_2_async_clients.py: the four async clients side by side, one call each, run concurrently.
Needs the four keys in .env (or, without a Gemini key, run its OpenAI, Anthropic and OpenRouter-shaped parts against the free local stand-in, lesson 03.1, 12.3)."""
import asyncio
import os

from anthropic import AsyncAnthropic
from dotenv import load_dotenv
from google import genai
from google.genai import types
from openai import AsyncOpenAI

load_dotenv()
PROMPT = "Reply with one word: what colour is a ripe banana?"


async def ask_openai(client: AsyncOpenAI) -> str:
    response = await client.responses.create(
        model="gpt-6-luna", input=PROMPT, reasoning={"effort": "none"}, max_output_tokens=32)
    return response.output_text


async def ask_anthropic(client: AsyncAnthropic) -> str:
    message = await client.messages.create(
        model="claude-haiku-5-5", max_tokens=256, messages=[{"role": "user", "content": PROMPT}])
    return "".join(block.text for block in message.content if block.type == "text")


async def ask_gemini(aclient: genai.Client) -> str:
    # the async methods live under client.aio and mirror the sync ones
    response = await aclient.aio.models.generate_content(
        model="gemini-3.8-flash", contents=PROMPT,
        config=types.GenerateContentConfig(max_output_tokens=256,
                                           thinking_config=types.ThinkingConfig(thinking_level=types.ThinkingLevel.LOW)))
    return response.text or ""


async def ask_openrouter(client: AsyncOpenAI) -> str:
    completion = await client.chat.completions.create(
        model="openai/gpt-6-luna", max_completion_tokens=64,
        messages=[{"role": "user", "content": PROMPT}])
    return completion.choices[0].message.content or ""


async def main() -> None:
    # `async with` closes each client's connection pool when the block ends (or on an exception)
    async with (
        AsyncOpenAI() as openai_client,
        AsyncAnthropic() as anthropic_client,
        AsyncOpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"],
                    default_headers={"HTTP-Referer": "https://example.com", "X-OpenRouter-Title": "Async demo"},
                    ) as openrouter_client,
    ):
        gemini_client = genai.Client()           # keep a reference: a throwaway client is garbage-collected
        try:
            answers = await asyncio.gather(      # four providers at the same time
                ask_openai(openai_client), ask_anthropic(anthropic_client),
                ask_gemini(gemini_client), ask_openrouter(openrouter_client))
        finally:
            await gemini_client.aio.aclose()     # the async side has its own close...
            gemini_client.close()                # ...and so does the sync side
    for name, answer in zip(("OpenAI", "Anthropic", "Gemini", "OpenRouter"), answers):
        print(f"{name:<11} {answer.strip()[:60]!r}")


asyncio.run(main())
Example output · illustrative4 lines
OpenAI      'Yellow'
Anthropic   'Yellow'
Gemini      'Yellow'
OpenRouter  'Yellow.'

The OpenAI, Anthropic and OpenRouter-shaped parts run against the free local stand-in (its replies differ from a hosted model's); the Gemini parts are hosted-only, because Gemini has no local stand-in. A few details worth noticing:

  • The shape of the code is identical to the sync version: only async def, await and the async client differ. Everything you learned in 03.1 and 03.8 (response objects, exception classes, max_retries, timeouts) applies unchanged. 03.1, 7.6 previewed this and 03.3, Part 10 covers async streaming.
  • Gemini keeps one Client. Its async methods are client.aio.models.generate_content(...), client.aio.interactions.create(...), client.aio.batches.create(...) and so on. Keep a reference to the client while you use it: a throwaway genai.Client().aio.... can be garbage-collected mid-call, and the request then fails with "Cannot send a request, as the client has been closed".
  • OpenRouter is AsyncOpenAI with a different base_url, plus its attribution headers (03.1, 6.6).
  • asyncio.gather over four providers is a pattern in itself: racing providers, or sending the same prompt to several models to compare them. 03.11 builds a wrapper that hides the four shapes.

2.3 One client per process, closed properly#

Each client owns an HTTP connection pool: a set of open, reusable connections to the provider. Creating the TLS connection costs a few round trips, so a pool that reuses connections is much faster than opening a new one per request. The rules (03.1, 7.5 owns the details):

  • Create the client once and share it between all your tasks. A client is safe to share between tasks in the same event loop.
  • Close it when you're done, to release the connections: async with AsyncOpenAI() as client: does it on the way out, even after an exception. In a web server, create it at start-up and close it at shutdown (in FastAPI, in the lifespan function), not inside the request handler.
  • Never create a client per task. It defeats pooling, opens a new TCP and TLS connection (the network connection and its encryption handshake) for every request, and under load can exhaust file descriptors. 4.6 measures it.
  • One event loop per client. An async client's pool belongs to the loop it was first used in. If you call asyncio.run() twice in one process, create a fresh client for each run.

2.4 Optional aiohttp backends#

By default, AsyncOpenAI and AsyncAnthropic send requests with httpx2 (their HTTP library since openai 3.0.0 and anthropic 2.0), and google-genai uses httpx. All three SDKs can use aiohttp instead, a different Python HTTP client built for async from the start. You install it with an extra and, for openai and anthropic, pass a client class:

bash
uv add "openai[aiohttp]" "anthropic[aiohttp]" "google-genai[aiohttp]"
SDK How to switch Notes
openai AsyncOpenAI(http_client=DefaultAioHttpClient()) DefaultAioHttpClient is exported by openai and keeps the SDK's default timeout, pool limits and redirect setting. Without the extra it raises "To use the aiohttp client you must have installed the package with the aiohttp extra"
anthropic AsyncAnthropic(http_client=DefaultAioHttpClient()) Same idea, exported by anthropic
SDK How to switch Notes
google-genai Nothing to do If aiohttp is installed, client.aio uses it automatically, unless you pass your own httpx_async_client or an async_client_args transport (HttpOptions(aiohttp_client=...) lets you pass a session of your own)

Why would you? Two reasons. aiohttp is lighter on CPU when thousands of requests are in flight, which matters for a gateway or a worker with high concurrency. And some teams already run aiohttp elsewhere (shared proxies, custom DNS and tracing). Why not? It is another dependency, httpx2-specific tools (such as httpx2.MockTransport, 03.10) don't work with it, and for ordinary jobs the difference is invisible, because the provider's latency dominates. Measure with 400 requests, 100 at a time, against a local mock server that takes 300 ms per request:

python
"""s2_4_aiohttp.py: the same async job on the default httpx2 transport and on the optional aiohttp one.
Needs: uv add "openai[aiohttp]"   (installs aiohttp and the adapter). MOCK server over real HTTP on
localhost (local_http_mock.py), 300 ms per request, 400 requests, 100 at a time."""
import asyncio
import time

from openai import AsyncOpenAI, DefaultAioHttpClient

import local_http_mock as mock

BASE_URL = mock.start()


async def run(label: str, make_client) -> None:
    mock.reset()
    semaphore = asyncio.Semaphore(100)
    async with make_client() as client:
        async def one(i: int) -> None:
            async with semaphore:
                await client.responses.create(model="gpt-6-luna", input=f"t{i}")
        start = time.perf_counter()
        cpu = time.process_time()
        await asyncio.gather(*(one(i) for i in range(400)))
    print(f"{label:<28} {time.perf_counter() - start:4.2f} s wall, {time.process_time() - cpu:4.2f} s CPU "
          f"(client and mock server share this process)")


async def main() -> None:
    await run("httpx2 (the default)", lambda: AsyncOpenAI(base_url=BASE_URL, api_key="sk-test"))
    await run("aiohttp (optional extra)", lambda: AsyncOpenAI(
        base_url=BASE_URL, api_key="sk-test", http_client=DefaultAioHttpClient()))

asyncio.run(main())
Output · a mock server on localhost, so only the client side differs2 lines
httpx2 (the default)         1.51 s wall, 0.56 s CPU (client and mock server share this process)
aiohttp (optional extra)     1.47 s wall, 0.35 s CPU (client and mock server share this process)

The wall time is the same, because both clients spend it waiting for the 300 ms answers (400 requests ÷ 100 at a time × 0.3 s ≈ 1.2 s, plus start-up). The CPU time differs: this process also runs the mock server, so the absolute numbers are inflated, but aiohttp used about a fifth to two fifths less CPU across three runs on the machine this was written on. Your numbers will differ; treat it as "slightly cheaper at high concurrency", not as a reason to switch.

The OpenAI and Anthropic SDKs against the local stand-in, to show the switch is real (Gemini has no local stand-in, so its form follows as a hosted-only sample):

python
"""s2_5_aiohttp_all.py: the aiohttp backend for the OpenAI and Anthropic SDKs, against the free local stand-in (layer 2).
Needs: uv add "openai[aiohttp]" "anthropic[aiohttp]"
Ollama on :11434 must be running (lesson 03.1, part 12)."""
import asyncio

import aiohttp
from anthropic import AsyncAnthropic
from anthropic import DefaultAioHttpClient as AnthropicAioHttpClient
from openai import AsyncOpenAI
from openai import DefaultAioHttpClient as OpenAIAioHttpClient


async def main() -> None:
    async with (
        AsyncOpenAI(base_url="http://localhost:11434/v1", api_key="ollama",
                    http_client=OpenAIAioHttpClient()) as openai_client,
        AsyncAnthropic(base_url="http://localhost:11434", api_key="ollama",
                       http_client=AnthropicAioHttpClient()) as anthropic_client,
    ):
        r = await openai_client.responses.create(model="gpt-6-luna", input="Say hi.", max_output_tokens=20)
        print("openai    ", type(openai_client._client).__name__, "->", r.output_text.strip()[:30])
        m = await anthropic_client.messages.create(model="claude-haiku-5-5", max_tokens=20,
                                                   messages=[{"role": "user", "content": "Say hi."}])
        print("anthropic ", type(anthropic_client._client).__name__, "->", m.content[0].text.strip()[:30])  # type: ignore[union-attr]
    print("aiohttp version", aiohttp.__version__)

asyncio.run(main())

Output (local model qwen2.5:0.5b via Ollama; the printed class names come from private attributes, used only for this demo):

text
openai     _InstalledAioHttpClient -> Hello! How can I help you toda
anthropic  _DefaultAioHttpClient -> Hello! How can I help you toda
aiohttp version 3.14.5

For google-genai, no argument is needed: with google-genai[aiohttp] installed, client.aio uses aiohttp automatically (unless you pass your own httpx client or transport):

python
# s2_5_aiohttp_gemini.py: google-genai picks up aiohttp by itself (hosted Gemini API)
import asyncio

from google import genai


async def main() -> None:
    client = genai.Client()     # reads GEMINI_API_KEY from the environment
    g = await client.aio.models.generate_content(model="gemini-3.8-flash", contents="Say hi.")
    print("gemini     uses aiohttp:", client._api_client._use_aiohttp(), "->", (g.text or "").strip()[:30])
    await client.aio.aclose()

asyncio.run(main())

2.5 Notebooks and the running event loop#

Jupyter and other notebooks already run an event loop. Pasting asyncio.run(main()) into a cell fails, because asyncio.run() refuses to start a loop inside a running one. This reproduces it without a notebook: main() plays the part of the notebook's loop.

python
"""s2_6_running_loop.py: why asyncio.run() fails in Jupyter, reproduced without Jupyter.
A notebook cell runs inside an event loop that is already running, which is what main() simulates."""
import asyncio


async def classify_all() -> str:
    await asyncio.sleep(0.01)                 # stands in for your LLM calls
    return "done"


async def main() -> None:                     # <- the notebook's already-running loop
    try:
        asyncio.run(classify_all())           # what people paste into a notebook cell
    except RuntimeError as e:
        # flush=True keeps our line and Python's warning (written to stderr) in the order they happened
        print("asyncio.run() inside a running loop:", e, flush=True)
    print("await classify_all():", await classify_all())       # what a notebook cell should do instead

asyncio.run(main())
Output5 lines
asyncio.run() inside a running loop: asyncio.run() cannot be called from a running event loop
s2_6_running_loop.py:16: RuntimeWarning: coroutine 'classify_all' was never awaited
  print("asyncio.run() inside a running loop:", e, flush=True)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
await classify_all(): done

The RuntimeWarning is also worth knowing: calling a coroutine function without awaiting it never runs it. (Python writes the warning to the error stream when it discards the never-run coroutine; the script flushes its own line first so that the two appear in the order they happened, and the output above shows the script's name without this machine's folder.) In a notebook, do the simple thing and await at the top level of the cell: write results = await classify_all() instead of asyncio.run(classify_all()). IPython and Jupyter allow top-level await. In a plain script, keep one asyncio.run(main()) at the bottom. The older workaround, the nest_asyncio package, patches the loop so nesting works; it can break other libraries, so prefer top-level await. Also remember that a notebook kernel keeps its clients alive between cells, so close them (await client.close()) when you're done, or you'll collect open connections.

2.6 A sync call inside async code blocks everything#

The most common async bug in LLM code: using the sync client (OpenAI()) inside an async def handler. The call doesn't await, so the event loop is stuck until it returns, and every other task, including other users' requests in a web server, waits. This sample uses time.sleep to stand in for a sync SDK call:

python
"""s2_7_blocking.py: the classic async bug: a blocking call inside `async def` freezes every other task.
Pure local: time.sleep stands in for a SYNC SDK call (OpenAI(), Anthropic()...), asyncio.sleep for an
awaited async one, asyncio.to_thread for the escape hatch."""
import asyncio
import time


def sync_call() -> str:                        # what client.responses.create(...) of a SYNC client is to the loop
    time.sleep(0.3)
    return "done"


async def blocking_in_async() -> str:
    return sync_call()                          # BUG: holds the whole event loop for 0.3 s


async def awaited() -> str:
    await asyncio.sleep(0.3)                    # what `await async_client.responses.create(...)` does
    return "done"


async def in_thread() -> str:
    return await asyncio.to_thread(sync_call)   # the sync call runs on a worker thread; the loop stays free


async def timed(label: str, make) -> None:
    start = time.perf_counter()
    await asyncio.gather(*(make() for _ in range(10)))
    print(f"{label:<44} {time.perf_counter() - start:4.2f} s for 10 calls")


async def main() -> None:
    await timed("sync call inside async def (blocks the loop)", blocking_in_async)
    await timed("await an async call", awaited)
    await timed("sync call via asyncio.to_thread", in_thread)

asyncio.run(main())
Output3 lines
sync call inside async def (blocks the loop) 3.05 s for 10 calls
await an async call                          0.30 s for 10 calls
sync call via asyncio.to_thread              0.31 s for 10 calls

Ten "sync calls" inside async def took 3 seconds, as if there were no concurrency. Fix it with the async client, or, when you're stuck with a sync library, await asyncio.to_thread(sync_function, ...), which runs the call on a worker thread so the loop stays free. (The default thread pool is small, min(32, CPU count + 4) threads, so for big fan-outs use the async client or the thread pool in 4.8.)


Part 3: Your first speed-up#

3.1 Try it: sequential vs async vs bounded async#

To see the effect, you need a server whose latency you control and that can serve many requests at once. A real provider has neither property you can rely on in a demo, and the free local stand-in (Ollama) answers one request at a time, which would hide the speed-up (3.2 shows exactly that). So this lesson uses a mock transport with an artificial latency. The real AsyncOpenAI client builds a real request, the mock "server" waits 300 ms and returns a valid Responses API body, and the SDK parses it into a real Response. Only the network is fake. Save this as mock_llm.py; later samples import it:

python
"""mock_llm.py: a MOCK OpenAI Responses endpoint with a fixed latency, for concurrency demos.

Nothing here touches the network. The fixture follows the Response object in
https://developers.openai.com/api/reference/resources/responses/methods/create
"""
import asyncio
import json

import httpx2
from openai import AsyncOpenAI


def response_body(text: str, model: str = "gpt-6-luna", service_tier: str | None = None) -> dict:
    """A minimal but valid Responses API body (the SDK parses it into a real Response object)."""
    body = {
        "id": "resp_mock", "object": "response", "created_at": 1793750400, "model": model,
        "status": "completed", "parallel_tool_calls": True, "tool_choice": "auto", "tools": [],
        "output": [{"type": "message", "id": "msg_mock", "role": "assistant", "status": "completed",
                    "content": [{"type": "output_text", "text": text, "annotations": []}]}],
        "usage": {"input_tokens": 40, "output_tokens": 3, "total_tokens": 43,
                  "input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0},
                  "output_tokens_details": {"reasoning_tokens": 0}},
    }
    if service_tier:
        body["service_tier"] = service_tier
    return body


def error_body(status: int) -> dict:
    """The error envelope OpenAI documents (https://developers.openai.com/api/docs/guides/error-codes)."""
    kind = {429: "rate_limit_exceeded", 500: "server_error"}.get(status, "invalid_request_error")
    return {"error": {"message": f"mock {status}", "type": kind, "param": None, "code": kind}}


class FakeResponsesServer:
    """Answers POST /responses after `latency` seconds. `failures` maps an input text to an HTTP status."""

    def __init__(self, latency: float = 0.3, failures: dict[str, int] | None = None) -> None:
        self.latency = latency
        self.failures = failures or {}
        self.calls = 0
        self.in_flight = 0
        self.peak_in_flight = 0          # the most requests the "server" ever saw at the same time

    async def handler(self, request: httpx2.Request) -> httpx2.Response:
        prompt = json.loads(request.content)["input"]
        self.calls += 1
        self.in_flight += 1
        self.peak_in_flight = max(self.peak_in_flight, self.in_flight)
        try:
            await asyncio.sleep(self.latency)          # the "model" thinking: pure waiting, no CPU
            status = self.failures.get(prompt)
            if status:
                headers = {"retry-after": "1"} if status == 429 else {}
                return httpx2.Response(status, json=error_body(status), headers=headers)
            return httpx2.Response(200, json=response_body(f"label for: {prompt}"))
        finally:
            self.in_flight -= 1

    def client(self, max_retries: int = 0, limits: httpx2.Limits | None = None) -> AsyncOpenAI:
        """A real AsyncOpenAI client whose HTTP layer is this mock. Retries off unless asked for."""
        transport = httpx2.MockTransport(self.handler)
        http_client = (httpx2.AsyncClient(transport=transport, limits=limits) if limits
                       else httpx2.AsyncClient(transport=transport))
        return AsyncOpenAI(api_key="sk-test", max_retries=max_retries, http_client=http_client)

The fixture follows the Response object in OpenAI's API reference and the error envelope in the error codes guide. FakeResponsesServer also records the peak number of requests in flight, which is the number we care about. Now the experiment: 20 tickets, 0.3 s each, three ways.

python
"""s3_1_timing.py: sequential vs unbounded vs bounded async, against a MOCK server with 300 ms latency."""
import asyncio
import time

from mock_llm import FakeResponsesServer

TICKETS = [f"ticket {i}" for i in range(20)]


async def classify_ticket(client, ticket: str) -> str:
    response = await client.responses.create(model="gpt-6-luna", input=ticket, max_output_tokens=16)
    return response.output_text


async def sequential() -> list[str]:
    server = FakeResponsesServer(latency=0.3)
    async with server.client() as client:
        results = [await classify_ticket(client, t) for t in TICKETS]   # one at a time
    print(f"sequential        {time.perf_counter() - START:5.2f} s  peak in flight: {server.peak_in_flight}")
    return results


async def unbounded() -> list[str]:
    server = FakeResponsesServer(latency=0.3)
    async with server.client() as client:
        results = await asyncio.gather(*(classify_ticket(client, t) for t in TICKETS))   # all 20 at once
    print(f"unbounded gather  {time.perf_counter() - START:5.2f} s  peak in flight: {server.peak_in_flight}")
    return list(results)


async def bounded(limit: int) -> list[str]:
    server = FakeResponsesServer(latency=0.3)
    semaphore = asyncio.Semaphore(limit)           # at most `limit` requests in flight

    async def one(client, ticket: str) -> str:
        async with semaphore:                      # wait here for a free slot
            return await classify_ticket(client, ticket)

    async with server.client() as client:
        results = await asyncio.gather(*(one(client, t) for t in TICKETS))
    print(f"bounded ({limit:>2})      {time.perf_counter() - START:5.2f} s  peak in flight: {server.peak_in_flight}")
    return list(results)


async def main() -> None:
    global START
    for run in (sequential, unbounded, lambda: bounded(5)):
        START = time.perf_counter()
        results = await run()
        assert results[7] == "label for: ticket 7"   # gather keeps input order
    print("20 requests, 0.3 s each: 6 s of waiting if done one by one")

START = 0.0
asyncio.run(main())
Output · mock server, 300 ms per request4 lines
sequential         6.13 s  peak in flight: 1
unbounded gather   0.32 s  peak in flight: 20
bounded ( 5)       1.22 s  peak in flight: 5
20 requests, 0.3 s each: 6 s of waiting if done one by one

Read it line by line:

  • Sequential: 6.1 s. Twenty waits of 0.3 s, one after another. Peak in flight: 1.
  • Unbounded gather: 0.32 s. All twenty calls start at once and finish together. The whole job takes about as long as the slowest single call. Peak in flight: 20.
  • Bounded (semaphore of 5): 1.2 s. Four "waves" of five calls (4 × 0.3 s). Peak in flight: 5.

Why would you ever pick the middle ground when unbounded is fastest? Because a real provider isn't a mock. Twenty simultaneous requests are fine; 20,000 simultaneous requests are a rate-limit storm, a socket-exhaustion bug and a memory spike (4.1). The semaphore is the dial between "slow and safe" and "fast and reckless".

A rule of thumb that lets you predict the numbers without running anything (it is called Little's law, and it's just multiplication): throughput = concurrency ÷ latency. Twenty in flight at 0.3 s each is 20 ÷ 0.3 ≈ 67 requests per second; 5 in flight is 17 per second, so 20 requests take about 1.2 s. For a real job: 20 in flight at 1.5 s each gives 13 requests per second, and 20,000 tickets take 20,000 ÷ 13 ≈ 25 minutes. To go faster you raise the concurrency, until a rate limit or the provider pushes back (Part 5).

Also look at what gather returned: results come back in the input order (results[7] is ticket 7), no matter which call finished first. That is convenient, and 4.3 shows what you give up when one call fails.

3.2 Try it: the same code against the local stand-in#

Now the same pattern against a real (small, local) model, with only four requests, to show honestly what a single-request server does. This needs Ollama running, as in 03.1, Part 12:

python
"""s3_2_local.py: the same comparison against the local stand-in (free, no key).
A single small local server mostly runs requests one after another, so expect little or no speed-up."""
import asyncio
import time

from openai import AsyncOpenAI

PROMPTS = ["Name a fruit.", "Name a planet.", "Name a metal.", "Name a colour."]


async def ask(client: AsyncOpenAI, prompt: str) -> float:
    start = time.perf_counter()
    await client.responses.create(model="gpt-6-luna", input=prompt, max_output_tokens=40)
    return time.perf_counter() - start


async def main() -> None:
    async with AsyncOpenAI(base_url="http://localhost:11434/v1", api_key="ollama") as client:
        await ask(client, "Say hi.")                      # warm-up: load the model into memory first

        start = time.perf_counter()
        each = [await ask(client, p) for p in PROMPTS]
        print(f"sequential: {time.perf_counter() - start:.2f} s  (each: {', '.join(f'{s:.2f}' for s in each)})")

        start = time.perf_counter()
        each = await asyncio.gather(*(ask(client, p) for p in PROMPTS))
        print(f"concurrent: {time.perf_counter() - start:.2f} s  (each: {', '.join(f'{s:.2f}' for s in each)})")

asyncio.run(main())

Output (local model qwen2.5:0.5b via Ollama; timings on a laptop, yours will differ):

text
sequential: 0.88 s  (each: 0.11, 0.26, 0.26, 0.26)
concurrent: 0.69 s  (each: 0.32, 0.51, 0.30, 0.69)

The concurrent run is not 4× faster (here it was only about 20% faster), and look at the individual times: the four calls finish at 0.3, 0.5, 0.3 and 0.7 s instead of all at the same time. The local server can only work on a request or two at once, so the others queue inside Ollama. The pattern is the same as against a hosted provider; the backend is what's different. Hosted providers run your requests in parallel on many GPUs, which is why the mock (an idealized hosted provider) shows the textbook 20× speed-up and the laptop doesn't. Two lessons: concurrency helps only as far as the server can run requests in parallel, and a local model is the wrong place to measure concurrency.


Part 4: Bounded concurrency#

4.1 Why unbounded is dangerous#

asyncio.gather(*(call(x) for x in items)) is a fine pattern for 20 items and a bug for 20,000. Five things go wrong when you start everything at once:

  1. Rate limits. Providers limit requests and tokens per minute (03.8, Part 9). 20,000 requests in the first second is a wall of 429s, and every retry joins the stampede.
  2. Sockets and file descriptors. Each in-flight request holds a connection. Operating systems cap open file descriptors per process (often 1,024 on Linux by default), and you hit Too many open files or connection errors long before the provider complains.
  3. Memory. Twenty thousand pending tasks, each holding its request body, its prompt and later its full response, add up, especially with long documents or images.
  4. Provider fairness and bills. A runaway fan-out with a bug in it (a wrong prompt, a missing max_output_tokens) spends money at machine speed. A bound is also a brake.
  5. Unreadable failure. If 20,000 calls fail at once with the same error, you learn nothing and pay for the attempts that did get through.

The fix is to say "no more than N at a time". That is a semaphore, and it is the tool you will use in nearly every async LLM program.

4.2 asyncio.Semaphore#

A semaphore is a counter of free slots. async with semaphore: takes a slot (or waits until one is free) and gives it back when the block ends, even if the block raises. You saw the whole idiom in 3.1:

python
semaphore = asyncio.Semaphore(20)          # at most 20 calls in flight

async def one(item):
    async with semaphore:                  # wait here for a free slot
        return await call_llm(item)        # only the call itself is inside the block

results = await asyncio.gather(*(one(x) for x in items))

Put only the network call inside the async with. Anything else you do per item (building the prompt, parsing, writing to a database, sleeping before a retry) belongs outside, or it holds a slot while doing nothing useful. Creating 20,000 tasks is cheap (each is a few kilobytes while waiting); it's the number in flight that you are bounding. For millions of items, 4.9 shows a pattern that doesn't create them all up front. Since Python 3.10 you can create a semaphore outside a running loop; older tutorials that warn about this are out of date.

How to choose N is 4.7 and Part 5. For a first run, 10 to 20 is a good start.

4.3 gather or TaskGroup: what happens when one call fails#

Calls will fail (03.8). What your concurrency primitive does when one fails decides whether you lose work. Python gives you three behaviours. This sample runs all three against the same mock server (SDK retries are off so errors surface immediately): ticket 2 gets a 500 and ticket 4 gets a 429, and the calls are staggered 50 ms apart so the order is visible.

python
"""s4_3_partial_failures.py: gather vs gather(return_exceptions=True) vs TaskGroup, when one request
gets a 500 and another a 429. MOCK server (mock_llm.py); SDK retries are off so the errors surface at once."""
import asyncio

import openai

from mock_llm import FakeResponsesServer

TICKETS = [f"ticket {i}" for i in range(6)]
FAILURES = {"ticket 2": 500, "ticket 4": 429}        # the fixture: which inputs fail, and how
done: list[str] = []                                  # which calls actually finished successfully


async def classify_ticket(client: openai.AsyncOpenAI, ticket: str, delay: float) -> str:
    await asyncio.sleep(delay)                        # stagger the calls so the order is visible
    response = await client.responses.create(model="gpt-6-luna", input=ticket, max_output_tokens=16)
    done.append(ticket)
    return response.output_text


async def plain_gather() -> None:
    server = FakeResponsesServer(latency=0.3, failures=FAILURES)
    async with server.client() as client:
        try:
            await asyncio.gather(*(classify_ticket(client, t, i * 0.05) for i, t in enumerate(TICKETS)))
        except openai.APIStatusError as e:
            print(f"  gather raised {type(e).__name__} ({e.status_code}); results: lost")
        await asyncio.sleep(0.5)                       # the other calls were NOT cancelled...
    print(f"  ...yet these still finished (and were billed): {sorted(done)}")


async def gather_return_exceptions() -> None:
    server = FakeResponsesServer(latency=0.3, failures=FAILURES)
    async with server.client() as client:
        outcomes = await asyncio.gather(*(classify_ticket(client, t, i * 0.05) for i, t in enumerate(TICKETS)),
                                        return_exceptions=True)
    for ticket, outcome in zip(TICKETS, outcomes):    # same order as the input
        if isinstance(outcome, BaseException):
            print(f"  {ticket}: {type(outcome).__name__}")
        else:
            print(f"  {ticket}: ok -> {outcome!r}")


async def task_group() -> None:
    server = FakeResponsesServer(latency=0.3, failures=FAILURES)
    async with server.client() as client:
        try:
            async with asyncio.TaskGroup() as tg:
                for i, t in enumerate(TICKETS):
                    tg.create_task(classify_ticket(client, t, i * 0.05))
        except* openai.RateLimitError as group:       # except* picks matching errors out of the group
            print(f"  RateLimitError x{len(group.exceptions)}")
        except* openai.InternalServerError as group:
            print(f"  InternalServerError x{len(group.exceptions)}")
    print(f"  finished before the group cancelled the rest: {sorted(done)}")


async def main() -> None:
    for title, demo in [("1. asyncio.gather (default)", plain_gather),
                        ("2. asyncio.gather(return_exceptions=True)", gather_return_exceptions),
                        ("3. asyncio.TaskGroup", task_group)]:
        done.clear()
        print(title)
        await demo()

asyncio.run(main())
Output · mock server; the openai SDK's real exception classes13 lines
1. asyncio.gather (default)
  gather raised InternalServerError (500); results: lost
  ...yet these still finished (and were billed): ['ticket 0', 'ticket 1', 'ticket 3', 'ticket 5']
2. asyncio.gather(return_exceptions=True)
  ticket 0: ok -> 'label for: ticket 0'
  ticket 1: ok -> 'label for: ticket 1'
  ticket 2: InternalServerError
  ticket 3: ok -> 'label for: ticket 3'
  ticket 4: RateLimitError
  ticket 5: ok -> 'label for: ticket 5'
3. asyncio.TaskGroup
  InternalServerError x1
  finished before the group cancelled the rest: ['ticket 0', 'ticket 1']
gather(*calls) (default) gather(*calls, return_exceptions=True) TaskGroup
When a call raises gather raises the first exception to your await The exception becomes a value in the result list The group cancels all other tasks and raises an ExceptionGroup when the async with block exits
Other calls Keep running (they are not cancelled), and you can no longer collect their results. Here they finished and were billed anyway All run to completion Cancelled at their next await (here, only tickets 0 and 1 had finished)
Results Lost A list in input order; each item is a value or an exception object You must store results yourself (in a dict, or by keeping the task objects)
Catching except SomeError: isinstance(item, BaseException) for each item except* SomeError: (note the star) picks matching errors out of the group
Use it when Almost never for LLM calls You want every outcome, and the calls are independent. The right default for bulk jobs The calls form one unit of work where partial results are useless (fetch three documents, then combine them)

The first column is the classic trap: plain gather neither cancels the others nor gives you their results, so you pay for work you then throw away. The third column is the opposite and just as deliberate: TaskGroup implements structured concurrency, in which a group of tasks lives and dies together, so one failure stops the rest. Look at what that did to the 429 on ticket 4: the group never reported it, because ticket 2's 500 cancelled ticket 4 before its call finished. That is correct behaviour for "all or nothing" work and wrong for "classify 20,000 independent tickets".

Two details:

  • CancelledError is not an Exception. Since Python 3.8 it inherits from BaseException, so except Exception: doesn't swallow it, which is what you want. If you catch it to clean up, re-raise it. Swallowing it makes the task un-cancellable, and TaskGroup and asyncio.timeout both depend on cancellation working.
  • A cancelled call may still be billed. Cancelling stops your side from waiting. The provider may already be generating, and many providers bill the tokens produced (03.8, 6.6; 03.3, 8.5 for streams).

4.4 Keep every outcome, and report progress#

For bulk jobs the pattern you want is: run with a bound, never let one item's failure escape, record every outcome with its key, and report progress. A small reusable function does it. The try/except is inside each task, so there is nothing for gather to raise:

python
"""bounded.py: run many LLM calls with bounded concurrency, keep every outcome, report progress."""
import asyncio
import time
from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass
from typing import Generic, TypeVar

T = TypeVar("T")


@dataclass
class ItemResult(Generic[T]):
    key: str                      # your own ID for the item (ticket ID, row number...)
    value: T | None = None        # the result, if it worked
    error: str | None = None      # "RateLimitError: ..." if it didn't
    seconds: float = 0.0

    @property
    def ok(self) -> bool:
        return self.error is None


async def run_bounded(items: Iterable[tuple[str, Callable[[], Awaitable[T]]]], *, concurrency: int,
                      on_progress: Callable[[int, int, int], None] | None = None) -> list[ItemResult[T]]:
    """items: (key, zero-argument coroutine function). Never raises for a single item's failure."""
    semaphore = asyncio.Semaphore(concurrency)
    work = list(items)
    finished = failed = 0

    async def one(key: str, make_call: Callable[[], Awaitable[T]]) -> ItemResult[T]:
        nonlocal finished, failed
        async with semaphore:
            start = time.perf_counter()
            try:
                outcome = ItemResult(key, value=await make_call(), seconds=time.perf_counter() - start)
            except Exception as e:                    # one item's failure must not lose the others
                outcome = ItemResult(key, error=f"{type(e).__name__}: {e}", seconds=time.perf_counter() - start)
        finished += 1
        failed += not outcome.ok
        if on_progress:
            on_progress(finished, failed, len(work))
        return outcome

    # gather keeps input order; CancelledError (Ctrl+C, a deadline) still propagates, as it should
    return list(await asyncio.gather(*(one(key, make_call) for key, make_call in work)))

Save it as bounded.py. run_bounded takes (key, function) pairs and returns one ItemResult per item (not called Outcome, which is the name of 03.8's check_response.Outcome), so each result carries your own ID (a ticket ID, a row number), not a position. Progress is a callback, so you can print, log or update a progress bar. Using it on 40 tickets, 3 of which are rigged to fail (500, 429 and 400):

python
"""s4_4_outcomes.py: bounded concurrency that keeps every success, records every failure, and
reports progress. MOCK server (mock_llm.py) with 3 failing inputs out of 40."""
import asyncio
import time

from bounded import run_bounded
from mock_llm import FakeResponsesServer

TICKETS = {f"T-{i:03d}": f"ticket {i}" for i in range(40)}
FAILURES = {"ticket 7": 500, "ticket 19": 429, "ticket 30": 400}


def progress(finished: int, failed: int, total: int) -> None:
    if finished % 10 == 0 or finished == total:       # every 10 items; a real job might log every N seconds
        print(f"  progress: {finished}/{total} done, {failed} failed")


async def main() -> None:
    server = FakeResponsesServer(latency=0.3, failures=FAILURES)
    start = time.perf_counter()
    async with server.client(max_retries=0) as client:
        def call_for(text: str):
            async def call() -> str:
                response = await client.responses.create(model="gpt-6-luna", input=text, max_output_tokens=16)
                return response.output_text
            return call

        outcomes = await run_bounded(((key, call_for(text)) for key, text in TICKETS.items()),
                                     concurrency=8, on_progress=progress)

    good = [o for o in outcomes if o.ok]
    bad = [o for o in outcomes if not o.ok]
    print(f"{len(good)} ok, {len(bad)} failed in {time.perf_counter() - start:.2f} s "
          f"(peak in flight: {server.peak_in_flight})")
    for o in bad:
        print(f"  retry later: {o.key}  {o.error}")

asyncio.run(main())
Output · mock server8 lines
  progress: 10/40 done, 1 failed
  progress: 20/40 done, 2 failed
  progress: 30/40 done, 2 failed
  progress: 40/40 done, 3 failed
37 ok, 3 failed in 1.60 s (peak in flight: 8)
  retry later: T-007  InternalServerError: Error code: 500 - mock 500
  retry later: T-019  RateLimitError: Error code: 429 - mock 429
  retry later: T-030  BadRequestError: Error code: 400 - mock 400

The summary is the point: 37 successes kept, 3 failures recorded with their key and exception, and the peak concurrency stayed at the bound of 8. What you do with the failures is the next decision: the 500 and 429 are worth retrying (usually after the main pass, with the classifier from 03.8, 4.4); the 400 is a bug in that request and retrying it unchanged would fail again. In production you would also write each success to durable storage as it arrives (a database row, a JSONL line), not at the end, so a crash at item 39,000 loses nothing; 11.2 builds exactly that.

Three smaller tools complete the picture:

  • asyncio.as_completed(coros) yields results as they finish instead of in input order. It is the right choice for a progress display or for writing results out immediately, but you must carry the key with each result because the order is arbitrary.
  • asyncio.timeout(seconds) (3.11+) puts a deadline around any block (5.3).
  • An asyncio.Queue with worker tasks avoids creating one task per item (4.9).

4.5 Retries inside the bound#

Where should retries go? Each task's try/except can catch a retryable failure and retry the call, either with the SDK's built-in retries (max_retries, which retries inside the create() call and so inside your slot) or with your own policy (03.8, Part 7 and Part 8). Three rules for bulk jobs:

  • One layer owns retries (03.8, 5.5). If you add your own retry loop around the SDK, set max_retries=0 on the client, or one failing request becomes 3 × 4 = 12 requests.
  • Don't sleep while holding a slot. A task that waits 30 seconds for a Retry-After while holding a semaphore slot wastes capacity that other tasks could use. Release the slot, sleep, then queue for a slot again. The sample in 5.2 does exactly that (await asyncio.sleep(...) is outside the async with). SDK-internal retries sleep inside the call, so they do hold a slot; that is acceptable for short waits and one more reason to prefer your own retry layer for big jobs.
  • Don't hand-write the retry loop for production. 03.8, 13.4 already built areliable_call(): retries owned by one layer, a total deadline, limiter.pause() on a 429 and a limiter reservation that is settled on every path. 5.2 uses it inside the semaphore and compares it with the simpler loop that teaches the steps. It holds its slot while it backs off, which is the trade-off against the "release the slot" rule above; a limiter that every task shares (pause) makes that cheap, because everyone is waiting anyway.

4.6 Your semaphore and the connection pool#

Two separate limits bound concurrency, and mixing them up causes confusing failures:

  • Your semaphore limits how many requests you start.
  • The HTTP client's connection pool limits how many connections it opens. openai and anthropic default to httpx2.Limits(max_connections=1000, max_keepalive_connections=100) and a 600-second pool timeout (the time a request may wait for a free connection), so by default the pool is not your limiter; your semaphore is. google-genai uses the httpx defaults unless you pass your own client.

Set the semaphore at or below the pool size. If you shrink the pool (to protect a proxy, say) below the semaphore, the excess requests queue for a connection, and that wait counts against the pool timeout: a tight pool timeout then turns queueing into APITimeoutError. This sample uses a mock server on localhost over real HTTP (a FastAPI app, local_http_mock.py) so that connections are real, and counts the TCP connections each approach opens:

python
"""local_http_mock.py: a MOCK Responses API served over real HTTP on localhost (FastAPI + uvicorn),
so connection pooling is real. It counts the TCP connections clients open."""
import asyncio
import threading
import time

import uvicorn
from fastapi import FastAPI, Request

from mock_llm import response_body

app = FastAPI()
seen_connections: set[tuple[str, int]] = set()   # (client host, client port): one per TCP connection
state = {"in_flight": 0, "peak": 0}


@app.post("/v1/responses")
async def responses(request: Request) -> dict:
    assert request.client is not None
    seen_connections.add((request.client.host, request.client.port))
    state["in_flight"] += 1
    state["peak"] = max(state["peak"], state["in_flight"])
    try:
        await asyncio.sleep(0.3)                  # pretend the model takes 300 ms
        return response_body("ok")
    finally:
        state["in_flight"] -= 1


def reset() -> None:
    seen_connections.clear()
    state.update(in_flight=0, peak=0)


def start(port: int = 8765) -> str:
    """Run the server in a background thread; return its base URL for the openai SDK."""
    server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning"))
    threading.Thread(target=server.run, daemon=True).start()
    while not server.started:
        time.sleep(0.01)
    return f"http://127.0.0.1:{port}/v1"
python
"""s4_6_pool_limits.py: your semaphore vs the client's connection pool, and why one client per task
is a bug. MOCK server over real HTTP on localhost (local_http_mock.py), 300 ms per request."""
import asyncio
import time

import httpx2
from openai import AsyncOpenAI, DefaultAsyncHttpx2Client

import local_http_mock as mock

BASE_URL = mock.start()
N = 40


async def run(label: str, make_client, concurrency: int, shared: bool) -> None:
    mock.reset()
    semaphore = asyncio.Semaphore(concurrency)
    shared_client = make_client() if shared else None

    async def one(i: int) -> None:
        async with semaphore:
            if shared_client:
                await shared_client.responses.create(model="gpt-6-luna", input=f"t{i}")
            else:
                async with make_client() as client:          # a NEW client (and pool) per task: the bug
                    await client.responses.create(model="gpt-6-luna", input=f"t{i}")

    start = time.perf_counter()
    await asyncio.gather(*(one(i) for i in range(N)))
    if shared_client:
        await shared_client.close()
    print(f"{label:<46} {time.perf_counter() - start:4.2f} s  peak in flight {mock.state['peak']:>2}  "
          f"TCP connections opened {len(mock.seen_connections):>2}")


def default_client() -> AsyncOpenAI:
    return AsyncOpenAI(base_url=BASE_URL, api_key="sk-test")


def small_pool_client() -> AsyncOpenAI:
    # DefaultAsyncHttpx2Client keeps the SDK's other defaults; we only shrink the pool to 4 connections
    return AsyncOpenAI(base_url=BASE_URL, api_key="sk-test",
                       http_client=DefaultAsyncHttpx2Client(limits=httpx2.Limits(max_connections=4)))


async def main() -> None:
    await run("one shared client, semaphore 10", default_client, 10, shared=True)
    await run("one shared client, semaphore 10, pool of 4", small_pool_client, 10, shared=True)
    await run("a new client per task, semaphore 10", default_client, 10, shared=False)

    # The pool queue has its own timeout: with 4 connections and a 0.1 s pool timeout, most requests fail
    client = AsyncOpenAI(base_url=BASE_URL, api_key="sk-test", max_retries=0,
                         http_client=DefaultAsyncHttpx2Client(limits=httpx2.Limits(max_connections=4),
                                                             timeout=httpx2.Timeout(30.0, pool=0.1)))
    outcomes = await asyncio.gather(*(client.responses.create(model="gpt-6-luna", input=f"t{i}")
                                      for i in range(10)), return_exceptions=True)
    print("pool of 4, pool timeout 0.1 s, 10 at once:",
          sorted({type(o).__name__ for o in outcomes}), f"{sum(isinstance(o, Exception) for o in outcomes)} failed")
    await client.close()

asyncio.run(main())
Output · mock server on localhost, 300 ms per request, 40 requests4 lines
one shared client, semaphore 10                1.30 s  peak in flight 10  TCP connections opened 10
one shared client, semaphore 10, pool of 4     3.05 s  peak in flight  4  TCP connections opened  4
a new client per task, semaphore 10            1.28 s  peak in flight 10  TCP connections opened 40
pool of 4, pool timeout 0.1 s, 10 at once: ['APITimeoutError', 'Response'] 6 failed
  • One shared client, semaphore 10: 10 connections, 1.3 s. The pool reuses connections. This is the correct shape.
  • Pool of 4, semaphore 10: only 4 requests ever run at once, so it takes 3.05 s. The pool silently became the bound. If you see "I set concurrency to 50 but only 10 requests are in flight", look at the pool.
  • A new client per task: the same speed on localhost, but 40 TCP connections instead of 10. Against a real HTTPS API each of those also pays a TLS handshake (several round trips), and in a long-running service sockets pile up in TIME_WAIT. The localhost mock hides the cost, but the connection count shows it.
  • Pool of 4 with a 0.1 s pool timeout, 10 requests at once: 6 fail with APITimeoutError, even though the server was fine. The request waited for a connection, not for the provider. A timeout error doesn't always mean the provider is slow (03.8, Part 6).

To change the pool in the openai SDK, pass DefaultAsyncHttpx2Client(limits=httpx2.Limits(...)) as http_client (it keeps the SDK's other defaults, as the sample does); anthropic has an equivalent. For google-genai, use HttpOptions(async_client_args={"limits": httpx.Limits(...)}), or pass your own httpx_async_client (this is the httpx path: if aiohttp is installed, client.aio uses it instead, 2.4).

4.7 Per-provider concurrency budgets#

Give each provider (or each model) its own semaphore. They have different latencies, limits and failure behaviours, and one slow provider shouldn't use up the slots of a fast one. This is useful when you fan the same job out across providers, when you use a fallback, or when an application calls several models:

python
"""s4_7_budgets.py: one concurrency budget per provider (or per model), shared by every task that
calls it. Pure local: the "calls" are asyncio.sleep with each provider's pretend latency."""
import asyncio
import time
from dataclasses import dataclass


@dataclass(frozen=True)
class Budget:
    concurrency: int          # how many requests may be in flight at once
    latency_s: float          # pretend answer time, for this demo only


# Start low and raise it while your 429 rate stays near zero (lesson 03.8, 9.4 on ramp-up). Values are examples.
BUDGETS = {"openai": Budget(20, 0.30), "anthropic": Budget(10, 0.40), "gemini": Budget(8, 0.25), "openrouter": Budget(4, 0.50)}
semaphores = {name: asyncio.Semaphore(b.concurrency) for name, b in BUDGETS.items()}   # fine at import time since Python 3.10
peak = {name: 0 for name in BUDGETS}
in_flight = {name: 0 for name in BUDGETS}


async def call(provider: str) -> None:
    async with semaphores[provider]:                 # the provider's own budget, not a global one
        in_flight[provider] += 1
        peak[provider] = max(peak[provider], in_flight[provider])
        await asyncio.sleep(BUDGETS[provider].latency_s)
        in_flight[provider] -= 1


async def main() -> None:
    work = [p for p in BUDGETS for _ in range(40)]   # 40 requests for each of the four providers
    start = time.perf_counter()
    await asyncio.gather(*(call(p) for p in work))
    print(f"{len(work)} calls in {time.perf_counter() - start:.2f} s")
    for name, b in BUDGETS.items():
        print(f"  {name:<11} budget {b.concurrency:>2}  peak in flight {peak[name]:>2}")

asyncio.run(main())
Output5 lines
160 calls in 5.01 s
  openai      budget 20  peak in flight 20
  anthropic   budget 10  peak in flight 10
  gemini      budget  8  peak in flight  8
  openrouter  budget  4  peak in flight  4

Each provider stayed at its own bound, and the job took as long as its tightest bound (OpenRouter's budget of 4 at 0.5 s: 40 ÷ 4 × 0.5 = 5 s). How do you choose the numbers?

Constraint What it gives you Where to look
Little's law Concurrency needed = target requests per second × average latency. For 20 req/s at 1.5 s you need about 30 in flight 3.1
Your rate limits At most RPM ÷ 60 requests per second, and TPM ÷ tokens-per-request ÷ 60. Concurrency above what the limit allows only causes 429s 03.8, 9.2
Ramp-up rules Some providers limit how fast usage may grow; start low and raise it while the 429 rate stays near zero 03.8, 9.4
The other work on the same key Limits are per organization or project, not per process. A batch backfill at full speed can starve your live traffic Use a separate project or key for bulk jobs (03.7 recommends separate budgets)
Local resources Memory for responses, sockets, CPU for parsing Your machine

Keep the numbers in configuration, not in code, so you can change them without a deploy. The providers publish rate limits (requests and tokens per minute); the limit pages used for this lesson don't define a general cap on concurrent requests for ordinary calls (Gemini's rate-limit page lists "concurrent batch requests" for its Batch API, 9.2). So treat the concurrency number as something you tune, not look up.

4.8 Threads for code that isn't async#

If your codebase is synchronous (a Django app, a script, a Celery task), you don't have to rewrite it to get concurrency. The sync clients are thread-safe, and a ThreadPoolExecutor gives you the same bounded concurrency, because waiting on the network releases Python's global interpreter lock. max_workers is your bound:

python
"""s4_8_threads.py: concurrency without async: a thread pool and ONE shared sync client.
MOCK server over real HTTP on localhost (local_http_mock.py), 300 ms per request."""
import time
from concurrent.futures import ThreadPoolExecutor, as_completed

from openai import OpenAI, OpenAIError

import local_http_mock as mock

client = OpenAI(base_url=mock.start(), api_key="sk-test")   # sync clients are safe to share between threads
TICKETS = {f"T-{i:03d}": f"ticket {i}" for i in range(20)}


def classify_ticket(text: str) -> str:
    return client.responses.create(model="gpt-6-luna", input=text, max_output_tokens=16).output_text


start = time.perf_counter()
results: dict[str, str] = {}
errors: dict[str, str] = {}
with ThreadPoolExecutor(max_workers=8) as pool:              # max_workers IS the concurrency limit
    futures = {pool.submit(classify_ticket, text): key for key, text in TICKETS.items()}
    for future in as_completed(futures):                     # in completion order, not input order
        key = futures[future]
        try:
            results[key] = future.result()
        except OpenAIError as e:
            errors[key] = repr(e)
print(f"{len(results)} ok, {len(errors)} failed in {time.perf_counter() - start:.2f} s "
      f"with 8 threads (peak in flight {mock.state['peak']}, TCP connections {len(mock.seen_connections)})")
client.close()
Output · mock server on localhost, 300 ms per request1 line
20 ok, 0 failed in 1.01 s with 8 threads (peak in flight 8, TCP connections 8)

Twenty requests in a second with 8 threads: ⌈20 ÷ 8⌉ × 0.3 s ≈ 0.9 s plus start-up. Notes:

  • Share one sync client between threads, as the sample does (8 TCP connections for 8 threads), and use as_completed to handle results as they arrive.
  • Threads cost more than tasks. Each thread has a stack (megabytes), and the OS schedules them. A few dozen is fine; a thousand is not, so use async if you need very high concurrency.
  • Errors surface in future.result(), not at submit time, so wrap that call as the sample does.
  • Calling async code from sync code uses asyncio.run(...) once at the top; calling sync code from async code uses asyncio.to_thread (2.6).

4.9 A worker pool for inputs that don't fit in memory#

Creating one task per item is fine for 20,000 items and wasteful for 20 million. A worker pool runs a fixed number of long-lived worker tasks that pull items from a bounded asyncio.Queue. The producer waits when the queue is full (back-pressure), so memory stays constant however large the input is. The "LLM call" in this sample is asyncio.sleep, so it is a pure local demonstration of the structure:

python
"""s4_9_worker_pool.py: a fixed pool of worker tasks fed by a bounded queue. For very large inputs
(a 1M-row file), this keeps only `workers` tasks and `maxsize` items in memory at any time.
Pure local: the "LLM call" is asyncio.sleep."""
import asyncio
import time
from collections.abc import Iterator


def read_rows(n: int) -> Iterator[tuple[str, str]]:
    for i in range(n):                                    # in real code: stream a CSV or a DB cursor
        yield f"T-{i:05d}", f"ticket text {i}"


async def fake_llm_call(text: str) -> str:
    await asyncio.sleep(0.01)
    return "billing" if text.endswith("7") else "other"


async def main(n: int = 10_000, workers: int = 50) -> None:
    queue: asyncio.Queue[tuple[str, str] | None] = asyncio.Queue(maxsize=workers * 2)  # back-pressure
    results: dict[str, str] = {}
    peak_tasks = 0

    async def worker() -> None:
        while (item := await queue.get()) is not None:   # None is the "no more work" signal
            key, text = item
            try:
                results[key] = await fake_llm_call(text)
            except Exception as e:                       # record and keep going
                results[key] = f"ERROR {type(e).__name__}"

    start = time.perf_counter()
    async with asyncio.TaskGroup() as tg:
        for _ in range(workers):
            tg.create_task(worker())
        for row in read_rows(n):
            await queue.put(row)                         # waits while the queue is full
            peak_tasks = max(peak_tasks, len(asyncio.all_tasks()))
        for _ in range(workers):
            await queue.put(None)
    print(f"{len(results):,} items in {time.perf_counter() - start:.2f} s with {workers} workers; "
          f"at most {peak_tasks} tasks alive at once")

asyncio.run(main())
Output1 line
10,000 items in 2.44 s with 50 workers; at most 51 tasks alive at once

Ten thousand items were handled by 50 workers, and at no point were more than 51 tasks alive (50 workers plus the main task). Each worker records an error and keeps going, as run_bounded does.


Part 5: Rate-aware throughput#

Deep-dive

5.1 Two limits, two tools#

A semaphore answers "how many requests are in flight right now?". A provider's rate limit asks a different question: "how many requests and tokens did you use this minute?" (03.8, Part 9). They're independent, and a job can break either one:

Limit Controlled by Tool Typical symptom when it's wrong
Requests (and bytes of memory, sockets) in flight Your concurrency bound asyncio.Semaphore Too high: memory and sockets. Too low: the job is slow, but no errors
Requests and tokens per minute The provider's quotas for your tier The token-bucket limiter from 03.8, 9.5 Too fast for the quota: 429s
flowchart LR
    subgraph app ["Your process"]
        t1["task 1"] --> sem
        t2["task 2"] --> sem
        t3["task 3 ... N"] --> sem
        sem["Semaphore<br/>(how many may run at once)"] --> lim["Rate limiter<br/>(how many per minute)"]
        lim --> pool["One shared client<br/>connection pool"]
    end
    pool --> api["Provider API<br/>(seconds per call)"]
    api -- "429 + Retry-After" --> lim

With 16 requests in flight and a 0.3-second latency, you send about 53 requests per second, which is 3,200 per minute. If your limit is 600 per minute, concurrency alone makes you hit the limit within seconds. The fix is to combine the two: the semaphore bounds the in-flight count, and the limiter makes each request wait until it fits under the per-minute budget before it goes out. The limiter is 03.8's rate_limiter.py (two token buckets, requests and tokens, with acquire(estimate) before a call, settle(estimate, actual) after it and pause(seconds) on a 429). Copy the current version from 03.8, 9.5; this lesson doesn't rebuild it. Two things in it matter here. Its burst_s argument sets how much may go out at once: each bucket holds burst_s seconds' worth of its limit, so the default of 60 lets a whole minute's budget through in the first instant, and burst_s=1 spreads it out (the refill rate, and so the sustained rate, never changes). And the retry loop around it is not worth writing again: 03.8, 13.4 wraps the limiter, the retries and a deadline in areliable_call(), which 5.2 uses.

5.2 Try it: semaphore, limiter and 429 adaptation#

This sample runs 60 requests against a mock server that enforces a limit of 10 requests per second (like a 600 RPM limit) and answers 429 with Retry-After: 1 beyond that. It compares five strategies. SDK retries are off (max_retries=0) so each 429 is visible and handled by our code:

  • A: semaphore of 16 and nothing else.
  • B: the same, plus the limiter set to 540 RPM (90% of the limit, leaving headroom).
  • C: as B, but RateLimiter(rpm=540, tpm=1_000_000, burst_s=1): the request bucket holds one second's worth (9 requests) instead of a minute's, because providers may enforce a per-minute limit over shorter windows.
  • D: no limiter, but an adaptive concurrency limit: halve the limit when a 429 arrives and raise it by one after every 10 successes. Engineers know this as AIMD (additive increase, multiplicative decrease), the rule TCP uses to find the speed a network can carry.
  • E: the production form of C: the same limiter, but each ticket goes through 03.8's areliable_call() (13.4) inside the semaphore, instead of the hand-written loop.

In the hand-written loop (A to D), a 429 makes the worker call limiter.pause(retry_after) so that every task holds back, not just the one that got the error, and then sleep outside the semaphore (4.5). Every acquire() is paired with a settle() in a finally, on the 429 path too: a reservation that is never settled stays charged to the token bucket, and the limiter slowly strangles your own traffic (03.8, 13.4, point 2). That is the one thing to copy from this loop. one() is a teaching version: it shows each step in 25 lines and leaves out the total deadline, the error classification and the typed outcome check that areliable_call() has, so use E in a real job.

python
"""s5_2_rate_aware.py: a semaphore (how many at once) plus a rate limiter (how many per minute),
with adaptation to 429s. MOCK server that allows 10 requests per second and answers 429 beyond that.
rate_limiter.py is the limiter built in lesson 03.8, section 9.5, and production_call.py is its areliable_call()
(03.8, section 13.4): row E shows the production-grade way to do what the hand-written loop in `one()` does."""
import asyncio
import json
import time

import httpx2
import openai
from openai import AsyncOpenAI

from mock_llm import error_body, response_body
from production_call import RetryPolicy, areliable_call
from rate_limiter import RateLimiter, estimate_tokens


class RateLimitedServer:
    """MOCK: a token bucket of 10 requests per second, like a provider's RPM limit (600 RPM)."""
    def __init__(self, per_second: float = 10.0) -> None:
        self.per_second, self.level, self.updated = per_second, per_second, time.monotonic()
        self.ok = self.rejected = 0

    async def handler(self, request: httpx2.Request) -> httpx2.Response:
        now = time.monotonic()
        self.level = min(self.per_second, self.level + (now - self.updated) * self.per_second)
        self.updated = now
        if self.level < 1:
            self.rejected += 1
            return httpx2.Response(429, json=error_body(429), headers={"retry-after": "1"})
        self.level -= 1
        self.ok += 1
        await asyncio.sleep(0.3)
        return httpx2.Response(200, json=response_body(f"label for {json.loads(request.content)['input']}"))


class AdaptiveLimit:
    """A concurrency limit that halves on a 429 and creeps back up after successes (AIMD)."""
    def __init__(self, start: int, floor: int = 1, ceiling: int = 64) -> None:
        self.limit, self.floor, self.ceiling = start, floor, ceiling
        self.in_flight, self.successes = 0, 0
        self._cond = asyncio.Condition()

    async def __aenter__(self) -> None:
        async with self._cond:
            await self._cond.wait_for(lambda: self.in_flight < self.limit)
            self.in_flight += 1

    async def __aexit__(self, *exc: object) -> None:
        async with self._cond:
            self.in_flight -= 1
            self._cond.notify_all()

    def on_success(self) -> None:
        self.successes += 1
        if self.successes % 10 == 0:                     # additive increase: +1 per 10 successes
            self.limit = min(self.ceiling, self.limit + 1)

    def on_rate_limited(self) -> None:
        self.limit = max(self.floor, self.limit // 2)    # multiplicative decrease


async def run_job(label: str, concurrency: int, limiter: RateLimiter | None, adaptive: bool, n: int = 60,
                  reliable: bool = False) -> None:
    server = RateLimitedServer()
    client = AsyncOpenAI(api_key="sk-test", max_retries=0,   # we handle 429s ourselves here
                         http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(server.handler)))
    gate = AdaptiveLimit(concurrency) if adaptive else None
    fixed = asyncio.Semaphore(concurrency)
    results: dict[int, str] = {}

    async def one(i: int) -> None:
        """A teaching loop: it shows each step. Row E replaces it with 03.8's areliable_call()."""
        text, wait = f"ticket {i}", 1.0
        for attempt in range(6):
            estimate = estimate_tokens(len(text), max_output_tokens=16)
            async with (gate or fixed):
                if limiter:
                    await limiter.acquire(estimate)
                actual: int | None = None                 # unknown unless the call returns usage
                try:
                    response = await client.responses.create(model="gpt-6-luna", input=text, max_output_tokens=16)
                    actual = response.usage.total_tokens if response.usage else None
                except openai.RateLimitError as e:
                    wait = float(e.response.headers.get("retry-after", "1"))
                    if limiter:
                        limiter.pause(wait)               # hold back EVERY task, not just this one
                    if gate:
                        gate.on_rate_limited()
                else:
                    if gate:
                        gate.on_success()
                    results[i] = response.output_text
                    return
                finally:
                    if limiter:                           # every acquire() is settled, even on a 429 (03.8, 13.4)
                        limiter.settle(estimate, actual)
            await asyncio.sleep(wait * (attempt + 1))     # outside the gate: don't hold a slot while waiting
        results[i] = "GAVE UP"

    async def one_reliable(i: int) -> None:
        """The same job through 03.8's areliable_call(): acquire, send, settle in a finally, limiter.pause on a
        429, backoff and one deadline. The semaphore wraps the whole call (a slot is held while it backs off)."""
        text = f"ticket {i}"

        async def send(timeout: float, client_request_id: str) -> object:
            return await client.responses.create(model="gpt-6-luna", input=text, max_output_tokens=16, timeout=timeout,
                                                 extra_headers={"X-Client-Request-Id": client_request_id})
        async with fixed:
            result = await areliable_call(send, policy=RetryPolicy(max_attempts=6, deadline_s=60, attempt_timeout_s=10),
                                          limiter=limiter, estimated_tokens=estimate_tokens(len(text), max_output_tokens=16),
                                          on_event=lambda event: None)
        results[i] = result.outcome.text if result.ok and result.outcome else "GAVE UP"

    start = time.perf_counter()
    async with client:
        await asyncio.gather(*((one_reliable if reliable else one)(i) for i in range(n)))
    gave_up = sum(v == "GAVE UP" for v in results.values())
    final = f", final limit {gate.limit}" if gate else ""
    print(f"{label:<38} {time.perf_counter() - start:5.2f} s  429s: {server.rejected:>3}  "
          f"gave up: {gave_up}{final}")


async def main() -> None:
    await run_job("semaphore 16, no limiter", 16, None, adaptive=False)
    await run_job("semaphore 16 + limiter at 540 RPM", 16, RateLimiter(rpm=540, tpm=1_000_000), adaptive=False)
    # The limiter's buckets start full (a whole minute's budget: 540 requests), so it lets an opening burst through.
    # Providers may enforce a minute limit over shorter windows, so cap the burst at one second's worth (03.8, 9.5):
    await run_job("semaphore 16 + limiter, burst of 9", 16, RateLimiter(rpm=540, tpm=1_000_000, burst_s=1), adaptive=False)
    await run_job("adaptive limit from 16, no limiter", 16, None, adaptive=True)
    await run_job("areliable_call + limiter, burst of 9", 16, RateLimiter(rpm=540, tpm=1_000_000, burst_s=1),
                  adaptive=False, reliable=True)

asyncio.run(main())
Output · mock server5 lines
semaphore 16, no limiter               15.40 s  429s: 150  gave up: 0
semaphore 16 + limiter at 540 RPM       5.35 s  429s:  10  gave up: 0
semaphore 16 + limiter, burst of 9      5.97 s  429s:   0  gave up: 0
adaptive limit from 16, no limiter      5.49 s  429s:   7  gave up: 0, final limit 4
areliable_call + limiter, burst of 9    5.97 s  429s:   0  gave up: 0
  • A: 150 rejected requests and 15.4 seconds. Sixteen workers keep hitting the wall, and each rejected one sleeps and retries. The job succeeds, but most of the requests were wasted. On a real provider the repeated 429s also count towards some limits, and some providers escalate.
  • B: 5.3 s with only 10 rejections. The limiter paces the traffic. The 10 rejections came from the limiter's request bucket, which starts full (540 requests: the default burst_s=60), so it lets an opening burst through that is bigger than the server's one-second bucket.
  • C: 0 rejections, 6.0 s. burst_s=1 fixes it. Real providers differ in how they enforce a per-minute limit (03.8, 9.3), so a small burst capacity is a sensible default.
  • D: 7 rejections and 5.5 s, with no knowledge of the limit. The adaptive limit started at 16, fell to 4 after the first 429s and stayed near there; the server's 10 req/s × 0.3 s means about 3 in flight is the sustainable level. Adaptation is the right tool when you don't know the limit (shared keys, other workloads, a provider that changes limits under load); a limiter is the right tool when you do.
  • E: the same 6.0 s and 0 rejections as C, with the retry policy, the deadline and the books-balanced limiter calls written once, in a module you have already tested. The price is that a slot stays held while a call backs off, which the shared pause() makes harmless here, since every task is waiting for the same second anyway.

The ideal time for 60 requests at 10 per second is 6 s, which B, C, D and E reached. In real code you'd combine them: a known-limit limiter as the main control, areliable_call() around each call, and an adaptive bound as the safety net.

5.3 A deadline and cancellation for a whole job#

Sometimes a job must stop by a given time: the nightly window ends, the user closes the tab, the cloud function has 15 minutes. asyncio.timeout() (3.11+) puts one deadline around everything inside it. When it expires, the loop cancels every task in the group, and your code can still save what it has. This is a different tool from the per-request timeouts in 03.8, Part 6: those bound one call, this bounds the job.

python
"""s5_3_deadline.py: a total deadline for a whole job. When time runs out, in-flight calls are
cancelled, finished results are kept, and the rest is reported as "not done". MOCK server (mock_llm.py)."""
import asyncio
import time

from mock_llm import FakeResponsesServer

TICKETS = {f"T-{i:03d}": f"ticket {i}" for i in range(40)}


async def main(deadline_s: float = 1.0, concurrency: int = 8) -> None:
    server = FakeResponsesServer(latency=0.3)
    done: dict[str, str] = {}                     # written as each call finishes, so nothing is lost
    cancelled: list[str] = []
    semaphore = asyncio.Semaphore(concurrency)

    async with server.client() as client:
        async def one(key: str, text: str) -> None:
            async with semaphore:
                try:
                    response = await client.responses.create(model="gpt-6-luna", input=text, max_output_tokens=16)
                except asyncio.CancelledError:
                    cancelled.append(key)                     # mid-request: the provider may still bill it
                    raise                                     # always re-raise CancelledError
                done[key] = response.output_text

        start = time.perf_counter()
        try:
            async with asyncio.timeout(deadline_s):           # Python 3.11+: one deadline for the whole job
                async with asyncio.TaskGroup() as tg:
                    for key, text in TICKETS.items():
                        tg.create_task(one(key, text))
        except TimeoutError:
            print(f"deadline of {deadline_s} s reached after {time.perf_counter() - start:.2f} s: "
                  f"{len(cancelled)} calls in flight were cancelled")

    not_done = [k for k in TICKETS if k not in done]
    print(f"kept {len(done)} results; {len(not_done)} not done (first: {not_done[0]}) -> save them for the next run")

asyncio.run(main())
Output · mock server, concurrency 8, deadline 1.0 s2 lines
deadline of 1.0 s reached after 1.00 s: 8 calls in flight were cancelled
kept 24 results; 16 not done (first: T-024) -> save them for the next run

Points to copy from this sample:

  • Results are written to done as each call finishes, so cancelling loses only the calls in flight. Never collect results only after gather returns if the job can be cancelled.
  • except asyncio.CancelledError: ...; raise records the key of the call that was interrupted and re-raises. It is the only way to learn which calls were mid-flight, and re-raising is mandatory (4.3).
  • The in-flight calls may still be billed. Eight requests were cancelled mid-flight. The provider may complete and bill them. Record them as "unknown", and on the next run treat them as not done (that costs a duplicate in the worst case, which is cheaper than losing the result).
  • asyncio.timeout raises TimeoutError when the deadline passes, after cancelling the inner work. Catch it outside the block.
  • Ctrl+C works the same way: asyncio.run cancels the main task on KeyboardInterrupt, which cancels the group. The same "save what finished" structure handles it.
  • Combine with a total retry budget: a deadline and an attempt cap together stop a job from retrying forever (03.8, 7.4).

The "not done" list is exactly the input of the next run. That idea, a job that always knows what is left, is the heart of Part 11.


Part 6: Batch APIs: the shared shape#

6.1 What a Batch API is#

A Batch API turns "make 20,000 calls" into "submit one job". You hand the provider a file (or a list) of complete requests. The provider runs them on spare capacity, at its own pace, within a completion window (24 hours on OpenAI and Anthropic; the target on Gemini and OpenRouter, where a job expires later: Gemini after 48 hours, and OpenRouter's limit depends on the provider, 6.2). You come back later, by polling or by webhook, and collect one result per request. In exchange for the wait, three things change:

  • The price drops by about half on OpenAI, Anthropic and Gemini, and typically on OpenRouter, for input and output tokens alike. The discount stacks with prompt caching, and the exact billing rules (and how to record a batch's cost) are in 03.7; prices are in 02.9, 6.5.
  • The limits change. Batch jobs run in their own rate-limit pool, so a huge backfill doesn't use up the quota that your live traffic needs. The pool is measured differently (requests and bytes per batch, and tokens queued), and each provider's part gives the numbers.
  • The failure model changes. There's no exception per request. One job runs thousands of requests and finishes with a result per request: some succeeded, some errored, some never ran. Invalid requests may not be reported until the batch finishes, because validation is often asynchronous. You find out what failed by reading the results, and you must be able to match each result to its input.

Two things a Batch API does not give you: a speed guarantee (a batch can finish in minutes or take the whole window, and a batch that doesn't finish in time expires), and streaming (requests inside a batch cannot stream).

6.2 The lifecycle, and how the four providers differ#

Every provider follows the same seven steps; only the nouns change:

sequenceDiagram
    participant You as Your code
    participant Store as Local manifest (SQLite)
    participant API as Provider Batch API
    You->>Store: 1. items pending, deterministic custom_ids
    You->>API: 2. upload JSONL (or send inline requests)
    You->>API: 3. create batch
    API-->>You: batch id, status validating
    You->>Store: 4. save the batch id at once
    loop polling with growing intervals
        You->>API: retrieve batch
        API-->>You: in_progress, request_counts
    end
    API-->>You: completed (or expired, failed)
    You->>API: 5. download results and errors
    You->>Store: 6. join on custom_id, mark done or retry
    You->>You: 7. resubmit only the failures

The differences that shape your code (all as of November 2026; every row is verified against the official page named in the provider's part):

OpenAI Anthropic
How you submit Upload a JSONL file (Files API, purpose="batch"), then batches.create(input_file_id=...) messages.batches.create(requests=[...]), inline
Request format {custom_id, method, url, body} per line {custom_id, params}, params = a normal Messages request
ID that comes back custom_id custom_id
One model per batch? Yes (per file) No: mix models freely
Size limits 50,000 requests, 200 MB 100,000 requests or 256 MB, whichever comes first
Status values validating, in_progress, finalizing, completed, failed, expired, cancelling, cancelled in_progress, canceling, ended
Results Download output_file_id and error_file_id (Files API) Stream batches.results(id) (JSONL)
Results kept The output file is deleted 30 days after the batch completes (configurable) 29 days after creation
Expires After 24 hours (expired) After 24 hours (expired results)
Cancel batches.cancel (takes up to 10 minutes) messages.batches.cancel
Webhook batch.completed, .failed, .expired, .cancelled None for Message Batches (Managed Agents webhooks are a beta for other products, 13.6)
Gemini OpenRouter
How you submit Inline list (under 20 MB in total) or a JSONL file uploaded with the Files API POST /api/v1/batches with inline requests (no SDK method; use the SDK's generic post)
Request format {key, request} per line (file), or a list of GenerateContentRequests (inline) {custom_id, body}; one model and one endpoint per batch
ID that comes back key (file) or the metadata you attach (inline) custom_id
One model per batch? Yes (model= of the create call) Yes
Size limits File: 2 GB. Inline: 20 MB 200 MB, and a request cap that is not published
Status values JOB_STATE_PENDING, RUNNING, SUCCEEDED, FAILED, CANCELLED, EXPIRED validating, in_progress, finalizing, completed, failed, expired, cancelled
Results dest.inlined_responses, or download dest.file_name Inline in GET /batches/{id} (results)
Results kept Not documented for batches. Output is delivered as a Files API file (48 hours per 03.6), so treat 48 hours as the worst case and download at once 30 days after you submit, then 410 Gone
Expires After 48 hours (JOB_STATE_EXPIRED) Provider-dependent: 24 h typically, 48 h for Google AI Studio, 96 h for Vertex
Cancel batches.cancel Not available; wait, then delete
Webhook batch.succeeded, .failed, .cancelled, .expired (preview) batch.completed, .failed, .expired, .cancelled

6.3 custom_id and key: your join column#

Results come back in any order. OpenAI says so in its guide ("the output line order may not match the input line order"), Anthropic puts it in a tip ("Batch results can be returned in any order"), and OpenRouter says that results are not in input order. Gemini is the odd one out: its batch guide is silent about order and only says that the key "is used in the response to indicate which output is the result of which request", while its REST reference says the responses are "written in the same order as the input requests" (9.1). Join on the ID anyway. The only reliable way to match a result to a request is the ID you attached to it: custom_id on OpenAI, Anthropic and OpenRouter, key in a Gemini file, metadata on an inline Gemini request. Treat it as the primary key of your job:

  • Derive it from your data, deterministically. triage-v1-10231 (job name + your ticket ID) is reproducible: the same ticket in the same job always gets the same ID, so you can rebuild the file, find an item in the results, and detect duplicates. Do not use random IDs or loop counters that change when the input order changes, because after a crash you can no longer tell which result belongs to which item (11.1).
  • Make them unique within a batch. OpenAI requires it, Anthropic asks for it ("Ensure each request in the batch has a unique custom_id"), and OpenRouter requires it.
  • Obey the strictest format. Anthropic's custom_id must match ^[a-zA-Z0-9_-]{1,64}$: 1 to 64 letters, digits, hyphens or underscores, so a ticket ID such as ZD#10236/a is rejected. If your IDs might contain other characters, hash them (the sample below does) and keep a map from custom_id to your own ID. Using the Anthropic rule everywhere means the same IDs work on all providers.
  • Don't put secrets or personal data in it. IDs show up in logs, consoles and results.

6.4 Polling done right#

All four providers need you to poll (webhooks are covered in Part 13 and are an addition, not a replacement). Polling sounds trivial and has four ways to go wrong:

  1. Polling too often. A fixed 10-second interval over a 2-hour batch is 720 requests of pure waste, and the status endpoint has rate limits too (Anthropic gives batch endpoints their own requests-per-minute limit; OpenRouter says once a minute is enough and tells you to back off if you get a 429).
  2. Polling forever. If the job never reaches a final state (your bug, or a state you didn't list as final), the loop never ends. Always set a maximum wait, and when it's reached, stop waiting without cancelling: the job may still be running, and you have its ID.
  3. Polling in lockstep. A hundred workers that all start at the same moment poll at the same moment. Add jitter (a random ±20%).
  4. Treating a poll failure as a job failure. A timeout on batches.retrieve says nothing about the batch. Let the SDK's retries handle it, and keep waiting.

The poller.py helper below grows the interval geometrically (×1.5 by default) up to a cap, adds jitter, stops at a maximum wait (after one last poll exactly at the deadline, so a job that finished in the final interval isn't missed), and takes the clock and sleep as parameters so you can test it without waiting. It also has an async twin, apoll_until() (see below). Save it as poller.py; every Batch lifecycle sample uses it:

python
"""poller.py: poll a long-running job with growing intervals, jitter, and a maximum total wait.
poll_until() is for scripts (it blocks with time.sleep); apoll_until() is the same logic for async code."""
import asyncio
import random
import time
from collections.abc import Awaitable, Callable
from typing import TypeVar

T = TypeVar("T")


class PollTimeout(Exception):
    """We stopped waiting. The job itself may still be running: keep its ID and check again later."""


def next_pause(interval: float, elapsed: float, max_wait: float, rng: random.Random) -> float | None:
    """How long to sleep before the next poll: the jittered interval, cut short so the LAST poll lands exactly on
    the deadline. None means the deadline has already passed: stop waiting."""
    remaining = max_wait - elapsed
    if remaining <= 0:
        return None
    return min(interval * rng.uniform(0.8, 1.2), remaining)


def poll_until(fetch: Callable[[], T], is_done: Callable[[T], bool], *, first: float = 5.0,
               factor: float = 1.5, max_interval: float = 300.0, max_wait: float = 26 * 3600,
               on_poll: Callable[[T, float], None] | None = None,
               sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic,
               rng: random.Random = random.Random()) -> T:
    """Call fetch() until is_done(result). Intervals grow from `first` by `factor` up to `max_interval`, with
    +-20% jitter so many pollers don't hit the API in lockstep. After `max_wait` it raises PollTimeout, having
    polled once AT the deadline (a job that finished in the last interval is not missed)."""
    start, interval = clock(), first
    while True:
        result = fetch()
        if on_poll:
            on_poll(result, clock() - start)
        if is_done(result):
            return result
        pause = next_pause(interval, clock() - start, max_wait, rng)
        if pause is None:
            raise PollTimeout(f"still not done after {clock() - start:.0f} s")
        sleep(pause)
        interval = min(max_interval, interval * factor)


async def apoll_until(fetch: Callable[[], Awaitable[T]], is_done: Callable[[T], bool], *, first: float = 5.0,
                      factor: float = 1.5, max_interval: float = 300.0, max_wait: float = 26 * 3600,
                      on_poll: Callable[[T, float], None] | None = None,
                      sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
                      clock: Callable[[], float] = time.monotonic,
                      rng: random.Random = random.Random()) -> T:
    """poll_until() for async code: `fetch` is a coroutine function (e.g. an async client's retrieve) and the
    waiting is `await asyncio.sleep`, so many jobs can be polled at once by one thread (see s6_5)."""
    start, interval = clock(), first
    while True:
        result = await fetch()
        if on_poll:
            on_poll(result, clock() - start)
        if is_done(result):
            return result
        pause = next_pause(interval, clock() - start, max_wait, rng)
        if pause is None:
            raise PollTimeout(f"still not done after {clock() - start:.0f} s")
        await sleep(pause)
        interval = min(max_interval, interval * factor)

What the schedule looks like over a pretend 2-hour batch, using a fake clock so the demo runs instantly:

python
"""s6_4_poll_schedule.py: what poll_until's schedule looks like over a 2-hour batch. Pure local:
a fake clock and a fake job, so the demo runs instantly."""
import random

from poller import PollTimeout, poll_until

now = 0.0
def fake_clock() -> float: return now
def fake_sleep(seconds: float) -> None:
    global now
    now += seconds

FINISHES_AT = 2 * 3600                                  # this pretend batch takes 2 hours
def fetch_status() -> str:
    return "completed" if now >= FINISHES_AT else "in_progress"

polls: list[float] = []
status = poll_until(fetch_status, lambda s: s == "completed", first=10, factor=1.5, max_interval=600,
                    on_poll=lambda s, elapsed: polls.append(elapsed),
                    sleep=fake_sleep, clock=fake_clock, rng=random.Random(42))
print(f"{status} after {len(polls)} polls; first polls at (s):", [round(p) for p in polls[:8]])
print("gaps later on (s):", [round(b - a) for a, b in zip(polls[-4:], polls[-3:])])
print("a fixed 10 s interval would have polled", FINISHES_AT // 10, "times")

now = 0.0
try:
    poll_until(lambda: "in_progress", lambda s: s == "completed", first=10, max_interval=600,
               max_wait=3600, sleep=fake_sleep, clock=fake_clock, rng=random.Random(42))
except PollTimeout as e:
    print("PollTimeout:", e)
Output4 lines
completed after 22 polls; first polls at (s): [0, 11, 23, 43, 73, 129, 210, 342]
gaps later on (s): [674, 482, 673]
a fixed 10 s interval would have polled 720 times
PollTimeout: still not done after 3600 s

Twenty-two polls instead of 720: dense at the start, when a small batch might finish quickly, and about every 10 minutes later. The second run shows PollTimeout after exactly the 3,600 seconds it was allowed: it means "I stopped waiting", not "the job failed". Persist the batch ID before you start polling (11.2), so that a later process can pick the job up again.

In async code, poll with apoll_until(). poll_until sleeps with time.sleep, which is exactly the blocking call that 2.6 warns about: called from an async def, it would freeze the event loop. apoll_until has the same schedule and the same PollTimeout, but awaits its fetch (an async client's retrieve) and sleeps with asyncio.sleep, so one task per batch lets a single thread watch as many jobs as you have. This sample polls four pretend batches at once, with the intervals scaled down so that it runs in a second:

python
"""s6_5_poll_many.py: poll several batches at once with apoll_until(): one task per batch, all on one thread.
Pure local: the "batches" finish after fixed delays, and the intervals are scaled down (0.02 s instead of 30 s)."""
import asyncio
import random
import time

from poller import apoll_until

FINISH_AFTER = {"batch_a": 0.30, "batch_b": 0.10, "batch_c": 0.55, "batch_d": 0.20}   # seconds, when each "completes"
t0 = time.monotonic()


async def retrieve(batch_id: str) -> dict[str, str]:       # stands in for `await client.batches.retrieve(batch_id)`
    await asyncio.sleep(0.005)                              # a network round trip
    done = time.monotonic() - t0 >= FINISH_AFTER[batch_id]
    return {"id": batch_id, "status": "completed" if done else "in_progress"}


async def wait_for(batch_id: str) -> dict[str, str]:
    return await apoll_until(lambda: retrieve(batch_id), lambda b: b["status"] == "completed",
                             first=0.02, factor=1.5, max_interval=0.2, max_wait=5, rng=random.Random(batch_id))


async def main() -> None:
    finished = []
    for task in asyncio.as_completed([wait_for(b) for b in FINISH_AFTER]):      # one task per batch
        batch = await task
        finished.append(batch["id"])
        print(f"  {time.monotonic() - t0:4.2f} s  {batch['id']} completed")
    print(f"all {len(finished)} done after {time.monotonic() - t0:.2f} s: the slowest batch ({max(FINISH_AFTER.values()):.2f} s) "
          f"plus up to one poll interval, not the sum of all four ({sum(FINISH_AFTER.values()):.2f} s)")

asyncio.run(main())
Output5 lines
  0.12 s  batch_b completed
  0.21 s  batch_d completed
  0.34 s  batch_a completed
  0.70 s  batch_c completed
all 4 done after 0.70 s: the slowest batch (0.55 s) plus up to one poll interval, not the sum of all four (1.15 s)

The four jobs finish in the order they complete, and the whole thing takes about as long as the slowest one (plus up to one poll interval), not the sum. With a real client the fetch is lambda: client.batches.retrieve(batch_id) on an AsyncOpenAI (or client.messages.batches.retrieve on AsyncAnthropic, client.aio.batches.get on Gemini).

6.5 Expiry, partial results and cancellation#

Three end states need explicit handling, and they mean slightly different things on each provider:

What happened What you have What to do
Completed / ended / succeeded The provider finished, but individual requests may still have failed A result for each request: the good ones and the errored ones Join on the ID, validate each result, resubmit the failed ones
Expired The window ended before everything ran Everything that did run (and was billed), plus a marker for the requests that never ran: batch_expired errors on OpenAI, expired results on Anthropic. On Gemini, an expired job "will not have any results to retrieve" Resubmit the missing requests, perhaps in smaller batches (11.4). Expired requests that never ran are not billed
Failed The batch itself was rejected, usually because the input file or request body was invalid Usually nothing ran and nothing was billed; the batch has an error message (OpenAI: errors, with the offending line) Fix the input and submit again
Cancelled You cancelled it Whatever ran before the cancellation, with partial results (Anthropic: "may contain partial results"; OpenAI: the output file) Resubmit what is missing, if you still want it

6.6 The example job used in Parts 7 to 11#

The rest of the lesson uses one running example: classify support tickets into four labels (billing, bug, account, other). Six sample tickets keep the outputs short, and one of them has an ID with characters that Anthropic would reject, on purpose. tickets.py holds the shared pieces: the Ticket type, the deterministic custom_id_for(), and parse_label(), which validates the model's answer (anything other than one of the four words is "unusable"). Save it as tickets.py:

python
"""tickets.py: the example job used throughout Parts 6-11: classify support tickets into four labels."""
import hashlib
import re
from dataclasses import dataclass

CATEGORIES = ("billing", "bug", "account", "other")
INSTRUCTIONS = "Classify the support ticket. Reply with exactly one word: billing, bug, account or other."
_SAFE_ID = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")    # Anthropic's custom_id rule, the strictest of the four


@dataclass(frozen=True)
class Ticket:
    ticket_id: str      # your own primary key, e.g. from the helpdesk database
    text: str


def custom_id_for(ticket: Ticket, job: str = "triage-v1") -> str:
    """Deterministic: the same ticket in the same job always gets the same ID. Never use random IDs."""
    candidate = f"{job}-{ticket.ticket_id}"
    if _SAFE_ID.match(candidate):
        return candidate
    digest = hashlib.sha256(candidate.encode()).hexdigest()[:40]   # unsafe characters or too long: hash it
    return f"{job[:20]}-{digest}"


def parse_label(text: str | None) -> str | None:
    """Validate the model's answer. None means "unusable": treat it as a failure to retry or review."""
    if not text:
        return None
    word = text.strip().strip(".").lower()
    return word if word in CATEGORIES else None


SAMPLE = [
    Ticket("10231", "I was charged twice for my October invoice."),
    Ticket("10232", "The export button crashes the app on Android."),
    Ticket("10233", "How do I change the email address on my account?"),
    Ticket("10234", "Do you have an office in Lisbon?"),
    Ticket("10235", "Refund still not received after 14 days."),
    Ticket("ZD#10236/a", "Login page shows a blank screen in Safari."),   # unsafe characters on purpose
]

Why reasoning={"effort": "none"} in the OpenAI requests and max_tokens: 256 with a low effort on Anthropic and Gemini? The current models think by default, and thinking tokens count against the output cap, so a cap of 16 tokens would be used up before the one-word answer appears (Module 02.8). Luna accepts effort: none; for the other two the lesson leaves room (256) and asks for low effort.


Part 7: The OpenAI Batch API#

7.1 Build the input file and reconcile the results#

OpenAI's Batch API takes a JSONL file ("JSON Lines": one JSON object per line, no commas between lines) uploaded through the Files API. Each line is one complete request:

json
{"custom_id": "triage-v1-10231", "method": "POST", "url": "/v1/responses", "body": {"model": "gpt-6-luna", "input": "...", "max_output_tokens": 16}}
  • custom_id: your ID, unique within the file (6.3).
  • method: always "POST".
  • url: the endpoint, one of /v1/responses, /v1/chat/completions, /v1/embeddings, /v1/completions, /v1/moderations, /v1/images/generations and /v1/images/edits (as of November 2026; the SDK's type also lists /v1/videos). Every line in a file uses the endpoint you pass to batches.create.
  • body: exactly the parameters you would send to that endpoint. For /v1/responses it is a normal responses.create(...) body (model, input, instructions, reasoning, max_output_tokens, tools, structured-output text.format...); for /v1/chat/completions it is a chat body with messages. Responses is the primary API in Module 03 (03.1), so the lesson uses it; a Chat Completions batch differs only in url and body.
  • One model per file. Every line must use the same model. To use two models, make two files and two batches.
  • Streaming has no meaning in a batch: the results come back as files. Don't put stream in the body.

The module below builds that file, downloads the two files you get back and reconciles them. It does what every robust batch job needs: it joins on custom_id, validates the model's answer (a status of incomplete, a refusal, or a label that isn't one of the four words is not a success), decides which failures are worth retrying, keeps each failed request's request_id for a support ticket (03.8, Part 12), reports anything missing from both files, and attaches to each result that ran its usage, converted by 03.7's cost_calc.from_openai_response(..., batch=True) (the response body doesn't say it was a batch, so your code passes that fact in). Three details are about size. download() streams a file to disk with client.files.with_streaming_response.content(...): a 50,000-request output file carries full response bodies and can be hundreds of megabytes, so client.files.content(id).content, which loads it all into memory, is the wrong tool. reconcile() then reads the file line by line instead of calling read_text(), so memory stays flat. And parse is a parameter (the default is the one-word check): 11.3b swaps in a schema.

Save the module as openai_batch_io.py:

python
"""openai_batch_io.py: build an OpenAI Batch API input file, download and reconcile its output and error files.
Formats: https://developers.openai.com/api/docs/guides/batch"""
import json
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path

from openai import OpenAI
from openai.types.responses import Response

from cost_calc import Usage, from_openai_response
from structured import OPENAI_TEXT
from tickets import INSTRUCTIONS, Ticket, custom_id_for, parse_label

MODEL = "gpt-6-luna"


def build_jsonl(tickets: list[Ticket], path: Path, model: str = MODEL, job: str = "triage-v1",
                structured: bool = False) -> dict[str, Ticket]:
    """One line per request. Every line must use the same model. Returns custom_id -> ticket.
    structured=True adds the schema (11.3b); the rest of the body is a normal Responses request."""
    index: dict[str, Ticket] = {}
    with path.open("w", encoding="utf-8") as f:
        for t in tickets:
            cid = custom_id_for(t, job)
            if cid in index:
                raise ValueError(f"duplicate custom_id {cid}")   # custom_ids must be unique in a file
            index[cid] = t
            body: dict = {"model": model, "instructions": INSTRUCTIONS, "input": t.text,
                          "reasoning": {"effort": "none"}, "max_output_tokens": 16}
            if structured:
                body["text"] = OPENAI_TEXT
                body["max_output_tokens"] = 32                   # `{"label":"billing"}` is a few more tokens than a word
            line = {"custom_id": cid, "method": "POST", "url": "/v1/responses", "body": body}
            f.write(json.dumps(line, ensure_ascii=False) + "\n")
    return index


def download(client: OpenAI, file_id: str, path: Path) -> None:
    """Stream a (possibly huge) output file to disk in chunks instead of holding it all in memory:
    `client.files.content(id).content` would load the whole file, and an output file carries full response bodies."""
    with client.files.with_streaming_response.content(file_id) as response:
        response.stream_to_file(path)


def output_text(body: dict) -> str:
    """The same text the SDK's response.output_text gives: every output_text part of every message."""
    return "".join(part.get("text", "") for item in body.get("output", []) if item.get("type") == "message"
                   for part in item.get("content", []) if part.get("type") == "output_text")


def refusal_text(body: dict) -> str | None:
    """A refusal is a 200 whose message has a part of type "refusal" instead of text (structured output or not)."""
    return next((part.get("refusal", "") for item in body.get("output", []) if item.get("type") == "message"
                 for part in item.get("content", []) if part.get("type") == "refusal"), None)


@dataclass
class Result:
    custom_id: str
    status: str                  # "ok", "invalid" (bad answer), "failed" (API error), "expired"
    label: str | None = None
    detail: str = ""             # why it failed, with the request ID when there is one (03.8, Part 12)
    retry: bool = False          # worth resubmitting as-is?
    usage: Usage | None = None   # what it was billed for (03.7's Usage, tier "batch"), when the request ran


def reconcile(output_file: Path | None, error_file: Path | None, expected: set[str],
              parse: Callable[[str | None], str | None] = parse_label) -> dict[str, Result]:
    """Join on custom_id (output order is NOT guaranteed); anything missing is reported too.
    Files are read line by line, so memory stays flat however big they are."""
    results: dict[str, Result] = {}
    for path in (p for p in (output_file, error_file) if p and p.exists()):
        with path.open(encoding="utf-8") as lines:
            for raw in lines:
                line = json.loads(raw)
                cid = line["custom_id"]
                response, error = line.get("response"), line.get("error")
                rid = f" [request_id {response['request_id']}]" if response and response.get("request_id") else ""   # 03.8, Part 12
                if error:                                      # e.g. {"code": "batch_expired", ...}
                    expired = error.get("code") == "batch_expired"
                    results[cid] = Result(cid, "expired" if expired else "failed",
                                          detail=error.get("message", ""), retry=True)
                elif response and response["status_code"] == 200:
                    body = response["body"]                    # a normal Responses API response object
                    usage = from_openai_response(Response.model_validate(body), batch=True)
                    text = output_text(body)
                    refusal = refusal_text(body)
                    if body.get("status") != "completed":      # e.g. "incomplete": hit max_output_tokens
                        results[cid] = Result(cid, "invalid", detail=f"status {body.get('status')}{rid}",
                                              retry=True, usage=usage)
                    elif refusal is not None:                  # it will refuse again: don't resubmit unchanged
                        results[cid] = Result(cid, "invalid", detail=f"refused: {refusal!r}{rid}", usage=usage)
                    elif (label := parse(text)) is None:
                        results[cid] = Result(cid, "invalid", detail=f"unexpected answer {text!r}{rid}", usage=usage)
                    else:
                        results[cid] = Result(cid, "ok", label=label, usage=usage)
                elif response:                                 # a per-request HTTP error, e.g. 400 or 500
                    status = response["status_code"]
                    message = response["body"].get("error", {}).get("message", "")
                    results[cid] = Result(cid, "failed", detail=f"HTTP {status}: {message}{rid}",
                                          retry=status == 429 or status >= 500)
    for cid in expected - results.keys():
        results[cid] = Result(cid, "failed", detail="missing from both files", retry=True)
    return results

The cost arithmetic lives in 03.7, so the job-level report is a few lines on top of cost_calc.price(). batch_cost.py prices each result's Usage (tier batch, which the price table turns into the 0.5 multiplier) and sums them. Save it as batch_cost.py; every lifecycle sample ends by printing its result:

python
"""batch_cost.py: what did a batch job cost? Prices each result's Usage with 03.7's cost_calc (batch tier) and sums.
Under the module's token convention `Usage.input` is UNCACHED input; `Usage.total_input` is every prompt token."""
from collections.abc import Iterable
from dataclasses import dataclass

from cost_calc import Usage, price
from prices import PriceTable


@dataclass
class JobCost:
    usd: float = 0.0
    priced: int = 0            # results that carried usage (they ran, so they are billed)
    unpriced: int = 0          # results with no usage: never ran, or an error (not billed)
    prompt_tokens: int = 0     # every prompt token, cached or not (Usage.total_input)
    output_tokens: int = 0

    def __str__(self) -> str:
        return (f"cost ${self.usd:.6f} for {self.priced} result(s) with usage "
                f"({self.prompt_tokens} prompt + {self.output_tokens} output tokens); {self.unpriced} without usage")


def job_cost(usages: Iterable[Usage | None], table: PriceTable | None = None) -> JobCost:
    table = table or PriceTable.load()                 # prices.yaml next to prices.py (03.7, 4.2)
    total = JobCost()
    for usage in usages:
        if usage is None:
            total.unpriced += 1
            continue
        total.usd += price(usage, table).usd           # tier "batch" -> the 0.5x multiplier from the table
        total.priced += 1
        total.prompt_tokens += usage.total_input
        total.output_tokens += usage.output
    return total

Now run it on real files. The input file is built for real. The output and error files are fixtures, written by hand in the documented line format, deliberately out of order, with one answer that isn't a label, one per-request 400, and one request that expired:

python
"""s7_1_openai_files.py: write a real OpenAI batch input file, then reconcile a FIXTURE output file
and error file (out of order, one invalid answer, one per-request 400, one expired request)."""
import json
from pathlib import Path

from batch_cost import job_cost
from mock_llm import response_body
from openai_batch_io import build_jsonl, reconcile
from tickets import SAMPLE

DATA = Path("data")
index = build_jsonl(SAMPLE, DATA / "openai_input.jsonl")
print("input file:", (DATA / "openai_input.jsonl").stat().st_size, "bytes,", len(index), "lines")
print("first line:", (DATA / "openai_input.jsonl").read_text().splitlines()[0])
ids = list(index)

# FIXTURE: what the Batch API could return, in the documented line format, deliberately out of order
ok = lambda cid, text: {"id": f"batch_req_{cid}", "custom_id": cid, "error": None,
                        "response": {"status_code": 200, "request_id": f"req_{cid}", "body": response_body(text)}}
output_lines = [ok(ids[2], "account"), ok(ids[0], "billing"), ok(ids[1], "Bug."), ok(ids[3], "I think it's other")]
error_lines = [
    {"id": "batch_req_x", "custom_id": ids[4], "error": None,
     "response": {"status_code": 400, "request_id": "req_x",
                  "body": {"error": {"message": "Invalid 'max_output_tokens'", "type": "invalid_request_error"}}}},
    {"id": "batch_req_y", "custom_id": ids[5], "response": None,
     "error": {"code": "batch_expired", "message": "This request could not be executed before the completion window expired."}},
]
(DATA / "openai_output.jsonl").write_text("".join(json.dumps(l) + "\n" for l in output_lines))
(DATA / "openai_errors.jsonl").write_text("".join(json.dumps(l) + "\n" for l in error_lines))

results = reconcile(DATA / "openai_output.jsonl", DATA / "openai_errors.jsonl", expected=set(ids))
for cid in ids:                                   # print in OUR order, not the file's
    r = results[cid]
    print(f"{index[cid].ticket_id:>11} {cid:<38} {r.status:<8} {r.label or '':<8} retry={r.retry!s:<5} {r.detail}")
print(job_cost(r.usage for r in results.values()))     # only results that ran carry usage; errors and expiries cost nothing

Output (the input file is real; the results are the fixture, parsed by the real reconciler):

text
input file: 2013 bytes, 6 lines
first line: {"custom_id": "triage-v1-10231", "method": "POST", "url": "/v1/responses", "body": {"model": "gpt-6-luna", "instructions": "Classify the support ticket. Reply with exactly one word: billing, bug, account or other.", "input": "I was charged twice for my October invoice.", "reasoning": {"effort": "none"}, "max_output_tokens": 16}}
      10231 triage-v1-10231                        ok       billing  retry=False 
      10232 triage-v1-10232                        ok       bug      retry=False 
      10233 triage-v1-10233                        ok       account  retry=False 
      10234 triage-v1-10234                        invalid           retry=False unexpected answer "I think it's other" [request_id req_triage-v1-10234]
      10235 triage-v1-10235                        failed            retry=False HTTP 400: Invalid 'max_output_tokens' [request_id req_x]
 ZD#10236/a triage-v1-dbb60702d5974093b8aa99b4dada38d04670d064 expired           retry=True  This request could not be executed before the completion window expired.
cost $0.000011 for 4 result(s) with usage (160 prompt + 12 output tokens); 2 without usage

Look at four things. The last line is the job's cost: four results carried usage, so four are priced (at the batch rate); the 400 and the expired request never produced tokens. The printed rows are in our order, although the fixture file was in a different one. The sixth ticket, ZD#10236/a, got a hashed ID (triage-v1-dbb6...), because the characters # and / are illegal in the strictest ID format, and index maps it back. And each failure got a different verdict: "I think it's other" is invalid and not retried (the same prompt will produce the same kind of answer; fix the prompt or review it), the 400 is failed and not retried (a bug in the request), and the batch_expired request is retry=True (it never ran).

7.2 Limits and where batches fit in your quotas#

Limit (as of November 2026) Value
Requests per batch 50,000
Input file size 200 MB
Embeddings batches 50,000 embedding inputs across all requests in the batch
Batches you can create 2,000 per hour (OpenAI's guide: "If you need to submit more requests, increase the number of requests per batch.")
Queued tokens A per-model limit on the prompt tokens waiting in batches, shown on your organization's limits page
Completion window "24h" (the only accepted value)
Price 50% of the synchronous price
Rate-limit pool Separate from your per-model limits: using the Batch API "will not consume tokens from your standard per-model rate limits"

The queued-token limit is the one that surprises people. A 50,000-request batch of long prompts can exceed it even though it fits the file limits. OpenAI's guide says only that "each model has a maximum number of prompt tokens that can be queued", points to your limits page for the number, and doesn't say what happens when you go over (no status, no error code). Expect the batch to fail and read batch.errors, but don't assume a size fits: look up the number for your model on the limits page (03.8, 9.2), estimate your batch's input tokens (11.5), and split accordingly (11.4). The lowest tiers can have a limit far below what a 50,000-request batch of long prompts needs.

7.3 The batch object and its statuses#

stateDiagram-v2
    [*] --> validating
    validating --> failed: input file rejected
    validating --> in_progress
    in_progress --> finalizing
    in_progress --> cancelling: you cancel
    in_progress --> expired: 24 h window ends
    finalizing --> completed
    cancelling --> cancelled
    completed --> [*]
    failed --> [*]
    expired --> [*]
    cancelled --> [*]
Status Meaning
validating OpenAI is checking the input file
failed The input file failed validation: nothing ran. The batch's errors list says which lines were wrong
in_progress Running
finalizing Done running; results are being written
completed Results are ready
expired The 24-hour window ended first. Requests that finished are in the output file and are billed; the rest are in the error file with code batch_expired
cancelling You asked to cancel; in-flight requests are finishing (up to 10 minutes)
cancelled Cancelled

Fields you'll use on the Batch object: id, status, request_counts (total, completed, failed), input_file_id, output_file_id, error_file_id, errors, created_at, expires_at, completed_at, and metadata. The SDK's Batch type also has a usage field (input, output and total tokens and details) that the guide doesn't describe, so treat it as informational: it is raw (input_tokens includes cached tokens), so keep counting from the per-request usage in the results, converted by cost_calc, if you need exact per-item numbers and a cost. request_counts counts requests that produced a response (completed) and ones that returned an error (failed); check it against total.

output_file_id and error_file_id are two files. Successful lines go to the output file; lines for requests that failed (a per-request error, or expiry) go to the error file. A batch can have both, either, or (rarely) neither. Both use the same line shape:

json
{"id": "batch_req_...", "custom_id": "triage-v1-10231", "response": {"status_code": 200, "request_id": "req_...", "body": { ...a normal Responses API response... }}, "error": null}

response.body is the same object a synchronous call returns, so you can parse it with the same code. response.status_code is that request's own HTTP status. A request that never ran has response: null and an error such as {"code": "batch_expired", ...}.

7.4 The full lifecycle (provider sample)#

Build, upload, create, poll, download, reconcile, list the failures. This is the complete code for one OpenAI batch:

python
"""s7_5_openai_batch.py: the full OpenAI Batch API lifecycle: build -> upload -> create -> poll ->
download -> reconcile -> list what to retry. Needs OPENAI_API_KEY in .env."""
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI
from openai.types import Batch

from batch_cost import job_cost
from openai_batch_io import build_jsonl, download, reconcile
from poller import poll_until
from tickets import SAMPLE

TERMINAL = {"completed", "failed", "expired", "cancelled"}


def run_openai_batch(client: OpenAI, workdir: Path, poll_first: float = 30.0) -> None:
    workdir.mkdir(exist_ok=True)
    # 1. Build the input file (one model per file; custom_ids derived from our own ticket IDs)
    index = build_jsonl(SAMPLE, workdir / "input.jsonl")

    # 2. Upload it with purpose="batch" (the Files API: lesson 03.6)
    with (workdir / "input.jsonl").open("rb") as f:
        uploaded = client.files.create(file=f, purpose="batch")

    # 3. Create the batch. Save batch.id durably BEFORE anything else: it is your only handle on the job
    batch = client.batches.create(
        input_file_id=uploaded.id, endpoint="/v1/responses", completion_window="24h",
        metadata={"job": "triage-v1", "chunk": "0"},           # searchable later with batches.list()
        output_expires_after={"anchor": "created_at", "seconds": 7 * 24 * 3600},   # 1 hour to 30 days
    )
    (workdir / "batch_id.txt").write_text(batch.id)
    print(f"created {batch.id}: {batch.status}")

    # 4. Poll with growing intervals until a terminal status
    def show(b: Batch, elapsed: float) -> None:
        counts = b.request_counts
        print(f"  {elapsed:6.0f} s  {b.status:<11} "
              f"{counts.completed if counts else 0}/{counts.total if counts else '?'} done, "
              f"{counts.failed if counts else 0} failed")
    batch = poll_until(lambda: client.batches.retrieve(batch.id), lambda b: b.status in TERMINAL,
                       first=poll_first, on_poll=show)

    if batch.status == "failed":                    # the INPUT was rejected: nothing ran, nothing billed
        for err in (batch.errors.data or []) if batch.errors else []:
            print(f"  line {err.line}: {err.code}: {err.message}")
        return

    # 5. Download results promptly (output files are deleted after their expiry). download() streams to disk in
    #    chunks: a 50,000-request output file can be hundreds of megabytes, so never hold it all in memory.
    out_path = err_path = None
    if batch.output_file_id:
        out_path = workdir / "output.jsonl"
        download(client, batch.output_file_id, out_path)
    if batch.error_file_id:
        err_path = workdir / "errors.jsonl"
        download(client, batch.error_file_id, err_path)

    # 6. Reconcile by custom_id, and decide what to retry
    results = reconcile(out_path, err_path, expected=set(index))
    for cid, r in results.items():
        print(f"  {index[cid].ticket_id:>11}  {r.status:<8} {r.label or '':<8} {r.detail}")
    retry = [index[cid] for cid, r in results.items() if r.retry]
    print(f"{batch.status}: {sum(r.status == 'ok' for r in results.values())} ok, {len(retry)} to resubmit")
    print(job_cost(r.usage for r in results.values()))     # per-result usage, priced as batch (03.7's cost_calc)
    if batch.usage:                                        # RAW tokens: input_tokens includes any cached ones
        print(f"batch.usage (raw): {batch.usage.input_tokens} input, {batch.usage.output_tokens} output tokens")


if __name__ == "__main__":
    load_dotenv()
    with OpenAI() as client:
        run_openai_batch(client, Path("openai_batch_run"))

Notes on the choices in it:

  • batches.create arguments. input_file_id and endpoint are required; completion_window must be "24h". metadata (up to 16 key-value pairs, keys up to 64 characters, values up to 512) is searchable only by scanning batches.list(), but it's the way to tag a batch with your batch key, which 11.6 uses to find a batch after a crash.
  • output_expires_after sets when the output and error files are deleted: {"anchor": "created_at", "seconds": ...} with seconds between 3,600 (one hour) and 2,592,000 (30 days). The SDK documents it; the guide only says the output file is deleted after 30 days. Note the SDK's own warning: the anchor is the file's creation time, not the batch's.
  • The batch ID is saved before polling, because it's the only handle you have on a job that may run for hours.
  • failed is handled separately. It means the input was rejected: read batch.errors.data (each item has a line, a code and a message), fix the file and resubmit. Nothing ran.
  • Download promptly, and write to disk before reconciling: download() streams each file in chunks, so a huge output file never has to fit in memory. After the retention period the files are gone.
  • Uploaded files stay in your account until you delete them. After the batch is done and downloaded, client.files.delete(input_file_id) (and the output files, if you don't need them) keeps your file storage tidy (03.6, Part 5).
Example output · illustrative15 lines
created batch_6a0c41e7d2f8819086b3c5e97a1d4f20: validating
       0 s  validating  0/0 done, 0 failed
      31 s  in_progress 0/6 done, 0 failed
      76 s  in_progress 3/6 done, 0 failed
     142 s  finalizing  6/6 done, 0 failed
     243 s  completed   6/6 done, 0 failed
        10231  ok       billing  
        10232  ok       bug      
        10233  ok       account  
        10234  ok       other    
        10235  ok       billing  
   ZD#10236/a  ok       bug      
completed: 6 ok, 0 to resubmit
cost $0.000017 for 6 result(s) with usage (281 prompt + 12 output tokens); 0 without usage
batch.usage (raw): 281 input, 12 output tokens

A six-request batch like this often finishes within minutes, but nothing guarantees it. The last lines are the job's cost, from the per-result usage (the sum of what the six requests were billed), and the raw batch.usage for comparison. It can't run on the local stand-in (Ollama has no Files or Batch endpoints; the call stops with a 404), so it is "not supported locally" and the output above is illustrative, modelled on the mocked run below.

7.5 Try it: the same code against a mock Batch API#

The next sample runs the unchanged run_openai_batch from the previous section against a mock of the Files and Batch endpoints. The real openai SDK builds a real multipart upload, a real batches.create call, real polls, and real streamed downloads; only the server is a mock. The mock walks the batch through validating, in_progress, finalizing and completed; in the output it returns, it shuffles the lines, makes one request return a 500 on its first attempt, and makes one request expire. The mock's job shapes follow the Batch API guide and the Batch object reference:

python
"""mock_openai_batch.py: a MOCK of the OpenAI Files + Batch endpoints, enough for full lifecycles.
Object shapes follow https://developers.openai.com/api/reference/resources/batches and
https://developers.openai.com/api/docs/guides/batch (output/error line formats).
With state_path set, the mock keeps its state in a JSON file, like a real provider that outlives
your process, so a crashed client can come back and find its batches.
Two switches for the demos of 11.6: an input line whose text contains INVALID makes the whole batch fail
validation (status "failed" with `errors`, nothing runs), and a line containing POISON fails with a 500
on EVERY attempt (a request that will never work). The mock also records the most batches open at once."""
import json
import random
import re
from pathlib import Path

import httpx2

from mock_llm import response_body


class MockOpenAIBatches:
    def __init__(self, seed: int = 7, state_path: Path | None = None) -> None:
        self.state_path = state_path
        self.state = {"files": {}, "batches": {}, "polls": {}, "attempts": {}, "next": 1, "peak_open": 0}
        if state_path and state_path.exists():
            self.state = json.loads(state_path.read_text())
        self.rng = random.Random(seed)
        self.requests_seen: list[str] = []

    def _new_id(self, prefix: str) -> str:
        n = self.state["next"]
        self.state["next"] += 1
        return f"{prefix}{n}"

    def _advance(self, batch_id: str) -> dict:
        b = self.state["batches"][batch_id]
        n = self.state["polls"][batch_id] = self.state["polls"].get(batch_id, 0) + 1
        lines = [json.loads(l) for l in self.state["files"][b["input_file_id"]].splitlines()]
        total = len(lines)
        bad = [i for i, l in enumerate(lines, 1) if "INVALID" in json.dumps(l["body"]["input"])]
        if bad and b["status"] not in ("failed",):               # FIXTURE: input validation rejects the whole file
            b["status"] = "validating" if n == 1 else "failed"
            if b["status"] == "failed":
                b["errors"] = {"object": "list", "data": [{"code": "invalid_value", "line": bad[0], "param": "body.input",
                                                           "message": "Invalid value in body.input"}]}
            return b
        if b["status"] not in ("completed", "failed"):
            b["status"] = ["validating", "in_progress", "in_progress", "finalizing"][n - 1] if n <= 4 else "completed"
            done = {1: 0, 2: total // 2, 3: total - 1}.get(n, total)
            b["request_counts"] = {"total": total, "completed": done, "failed": 0}
            if b["status"] == "completed":
                self._write_results(b, lines)
        return b

    def _write_results(self, b: dict, lines: list[dict]) -> None:
        out, err = [], []
        for i, line in enumerate(lines):
            cid = line["custom_id"]
            attempt = self.state["attempts"][cid] = self.state["attempts"].get(cid, 0) + 1
            if "POISON" in json.dumps(line["body"]["input"]) or (i == 1 and attempt == 1):   # FIXTURE: 500s (POISON: always)
                err.append({"id": f"batch_req_{cid}", "custom_id": cid, "error": None,
                            "response": {"status_code": 500, "request_id": f"req_{cid}",
                                         "body": {"error": {"message": "The server had an error", "type": "server_error"}}}})
            elif i == len(lines) - 1 and attempt == 1 and len(lines) > 2:   # FIXTURE: one request never ran
                err.append({"id": f"batch_req_{cid}", "custom_id": cid, "response": None,
                            "error": {"code": "batch_expired", "message": "This request could not be executed before the completion window expired."}})
            else:
                label = ["billing", "bug", "account", "other"][sum(map(ord, cid)) % 4]
                out.append({"id": f"batch_req_{cid}", "custom_id": cid, "error": None,
                            "response": {"status_code": 200, "request_id": f"req_{cid}", "body": response_body(label)}})
        self.rng.shuffle(out)                              # output order is NOT guaranteed
        out_id, err_id = self._new_id("file-out"), self._new_id("file-err")
        self.state["files"][out_id] = "".join(json.dumps(l) + "\n" for l in out)
        self.state["files"][err_id] = "".join(json.dumps(l) + "\n" for l in err)
        b.update(output_file_id=out_id, error_file_id=err_id if err else None, completed_at=1793754000,
                 request_counts={"total": len(lines), "completed": len(out), "failed": len(err)},
                 usage={"input_tokens": 41 * len(out), "output_tokens": 2 * len(out), "total_tokens": 43 * len(out),
                        "input_tokens_details": {"cached_tokens": 0}, "output_tokens_details": {"reasoning_tokens": 0}})

    def handler(self, request: httpx2.Request) -> httpx2.Response:
        try:
            return self._handle(request)
        finally:
            if self.state_path:
                self.state_path.write_text(json.dumps(self.state))

    def _handle(self, request: httpx2.Request) -> httpx2.Response:
        path, method = request.url.path, request.method
        self.requests_seen.append(f"{method} {path}")
        if method == "POST" and path.endswith("/files"):
            body = request.read().decode()               # multipart upload: keep the file part
            jsonl = re.search(r'filename="[^"]*"\r\n(?:[^\r\n]+\r\n)*\r\n(.*?)\r\n--', body, re.S)
            assert jsonl and 'name="purpose"' in body
            file_id = self._new_id("file-in")
            self.state["files"][file_id] = jsonl.group(1)
            return httpx2.Response(200, json={"id": file_id, "object": "file", "bytes": len(jsonl.group(1)),
                                              "created_at": 1793750400, "filename": "input.jsonl",
                                              "purpose": "batch", "status": "processed"})
        if method == "POST" and path.endswith("/batches"):
            params = json.loads(request.content)
            batch = {"id": self._new_id("batch_"), "object": "batch", "endpoint": params["endpoint"],
                     "input_file_id": params["input_file_id"], "completion_window": params["completion_window"],
                     "status": "validating", "created_at": 1793750400 + self.state["next"], "expires_at": 1793836800,
                     "metadata": params.get("metadata"), "output_file_id": None, "error_file_id": None,
                     "request_counts": {"total": 0, "completed": 0, "failed": 0}}
            self.state["batches"][batch["id"]] = batch
            open_now = sum(b["status"] not in ("completed", "failed") for b in self.state["batches"].values())
            self.state["peak_open"] = max(self.state["peak_open"], open_now)
            return httpx2.Response(200, json=batch)
        if method == "GET" and path.endswith("/batches"):          # list, newest first (no filtering)
            data = sorted(self.state["batches"].values(), key=lambda b: -b["created_at"])
            return httpx2.Response(200, json={"object": "list", "data": data, "has_more": False,
                                              "first_id": data[0]["id"] if data else None,
                                              "last_id": data[-1]["id"] if data else None})
        if method == "GET" and (m := re.search(r"/batches/([^/]+)$", path)):
            return httpx2.Response(200, json=self._advance(m.group(1)))
        if method == "GET" and (m := re.search(r"/files/([^/]+)/content$", path)):
            return httpx2.Response(200, content=self.state["files"][m.group(1)].encode())
        return httpx2.Response(404, json={"error": {"message": f"mock has no {method} {path}"}})
python
"""s7_6_openai_batch_mock.py: run the unchanged lifecycle from s7_5 against a MOCK Batch API."""
from pathlib import Path

import httpx2
from openai import OpenAI

from mock_openai_batch import MockOpenAIBatches
from s7_5_openai_batch import run_openai_batch

mock = MockOpenAIBatches()
client = OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(mock.handler)))
run_openai_batch(client, Path("data/openai_mock_run"), poll_first=0.01)
print("HTTP calls the SDK made:", ", ".join(dict.fromkeys(mock.requests_seen)))
Output · mock server, so 0 s for every poll16 lines
created batch_2: validating
       0 s  validating  0/6 done, 0 failed
       0 s  in_progress 3/6 done, 0 failed
       0 s  in_progress 5/6 done, 0 failed
       0 s  finalizing  6/6 done, 0 failed
       0 s  completed   4/6 done, 2 failed
        10235  ok       billing  
        10233  ok       account  
        10231  ok       billing  
        10234  ok       other    
        10232  failed            HTTP 500: The server had an error [request_id req_triage-v1-10232]
   ZD#10236/a  expired           This request could not be executed before the completion window expired.
completed: 4 ok, 2 to resubmit
cost $0.000011 for 4 result(s) with usage (160 prompt + 12 output tokens); 2 without usage
batch.usage (raw): 164 input, 8 output tokens
HTTP calls the SDK made: POST /v1/files, POST /v1/batches, GET /v1/batches/batch_2, GET /v1/files/file-out3/content, GET /v1/files/file-err4/content

The mock server's replies (the 500 and the expiry) are fixtures; what the output proves is that the real SDK and our code handle the protocol correctly: the order of calls (upload, create, retrieve ×5, two streamed downloads), the status progression, the shuffled lines being joined by custom_id, the two failures being listed for resubmission, and the cost being summed from the four results that ran. The last line shows the SDK made exactly five kinds of HTTP calls.

7.6 More OpenAI specifics#

  • Webhooks. OpenAI can send batch.completed, batch.failed, batch.expired and batch.cancelled events to a URL you register, so you don't have to poll (13.6).
  • Cancelling. client.batches.cancel(batch_id) moves it to cancelling, then cancelled (up to 10 minutes). Requests that finished before the cancellation are in the output file, and are billed.
  • Listing. client.batches.list(limit=...) pages through batches newest first (cursor after). You can't filter by metadata, so a recovery routine scans.
  • Prompt caching and batches. Caching discounts apply; hits are less predictable because requests run in any order. See 03.7.
  • No streaming, no background. A batch request is a plain request.
  • Billing. Batch is billed at 50%. The response body doesn't say it was a batch, so your code has to know from context: from_openai_response(response, batch=True) and from_openai_chat(completion, batch=True) in 03.7's cost_calc take that flag, as the reconciler above does, and only requests that ran (those with a response body) are billed.
  • Structured output and tools work in batch requests, because the body is a normal request body: OpenAI's structured-outputs guide lists the Batch API among the APIs that support it (03.4, 03.5; the classifier as a schema is 11.3b). A tool-calling batch returns the model's requests to call tools, not tool results: running an agent loop through a Batch API means one batch per turn, which is rarely worth it.

Part 8: The Anthropic Message Batches API#

Deep-dive

8.1 Build the requests and reconcile the results#

Anthropic's batch interface is simpler to submit than OpenAI's: there is no file to upload. You pass a list of requests to client.messages.batches.create(requests=[...]). Each request is:

  • custom_id: 1 to 64 characters, matching ^[a-zA-Z0-9_-]{1,64}$, unique within the batch (6.3).
  • params: a normal Messages API request (model, max_tokens, messages, system, tools, output_config, thinking settings, and so on). Because each request carries its own model, one batch can mix models and request types: "Because each request in the batch is processed independently, you can mix different types of requests within a single batch."

Almost any Messages feature works inside a batch: vision, tool use (including the server tools such as web search), system prompts, multi-turn conversations, extended thinking, structured outputs and most beta features. Four parameters are not allowed, and including any of them "returns a validation error":

Not allowed in a batch Why
stream: true Results come back as one file, not a stream
speed (fast mode) Fast mode tunes synchronous latency, which doesn't apply to asynchronous work
fallbacks (server-side fallback) Doesn't apply to batches; the refusals guide describes how to retry refused batch requests yourself
max_tokens: 0 (cache pre-warming) A cache entry written during batch processing would likely expire before the follow-up request runs. Every batched request needs max_tokens of at least 1

The module below builds the requests and reconciles the results the same way the OpenAI one does. Anthropic's four result types map onto our statuses: succeeded (validate the content and the stop_reason), errored (read result.error.error.type: invalid_request_error means fix the request, anything else, such as overloaded_error or api_error, can be retried), and canceled and expired (the request never reached the model: retry). Save it as anthropic_batch_io.py:

python
"""anthropic_batch_io.py: build Message Batch requests, save streamed results to JSONL, reconcile them.
Formats: https://platform.claude.com/docs/en/build-with-claude/batch-processing"""
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from pathlib import Path

from anthropic.types import OutputConfigParam
from anthropic.types.messages import MessageBatchIndividualResponse
from anthropic.types.messages.batch_create_params import Request

from cost_calc import Usage, from_anthropic
from structured import ANTHROPIC_FORMAT
from tickets import INSTRUCTIONS, Ticket, custom_id_for, parse_label

MODEL = "claude-haiku-5-5"


def build_requests(tickets: list[Ticket], model: str = MODEL, job: str = "triage-v1",
                   structured: bool = False) -> tuple[list[Request], dict[str, Ticket]]:
    """Each request is {custom_id, params}; params are normal Messages API parameters.
    Not allowed inside a batch: stream, speed, fallbacks, max_tokens=0. structured=True adds the schema (11.3b)."""
    requests: list[Request] = []
    index: dict[str, Ticket] = {}
    for t in tickets:
        cid = custom_id_for(t, job)                  # must match ^[a-zA-Z0-9_-]{1,64}$
        if cid in index:
            raise ValueError(f"duplicate custom_id {cid}")
        index[cid] = t
        output_config: OutputConfigParam = {"effort": "low", "format": ANTHROPIC_FORMAT} if structured else {"effort": "low"}
        requests.append({"custom_id": cid, "params": {
            "model": model, "max_tokens": 256,         # room for adaptive thinking plus a one-word answer
            "system": INSTRUCTIONS, "output_config": output_config,
            "messages": [{"role": "user", "content": t.text}]}})
    return requests, index


def save_results(results: Iterable[MessageBatchIndividualResponse], path: Path) -> int:
    """Stream results to disk FIRST (they expire after 29 days), then process the file."""
    n = 0
    with path.open("w", encoding="utf-8") as f:
        for r in results:
            f.write(r.model_dump_json() + "\n")
            n += 1
    return n


@dataclass
class Result:
    custom_id: str
    status: str                  # "ok", "invalid", "errored", "canceled", "expired"
    label: str | None = None
    detail: str = ""
    retry: bool = False
    usage: Usage | None = None   # what it was billed for (03.7's Usage, tier "batch"), when the request ran


def reconcile(path: Path, expected: set[str],
              parse: Callable[[str | None], str | None] = parse_label) -> dict[str, Result]:
    results: dict[str, Result] = {}
    with path.open(encoding="utf-8") as lines:     # line by line: the file can be big
        for raw in lines:
            line = MessageBatchIndividualResponse.model_validate_json(raw)
            cid, outcome = line.custom_id, line.result
            if outcome.type == "succeeded":            # the only result type you are billed for
                message = outcome.message
                usage = from_anthropic(message)
                usage.tier = "batch"                   # a batch result bills at the batch rate; we know that from context
                text = "".join(b.text for b in message.content if b.type == "text")
                if message.stop_reason == "refusal":   # it will refuse again: don't resubmit unchanged
                    results[cid] = Result(cid, "invalid", detail="refused", usage=usage)
                elif message.stop_reason != "end_turn":   # e.g. "max_tokens": truncated
                    results[cid] = Result(cid, "invalid", detail=f"stop_reason {message.stop_reason}",
                                          retry=True, usage=usage)
                elif (label := parse(text)) is None:
                    results[cid] = Result(cid, "invalid", detail=f"unexpected answer {text!r}", usage=usage)
                else:
                    results[cid] = Result(cid, "ok", label=label, usage=usage)
            elif outcome.type == "errored":
                error = outcome.error.error             # the standard error shape: type and message
                fix_first = error.type == "invalid_request_error"   # retrying unchanged would fail again
                rid = f" [request_id {outcome.error.request_id}]" if outcome.error.request_id else ""   # for a support ticket
                results[cid] = Result(cid, "errored", detail=f"{error.type}: {error.message}{rid}",
                                      retry=not fix_first)
            else:                                       # "canceled" or "expired": never ran, not billed
                results[cid] = Result(cid, outcome.type, retry=True)
    for cid in expected - results.keys():
        results[cid] = Result(cid, "errored", detail="missing from results", retry=True)
    return results

Some details in it:

  • Typed requests. Request is the SDK's TypedDict, so pyright checks the keys of params. The documentation example builds Request(custom_id=..., params=MessageCreateParamsNonStreaming(...)); a plain dict with the same keys is equivalent.
  • save_results writes the stream to disk first. batches.results() returns a decoder that reads JSONL lazily from the response, so results aren't held in memory, and each line is a MessageBatchIndividualResponse object. Results are available for 29 days, so persisting them locally is how you avoid a lost-results bug.
  • outcome.error.error.type really is nested twice: the result's error is an error response (type: "error"), and the actual error is inside it.
  • stop_reason is checked. max_tokens means the answer was cut off; end_turn is the normal ending. refusal and other values need handling too (03.8, Part 10).

Real request building, with a fixture results file in the documented line format (out of order, one truncated answer, one invalid answer, one errored request and one expired one):

python
"""s8_1_anthropic_files.py: build real Message Batch requests, then reconcile a FIXTURE results file
(out of order, one invalid answer, one truncated, one errored, one expired)."""
import json
import tempfile
from pathlib import Path

from anthropic.types.messages import MessageBatchIndividualResponse

from anthropic_batch_io import MODEL, build_requests, reconcile
from batch_cost import job_cost
from cost_tracker import CostTracker
from prices import PriceTable
from tickets import SAMPLE

requests, index = build_requests(SAMPLE)
print(f"{len(requests)} requests, {len(json.dumps(requests))} bytes; first:")
print(json.dumps(requests[0]))
ids = list(index)


def message(text: str, stop_reason: str = "end_turn") -> dict:   # the documented Message shape
    return {"id": "msg_01", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
            "content": [{"type": "text", "text": text}], "stop_reason": stop_reason, "stop_sequence": None,
            "usage": {"input_tokens": 38, "output_tokens": 2}}

# FIXTURE: the documented results.jsonl line format, deliberately out of order
lines = [
    {"custom_id": ids[3], "result": {"type": "succeeded", "message": message("Other")}},
    {"custom_id": ids[0], "result": {"type": "succeeded", "message": message("billing")}},
    {"custom_id": ids[2], "result": {"type": "succeeded", "message": message("Account question", "max_tokens")}},
    {"custom_id": ids[1], "result": {"type": "succeeded", "message": message("bug")}},
    {"custom_id": ids[4], "result": {"type": "errored", "error": {"type": "error", "error": {
        "type": "invalid_request_error", "message": "max_tokens: must be at least 1"}}}},
    {"custom_id": ids[5], "result": {"type": "expired"}},
]
path = Path("data/anthropic_results.jsonl")
path.write_text("".join(json.dumps(l) + "\n" for l in lines))

results = reconcile(path, set(ids))
for cid, r in sorted(results.items(), key=lambda kv: ids.index(kv[0])):
    print(f"{index[cid].ticket_id:>11}  {r.status:<8} {r.label or '':<8} retry={r.retry!s:<5} {r.detail}")
print(job_cost(r.usage for r in results.values()))     # errored, canceled and expired requests are not billed


# The long-term record (03.7, 5.8): one tracker.record(..., batch=True) per result that ran. The message body
# doesn't say it came from a batch, so we do; without batch=True the same tokens would be priced at the standard rate.
tracker = CostTracker(PriceTable.load(), Path(tempfile.mkdtemp()) / "calls.jsonl", env="demo")
for raw in path.read_text().splitlines():
    line = MessageBatchIndividualResponse.model_validate_json(raw)
    if line.result.type == "succeeded":
        rec = tracker.record(provider="anthropic", model=MODEL, response=line.result.message, feature="triage-batch",
                             batch=True)
        print(f"{line.custom_id:<22} tier={rec.tier} batch={rec.batch} cost=${rec.cost_usd:.7f} status={rec.status}")
print("tracker total:", f"${sum(json.loads(x)['cost_usd'] for x in tracker.sink.read_text().splitlines()):.6f}")

Output (the requests are real; the results are the fixture, parsed by the real SDK models):

text
6 requests, 1965 bytes; first:
{"custom_id": "triage-v1-10231", "params": {"model": "claude-haiku-5-5", "max_tokens": 256, "system": "Classify the support ticket. Reply with exactly one word: billing, bug, account or other.", "output_config": {"effort": "low"}, "messages": [{"role": "user", "content": "I was charged twice for my October invoice."}]}}
      10231  ok       billing  retry=False 
      10232  ok       bug      retry=False 
      10233  invalid           retry=True  stop_reason max_tokens
      10234  ok       other    retry=False 
      10235  errored           retry=False invalid_request_error: max_tokens: must be at least 1
 ZD#10236/a  expired           retry=True  
cost $0.000010 for 4 result(s) with usage (152 prompt + 8 output tokens); 2 without usage
triage-v1-10234        tier=batch batch=True cost=$0.0000024 status=ok
triage-v1-10231        tier=batch batch=True cost=$0.0000024 status=ok
triage-v1-10233        tier=batch batch=True cost=$0.0000024 status=truncated
triage-v1-10232        tier=batch batch=True cost=$0.0000024 status=ok
tracker total: $0.000010

The four lines after the cost are the tracker integration (03.7, 5.8): for each result that ran, the sample calls tracker.record(provider="anthropic", model=MODEL, response=message, feature="triage-batch", batch=True). The Message inside a batch result carries no sign that it came from a batch, so batch=True is how your code says so; the tracker then prices it at the batch rate and appends one JSON line to its log (each record shows tier=batch, and the truncated answer is status=truncated even though it is billed). Its total, $0.000010, matches job_cost above it, which is the check that the two paths agree. If you wrap the call itself, the same flag works on the context manager: with tracker.track(..., batch=True) as call:. A request that errored or expired has no message to record, so it gets no line.

The ZD#10236/a ticket again got its hashed ID. Note which failures are worth retrying: the truncated answer (retry with a larger max_tokens, not unchanged), the expired request (never ran), but not the invalid_request_error (fix the request) and not the wrong-format answer (fix the prompt). The last line is the job's cost: each succeeded message's usage goes through 03.7's from_anthropic and is priced at the batch rate (the reconciler sets the tier from context, because a batch result is billed as batch whatever else the body says). The errored and expired requests carry no usage and, as 8.2 says, aren't billed. When an errored result carries a request_id, the reconciler keeps it in detail.

8.2 Limits, statuses and results#

Limit (as of November 2026) Value
Requests per batch 100,000, or 256 MB, whichever is reached first (a larger body gets a 413 request_too_large)
Time "most batches finishing in less than 1 hour"; a batch expires if not finished within 24 hours
Results kept 29 days after the batch's creation (not its end). After that you can still view the batch, but not download results
Scope A batch belongs to a Workspace; only requests for the same workspace see it
Price 50% of standard prices for input, output and special tokens
Zero data retention Not eligible: batch data is stored for 29 days
Spending cap Batches "may go slightly over" the spend limit set for the workspace, because of high concurrent throughput

Batch rate limits are separate from your Messages API limits, and by design a batch doesn't touch your live quotas ("Usage of the Batches API does not affect rate limits in the Messages API"). Three numbers apply, per usage tier. As of November 2026 for the Start, Build and Scale tiers: HTTP requests per minute to the batch endpoints (1,000, 2,000 and 4,000), batch requests in the processing queue (200,000, 300,000 and 500,000), and requests per batch (100,000 for all three). The queue limit counts every request in every batch that hasn't been processed yet, so two 100,000-request batches fill a Start-tier queue. Look up your own tier's numbers on Anthropic's rate-limit page and in the Console.

Statuses. processing_status is in_progress while any request is still processing, canceling after you asked to cancel, and ended when every request has a result. The batch object also has request_counts (processing, succeeded, errored, canceled, expired), created_at, expires_at (24 hours after creation), ended_at, cancel_initiated_at and results_url. Unlike OpenAI there is no separate "failed" or "expired" batch status: the batch just ends, and each request carries its own outcome. Billing is on the succeeded ones only: errored, canceled and expired requests "will not be billed".

Results are retrieved with client.messages.batches.results(batch_id) once the status is ended. Each streamed line looks like {"custom_id": "...", "result": {"type": "succeeded", "message": {...}}}, and the message is a normal Message (content blocks, stop_reason, usage). With the async client the call is awaited first: async for r in await client.messages.batches.results(id).

8.3 The full lifecycle (provider sample)#

python
"""s8_4_anthropic_batch.py: the full Message Batches lifecycle: build -> create -> poll ->
stream results to disk -> reconcile -> list what to retry. Needs ANTHROPIC_API_KEY in .env."""
from pathlib import Path

import anthropic
from anthropic.types.messages import MessageBatch
from dotenv import load_dotenv

from anthropic_batch_io import build_requests, reconcile, save_results
from batch_cost import job_cost
from poller import poll_until
from tickets import SAMPLE


def run_anthropic_batch(client: anthropic.Anthropic, workdir: Path, poll_first: float = 30.0) -> None:
    workdir.mkdir(exist_ok=True)
    requests, index = build_requests(SAMPLE)               # 1. build (100,000 requests / 256 MB max)

    batch = client.messages.batches.create(requests=requests)   # 2. create: no file upload needed
    (workdir / "batch_id.txt").write_text(batch.id)        # save the handle before anything else
    print(f"created {batch.id}: {batch.processing_status}, expires {batch.expires_at:%Y-%m-%d %H:%M} UTC")

    def show(b: MessageBatch, elapsed: float) -> None:     # 3. poll: in_progress -> (canceling) -> ended
        c = b.request_counts
        print(f"  {elapsed:6.0f} s  {b.processing_status:<11} processing={c.processing} "
              f"succeeded={c.succeeded} errored={c.errored} canceled={c.canceled} expired={c.expired}")
    batch = poll_until(lambda: client.messages.batches.retrieve(batch.id),
                       lambda b: b.processing_status == "ended", first=poll_first, on_poll=show)

    # 4. Stream the results to a local file first (kept 29 days after creation), then reconcile
    path = workdir / "results.jsonl"
    save_results(client.messages.batches.results(batch.id), path)
    results = reconcile(path, expected=set(index))
    for cid, r in results.items():
        print(f"  {index[cid].ticket_id:>11}  {r.status:<8} {r.label or '':<8} {r.detail}")
    retry = [cid for cid, r in results.items() if r.retry]
    print(f"ended: {sum(r.status == 'ok' for r in results.values())} ok, {len(retry)} to resubmit")
    print(job_cost(r.usage for r in results.values()))     # per-result usage, priced as batch (03.7's cost_calc)

    # 5. Optional: delete the batch (and its stored inputs/outputs) once your copy is safe
    client.messages.batches.delete(batch.id)


if __name__ == "__main__":
    load_dotenv()
    with anthropic.Anthropic() as client:
        run_anthropic_batch(client, Path("anthropic_batch_run"))
Example output · illustrative13 lines
created msgbatch_01Rk2mXq8d7YtZpV3nHc9aWs: in_progress, expires 2026-11-05 09:14 UTC
       0 s  in_progress processing=6 succeeded=0 errored=0 canceled=0 expired=0
      33 s  in_progress processing=6 succeeded=0 errored=0 canceled=0 expired=0
      81 s  in_progress processing=2 succeeded=4 errored=0 canceled=0 expired=0
     149 s  ended       processing=0 succeeded=6 errored=0 canceled=0 expired=0
        10233  ok       account  
        10231  ok       billing  
        10235  ok       billing  
        10232  ok       bug      
   ZD#10236/a  ok       bug      
        10234  ok       other    
ended: 6 ok, 0 to resubmit
cost $0.000049 for 6 result(s) with usage (228 prompt + 150 output tokens); 0 without usage

Against the local stand-in it fails with a 404 (Ollama has no /v1/messages/batches), so it is "not supported locally"; the mocked run below exercises the same code with the real SDK. Points to notice:

  • No upload step, and no output files: create returns at once with in_progress, and the results are streamed from the API.
  • expires_at is printed so the log shows the deadline (24 hours after creation).
  • batches.delete removes the batch and its stored results once your own copy is safe. Anthropic's rule: a batch "can only be deleted once they've finished processing"; to delete an in-progress batch, cancel it first. Deleting is optional (results are removed after 29 days anyway), and it's the right thing when the inputs are sensitive.
  • Cancelling: client.messages.batches.cancel(id) sets processing_status to canceling immediately, and later to ended, with partial results for the requests that finished first ("cancellation might not take immediate effect"). You can't edit a submitted batch: cancel it and submit a new one.

8.4 Try it: the same code against a mock Batches API#

The mocked server below answers create, retrieve, results and delete, walks the batch through in_progress twice and then ended, shuffles the results, and makes request number 3 come back errored with an overloaded_error. Shapes follow the Create a Message Batch reference and the batch guide's results examples:

python
"""mock_anthropic_batch.py: a MOCK of the Message Batches endpoints (create, retrieve, results, delete).
Shapes follow https://platform.claude.com/docs/en/api/messages/batches/create and the batch guide."""
import json
import random
import re

import httpx2


class MockAnthropicBatches:
    def __init__(self, seed: int = 3) -> None:
        self.requests: list[dict] = []
        self.polls = 0
        self.rng = random.Random(seed)
        self.seen: list[str] = []

    def _batch(self, status: str, counts: dict) -> dict:
        return {"id": "msgbatch_mock1", "type": "message_batch", "processing_status": status,
                "request_counts": counts, "created_at": "2026-11-04T09:00:00Z",
                "expires_at": "2026-11-05T09:00:00Z", "ended_at": None if status != "ended" else "2026-11-04T09:41:00Z",
                "cancel_initiated_at": None, "archived_at": None,
                "results_url": "https://api.anthropic.com/v1/messages/batches/msgbatch_mock1/results" if status == "ended" else None}

    def _results(self) -> bytes:
        lines = []
        for i, r in enumerate(self.requests):
            cid = r["custom_id"]
            if i == 2:                                     # FIXTURE: an API-side error for one request
                result = {"type": "errored", "error": {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}}
            else:
                label = ["billing", "bug", "account", "other"][i % 4]
                result = {"type": "succeeded", "message": {
                    "id": f"msg_{i}", "type": "message", "role": "assistant", "model": r["params"]["model"],
                    "content": [{"type": "text", "text": label}], "stop_reason": "end_turn", "stop_sequence": None,
                    "usage": {"input_tokens": 38, "output_tokens": 2}}}
            lines.append({"custom_id": cid, "result": result})
        self.rng.shuffle(lines)                            # results come back in any order
        return "".join(json.dumps(l) + "\n" for l in lines).encode()

    def handler(self, request: httpx2.Request) -> httpx2.Response:
        path, method = request.url.path, request.method
        self.seen.append(f"{method} {path}")
        n = len(self.requests)
        if method == "POST" and path == "/v1/messages/batches":
            self.requests = json.loads(request.content)["requests"]
            counts = {"processing": len(self.requests), "succeeded": 0, "errored": 0, "canceled": 0, "expired": 0}
            return httpx2.Response(200, json=self._batch("in_progress", counts))
        if method == "GET" and re.fullmatch(r"/v1/messages/batches/[^/]+", path):
            self.polls += 1
            if self.polls < 3:
                done = (n // 2) * (self.polls - 1)
                counts = {"processing": n - done, "succeeded": done, "errored": 0, "canceled": 0, "expired": 0}
                return httpx2.Response(200, json=self._batch("in_progress", counts))
            counts = {"processing": 0, "succeeded": n - 1, "errored": 1, "canceled": 0, "expired": 0}
            return httpx2.Response(200, json=self._batch("ended", counts))
        if method == "GET" and path.endswith("/results"):
            return httpx2.Response(200, content=self._results())
        if method == "DELETE":
            return httpx2.Response(200, json={"id": "msgbatch_mock1", "type": "message_batch_deleted"})
        return httpx2.Response(404, json={"type": "error", "error": {"type": "not_found_error", "message": path}})
python
"""s8_5_anthropic_batch_mock.py: run the unchanged lifecycle from s8_4 against a MOCK Batches API."""
from pathlib import Path

import anthropic
import httpx2

from mock_anthropic_batch import MockAnthropicBatches
from s8_4_anthropic_batch import run_anthropic_batch

mock = MockAnthropicBatches()
client = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(mock.handler)))
run_anthropic_batch(client, Path("data/anthropic_mock_run"), poll_first=0.01)
print("HTTP calls the SDK made:", ", ".join(dict.fromkeys(mock.seen)))
Output · mock server13 lines
created msgbatch_mock1: in_progress, expires 2026-11-05 09:00 UTC
       0 s  in_progress processing=6 succeeded=0 errored=0 canceled=0 expired=0
       0 s  in_progress processing=3 succeeded=3 errored=0 canceled=0 expired=0
       0 s  ended       processing=0 succeeded=5 errored=1 canceled=0 expired=0
        10231  ok       billing  
        10233  errored           overloaded_error: Overloaded
        10234  ok       other    
   ZD#10236/a  ok       bug      
        10235  ok       billing  
        10232  ok       bug      
ended: 5 ok, 1 to resubmit
cost $0.000012 for 5 result(s) with usage (190 prompt + 10 output tokens); 1 without usage
HTTP calls the SDK made: POST /v1/messages/batches, GET /v1/messages/batches/msgbatch_mock1, GET /v1/messages/batches/msgbatch_mock1/results, DELETE /v1/messages/batches/msgbatch_mock1

The real SDK made the four calls in the last line, parsed the JSONL results into MessageBatchIndividualResponse objects, and our reconciler joined them on custom_id: five succeeded, one errored with a retryable overloaded_error, listed for resubmission.

8.5 More Anthropic specifics#

  • Prompt caching in a batch. Caching works and the discounts stack, but cache hits are "best-effort" because requests run concurrently and in any order ("typical hit rates range from 30 percent to 98 percent"). To raise the odds: put identical cache_control blocks in every request, and use the 1-hour cache duration ("ttl": "1h"): Anthropic's batch-processing page recommends it for batches with shared context, "because batches can take longer than 5 minutes to process" (Batch processing, prompt caching in batches; the option itself is on the prompt-caching page; 1-hour cache writes cost 2x the base input price, against 1.25x for 5 minutes). Anthropic's recommended pattern is to send one request with the shared prefix first, wait for it, then submit the rest; 03.7, 6.6 covers it.
  • Extended output (beta). The output-300k-2026-03-24 beta header raises the max_tokens cap to 300,000 for batch requests on some models (Opus 5.5, Opus 5, Sonnet 5.5 and Haiku 5.5 among them), and it works on the Message Batches API only: use client.beta.messages.batches.create(betas=["output-300k-2026-03-24"], requests=[...]). A single 300k-token generation can take over an hour, so plan for the 24-hour window. Check the batch guide for the current model list.
  • Server tools (web search, web fetch, code execution) work in batches, and the batch loop may run more iterations per turn before returning stop_reason: "pause_turn". If a result has pause_turn, the turn did not finish: continue it with a follow-up request. Web search is throttled per organization inside batches, so big web-search batches may take longer.
  • API version. "Batch results use the API version of the request that created the batch": the SDK sends anthropic-version: 2026-10-21, so the results follow that version's shapes.
  • No webhooks for batches. Anthropic's webhooks don't include Message Batches (as of November 2026), so poll (6.4). The webhooks that exist are Managed Agents webhooks (beta, for sessions, agents, deployments and the like) and organization webhooks (an Admin API beta, by request, for two user-profile enforcement events that Anthropic says it isn't sending yet). Neither tells you a batch has ended; 13.6 has the details and what Anthropic's delivery rules (3 attempts, then the event is dropped) mean for a poll-plus-webhook design.
  • Cloud platforms. The Batch API is also available on Claude Platform on AWS and Claude Models on Google Cloud (Anthropic managed); the Managed Agents product has no batch interface.
  • Two optional arguments. create also accepts workspace_id and user_profile_id, for credentials that can act in more than one workspace and for attributing a batch to a party other than your organization. Most projects never need them.

Part 9: The Gemini Batch API#

Reference

9.1 Build the requests and reconcile the results#

Gemini gives you two ways to submit, and picks the output form from your choice of input:

Inline requests Input file
What you pass src=[...]: a list of request dicts src="files/abc123": the name of a JSONL file you uploaded with the Files API
Size limit "keep the total request size under 20MB" 2 GB per file
Request shape {"contents": [...], "config": {...}, "metadata": {...}} (SDK InlinedRequest) {"key": "...", "request": {...}} per line, where request is a GenerateContentRequest in REST field names
Your ID The metadata dict you attach (the SDK echoes it on the result) key
Results job.dest.inlined_responses: a list of InlinedResponse (response, error, metadata) job.dest.file_name: a results file; download it with client.files.download(file=...)
Best for Tens to a few thousand small requests Anything big, and anything with images or documents you reference by file

Per-request configuration (system instructions, tools, structured output, thinking level, cached_content) goes inside each request, so requests in one job may differ, but the model is fixed per job (model= of batches.create).

Google's batch guide says nothing about the order of results: it only says that the key "is used in the response to indicate which output is the result of which request". The REST reference does: responsesFile says "The responses will be written in the same order as the input requests" and inlinedResponses says "The responses will be in the same order as the input requests" (checked against the reference on 4 November 2026). Don't rely on it. The other providers explicitly say order isn't guaranteed, the guide that people actually read doesn't promise it, a retry or a failed line might shift positions, and it costs nothing to join on the key. The module below always does: key for files, the metadata["key"] we attached for inline results. It handles both forms and checks the finish reason of every response. Save it as gemini_batch_io.py:

python
"""gemini_batch_io.py: build Gemini Batch API requests (inline or JSONL file) and reconcile results.
Formats: https://aistudio.google.com/docs/batch-api . The Batch API is generateContent-only."""
import json
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path

from google.genai import types

from cost_calc import Usage, from_gemini
from structured import GEMINI_GENERATION_CONFIG
from tickets import INSTRUCTIONS, Ticket, custom_id_for, parse_label

MODEL = "gemini-3.8-flash"
CONFIG = {"max_output_tokens": 256,                       # room for thinking plus a one-word answer
          "thinking_config": {"thinking_level": "low"}}  # "minimal" is not supported on 3.8 Flash


def build_jsonl(tickets: list[Ticket], path: Path, job: str = "triage-v1",
                structured: bool = False) -> dict[str, Ticket]:
    """File input: one {"key", "request"} per line, request = a GenerateContentRequest (REST field names).
    structured=True adds the schema (11.3b)."""
    index: dict[str, Ticket] = {}
    with path.open("w", encoding="utf-8") as f:
        for t in tickets:
            key = custom_id_for(t, job)
            index[key] = t
            request = {"contents": [{"role": "user", "parts": [{"text": t.text}]}],
                       "system_instruction": {"parts": [{"text": INSTRUCTIONS}]},
                       "generation_config": {**CONFIG, **(GEMINI_GENERATION_CONFIG if structured else {})}}
            f.write(json.dumps({"key": key, "request": request}, ensure_ascii=False) + "\n")
    return index


def build_inline(tickets: list[Ticket], job: str = "triage-v1",
                 structured: bool = False) -> tuple[list[types.InlinedRequestDict], dict[str, Ticket]]:
    """Inline input (total under 20 MB): SDK-style requests, each tagged with our key in metadata."""
    index = {custom_id_for(t, job): t for t in tickets}
    schema: types.GenerateContentConfigDict = (
        {"response_mime_type": "application/json", "response_json_schema": GEMINI_GENERATION_CONFIG["response_json_schema"]}
        if structured else {})
    requests: list[types.InlinedRequestDict] = [
        {"contents": [{"role": "user", "parts": [{"text": t.text}]}],
         "config": {"system_instruction": INSTRUCTIONS, "max_output_tokens": 256,
                    "thinking_config": {"thinking_level": types.ThinkingLevel.LOW}, **schema},
         "metadata": {"key": key}}
        for key, t in index.items()]
    return requests, index


@dataclass
class Result:
    key: str
    status: str                  # "ok", "invalid", "failed"
    label: str | None = None
    detail: str = ""
    retry: bool = False
    usage: Usage | None = None   # what it was billed for (03.7's Usage, tier "batch"), when the request ran


def _judge(key: str, response: types.GenerateContentResponse,
           parse: Callable[[str | None], str | None] = parse_label) -> Result:
    usage = from_gemini(response, MODEL, batch=True) if response.usage_metadata else None
    candidate = (response.candidates or [None])[0]
    reason = candidate.finish_reason if candidate else None
    if reason != types.FinishReason.STOP:                  # MAX_TOKENS, SAFETY, no candidate...
        return Result(key, "invalid", detail=f"finish_reason {reason}", usage=usage,
                      retry=reason == types.FinishReason.MAX_TOKENS)
    label = parse(response.text)
    if label is None:
        return Result(key, "invalid", detail=f"unexpected answer {response.text!r}", usage=usage)
    return Result(key, "ok", label=label, usage=usage)


def reconcile_file(path: Path, expected: set[str],
                   parse: Callable[[str | None], str | None] = parse_label) -> dict[str, Result]:
    """Output file lines carry your key plus either a response or an error (a google.rpc.Status).
    Read line by line, so a big results file never sits in memory twice."""
    results: dict[str, Result] = {}
    with path.open(encoding="utf-8") as lines:
        for raw in lines:
            line = json.loads(raw)
            key = line["key"]
            if line.get("response"):
                results[key] = _judge(key, types.GenerateContentResponse.model_validate(line["response"]), parse)
            else:
                error = line.get("error") or line.get("status") or {}
                code = error.get("code", 0)
                results[key] = Result(key, "failed", detail=f"{code} {error.get('message', '')}",
                                      retry=code in (429, 500, 503, 504))
    for key in expected - results.keys():
        results[key] = Result(key, "failed", detail="missing from results", retry=True)
    return results


def reconcile_inline(responses: list[types.InlinedResponse], expected: set[str],
                     parse: Callable[[str | None], str | None] = parse_label) -> dict[str, Result]:
    """Inline results: join on the metadata key we sent, not on list position."""
    results: dict[str, Result] = {}
    for r in responses:
        key = (r.metadata or {}).get("key", "?")
        if r.response:
            results[key] = _judge(key, r.response, parse)
        else:
            code = r.error.code if r.error else None
            results[key] = Result(key, "failed", detail=f"{code} {r.error.message if r.error else ''}",
                                  retry=code in (429, 500, 503, 504))
    for key in expected - results.keys():
        results[key] = Result(key, "failed", detail="missing from results", retry=True)
    return results

Notes on the module:

  • CONFIG asks for thinking_level: low and leaves 256 output tokens: the current Gemini models think by default, and minimal isn't accepted on 3.8 Flash (02.8). Without room for thinking, you'd get finish_reason: MAX_TOKENS and an empty answer.
  • The JSONL builder writes REST field names (generation_config, system_instruction) because that's what the Batch file format is. The inline builder uses the SDK's Python types (config, with system_instruction), because inline requests go through the SDK.
  • Each result is judged by _judge: anything other than FinishReason.STOP is invalid, and only MAX_TOKENS is worth retrying (with a bigger cap). Safety blocks and PROHIBITED_CONTENT will repeat (03.8, Part 10).
  • A per-request error is a google.rpc.Status (code, message, status). Codes 429, 500, 503 and 504 are retried.
  • Each result that ran carries usage_metadata, which cost_calc.from_gemini(response, model, batch=True) (03.7) turns into a Usage at the batch tier. Thinking tokens are counted as output, as in a normal call. reconcile_file reads the results file line by line, and parse is a parameter, as in the OpenAI module (11.3b).

Real file building, with a fixture results file (out of order, one truncated answer, one wrong-format answer, one error line):

python
"""s9_1_gemini_files.py: write a real Gemini batch JSONL input file, then reconcile a FIXTURE
output file (out of order, one truncated, one invalid, one error line)."""
import json
from pathlib import Path

from batch_cost import job_cost
from gemini_batch_io import build_jsonl, reconcile_file
from tickets import SAMPLE

index = build_jsonl(SAMPLE, Path("data/gemini_input.jsonl"))
print("first line:", Path("data/gemini_input.jsonl").read_text().splitlines()[0])
keys = list(index)


def response(text: str, finish: str = "STOP") -> dict:       # REST (camelCase) GenerateContentResponse
    return {"candidates": [{"content": {"role": "model", "parts": [{"text": text}]}, "finishReason": finish}],
            "usageMetadata": {"promptTokenCount": 31, "candidatesTokenCount": 1, "totalTokenCount": 60,
                              "thoughtsTokenCount": 28},
            "modelVersion": "gemini-3.8-flash"}

# FIXTURE: output lines in the documented {"key", "response" | error} form, out of order
lines = [{"key": keys[1], "response": response("bug")},
         {"key": keys[0], "response": response("Billing")},
         {"key": keys[4], "response": response("", "MAX_TOKENS")},
         {"key": keys[3], "response": response("other")},
         {"key": keys[2], "response": response("It is about the account")},
         {"key": keys[5], "error": {"code": 500, "message": "Internal error encountered.", "status": "INTERNAL"}}]
Path("data/gemini_output.jsonl").write_text("".join(json.dumps(l) + "\n" for l in lines))

results = reconcile_file(Path("data/gemini_output.jsonl"), set(keys))
for key in keys:
    r = results[key]
    print(f"{index[key].ticket_id:>11}  {r.status:<8} {r.label or '':<8} retry={r.retry!s:<5} {r.detail}")
print(job_cost(r.usage for r in results.values()))
Output · the input file is real; the results are the fixture8 lines
first line: {"key": "triage-v1-10231", "request": {"contents": [{"role": "user", "parts": [{"text": "I was charged twice for my October invoice."}]}], "system_instruction": {"parts": [{"text": "Classify the support ticket. Reply with exactly one word: billing, bug, account or other."}]}, "generation_config": {"max_output_tokens": 256, "thinking_config": {"thinking_level": "low"}}}}
      10231  ok       billing  retry=False 
      10232  ok       bug      retry=False 
      10233  invalid           retry=False unexpected answer 'It is about the account'
      10234  ok       other    retry=False 
      10235  invalid           retry=True  finish_reason FinishReason.MAX_TOKENS
 ZD#10236/a  failed            retry=True  500 Internal error encountered.
cost $0.000330 for 5 result(s) with usage (155 prompt + 145 output tokens); 1 without usage

The last line prices the five results that carried usage, at the batch rate. The thinking tokens (28 per request in the fixture) dominate the output count, which is why a one-word answer still costs more than the prompt.

9.2 Limits, job states and results#

Limit (as of November 2026) Value
Concurrent batch requests 100 (Google's wording on its rate-limit page, which doesn't say whether the unit is jobs or requests; don't assume it means 100 jobs, and check the page)
Input file 2 GB (uploaded through the Files API; 20 GB of file storage per project)
Inline requests 20 MB in total
Enqueued tokens A cap per model and usage tier on the tokens waiting in your active batch jobs. Examples from Google's rate-limit page: Gemini 3.8 Flash 3,000,000 on Tier 1, 400,000,000 on Tier 2, 1,000,000,000 on Tier 3; Gemini 4 Argon 5,000,000, 500,000,000 and 1,000,000,000; Gemini 3.5 Flash-Lite 10,000,000, 500,000,000 and 1,000,000,000
Target turnaround 24 hours; a job still pending or running after 48 hours becomes JOB_STATE_EXPIRED and has no results
Price 50% of the standard price for the model; context caching is supported in batch (cache hits at the standard caching rates)

The enqueued-token cap is the limit that catches large jobs on the lower tiers. Twenty thousand tickets at 160 input tokens each is 3.2 million tokens: just over the 3 million a Tier-1 account may queue for 3.8 Flash. The job must be split and submitted in waves (11.4). Check your tier and the current numbers on Google's rate-limit page.

Job states (the SDK's JobState enum, mapped from the API's BATCH_STATE_*):

State Meaning
JOB_STATE_PENDING Created and waiting to be processed
JOB_STATE_RUNNING In progress
JOB_STATE_SUCCEEDED Finished; results can be retrieved (individual requests may still have errors)
JOB_STATE_FAILED The job failed (system or validation error)
JOB_STATE_CANCELLED You cancelled it
JOB_STATE_EXPIRED Pending or running for more than 48 hours; no results. "You can try submitting the job again or splitting up the requests into smaller batches"

The SDK's JobState has more members (QUEUED, PAUSED, PARTIALLY_SUCCEEDED, UPDATING, CANCELLING); they are mostly used by the Vertex AI side of the SDK. On the Gemini Developer API you'll see the six above.

9.3 The full lifecycle (provider sample)#

python
"""s9_4_gemini_batch.py: the full Gemini Batch API lifecycle, with inline requests or a JSONL file:
build -> (upload) -> create -> poll -> fetch results -> reconcile. Needs GEMINI_API_KEY in .env."""
from pathlib import Path

from dotenv import load_dotenv
from google import genai
from google.genai import types

from batch_cost import job_cost
from gemini_batch_io import MODEL, build_inline, build_jsonl, reconcile_file, reconcile_inline
from poller import poll_until
from tickets import SAMPLE

TERMINAL = {types.JobState.JOB_STATE_SUCCEEDED, types.JobState.JOB_STATE_FAILED,
            types.JobState.JOB_STATE_CANCELLED, types.JobState.JOB_STATE_EXPIRED}


def run_gemini_batch(client: genai.Client, workdir: Path, use_file: bool, poll_first: float = 30.0) -> None:
    workdir.mkdir(exist_ok=True)
    if use_file:                                           # large jobs: JSONL via the Files API (2 GB max)
        index = build_jsonl(SAMPLE, workdir / "input.jsonl")
        uploaded = client.files.upload(file=workdir / "input.jsonl",
                                       config=types.UploadFileConfig(display_name="triage-v1", mime_type="jsonl"))
        assert uploaded.name
        src: str | list[types.InlinedRequestDict] = uploaded.name   # "files/..."
    else:                                                  # small jobs: inline, under 20 MB in total
        src, index = build_inline(SAMPLE)

    job = client.batches.create(model=MODEL, src=src, config={"display_name": "triage-v1"})
    assert job.name
    (workdir / "batch_name.txt").write_text(job.name)      # "batches/...": save it before anything else
    print(f"created {job.name}: {job.state}")

    job = poll_until(lambda: client.batches.get(name=job.name or ""), lambda j: j.state in TERMINAL,
                     first=poll_first, on_poll=lambda j, t: print(f"  {t:6.0f} s  {j.state}"))

    if job.state != types.JobState.JOB_STATE_SUCCEEDED:   # failed / cancelled / expired (48 h)
        # google-genai 2.34.0 does not copy `error` (or batch stats) from the Developer API's reply into BatchJob,
        # so the reason is not available here: GET the job over REST to read it (the warning in 9.2)
        print(f"job ended {job.state}")
        return
    if job.dest and job.dest.file_name:                    # file input -> results file
        path = workdir / "output.jsonl"
        path.write_bytes(client.files.download(file=job.dest.file_name) or b"")   # returns ALL the bytes at once
        results = reconcile_file(path, set(index))
    elif job.dest and job.dest.inlined_responses:          # inline input -> inline results
        results = reconcile_inline(job.dest.inlined_responses, set(index))
    else:
        raise RuntimeError("succeeded but no results: check job.dest")
    for key, r in results.items():
        print(f"  {index[key].ticket_id:>11}  {r.status:<8} {r.label or '':<8} {r.detail}")
    print(f"{sum(r.status == 'ok' for r in results.values())} ok, "
          f"{sum(r.retry for r in results.values())} to resubmit")
    print(job_cost(r.usage for r in results.values()))     # per-result usage, priced as batch (03.7's cost_calc)


if __name__ == "__main__":
    load_dotenv()
    client = genai.Client()                               # keep a reference while you use it (03.1, 7.5)
    run_gemini_batch(client, Path("gemini_batch_run"), use_file=False)
    client.close()
Example output · illustrative13 lines
created batches/s3k7q1x0n9v2c8f5p4d6a1m2z7b3t0y8w5r9: JobState.JOB_STATE_PENDING
       0 s  JobState.JOB_STATE_PENDING
      29 s  JobState.JOB_STATE_RUNNING
      72 s  JobState.JOB_STATE_RUNNING
     138 s  JobState.JOB_STATE_SUCCEEDED
        10232  ok       bug      
        10231  ok       billing  
        10235  ok       billing  
   ZD#10236/a  ok       bug      
        10233  ok       account  
        10234  ok       other    
6 ok, 0 to resubmit
cost $0.000385 for 6 result(s) with usage (186 prompt + 168 output tokens); 0 without usage

The sample calls batches.create with either form (use_file switches between them). Against the local stand-in it fails with a 404, so it's "not supported locally". Details to notice:

  • The Files API step (files.upload(..., config=UploadFileConfig(display_name=..., mime_type="jsonl"))) is 03.6's topic. Files you upload are deleted automatically after 48 hours (03.6), the same time a batch job expires, so upload, create and finish within that window. The guide doesn't say how long the results file lives (6.2): download it as soon as the job succeeds. Without a destination, client.files.download returns the whole file as bytes, as the sample does. The signature also accepts a destination (a path or an open file), but we haven't verified whether the SDK streams to it or buffers, so for a very large results file (a job can have up to 2 GB of input), measure the memory before you rely on either form, and keep jobs a sensible size (11.4).
  • job.name (batches/...) is the handle to save before anything else.
  • job.dest.file_name for file jobs, job.dest.inlined_responses for inline jobs. If a succeeded job has neither, the sample raises: something is wrong, and silence would hide it.
  • The config. config={"display_name": "triage-v1"} names the job; the SDK's config type also has dest (Vertex only) and a webhook_config field. webhook_config is present in the SDK but not shown in Google's documentation for batches: Google's webhook page documents it on interactions.create and documents batches through static webhooks (client.webhooks.create(subscribed_events=["batch.succeeded", ...]), 13.6). Use the static form, which is documented, and treat a per-batch webhook_config as unverified.
  • Other methods: client.batches.get(name=...), .list() (with config={"page_size": ...}), .cancel(name=...) and .delete(name=...). Deleting a job "stops processing new requests and is removed from the list". Embedding jobs use client.batches.create_embeddings(model=..., src={...}).
  • Async: every method exists under client.aio.batches.

9.4 Try it: the same code against a mock Gemini Batch API#

google-genai 2.34.0 talks httpx (not httpx2; 3.x flips this, see the note in Setup), so the mock is an httpx.MockTransport passed through HttpOptions(httpx_client=...). The mock implements batchGenerateContent, the resumable file upload, batches.get and the results download, and its state arrives as BATCH_STATE_* in the job's metadata, as the real API does. It runs the same lifecycle twice, once with inline requests and once with a file. Request 4 comes back as a 503 in both:

python
"""mock_gemini_batch.py: a MOCK of the Gemini Developer API batch endpoints (batchGenerateContent,
batches.get, resumable file upload, file download). Wire shapes: https://ai.google.dev/api/batch-mode
(state arrives as metadata.state = BATCH_STATE_*; the SDK maps it to JobState.JOB_STATE_*)."""
import json
import random
import re

import httpx


def _response(text: str) -> dict:
    return {"candidates": [{"content": {"role": "model", "parts": [{"text": text}]}, "finishReason": "STOP"}],
            "usageMetadata": {"promptTokenCount": 31, "candidatesTokenCount": 1, "totalTokenCount": 60},
            "modelVersion": "gemini-3.8-flash"}


class MockGeminiBatches:
    def __init__(self, seed: int = 5) -> None:
        self.requests: list[dict] = []
        self.file_lines: list[dict] = []
        self.polls = 0
        self.rng = random.Random(seed)
        self.seen: list[str] = []
        self.batch: dict = {}

    def _results(self) -> list[tuple[str, dict]]:
        out = []
        for i, (key, _) in enumerate(self._keyed()):
            out.append((key, {"error": {"code": 503, "message": "The model is overloaded.", "status": "UNAVAILABLE"}}
                        if i == 3 else {"response": _response(["billing", "bug", "account", "other"][i % 4])}))
        self.rng.shuffle(out)
        return out

    def _keyed(self) -> list[tuple[str, dict]]:
        if self.file_lines:
            return [(l["key"], l["request"]) for l in self.file_lines]
        return [(r["metadata"]["key"], r["request"]) for r in self.requests]

    def handler(self, request: httpx.Request) -> httpx.Response:
        url, method = request.url, request.method
        self.seen.append(f"{method} {url.path}")
        if method == "POST" and url.path == "/upload/v1beta/files":          # resumable upload: start
            return httpx.Response(200, headers={"x-goog-upload-url": "https://mock.local/upload/1",
                                                "x-goog-upload-status": "active"}, json={})
        if method == "POST" and url.path == "/upload/1":                     # upload, finalize
            self.file_lines = [json.loads(l) for l in request.read().decode().splitlines() if l.strip()]
            return httpx.Response(200, headers={"x-goog-upload-status": "final"},
                                  json={"file": {"name": "files/in1", "mimeType": "jsonl", "state": "ACTIVE"}})
        if method == "POST" and url.path.endswith(":batchGenerateContent"):
            body = json.loads(request.content)["batch"]
            self.requests = body["inputConfig"].get("requests", {}).get("requests", [])
            self.batch = {"name": "batches/mock1", "metadata": {
                "@type": "type.googleapis.com/google.ai.generativelanguage.v1main.GenerateContentBatch",
                "model": "models/gemini-3.8-flash", "displayName": body.get("displayName"),
                "state": "BATCH_STATE_PENDING", "createTime": "2026-11-04T09:00:00Z"}}
            return httpx.Response(200, json=self.batch)
        if method == "GET" and url.path == "/v1beta/batches/mock1":
            self.polls += 1
            meta = self.batch["metadata"]
            meta["state"] = {1: "BATCH_STATE_PENDING", 2: "BATCH_STATE_RUNNING"}.get(self.polls, "BATCH_STATE_SUCCEEDED")
            if meta["state"] == "BATCH_STATE_SUCCEEDED":
                results = self._results()
                if self.file_lines:
                    meta["output"] = {"responsesFile": "files/out1"}
                else:
                    meta["output"] = {"inlinedResponses": {"inlinedResponses": [
                        {**r, "metadata": {"key": k}} for k, r in results]}}
            return httpx.Response(200, json=self.batch)
        if method == "GET" and "files/out1:download" in url.path:
            lines = [{"key": k, **r} for k, r in self._results()]
            return httpx.Response(200, content="".join(json.dumps(l) + "\n" for l in lines).encode())
        return httpx.Response(404, json={"error": {"code": 404, "message": f"mock: {method} {url.path}", "status": "NOT_FOUND"}})
python
"""s9_5_gemini_batch_mock.py: run the unchanged lifecycle from s9_4 against a MOCK Gemini batch API,
once with inline requests and once with a JSONL file. google-genai uses httpx, so the mock is httpx."""
from pathlib import Path

import httpx
from google import genai
from google.genai import types

from mock_gemini_batch import MockGeminiBatches
from s9_4_gemini_batch import run_gemini_batch

for use_file in (False, True):
    mock = MockGeminiBatches()
    client = genai.Client(api_key="sk-test", http_options=types.HttpOptions(
        httpx_client=httpx.Client(transport=httpx.MockTransport(mock.handler))))
    print(f"--- {'JSONL file' if use_file else 'inline requests'} ---")
    run_gemini_batch(client, Path(f"data/gemini_mock_{'file' if use_file else 'inline'}"), use_file, poll_first=0.01)
    print("HTTP calls:", ", ".join(dict.fromkeys(mock.seen)))
    client.close()
Output · mock server28 lines
--- inline requests ---
created batches/mock1: JobState.JOB_STATE_PENDING
       0 s  JobState.JOB_STATE_PENDING
       0 s  JobState.JOB_STATE_RUNNING
       0 s  JobState.JOB_STATE_SUCCEEDED
        10232  ok       bug      
        10231  ok       billing  
        10234  failed            503 The model is overloaded.
   ZD#10236/a  ok       bug      
        10233  ok       account  
        10235  ok       billing  
5 ok, 1 to resubmit
cost $0.000068 for 5 result(s) with usage (155 prompt + 5 output tokens); 1 without usage
HTTP calls: POST /v1beta/models/gemini-3.8-flash:batchGenerateContent, GET /v1beta/batches/mock1
--- JSONL file ---
created batches/mock1: JobState.JOB_STATE_PENDING
       0 s  JobState.JOB_STATE_PENDING
       0 s  JobState.JOB_STATE_RUNNING
       0 s  JobState.JOB_STATE_SUCCEEDED
        10235  ok       billing  
        10233  ok       account  
   ZD#10236/a  ok       bug      
        10231  ok       billing  
        10232  ok       bug      
        10234  failed            503 The model is overloaded.
5 ok, 1 to resubmit
cost $0.000068 for 5 result(s) with usage (155 prompt + 5 output tokens); 1 without usage
HTTP calls: POST /upload/v1beta/files, POST /upload/1, POST /v1beta/models/gemini-3.8-flash:batchGenerateContent, GET /v1beta/batches/mock1, GET /v1beta/files/out1:download

The two runs make different HTTP calls (the file run includes the two-step resumable upload and the results download) and arrive at the same reconciled result. In both, results were joined on the key, and the 503 is listed for resubmission.

9.5 Batches and the Interactions API#

If your code uses Interactions (client.interactions.create(model=..., input=..., ...)), you can't submit those requests as they are. A Gemini batch line is a GenerateContentRequest. The translation is mechanical for text work:

Interactions request Batch (generateContent) request
input="text" (or typed content) contents=[{"role": "user", "parts": [{"text": "..."}]}]
system_instruction system_instruction (JSONL) or config.system_instruction (inline)
generation_config (max_output_tokens, thinking_level, ...) generation_config (JSONL) or the matching GenerateContentConfig fields (inline)
response_format / response_mime_type response_mime_type and response_schema / response_json_schema (03.4)
tools tools
previous_interaction_id, store No equivalent. Batch requests are stateless: send the full history in contents (03.2)
service_tier Not applicable to the batch job (the job itself is the cheaper tier)

So in an Interactions-based codebase, keep one small function that renders your prompt into both shapes, and use the generateContent one for batches. Google's other route for existing OpenAI code is its OpenAI-compatible endpoint, which "supports Batch API" too (its OpenAI compatibility page has the examples), but it's a separate surface with its own limits; this lesson sticks to the native one.


Part 10: OpenRouter's Batch API#

Reference

OpenRouter has its own Batch API, documented at openrouter.ai/docs/guides/features/batch-api and in its Batch API Quickstart (as of November 2026). It is not OpenAI's /v1/batches with a file upload. It's a simpler, inline design, so you can't point the openai SDK's client.batches at it. You call it through the SDK's generic HTTP methods.

10.1 What it is, and what the :batch variant means#

OpenRouter's model catalogue has variants: suffixes such as :free, :nitro and :floor (02.9, 5.4). :batch is a catalogue variant: the batch-priced version of a model, with the pricing and endpoints that apply to batched requests. You find those models by filtering the model list on ?variant=batch. You don't write :batch in your request. The quickstart says to use the model's normal slug: you send "model": "anthropic/claude-haiku-5.5", and a model with no batch variant gets a 400.

Item OpenRouter Batch API
Endpoint POST https://openrouter.ai/api/v1/batches (also GET /batches, GET /batches/{id}, DELETE /batches/{id})
Request endpoints /v1/chat/completions, /v1/responses, /v1/messages and /v1/embeddings; one model and one endpoint per batch
Input Inline. The body has endpoint, model, optional completion_window ("24h", the only value), provider, callback_url, and requests: a list of {"custom_id": "...", "body": {...}} where body is the normal body for that endpoint
Size Up to 200 MB per batch, and a request cap that OpenRouter adjusts over time and doesn't list as a number (an over-limit submit gets a 413 whose message states the current value)
Price "Typically 50% of the sync per-token price"; each model page shows its batch price. Some components aren't discounted (web search calls, and prompt-caching rates vary by model). usage.cost reports what was charged
Turnaround Within 24 hours on most providers; Google AI Studio allows 48 hours and Google Vertex up to 96 hours
Results Inline in GET /batches/{id} as results; no file download. Not in input order: match on custom_id
Retention Deleted 30 days after you submit (then 410 Gone), or when you delete the batch. Batch endpoints do not train on your data
Cancel Not supported ("There is no cancel endpoint yet"). Wait for the batch to finish, then delete it
Notifications An optional signed webhook (13.6)

OpenRouter picks the cheapest provider that serves the model in batch mode, and moves the batch to the next one if that provider has no capacity. The response's provider field says which one ran it. You can restrict it with provider.only and provider.allow_fallbacks; provider.order and provider.sort are rejected for batches.

10.2 Differences that matter in code#

  • A 202 means "stored", not "valid". OpenRouter checks every request after accepting the batch, and a failed check moves the batch to failed with an error.message that names the bad request's custom_id (the same late-validation trap as Anthropic's).
  • Field order matters. Put endpoint, model, provider, completion_window and callback_url before requests. OpenRouter reads the body as a stream, so that it can accept large batches without buffering them; if requests comes first, the submit returns a 400. Python dicts keep insertion order and json writes them in that order, so build the dict with requests last.
  • 402 before it starts. OpenRouter estimates the batch's cost and compares it with your balance (BYOK and invoiced accounts skip this). If the estimate is higher, the submit returns 402.
  • A completed batch can contain failed requests. Each results entry has either a response or an error. Check request_counts.failed.
  • Things a batch can't do (all as of November 2026): streaming, speed, image or audio output, base64 or data-URI images (use public image URLs, and pin a provider that can read them), audio input, OpenRouter's web search (:online, the web plugin), Zero Data Retention (batch stores data for 30 days), regional data residency (batch runs on US-based infrastructure), and the provider order and sort options.
  • Each result's response.body has the same shape as that endpoint's synchronous response, and its id is the generation ID.
  • Errors worth knowing: 400 (bad input, requests not last, a private callback_url, a model without a batch entry), 402 (estimate above balance), 404 (no provider serves the model in batch mode for your provider settings), 409 (deleting a running batch), 410 (older than 30 days), 413 (too many requests or over 200 MB), 422 (the model targets the :online variant, or a feature batch rejects), 429 (too many submits, or too many batches or requests in progress).

10.3 The full lifecycle (provider sample)#

The SDK has no batches resource for this API, but OpenAI clients expose generic post, get and delete methods that keep the base URL, Authorization header, timeouts and retries. Passing cast_to=dict returns the JSON as a plain dict:

python
"""s10_3_openrouter_batch.py: OpenRouter's Batch API (inline requests, results inline, no file upload).
The openai SDK has no OpenRouter batch methods, so we use its generic client.post/get/delete, which
keep the base URL, auth header, timeouts and retries. Needs OPENROUTER_API_KEY in .env."""
import os
from typing import Any

from dotenv import load_dotenv
from openai import OpenAI

from openai_batch_io import output_text
from poller import poll_until
from tickets import INSTRUCTIONS, SAMPLE, custom_id_for, parse_label

TERMINAL = {"completed", "failed", "expired", "cancelled"}


def run_openrouter_batch(client: OpenAI, poll_first: float = 60.0) -> None:
    index = {custom_id_for(t): t for t in SAMPLE}
    # Field order matters: OpenRouter streams the body, so endpoint/model/etc. must come BEFORE requests
    body: dict[str, Any] = {
        "endpoint": "/v1/responses",                       # also /v1/chat/completions, /v1/messages, /v1/embeddings
        "model": "anthropic/claude-haiku-5.5",              # the normal slug; it must have a :batch catalogue entry
        "completion_window": "24h",
        "requests": [{"custom_id": cid, "body": {"instructions": INSTRUCTIONS, "input": t.text,
                                                 "max_output_tokens": 256}}
                     for cid, t in index.items()],
    }
    batch: dict[str, Any] = client.post("/batches", body=body, cast_to=dict)    # 202 Accepted: stored, not yet checked
    print(f"created {batch['id']}: {batch['status']} on {batch.get('provider')}")

    def show(b: dict[str, Any], elapsed: float) -> None:
        c = b.get("request_counts") or {}
        print(f"  {elapsed:6.0f} s  {b['status']:<11} {c.get('completed', 0)}/{c.get('total', '?')} done")
    batch = poll_until(lambda: client.get(f"/batches/{batch['id']}", cast_to=dict),
                       lambda b: b["status"] in TERMINAL, first=poll_first, on_poll=show)

    if batch["status"] != "completed":
        print(f"{batch['status']}: {(batch.get('error') or {}).get('message')}")
        return
    for r in batch["results"]:                              # inline results, in ANY order
        t = index[r["custom_id"]]
        if r.get("response") and r["response"]["status_code"] == 200:
            label = parse_label(output_text(r["response"]["body"]))
            print(f"  {t.ticket_id:>11}  {'ok' if label else 'invalid':<8} {label or ''}")
        else:
            print(f"  {t.ticket_id:>11}  failed   {r.get('error')}")
    usage = batch.get("usage") or {}                        # OpenRouter reports the cost itself, in dollars (03.7, Part 9)
    print(f"cost ${usage.get('cost', 0):.6f}; {batch['request_counts']['failed']} failed")
    client.delete(f"/batches/{batch['id']}", cast_to=dict)  # results are deleted after 30 days anyway


if __name__ == "__main__":
    load_dotenv()
    with OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"],
                default_headers={"HTTP-Referer": "https://example.com", "X-OpenRouter-Title": "Ticket triage"}) as client:
        run_openrouter_batch(client)
Example output · illustrative11 lines
created batch_8f3a1c7e92d44b05a6c1e0d9b2f7a413: validating on Anthropic
       0 s  validating  0/6 done
      62 s  in_progress 0/6 done
     131 s  completed   6/6 done
        10233  ok       account
        10231  ok       billing
        10235  ok       billing
        10232  ok       bug
        10234  ok       other
   ZD#10236/a  ok       bug
cost $0.000054; 0 failed

The sample reuses output_text() from the OpenAI module, because each response.body is a Responses-format body here, and the same parse_label() as before. Against the local stand-in it fails with a 404 (Ollama has no /v1/batches), so it is "not supported locally". The usage.cost line is OpenRouter's own field, in dollars (03.7, Part 9).

10.4 Try it: the same code against a mock OpenRouter Batch API#

The mock enforces the one rule that is easy to get wrong: it asserts that requests comes after model in the raw request body. It answers 202 with validating, then walks through in_progress and finalizing to completed, returns shuffled results, and makes one request fail with a 500 (the provider's error, inside a completed batch). The shapes follow the Batch API Quickstart:

python
"""s10_4_openrouter_batch_mock.py: run s10_3 against a MOCK of OpenRouter's /api/v1/batches.
Shapes follow https://openrouter.ai/docs/batch-quickstart (202 on submit; results inline)."""
import json
import random

import httpx2
from openai import OpenAI

from mock_llm import response_body
from s10_3_openrouter_batch import run_openrouter_batch

state: dict = {"polls": 0}


def handler(request: httpx2.Request) -> httpx2.Response:
    if request.method == "POST":
        raw = request.content.decode()
        assert raw.index('"requests"') > raw.index('"model"'), "requests must come last"
        state["requests"] = json.loads(raw)["requests"]
        n = len(state["requests"])
        return httpx2.Response(202, json={"id": "batch_or1", "object": "batch", "status": "validating",
                                          "provider": "Anthropic", "request_counts": {"total": n, "completed": 0, "failed": 0},
                                          "results": None, "usage": None, "error": None})
    if request.method == "DELETE":
        return httpx2.Response(200, json={"id": "batch_or1", "object": "batch",
                                          "deletion": {"openrouter": "deleted", "upstream": {"provider": "Anthropic", "status": "deleted"}}})
    state["polls"] += 1
    reqs = state["requests"]
    status = ["validating", "in_progress", "finalizing"][state["polls"] - 1] if state["polls"] <= 3 else "completed"
    batch = {"id": "batch_or1", "object": "batch", "status": status, "provider": "Anthropic",
             "request_counts": {"total": len(reqs), "completed": len(reqs) - 1 if status == "completed" else 0,
                                "failed": 1 if status == "completed" else 0}, "results": None, "usage": None}
    if status == "completed":
        results = [{"id": f"batch_req_{i}", "custom_id": r["custom_id"], "error": None,
                    "response": {"status_code": 200, "request_id": f"request_{i}",
                                 "body": response_body(["billing", "bug", "account", "other"][i % 4], "anthropic/claude-haiku-5.5")}}
                   for i, r in enumerate(reqs[:-1])]
        results.append({"id": "batch_req_x", "custom_id": reqs[-1]["custom_id"], "response": None,
                        "error": {"code": 500, "message": "Provider returned error"}})   # FIXTURE: one failure
        random.Random(1).shuffle(results)
        batch.update(results=results, usage={"prompt_tokens": 205, "completion_tokens": 5, "total_tokens": 210,
                                             "cost": 0.0000225, "is_byok": False})
    return httpx2.Response(200, json=batch)


client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key="sk-test",
                http_client=httpx2.Client(transport=httpx2.MockTransport(handler)))
run_openrouter_batch(client, poll_first=0.01)
Output · mock server12 lines
created batch_or1: validating on Anthropic
       0 s  validating  0/6 done
       0 s  in_progress 0/6 done
       0 s  finalizing  0/6 done
       0 s  completed   5/6 done
        10233  ok       account
        10234  ok       other
   ZD#10236/a  failed   {'code': 500, 'message': 'Provider returned error'}
        10231  ok       billing
        10235  ok       billing
        10232  ok       bug
cost $0.000023; 1 failed

The batch completed with 5 of 6 requests done and 1 failed, which is exactly the "completed doesn't mean all succeeded" case (6.5). The usage and cost numbers in the fixture are placeholders, not real prices. The cost line is formatted with six decimals ($0.000023), because Python's default would print scientific notation (2.25e-05), which is hard to read in a log.

10.5 Batch through OpenRouter, or direct?#

Through OpenRouter Direct to the provider
Provider choice One API for many providers' batch services; it chooses the cheapest and falls back You pick the provider and model
Format One inline format for every provider Three different formats (this lesson's Parts 7 to 9)
Features A subset: no streaming or speed, restricted image/file inputs, no Zero Data Retention, no cancel The provider's full feature set (all of Anthropic's server tools; Gemini's file-based multimodal batches)
Limits and price OpenRouter's own; the model page shows the batch price (03.7 for how OpenRouter reports cost) The provider's own

For one-provider jobs, direct is simpler and feature-complete. For a job that should run on whichever provider is cheapest, or on a model your own account can't batch directly, OpenRouter's single inline format is convenient.


Part 11: Designing a robust batch job#

A batch call is easy. A batch job that survives crashes, partial failures, expiry, and your own mistakes is a design. The parts below are the pieces a production job needs. 02.3 promised that indexing jobs would be "resumable so a failure at item 80,000 doesn't restart from zero"; 11.6 delivers it, with a classification job as the example.

11.1 Deterministic IDs and idempotent resubmission#

Everything else rests on one idea: the same input must always produce the same request ID, so that "have I already done this item?" has a stable answer.

  • Build custom_id from your data: {job}-{your primary key} (triage-v1-10231). custom_id_for() in tickets.py does it, and hashes IDs that contain characters the strictest provider rejects.
  • Put the job name and prompt version in it. If you change the prompt, the model or the schema, results from the old prompt must not be mixed with results from the new one. A new job name (triage-v2) gives new IDs and a clean slate; the same name means "the same job, continue".
  • Never use random IDs, uuid4() or a loop counter. After a crash you'd have no way to tell which result belongs to which item, and a rerun would treat everything as new work and pay for it twice.
  • Resubmit only failures. Idempotent means that doing something twice has the same effect as doing it once. Idempotent resubmission means "if I run the whole job again, only the items that don't have a good result yet are sent". With deterministic IDs and a record of which IDs are done (11.2), that is one WHERE status != 'done'.

One more reason to care: none of the providers de-duplicates batch creation for you. Google says it explicitly ("The creation of a batch job is not idempotent"), and OpenAI, Anthropic and OpenRouter document no idempotency key on batch creation either (none documented; see 03.8, 11.1). If you call create twice you have two batches and you pay for both. The defence is on your side: record your intent before you call, tag the batch with your own key where the provider lets you, and look for it before resubmitting (11.6).

11.2 A local manifest in SQLite#

A manifest is a table of every item and its state, plus a table of every batch and its state, stored somewhere that survives your process. A JSON or JSONL file works for small jobs. SQLite (in Python's standard library, one file, transactional) is the best default, because a crash in the middle of a write can't leave it half-updated. The schema below is what the runner in 11.6 uses:

Table Column Meaning
items custom_id (primary key) The deterministic ID
ticket_id, text The input (or a pointer to it)
status pending → submitted → done, or failed (given up)
batch_key, attempts Which batch holds it now, and how many times it has been submitted
label, detail The validated result, or why it failed
batches batch_key (primary key) Our name for the batch, decided before calling the API
batch_id The provider's ID, once we know it
status creating → submitted → collected

Two disciplines make it work:

  1. Write the intent first, then act, then record the outcome, each in its own committed transaction. The runner marks the items submitted and the batch creating before it uploads and creates the batch, and records the provider's ID right after. A crash at any point leaves a state you can reason about.
  2. Update results and statuses in one transaction. When a batch is collected, the item results and the batch's collected flag are committed together, so a crash can't leave "results saved but batch not marked" (which would re-process the batch) or the reverse (which would lose the results).

11.3 Validate every result before you use it#

A "succeeded" request is not a usable answer. Between the response and your database, check:

Check Why Example
Stop reason / status A cut-off answer looks fine until you parse it OpenAI status != "completed" (e.g. incomplete for max_output_tokens), Anthropic stop_reason != "end_turn", Gemini finish_reason != STOP. Retry truncation with a larger cap, not unchanged
Refusals and blocks They're successes at the HTTP level and they repeat stop_reason: "refusal", a Gemini safety finish_reason. Don't retry blindly (03.8, 10.4)
Format The model may answer in a sentence instead of one word parse_label(): anything but the four labels is invalid
Schema For structured output, parse into your Pydantic model; validation failures are data, not exceptions to swallow 03.4, 11.3b
Business rules A label must exist in your taxonomy; an extracted date must be a date Your code
Completeness Every request you sent has exactly one result expected - results.keys()

Keep the verdicts separate: ok, invalid (the model answered, but not usably), failed (an API error) and expired/canceled (never ran). They need different reactions. The reconcilers in Parts 7 to 9 return exactly these, with a retry flag, so the rest of the job doesn't parse strings. Spot-check a random sample of the ok results by hand as well: an answer that passes your format check can still be wrong, and measuring correctness is Module 10A's job.

11.3b Structured output in a batch: let the schema do the validating#

Classification at scale is the main production use of a Batch API, and 03.4 teaches the right way to get one label out of a model: a schema, not a polite request for "one word". The example job so far (parse_label) is the prompt-and-parse baseline: it asks for a word and string-matches the reply, so an answer like "I think it's other" becomes an invalid result. Much of that invalid class is an artefact of asking in prose. With a schema the provider constrains the output, so the reply is JSON in the shape you declared.

One Pydantic model describes the answer, with a Literal for the label and extra="forbid" (which becomes additionalProperties: false, required by the strict modes). Save this as structured.py; the three *_batch_io.py modules import it, and each builder takes structured=True:

python
"""structured.py: the ticket classifier as a SCHEMA instead of "reply with one word" (11.3b). One Pydantic model
describes the answer; each provider gets it in its own batch-request field; parse_triage() validates what comes back."""
from typing import Literal

from anthropic.types.json_output_format_param import JSONOutputFormatParam
from pydantic import BaseModel, ConfigDict, ValidationError


class Triage(BaseModel):
    model_config = ConfigDict(extra="forbid")          # becomes additionalProperties: false, which strict modes require
    label: Literal["billing", "bug", "account", "other"]


SCHEMA: dict = Triage.model_json_schema()              # {"properties": {"label": {"enum": [...]}}, "required": ["label"], ...}

# Where the schema goes in a BATCH request. The body is a normal request body (the same fields as a synchronous call):
OPENAI_TEXT = {"format": {"type": "json_schema", "name": "triage", "strict": True, "schema": SCHEMA}}      # Responses: text=
ANTHROPIC_FORMAT: JSONOutputFormatParam = {"type": "json_schema", "schema": SCHEMA}                      # Messages: output_config={"format": ...}
GEMINI_GENERATION_CONFIG = {"response_mime_type": "application/json", "response_json_schema": SCHEMA}     # generateContent


def parse_triage(text: str | None) -> str | None:
    """Same contract as tickets.parse_label (label or None), but validated by the schema's own model."""
    if not text:
        return None
    try:
        return Triage.model_validate_json(text).label
    except ValidationError:                            # truncated JSON, a wrong label, extra keys...
        return None

A batch request body is a normal request body, so the schema goes in the same field as in a synchronous call:

Where the schema goes in a batch request What to know
OpenAI body.text = {"format": {"type": "json_schema", "name": ..., "strict": true, "schema": ...}} (Responses); body.response_format on Chat Completions OpenAI's structured-outputs guide lists the Batch API among the APIs that support it
Anthropic params.output_config = {"format": {"type": "json_schema", "schema": ...}} The structured-outputs page lists batch processing (at the 50% discount), and output_config is not among the parameters a batch rejects (8.1). An unsupported schema feature (a recursive schema, numeric or string-length constraints, additionalProperties other than false) is a 400 in a synchronous call, so in a batch expect errored results, found late (the same rule as 8.1): send one request synchronously first
Where the schema goes in a batch request What to know
Gemini File: generation_config with response_mime_type: "application/json" and response_json_schema. Inline: the same keys in config Google's batch guide shows the inline form with response_mime_type and response_schema; response_json_schema is the field 03.4 recommends, and the guide shows no JSONL example with a schema, so dry-run one request of each shape before submitting
OpenRouter The normal body for the endpoint you chose (text.format on /v1/responses, response_format on chat completions) Whether the model's provider honours the schema is the usual per-provider question from 03.4

No batch-specific restriction on structured output is documented for any of the four, so the limits are the synchronous ones. This sample builds the requests for each provider, prints the field that carries the schema, then reconciles four fixture result lines (a normal answer, another normal answer, a reply cut off at the output cap, and a refusal) with the schema parser, and again with the one-word parser:

python
"""s11_3_structured_batch.py: the ticket classifier as a schema (11.3b). Layer 1, no network: the batch-request
fragment each provider needs, and the OpenAI reconciler judging FIXTURE output lines with both parsers."""
import json
from pathlib import Path

from anthropic_batch_io import build_requests
from gemini_batch_io import build_inline, build_jsonl as build_gemini_jsonl
from mock_llm import response_body
from openai_batch_io import build_jsonl, reconcile
from structured import SCHEMA, parse_triage
from tickets import SAMPLE, parse_label

DATA = Path("data")
print("schema:", json.dumps(SCHEMA), "\n")

# 1. Where the schema goes in each provider's BATCH request: the same field as in a synchronous call.
build_jsonl(SAMPLE, DATA / "openai_structured.jsonl", structured=True)
body = json.loads((DATA / "openai_structured.jsonl").read_text().splitlines()[0])["body"]
print("OpenAI    body.text          =", json.dumps(body["text"]["format"]["type"]), "+ name/strict/schema; max_output_tokens", body["max_output_tokens"])
requests, _ = build_requests(SAMPLE, structured=True)
output_config = json.loads(json.dumps(requests[0]))["params"]["output_config"]      # a plain dict
print("Anthropic params.output_config =", {**output_config, "format": {**output_config["format"], "schema": "..."}})
build_gemini_jsonl(SAMPLE, DATA / "gemini_structured.jsonl", structured=True)
config = json.loads((DATA / "gemini_structured.jsonl").read_text().splitlines()[0])["request"]["generation_config"]
print("Gemini    generation_config  =", {k: (v if k != "response_json_schema" else "...") for k, v in config.items()})
inline, _ = build_inline(SAMPLE, structured=True)
print("Gemini    inline config keys =", sorted(inline[0].get("config") or {}))

# 2. Judging results. FIXTURE lines in the documented OpenAI output format, one per situation.
index = build_jsonl(SAMPLE[:4], DATA / "openai_structured4.jsonl", structured=True)
ids = list(index)


def line(cid: str, body: dict) -> dict:
    return {"id": f"batch_req_{cid}", "custom_id": cid, "error": None,
            "response": {"status_code": 200, "request_id": f"req_{cid}", "body": body}}


refusal = response_body("")
refusal["output"][0]["content"] = [{"type": "refusal", "refusal": "I can't help with that."}]
truncated = response_body('{"label": "acc')
truncated["status"], truncated["incomplete_details"] = "incomplete", {"reason": "max_output_tokens"}
lines = [line(ids[0], response_body('{"label":"billing"}')),          # the normal case
         line(ids[1], response_body('{"label":"bug"}')),
         line(ids[2], truncated),                                      # hit the cap mid-object
         line(ids[3], refusal)]                                        # a refusal is a 200 with no text
(DATA / "openai_structured_out.jsonl").write_text("".join(json.dumps(l) + "\n" for l in lines))

for name, parse in (("schema parser   ", parse_triage), ("one-word parser ", parse_label)):
    results = reconcile(DATA / "openai_structured_out.jsonl", None, set(ids), parse=parse)
    print(f"\n{name}", {r.custom_id[-5:]: (r.status, r.label) for r in results.values()})
    for r in results.values():
        print(f"   {r.custom_id[-5:]}  {r.status:<8} retry={r.retry!s:<5} {r.detail}")
Output · layer 1, no network; the result lines are fixtures18 lines
schema: {"additionalProperties": false, "properties": {"label": {"enum": ["billing", "bug", "account", "other"], "title": "Label", "type": "string"}}, "required": ["label"], "title": "Triage", "type": "object"} 

OpenAI    body.text          = "json_schema" + name/strict/schema; max_output_tokens 32
Anthropic params.output_config = {'effort': 'low', 'format': {'type': 'json_schema', 'schema': '...'}}
Gemini    generation_config  = {'max_output_tokens': 256, 'thinking_config': {'thinking_level': 'low'}, 'response_mime_type': 'application/json', 'response_json_schema': '...'}
Gemini    inline config keys = ['max_output_tokens', 'response_json_schema', 'response_mime_type', 'system_instruction', 'thinking_config']

schema parser    {'10231': ('ok', 'billing'), '10232': ('ok', 'bug'), '10233': ('invalid', None), '10234': ('invalid', None)}
   10231  ok       retry=False 
   10232  ok       retry=False 
   10233  invalid  retry=True  status incomplete [request_id req_triage-v1-10233]
   10234  invalid  retry=False refused: "I can't help with that." [request_id req_triage-v1-10234]

one-word parser  {'10231': ('invalid', None), '10232': ('invalid', None), '10233': ('invalid', None), '10234': ('invalid', None)}
   10231  invalid  retry=False unexpected answer '{"label":"billing"}' [request_id req_triage-v1-10231]
   10232  invalid  retry=False unexpected answer '{"label":"bug"}' [request_id req_triage-v1-10232]
   10233  invalid  retry=True  status incomplete [request_id req_triage-v1-10233]
   10234  invalid  retry=False refused: "I can't help with that." [request_id req_triage-v1-10234]

Read it in three parts. The first lines show where the schema goes: one field per provider. The schema run judges the fixtures correctly: the two normal answers are ok with their labels, the truncated reply (status incomplete) is invalid and worth retrying with a bigger max_output_tokens, and the refusal is invalid and not retried, because it will refuse again. The prose class (unexpected answer "I think it's other") can't occur in this run, because the decoder is held to the schema. The last block is a trap: change the request and the parser together. With the one-word parser, every perfectly good {"label":"billing"} is invalid, because JSON is not a bare word. (Note also that the schema version raises max_output_tokens from 16 to 32: the JSON wrapper costs a few more output tokens than a word.)

A schema doesn't make the answers right, only well-formed: a Literal can't tell you that billing is the correct label. Refusals and truncation remain, and so does everything in 11.3's other rows. What you gain is that the format check is done by the provider and by model_validate_json, not by string matching you wrote.

11.4 Splitting a job under the limits#

Each provider caps a batch by requests and bytes, and some also cap the tokens you may have queued (7.2, 8.2, 9.2). A job that doesn't fit has to be split, and there are reasons to split even when it fits: a smaller batch finishes sooner, one bad line fails less work, and a stuck batch hurts less. chunking.py plans the split greedily and stays 5% under each limit, so a small estimation error can't fail a batch:

python
"""chunking.py: split a big job into batches that respect each provider's per-batch limits."""
from dataclasses import dataclass


@dataclass(frozen=True)
class BatchLimits:
    max_requests: int
    max_bytes: int
    note: str = ""


# As of November 2026. Re-check the pages in section 11.4 before relying on a number.
LIMITS = {
    "openai": BatchLimits(50_000, 200 * 1024 * 1024, "input file; 2,000 batches per hour; queued-token cap per model"),
    "anthropic": BatchLimits(100_000, 256 * 1024 * 1024, "whichever limit is reached first"),
    "gemini-file": BatchLimits(10**9, 2 * 1024**3, "2 GB input file; 100 concurrent jobs; enqueued-token cap per model"),
    "gemini-inline": BatchLimits(10**9, 20 * 1024 * 1024, "the whole create request must stay under 20 MB"),
}


def plan_chunks(sizes: list[int], limits: BatchLimits, *, tokens: list[int] | None = None,
                max_tokens: int | None = None, safety: float = 0.95) -> list[range]:
    """Greedy split of items 0..n-1 (in order) into consecutive ranges. `sizes` are the bytes each request
    adds to the file. Stays `safety` x under every limit, so a small estimation error doesn't fail a batch."""
    max_req = int(limits.max_requests * safety)
    max_bytes = int(limits.max_bytes * safety)
    cap_tokens = int(max_tokens * safety) if max_tokens else None
    chunks: list[range] = []
    start = used_bytes = used_tokens = 0
    for i, size in enumerate(sizes):
        t = tokens[i] if tokens else 0
        if size > max_bytes or (cap_tokens and t > cap_tokens):
            raise ValueError(f"item {i} alone ({size} bytes, {t} tokens) is over the per-batch limit")
        if i - start >= max_req or used_bytes + size > max_bytes or (cap_tokens and used_tokens + t > cap_tokens):
            chunks.append(range(start, i))
            start, used_bytes, used_tokens = i, 0, 0
        used_bytes += size
        used_tokens += t
    if start < len(sizes):
        chunks.append(range(start, len(sizes)))
    return chunks

The per-provider numbers in LIMITS are the ones in this lesson (check them again before you rely on them: they are volatile). Running it on 120,000 synthetic tickets, with the real OpenAI line format as the size proxy:

python
"""s11_4_chunking.py: how many batches does a job need? Real request sizes, measured by building the
real JSONL lines for 120,000 synthetic tickets; limits from chunking.py (layer 1, no network)."""
import json
import random

from chunking import LIMITS, plan_chunks
from tickets import INSTRUCTIONS

rng = random.Random(1)
WORDS = "refund invoice charged twice login password app crashes export slow dashboard email address billing plan upgrade".split()
tickets = [" ".join(rng.choices(WORDS, k=rng.randint(15, 160))) for _ in range(120_000)]   # 15-160 words each

# The size of each OpenAI batch line (same format as openai_batch_io.build_jsonl), in bytes
sizes = [len(json.dumps({"custom_id": f"triage-v1-{i}", "method": "POST", "url": "/v1/responses",
                         "body": {"model": "gpt-6-luna", "instructions": INSTRUCTIONS, "input": text,
                                  "reasoning": {"effort": "none"}, "max_output_tokens": 16}}).encode()) + 1
         for i, text in enumerate(tickets)]
print(f"{len(tickets):,} tickets, {sum(sizes) / 1e6:.1f} MB of JSONL in total ({sum(sizes) / len(sizes):.0f} bytes per line)")

for name, limits in LIMITS.items():
    chunks = plan_chunks(sizes, limits)
    print(f"{name:<14} {len(chunks):>3} batch(es): " + ", ".join(f"{len(c):,}" for c in chunks[:4]) + (" ..." if len(chunks) > 4 else ""))

# A token-based cap (Gemini: enqueued tokens per model; OpenAI: queued tokens per model). Roughly 4 characters per token.
tokens = [(len(t) + len(INSTRUCTIONS)) // 4 for t in tickets]
chunks = plan_chunks(sizes, LIMITS["gemini-file"], tokens=tokens, max_tokens=3_000_000)
print(f"gemini-file with a 3,000,000-token enqueued cap: {len(chunks)} job(s) of about {len(chunks[0]):,} requests")
Output6 lines
120,000 tickets, 108.5 MB of JSONL in total (904 bytes per line)
openai           3 batch(es): 47,500, 47,500, 25,000
anthropic        2 batch(es): 95,000, 25,000
gemini-file      1 batch(es): 120,000
gemini-inline    6 batch(es): 22,071, 22,055, 21,993, 22,022 ...
gemini-file with a 3,000,000-token enqueued cap: 8 job(s) of about 16,232 requests

The same 108 MB job needs three OpenAI batches (only the 50,000-request cap binds: 108 MB is far below the 190 MB, 95% of 200 MB, that the planner allows), two Anthropic batches, one Gemini file, and six inline Gemini requests (the 20 MB limit); and with a 3-million-token queue cap, eight Gemini jobs. When a token cap is what limits you (Gemini's enqueued tokens, OpenAI's queued tokens), the chunks can't all be in the queue at once: submit the next chunk when an earlier one finishes. The runner in 11.6 does this on purpose: give it a queue_cap_tokens (or a simpler max_open_batches) and it submits a chunk only while the queue has room, and submits more after each collect, so the job drains through the cap instead of being rejected for exceeding it. The sizes here use OpenAI's line format for all providers; Anthropic and Gemini lines differ by a few hundred bytes, which is why the 5% margin exists.

11.5 Estimate before you submit#

A batch is cheap per token, but 400,000 requests aren't cheap, and a bug that doubles your prompt size (a forgotten document attached to every request) is exactly the mistake you make at 2 a.m. Before submitting, compute and print what the job will cost, and refuse above a threshold. The module job_calc.py has the cost arithmetic (it is reused in Part 14); its prices are copied from the table in 03.7, 4.2 and are list prices as of 4 November 2026, so keep real prices in a dated configuration file as 03.7 recommends. Two things to know. Its input_tokens are uncached input (the module's convention), so the calculator ignores prompt caching on purpose: for a batch that shares a long prefix, the real bill is lower, and 03.7 prices cache reads. And the copy of the table can drift, so check_prices() compares it with 03.7's prices.yaml and raises on a mismatch (the table, not this file, is the source of truth). It looks the prices up for today's date, so from 1 January 2027 it will flag Gemini 3.8 Flash, whose introductory price in the table ends on 31 December 2026: that is the signal to update PRICES, not a bug:

python
"""job_calc.py: estimate wall time and cost of one job done three ways: bounded async, flex, batch.
Every number below is an ASSUMPTION or a list price you must re-check; the point is the arithmetic."""
import datetime as dt
import math
from dataclasses import dataclass

# USD per 1M tokens (input, output), for UNCACHED input: under the module's token convention `input_tokens` below
# means uncached input, so this calculator ignores prompt caching on purpose (03.7 prices cache reads and writes).
# Copied from the price table in lesson 03.7, section 4.2 (4 Nov 2026), and checked against it by check_prices().
# Gemini 3.8 Flash shows its introductory price, which the table lists as valid through 31 December 2026.
PRICES: dict[str, tuple[float, float]] = {
    "gpt-6-luna": (0.10, 0.50),
    "claude-haiku-5-5": (0.10, 0.50),
    "claude-sonnet-5-5": (2.00, 10.00),
    "gemini-3.8-flash": (0.75, 3.75),
}
DISCOUNT = {"standard": 1.0, "flex": 0.5, "batch": 0.5}   # multipliers on every token rate (lesson 03.7)


@dataclass(frozen=True)
class Job:
    requests: int = 20_000
    input_tokens: int = 160          # per request: instruction + ticket
    output_tokens: int = 4           # one word (add thinking tokens if your model reasons)


@dataclass(frozen=True)
class Limits:
    rpm: int = 4_000                 # requests per minute you are allowed (look yours up: lesson 03.8, 9.2)
    tpm: int = 2_000_000             # tokens per minute


def cost_usd(job: Job, model: str, tier: str, extra_requests: int = 0) -> float:
    """Price of the job. `extra_requests` = calls that are billed twice (retried after a timeout)."""
    price_in, price_out = PRICES[model]
    n = job.requests + extra_requests
    return n * (job.input_tokens * price_in + job.output_tokens * price_out) / 1e6 * DISCOUNT[tier]


def async_wall_s(job: Job, limits: Limits, *, concurrency: int, latency_s: float,
                 extra_wait_s: float = 0.0) -> tuple[float, str]:
    """Whichever constraint is slowest wins: waiting for answers (concurrency-bound) or the provider's
    quotas. Returns (seconds, name of the binding constraint)."""
    candidates = {
        "concurrency": job.requests / concurrency * (latency_s + extra_wait_s),
        "RPM": job.requests / limits.rpm * 60,
        "TPM": job.requests * (job.input_tokens + job.output_tokens) / limits.tpm * 60,
    }
    name = max(candidates, key=lambda k: candidates[k])
    return candidates[name], name


def fmt_duration(seconds: float) -> str:
    if seconds < 90:
        return f"{seconds:.0f} s"
    if seconds < 5400:
        return f"{seconds / 60:.0f} min"
    return f"{seconds / 3600:.1f} h"


def retry_cost_requests(job: Job, timeout_rate: float) -> int:
    """Requests that timed out client-side but ran anyway, so the retry is billed a second time (lesson 03.8, 6.6)."""
    return math.ceil(job.requests * timeout_rate)


NO_FLEX = {"claude-haiku-5-5", "claude-sonnet-5-5"}       # Anthropic has no flex tier (12.1): only batch applies

PROVIDER_OF = {"gpt-6-luna": "openai", "claude-haiku-5-5": "anthropic", "claude-sonnet-5-5": "anthropic",
               "gemini-3.8-flash": "gemini"}


def check_prices(on: dt.date | None = None) -> str:
    """Compare PRICES and DISCOUNT with 03.7's prices.yaml (needs 03.7's prices.py next to this file) and raise on a
    mismatch, so the two copies can't drift apart unnoticed. The table, not this file, is the source of truth."""
    from prices import PriceTable
    table = PriceTable.load()
    for model, (price_in, price_out) in PRICES.items():
        provider = PROVIDER_OF[model]
        rates = table.period(provider, model, on or dt.date.today()).rates
        tiers = table.model(provider, model).tiers
        if (rates["input"], rates["output"]) != (price_in, price_out):
            raise AssertionError(f"{model}: calculator has {price_in}/{price_out}, the table has {rates['input']}/{rates['output']}")
        for tier, multiplier in tiers.items():
            if tier in DISCOUNT and multiplier != DISCOUNT[tier]:
                raise AssertionError(f"{model}: the {tier} multiplier is {multiplier} in the table, {DISCOUNT[tier]} here")
    return f"prices match 03.7's table (version {table.version})"

The estimator reads the file you are about to submit, so it measures what will actually be sent. It uses the rough "4 characters per token" rule; for an exact input count use the providers' counting endpoints (03.7, Part 2), and remember that output tokens are unknowable in advance: the sample uses the max_output_tokens cap, which is a ceiling and so a safe worst case.

python
"""s11_5_estimate.py: estimate size, tokens, cost and time BEFORE submitting a batch, and refuse if the
estimate is over budget. Layer 1: real JSONL built from synthetic tickets; token counts are the rough
4-characters-per-token rule (lesson 03.7 shows exact counting)."""
import json
import random
import tempfile
from pathlib import Path

from chunking import LIMITS, plan_chunks
from job_calc import Job, cost_usd
from openai_batch_io import build_jsonl
from tickets import Ticket

MAX_BUDGET_USD = 2.00


def estimate(path: Path, model: str) -> None:
    lines = path.read_text(encoding="utf-8").splitlines()
    sizes = [len(line.encode()) + 1 for line in lines]
    bodies = [json.loads(line)["body"] for line in lines]
    in_chars = sum(len(b["instructions"]) + len(str(b["input"])) for b in bodies)
    out_cap = sum(b["max_output_tokens"] for b in bodies)              # a ceiling: real answers are shorter
    job = Job(requests=len(lines), input_tokens=round(in_chars / 4 / len(lines)), output_tokens=round(out_cap / len(lines)))
    chunks = plan_chunks(sizes, LIMITS["openai"])
    cost = cost_usd(job, model, "batch")
    print(f"{len(lines):,} requests, {sum(sizes) / 1e6:.1f} MB, ~{job.requests * job.input_tokens / 1e6:.2f}M input tokens, "
          f"output capped at {out_cap:,}")
    print(f"limits: {len(chunks)} batch(es) needed; worst-case batch cost on {model}: ${cost:.2f} (budget ${MAX_BUDGET_USD:.2f})")
    if cost > MAX_BUDGET_USD:
        raise SystemExit("estimate over budget: refusing to submit")
    print("ok to submit")


rng = random.Random(2)
words = "refund invoice charged twice login password app crashes export slow dashboard email".split()
for n, label in ((5_000, "5,000 tickets"), (400_000, "400,000 tickets")):
    tickets = [Ticket(str(i), " ".join(rng.choices(words, k=rng.randint(15, 160)))) for i in range(n)]
    with tempfile.TemporaryDirectory() as d:
        build_jsonl(tickets, Path(d) / "in.jsonl")
        print(f"--- {label}")
        try:
            estimate(Path(d) / "in.jsonl", "gpt-6-luna")
        except SystemExit as e:
            print(e)
Output8 lines
--- 5,000 tickets
5,000 requests, 4.5 MB, ~0.89M input tokens, output capped at 80,000
limits: 1 batch(es) needed; worst-case batch cost on gpt-6-luna: $0.06 (budget $2.00)
ok to submit
--- 400,000 tickets
400,000 requests, 360.0 MB, ~70.00M input tokens, output capped at 6,400,000
limits: 9 batch(es) needed; worst-case batch cost on gpt-6-luna: $5.10 (budget $2.00)
estimate over budget: refusing to submit

The 5,000-ticket job costs six cents, and the 400,000-ticket one is refused: $5.10 is above the $2 budget. In production the same check also looks at the number of batches (the chunk plan), at the daily spend so far, and at whether this job name already ran today (03.7, Part 12).

11.6 Try it: a resumable job, killed and restarted#

Now the pieces together: a runner that loads items into SQLite, submits them in chunks while the provider's queue has room, polls, collects, resubmits retryable failures, gives up on the rest, and can be killed at any moment. It uses the OpenAI Batch API, but the structure applies to the others. Read it with the diagram:

flowchart TD
    s(["start or restart"]) --> rec["recover(): batches stuck in 'creating'<br/>ask the provider by metadata batch_key"]
    rec --> sub["submit_pending(): only while the queue has room<br/>(queue_cap_tokens or max_open_batches)<br/>1 write intent (items submitted, batch 'creating')<br/>2 build file, upload, create batch<br/>3 write batch id (batch 'submitted')"]
    sub --> col["collect_finished(): poll open batches<br/>status failed: items 'failed', batch 'rejected', never resubmitted<br/>else download, reconcile, one transaction:<br/>ok = done / retryable with attempts left = pending / else failed"]
    col --> more{"anything pending<br/>or still open?"}
    more -- "pending: submit what fits now" --> sub
    more -- "open: wait and poll" --> col
    more -- "no" --> done(["done"])
    sub -. "crash between 2 and 3" .-> rec
python
"""batch_runner.py: a resumable OpenAI batch job with a SQLite checkpoint.
Every state change is committed before the next step, so the process can die at ANY point and a
re-run continues where it stopped: it never resubmits finished work, it finds batches it created but
didn't get to record, it submits chunks gradually so it never exceeds a queue cap, it never resubmits a batch
whose input the provider rejected, and it marks items that run out of attempts as failed."""
import os
import sqlite3
import time
from pathlib import Path

from openai import OpenAI

from batch_cost import job_cost
from openai_batch_io import build_jsonl, download, reconcile
from prices import PriceTable
from tickets import INSTRUCTIONS, Ticket, custom_id_for

SCHEMA = """
CREATE TABLE IF NOT EXISTS items (
    custom_id TEXT PRIMARY KEY, ticket_id TEXT, text TEXT,
    status TEXT NOT NULL DEFAULT 'pending',   -- pending | submitted | done | failed (given up)
    batch_key TEXT, attempts INTEGER NOT NULL DEFAULT 0, label TEXT, detail TEXT,
    est_tokens INTEGER NOT NULL DEFAULT 0,    -- rough prompt tokens, to respect a queued-token cap
    cost_usd REAL NOT NULL DEFAULT 0);        -- summed over every attempt that was billed
CREATE TABLE IF NOT EXISTS batches (
    batch_key TEXT PRIMARY KEY,               -- OUR name for the batch, decided before we call the API
    batch_id TEXT,                            -- the provider's ID, once we know it
    status TEXT NOT NULL);                    -- creating | submitted | collected | rejected (failed validation)
"""
TERMINAL = {"completed", "failed", "expired", "cancelled"}


def estimate_tokens(text: str) -> int:
    """The rough '4 characters per token' rule on instruction + ticket (03.7 has exact counting)."""
    return (len(INSTRUCTIONS) + len(text)) // 4 + 1


def crash_point(name: str) -> None:
    """For the demo only: simulate `kill -9` at a named point."""
    if os.environ.get("CRASH_AT") == name:
        print(f"  !! crashing at {name}", flush=True)
        os._exit(1)                          # no cleanup, no flush: what `kill -9` does


class BatchJob:
    def __init__(self, client: OpenAI, db_path: Path, workdir: Path, job: str = "triage-v1",
                 chunk_size: int = 50_000, max_attempts: int = 3,
                 queue_cap_tokens: int | None = None, max_open_batches: int | None = None) -> None:
        """queue_cap_tokens: the most prompt tokens you may have waiting in batches at once (OpenAI's per-model
        queued-token limit, Gemini's enqueued-token cap: look yours up). max_open_batches: a simpler cap."""
        self.client, self.workdir, self.job = client, workdir, job
        self.chunk_size, self.max_attempts = chunk_size, max_attempts
        self.queue_cap_tokens, self.max_open_batches = queue_cap_tokens, max_open_batches
        self.peak_queued_tokens = 0
        self.prices = PriceTable.load()
        self.db = sqlite3.connect(db_path)
        self.db.executescript(SCHEMA)
        workdir.mkdir(exist_ok=True)

    def load(self, tickets: list[Ticket]) -> None:
        """Idempotent: re-running adds new tickets and ignores ones already known."""
        with self.db:
            self.db.executemany("INSERT OR IGNORE INTO items (custom_id, ticket_id, text, est_tokens) VALUES (?, ?, ?, ?)",
                                [(custom_id_for(t, self.job), t.ticket_id, t.text, estimate_tokens(t.text)) for t in tickets])

    def recover(self) -> None:
        """A batch stuck in 'creating' means we crashed around batches.create. Ask the provider."""
        for batch_key, in self.db.execute("SELECT batch_key FROM batches WHERE status = 'creating'").fetchall():
            # batches.list() is newest first and auto-paginates through the WHOLE account if you iterate it, so
            # look at the first page only: a batch we created moments ago is on it. (An account that has made more
            # than 100 batches since would hide ours: then raise `limit` or follow `after`.)
            recent = self.client.batches.list(limit=100).data
            found = next((b for b in recent if (b.metadata or {}).get("batch_key") == batch_key), None)
            with self.db:
                if found:                          # it exists: adopt it instead of paying twice
                    self.db.execute("UPDATE batches SET batch_id = ?, status = 'submitted' WHERE batch_key = ?",
                                    (found.id, batch_key))
                    print(f"  recovered {batch_key} -> {found.id} (created before the crash)")
                else:                              # it never got created: put its items back
                    self.db.execute("UPDATE items SET status = 'pending', batch_key = NULL, attempts = attempts - 1 "
                                    "WHERE batch_key = ?", (batch_key,))
                    self.db.execute("DELETE FROM batches WHERE batch_key = ?", (batch_key,))
                    print(f"  {batch_key} was never created; its items are pending again")

    def queued(self) -> tuple[int, int]:
        """(open batches, estimated prompt tokens waiting in them): what the provider's queue holds from us."""
        n, = self.db.execute("SELECT COUNT(*) FROM batches WHERE status IN ('creating', 'submitted')").fetchone()
        tokens, = self.db.execute("SELECT COALESCE(SUM(est_tokens), 0) FROM items WHERE status = 'submitted'").fetchone()
        return n, tokens

    def submit_pending(self) -> None:
        """Submit pending items chunk by chunk, but only while the queue has room. What does not fit stays
        `pending`; run() calls this again after each collect, so the job drains through the cap gradually."""
        rows = self.db.execute("SELECT custom_id, ticket_id, text, est_tokens FROM items WHERE status = 'pending' "
                               "AND attempts < ? ORDER BY custom_id", (self.max_attempts,)).fetchall()
        for start in range(0, len(rows), self.chunk_size):       # split under the per-batch limits
            chunk = rows[start:start + self.chunk_size]
            chunk_tokens = sum(t for *_, t in chunk)
            open_batches, queued_tokens = self.queued()
            if open_batches:                                      # something is queued: is there room for this chunk?
                if self.max_open_batches is not None and open_batches >= self.max_open_batches:
                    break
                if self.queue_cap_tokens is not None and queued_tokens + chunk_tokens > self.queue_cap_tokens:
                    break
            elif self.queue_cap_tokens is not None and chunk_tokens > self.queue_cap_tokens:
                # even an EMPTY queue can't take it: waiting won't help, so say so instead of looping forever
                raise ValueError(f"a chunk of ~{chunk_tokens} tokens exceeds the queue cap of {self.queue_cap_tokens}: "
                                 "use a smaller chunk_size")
            self.peak_queued_tokens = max(self.peak_queued_tokens, queued_tokens + chunk_tokens)
            n = self.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0]
            batch_key = f"{self.job}-b{n:04d}"
            with self.db:                                         # 1. record the intent first
                self.db.execute("INSERT INTO batches VALUES (?, NULL, 'creating')", (batch_key,))
                self.db.executemany("UPDATE items SET status = 'submitted', batch_key = ?, attempts = attempts + 1 "
                                    "WHERE custom_id = ?", [(batch_key, cid) for cid, *_ in chunk])
            crash_point(f"before_create_{batch_key}")             # a crash here leaves an uploaded-or-not file and no batch
            path = self.workdir / f"{batch_key}.jsonl"
            build_jsonl([Ticket(tid, text) for _, tid, text, _ in chunk], path, job=self.job)
            with path.open("rb") as f:
                file_id = self.client.files.create(file=f, purpose="batch").id
            batch = self.client.batches.create(input_file_id=file_id, endpoint="/v1/responses",
                                               completion_window="24h", metadata={"batch_key": batch_key})
            crash_point(f"after_create_{batch_key}")              # the dangerous window
            with self.db:                                         # 2. record the provider's ID
                self.db.execute("UPDATE batches SET batch_id = ?, status = 'submitted' WHERE batch_key = ?",
                                (batch.id, batch_key))
            print(f"  submitted {batch_key} = {batch.id} ({len(chunk)} items, ~{chunk_tokens} tokens; "
                  f"queue now ~{queued_tokens + chunk_tokens})", flush=True)

    def collect_finished(self) -> int:
        """Check each open batch once; reconcile the finished ones. Returns how many are still open."""
        still_open = 0
        for batch_key, batch_id in self.db.execute(
                "SELECT batch_key, batch_id FROM batches WHERE status = 'submitted'").fetchall():
            batch = self.client.batches.retrieve(batch_id)
            if batch.status not in TERMINAL:
                still_open += 1
                continue
            if batch.status == "failed":
                # The INPUT was rejected: nothing ran, so there are no results to reconcile, and sending the same
                # file again would fail the same way. Record why, give up on these items, and move on.
                problems = "; ".join(f"line {e.line}: {e.code}: {e.message}"
                                     for e in (batch.errors.data if batch.errors and batch.errors.data else []))
                with self.db:
                    self.db.execute("UPDATE items SET status = 'failed', detail = ? WHERE batch_key = ?",
                                    (f"batch {batch_id} failed validation: {problems or 'no details'}", batch_key))
                    self.db.execute("UPDATE batches SET status = 'rejected' WHERE batch_key = ?", (batch_key,))
                print(f"  REJECTED {batch_key} ({batch_id}): {problems}. Not resubmitted: fix the input, then requeue.")
                continue
            paths = {}
            for kind, file_id in (("out", batch.output_file_id), ("err", batch.error_file_id)):
                if file_id:
                    paths[kind] = self.workdir / f"{batch_key}.{kind}.jsonl"
                    download(self.client, file_id, paths[kind])   # streamed to disk, not held in memory
            attempts = dict(self.db.execute("SELECT custom_id, attempts FROM items WHERE batch_key = ?", (batch_key,)))
            # completed, expired or cancelled: whatever is missing from the files is a retryable failure
            results = reconcile(paths.get("out"), paths.get("err"), set(attempts))
            with self.db:                                         # results and batch status: one transaction
                for cid, r in results.items():
                    if r.status == "ok":
                        status, detail = "done", r.detail
                    elif r.retry and attempts[cid] < self.max_attempts:
                        status, detail = "pending", r.detail      # worth another try, and attempts remain
                    else:                                         # permanent, or out of attempts: GIVE UP, say why
                        status = "failed"
                        detail = r.detail + (f" (gave up after {attempts[cid]} attempts)" if r.retry else "")
                    self.db.execute("UPDATE items SET status = ?, label = ?, detail = ?, cost_usd = cost_usd + ? "
                                    "WHERE custom_id = ?",
                                    (status, r.label, detail, job_cost([r.usage], self.prices).usd, cid))
                self.db.execute("UPDATE batches SET status = 'collected' WHERE batch_key = ?", (batch_key,))
            crash_point(f"after_collect_{batch_key}")
            print(f"  collected {batch_key}: {sum(r.status == 'ok' for r in results.values())}/{len(results)} ok")
        return still_open

    def run(self, poll_seconds: float = 60.0) -> None:
        self.recover()
        while True:
            self.submit_pending()
            if self.collect_finished() == 0 and not self.db.execute(
                    "SELECT 1 FROM items WHERE status = 'pending' AND attempts < ?", (self.max_attempts,)).fetchone():
                break
            time.sleep(poll_seconds)

    def summary(self) -> dict[str, int]:
        return dict(self.db.execute("SELECT status, COUNT(*) FROM items GROUP BY status").fetchall())

    def cost_usd(self) -> float:
        return self.db.execute("SELECT COALESCE(SUM(cost_usd), 0) FROM items").fetchone()[0]

    def failures(self) -> list[tuple[str, str]]:
        """What a human needs to see: every item we gave up on, and why."""
        return self.db.execute("SELECT ticket_id, detail FROM items WHERE status = 'failed' ORDER BY ticket_id").fetchall()

Why each part is shaped as it is:

  • load() is idempotent (INSERT OR IGNORE): run it again with the same data and nothing changes. New tickets are added; known ones are left alone. It also stores a rough token estimate per item, which the queue cap needs.
  • submit_pending() submits chunk by chunk, but only while the queue has room: it stops when max_open_batches batches are open, or when the estimated tokens already queued plus the next chunk would exceed queue_cap_tokens. What doesn't fit stays pending, and run() calls it again after each collect, so the job drains through the cap gradually. (If even an empty queue can't hold one chunk, it raises instead of waiting forever: use a smaller chunk_size.) For each chunk it writes the intent (items submitted, batch creating) in one transaction, builds the file, uploads it, creates the batch with metadata={"batch_key": ...}, and only then records the provider's ID. attempts is incremented here, so an item can't be resubmitted forever (max_attempts).
  • The dangerous window is between batches.create returning and the database write. If the process dies there, the batch exists at OpenAI but the manifest says creating. crash_point() lets the demo kill the process at three named places: before_create_<batch_key> (the intent is recorded, nothing is at the provider), after_create_<batch_key> (the dangerous window) and after_collect_<batch_key> (results stored, batch marked). A crash between files.create and batches.create also leaves an orphan upload: an input file in your account that no batch uses, which recover() never deletes. List your files with purpose="batch" and delete the stragglers now and then (03.6, Part 5).
  • recover() runs first on every start. For each batch stuck in creating, it looks through the first page of client.batches.list(limit=100) for a batch whose metadata carries our batch_key. The list is newest first and iterating it directly would page through every batch the project has ever made, so the runner takes one page: a batch we created moments ago is on it (raise limit, or follow after, on a busy account). If found, it adopts it ("created before the crash"); if not, the create never happened, so the items go back to pending and the attempt is not counted.
  • collect_finished() polls each open batch once (no sleeping inside), streams the files to disk, reconciles, and in one transaction stores every item result and marks the batch collected. Each item then ends in one of three places: done; pending again, if its failure is retryable and it has attempts left; or failed, with the reason and, if it ran out of attempts, "gave up after N attempts". An item can no longer sit in pending forever with nothing that will pick it up.
  • A batch with status failed is different from a batch with failed requests. failed means the provider rejected the input (7.3): nothing ran, and sending the same file again would be rejected the same way. The runner marks the batch rejected, stores batch.errors (line, code, message) as each item's detail, sets its items to failed, and does not resubmit. Only completed, expired and cancelled batches go through reconciliation, where anything missing from the files is a retryable failure. After you fix the input, requeue the items yourself (UPDATE items SET status = 'pending', attempts = 0 WHERE ...).
  • Cost. Each result's usage is priced by batch_cost (03.7's cost_calc at the batch tier) and added to the item's cost_usd on every attempt that was billed, so job.cost_usd() is the real total, retries included.
  • run() loops: recover, submit, collect, sleep, until nothing is pending and nothing is open.
  • Chunking is by chunk_size here (tiny in the demo); use plan_chunks() in real code.

The demo runs the whole thing against the mock OpenAI Batch API from 7.5 with its state kept in a file, so that, like a real provider, it outlives the crashed process. The first job loads 23 tickets in chunks of 5 under a queue cap of 300 estimated tokens (two chunks fit, three don't), then kills the process with os._exit(1) (no cleanup, as kill -9 would) right after the second batches.create, and starts it again twice. The second job (the last run in the script) has a ticket that makes the provider reject its batch and a ticket that fails on every attempt:

python
"""s11_6_resumable.py: run the resumable job against a MOCK Batch API whose state lives in a file
(like a real provider, it survives our crash). Two demos, chosen with DEMO=...:
  cap (default): 23 tickets under a queue cap, with CRASH_AT=... to kill the process mid-job;
  bad:           a batch the provider REJECTS, and a ticket that fails on every attempt."""
import os
import sys
from pathlib import Path

import httpx2
from openai import OpenAI

from batch_runner import BatchJob
from mock_openai_batch import MockOpenAIBatches
from tickets import Ticket

DEMO = os.environ.get("DEMO", "cap")
WORK = Path("data/resumable" if DEMO == "cap" else "data/resumable_bad")
WORK.mkdir(parents=True, exist_ok=True)
mock = MockOpenAIBatches(state_path=WORK / "provider_state.json")
client = OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(mock.handler)))

if DEMO == "cap":
    # ~27 estimated tokens per ticket, 135 per chunk of 5: a cap of 300 lets two chunks wait at once, not three
    job = BatchJob(client, WORK / "checkpoint.sqlite", WORK, chunk_size=5, queue_cap_tokens=300)
    job.load([Ticket(f"{10300 + i}", f"ticket text {i}") for i in range(23)])
else:
    job = BatchJob(client, WORK / "checkpoint.sqlite", WORK, chunk_size=5, max_attempts=3)
    tickets = [Ticket(f"{10300 + i}", f"ticket text {i}") for i in range(14)]
    tickets[3] = Ticket("10303", "INVALID: this line makes the provider reject its whole batch")
    tickets[7] = Ticket("10307", "POISON: this one fails on every attempt")
    job.load(tickets)

print("before:", job.summary(), flush=True)
job.run(poll_seconds=0.01)
print("after: ", job.summary(), f"| cost ${job.cost_usd():.6f}")
state = mock.state
print(f"provider saw {len(state['batches'])} batches created; at most {state['peak_open']} open at once"
      + (f"; our queue estimate peaked at ~{job.peak_queued_tokens} tokens" if job.peak_queued_tokens else ""))
for ticket_id, detail in job.failures():
    print(f"  failed {ticket_id}: {detail}")
sys.exit(0)
bash
#!/bin/bash
# s11_6_demo.sh: start the job, kill it right after the 2nd batch is created, then run it again;
# then a second job in which the provider rejects one batch and one ticket never succeeds.
cd "$(dirname "$0")"; rm -rf data/resumable data/resumable_bad
RUN="uv run -q --with openai --with anthropic --with google-genai --with httpx --with python-dotenv --with pyyaml --with pydantic python s11_6_resumable.py"
echo "=== run 1 (crashes) ==="; CRASH_AT=after_create_triage-v1-b0001 $RUN; echo "exit code $?"
echo "=== run 2 (resumes) ==="; $RUN
echo "=== run 3 (nothing left to do) ==="; $RUN
echo "=== a rejected batch and a ticket that never works ==="; DEMO=bad $RUN
Output · mock server46 lines
=== run 1 (crashes) ===
before: {'pending': 23}
  submitted triage-v1-b0000 = batch_2 (5 items, ~130 tokens; queue now ~130)
  !! crashing at after_create_triage-v1-b0001
exit code 1
=== run 2 (resumes) ===
before: {'pending': 13, 'submitted': 10}
  recovered triage-v1-b0001 -> batch_4 (created before the crash)
  collected triage-v1-b0000: 3/5 ok
  collected triage-v1-b0001: 3/5 ok
  submitted triage-v1-b0002 = batch_10 (5 items, ~130 tokens; queue now ~130)
  submitted triage-v1-b0003 = batch_12 (5 items, ~130 tokens; queue now ~260)
  collected triage-v1-b0002: 4/5 ok
  collected triage-v1-b0003: 3/5 ok
  submitted triage-v1-b0004 = batch_18 (5 items, ~130 tokens; queue now ~130)
  submitted triage-v1-b0005 = batch_20 (5 items, ~130 tokens; queue now ~260)
  collected triage-v1-b0004: 4/5 ok
  collected triage-v1-b0005: 3/5 ok
  submitted triage-v1-b0006 = batch_26 (3 items, ~78 tokens; queue now ~78)
  collected triage-v1-b0006: 3/3 ok
after:  {'done': 23} | cost $0.000063
provider saw 7 batches created; at most 2 open at once; our queue estimate peaked at ~260 tokens
=== run 3 (nothing left to do) ===
before: {'done': 23}
after:  {'done': 23} | cost $0.000063
provider saw 7 batches created; at most 2 open at once
=== a rejected batch and a ticket that never works ===
before: {'pending': 14}
  submitted triage-v1-b0000 = batch_2 (5 items, ~142 tokens; queue now ~142)
  submitted triage-v1-b0001 = batch_4 (5 items, ~137 tokens; queue now ~279)
  submitted triage-v1-b0002 = batch_6 (4 items, ~104 tokens; queue now ~383)
  REJECTED triage-v1-b0000 (batch_2): line 4: invalid_value: Invalid value in body.input. Not resubmitted: fix the input, then requeue.
  collected triage-v1-b0001: 2/5 ok
  collected triage-v1-b0002: 2/4 ok
  submitted triage-v1-b0003 = batch_12 (5 items, ~137 tokens; queue now ~137)
  collected triage-v1-b0003: 4/5 ok
  submitted triage-v1-b0004 = batch_16 (1 items, ~33 tokens; queue now ~33)
  collected triage-v1-b0004: 0/1 ok
after:  {'done': 8, 'failed': 6} | cost $0.000022
provider saw 5 batches created; at most 3 open at once; our queue estimate peaked at ~383 tokens
  failed 10300: batch batch_2 failed validation: line 4: invalid_value: Invalid value in body.input
  failed 10301: batch batch_2 failed validation: line 4: invalid_value: Invalid value in body.input
  failed 10302: batch batch_2 failed validation: line 4: invalid_value: Invalid value in body.input
  failed 10303: batch batch_2 failed validation: line 4: invalid_value: Invalid value in body.input
  failed 10304: batch batch_2 failed validation: line 4: invalid_value: Invalid value in body.input
  failed 10307: HTTP 500: The server had an error [request_id req_triage-v1-10307] (gave up after 3 attempts)

Read the four runs:

  • Run 1 submitted batch b0000 (~130 tokens in the queue), created b0001 at the provider, and died before recording it. Exit code 1.
  • Run 2 starts with {'pending': 13, 'submitted': 10}: the manifest knows ten items are in flight. recover() found b0001 at the provider by its batch_key and adopted it, rather than creating a duplicate. The queue is already at its cap (two batches, about 260 of the 300 tokens), so the first pass submits nothing and only collects. From then on the job never has more than two batches queued: each pass submits as many chunks as the cap allows, collects, and submits more. The last line shows it from both sides: the provider's own record says at most 2 batches were open at once, and the runner's estimate peaked at ~260 tokens, under the cap of 300. (A runner that submitted every chunk in its first pass would, on a provider with a queued-token cap, make exactly the over-limit submission that 11.4 warns about.) The mock fails two requests per batch on their first attempt (a 500 and an expiry), and those items went back into later batches. Final state: all 23 items done, at a total cost of $0.000063.
  • Run 3 found nothing to do and exited at once.
  • The last job shows two more cases a real job meets: a rejected batch and a ticket that never works. Batch b0000 held a line that the mock provider rejects (status: failed, with errors naming line 4). The runner printed REJECTED, marked its five items failed with the provider's message, and did not resubmit it: the provider saw 5 batches created, not a stream of identical rejected files. Ticket 10307 failed with a 500 on every attempt, so after three submissions (max_attempts) it is failed, with "gave up after 3 attempts" and the request ID of its last failure, the ticket-ready record from 03.8, Part 12. The final summary is {'done': 8, 'failed': 6}, not a pile of items stuck in pending.

The job never resubmitted a finished item and never lost a batch. Two limits of this sketch: it handles one provider and one kind of crash (the process dying; a corrupted database or a deleted work folder would need backups), and polling inside run() is blunt (a real service would hand the polling to a scheduler, Module 11C). Recovery differs by provider, because it depends on what you can tag:

Can you tag the batch with your key? How to recover a batch created just before a crash
OpenAI Yes: metadata (16 pairs) As above: scan the first page of batches.list() for your batch_key
Anthropic No field on batches.create List batches created after your intent record and match on request_counts total (and, if needed, peek at the results' custom_ids). If it's ambiguous, accept the duplicate or cancel the extra one
Can you tag the batch with your key? How to recover a batch created just before a crash
Gemini Yes: display_name (use your batch_key) Scan client.batches.list() for it
OpenRouter No List batches created after your intent record and match on request_counts.total

11.7 Retrying failures without duplicating work#

After the first pass, you have some done, a few pending (retryable failures) and a few failed or invalid. What next?

  • Retry the retryable ones, a limited number of times. attempts and max_attempts stop an item that keeps failing from being resubmitted forever (and from costing money each time), and an item that runs out of attempts is marked failed with the reason, so the final summary tells the truth. A rejected batch (failed) is not a retry candidate at all: fix the input first.
  • Change something when the retry would otherwise repeat. A truncated answer needs a larger max_output_tokens; a wrong-format answer needs a stricter instruction or a better model. Resubmitting the identical request after a deterministic failure just pays twice.
  • Use a different path for the tail. The last 40 items of a 20,000-item job don't deserve a 24-hour batch window. Run the failures through the async path (Parts 3 to 5) with a stronger model if needed: they're few, you pay the standard price on a handful, and the job finishes today.
  • Keep the attempt history. When an item ends up failed, a human should be able to see its last error and every request ID involved. That's the same ticket-ready record 03.8, Part 12 describes for single calls.
  • Report the totals. At the end, print the counts (job.summary()), the total cost (job.cost_usd(), which includes every billed attempt) and the list of items you gave up on (job.failures()). If the counts don't add up to the input size, something was lost.

11.8 A checklist#

Before you submit While it runs After it ends
Dry-run one request of each shape through the synchronous API Save the batch ID the moment you have it Download results immediately, to disk
Deterministic custom_ids with a job and prompt version Poll with growing intervals and a maximum wait Join on the ID; check the counts add up
Split under the request, byte and token limits, and submit under the queue cap Record state transitions in the manifest Validate each result (stop reason, format, schema)
Estimate the cost and refuse above a threshold Don't resubmit "just in case" Resubmit only retryable failures, once or twice, with a change
Use a separate project or key for bulk work Watch for expiry (the clock started at creation) Delete uploaded files (and any orphan uploads from a crash) and batches you don't need. Report the job's cost

Part 12: Flex and priority tiers#

Deep-dive

Between "standard" and "Batch API" there's a middle path: keep calling the normal synchronous endpoint, but tell the provider how urgent the call is. A flex tier trades speed and certainty for a lower price. A priority (fast) tier trades money for speed. The prices are in 02.9, 6.5, and applying them to a bill is 03.7; this part is about using them in code. All of it is as of November 2026, and the tiers are young (several are beta or preview), so check the current pages before you depend on one.

12.1 The tiers, provider by provider#

OpenAI Anthropic
Cheaper, slower service_tier="flex" (beta, limited models): Batch prices on a synchronous call None
Faster, dearer service_tier="fast"; "priority" is the same (renamed Fast mode on 30 July 2026) speed="fast" on Claude Fable 5.2 and Opus 5.5 (research preview on Opus 5, by waitlist, and on Opus 4.8, where it is deprecated and removed on 30 November 2026; both need the fast-mode-2026-02-01 beta header)
Even faster "ultrafast", access-controlled, on a few models None
The default "auto": the project's setting (standard unless you changed it) Standard
What flex feels like Slower, and sometimes a 429 Resource Unavailable (not charged) n/a
Does it fall back for you? No: you retry, or resend with "auto" n/a
How to see the tier used response.service_tier usage.service_tier (standard, priority, batch) and usage.speed (standard, fast)
Read the docs Flex, Fast mode Fast mode, Service tiers
Gemini OpenRouter
Cheaper, slower service_tier flex (preview): 50% of standard service_tier: "flex", or the :floor variant
Faster, dearer service_tier priority (preview): 75% to 100% above standard service_tier: "priority" or "fast", or the :nitro variant
Even faster None "ultrafast" (selected OpenAI models, opt-in)
The default Standard The provider's regular capacity
What flex feels like Minutes (a 1 to 15 minute target); best-effort and "sheddable": may be preempted; 503 or 429 when at capacity A flex endpoint can return a capacity error like the provider's
Does it fall back for you? No: "To prevent unexpected charges, the system won't automatically upgrade a Flex request to the Standard tier if Flex capacity is full" Routing admits flex endpoints only when it's cheapest, and falls back only to equal-or-cheaper endpoints
How to see the tier used The x-gemini-service-tier response header, documented on the priority page (its possible values aren't listed); the flex page documents no tier field or header service_tier at the top level (Chat Completions, Responses) or in usage (Messages)
Read the docs Flex, Priority Service tiers

Each provider's details:

  • OpenAI flex. Set service_tier="flex" on a Responses or Chat Completions request. It's priced at Batch rates, and prompt caching discounts add to that. It's beta with a limited set of models (the pricing page lists them). Flex requests may wait in a queue, so the guide raises the SDK timeout from the default 10 minutes to 15 (OpenAI(timeout=900.0), or per request with client.with_options(timeout=900.0)). The SDK retries a 408 twice by itself. When flex has no capacity you get a 429 Resource Unavailable and you aren't charged; the guide suggests either exponential backoff or retrying with standard processing, by resending with service_tier="auto" (or omitting the parameter).
  • OpenAI fast. service_tier="fast" or "priority" ("Priority processing was renamed Fast mode on July 30, 2026") gives up to 2.5× the speed and more consistent latency for a per-token premium (twice the standard rate for GPT-5.6 Sol, the one model whose multiplier the guide states, as of November 2026; the price table is 03.7's). There's a ramp limit: once your traffic reaches about a million input tokens per minute, increase it by no more than 50% every 15 minutes, or some requests are downgraded to standard speed and billed at standard rates, with service_tier: "default" in the response. The guide's advice: "Avoid running large extract, transform, and load (ETL) or batch jobs in Fast mode." Fast is for latency, not for bulk throughput. You can also set a project-level tier in the dashboard, so requests with no service_tier default to Fast.
  • Anthropic. There's no flex. The service_tier parameter ("auto" or "standard_only") only matters if you hold a Priority Tier capacity commitment, which Anthropic describes as legacy and no longer sells ("Service tiers are legacy"). Fast mode (speed="fast") is the current option: up to 2.5× output tokens per second on supported models, at premium prices ($8 and $40 per million input and output tokens on Opus 5.5, $16 and $80 on Fable 5.2; see 03.7). It has its own rate limit (headers anthropic-fast-input-tokens-remaining and friends), isn't available in Batch API requests or with a Priority Tier commitment, and requests at different speeds don't share prompt-cache entries. The SDK retries a fast-mode 429 twice, honouring retry-after; to fall back to standard speed instead of waiting, set max_retries=0 on that request, catch RateLimitError, and resend without speed. The docs show this pattern in full. Two dates to know: fast mode on Claude Opus 4.8 is deprecated and will be removed on 30 November 2026 (afterwards speed: "fast" on claude-opus-4-8 returns an error), and fast mode on Opus 5 is a research preview you get by contacting your account manager or joining the waitlist; Fable 5.2 and Opus 5.5 are the models where it is generally available (as of November 2026, checked on Anthropic's fast-mode page on 11 November 2026).
  • Gemini. Google's flex and priority pages show service_tier on the Interactions API: client.interactions.create(model=..., input=..., service_tier="flex") (or "priority"), and they don't mention generate_content. The SDK's types.ServiceTier enum (flex, standard, priority) and a service_tier field on GenerateContentConfig also exist in google-genai 2.34.0, so generate_content accepts it too, but that form is SDK-only: Google's pages don't document it, so test it before you depend on it. Timeouts in the Gemini SDK are in milliseconds (03.8, 6.1): Google's own example is HttpOptions(timeout=900000) for 15 minutes. Flex traffic "counts toward general rate limits"; it doesn't get the extended limits Batch has. Priority has its own limits, 0.3× the standard limits by default, and overflow is downgraded quietly: "automatically and gracefully downgraded to Standard processing", "instead of failing with a 503 or 429 error", billed at standard rates. The priority page tells you to watch the x-gemini-service-tier response header to see how often that happens; it doesn't list the header's possible values (the only one it names is standard, in the context of a downgrade), so treat anything other than the tier you asked for as a downgrade and log it. The flex page documents no response field or header at all.
  • OpenRouter. The service_tier request field (default, flex, priority, fast, ultrafast) is accepted on Chat Completions and on the Anthropic-style Messages endpoint; the model variants :floor (sort by price, admit flex endpoints) and :nitro (sort by throughput, admit priority endpoints) are the lighter-weight route. A request is billed at the tier that served it. The response reports priority, never fast. A priority request that falls back to a default endpoint is billed at the standard rate.

12.2 Try it: flex with backoff and a fallback to standard#

Flex is a bet: usually half price, sometimes a 429. A job that uses it needs the second half of the bet written down: what do we do when flex says no? The function below tries flex a few times with backoff, treats only a rate-limit-type error as "flex is busy" (any other failure, such as a quota error or a bad request, is raised: falling back to standard wouldn't fix it), and finally pays the standard price instead of failing. It uses classify() from 03.8. The server is a mock that says "no capacity" twice in one scenario and forever in the other; the SDK and its exceptions are real:

python
"""s12_1_flex_mock.py: handling OpenAI flex processing: slow answers, 429 "Resource Unavailable",
and falling back to the standard tier. MOCK server; the real openai SDK and its real exceptions."""
import asyncio
import json

import httpx2
import openai
from openai import AsyncOpenAI
from openai.types.responses import Response

from llm_errors import Kind, classify
from mock_llm import error_body, response_body

busy_for = 2          # the mock says "no flex capacity" for the first 2 flex requests
log: list[str] = []   # what the server saw


async def handler(request: httpx2.Request) -> httpx2.Response:
    global busy_for
    tier = json.loads(request.content).get("service_tier", "auto")
    log.append(tier)
    if tier == "flex":
        await asyncio.sleep(0.2)                    # flex is slower: minutes in real life
        if busy_for > 0:
            busy_for -= 1
            # FIXTURE: flex has no capacity. OpenAI documents "429 Resource Unavailable" (not charged);
            # the docs don't give an error code, so we only rely on the status.
            body = error_body(429)
            body["error"]["message"] = "Resource Unavailable"
            return httpx2.Response(429, json=body)
        return httpx2.Response(200, json=response_body("billing", service_tier="flex"))
    return httpx2.Response(200, json=response_body("billing", service_tier="default"))


async def classify_with_flex(client: AsyncOpenAI, text: str, *, flex_attempts: int = 3,
                             backoff: float = 0.05) -> tuple[Response, str]:
    """Try flex a few times with backoff, then pay the standard price rather than fail."""
    for attempt in range(1, flex_attempts + 1):
        try:
            response = await client.responses.create(
                model="gpt-6-luna", input=text, max_output_tokens=16, service_tier="flex")
            return response, f"flex on attempt {attempt}"
        except openai.APIStatusError as e:
            failure = classify(e)
            if failure.kind is not Kind.RATE_LIMITED:     # quota, auth, bad request...: never fall back
                raise
            print(f"  attempt {attempt}: 429 {failure.message!r} (not billed)")
            await asyncio.sleep(backoff * 2 ** attempt)
    response = await client.responses.create(             # "auto" = the project's default tier
        model="gpt-6-luna", input=text, max_output_tokens=16, service_tier="auto")
    return response, "fell back to standard"


async def main() -> None:
    global busy_for
    client = AsyncOpenAI(api_key="sk-test", max_retries=0, timeout=900.0,    # 15 minutes, as OpenAI's flex guide suggests
                         http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)))
    async with client:
        for label, busy in (("flex has capacity after 2 refusals", 2), ("flex stays busy", 99)):
            busy_for, log[:] = busy, []
            response, how = await classify_with_flex(client, "Refund still not received")
            print(f"{label}: {how}; response.service_tier={response.service_tier!r}; "
                  f"server saw tiers {log}")

asyncio.run(main())
Output · mock server7 lines
  attempt 1: 429 'Error code: 429 - Resource Unavailable' (not billed)
  attempt 2: 429 'Error code: 429 - Resource Unavailable' (not billed)
flex has capacity after 2 refusals: flex on attempt 3; response.service_tier='flex'; server saw tiers ['flex', 'flex', 'flex']
  attempt 1: 429 'Error code: 429 - Resource Unavailable' (not billed)
  attempt 2: 429 'Error code: 429 - Resource Unavailable' (not billed)
  attempt 3: 429 'Error code: 429 - Resource Unavailable' (not billed)
flex stays busy: fell back to standard; response.service_tier='default'; server saw tiers ['flex', 'flex', 'flex', 'auto']

Check what the server saw. In the first scenario the third flex attempt succeeded and the response said service_tier='flex'. In the second, three flex attempts failed, and the fourth request used "auto" and the response said 'default': we paid the standard price, and the response tells us so. The mock's 429 Resource Unavailable message follows OpenAI's guide, which doesn't give an error code, so the function relies on the status alone. It also sets the client timeout to 900 s, as the guide suggests, and max_retries=0 so that this code is the only retry layer (03.8, 5.5).

Two production notes. A flex job should still have a deadline (5.3): "retry flex until it works" can wait for hours. And when you fall back, count it: if more than a few percent of your requests end up standard-priced, the saving is mostly gone, and a Batch API may be the better tool.

12.3 Provider sample: ask each provider for a tier, then read which one served you#

python
"""s12_2_tiers.py: ask each provider for its cheaper-but-slower tier (or its faster one), then read
which tier actually served the request. Needs the four keys in .env."""
import os

import anthropic
from dotenv import load_dotenv
from google import genai
from google.genai import types
from openai import OpenAI

load_dotenv()
PROMPT = "Classify this ticket as billing, bug, account or other: 'Refund still not received after 14 days.'"

# --- OpenAI: flex = Batch prices for a synchronous call. Slower, so raise the timeout (default 10 min).
openai_client = OpenAI(timeout=900.0)
response = openai_client.responses.create(
    model="gpt-6-luna", input=PROMPT, reasoning={"effort": "none"}, max_output_tokens=16,
    service_tier="flex")                       # "fast" (alias "priority") is the other direction
print("OpenAI    asked flex, served:", response.service_tier)      # "flex"; "default" if it was downgraded

# --- Anthropic: no flex tier. Its service_tier parameter ("auto" / "standard_only") only matters if you
# hold a Priority Tier commitment (no longer sold). The "pay more for speed" option is fast mode.
claude = anthropic.Anthropic()
message = claude.messages.create(
    model="claude-opus-5-5", max_tokens=256, speed="fast",
    messages=[{"role": "user", "content": PROMPT}])
print("Anthropic asked fast, served speed:", message.usage.speed, "| tier:", message.usage.service_tier)

# --- Gemini: Google documents service_tier on the INTERACTIONS API (its flex and priority pages).
# SDK timeouts are in MILLISECONDS. The flex page documents no response field or header that names the tier served.
gemini = genai.Client(http_options=types.HttpOptions(timeout=900_000))
interaction = gemini.interactions.create(model="gemini-3.8-flash", input=PROMPT, service_tier="flex")
print("Gemini    asked flex on Interactions, status:", interaction.status)

# google-genai 2.34.0 ALSO accepts the field on generate_content (SDK only: Google's pages show no such form).
# Priority's page says to watch the x-gemini-service-tier response header, without listing its possible values.
reply = gemini.models.generate_content(
    model="gemini-3.8-flash", contents=PROMPT,
    config=types.GenerateContentConfig(
        service_tier=types.ServiceTier.FLEX, max_output_tokens=256,
        thinking_config=types.ThinkingConfig(thinking_level=types.ThinkingLevel.LOW)))
headers = {k.lower(): v for k, v in ((reply.sdk_http_response.headers if reply.sdk_http_response else None) or {}).items()}
print("Gemini    asked flex on generate_content, x-gemini-service-tier:", headers.get("x-gemini-service-tier"))

# --- OpenRouter: a top-level service_tier on Chat Completions (or the :floor / :nitro model variants)
router = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"],
                default_headers={"HTTP-Referer": "https://example.com", "X-OpenRouter-Title": "Tier demo"},
                timeout=900.0)
completion = router.chat.completions.create(
    model="openai/gpt-6-luna", max_completion_tokens=64, service_tier="flex",
    messages=[{"role": "user", "content": PROMPT}])
print("OpenRouter asked flex, served:", completion.service_tier)    # top-level on Chat Completions
Example output · illustrative5 lines
OpenAI    asked flex, served: flex
Anthropic asked fast, served speed: fast | tier: standard
Gemini    asked flex on Interactions, status: completed
Gemini    asked flex on generate_content, x-gemini-service-tier: None
OpenRouter asked flex, served: flex

The service_tier, speed and ServiceTier.FLEX names are the real names in the SDK versions named in Setup (a type checker confirms them; interactions.create takes untyped **body, so a type checker can't check its service_tier, and the documentation is the authority there). Against the local stand-in the OpenAI and Anthropic parts run end to end: Ollama ignores tiers and replies normally, so every tier field comes back empty or default locally, and that is why the output above is illustrative. The Gemini part is hosted-only, because Gemini has no local stand-in. Notice the three places the answer lives: a field on the response object (OpenAI, OpenRouter), a field inside usage (Anthropic), and a response header (Gemini), which the sample reads through response.sdk_http_response.headers on the SDK-only generate_content form. Gemini's documented form is the Interactions call at the top of the Gemini block, and the illustrative output prints None for the header on a flex request on purpose: Google documents the header on the priority page only, so don't assume a flex request sets it. (The sample doesn't print traffic_type: it is a Vertex field and is None on the Developer API.)

12.4 Flex or Batch?#

Both are "about half price". The difference is the shape of the work:

Flex + async Batch API
Interface A normal call; you control concurrency, retries and ordering A job: submit, wait, collect
Latency Slower than standard, still seconds to minutes per call Minutes to 24 hours for the whole job
Failure model Per-call errors, including 429s when flex is busy Per-request outcomes at the end; the job can expire
Throughput limits Your normal rate limits apply (Gemini: flex doesn't get Batch's extended limits) A separate, usually larger pool
State to keep The progress of your own loop The batch ID and a manifest
Good for Work needed in minutes to hours, results that feed the next step, jobs that need partial results early Overnight and weekend jobs, huge jobs, jobs that must not compete with live traffic
Not available on Anthropic (no flex tier) OpenRouter models without a :batch entry

If you need the answers the same afternoon, use flex, or standard with a rate limiter. If you can wait until tomorrow, use a Batch API: there's less to operate and no 429 dance.


Part 13: Background mode and webhooks#

Deep-dive

13.1 When one call is the whole job#

Batch APIs are for many requests. Background mode is for one request that takes too long to hold a connection open for: a deep-research run, a very long generation, a reasoning model working for many minutes. Networks drop idle connections, load balancers time out (Google notes that standard HTTP requests "typically close after 60 seconds"), and your own process may restart. In background mode the provider accepts the request, returns immediately with an ID, keeps working server-side, and lets you fetch the result by polling (or be notified by a webhook). If your connection drops, the work doesn't.

Background mode is a feature of two of the four providers:

OpenAI Anthropic
Background mode background=True on responses.create None on the Messages API (use streaming, 03.8, 6.4, or the Batch API)
Poll with responses.retrieve(id) n/a
Cancel with responses.cancel(id) n/a
Needs stored state Yes (see below) n/a
Gemini OpenRouter
Background mode background=True on interactions.create only; generate_content has no background mode Not documented as a mode; its Responses API is stateless only (store: true is a 400), so there is no stored response to poll. The Responses request schema in OpenRouter's SDK reference lists a background boolean described only as "Run request in background", so check the current page before relying on either reading
Poll with interactions.get(id=...) n/a
Cancel with interactions.cancel(id=...) n/a
Needs stored state Yes: store=False with background=True is a 400 n/a

13.2 OpenAI: background=True#

Add background=True to a Responses call. You get back a Response with status: "queued" at once. Then:

  • Poll responses.retrieve(response.id) while the status is queued or in_progress ("Keep polling while the request is in the queued or in_progress state"). When it leaves those, it's final: completed, failed, cancelled or incomplete. A completed response has the normal output; the others carry error or incomplete_details.
  • Judge the response only after polling has ended, with check_response(). "Completed" is not "usable" (03.8, Part 10): a completed response can still be a refusal, empty, or carry an error, and incomplete and failed carry their reason. 03.8's check_response() turns any of them into one typed Outcome (.status, .text, .detail, .usable), so branch on that instead of on response.status. Never call it inside the polling loop: for a response that is still queued or in_progress it returns INCOMPLETE (and for cancelled, FAILED), so acting on its verdict mid-poll would treat a healthy running job as broken (cancel it, or start it again). The loop's own stop test is the status; the check runs once, on the final response.
  • Cancel with client.responses.cancel(response.id). It's idempotent: "Cancelling twice is idempotent - subsequent calls simply return the final Response object." (To cancel a synchronous response, you close the connection.)
  • Storage. A background response must be kept server-side so you can poll it. Responses are stored for 30 days by default. If your project uses Zero Data Retention, or you pass store=False, the data is still written temporarily "to support async execution and polling" and is kept for about 10 minutes, then deleted: fetch the result within that time. Under the "Modified Abuse Monitoring" setting a background response is kept after polling only if you pass store=True explicitly. See 03.2 for what store does, and OpenAI's background guide for your project's data controls.
  • Streaming a background response. Pass background=True, stream=True, track each event's sequence_number, and resume with responses.retrieve(id, stream=True, starting_after=N). A response can be re-streamed only if it was created with stream=true, and the time to first token (TTFT) is currently higher than for synchronous responses. That is 03.3, Part 9's topic and isn't repeated here.
  • Webhooks. response.completed, response.failed, response.cancelled and response.incomplete events can replace the polling loop (13.6).

13.4 Polling a background job, with a way out#

The sample below starts a job on each provider, polls with the poll_until helper from 6.4 (growing intervals, jitter, a maximum wait) and, if it runs out of patience, cancels the job before raising, so you don't keep paying for work you've abandoned. When polling ends normally it returns check_response(response), the typed Outcome from 03.8 (copy check_response.py from 03.8, 10.2), instead of reading response.output_text and hoping. In async code, use apoll_until from 6.4. To retry transient failures of the start call, or to rate-limit many background starts, wrap the call in areliable_call() (03.8, 13.4) rather than writing the loop again:

python
"""s13_1_background.py: background mode on OpenAI (Responses) and Gemini (Interactions):
start the job, poll it with growing intervals, cancel it if we run out of patience, and only when polling has
ended judge the result with check_response() (03.8, Part 10).
Needs OPENAI_API_KEY / GEMINI_API_KEY in .env. poller.py is from section 6.4, check_response.py from 03.8."""
from dotenv import load_dotenv
from google import genai
from openai import OpenAI

from check_response import Outcome, check_response
from poller import PollTimeout, poll_until

STILL_RUNNING = {"queued", "in_progress"}      # both providers: poll while the status is one of these


def run_openai_background(client: OpenAI, prompt: str, max_wait: float = 1800.0) -> Outcome:
    # background=True returns at once with status "queued". The response is stored (store defaults to
    # true) so that you can fetch it later; with store=false or ZDR it is kept for only about 10 minutes.
    response = client.responses.create(model="gpt-6-luna", input=prompt, background=True,
                                       reasoning={"effort": "none"}, max_output_tokens=2000)
    print(f"started {response.id}: {response.status}")      # save the ID: it is your only handle
    try:
        response = poll_until(lambda: client.responses.retrieve(response.id),
                              lambda r: r.status not in STILL_RUNNING,
                              first=2.0, factor=1.5, max_interval=30.0, max_wait=max_wait,
                              on_poll=lambda r, t: print(f"  {t:5.0f} s  {r.status}"))
    except PollTimeout:
        client.responses.cancel(response.id)               # idempotent: a second cancel returns the final object
        raise
    # Polling is over, so the response is final. NOW check it: a "completed" can still be a refusal or empty, and
    # failed/incomplete/cancelled carry their reason. Never call check_response() inside the loop: for a response
    # that is still queued or in_progress it answers INCOMPLETE, which would label a healthy running job.
    return check_response(response)


def run_gemini_background(client: genai.Client, prompt: str, max_wait: float = 1800.0) -> Outcome:
    # Interactions only. background=True needs store=True (the default): store=False is a 400.
    interaction = client.interactions.create(model="gemini-3.8-flash", input=prompt, background=True)
    interaction_id = interaction.id
    assert interaction_id, "a stored interaction always has an ID"
    print(f"started {interaction_id}: {interaction.status}")
    try:
        interaction = poll_until(lambda: client.interactions.get(id=interaction_id),
                                 lambda i: i.status not in STILL_RUNNING,
                                 first=2.0, factor=1.5, max_interval=30.0, max_wait=max_wait,
                                 on_poll=lambda i, t: print(f"  {t:5.0f} s  {i.status}"))
    except PollTimeout:
        client.interactions.cancel(id=interaction_id)
        raise
    # "requires_action" also ends the polling loop: the job is waiting for YOU (a tool result to send back, 03.5),
    # not for the server. This sample passes no tools so it can't happen here; real code must answer it or cancel
    # the interaction, or the job stays open. check_response() reports it as not usable.
    return check_response(interaction)                   # again: only after polling has ended


if __name__ == "__main__":
    load_dotenv()
    prompt = "Write a 300-word summary of how HTTP caching works."
    with OpenAI() as openai_client:
        outcome = run_openai_background(openai_client, prompt)
        print(f"{outcome.status.value}: {outcome.text[:200]}")
    with genai.Client() as gemini_client:
        outcome = run_gemini_background(gemini_client, prompt)
        print(f"{outcome.status.value}: {outcome.text[:200]}")
Example output · illustrative13 lines
started resp_6a0c5a13e5c88190a4f1d7b2c93e0a71: queued
      0 s  queued
      2 s  in_progress
      5 s  in_progress
     11 s  in_progress
     19 s  completed
ok: HTTP caching lets a client or an intermediary reuse a stored response instead of asking the origin server again. The server...
started v1_Chd...: in_progress
      0 s  in_progress
      2 s  in_progress
      6 s  in_progress
     14 s  completed
ok: HTTP caching works by storing copies of responses so later requests can be answered without contacting the origin server...

Against the local stand-in the sample shows what isn't possible there: the OpenAI call is accepted (Ollama ignores background and answers completed at once) and then responses.retrieve returns a 404, because the local server doesn't store responses; and Gemini's Interactions background mode has no local stand-in at all (the stand-in's known gaps). So the real run is "not supported locally", and the output above is illustrative.

To see the real SDKs handle the protocol, here is the same code against mock servers: a job that finishes after three polls, and a job we give up on after three seconds, which gets cancelled. The OpenAI mock is a state machine behind httpx2.MockTransport; the Gemini one is behind httpx.MockTransport. Their shapes follow the OpenAI background guide and the Gemini background-execution page; Gemini's in-progress body is minimal because the docs don't spell it out:

python
"""mock_background.py: MOCKS of background jobs: OpenAI Responses (background=True) and Gemini
Interactions (background=True). Each answers the create call at once with a running job, then
reports progress on every poll. Shapes: https://developers.openai.com/api/docs/guides/background and
https://aistudio.google.com/docs/background-execution (status values); the Interaction body follows
what the SDK parses (id, status, created, updated, steps)."""
import json
import re

import httpx
import httpx2

from mock_llm import response_body


class MockOpenAIBackground:
    def __init__(self, polls_until_done: int = 3) -> None:
        self.polls_until_done, self.polls, self.cancelled = polls_until_done, 0, False
        self.seen: list[str] = []

    def _body(self, status: str) -> dict:
        body = response_body("billing")
        body["id"], body["status"], body["background"] = "resp_bg1", status, True
        if status != "completed":
            body["output"], body["usage"] = [], None
        return body

    def handler(self, request: httpx2.Request) -> httpx2.Response:
        self.seen.append(f"{request.method} {request.url.path}")
        if request.method == "POST" and request.url.path.endswith("/responses"):
            assert json.loads(request.content)["background"] is True
            return httpx2.Response(200, json=self._body("queued"))
        if request.method == "POST" and request.url.path.endswith("/cancel"):
            self.cancelled = True
            return httpx2.Response(200, json=self._body("cancelled"))
        if request.method == "GET":
            self.polls += 1
            if self.cancelled:
                return httpx2.Response(200, json=self._body("cancelled"))
            status = "completed" if self.polls >= self.polls_until_done else "in_progress"
            return httpx2.Response(200, json=self._body(status))
        return httpx2.Response(404, json={"error": {"message": "mock"}})


class MockGeminiInteractions:
    def __init__(self, polls_until_done: int = 3) -> None:
        self.polls_until_done, self.polls, self.cancelled = polls_until_done, 0, False
        self.seen: list[str] = []

    def _body(self, status: str) -> dict:
        body: dict = {"id": "int_bg1", "object": "interaction", "model": "gemini-3.8-flash", "status": status,
                "created": "2026-11-04T11:37:09", "updated": "2026-11-04T11:37:10"}
        if status == "completed":
            body["steps"] = [{"type": "model_output", "content": [{"type": "text", "text": "billing"}]}]
        return body

    def handler(self, request: httpx.Request) -> httpx.Response:
        self.seen.append(f"{request.method} {request.url.path}")
        if request.method == "POST" and request.url.path.endswith("/interactions"):
            assert json.loads(request.content)["background"] is True
            return httpx.Response(200, json=self._body("in_progress"))
        if request.method == "POST" and request.url.path.endswith("/cancel"):
            self.cancelled = True
            return httpx.Response(200, json=self._body("cancelled"))
        if request.method == "GET" and re.search(r"/interactions/int_bg1$", request.url.path):
            self.polls += 1
            if self.cancelled:
                return httpx.Response(200, json=self._body("cancelled"))
            return httpx.Response(200, json=self._body("completed" if self.polls >= self.polls_until_done else "in_progress"))
        return httpx.Response(404, json={"error": {"code": 404, "message": "mock", "status": "NOT_FOUND"}})
python
"""s13_2_background_mock.py: s13_1's background code against MOCK servers: a job that finishes after
three polls, and a job we give up on (max_wait) and cancel."""
import httpx
import httpx2
from google import genai
from google.genai import types
from openai import OpenAI
from openai.types.responses import Response

from check_response import check_response
from mock_background import MockGeminiInteractions, MockOpenAIBackground
from mock_llm import response_body
from poller import PollTimeout
from s13_1_background import run_gemini_background, run_openai_background


def openai_client(mock: MockOpenAIBackground) -> OpenAI:
    return OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(mock.handler)))


def gemini_client(mock: MockGeminiInteractions) -> genai.Client:
    return genai.Client(api_key="sk-test", http_options=types.HttpOptions(
        httpx_client=httpx.Client(transport=httpx.MockTransport(mock.handler))))


print("--- OpenAI: finishes")
m = MockOpenAIBackground(polls_until_done=3)
outcome = run_openai_background(openai_client(m), "classify", max_wait=60)
print(f"answer: {outcome.text} ({outcome.status.value})")
print("--- OpenAI: we run out of patience")
m = MockOpenAIBackground(polls_until_done=99)
try:
    run_openai_background(openai_client(m), "classify", max_wait=3)
except PollTimeout as e:
    print("PollTimeout:", e, "| cancel sent:", m.cancelled, "|", ", ".join(dict.fromkeys(m.seen)))

print("--- Gemini Interactions: finishes")
g = MockGeminiInteractions(polls_until_done=3)
outcome = run_gemini_background(gemini_client(g), "classify", max_wait=60)
print(f"answer: {outcome.text} ({outcome.status.value})")
print("--- Gemini Interactions: we run out of patience")
g = MockGeminiInteractions(polls_until_done=99)
try:
    run_gemini_background(gemini_client(g), "classify", max_wait=3)
except PollTimeout as e:
    print("PollTimeout:", e, "| cancel sent:", g.cancelled, "|", ", ".join(dict.fromkeys(g.seen)))

print("--- what check_response() says for each status: call it only AFTER polling ends")
for status in ("queued", "in_progress", "completed", "failed", "incomplete"):
    body = response_body("billing")
    body["status"] = status
    if status == "failed":
        body["error"] = {"code": "server_error", "message": "The server had an error"}
    if status == "incomplete":
        body["incomplete_details"] = {"reason": "max_output_tokens"}
    verdict = check_response(Response.model_validate(body))
    print(f"  {status:<12} -> {verdict.status.value:<10} usable={verdict.usable!s:<5} {verdict.detail or ''}")

Output (mock servers; the poll intervals have random jitter, so your timings differ a little):

text
--- OpenAI: finishes
started resp_bg1: queued
      0 s  in_progress
      2 s  in_progress
      5 s  completed
answer: billing (ok)
--- OpenAI: we run out of patience
started resp_bg1: queued
      0 s  in_progress
      2 s  in_progress
      3 s  in_progress
PollTimeout: still not done after 3 s | cancel sent: True | POST /v1/responses, GET /v1/responses/resp_bg1, POST /v1/responses/resp_bg1/cancel
--- Gemini Interactions: finishes
started int_bg1: in_progress
      0 s  in_progress
      2 s  in_progress
      5 s  completed
answer: billing (ok)
--- Gemini Interactions: we run out of patience
started int_bg1: in_progress
      0 s  in_progress
      2 s  in_progress
      3 s  in_progress
PollTimeout: still not done after 3 s | cancel sent: True | POST /v1beta/interactions, GET /v1beta/interactions/int_bg1, POST /v1beta/interactions/int_bg1/cancel
--- what check_response() says for each status: call it only AFTER polling ends
  queued       -> incomplete usable=False queued
  in_progress  -> incomplete usable=False in_progress
  completed    -> ok         usable=True  
  failed       -> failed     usable=False server_error
  incomplete   -> truncated  usable=False max_output_tokens

Both providers' flows look the same: one create call, a few polls with growing gaps, then either the answer or a PollTimeout followed by a cancel. The last line of each timeout case lists the exact HTTP calls: create, poll, cancel. Look at the last poll in the timeout cases: it happens at 3 s, exactly the max_wait, because poll_until always polls once at the deadline (6.4), so a job that finished in the last interval is not missed. The final block shows what check_response() makes of each status: queued and in_progress are incomplete (not usable), which is why you must not act on its verdict mid-poll; failed carries the provider's error code, and incomplete is reported as truncated with its reason.

13.5 Polling or webhooks?#

Polling Webhooks
Needs a public URL? No Yes: an HTTPS endpoint the provider can reach
Latency to notice completion Up to your poll interval Seconds
Cost A request per poll (small, but rate-limited) None while waiting
Failure modes Your process dies, so you need persisted IDs Your endpoint is down, so the provider retries for a while, then gives up
Good for Scripts, notebooks, laptops, cron jobs, behind a firewall Services, many concurrent long jobs, user-facing "we'll email you" flows

Use both in production: the webhook is a hint, and polling is the safety net. A webhook can be delayed, duplicated or lost. A slow poll (every 10 to 15 minutes) over the jobs still marked open in your manifest catches anything the webhook missed. OpenRouter's guide says the same thing: "Use a webhook to find out when a batch finishes, and keep a slow poll as a backup." Anthropic's Managed Agents webhooks make the point bluntly: up to three attempts, then the event is dropped, with no signal that it was lost, and "Webhooks aren't a durable log" (13.6). And handle each job exactly once whichever signal arrives first.

13.6 Webhooks: what each provider sends#

A webhook is an HTTP POST that the provider sends to your server when something finishes. You give the provider a URL; it calls the URL. All four providers' schemes in this lesson follow (or resemble) the Standard Webhooks specification: three headers (webhook-id, webhook-timestamp, webhook-signature) and an HMAC signature over the ID, the timestamp and the raw body. A caution about the Anthropic column: Anthropic has webhooks, but none for Message Batches, so everything in that column is background for other products, and for batches you poll (8.5). It is described here as Anthropic's pages describe it on 4 November 2026.

OpenAI Anthropic
Events for this lesson's jobs batch.completed, batch.failed, batch.expired, batch.cancelled; response.completed, response.failed, response.cancelled, response.incomplete (the SDK has more, for evals, fine-tuning, realtime and agents) None for Message Batches (not used for batches). Managed Agents webhooks (a beta: sessions, agents, deployments, vaults, environments and memory stores) exist. Organization webhooks are a separate Admin API beta, by request, with two user-profile enforcement events, and Anthropic says it doesn't send them yet, so a registered endpoint receives nothing
How you register Dashboard (the guide's route): a name, a public URL and event types; shown a signing secret once. The SDK source on GitHub (11 November 2026) also has endpoint-management methods (client.webhooks.create, rotate_secret) that the guide doesn't describe Managed Agents: the Console Webhooks page (HTTPS on port 443 with a public hostname, one endpoint per workspace, a whsec_ secret shown once; beta header managed-agents-2026-04-01, not eligible for zero data retention). Organization webhooks: the Admin API (/v1/organizations/webhooks, beta header webhooks-2026-10-07, you ask your account team for access; the create response has the signing_secret)
Payload {id, object: "event", created_at, type, data: {id}} {type: "event", id: "whe_...", created_at, data: {type, id, organization_id, workspace_id}}: the event type is in data.type, and the event carries IDs, not the object
Signature Standard Webhooks: v1,<base64 HMAC-SHA256> over {webhook-id}.{webhook-timestamp}.{body}; secret whsec_... is base64 Standard Webhooks
Verify with client.webhooks.unwrap(payload, headers, secret=...) (env OPENAI_WEBHOOK_SECRET) client.beta.webhooks.unwrap(payload, headers=..., key=...) (env ANTHROPIC_WEBHOOK_SIGNING_KEY; needs pip install "anthropic[webhooks]")
Retries if you don't answer 2xx Up to 72 hours, exponential backoff Up to 3 delivery attempts (jittered exponential backoff, 5 to 120 seconds) for Managed Agents, after which the event is dropped: not queued, with no signal that it was lost ("Webhooks aren't a durable log"). Organization webhooks: "a few times over the next few minutes", then dropped. A 3xx, a non-public IP address, or sustained failures disable the endpoint (events during that time aren't replayed)
Duplicates Rare; dedupe on the webhook-id header Possible; dedupe on the top-level event.id (the same value as webhook-id; it is unique per event, not per delivery)
Replay window The SDK rejects timestamps more than 5 minutes off unwrap() rejects a payload more than 5 minutes old; webhook-timestamp is regenerated on every retry, so retries pass the check, and the payload's created_at says when the event happened
Gemini OpenRouter
Events for this lesson's jobs batch.succeeded, batch.failed, batch.cancelled, batch.expired; interaction.completed, interaction.failed, interaction.requires_action, interaction.cancelled; video.generated (preview) batch.completed, batch.failed, batch.expired, batch.cancelled
How you register Static: client.webhooks.create(name=, subscribed_events=[...], uri=...) returns a one-time signing secret (webhook.new_signing_secret). Dynamic: webhook_config on one request (documented for interactions.create with background=True; not shown for batches) callback_url on the batch, or a workspace default; a signing secret is optional
Payload A "thin" payload: {type, version, timestamp, data: {id, output_file_uri?, error_code?, error_message?}} {id, object: "event", type, created_at, data: {id}}
Signature Static: Standard Webhooks. Dynamic: a JWT (RS256), verified against Google's public keys (JWKS) Its own: X-OpenRouter-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256>, signed over <t>, + the raw body
Verify with The standardwebhooks package, or your own HMAC Your own HMAC
Retries if you don't answer 2xx 24 hours, exponential backoff A non-2xx makes OpenRouter retry ("return a non-2xx so OpenRouter retries")
Duplicates "At-least-once"; dedupe on webhook-id Same event ID and X-OpenRouter-Idempotency-Key (<batch id>-<status>)
Replay window Reject payloads older than 5 minutes The documented example checks 5 minutes

Four rules apply to every provider:

  1. Verify the signature on the raw request body, before parsing it. If you parse the JSON and serialize it again, the bytes change and the signature fails; in FastAPI use await request.body(), not a Pydantic model parameter.
  2. Check the timestamp (about 5 minutes) so that a captured request can't be replayed.
  3. Answer 2xx quickly and do the work elsewhere. Providers wait only a few seconds; a slow handler looks like a failure and triggers retries.
  4. Deduplicate on the event ID, and put only the job ID on a durable queue. The event never contains the results. A worker fetches them with the normal API, and may need to retry for a few seconds, because the webhook can arrive slightly before the status endpoint shows the final state.

13.7 A webhook receiver that verifies signatures#

sequenceDiagram
    participant Job as Provider job
    participant Hook as Your webhook endpoint
    participant Q as Durable queue
    participant W as Worker
    participant API as Provider API
    Job->>Hook: POST event (id, type, data.id) + signature headers
    Hook->>Hook: secret missing or empty? refuse with 500 (fail closed)
    Hook->>Hook: verify signature on the raw body, check timestamp
    Hook->>Q: enqueue the job ID once (dedupe on event id)
    Hook-->>Job: 200 within a few seconds
    Q->>W: job ID
    W->>API: fetch the batch or response
    API-->>W: results
    Note over Job,Hook: no 2xx means the provider retries (OpenAI up to 72 hours, Gemini 24 hours, Anthropic Managed Agents 3 attempts then drops the event)

The module below is a FastAPI app with one route per provider (there is no Anthropic route: Anthropic has no webhook for batches, 13.6). The OpenAI route uses the SDK's own client.webhooks.unwrap, which checks the three headers and the timestamp tolerance (300 seconds), then parses the event. The Gemini route verifies the Standard Webhooks signature by hand, and the OpenRouter route its own scheme. All three verify the raw body, deduplicate on the event ID and only queue the job ID.

Fail closed is the general rule behind this: when a safety check cannot run (the secret is missing, the config is unreadable), refuse the request instead of letting it through. The opposite, failing open, turns a misconfiguration into a hole, because "I couldn't check, so I'll accept" is exactly what an attacker hopes for. The same rule appears wherever a check guards something (03.7's hash key, 03.10's log redaction, 03.11's before hooks).

The module fails closed: every route reads its secret on each request, and if the secret is unset, empty, blank, or decodes to an empty key, the route refuses with a 500 and logs an error. That is deliberate. A secret that defaulted to the empty string would be a signing key that anyone can use: an HMAC computed with an empty key is something an attacker can compute too, so the receiver would accept a forged event as genuine (this is the bug the forgery test below guards against). A 500 is right for our own misconfiguration, because it is not an attack and the provider will retry the delivery once you fix the secret; a 400 stays for a bad signature. The Standard Webhooks key is the base64-decoded secret (with or without the whsec_ prefix), as the specification says, so there is no "use the raw bytes" fallback. And only after the signature has verified does the code look inside the body, so a signed event of an unexpected shape is acknowledged and logged rather than crashing with a 500:

python
"""webhook_receiver.py: a FastAPI receiver for provider webhooks. It FAILS CLOSED: a route with no secret
configured refuses every request. It verifies the signature on the RAW body, answers 2xx quickly, ignores
repeats, and only queues the job ID: fetching results happens later.
Run for real with:  OPENAI_WEBHOOK_SECRET=whsec_... GEMINI_WEBHOOK_SECRET=whsec_... uv run uvicorn webhook_receiver:app"""
import base64
import hashlib
import hmac
import json
import logging
import os
import time

from fastapi import FastAPI, Request, Response
from openai import OpenAI

log = logging.getLogger("webhooks")
app = FastAPI()
# The receiver never calls the OpenAI API: this client is only used for its webhook verification
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "unused-by-the-receiver"))

seen_ids: set[str] = set()                 # production: a unique constraint in a database
jobs: list[tuple[str, str]] = []           # production: a durable queue (database table, SQS, Redis...)
TOLERANCE_S = 300                          # reject deliveries older (or newer) than 5 minutes: replay protection


class SecretNotConfigured(RuntimeError):
    """Our misconfiguration, not an attack: answer 500 (providers retry) and shout in the logs."""


def secret_from_env(name: str) -> str:
    """The signing secret for one route, read on every request. Unset, empty or blank means REFUSE: a missing
    secret must never turn into 'accept everything' (an empty HMAC key is a key anyone can sign with)."""
    value = os.environ.get(name, "").strip()
    if not value:
        log.error("%s is not set: refusing every request to this route", name)
        raise SecretNotConfigured(name)
    return value


def standard_key(secret: str) -> bytes:
    """Standard Webhooks (standardwebhooks.com): the key is the BASE64-DECODED secret, with or without 'whsec_'."""
    key = base64.b64decode(secret.removeprefix("whsec_"), validate=True)
    if not key:                                                          # 'whsec_' on its own decodes to nothing
        log.error("the signing secret decodes to an empty key: refusing every request to this route")
        raise SecretNotConfigured("secret decodes to an empty key")
    return key


def verify_standard_webhook(body: bytes, headers: dict[str, str] | object, key: bytes) -> None:
    """HMAC-SHA256 over '{webhook-id}.{webhook-timestamp}.{body}', base64-encoded, sent as 'v1,<sig>'
    (several allowed). Raises ValueError or KeyError when the delivery is not authentic."""
    h = {k.lower(): v for k, v in headers.items()}                       # type: ignore[attr-defined]
    msg_id, ts, signatures = h["webhook-id"], h["webhook-timestamp"], h["webhook-signature"]
    if abs(time.time() - int(ts)) > TOLERANCE_S:
        raise ValueError("timestamp outside tolerance")
    expected = base64.b64encode(hmac.new(key, f"{msg_id}.{ts}.".encode() + body, hashlib.sha256).digest())
    if not any(hmac.compare_digest(expected, s.removeprefix("v1,").encode()) for s in signatures.split()):
        raise ValueError("bad signature")


def enqueue_once(event_id: str, kind: str, resource_id: str) -> bool:
    """True if this delivery was new. Providers deliver at least once, so repeats WILL happen."""
    if event_id in seen_ids:
        return False
    seen_ids.add(event_id)
    jobs.append((kind, resource_id))       # store only the ID: the event never contains the results
    return True


def acknowledge_unusable(why: str) -> Response:
    """The signature was valid but the body isn't an event we use. 2xx stops the provider's retries; log it."""
    log.warning("authentic delivery ignored: %s", why)
    return Response(status_code=200)


@app.post("/webhooks/openai")
async def openai_webhook(request: Request) -> Response:
    body = await request.body()            # the exact bytes OpenAI signed: never re-serialize parsed JSON
    try:
        secret = secret_from_env("OPENAI_WEBHOOK_SECRET")
    except SecretNotConfigured:
        return Response("webhook secret not configured", status_code=500)
    try:
        # Checks webhook-id, webhook-timestamp (5 min tolerance) and webhook-signature, then parses
        event = client.webhooks.unwrap(body, request.headers, secret=secret)
    except ValueError:                     # InvalidWebhookSignatureError is a ValueError; so is bad JSON
        return Response("invalid signature", status_code=400)
    resource_id = getattr(event.data, "id", None)       # the response or batch ID; some event types have no such ID
    if resource_id and event.type.startswith(("response.", "batch.")):
        enqueue_once(request.headers["webhook-id"], event.type, resource_id)
    return Response(status_code=200)       # answer fast; anything slow belongs in a worker


@app.post("/webhooks/gemini")
async def gemini_webhook(request: Request) -> Response:
    body = await request.body()
    try:
        key = standard_key(secret_from_env("GEMINI_WEBHOOK_SECRET"))
    except SecretNotConfigured:
        return Response("webhook secret not configured", status_code=500)
    except ValueError:                     # not valid base64: also OUR misconfiguration
        log.error("GEMINI_WEBHOOK_SECRET is not valid base64: refusing every request to this route")
        return Response("webhook secret not configured", status_code=500)
    try:
        verify_standard_webhook(body, request.headers, key)
    except (ValueError, KeyError):         # KeyError: a header is missing
        return Response("invalid signature", status_code=400)
    try:                                   # authentic, so now (and only now) look inside
        event = json.loads(body)
        kind, resource_id = event["type"], event["data"]["id"]
    except (ValueError, KeyError, TypeError):
        return acknowledge_unusable("unexpected body shape")
    if isinstance(kind, str) and kind.startswith(("batch.", "interaction.")):
        enqueue_once(request.headers["webhook-id"], kind, str(resource_id))
    return Response(status_code=200)


@app.post("/webhooks/openrouter")
async def openrouter_webhook(request: Request) -> Response:
    body = await request.body()
    try:
        secret = secret_from_env("OPENROUTER_WEBHOOK_SECRET")
    except SecretNotConfigured:
        return Response("webhook secret not configured", status_code=500)
    # OpenRouter's own scheme: header "X-OpenRouter-Signature: t=<unix s>,v1=<hex HMAC-SHA256>",
    # signed over '<t>,' followed by the raw body (a comma, not a dot)
    try:
        parts = dict(p.split("=", 1) for p in request.headers["x-openrouter-signature"].split(","))
        if abs(time.time() - int(parts["t"])) > TOLERANCE_S:
            raise ValueError("timestamp outside tolerance")
        expected = hmac.new(secret.encode(), f"{parts['t']},".encode() + body, hashlib.sha256).hexdigest()
        if not hmac.compare_digest(expected.encode(), parts["v1"].encode()):
            raise ValueError("bad signature")
    except (ValueError, KeyError):
        return Response("invalid signature", status_code=400)
    try:
        event = json.loads(body)
        event_id, kind, resource_id = event["id"], event["type"], event["data"]["id"]
    except (ValueError, KeyError, TypeError):
        return acknowledge_unusable("unexpected body shape")
    enqueue_once(str(event_id), str(kind), str(resource_id))      # OpenRouter's repeats share the event id
    return Response(status_code=200)

The in-memory seen_ids and jobs are stand-ins: in production the event IDs belong in a database table with a unique constraint (so two simultaneous deliveries can't both insert) and the jobs in a durable queue or a table that a worker polls. To run it for real: set the three secrets in the environment and start uvicorn webhook_receiver:app, then expose the port with a tunnelling tool while developing (or use a request-catcher site to see a real delivery first).

You can test the receiver without any provider by playing the provider yourself: sign a body with a test secret exactly as the provider would, and POST it. This also shows how the signature works. (The secrets are placeholders for the test, and the OpenAI check uses the SDK's real verification code.) The second half of the test is the forgery test: it signs an event with an empty key, as an attacker would against a receiver whose secret is missing, and checks that every misconfiguration is refused:

python
"""s13_6_webhook_test.py: exercise webhook_receiver.py with locally SIGNED payloads (layer 1, no network).
We play the provider: sign a body with a test secret, POST it, and look at the status and the queue.
The last block is the forgery test: with no secret configured, or a secret that decodes to nothing, an attacker
who signs with an EMPTY key must still be refused."""
import base64
import contextlib
import hashlib
import hmac
import json
import logging
import os
import sys
import time
from collections.abc import Iterator

os.environ.update(OPENAI_WEBHOOK_SECRET="whsec_" + base64.b64encode(b"test-secret-not-real").decode(),
                  GEMINI_WEBHOOK_SECRET="whsec_" + base64.b64encode(b"another-test-secret").decode(),
                  OPENROUTER_WEBHOOK_SECRET="or-test-secret")

from fastapi.testclient import TestClient  # noqa: E402  (after the env vars: the app reads them at import)

import webhook_receiver as wr  # noqa: E402

logging.basicConfig(stream=sys.stdout, level=logging.WARNING, format="      receiver log: %(message)s")  # show the receiver's log lines in order
http = TestClient(wr.app)


def standard_headers(secret: str, body: bytes, msg_id: str, ts: int | None = None) -> dict[str, str]:
    """What OpenAI and Gemini send (Standard Webhooks): id, timestamp, and 'v1,<base64 HMAC-SHA256>'."""
    ts = int(time.time()) if ts is None else ts
    key = base64.b64decode(secret.removeprefix("whsec_"))
    sig = base64.b64encode(hmac.new(key, f"{msg_id}.{ts}.".encode() + body, hashlib.sha256).digest()).decode()
    return {"webhook-id": msg_id, "webhook-timestamp": str(ts), "webhook-signature": f"v1,{sig}",
            "content-type": "application/json"}


def show(label: str, response) -> None:
    print(f"{label:<44} -> {response.status_code}   jobs queued: {len(wr.jobs)}")


@contextlib.contextmanager
def secret_is(name: str, value: str | None) -> Iterator[None]:
    """Temporarily unset (None) or change one secret, to test a misconfigured receiver."""
    old = os.environ.get(name)
    if value is None:
        os.environ.pop(name, None)
    else:
        os.environ[name] = value
    try:
        yield
    finally:
        if old is None:
            os.environ.pop(name, None)
        else:
            os.environ[name] = old


# FIXTURE: an OpenAI event as documented: {id, object, created_at, type, data: {id}}
event = json.dumps({"id": "evt_001", "object": "event", "created_at": int(time.time()),
                    "type": "response.completed", "data": {"id": "resp_abc123"}}).encode()
secret = os.environ["OPENAI_WEBHOOK_SECRET"]

show("OpenAI: valid signature", http.post("/webhooks/openai", content=event, headers=standard_headers(secret, event, "msg_1")))
show("OpenAI: the same delivery again (retry)", http.post("/webhooks/openai", content=event, headers=standard_headers(secret, event, "msg_1")))
tampered = event.replace(b"resp_abc123", b"resp_evil99")
show("OpenAI: body changed after signing", http.post("/webhooks/openai", content=tampered, headers=standard_headers(secret, event, "msg_2")))
show("OpenAI: signed with the wrong secret", http.post("/webhooks/openai", content=event,
     headers=standard_headers("whsec_" + base64.b64encode(b"someone-else").decode(), event, "msg_3")))
show("OpenAI: timestamp 10 minutes old (replay)", http.post("/webhooks/openai", content=event,
     headers=standard_headers(secret, event, "msg_4", ts=int(time.time()) - 600)))
show("OpenAI: no signature headers at all", http.post("/webhooks/openai", content=event))

batch = json.dumps({"id": "evt_002", "object": "event", "created_at": int(time.time()),
                    "type": "batch.completed", "data": {"id": "batch_789"}}).encode()
show("OpenAI: batch.completed", http.post("/webhooks/openai", content=batch, headers=standard_headers(secret, batch, "msg_5")))

# FIXTURE: Gemini's thin payload (https://aistudio.google.com/docs/webhooks#webhook-envelope)
gem = json.dumps({"type": "batch.succeeded", "version": "v1", "timestamp": "2026-11-04T12:00:00Z",
                  "data": {"id": "batch_123456", "output_file_uri": "files/out1"}}).encode()
show("Gemini: batch.succeeded", http.post("/webhooks/gemini", content=gem,
     headers=standard_headers(os.environ["GEMINI_WEBHOOK_SECRET"], gem, "msg_g1")))

# FIXTURE: OpenRouter's body and header (https://openrouter.ai/docs/batch-quickstart)
orb = json.dumps({"id": "evt_51504673", "object": "event", "type": "batch.completed",
                  "created_at": int(time.time()), "data": {"id": "batch_or1"}}).encode()
t = str(int(time.time()))
sig = hmac.new(b"or-test-secret", f"{t},".encode() + orb, hashlib.sha256).hexdigest()
show("OpenRouter: batch.completed", http.post("/webhooks/openrouter", content=orb,
     headers={"x-openrouter-signature": f"t={t},v1={sig}"}))

# --- The forgery test. A receiver whose secret defaults to "" signs with an EMPTY key, and an HMAC with an
# empty key is something ANYONE can compute, so it would accept a forged event (HTTP 200). This one must refuse.
print("\n--- forging events with an EMPTY signing key")
forged = json.dumps({"type": "batch.succeeded", "version": "v1", "timestamp": "2026-11-04T12:00:00Z",
                     "data": {"id": "batch_FORGED"}}).encode()
forged_gemini = {"webhook-id": "msg_x", "webhook-timestamp": str(int(time.time())), "content-type": "application/json"}
forged_gemini["webhook-signature"] = "v1," + base64.b64encode(
    hmac.new(b"", f"msg_x.{forged_gemini['webhook-timestamp']}.".encode() + forged, hashlib.sha256).digest()).decode()
t = str(int(time.time()))
forged_or = {"x-openrouter-signature": f"t={t},v1=" + hmac.new(b"", f"{t},".encode() + forged, hashlib.sha256).hexdigest()}

with secret_is("GEMINI_WEBHOOK_SECRET", None):
    show("Gemini: secret unset, forged with empty key", http.post("/webhooks/gemini", content=forged, headers=forged_gemini))
with secret_is("GEMINI_WEBHOOK_SECRET", ""):
    show("Gemini: secret empty, forged with empty key", http.post("/webhooks/gemini", content=forged, headers=forged_gemini))
with secret_is("GEMINI_WEBHOOK_SECRET", "whsec_"):
    show("Gemini: secret 'whsec_' only (empty key)", http.post("/webhooks/gemini", content=forged, headers=forged_gemini))
show("Gemini: secret set, forged with empty key", http.post("/webhooks/gemini", content=forged, headers=forged_gemini))
with secret_is("OPENROUTER_WEBHOOK_SECRET", None):
    show("OpenRouter: secret unset, forged empty key", http.post("/webhooks/openrouter", content=forged, headers=forged_or))
with secret_is("OPENROUTER_WEBHOOK_SECRET", ""):
    show("OpenRouter: secret empty, forged empty key", http.post("/webhooks/openrouter", content=forged, headers=forged_or))
show("OpenRouter: secret set, forged empty key", http.post("/webhooks/openrouter", content=forged, headers=forged_or))
with secret_is("OPENAI_WEBHOOK_SECRET", None):
    show("OpenAI: secret unset, valid-looking event", http.post("/webhooks/openai", content=event,
         headers=standard_headers(secret, event, "msg_9")))

# A genuine, correctly signed event whose body has an unexpected shape: authentic, so acknowledge (200) and
# log it, and do not crash with an unhandled KeyError (HTTP 500).
odd = json.dumps({"type": "batch.succeeded", "data": {}}).encode()
show("Gemini: signed, but no data.id in the body", http.post("/webhooks/gemini", content=odd,
     headers=standard_headers(os.environ["GEMINI_WEBHOOK_SECRET"], odd, "msg_g2")))
Output · a FastAPI TestClient, so no network and no server27 lines
OpenAI: valid signature                      -> 200   jobs queued: 1
OpenAI: the same delivery again (retry)      -> 200   jobs queued: 1
OpenAI: body changed after signing           -> 400   jobs queued: 1
OpenAI: signed with the wrong secret         -> 400   jobs queued: 1
OpenAI: timestamp 10 minutes old (replay)    -> 400   jobs queued: 1
OpenAI: no signature headers at all          -> 400   jobs queued: 1
OpenAI: batch.completed                      -> 200   jobs queued: 2
Gemini: batch.succeeded                      -> 200   jobs queued: 3
OpenRouter: batch.completed                  -> 200   jobs queued: 4

--- forging events with an EMPTY signing key
      receiver log: GEMINI_WEBHOOK_SECRET is not set: refusing every request to this route
Gemini: secret unset, forged with empty key  -> 500   jobs queued: 4
      receiver log: GEMINI_WEBHOOK_SECRET is not set: refusing every request to this route
Gemini: secret empty, forged with empty key  -> 500   jobs queued: 4
      receiver log: the signing secret decodes to an empty key: refusing every request to this route
Gemini: secret 'whsec_' only (empty key)     -> 500   jobs queued: 4
Gemini: secret set, forged with empty key    -> 400   jobs queued: 4
      receiver log: OPENROUTER_WEBHOOK_SECRET is not set: refusing every request to this route
OpenRouter: secret unset, forged empty key   -> 500   jobs queued: 4
      receiver log: OPENROUTER_WEBHOOK_SECRET is not set: refusing every request to this route
OpenRouter: secret empty, forged empty key   -> 500   jobs queued: 4
OpenRouter: secret set, forged empty key     -> 400   jobs queued: 4
      receiver log: OPENAI_WEBHOOK_SECRET is not set: refusing every request to this route
OpenAI: secret unset, valid-looking event    -> 500   jobs queued: 4
      receiver log: authentic delivery ignored: unexpected body shape
Gemini: signed, but no data.id in the body   -> 200   jobs queued: 4

Read the status codes. A correctly signed event is queued (200). The same delivery again is acknowledged (200, so the provider stops retrying) but not queued twice. A body changed after signing, a wrong secret, a timestamp ten minutes old and a request with no signature headers are all rejected with 400, and nothing is queued. Gemini's and OpenRouter's routes accept their own formats. Returning 400 for a bad signature is right; returning a non-2xx for a good event you failed to store is also right, because it makes the provider retry.

Then the forgery block. With the secret unset, empty, or just whsec_ (an empty key), the Gemini and OpenRouter routes answer 500 and the queue does not change (4 jobs before and after): the empty-key forgery fails. With a real secret configured, the same forged event gets a 400. The OpenAI route with no secret is also 500, with a log line saying which variable is missing, instead of an InvalidWebhookSignatureError turned into a 400 that looks like an attack. Last, a correctly signed Gemini event whose body has no data.id is acknowledged (200) and logged, not a crash.

13.3 Gemini: background=True on Interactions#

Interactions is where Google's long-running work lives (deep-research agents, managed agents, plain models with huge outputs). client.interactions.create(model=..., input=..., background=True) returns an Interaction immediately with status: "in_progress"; client.interactions.get(id=...) polls it; client.interactions.cancel(id=...) stops it; client.interactions.delete(id=...) removes the record.

  • Status values. Google's page lists in_progress, requires_action (paused for client input, such as confirming a tool run), completed, failed (e.g. a tool failure or rate limit) and cancelled. The SDK's type is wider: in_progress, requires_action, completed, failed, cancelled, incomplete, budget_exceeded, queued and requires_continuation. So poll while the status is queued or in_progress, and treat everything else as "look at it": requires_action in particular means the job is waiting for you, not for the server.
  • store must stay true. "background=True requires store=True, which is the default": store=False returns a 400. Stored interactions are kept 55 days on paid tiers (configurable to 7, 14, 28 or 55 days in Google AI Studio) and 1 day on the free tier, and can be deleted at any time (as of November 2026).
  • Chaining. Using previous_interaction_id on an interaction that is still in_progress returns a 400: wait for completed first.
  • Streaming a background interaction. A background interaction can be streamed and, if the connection drops, resumed from the last event you received with last_event_id (client.interactions.get(id=..., stream=True, last_event_id=...)). That is the Gemini counterpart of the OpenAI cursor above, and 03.3, Part 9 covers both, so it isn't repeated here.
  • requires_action leaves the job open. A job in that state is waiting for you (a tool result to send back, 03.5). The polling loop stops on it, because it isn't queued or in_progress, so real code must answer it or cancel the interaction; the sample below passes no tools, so it can't happen there, and check_response() reports it as not usable.
  • Why use it. Foreground interactions have output caps (65,536 tokens streaming, 32,768 non-streaming), and long decode on a flagship model (up to about a million output tokens) is for background runs.
  • Webhooks. interactions.create(..., background=True, webhook_config={"uris": [...], "user_metadata": {...}}) registers a per-request webhook (Google notes it needs an SDK newer than 2.0.0; 2.34.0 qualifies). webhook_config requires background=True. See 13.6.

Part 14: Choosing: a worked example#

14.1 Classifying 20,000 tickets three ways#

The task: label 20,000 support tickets with one of four categories. Each request is about 160 input tokens (instruction plus ticket) and a one-word answer of about 4 output tokens. You can do it with (A) async with a concurrency of 20, (B) flex tier with the same concurrency, or (C) a Batch API. The calculator below puts numbers on each. It uses job_calc.py from 11.5 and is pure arithmetic (layer 1: no network), so every assumption is a line you can change:

  • Latency: 1.5 s per standard call; 20 s per flex call, with 15% of first attempts refused (429, not billed) and about 8 s of backoff for each of those. These are guesses. Measure your own with a hundred calls before you plan.
  • Limits: 4,000 requests per minute and 2,000,000 tokens per minute (look yours up, 03.8, 9.2).
  • Failures: 1% of async calls fail transiently (the SDK retries them), and 0.5% time out client-side but still run and bill, so the retry is billed again (03.8, 6.6).
  • Prices: list prices from 03.7's table (4 November 2026), with flex and batch at half. The script starts by running check_prices() (11.5), which raises if the calculator's copy drifts from that table. Anthropic has no flex tier, so its flex column is n/a; and the calculator ignores prompt caching (its input is uncached, the module's convention).
python
"""s14_1_calculator.py: the worked example. 20,000 support tickets classified three ways. Layer 1:
pure arithmetic on stated assumptions, no network. Change the assumptions at the top and re-run."""
from typing import Any

from job_calc import NO_FLEX, PRICES, Job, Limits, async_wall_s, check_prices, cost_usd, fmt_duration, retry_cost_requests

print(check_prices(), "\n")                  # raises if PRICES drifts from 03.7's prices.yaml
job = Job(requests=20_000, input_tokens=160, output_tokens=4)
limits = Limits(rpm=4_000, tpm=2_000_000)

# Assumptions (all of them are guesses to replace with your own measurements):
ASYNC: dict[str, Any] = dict(concurrency=20, latency_s=1.5)                      # a short classification answers in ~1.5 s
FLEX: dict[str, Any] = dict(concurrency=20, latency_s=20.0, extra_wait_s=0.15 * 8.0)   # slower, and 15% of first tries refused, then ~8 s backoff
TIMEOUT_RATE = 0.005                                              # 0.5% of async calls time out client-side but still bill

async_s, async_by = async_wall_s(job, limits, **ASYNC)
flex_s, flex_by = async_wall_s(job, limits, **FLEX)
flex_100_s, flex_100_by = async_wall_s(job, limits, **{**FLEX, "concurrency": 100})
fast_s, fast_by = async_wall_s(job, limits, **{**ASYNC, "concurrency": 400})
print(f"{job.requests:,} tickets x ({job.input_tokens} in + {job.output_tokens} out tokens) = "
      f"{job.requests * (job.input_tokens + job.output_tokens) / 1e6:.1f}M tokens\n")

print(f"{'wall time':<12}{fmt_duration(async_s):>8}   async, 20 at once        (bound by: {async_by})")
print(f"{'':<12}{fmt_duration(fast_s):>8}   async, 400 at once       (bound by: {fast_by}; this is what the rate limiter enforces)")
print(f"{'':<12}{fmt_duration(flex_s):>8}   flex, 20 at once         (bound by: {flex_by})")
print(f"{'':<12}{fmt_duration(flex_100_s):>8}   flex, 100 at once        (bound by: {flex_100_by})")
print(f"{'':<12}{'1-24 h':>8}   batch: a single job, no concurrency to manage; the provider decides when it runs\n")

extra = retry_cost_requests(job, TIMEOUT_RATE)
print(f"{'model':<20}{'async':>9}{'flex':>9}{'batch':>9}   (USD; async includes {extra} calls billed twice after timeouts)")
for model in PRICES:
    flex = "n/a" if model in NO_FLEX else f"{cost_usd(job, model, 'flex'):.2f}"      # Anthropic has no flex tier
    print(f"{model:<20}{cost_usd(job, model, 'standard', extra):>9.2f}{flex:>9}{cost_usd(job, model, 'batch'):>9.2f}")

print("\nWhat happens to the failures:")
print(f"  async: ~{job.requests * 0.01:.0f} transient errors (1%): the SDK retries them; the {extra} timeouts may be billed twice")
print(f"  flex:  ~{job.requests * 0.15:,.0f} first attempts refused with 429 'Resource Unavailable' (not billed); retry, then fall back to standard")
print("  batch: each request ends ok / errored / expired; you resubmit only those, in a second, smaller batch")
Output · layer 1; arithmetic on the stated assumptions, not a measurement20 lines
prices match 03.7's table (version 2026-11-04) 

20,000 tickets x (160 in + 4 out tokens) = 3.3M tokens

wall time     25 min   async, 20 at once        (bound by: concurrency)
               5 min   async, 400 at once       (bound by: RPM; this is what the rate limiter enforces)
               5.9 h   flex, 20 at once         (bound by: concurrency)
              71 min   flex, 100 at once        (bound by: concurrency)
              1-24 h   batch: a single job, no concurrency to manage; the provider decides when it runs

model                   async     flex    batch   (USD; async includes 100 calls billed twice after timeouts)
gpt-6-luna               0.36     0.18     0.18
claude-haiku-5-5         0.36      n/a     0.18
claude-sonnet-5-5        7.24      n/a     3.60
gemini-3.8-flash         2.71     1.35     1.35

What happens to the failures:
  async: ~200 transient errors (1%): the SDK retries them; the 100 timeouts may be billed twice
  flex:  ~3,000 first attempts refused with 429 'Resource Unavailable' (not billed); retry, then fall back to standard
  batch: each request ends ok / errored / expired; you resubmit only those, in a second, smaller batch

14.2 Reading the result#

Time.

  • Async with 20 in flight: 25 minutes, limited by the concurrency (20 ÷ 1.5 s ≈ 13 requests per second), far below the quota. Raising the concurrency to 400 brings it down to 5 minutes, where the 4,000-per-minute rate limit takes over. That is what the semaphore plus the limiter of Part 5 is for.
  • Flex at the same concurrency takes nearly six hours, because each call is slow and some are refused. Flex needs more concurrency to compensate (100 in flight: 71 minutes). It's the same code with a bigger semaphore and a longer timeout.
  • A Batch API has no concurrency to manage and no guarantee: anywhere from minutes to 24 hours.

Cost.

Model Async Flex Batch Batch saves
gpt-6-luna $0.36 $0.18 $0.18 18 cents
claude-sonnet-5-5 $7.24 n/a (no flex tier) $3.60 $3.64
Model Async Flex Batch Batch saves
gemini-3.8-flash $2.71 $1.35 $1.35 $1.36

For a small, cheap model the saving is cents, and the engineering time for a batch pipeline costs more than the discount saves. For a bigger model or 100× more tickets, the discount is real money: at 2 million tickets on Sonnet the same arithmetic gives about $724 against $360. The decision rule: estimate the saving, then compare it with the cost of building and operating the more complex path. The async path with a limiter is 100 lines of code you already have; the batch path is a pipeline with state (Part 11).

Provider limits can decide for you. 20,000 tickets at 164 tokens is 3.3 million tokens. On Gemini's Tier 1 the enqueued-token cap for 3.8 Flash is 3 million (9.2), so the batch must be split in two jobs and submitted in waves. Anthropic's batch limits are in requests, not tokens (100,000 per batch, and a processing queue of 200,000 requests on the Start tier, 8.2), so 20,000 tickets fit in one batch. OpenAI has a per-model limit on queued prompt tokens, but its guide gives no number (7.2): whether 3.3 million tokens fits depends on your model and tier, so look the number up on your limits page before you assume it does, and use the queue cap in the runner (11.6) if it doesn't.

14.3 What happens when things fail#

Async (20 at once) Flex (100 at once) Batch
Typical failures 429s, 5xx, timeouts 429 Resource Unavailable (not billed), timeouts Per-request errored, expired, and invalid or truncated answers
How you learn An exception per call An exception per call At the end, in the results
What it costs Timed-out calls may bill twice (here about 100 calls) Refused calls are free; fallbacks pay standard prices Only successes bill (Anthropic), completed requests bill on expiry
Handling run_bounded keeps successes and records failures (4.4); retry with the classifier Backoff, then fall back to standard (12.2) Reconcile on custom_id, resubmit the failures in a second, small batch or through the async path (11.7)
State to persist Which items are done (at least in a file) The same The manifest and the batch IDs (11.2)
If the process dies Restart from the saved results Same The batch keeps running at the provider; resume with the manifest (11.6)

14.4 A decision checklist#

Work down the list and stop at the first "yes":

  1. Is a person or a live process waiting for each answer? Use standard async with streaming where it helps, and bounded concurrency (Parts 2 to 5). Pay for fast mode only if latency is measurably costing you.
  2. Is it one very long task rather than many? Use background mode and a webhook or a slow poll (Part 13).
  3. Is the saving smaller than a day of engineering? Use async with a rate limiter. Stay simple.
  4. Can the whole job wait up to 24 hours, and do you have no use for partial results before it ends? Use a Batch API (Parts 6 to 11).
  5. Do you need the results within hours, or each result as soon as it's ready, and the provider has a flex tier? Use flex with a deadline and a fallback (Part 12).
  6. Is the volume so large it would starve your live traffic's quota? Put it in a Batch API (separate pool) or a separate project and key.

And whatever you pick: bound the concurrency, save progress as you go, validate every answer, and decide ahead of time what happens to the failures.

14.5 When one process isn't enough#

Everything here runs in one process and keeps its state in one SQLite file. When you need many workers, schedules, retries across machines, a dashboard of job states and alerting, you're building a job orchestration system with queues and workers (Celery, RQ, Temporal, Airflow, a cloud queue). That is Module 11C's territory. The design in this lesson (deterministic IDs, a manifest with explicit states, idempotent steps, results validated and stored before use) is exactly what those systems need from you, so the work carries over.


Common misconceptions#

Misconception Reality
"More concurrency is always faster." Only until a rate limit, the connection pool or the provider's capacity pushes back. After that you get 429s and retries, and the job gets slower (5.2).
"async def makes my code concurrent." Only the awaited calls overlap. A sync client inside async def blocks the whole event loop (2.6).
"asyncio.gather cancels the others when one fails." It doesn't. The first exception is raised, the other calls keep running and billing, and you lose their results. Use return_exceptions=True, or a TaskGroup when you really want all-or-nothing (4.3).
"A client per task is fine, it's just an object." Each client owns a connection pool. One per task means one TCP and TLS connection per request (4.6).
"A semaphore limits my requests per minute." It limits requests in flight. A per-minute quota needs a rate limiter (Part 5).
"asyncio.run() works in a notebook." A notebook already has a running loop; await at the top level of the cell (2.5).
"Batch results come back in the order I sent them." OpenAI, Anthropic and OpenRouter say outright they don't. Gemini's guide is silent and its REST reference says input order; join on the ID anyway (6.3).
"A completed batch means every request succeeded." The job ended; individual requests may have errored, expired or returned unusable answers. Count and validate (6.5, 11.3).
"Batch jobs are safe to resubmit." Creating a batch isn't idempotent on any provider. A resubmit after an ambiguous crash creates a second job and a second bill (11.1).
"I can fetch the results next month." OpenAI's output files are deleted after 30 days (configurable), Anthropic's results after 29, OpenRouter's after 30. Gemini's guide states no retention for batch output, which arrives as a Files API file (48 hours per 03.6), so assume 48 hours at most. Download promptly (6.2).
"Gemini's Batch API works with Interactions." It is generateContent only; translate your requests (9.5).
"OpenRouter has no batch API." It has its own inline one, with webhooks, no cancel, and a catalogue :batch variant you don't write yourself (Part 10).
"Flex is just a cheaper tier, it can't fail." It can return 429 Resource Unavailable (not billed) and it's slower. Plan the fallback (12.2).
"Fast mode raises my throughput." It lowers latency. It doesn't raise rate limits, and a job that is rate-limited stays rate-limited (12.3).
"Background mode means the job can't fail or be abandoned." It survives a dropped connection, not a bug. It keeps billing until it finishes or you cancel it (13.4).
"A webhook is enough; no need to poll." Webhooks can be late, duplicated or lost. Keep a slow poll as a safety net and deduplicate (13.5).
"My webhook handler can parse the JSON first." Verify the signature on the raw bytes before parsing (13.7).
"If the signing secret isn't set, the receiver just skips the check." That is the worst failure: an empty secret is a key anyone can sign with, so the receiver accepts forged events. A receiver fails closed: no secret, no events (13.7).
"Anthropic has webhooks, so I can wait for a batch webhook." Not for Message Batches. Managed Agents webhooks are a beta for other products (3 attempts, then the event is dropped) and organization webhooks don't send events yet; poll batches (13.6).
"If a job came back completed, I can use its text." Only after polling has ended and check_response() agrees: a completed response can be a refusal or empty, and the check says incomplete for a job that is still running, so never act on it mid-poll (13.2).
"Server-side batching and Batch APIs are the same thing." One is how a provider's GPUs serve many users; the other is a job interface with a discount (1.4).

Key takeaways#

  • LLM calls are I/O-bound: concurrency raises throughput and leaves per-call latency unchanged. Throughput is roughly concurrency ÷ latency.
  • Pick the tool by who is waiting and what it's worth: async for interactive work, flex for bulk work needed soon, a Batch API for bulk work that can wait up to 24 hours, background mode for one long task. Estimate the saving before building anything more complex.
  • Use one async client per process, close it, and never put a sync call inside async def. AsyncOpenAI, AsyncAnthropic and client.aio all share their sync twins' methods.
  • Bound concurrency with a semaphore, put only the network call inside it, and keep every outcome: gather(return_exceptions=True) or a wrapper that catches inside each task. Use TaskGroup only for all-or-nothing work.
  • A semaphore limits requests in flight, a rate limiter limits requests per minute. Combine them, make a 429 pause everyone, and put a deadline around the whole job.
  • Mind the connection pool: it can silently become your real concurrency bound, and a client per task defeats it.
  • Batch APIs (OpenAI, Anthropic, Gemini; OpenRouter's own variant) cost about half, run in their own rate-limit pool, return results in any order, and can expire. Join on custom_id or key, download promptly, and validate every result.
  • Know each provider's shape: OpenAI = JSONL file + Files API, 50,000 requests / 200 MB; Anthropic = inline requests, 100,000 / 256 MB, results streamed, 29 days; Gemini = inline (20 MB) or JSONL file (2 GB), generateContent only, 48 hours; OpenRouter = inline JSON, results inline, no cancel.
  • A robust job has deterministic IDs, a manifest, a recorded intent before each action, one transaction per collected batch, an up-front estimate, a queue cap it respects, and a retry policy that changes something. A batch the provider rejected (failed) is not retried; an item out of attempts is marked failed, not left pending. Then it can be killed and resumed without paying twice, and it can report what it cost (per-result usage through 03.7's cost_calc).
  • When you can, ask for a schema instead of a word (11.3b): the format check moves to the provider, and the invalid class shrinks to refusals and truncation. Change the request and the parser together.
  • Flex can say no (429, not billed) and is slower, so raise timeouts and write the fallback. Fast/priority buys latency, not throughput. Read the tier actually used from the response (a field, usage, or a header).
  • Background mode (OpenAI Responses, Gemini Interactions) keeps a job alive without your connection: poll with backoff, cancel when you give up. Webhooks push completion: verify the signature on the raw body, check the timestamp, answer 2xx fast, deduplicate, queue the ID, and keep a slow poll as a backup. A receiver fails closed: with no secret configured it refuses everything. Anthropic has no webhook for Message Batches, so poll. After polling, judge the final response with check_response(), never during it.

Terms introduced in this lesson#

Term One-line definition
I/O-bound Work whose time is spent waiting for something outside your program (the network), not computing
Concurrency Having many operations in progress at once, so waiting overlaps
Little's law Throughput = concurrency ÷ latency: how many requests must be in flight to reach a target rate (3.1)
Connection pool The set of open, reusable HTTP connections a client keeps to a provider; it can silently cap your real concurrency (4.6)
Event loop The scheduler that runs async tasks, switching at each await
Task A coroutine scheduled to run on the event loop
Semaphore A counter of free slots that limits how many tasks run a block at once
Bounded concurrency Running many tasks but never more than a fixed number at a time
TaskGroup An async structure whose tasks live and die together: one failure cancels the rest
ExceptionGroup / except* The container for several exceptions at once, and the syntax that catches matching ones from it
Back-pressure Making a producer wait when consumers can't keep up, so memory stays bounded
aiohttp backend An optional HTTP transport for the async SDK clients, instead of httpx / httpx2
AIMD Additive increase, multiplicative decrease: raise a limit slowly, cut it sharply on an error
Batch API A job interface: submit many requests, collect results later, at about half price
Completion window The time a provider has to finish a batch before it expires: 24 hours on OpenAI and Anthropic, the target on Gemini (which expires jobs after 48 hours) and OpenRouter (provider-dependent)
custom_id / key Your own ID for a request in a batch, returned with its result; the join column
JSONL JSON Lines: one JSON object per line, the file format of batch input and output
Result reconciliation Matching results to inputs by ID, and accounting for every request
Partial failure A batch (or concurrent run) in which some requests succeeded and some failed
Manifest / checkpoint A durable record of each item's and batch's state, so a job can resume
Idempotent resubmission Re-running a job so that only the items without a good result are sent again
Request packing Putting several items into one request to save instruction tokens and request counts
Flex / priority tiers Two synchronous service tiers for the same model: flex is cheaper, slower and best-effort (it may refuse requests), priority is pricier and lowers latency
Background mode Starting a long request that the provider keeps running server-side, fetched later
Webhook An HTTP POST the provider sends to your server when a job finishes
Signature verification Checking an HMAC (or JWT) over the raw body and timestamp to prove a webhook is genuine
Fail closed When a check can't run (a missing secret, an unreadable config), refuse everything instead of accepting everything
Queue cap A limit on what you may have waiting at the provider at once (tokens or requests); a resumable job submits only while it has room
Standard Webhooks The open specification for webhook headers and signatures that several providers follow

Exercises#

All of these run without keys, against the mocks and local code from this lesson.

  1. Little's law (3.1): change the mock's latency to 1.0 s and the concurrency to 8. Predict the wall time for 40 requests before you run it, then run it. What would you set the concurrency to for 100 requests per second?
  2. Pool vs semaphore (4.6): make a shared client with max_connections=4 and a semaphore of 20. Where does the waiting happen, and what pool timeout makes requests fail? Then raise the pool to 20 and compare.
  3. TaskGroup (4.3): wrap each task in try/except Exception inside the TaskGroup and record the failures in a dict. Does the group still cancel anything? What did you rebuild?
  4. Progress (4.4): add a progress callback that prints every 5 seconds with a throughput figure (items per second) instead of every 10 items.
  5. Limiter (5.2): set the mock server's limit to 5 requests per second without changing the client, and watch the adaptive concurrency limit settle. Then add a limiter at 4.5 requests per second and compare 429 counts.
  6. Deadline (5.3): change the deadline to 5 seconds and save the finished results to a JSONL file as they arrive. Run it twice and make the second run skip the finished keys.
  7. Polling (6.4): add a "stuck" job to s6_4_poll_schedule.py that stays in_progress forever, and show that PollTimeout carries enough information for a later process to resume (what must you have saved?).
  8. Reconcile (7.1, 8.1, 9.1): add a seventh ticket whose custom_id appears twice in an OpenAI output file (a duplicate line). What does reconcile do? Decide what it should do and change it.
  9. Chunking (11.4): give plan_chunks a list where one item is bigger than the byte limit. What happens, and why is raising an error better than skipping the item?
  10. Resume (11.6): run the demo with CRASH_AT=before_create_triage-v1-b0000, and again with CRASH_AT=after_collect_triage-v1-b0000 (the three crash points in batch_runner.py are before_create_<key>, after_create_<key> and after_collect_<key>). Which state does the manifest end up in each time, what does recover() print, and does the final result differ?
  11. Estimate (11.5): add the output cost of a reasoning model (500 hidden tokens per answer) to s11_5_estimate.py. How much does a 5,000-ticket job grow?
  12. Flex (12.2): change the mock so flex answers 429 with a Retry-After: 2. Use parse_retry_after from 03.8 to wait exactly that long instead of the fixed backoff.
  13. Webhooks (13.7): add a test that sends the same signed event from two threads at the same moment. Can your receiver queue it twice? Make enqueue_once safe with a SQLite unique constraint.
  14. Calculator (14.1): change the assumptions to 2,000,000 tickets on claude-sonnet-5-5 with 600 input tokens each and a 5,000 RPM limit. How many OpenAI batches does that need, and does the async path still finish overnight?
  15. Queue cap (11.6): change queue_cap_tokens in s11_6_resumable.py to 150, then to 100. What does the peak queue estimate become, and what does the runner do at 100 (a chunk is about 130 tokens)? Why is raising an error better than waiting?
  16. A rejected batch (11.6): requeue the five items of the rejected batch after changing the text of ticket 10303 (what SQL do you need?). Does the runner submit them again, and how many batches does the provider see now?
  17. Schema (11.3b): add a fifth label to Triage and rebuild the requests. Which field of which provider's request changes, and what happens to results from the old job name? Then make the one-word parser and the schema parser disagree on a fixture of your own.
  18. Forgery (13.7): add an Anthropic-style route that accepts any event type, then write the test that signs with an empty key. What must the route do so that the test passes?
Hints and what to expect
  1. Prediction: 40 ÷ 8 × 1.0 s = 5 s plus start-up, with a peak of 8 in flight. For 100 requests per second at 1.0 s per call, Little's law says about 100 in flight (as long as the server and your rate limits allow it).
  2. With a pool of 4 the 16 surplus tasks wait inside the pool, for a connection, not for the provider; 40 requests take about 40 ÷ 4 × 0.3 = 3 s instead of about 0.6 s. Requests fail when the wait exceeds the client's pool timeout (APITimeoutError). At 20 connections nothing queues.
  3. Nothing is cancelled any more, because no exception ever leaves a task. You have rebuilt run_bounded from 4.4.
  4. Keep the time of the last print and the count at that moment; print when five seconds have passed: (finished - last_count) / (now - last_time) is the throughput.
  5. At 5 requests per second and 0.3 s per call, about 1.5 requests are in flight in steady state, so the adaptive limit shrinks towards 1 or 2. A limiter at 4.5 requests per second (rpm=270, burst_s=1) should give zero or near-zero 429s.
  6. Write each result to the JSONL file inside one() as soon as the call returns (after the await, before the function ends). On the second run read the keys already in the file and skip them when you build the task list.
  7. A later process needs the batch ID (and which provider it belongs to), plus the custom_id map or manifest. PollTimeout only says that you stopped waiting; it carries no state about the job, and it does not cancel it.
  8. As written, reconcile keeps the last line for a repeated custom_id (the dictionary assignment overwrites) and says nothing. A good change: detect the repeat, keep the first result, and record a failed or invalid note for the duplicate, because a provider should never send one and you want to hear about it.
  9. plan_chunks raises ValueError naming the item. Skipping would lose the item silently; the error forces a decision (shorten the document, send it by another path).
  10. before_create_...: the manifest shows the batch as creating and its items submitted, but the provider has no batch. recover() prints that the batch "was never created; its items are pending again" (and gives the attempts back). after_collect_...: results and the collected flag are committed together, so there is nothing to recover and the next run goes on with the next chunk. Both runs end with all 23 items done.
  11. Add 500 to output_tokens for the job estimate (the visible cap stays 16). At $0.50 per million output tokens and the batch half price, a 5,000-ticket job grows from about $0.06 to about $0.69: output tokens cost five times what input tokens do, and 500 hidden tokens dwarf 16 visible ones.
  12. Read the header with parse_retry_after(e.response.headers) and await asyncio.sleep(...) for exactly that long (it returns None when there is no usable header: then use your backoff).
  13. Two threads can both see "not seen yet" before either records the ID. Make the ID the primary key of a SQLite table and insert it: INSERT raises IntegrityError for the second one, and only the thread whose insert succeeded queues the job.
  14. By the module's arithmetic: Sonnet at standard prices costs about $2,480 and as a batch about $1,240. With roughly 2.7 KB per request line the 47,500-request planning cap (not the byte cap) binds, so about 43 OpenAI batches. Async: 20 at once takes about 42 hours; 400 at once is bound by the 2,000,000 tokens-per-minute default (about 10 hours) or, with a raised token limit, by the 5,000 RPM (about 6.7 hours). Overnight is possible only with high concurrency and a higher token limit.
  15. At 150 the runner keeps one batch (about 130 tokens) queued at a time, so the peak estimate is about 130. At 100 even an empty queue cannot take a 130-token chunk, so submit_pending raises ValueError: waiting would never help, and a loop that waits forever hides a configuration mistake.
  16. Fix the text first (UPDATE items SET text = '...' WHERE ticket_id = '10303'), then requeue the five items: UPDATE items SET status = 'pending', attempts = 0, detail = NULL WHERE batch_key = 'triage-v1-b0000'. The runner submits them as a new batch, so the provider has now seen six batches in all.
  17. The Literal in Triage changes, and with it the schema in all three request fields (OpenAI text.format.schema, Anthropic output_config.format.schema, Gemini response_json_schema). Rename the job (triage-v2): new custom_ids keep the old results apart from the new ones. For disagreement, use a fixture such as Bug. (the one-word parser accepts it, the schema parser rejects it) and {"label":"bug"} (the opposite).
  18. The route must refuse with a 500 when no secret is configured, never verify against an empty key, and verify the raw body before it reads anything. The test passes when the empty-key forgery gets 500 with no secret set and 400 with a real one.

Check yourself#

  1. Why does running 20 LLM calls concurrently not make any single call faster, and what does it improve?
  2. What is the difference between a semaphore and a rate limiter, and why might you need both?
  3. What happens to the other tasks when one raises in asyncio.gather(*calls), in gather(..., return_exceptions=True), and in a TaskGroup?
  4. Why should except asyncio.CancelledError re-raise?
  5. A FastAPI endpoint uses async def and the sync OpenAI() client, and it is slow under load. Why, and what are two fixes?
  6. You set a semaphore of 50, but only 10 requests are ever in flight. Where do you look?
  7. Which statement is correct for all four providers' batch results: they come back in input order; they can be matched by an ID you chose; they are kept forever? Name each provider's retention, and say which one is not documented.
  8. A batch's status is completed/ended/succeeded. Why can your job still have failures, and how do you find them?
  9. Why does Anthropic's batch custom_id rule force you to think about IDs like ZD#10236/a?
  10. What does Gemini's Batch API not support that Google's recommended API for new projects does, and how do you cope?
  11. Your batch job crashed between batches.create and saving the batch ID. How can you find the batch on OpenAI? On Anthropic?
  12. When is flex the right tool, and what must your code do when it gets a 429?
  13. How can you tell, in code, which service tier served a request on each of the four providers?
  14. What happens to a background response when you pass store=False, and what does Gemini do if you combine background=True with store=False?
  15. List four things a webhook receiver must do, and the one thing it must not do before verification.
  16. Your resumable runner has a queue cap and one of its batches comes back with status failed. What should it do with that batch's items, and why not just resubmit them? And what should happen to an item that has used up its attempts?
  17. A webhook receiver's signing secret isn't set. What should every route do, and why is "verify with an empty key" dangerous?

Further resources#


← 03.8 — Errors, Rate Limits, Timeouts and Retries | Module 03 overview | 03.10 — Logging, Debugging and Testing LLM Code →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close