03.8 Errors, Rate Limits, Timeouts and Retries
Every LLM call you ship will fail sometimes. Some failures are ordinary: the network drops or a server restarts. Some are specific to LLM APIs: the provider is overloaded, you've used up your tokens-per-minute budget, you've run out of credits, or the model refused, was blocked or stopped half-way through an answer that still arrived as 200 OK. This lesson teaches you to tell these failures apart precisely, for OpenAI, Anthropic, Gemini and OpenRouter, and to react to each one correctly: retry it, wait for it, fix it, or show the user something sensible. You'll learn exactly what each SDK already does for you (and where the docs and the SDKs disagree), how to set timeouts that fit the work, how to back off without causing a stampede, how to stay under rate limits before you hit them, and how to avoid paying twice for one answer. You'll finish with one tested function that makes a production-grade call to any of the four providers.
What you'll learn
- The four kinds of failure (transport, HTTP error, error inside a 200, and "successful" responses that are failures for your app), and the right reaction to each
- The complete error taxonomy of all four providers: HTTP status, the provider's error type or code, the SDK exception class, and whether to retry, in verified tables
- The traps in the exception hierarchies:
APIErroralso catching connection errors, Anthropic'sOverloadedErrornot being anInternalServerError, Gemini's Interactions API raising a completely separate family of exceptions, and OpenRouter's 402 having no class of its own - Why a 429 can mean "slow down" or "you're out of money", and how to tell which in code
- Exactly how each SDK retries by default (counts, backoff formula,
Retry-After,x-should-retry), and how to configure or disable it - Timeouts: connect, read, write and pool; per-attempt and total deadlines; Gemini's milliseconds; Anthropic's 10-minute guard; and why a timed-out request can still bill you
- Exponential backoff with jitter (the four AWS formulas), parsing
Retry-Aftercorrectly, and retry budgets tenacity: retrying only what should be retried, honouringRetry-Afterwith a custom wait, async, logging, and when not to use it at all- Rate limits in code: each provider's dimensions and tiers, the rate-limit headers and a parser for them, and a client-side token-bucket limiter (with a burst control) that estimates tokens before a call and corrects itself from
usageafterwards - A
check_response()that turns refusals, safety blocks, truncation, cancelled or unfinished responses and errors inside a 200 into typed outcomes, and which of those are worth a retry - Idempotency: why none of the four APIs protects you from duplicate charges, and how to make tool side effects safe yourself
- Request IDs, support tickets, and degrading gracefully when the provider can't help
What you don't need
- Any API key. Every sample in this lesson runs without one, except two marked provider samples. Errors come from the real SDKs, either against the free local stand-in from lesson 03.1 or against small mock servers that return each provider's documented error shapes.
- Prior experience with retries or rate limiting. Generic Python retry basics are in Module 01B, and this lesson explains everything it uses.
- Knowledge of circuit breakers, gateways or multi-provider routing. Those are system-level concerns for Module 11C. This lesson is about getting one call right.
Setup
The samples need Python 3.11+ and the three official SDKs. They 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 tenacity:
uv add openai anthropic google-genai python-dotenv tenacity httpx
# or: pip install openai anthropic google-genai python-dotenv tenacity httpxFirst 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.
The two provider samples (10.5 and 13.3) read keys from a .env file (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY), as set up in 03.1. Without keys, point the OpenAI, Anthropic and OpenRouter-shaped calls at the free local stand-in (03.1, 12.3): they run unchanged. Gemini has no local stand-in (Ollama doesn't speak Gemini's API: 03.1, 12.4), so the Gemini parts of those samples need a hosted key. The section 2.3 sample talks to the stand-in directly, so it needs Ollama running.
Several samples import small modules built in this lesson: retry_after.py (7.3), llm_errors.py (4.4), ratelimit_headers.py (9.3), rate_limiter.py (9.5), check_response.py (10.2) and production_call.py (13.2, with an async twin in 13.4). Keep them in the same folder as the samples. Each module is given in full where it is introduced.
What you must be able to do after this lesson#
- Classify an LLM failure as transport, rate limit, server or client error
- Decide what to retry and what never to retry
- Write backoff with jitter
- Set timeouts correctly
- Handle rate limits in code
- Write a production call with retries
Why this matters for an AI engineer#
LLM calls are slow, metered in tokens, rate-limited in tokens, and can fail after they succeed. The engineers who ship reliable AI features are the ones who know exactly which failures to retry and which to surface.
| You'll hear... | You'll understand it after... |
|---|---|
| "We got a 429. Just retry it." | 4.2 A 429 can mean "slow down" or "out of money" |
| "Claude keeps returning 529s." | 3.3 Anthropic |
"Our except InternalServerError didn't catch the overload." |
3.3 Anthropic |
| "The Gemini SDK retries automatically, right?" | 5.2 google-genai |
| "Each request turned into 24 attempts during the outage." | 5.5 The double-retry trap |
| "The request timed out, but we were still billed." | 6.6 Timeouts that still bill |
| "Why does the Anthropic SDK say streaming is required?" | 6.4 Anthropic's 10-minute guard |
| "Add exponential backoff with jitter." | Part 7: Backoff done right |
"The server said Retry-After: 30." |
7.2 Retry-After |
"Wrap it in @retry from tenacity." |
Part 8: tenacity |
| "We're hitting our TPM limit at 9 a.m. every day." | Part 9: Rate limits in code |
| "The API returned 200 but the answer was empty." | Part 10: Errors that arrive as HTTP 200 |
| "A retry sent the customer two refund emails." | Part 11: Idempotency and duplicate charges |
| "Send support the request ID." | Part 12: Request IDs and support tickets |
| "What should the user see when the model is down?" | 13.5 Graceful degradation |
Part 1: How LLM calls fail#
1.1 Four kinds of failure#
An LLM call can go wrong in four different places, and each needs a different reaction. Think of ordering food by phone:
- The call doesn't connect (a transport failure): no dial tone, the line drops, or nobody picks up before you give up. In code that means DNS failures, TLS errors, a refused or reset connection, or a timeout. There is no HTTP response at all.
- The restaurant says no (an HTTP error): "we're closed" or "we're too busy, call back in ten minutes". The server answers with a 4xx or 5xx status and a JSON body explaining why.
- The order is accepted, then something breaks (an error inside a 200): the kitchen starts cooking and then runs out of an ingredient. The server has already sent
200 OK, so the error travels inside the body: an error event in a stream,finish_reason: "error", or (on OpenRouter) a 200 whose JSON is just anerrorobject. - The food arrives, but it's not what you can use (a "successful" failure): the answer is a refusal, was blocked by a safety system, was cut off at the output limit, is empty because the model spent its budget thinking, or the response says
status: "incomplete"orstop_reason: "model_context_window_exceeded". Everything at the HTTP level worked, so nothing raises an exception.
Here is the whole decision as one tree. The rest of the lesson fills in every box:
flowchart TD
S["Call the provider"] --> Q1{"Did an HTTP response arrive?"}
Q1 -- "no" --> T["1. Transport failure<br/>DNS, TLS, refused, reset, timeout"]
T --> TA["Retry with backoff<br/>(a timed-out request may still have run and billed)"]
Q1 -- "yes" --> Q2{"Status 4xx or 5xx?"}
Q2 -- "yes" --> H["2. HTTP error with a JSON body"]
H --> Q3{"Retryable?<br/>408, 409, 429 slow-down,<br/>5xx, 529"}
Q3 -- "yes" --> HA["Retry: honour Retry-After,<br/>else full-jitter backoff"]
Q3 -- "no: 400, 401, 403, 404,<br/>413, 422, quota, billing" --> HB["Don't retry: fix the request,<br/>trim the context or alert a human"]
Q2 -- "no: 200" --> Q4{"Error inside the 200?<br/>error event, finish_reason error,<br/>body with an error object"}
Q4 -- "yes" --> E["3. Error after 200 OK"]
E --> EA["Not retried by the SDKs (one exception: google-genai<br/>resumes long Gemini generations, 03.3). Your code decides:<br/>restart, continue or fail"]
Q4 -- "no" --> Q5{"check_response():<br/>refused, blocked, truncated,<br/>empty, incomplete?"}
Q5 -- "yes" --> F["4. A successful failure"]
F --> FA["Handle as an outcome:<br/>fallback message, bigger budget,<br/>shorter input. Usually not a retry"]
Q5 -- "no" --> OK["Use the answer<br/>(still validate it)"]| Kind | How you notice | Typical reaction | Where |
|---|---|---|---|
| 1. Transport | An exception with no status code (APIConnectionError, APITimeoutError, raw httpx errors on Gemini) |
Retry with backoff, within a total deadline. Remember that a timed-out request may have run | Part 2, Part 6 |
| 2. HTTP error | A status exception (RateLimitError, BadRequestError, errors.ClientError...) |
Depends on the status and the error code: retry, wait, fix the request, or alert | Part 3, Part 4 |
| 3. Error inside a 200 | Mid-stream error events, or a 200 body with error |
Not retried by the SDKs. One exception: google-genai resumes long Gemini generations from a continuation_token (03.3, 4.5b). Anything else is your code's decision |
03.3 Part 7, 10.1 |
| 4. "Successful" failure | Only by inspecting the response: status, stop reason, refusal fields, block reasons | Handle as an outcome: show a fallback, raise the budget, shorten the input. Usually not a retry | Part 10 |
1.2 What's different about LLM APIs#
If you've called payment, maps or storage APIs for years, most of your instincts still apply. These don't:
| Ordinary REST API | LLM API | What it means for you |
|---|---|---|
| Requests take milliseconds | Requests take seconds to many minutes (long outputs, reasoning) | Default timeouts are long (10 minutes on openai and anthropic), and a short one kills healthy requests (Part 6) |
| Rate limits count requests | Rate limits count tokens too, input and output, per minute | One huge request can use your whole minute (Part 9, 02.7, 6.4) |
| 429 means "slow down" | 429 can also mean "you're out of money" | Retrying a billing 429 can never work (4.2) |
| A 200 means success | A 200 can carry a refusal, a block, a truncated answer, or an error | Check every response before using it (Part 10) |
| Retrying returns the same thing | Retrying returns a different answer (generation isn't deterministic, 02.5 Part 7) | Never splice a retried stream onto a broken one (03.3, 7.4) |
| Idempotency keys are common (payment APIs) | None of the four inference APIs supports them | A retry after a timeout can bill twice and repeat tool side effects (Part 11) |
| Failures cost nothing | Failures can cost money: input is processed before many errors, abandoned requests may finish server-side, and some Anthropic refusals are billed (10.4) | Cap retries and log usage as unknown, not zero (03.3, 7.6) |
Part 2: Transport failures#
2.1 When no HTTP response arrives#
A transport failure happens below HTTP: the client never got a status code. The common causes:
| Cause | What happened | Typical message in the cause chain |
|---|---|---|
| DNS failure | The host name couldn't be turned into an IP address (typo in base_url, no network, a broken VPN) |
ConnectError: [Errno 8] nodename nor servname provided |
| Connection refused | Nothing is listening at that address and port (a local server that isn't running, a wrong port) | ConnectError: [Errno 61] Connection refused |
| TLS failure | The encrypted connection couldn't be set up: a corporate proxy re-signing traffic, missing CA certificates (03.1, 4.5) | ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] |
| Connection reset | The connection was open, then dropped (a proxy, a load balancer, a server restart) | RemoteProtocolError, ReadError |
| Timeout | The client gave up waiting: to connect, to send, for the next bytes, or for a pooled connection (Part 6) | ConnectTimeout, ReadTimeout, WriteTimeout, PoolTimeout |
The underlying HTTP library (httpx2 for openai and anthropic, httpx for google-genai) raises these. What reaches your code depends on the SDK:
| SDK | Connection failure | Timeout | Original error |
|---|---|---|---|
openai |
openai.APIConnectionError |
openai.APITimeoutError (a subclass of APIConnectionError) |
e.__cause__ |
anthropic |
anthropic.APIConnectionError |
anthropic.APITimeoutError (a subclass of APIConnectionError) |
e.__cause__ |
| SDK | Connection failure | Timeout | Original error |
|---|---|---|---|
google-genai, client.models.* |
The raw httpx exception, e.g. httpx.ConnectError (not a genai.errors.APIError) |
The raw httpx.ReadTimeout / httpx.ConnectTimeout (subclasses of httpx.TimeoutException) |
It is the original |
google-genai, client.interactions.* |
APIConnectionError from google.genai._interactions |
APITimeoutError from google.genai._interactions |
e.__cause__ |
OpenRouter (through openai) |
As openai |
As openai |
As openai |
A transport failure is usually worth retrying, with one serious caveat: after a timeout, you don't know whether the provider received and processed the request. It may have generated the full answer and billed you for it (6.6).
2.2 What an exception object carries#
Status exceptions carry everything the server said. You'll use these attributes constantly:
openai (and OpenRouter) |
anthropic |
|
|---|---|---|
| Base class to catch | openai.APIError (all API errors), openai.APIStatusError (has a status) |
anthropic.APIError, anthropic.APIStatusError |
| HTTP status | e.status_code |
e.status_code |
| Provider's error string | e.code (e.g. "credit_balance_exhausted") and e.type (e.g. "insufficient_quota") |
e.type (e.g. "overloaded_error") |
| Message | e.message |
e.message |
| Which parameter was wrong | e.param (from the body, None when the API doesn't say) |
none (read the message) |
| Parsed body | e.body: the inner error object (the SDK strips the outer {"error": ...}) |
e.body: the whole body, {"type": "error", "error": {...}, "request_id": ...} |
| Request ID | e.request_id (from x-request-id) |
e.request_id (from request-id) |
| Raw response | e.response (headers via e.response.headers) |
e.response |
google-genai models.* |
google-genai interactions.* |
|
|---|---|---|
| Base class to catch | genai.errors.APIError (ClientError 4xx, ServerError 5xx) |
_interactions.APIError, _interactions.APIStatusError |
| HTTP status | e.code (an int) |
e.status_code |
| Provider's error string | e.status (e.g. "RESOURCE_EXHAUSTED") |
e.body["error"]["code"] (e.g. "payment_required") |
| Message | e.message |
e.message |
| Which parameter was wrong | none | none |
| Parsed body | e.details: the whole JSON body |
e.body: the whole body |
| Request ID | none: read e.response.headers if you need anything |
none |
| Raw response | e.response |
e.response |
These were read from the SDK source (openai/_exceptions.py, anthropic/_exceptions.py, google/genai/errors.py, google/genai/_gaos/lib/compat_errors.py) in the versions named in Setup.
2.3 Try it: real errors from a real (local) server#
These errors come from a real HTTP server, the free local stand-in from 03.1 Part 12: an unknown model, a malformed request, and a port where nothing is listening (port 9 on your own machine). Every client has max_retries=0 so you see each failure once, immediately. Gemini has no local stand-in, so the sample's Gemini lines are the two that never need a server: a client-side validation error and a refused connection.
"""Real errors from a real (local) server: an unknown model, a malformed request and a
refused connection, through the SDKs. Needs the local stand-in: Ollama on :11434. Gemini has no
local stand-in, so its two lines come from a client-side check and a refused connection."""
import anthropic
import openai
from google import genai
from google.genai import errors, types
def show(label: str, e: Exception) -> None:
print(f"{label}: {type(e).__name__}")
for attr in ("status_code", "code", "type", "status", "request_id"):
if hasattr(e, attr):
print(f" .{attr} = {getattr(e, attr)!r}")
body = getattr(e, "body", None) if not isinstance(e, errors.APIError) else e.details
if body is not None:
print(f" body = {str(body)[:110]}")
if not hasattr(e, "request"):
print(f" message = {str(e)[:110]}")
if e.__cause__ is not None:
print(f" caused by: {type(e.__cause__).__name__}")
# max_retries=0 everywhere: we want to see each failure once, immediately.
oai = openai.OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0)
claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama", max_retries=0)
gem = genai.Client(api_key="x") # never reaches a server in this script: see sections 2 and 3
print("=== 1. Unknown model ===")
try:
oai.responses.create(model="gpt-6-lunar", input="Hi") # typo in the model ID
except openai.NotFoundError as e:
show("openai", e)
try:
claude.messages.create(model="claude-haiku-5-6", max_tokens=50,
messages=[{"role": "user", "content": "Hi"}])
except anthropic.NotFoundError as e:
show("anthropic", e)
print("\n=== 2. Malformed request ===")
try:
oai.responses.create(model="gpt-6-luna", input=[ # a content part type that doesn't exist
{"role": "user", "content": [{"type": "input_txt", "text": "Hi"}]}]) # type: ignore[list-item]
except openai.BadRequestError as e:
show("openai", e)
try:
claude.messages.create(model="claude-haiku-5-5", max_tokens=50, messages=[]) # no messages at all
except anthropic.BadRequestError as e:
show("anthropic", e)
try:
gem.models.generate_content(model="gemini-3.8-flash", contents=[])
except (errors.APIError, ValueError) as e:
show("gemini", e)
print("\n=== 3. Nothing listening (port 9 is unused) ===")
dead = "http://127.0.0.1:9"
try:
openai.OpenAI(base_url=dead + "/v1", api_key="x", max_retries=0).responses.create(model="gpt-6-luna", input="Hi")
except openai.APIConnectionError as e:
show("openai", e)
try:
anthropic.Anthropic(base_url=dead, api_key="x", max_retries=0).messages.create(
model="claude-haiku-5-5", max_tokens=50, messages=[{"role": "user", "content": "Hi"}])
except anthropic.APIConnectionError as e:
show("anthropic", e)
dead_gem = genai.Client(api_key="x", http_options=types.HttpOptions(base_url=dead, timeout=5_000))
try:
dead_gem.models.generate_content(model="gemini-3.8-flash", contents="Hi")
except Exception as e: # not a genai error at all: see the text
show("gemini", e)
print(" is genai.errors.APIError?", isinstance(e, errors.APIError))=== 1. Unknown model ===
openai: NotFoundError
.status_code = 404
.code = None
.type = 'not_found_error'
.request_id = None
body = {'message': "model 'gpt-6-lunar' not found", 'type': 'not_found_error', 'param': None, 'code': None}
anthropic: NotFoundError
.status_code = 404
.type = 'not_found_error'
.request_id = None
body = {'type': 'error', 'error': {'type': 'not_found_error', 'message': "model 'claude-haiku-5-6' not found"}, 'requ
=== 2. Malformed request ===
openai: BadRequestError
.status_code = 400
.code = None
.type = 'invalid_request_error'
.request_id = None
body = {'message': 'input[0]: content[0]: unknown content type: input_txt', 'type': 'invalid_request_error', 'param':
anthropic: BadRequestError
.status_code = 400
.type = 'invalid_request_error'
.request_id = None
body = {'type': 'error', 'error': {'type': 'invalid_request_error', 'message': 'messages is required'}, 'request_id':
gemini: ValueError
message = contents are required.
=== 3. Nothing listening (port 9 is unused) ===
openai: APIConnectionError
.code = None
.type = None
caused by: ConnectError
anthropic: APIConnectionError
caused by: ConnectError
gemini: ConnectError
caused by: ConnectError
is genai.errors.APIError? FalseWhat this shows, and where the stand-in differs from the hosted APIs:
- The exception classes and attributes are real.
NotFoundError,BadRequestErrorandAPIConnectionErrorcome from the SDKs' own status-to-class mapping, exactly as with a hosted provider. request_idisNonebecause the stand-in sends nox-request-idorrequest-idheader. Hosted OpenAI and Anthropic always do, and so does every Anthropic error body ("request_id": "req_...").- Don't build logic on the stand-in's status codes or messages. They are Ollama's. Gemini isn't in the first section because it has no local stand-in; the hosted Gemini API uses 404
NOT_FOUNDfor an unknown model. - The Gemini "malformed request" never reached a server.
contents=[]is rejected inside the SDK with a plainValueError. Some validation happens client-side in every SDK, so catchValueErrorandTypeErrornear the call too, or (better) let your type checker catch them first. - Gemini's connection failure is a raw
httpx.ConnectError, not agenai.errors.APIError, as the table in 2.1 warned. The Interactions exception classes live ingoogle.genai._gaos.lib.compat_errors: private twice over (3.4).
Part 3: The error taxonomy, provider by provider#
Reference
3.1 The exception trees#
Before the per-provider tables, here is every exception class each SDK defines, printed straight from the installed packages:
"""Print each SDK's exception tree, straight from the installed classes (no network)."""
import anthropic
import openai
from google.genai import _interactions, errors # _interactions is private: see 3.3
def tree(root: type, module_objs: list[type], indent: str = "") -> None:
print(f"{indent}{root.__name__}")
children = [c for c in module_objs if root in c.__bases__]
for child in sorted(children, key=lambda c: c.__name__):
tree(child, module_objs, indent + " ")
def classes(mod: object) -> list[type]:
return [v for v in list(vars(mod).values()) if isinstance(v, type) and issubclass(v, BaseException)
and not v.__name__.startswith("_")]
print("--- openai 3.42.1 ---"); tree(openai.OpenAIError, classes(openai))
print("--- anthropic 2.4.0 ---"); tree(anthropic.AnthropicError, classes(anthropic))
print("--- google-genai 2.34.0: client.models.* ---"); tree(errors.APIError, classes(errors))
print("--- google-genai 2.34.0: client.interactions.* ---")
tree(_interactions.GeminiNextGenAPIClientError, classes(_interactions))
print("\nTraps:")
print(" anthropic OverloadedError is an InternalServerError?",
issubclass(anthropic.OverloadedError, anthropic.InternalServerError))
print(" openai APITimeoutError is an APIConnectionError?",
issubclass(openai.APITimeoutError, openai.APIConnectionError))
print(" openai LengthFinishReasonError is an APIError?",
issubclass(openai.LengthFinishReasonError, openai.APIError))
print(" interactions RateLimitError is a genai errors.APIError?",
issubclass(_interactions.RateLimitError, errors.APIError))--- openai 3.42.1 ---
OpenAIError
APIError
APIConnectionError
APITimeoutError
APIResponseValidationError
APIStatusError
AuthenticationError
OAuthError
BadRequestError
ConflictError
InternalServerError
NotFoundError
PermissionDeniedError
RateLimitError
UnprocessableEntityError
ContentFilterFinishReasonError
LengthFinishReasonError
WebSocketConnectionClosedError
WebSocketQueueFullError
--- anthropic 2.4.0 ---
AnthropicError
APIError
APIConnectionError
APITimeoutError
APIResponseValidationError
APIStatusError
AuthenticationError
BadRequestError
ConflictError
DeadlineExceededError
InternalServerError
NotFoundError
OverloadedError
PermissionDeniedError
RateLimitError
RequestTooLargeError
ServiceUnavailableError
UnprocessableEntityError
APIWebhookValidationError
CredentialsError
IdentityTokenFileError
RetryableError
WorkloadIdentityError
--- google-genai 2.34.0: client.models.* ---
APIError
ClientError
ServerError
--- google-genai 2.34.0: client.interactions.* ---
GeminiNextGenAPIClientError
APIError
APIConnectionError
APITimeoutError
APIResponseValidationError
APIStatusError
AuthenticationError
BadRequestError
ConflictError
InternalServerError
NotFoundError
PermissionDeniedError
RateLimitError
UnprocessableEntityError
Traps:
anthropic OverloadedError is an InternalServerError? False
openai APITimeoutError is an APIConnectionError? True
openai LengthFinishReasonError is an APIError? False
interactions RateLimitError is a genai errors.APIError? FalseRead the trees for their shape, then the tables below for meaning:
openaiandanthropicshare a design (both SDKs are generated by Stainless):APIErrorsplits intoAPIConnectionError(no response) andAPIStatusError(a response with a 4xx or 5xx status), and each common status has a subclass.anthropichas more status classes:RequestTooLargeError(413),OverloadedError(529), and two classes used only by its cloud clients (3.3). It also has non-HTTP errors for credentials (CredentialsError,WorkloadIdentityError) andRetryableError, which middleware can raise to opt a request into the retry policy.google-genaihas two unrelated families.client.models.*raiseserrors.APIErrorwith just two subclasses, split by 4xx and 5xx.client.interactions.*raises a Stainless-style family rooted atGeminiNextGenAPIClientError, which shares no base class with the first apart fromException.- Parse-helper errors aren't API errors.
LengthFinishReasonErrorandContentFilterFinishReasonErrorsubclassOpenAIErrordirectly, soexcept openai.APIErrormisses them (3.2).
3.2 OpenAI#
OpenAI's error-codes guide lists each error by status and code; the SDK maps statuses to classes. As of November 2026:
| HTTP | What the guide calls it (type / code) |
SDK class | Retry? | What to do |
|---|---|---|---|---|
| 400 | Invalid request, e.g. a bad parameter, an input over the context window, an invalid service_tier (type: invalid_request_error) |
BadRequestError |
No | Fix the request; trim the input for context errors |
| 401 | "Invalid Authentication", "Incorrect API key provided", "You must be a member of an organization", "IP not authorized" | AuthenticationError (OAuthError for failed workload-identity token exchanges) |
No | Alert: wrong, revoked or misplaced key; IP allowlist |
| 403 | "Country, region, or territory not supported"; no access to a model or project | PermissionDeniedError |
No | Check project permissions and model access |
| 404 | Unknown model or resource | NotFoundError |
No | Fix the model ID or path |
| 409 | Conflict | ConflictError |
Yes (the SDK does) | Retry with backoff |
| 422 | Unprocessable entity | UnprocessableEntityError |
No | Fix the request |
| 429 | "Rate limit reached for requests" | RateLimitError |
Yes | Wait at least Retry-After, then back off |
| 429 | "Slow down": type: rate_limit_error, code: slow_down ("Your request rate increased too quickly") |
RateLimitError |
Yes, slower | Back off, reduce the rate, increase gradually (9.4) |
| 429 | code: credit_balance_exhausted, organization_spend_limit_exceeded, project_spend_limit_exceeded, organization_usage_limit_exceeded (type can still be insufficient_quota) |
RateLimitError |
Never | Alert a human: add credits or raise the limit |
| 500 | "The server had an error while processing your request" | InternalServerError |
Yes | Retry after a brief wait |
| 503 | "Model temporarily overloaded": type: service_unavailable_error, code: server_is_overloaded |
InternalServerError |
Yes | Wait Retry-After if present, then retry |
| other ≥500 | Gateway errors (502, 504) | InternalServerError |
Yes | Retry |
| — | No response / timed out | APIConnectionError / APITimeoutError |
Yes | Retry (mind 6.6) |
Three quotes from the guide settle the billing case: "For billing-related errors, inspect error.code to identify the specific cause. The broader error.type can still be insufficient_quota." "Retrying billing, spend, or quota errors won't restore API access." And on overload: "If a Retry-After header is present, wait at least as long as it specifies before retrying." The rate-limits guide adds that Retry-After "may be present on 429 responses caused by a temporary rate limit and 503 responses caused by temporary model overload."
Three more exceptions that don't come from an error status:
APIResponseValidationError: the response didn't match the SDK's expected shape. You'll only see it if you construct the client with the private_strict_response_validation=True; by default the SDK builds response objects without validating them, which is why a malformed 200 can quietly produceNonefields (10.1).LengthFinishReasonError: raised by the Chat Completions parse helpers (chat.completions.parse()and the streaming equivalent) whenfinish_reasonis"length", so the JSON was cut off. Itscompletionattribute holds the partial result. (responses.parse()raises a PydanticValidationErroron truncated output instead: 03.4.)ContentFilterFinishReasonError: the same parse helpers, whenfinish_reasonis"content_filter".
Both parse-helper errors subclass OpenAIError, not APIError, so catch them explicitly around .parse() calls.
3.3 Anthropic#
Anthropic's errors page lists each status with an error type; the SDK maps statuses to classes. As of November 2026:
| HTTP | error.type |
SDK class (first-party Anthropic client) |
Retry? | What to do |
|---|---|---|---|---|
| 400 | invalid_request_error; also returned "when usage reaches an organization or workspace spend limit you set" |
BadRequestError |
No | Fix the request; "prompt is too long" means trim the input |
| 401 | authentication_error |
AuthenticationError |
No | Alert |
| 402 | billing_error ("an issue with your billing or payment information") |
plain APIStatusError (no subclass) |
No | Alert |
| 403 | permission_error |
PermissionDeniedError |
No | Check the key's workspace and permissions |
| 404 | not_found_error |
NotFoundError |
No | Fix the model ID or path |
| 409 | conflict_error ("Resolve the conflict, then retry the request") |
ConflictError |
Yes | Retry |
| 413 | request_too_large ("Request exceeds the maximum allowed number of bytes") |
RequestTooLargeError |
No | Shrink the request: the per-endpoint size limits are in 03.6, 1.7 |
| 429 | rate_limit_error: a rate limit or "its usage tier's monthly spend cap" |
RateLimitError |
Yes, unless it's the tier spend cap | Rate limit: wait retry-after. Tier spend cap: alert |
| 500 | api_error |
InternalServerError |
Yes | "Retry the request with exponential backoff" |
| 504 | timeout_error (also returned with other statuses, such as 500) |
InternalServerError |
Yes | Retry; consider streaming for long requests (6.4) |
| 529 | overloaded_error |
OverloadedError |
Yes | Retry with backoff |
| — | No response / timed out | APIConnectionError / APITimeoutError |
Yes | Retry |
Every error body has the same shape, and every response (error or not) has a request-id header:
{"type": "error", "error": {"type": "not_found_error", "message": "The requested resource could not be found."},
"request_id": "req_011CSHoEeqs5C35K2UUqR7Fy"}Cloud clients map two more statuses. The legacy AnthropicBedrock client raises ServiceUnavailableError for 503, and AnthropicVertex raises ServiceUnavailableError (503) and DeadlineExceededError (504). On the first-party client those statuses become InternalServerError, so the two classes never appear there. Neither cloud client maps 413 or 529 to their own classes. If you use several clients, catch anthropic.APIStatusError and branch on e.status_code and e.type.
3.6 Try it: provider errors from mock servers#
You can't make a real provider return a spend-cap 429 or a 529 on demand, but you can make the real SDK raise its real exception from the documented error body. Each mock below returns one fixture, copied from the shape in the provider's docs (values made up), through httpx2.MockTransport for openai/anthropic and httpx.MockTransport for google-genai (03.1, 4.5 explains why the two differ; with google-genai 3.x, httpx is no longer installed with the SDK, so uv add httpx or build the Gemini mock with httpx2):
# s3_4_mock_errors.py: provider error fixtures raised by the real SDKs through mock transports.
"""Provider errors you can't trigger on demand, raised by the REAL SDKs from mock servers.
Each fixture copies the provider's documented error shape; header and field values are made up."""
from typing import Any
import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import _interactions, errors, types
def oai_client(status: int, body: dict[str, Any], headers: dict[str, str] | None = None,
base_url: str | None = None) -> openai.OpenAI:
transport = httpx2.MockTransport(lambda req: httpx2.Response(status, json=body, headers=headers))
return openai.OpenAI(api_key="sk-test", base_url=base_url, max_retries=0, # see each error once
http_client=httpx2.Client(transport=transport))
def claude_client(status: int, body: dict[str, Any], headers: dict[str, str] | None = None) -> anthropic.Anthropic:
transport = httpx2.MockTransport(lambda req: httpx2.Response(status, json=body, headers=headers))
return anthropic.Anthropic(api_key="sk-ant-test", max_retries=0, http_client=httpx2.Client(transport=transport))
def gemini_client(status: int, body: dict[str, Any], headers: dict[str, str] | None = None) -> tuple[genai.Client, list[int]]:
calls: list[int] = []
def handler(req: httpx.Request) -> httpx.Response:
calls.append(1)
return httpx.Response(status, json=body, headers=headers)
client = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=httpx.MockTransport(handler))))
return client, calls
HI: list[Any] = [{"role": "user", "content": "Hi"}]
print("=== OpenAI ===")
RATE_LIMITED = {"error": {"message": "Your request rate increased too quickly. Reduce your request rate and "
"increase it gradually.", "type": "rate_limit_error", "param": None, "code": "slow_down"}}
try:
oai_client(429, RATE_LIMITED, {"x-request-id": "req_a1", "retry-after": "2"}
).responses.create(model="gpt-6-luna", input="Hi")
except openai.RateLimitError as e:
print(f"429 slow down : {type(e).__name__} code={e.code!r} type={e.type!r} request_id={e.request_id!r}"
f" retry-after={e.response.headers.get('retry-after')} <- retry, later")
QUOTA = {"error": {"message": "Your organization has no prepaid credits remaining.",
"type": "insufficient_quota", "param": None, "code": "credit_balance_exhausted"}}
try:
oai_client(429, QUOTA, {"x-request-id": "req_a2"}).responses.create(model="gpt-6-luna", input="Hi")
except openai.RateLimitError as e:
print(f"429 no money : {type(e).__name__} code={e.code!r} type={e.type!r} <- same class, never retry")
print("\n=== Anthropic ===")
try:
claude_client(429, {"type": "error", "error": {"type": "rate_limit_error",
"message": "This request would exceed your organization's rate limit of 2,000,000 input tokens per minute."},
"request_id": "req_011CExample429"},
{"request-id": "req_011CExample429", "retry-after": "7"}
).messages.create(model="claude-haiku-5-5", max_tokens=100, messages=HI)
except anthropic.RateLimitError as e:
print(f"429 slow down : {type(e).__name__} type={e.type!r} retry-after={e.response.headers.get('retry-after')}"
f" request_id={e.request_id!r}")
SPEND_CAP = {"type": "error", "error": {"type": "rate_limit_error",
"message": "You have reached your organization's monthly spend limit.",
"details": {"error_code": "enforced_spend_limit_reached"}}, "request_id": "req_011CExampleCap"}
try:
claude_client(429, SPEND_CAP, {"request-id": "req_011CExampleCap"} # note: no retry-after header
).messages.create(model="claude-haiku-5-5", max_tokens=100, messages=HI)
except anthropic.RateLimitError as e:
body: Any = e.body
print(f"429 spend cap : {type(e).__name__} type={e.type!r} "
f"details.error_code={body['error']['details']['error_code']!r} retry-after={e.response.headers.get('retry-after')}")
try:
claude_client(529, {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"},
"request_id": "req_011CExample529"}, {"request-id": "req_011CExample529"}
).messages.create(model="claude-haiku-5-5", max_tokens=100, messages=HI)
except anthropic.InternalServerError:
print("529 : caught as InternalServerError (this line never prints)")
except anthropic.OverloadedError as e:
print(f"529 overloaded: {type(e).__name__} status={e.status_code} type={e.type!r}"
f" is InternalServerError? {isinstance(e, anthropic.InternalServerError)}")
try:
claude_client(413, {"type": "error", "error": {"type": "request_too_large",
"message": "Request exceeds the maximum allowed number of bytes."}, "request_id": "req_011CExample413"},
{"request-id": "req_011CExample413"}).messages.create(model="claude-haiku-5-5", max_tokens=100, messages=HI)
except anthropic.RequestTooLargeError as e:
print(f"413 too big : {type(e).__name__} type={e.type!r} <- shrink the request, never retry as-is")
print("\n=== Gemini generate_content ===")
EXHAUSTED = {"error": {"code": 429, "status": "RESOURCE_EXHAUSTED",
"message": "You exceeded your current quota, please check your plan and billing details.",
"details": [
{"@type": "type.googleapis.com/google.rpc.QuotaFailure",
"violations": [{"quotaMetric": "generativelanguage.googleapis.com/generate_content_requests",
"quotaId": "GenerateRequestsPerMinutePerProjectPerModel"}]},
{"@type": "type.googleapis.com/google.rpc.RetryInfo", "retryDelay": "17s"}]}}
gem, calls = gemini_client(429, EXHAUSTED)
try:
gem.models.generate_content(model="gemini-3.8-flash", contents="Hi")
except errors.ClientError as e:
retry_info = next((d for d in e.details["error"]["details"] if d["@type"].endswith("RetryInfo")), {})
print(f"429 : {type(e).__name__} code={e.code} status={e.status!r} retryDelay={retry_info.get('retryDelay')!r}"
f" HTTP calls made={len(calls)}")
print("\n=== Gemini Interactions (a different exception family) ===")
gem_i, calls = gemini_client(402, {"error": {"code": "payment_required", "message": "Prepaid credits exhausted."}})
try:
gem_i.interactions.create(model="gemini-3.8-flash", input="Hi")
except errors.APIError:
print("never printed: Interactions errors are not genai.errors.APIError")
except _interactions.APIStatusError as e:
body = e.body
print(f"402 : {type(e).__name__} status={e.status_code} code={body['error']['code']!r} calls={len(calls)}")
gem_i, calls = gemini_client(429, {"error": {"code": "rate_limit_exceeded", "message": "Too many requests."}},
{"retry-after-ms": "20"})
try:
gem_i.interactions.create(model="gemini-3.8-flash", input="Hi")
except _interactions.RateLimitError as e:
print(f"429 : {type(e).__name__} status={e.status_code} calls={len(calls)} <- retried by default")
print("\n=== OpenRouter (openai SDK, base_url=https://openrouter.ai/api/v1) ===")
OR = "https://openrouter.ai/api/v1"
try:
oai_client(402, {"error": {"code": 402, "message": "Insufficient credits. Add more using https://openrouter.ai/credits"}},
base_url=OR).chat.completions.create(model="openai/gpt-6-luna", messages=HI)
except openai.APIStatusError as e:
print(f"402 : {type(e).__name__} (no subclass for 402) status={e.status_code} e.code={e.code!r}")
BUDGET = {"error": {"code": 403, "message": "Budget limit exceeded (weekly limit). Contact your org admin. "
"$52.00 of $50.00 used; resets 2026-11-09T00:00:00.000Z.",
"metadata": {"limit_source": "openrouter_guardrail_budget", "scope": "workspace_default_member",
"limit_usd": 50, "spend_usd": 52, "resets_at": "2026-11-09T00:00:00.000Z",
"remedy_hint": "Contact your org admin."}}}
try:
oai_client(403, BUDGET, base_url=OR).chat.completions.create(model="openai/gpt-6-luna", messages=HI)
except openai.PermissionDeniedError as e:
meta = e.body["metadata"] if isinstance(e.body, dict) else {}
print(f"403 budget : {type(e).__name__} limit_source={meta['limit_source']!r} resets_at={meta['resets_at']!r}")
MODERATION = {"error": {"code": 403, "message": "Input was flagged by moderation.",
"metadata": {"reasons": ["harassment"], "flagged_input": "you are a ...",
"provider_name": "OpenAI", "model_slug": "openai/gpt-6-luna"}}}
try:
oai_client(403, MODERATION, base_url=OR).chat.completions.create(model="openai/gpt-6-luna", messages=HI)
except openai.PermissionDeniedError as e:
meta = e.body["metadata"] if isinstance(e.body, dict) else {}
print(f"403 moderation: {type(e).__name__} reasons={meta['reasons']} provider={meta['provider_name']!r}")=== OpenAI ===
429 slow down : RateLimitError code='slow_down' type='rate_limit_error' request_id='req_a1' retry-after=2 <- retry, later
429 no money : RateLimitError code='credit_balance_exhausted' type='insufficient_quota' <- same class, never retry
=== Anthropic ===
429 slow down : RateLimitError type='rate_limit_error' retry-after=7 request_id='req_011CExample429'
429 spend cap : RateLimitError type='rate_limit_error' details.error_code='enforced_spend_limit_reached' retry-after=None
529 overloaded: OverloadedError status=529 type='overloaded_error' is InternalServerError? False
413 too big : RequestTooLargeError type='request_too_large' <- shrink the request, never retry as-is
=== Gemini generate_content ===
429 : ClientError code=429 status='RESOURCE_EXHAUSTED' retryDelay='17s' HTTP calls made=1
=== Gemini Interactions (a different exception family) ===
402 : APIStatusError status=402 code='payment_required' calls=1
429 : RateLimitError status=429 calls=4 <- retried by default
=== OpenRouter (openai SDK, base_url=https://openrouter.ai/api/v1) ===
402 : APIStatusError (no subclass for 402) status=402 e.code='402'
403 budget : PermissionDeniedError limit_source='openrouter_guardrail_budget' resets_at='2026-11-09T00:00:00.000Z'
403 moderation: PermissionDeniedError reasons=['harassment'] provider='OpenAI'The lines to study:
- The two OpenAI 429s raise the same class. Only
e.codetells "retry later" from "never retry". - The Anthropic spend cap is a
RateLimitErrorwithtype == "rate_limit_error", identical to a real rate limit until you readdetails.error_code, and it has noretry-after. - The
except anthropic.InternalServerErrorbranch didn't catch the 529. Python checked it first and moved on, becauseOverloadedErrorisn't a subclass. - Gemini made one HTTP call (
models.*doesn't retry by default, 5.2), andretryDelayis readable frome.details. - The Interactions 429 made four calls before raising: Interactions does retry by default, and here it honoured the mock's
retry-after-ms: 20. The 402 made one call: 402 isn't on its retry list. - OpenRouter's 402 is a bare
APIStatusErrorwithe.code == "402". Branch one.status_codeande.body["metadata"].
3.7 Order your except clauses from specific to general#
Python runs the first except clause that matches, so put subclasses before their parents. The ordering that works for openai (the same works for anthropic, adding OverloadedError):
"""except clauses from specific to general (mock transports raise each failure once)."""
import httpx2
import openai
def client_that(fails_with: httpx2.Response | Exception) -> openai.OpenAI:
def handler(req: httpx2.Request) -> httpx2.Response:
if isinstance(fails_with, Exception):
raise fails_with
return fails_with
return openai.OpenAI(api_key="sk-test", max_retries=0, http_client=httpx2.Client(transport=httpx2.MockTransport(handler)))
def ask(client: openai.OpenAI) -> str:
try:
return client.responses.create(model="gpt-6-luna", input="Hi").output_text
except openai.APITimeoutError: # before APIConnectionError: it's a subclass
return "timeout: retry, but it may have run"
except openai.APIConnectionError:
return "connection: retry"
except openai.RateLimitError as e: # before APIStatusError
return f"429: {'alert, out of money' if e.code == 'credit_balance_exhausted' else 'wait, then retry'}"
except openai.InternalServerError:
return "5xx: retry"
except openai.APIStatusError as e: # every other status, including OpenRouter's 402
return f"{e.status_code}: don't retry, fix or alert"
except openai.APIError: # anything else the API layer raised (last!)
return "other API error"
ERR = {"error": {"message": "x", "type": "x", "param": None, "code": None}}
print(ask(client_that(httpx2.ReadTimeout("simulated"))))
print(ask(client_that(httpx2.ConnectError("simulated"))))
print(ask(client_that(httpx2.Response(429, json={"error": {"message": "x", "type": "insufficient_quota",
"param": None, "code": "credit_balance_exhausted"}}))))
print(ask(client_that(httpx2.Response(503, json=ERR))))
print(ask(client_that(httpx2.Response(402, json={"error": {"code": 402, "message": "Insufficient credits"}}))))timeout: retry, but it may have run
connection: retry
429: alert, out of money
5xx: retry
402: don't retry, fix or alertexcept openai.APIError matches everything, including connection errors and timeouts, so it belongs last. And note what except Exception would add: your own bugs (KeyError, TypeError) disguised as provider failures. Catch the SDK's base class, not Exception, unless you re-raise. That is why reliable_call() in 13.2 catches only the provider and transport families and lets your own bugs crash loudly.
3.4 Gemini#
client.models.* (generate_content and friends) raise google.genai.errors.ClientError for any 4xx and ServerError for any 5xx, both subclasses of errors.APIError. You branch on e.code (the HTTP status, an integer) and e.status (a Google status string). As of November 2026, Gemini's troubleshooting page names only a few of these status strings itself (429 RESOURCE_EXHAUSTED, 503 UNAVAILABLE, 403 PERMISSION_DENIED), but the API follows Google's standard error model, so these are the ones you'll meet:
| HTTP | e.status |
Typical cause | Retry? |
|---|---|---|---|
| 400 | INVALID_ARGUMENT |
Malformed request, unknown field, input over the context window | No |
| 400 | FAILED_PRECONDITION |
The request can't run in the current state (for example, free tier not available in your country, or billing required) | No |
| 402 | (prepay credits exhausted) | Out of prepaid credits | No |
| 403 | PERMISSION_DENIED |
Key without access, wrong project, restricted key | No |
| 404 | NOT_FOUND |
Unknown model or resource | No |
| 408 | (not named on the page) | Listed with 429 and 5xx as a transient error. The troubleshooting page has no table row for it | Yes |
| 429 | RESOURCE_EXHAUSTED |
A rate limit or a spend-based limit ("If you hit a spend-based rate limit, the API returns a 429 RESOURCE_EXHAUSTED error", from Google's rate-limits page) |
Yes, with care |
| 500 | INTERNAL |
Server error; sometimes an input that's too long | Yes, a few times |
| 503 | UNAVAILABLE |
Overloaded | Yes |
| 504 | DEADLINE_EXCEEDED |
The request took too long server-side | Yes; a longer timeout may help |
The guidance on the troubleshooting page is short and sound: "Only retry on transient errors (like 429, 408, or 5xx). Do not retry on client errors (like 400, 402, or 403)."
A RESOURCE_EXHAUSTED body may also carry structured details in Google's standard error format, such as a google.rpc.QuotaFailure (which quota was hit) and a google.rpc.RetryInfo with a retryDelay like "17s". Gemini's own docs don't document these details (as of November 2026), but the SDK passes the whole body through in e.details, and Google's error model says of RetryInfo: "Clients should wait at least this long between retrying the same request." Treat retryDelay as a helpful hint when present, never as guaranteed. 7.3 parses it.
client.interactions.* raise a different family of exceptions, and its classes are importable only from a private module, google.genai._interactions:
| HTTP | Class (in google.genai._interactions) |
error.code strings in the body (as of November 2026) |
Retry? |
|---|---|---|---|
| 400 | BadRequestError |
invalid_request, failed_precondition, parameter_unknown |
No |
| 401 | AuthenticationError |
authentication |
No |
| 402 | APIStatusError |
payment_required ("Don't retry: the request won't succeed until credits are added.") |
No |
| 403 | PermissionDeniedError |
permission_denied |
No |
| 404 | NotFoundError |
not_found, model_not_found |
No |
| 409 | ConflictError |
already_exists, aborted |
Depends (aborted yes) |
| 416 | APIStatusError |
out_of_range |
No |
| 422 | UnprocessableEntityError |
— | No |
| 429 | RateLimitError |
rate_limit_exceeded (per-minute or per-second), quota_exceeded (the daily quota), too_many_requests |
rate_limit_exceeded and too_many_requests yes; quota_exceeded no (it won't clear until the quota resets) |
| 499 | APIStatusError |
cancelled |
No |
| 5xx | InternalServerError |
api_error (500), unimplemented (501), service_unavailable (503), deadline_exceeded (504) |
Yes, except unimplemented. For deadline_exceeded, only after you raise or remove your own client deadline: Google's advice is "Remove or increase client deadline setting to use the server default" |
| — | APIConnectionError, APITimeoutError |
— | Yes |
The body shape is {"error": {"code": "<snake_case>", "message": "..."}}, and Google's errors page adds that "any error code not listed above falls back to the snake_case version of the HTTP status". In a stream, errors arrive as an event with event_type: "error" (03.3, 7.2). Google's page lists two more groups of codes with no HTTP status: generation blocked codes (content_blocked, safety, recitation, language, prohibited_content, spii, blocklist, image_safety, image_prohibited_content, image_recitation, image_other: "modify your input and retry") and generation error codes about the model's output (malformed_tool_call, malformed_function_call, unexpected_tool_call, too_many_tool_calls, no_image, missing_thought_signature). They aren't HTTP errors, so 10.1 treats them as outcomes of a 200. The Interactions exceptions have status_code, message, body, response and request, but no request_id.
# gemini_errors.py: one place that knows where Gemini's exception classes live
from google.genai import errors
try: # private module as of google-genai 2.34.0: no public import path exists yet
from google.genai import _interactions
GEMINI_ERRORS: tuple[type[BaseException], ...] = (errors.APIError, _interactions.APIError)
except ImportError: # moved in a newer SDK: fall back to the public family and fix the import
GEMINI_ERRORS = (errors.APIError,)
# usage: except GEMINI_ERRORS as e: status = getattr(e, "status_code", None) or getattr(e, "code", None)llm_errors.py in 4.4 uses exactly this pattern, and exports the result as GEMINI_ERRORS (plus PROVIDER_ERRORS, all four SDK families together, which 13.2 catches).
3.5 OpenRouter#
OpenRouter is a gateway in front of many providers, so its errors combine its own (credits, budgets, moderation) with errors passed through from the provider. Every error has one shape, with the HTTP status repeated as code:
{"error": {"code": 403, "message": "Budget limit exceeded (weekly limit). ...", "metadata": {"limit_source": "openrouter_guardrail_budget"}}}| HTTP | Meaning (OpenRouter docs, as of November 2026) | openai SDK class |
Retry? |
|---|---|---|---|
| 400 | "Bad Request (invalid or missing params, CORS)" | BadRequestError |
No |
| 401 | "Invalid credentials (OAuth session expired, disabled/invalid API key)" | AuthenticationError |
No |
| 402 | "Your account or API key has insufficient credits" (also any request, even to a free model, while the balance is negative) | plain APIStatusError |
No, except the in-flight budget case below |
| 403 | "Forbidden (insufficient permissions, guardrail block, or moderation flag)" | PermissionDeniedError |
No |
| 408 | "Your request timed out" | APIStatusError |
Yes |
| 429 | "You are being rate limited" | RateLimitError |
Yes |
| 502 | "Your chosen model is down or we received an invalid response from it" | InternalServerError |
Yes |
| 503 | "There is no available model provider that meets your routing requirements" | InternalServerError |
Yes, but check your provider routing settings if it persists |
The metadata object is where the useful detail is:
- Moderation 403s carry
reasons(a list),flagged_input(at most 100 characters, "truncated in the middle"),provider_nameandmodel_slug. - Budget 403s carry
limit_source(openrouter_guardrail_budget,openrouter_workspace_budgetoropenrouter_key_limit),scope,limit_usd,spend_usd,resets_at(nullfor a lifetime budget) andremedy_hint. The docs advise you to "branch onlimit_source, not on this text", and note "there is noRetry-Afterheader because the wait is usually hours or days". - 402s from the in-flight budget (a cap on how much spending can be in progress at once) carry
limit_source: "openrouter_in_flight_budget"andreason: "in_flight_budget_exhausted". This one is transient: "The response includes aRetry-Afterheader; wait for it and retry." A 402 withreason: "weight_exceeds_budget"(limit_source: "openrouter_credits") means "retrying will not help". - Typed errors: on Chat Completions,
metadata.error_typenames the problem precisely (on OpenRouter's Responses API it is a top-levelerror_type; on its Messages endpoint,error.error_type):
error_type (as of November 2026) |
HTTP |
|---|---|
context_length_exceeded, max_tokens_exceeded, token_limit_exceeded, string_too_long, invalid_request, invalid_prompt, invalid_image, image_too_large, image_too_small, unsupported_image_format, image_download_failed |
400 |
authentication |
401 |
payment_required |
402 |
permission_denied, content_policy_violation, refusal |
403 |
not_found, image_not_found |
404 |
precondition_failed |
412 |
payload_too_large |
413 |
unprocessable |
422 |
rate_limit_exceeded |
429 |
server, unmapped |
500 |
provider_unavailable |
502 |
provider_overloaded |
503 |
timeout |
504 |
On the Retry-After header, the docs say OpenRouter "may include" it "on 429 and 503 responses, and on 402 responses whose error.metadata.limit_source is openrouter_in_flight_budget", and add that the official SDKs never retry a 402 on their own.
Part 4: What to retry, and what never to retry#
4.1 The decision table#
A retry sends the same request again, hoping the failure was temporary. That only makes sense when the failure was about timing (the server was busy, the network blinked, you were going too fast), never when it was about the request itself (wrong, too big, not allowed) or your account (no money, no access). One table for all four providers:
| Failure | Statuses / codes | Retry? | Reaction |
|---|---|---|---|
| Connection failed, connection reset | APIConnectionError, httpx.TransportError |
Yes | Backoff, within a total deadline |
| Client timeout | APITimeoutError, httpx.TimeoutException |
Yes, carefully | The request may have completed and billed (6.6); maybe raise the timeout or stream instead |
| Request timeout | 408; Anthropic 504 timeout_error; Gemini 504 DEADLINE_EXCEEDED |
Yes | Backoff |
| Conflict | 409 (Interactions aborted) |
Yes | Backoff |
| Rate limited | 429 slow_down, rate_limit_error, RESOURCE_EXHAUSTED, rate_limit_exceeded; OpenRouter 402 in_flight_budget_exhausted |
Yes | Wait at least Retry-After; otherwise backoff with jitter; slow your whole client down (9.5) |
| Overloaded | 503 (server_is_overloaded, UNAVAILABLE, provider_overloaded), Anthropic 529 |
Yes | Backoff; after a few attempts, consider a fallback model (13.5) |
| Server error | 500, 502, 504 | Yes, a few times | Backoff; if it persists for one input, that input may be the trigger |
| Quota, spend cap, credits, billing | OpenAI 429 credit_balance_exhausted and the *_limit_exceeded codes; Anthropic 429 enforced_spend_limit_reached, 402 billing_error, 400 self-set spend limit; Gemini 402, Interactions quota_exceeded, payment_required; OpenRouter 402 credits, 403 budgets |
Never | Fail fast and alert a human. Nothing changes until someone pays or raises a limit |
| Authentication | 401 | Never | Alert: wrong, missing or revoked key |
| Permission, moderation | 403 | Never | Log the reason; tell the user the request can't be processed |
| Not found | 404 | Never | A bug: wrong model ID or path |
| Malformed request | 400, 422 | Never | A bug in your request: log it with the request ID and fix the code |
| Context too long | 400 with a context message; OpenRouter context_length_exceeded |
Not as-is | Trim the history or the input, then send a new request (02.7 Part 4) |
| Request too large | 413 | Not as-is | Shrink the payload (fewer or smaller images, a file upload instead of inline bytes, 03.6) |
| Server says don't | x-should-retry: false |
Never | Obey (4.3) |
4.2 A 429 can mean "slow down" or "out of money"#
HTTP defines 429 as "Too Many Requests" (RFC 6585, section 4). LLM providers reuse it for running out of money as well, so three of the four providers send a 429 that retrying can never fix, and the fourth, OpenRouter, uses 402 and 403 for the same situations:
| Provider | "Slow down" 429 | "Out of money" (same status!) | How to tell them apart in code |
|---|---|---|---|
| OpenAI | code: slow_down, or a rate-limit message |
code: credit_balance_exhausted, organization_spend_limit_exceeded, project_spend_limit_exceeded, organization_usage_limit_exceeded |
e.code in BILLING_CODES (the type may still say insufficient_quota) |
| Anthropic | error.type: rate_limit_error, usually with retry-after |
The same rate_limit_error, plus error.details.error_code: "enforced_spend_limit_reached" (the tier spend cap), and no retry-after |
e.body["error"].get("details", {}).get("error_code") |
| Provider | "Slow down" 429 | "Out of money" (same status!) | How to tell them apart in code |
|---|---|---|---|
Gemini models.* |
RESOURCE_EXHAUSTED |
Also RESOURCE_EXHAUSTED (spend-based limits) |
Not reliably distinguishable: cap retries and alert if it persists |
| Gemini Interactions | rate_limit_exceeded, too_many_requests |
quota_exceeded (daily quota) |
e.body["error"]["code"] |
| OpenRouter | 429 rate_limit_exceeded |
Uses 402 for credits and 403 for budgets instead | Branch on the status and metadata.limit_source |
4.3 x-should-retry: the server decides#
OpenAI and Anthropic can send a non-standard response header, x-should-retry: true or x-should-retry: false, and both SDKs obey it before looking at the status code (from _should_retry in each SDK's _base_client.py):
x-should-retry: falseon a 503 means "don't retry this one", even though 503 is normally retryable.x-should-retry: trueon a 400 means "retry", even though 400 normally isn't.
Neither provider documents when it sends the header, so treat it as authoritative when present, and let your own retry layer obey it too (the classifier below does). One SDK detail: in openai, a Retry-After longer than 120 seconds stops retries even before x-should-retry is read (5.1).
4.4 A classifier for all four providers#
Here is the decision table as code. classify() takes any exception from any of the four SDKs and returns one Failure: what kind of problem it is, whether to retry, the provider's code, the request ID and the server's requested wait. The tenacity policy (Part 8) and the production call (Part 13) are built on it. The same module exports the exception families the production call is allowed to catch (PROVIDER_ERRORS), and treats raw httpx and httpx2 transport errors and a plain TimeoutError like the SDKs' own connection and timeout errors.
"""llm_errors.py: turn any exception from the four providers into one decision:
what went wrong, may we retry, and how long the server asked us to wait."""
from dataclasses import dataclass
from enum import Enum
from typing import Any
import anthropic
import httpx
import openai
from google.genai import errors as genai_errors
try: # openai and anthropic use httpx2 (Pydantic's fork); a raw httpx2 error can escape in rare paths
import httpx2
HTTPX2_TIMEOUTS: tuple[type[BaseException], ...] = (httpx2.TimeoutException,)
HTTPX2_TRANSPORT: tuple[type[BaseException], ...] = (httpx2.TransportError,)
HTTPX2_ERRORS: tuple[type[BaseException], ...] = (httpx2.HTTPError,)
except ImportError: # pragma: no cover
HTTPX2_TIMEOUTS = HTTPX2_TRANSPORT = HTTPX2_ERRORS = ()
from retry_after import parse_google_retry_delay, parse_retry_after
try: # Interactions errors live in a private module (lesson 3.3); don't let an SDK refactor break us
from google.genai import _interactions as _gi
INTERACTIONS_ERRORS: tuple[type[BaseException], ...] = (_gi.APIError,)
except ImportError: # pragma: no cover
INTERACTIONS_ERRORS = ()
# Every exception family a provider call can raise (Part 3). Anything else, a TypeError or a KeyError, is a bug in OUR
# code and must not be dressed up as a provider failure (3.7): production_call.py catches only these.
GEMINI_ERRORS: tuple[type[BaseException], ...] = (genai_errors.APIError, *INTERACTIONS_ERRORS)
PROVIDER_ERRORS: tuple[type[BaseException], ...] = (
openai.APIError, anthropic.APIError, *GEMINI_ERRORS, httpx.HTTPError, *HTTPX2_ERRORS, TimeoutError)
class Kind(str, Enum):
RATE_LIMITED = "rate_limited" # slow down, then retry
OVERLOADED = "overloaded" # provider busy (503, 529): retry with backoff
SERVER_ERROR = "server_error" # 500, 502, 504: retry a few times
TIMEOUT = "timeout" # we gave up waiting: retry, but it may have run (and billed)
CONNECTION = "connection" # DNS, TLS, refused, reset: retry
CONFLICT = "conflict" # 409: retry
QUOTA = "quota" # out of credits, spend cap, daily quota: alert a human
AUTH = "auth" # 401: wrong or revoked key: alert
PERMISSION = "permission" # 403: no access, moderation, budget: don't retry
CONTEXT_TOO_LONG = "context_too_long" # trim the input, then try again
TOO_LARGE = "too_large" # 413: request bytes over the limit
BAD_REQUEST = "bad_request" # 400, 404, 422: a bug in our request
UNKNOWN = "unknown"
RETRYABLE = {Kind.RATE_LIMITED, Kind.OVERLOADED, Kind.SERVER_ERROR, Kind.TIMEOUT, Kind.CONNECTION, Kind.CONFLICT}
OPENAI_BILLING_CODES = {"insufficient_quota", "credit_balance_exhausted", "organization_spend_limit_exceeded",
"project_spend_limit_exceeded", "organization_usage_limit_exceeded"}
INTERACTIONS_QUOTA_CODES = {"payment_required", "quota_exceeded"}
OPENROUTER_BUDGET_SOURCES = {"openrouter_guardrail_budget", "openrouter_workspace_budget", "openrouter_key_limit"}
# The 400 for a spend limit you set yourself starts "You have reached your specified API usage limits" (or "...specified
# workspace API usage limits"): there is no error code to match, so the message is the only signal (Anthropic rate-limits page)
SELF_SET_LIMIT_HINT = "api usage limits"
CONTEXT_HINTS = ("context_length_exceeded", "context window", "prompt is too long", "too many tokens",
"input token count", "maximum context length") # the last one is OpenRouter's wording
@dataclass
class Failure:
kind: Kind
retryable: bool
status: int | None
code: str | None # the provider's own code/type string
message: str
request_id: str | None
retry_after: float | None # seconds the server asked us to wait, if it said
def classify(exc: BaseException) -> Failure:
status, code, body, headers, request_id = _extract(exc)
message = str(getattr(exc, "message", None) or exc)[:300]
text = f"{code} {message}".lower()
# 1. No HTTP response at all
if isinstance(exc, (openai.APITimeoutError, anthropic.APITimeoutError, httpx.TimeoutException,
*HTTPX2_TIMEOUTS, TimeoutError)) or type(exc).__name__ == "APITimeoutError":
kind = Kind.TIMEOUT
elif isinstance(exc, (openai.APIConnectionError, anthropic.APIConnectionError, httpx.TransportError,
*HTTPX2_TRANSPORT)) or type(exc).__name__ == "APIConnectionError":
kind = Kind.CONNECTION
elif code == "in_flight_budget_exhausted": # OpenRouter 402 that clears by itself
kind = Kind.RATE_LIMITED
# 2. Money, not speed: these arrive as 429 (or 402/403) and never get better by retrying
elif status == 402 or code in OPENAI_BILLING_CODES or code in INTERACTIONS_QUOTA_CODES \
or code in OPENROUTER_BUDGET_SOURCES or code in ("enforced_spend_limit_reached", "billing_error") \
or (status == 400 and SELF_SET_LIMIT_HINT in text): # Anthropic: a spend limit you set yourself is a 400
kind = Kind.QUOTA
elif status == 429:
kind = Kind.RATE_LIMITED
elif status == 413:
kind = Kind.TOO_LARGE
elif status in (400, 422) and any(h in text for h in CONTEXT_HINTS):
kind = Kind.CONTEXT_TOO_LONG
elif status in (400, 404, 422):
kind = Kind.BAD_REQUEST
elif status == 401:
kind = Kind.AUTH
elif status == 403:
kind = Kind.PERMISSION
elif status in (408, 504) or code in ("timeout_error", "deadline_exceeded", "timeout"):
kind = Kind.TIMEOUT
elif status == 409:
kind = Kind.CONFLICT
elif status in (503, 529) or code in ("overloaded_error", "server_is_overloaded", "provider_overloaded"):
kind = Kind.OVERLOADED
elif status is not None and status >= 500:
kind = Kind.SERVER_ERROR
else:
kind = Kind.UNKNOWN
retryable = kind in RETRYABLE
should_retry = headers.get("x-should-retry") # the server's explicit verdict wins
if should_retry in ("true", "false"):
retryable = should_retry == "true"
wait = parse_retry_after(headers) if headers else None
if wait is None:
wait = parse_google_retry_delay(body)
return Failure(kind, retryable, status, code, message, request_id, wait)
def _extract(exc: BaseException) -> tuple[int | None, str | None, Any, dict[str, str], str | None]:
"""(status, code, body, headers, request_id) from whichever SDK raised."""
response = getattr(exc, "response", None)
headers = {k.lower(): v for k, v in response.headers.items()} if response is not None else {}
request_id = headers.get("x-request-id") or headers.get("request-id") or headers.get("x-generation-id")
if isinstance(exc, genai_errors.APIError): # Gemini generate_content
return exc.code, exc.status, exc.details, headers, request_id
body: Any = getattr(exc, "body", None)
status = getattr(exc, "status_code", None)
code: str | None = None
if isinstance(exc, openai.APIError) and isinstance(body, dict): # OpenAI and OpenRouter
meta = body.get("metadata") or {}
code = (meta.get("error_type") or meta.get("reason") or meta.get("limit_source")
or (body.get("code") if isinstance(body.get("code"), str) else None) or body.get("type"))
elif isinstance(exc, anthropic.APIStatusError) and isinstance(body, dict):
err = body.get("error") or {}
code = (err.get("details") or {}).get("error_code") or err.get("type")
elif INTERACTIONS_ERRORS and isinstance(exc, INTERACTIONS_ERRORS) and isinstance(body, dict):
code = (body.get("error") or {}).get("code")
return status, code, body, headers, request_idIt imports parse_retry_after and parse_google_retry_delay from retry_after.py, built and tested in 7.3. Now run it against real SDK exceptions raised from documented error bodies:
"""Run llm_errors.classify() over real SDK exceptions raised from documented error shapes (mock servers)."""
from typing import Any
import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import types
from llm_errors import classify
HI: Any = [{"role": "user", "content": "Hi"}]
def raised(fn) -> BaseException:
try:
fn()
except Exception as e: # noqa: BLE001 - the demo wants whatever the SDK raises
return e
raise AssertionError("expected an exception")
def oai(status: int, error: dict[str, Any], headers: dict[str, str] | None = None, openrouter: bool = False):
http = httpx2.Client(transport=httpx2.MockTransport(
lambda r: httpx2.Response(status, json={"error": error}, headers=headers)))
c = openai.OpenAI(api_key="sk-test", max_retries=0, http_client=http,
base_url="https://openrouter.ai/api/v1" if openrouter else None)
if openrouter:
return lambda: c.chat.completions.create(model="openai/gpt-6-luna", messages=HI)
return lambda: c.responses.create(model="gpt-6-luna", input="Hi")
def ant(status: int, error: dict[str, Any], headers: dict[str, str] | None = None):
http = httpx2.Client(transport=httpx2.MockTransport(lambda r: httpx2.Response(
status, json={"type": "error", "error": error, "request_id": "req_011CDemo"},
headers={"request-id": "req_011CDemo", **(headers or {})})))
c = anthropic.Anthropic(api_key="sk-ant-test", max_retries=0, http_client=http)
return lambda: c.messages.create(model="claude-haiku-5-5", max_tokens=100, messages=HI)
def gem(status: int, body: dict[str, Any], interactions: bool = False):
c = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(httpx_client=httpx.Client(
transport=httpx.MockTransport(lambda r: httpx.Response(status, json=body)))))
if interactions:
return lambda: c.interactions.create(model="gemini-3.8-flash", input="Hi")
return lambda: c.models.generate_content(model="gemini-3.8-flash", contents="Hi")
def refused() -> None:
openai.OpenAI(base_url="http://127.0.0.1:9/v1", api_key="x", max_retries=0).responses.create(
model="gpt-6-luna", input="Hi")
CASES = [
("OpenAI 429 slow_down", oai(429, {"message": "Your request rate increased too quickly.", "type": "rate_limit_error",
"code": "slow_down"}, {"retry-after": "3"})),
("OpenAI 429 credit_balance_exhausted", oai(429, {"message": "No prepaid credits remaining.",
"type": "insufficient_quota", "code": "credit_balance_exhausted"})),
("OpenAI 503 server_is_overloaded", oai(503, {"message": "The requested model is temporarily overloaded.",
"type": "service_unavailable_error", "code": "server_is_overloaded"})),
# OpenAI's error-codes page lists no code for "input too long", so match the message (this wording is reported
# from real calls, not documented) and, if a code is present, context_length_exceeded:
("OpenAI 400, context (message only)", oai(400, {"message": "Your input exceeds the context window of this model.",
"type": "invalid_request_error", "code": None})),
("OpenAI 400, context (code present)", oai(400, {"message": "Too long.", "type": "invalid_request_error",
"code": "context_length_exceeded"})),
("OpenAI 401", oai(401, {"message": "Incorrect API key provided.", "type": "invalid_request_error", "code": None})),
("OpenAI 503 + x-should-retry: false", oai(503, {"message": "Overloaded."}, {"x-should-retry": "false"})),
("Anthropic 429 rate_limit_error", ant(429, {"type": "rate_limit_error", "message": "Rate limited."},
{"retry-after": "12"})),
("Anthropic 429 spend cap", ant(429, {"type": "rate_limit_error", "message": "Monthly spend cap reached.",
"details": {"error_code": "enforced_spend_limit_reached"}})),
("Anthropic 400 self-set spend limit", ant(400, {"type": "invalid_request_error",
"message": "You have reached your specified API usage limits. "
"You will regain access on 2026-12-01 at 00:00 UTC."})),
("Anthropic 529 overloaded_error", ant(529, {"type": "overloaded_error", "message": "Overloaded"})),
("Anthropic 413 request_too_large", ant(413, {"type": "request_too_large",
"message": "Request exceeds the maximum allowed number of bytes."})),
("Anthropic 400 prompt is too long", ant(400, {"type": "invalid_request_error",
"message": "prompt is too long: 1000012 tokens > 1000000 maximum"})),
("Anthropic 402 billing_error", ant(402, {"type": "billing_error", "message": "Billing issue."})),
("Gemini 429 RESOURCE_EXHAUSTED", gem(429, {"error": {"code": 429, "status": "RESOURCE_EXHAUSTED",
"message": "Resource has been exhausted.",
"details": [{"@type": "type.googleapis.com/google.rpc.RetryInfo", "retryDelay": "17s"}]}})),
("Gemini 503 UNAVAILABLE", gem(503, {"error": {"code": 503, "status": "UNAVAILABLE",
"message": "The model is overloaded."}})),
("Gemini Interactions 402 payment_required", gem(402, {"error": {"code": "payment_required",
"message": "Out of credits."}}, True)),
("OpenRouter 402 credits", oai(402, {"code": 402, "message": "Insufficient credits."}, openrouter=True)),
("OpenRouter 402 in-flight budget", oai(402, {"code": 402, "message": "In-flight budget exhausted.",
"metadata": {"reason": "in_flight_budget_exhausted", "limit_source": "openrouter_in_flight_budget"}},
{"retry-after": "2"}, openrouter=True)),
("OpenRouter 403 budget", oai(403, {"code": 403, "message": "Budget limit exceeded (weekly limit).",
"metadata": {"limit_source": "openrouter_guardrail_budget"}}, openrouter=True)),
("OpenRouter 400 maximum context length", oai(400, {"code": 400, "message":
"This endpoint's maximum context length is 128000 tokens. However, you requested about 131500 tokens."},
openrouter=True)),
("OpenRouter 400 context_length_exceeded", oai(400, {"code": 400, "message": "Too many tokens.",
"metadata": {"error_type": "context_length_exceeded"}}, openrouter=True)),
("Connection refused (any SDK)", refused),
]
print(f"{'case':<42} {'exception':<22} {'kind':<17} retry wait")
for label, fn in CASES:
e = raised(fn)
f = classify(e)
print(f"{label:<42} {type(e).__name__:<22} {f.kind.value:<17} {str(f.retryable):<6} {f.retry_after}")case exception kind retry wait
OpenAI 429 slow_down RateLimitError rate_limited True 3.0
OpenAI 429 credit_balance_exhausted RateLimitError quota False None
OpenAI 503 server_is_overloaded InternalServerError overloaded True None
OpenAI 400, context (message only) BadRequestError context_too_long False None
OpenAI 400, context (code present) BadRequestError context_too_long False None
OpenAI 401 AuthenticationError auth False None
OpenAI 503 + x-should-retry: false InternalServerError overloaded False None
Anthropic 429 rate_limit_error RateLimitError rate_limited True 12.0
Anthropic 429 spend cap RateLimitError quota False None
Anthropic 400 self-set spend limit BadRequestError quota False None
Anthropic 529 overloaded_error OverloadedError overloaded True None
Anthropic 413 request_too_large RequestTooLargeError too_large False None
Anthropic 400 prompt is too long BadRequestError context_too_long False None
Anthropic 402 billing_error APIStatusError quota False None
Gemini 429 RESOURCE_EXHAUSTED ClientError rate_limited True 17.0
Gemini 503 UNAVAILABLE ServerError overloaded True None
Gemini Interactions 402 payment_required APIStatusError quota False None
OpenRouter 402 credits APIStatusError quota False None
OpenRouter 402 in-flight budget APIStatusError rate_limited True 2.0
OpenRouter 403 budget PermissionDeniedError quota False None
OpenRouter 400 maximum context length BadRequestError context_too_long False None
OpenRouter 400 context_length_exceeded BadRequestError context_too_long False None
Connection refused (any SDK) APIConnectionError connection True NoneDesign choices worth copying:
- Money is checked before speed. The quota rule runs before the generic
status == 429rule, so a billing 429 can never be classified as a rate limit. - The server's
x-should-retryoverrides the table, as the SDKs do. - A spend limit you set yourself on Anthropic is matched by its message. It arrives as a 400
invalid_request_errorwith no error code, and the message starts "You have reached your specified API usage limits" (or "...specified workspace API usage limits"), soSELF_SET_LIMIT_HINTlooks forapi usage limitsin the text. Without that rule the call would be classifiedbad_request("a bug in our request"): still not retried, but nobody would be alerted that the budget is spent. - Context-length detection is by message as well as code. Anthropic has no dedicated code for "input too long" (the hint is its message, "prompt is too long"). OpenAI's error-codes page lists no code for it either, so the classifier matches the message and, when one is present,
context_length_exceeded(widely reported from real calls, but not documented, so the first fixture in the output hascode: Noneand the second a code). OpenRouter's typederror_typeiscontext_length_exceeded, and its plain 400 message reads "This endpoint's maximum context length is ...", which is why"maximum context length"is inCONTEXT_HINTS. Message matching is fragile, so log any 400 the classifier can't place, and adjust the tuple. - The private Interactions import is guarded, as recommended in 3.4.
4.5 Never retry without a cap: a bug that burns money#
The most expensive retry bug is the simplest one:
while True: # DON'T: no cap, no backoff, no deadline, and it swallows everything
try:
return call_llm(prompt)
except Exception:
continueIt looks harmless because "it eventually succeeds". Now give it a request that can't succeed: a long prompt and a long answer that take the provider 40 seconds, with a 30-second client timeout. Each attempt times out and is retried instantly. And because the provider may keep working on abandoned non-streaming requests (it's undocumented for OpenAI and Anthropic, 6.6), each one may also be billed.
The sample runs the loop against a mock server that raises the SDK's real timeout error at once, so nothing waits. The for ... in range(200) is there only so the demo ends; the loop's logic has no cap at all. It runs the loop three times: around a request that always times out, around a bug in our own code, and the same stuck request through reliable_call() from 13.2:
"""The bug, run for real against a MOCK server: an uncapped retry loop around a request that can never
finish inside the client's timeout, and around a bug in our own code. The mock raises the SDK's real
timeout error at once (no waiting); we count attempts, tally the exception classes, and add up an
ASSUMED bill (if the provider finishes abandoned non-streaming requests, which is undocumented, 6.6)."""
from collections import Counter
from typing import Any
import httpx2
import openai
from production_call import RetryPolicy, reliable_call
CLIENT_TIMEOUT_S = 30
COST_PER_ATTEMPT = 0.12 # dollars for a long prompt plus a long answer (made up, but plausible)
SAFETY_STOP = 200 # ONLY so this demo ends: the buggy loop itself has no cap
server_started = 0
def too_slow(request: httpx2.Request) -> httpx2.Response:
global server_started
server_started += 1 # the "server" starts (and may finish) the work every time
raise httpx2.ReadTimeout("the server needs 40 s, the client waits 30 s")
client = openai.OpenAI(api_key="sk-test", max_retries=0, timeout=CLIENT_TIMEOUT_S,
http_client=httpx2.Client(transport=httpx2.MockTransport(too_slow)))
def buggy_call(**extra: Any) -> None:
"""while True: try: call() except Exception: continue <- no cap, no backoff, no deadline."""
seen: Counter[str] = Counter()
for _ in range(SAFETY_STOP): # stands in for `while True`
try:
client.responses.create(model="gpt-6-luna", input="Summarize this 300-page report...", **extra)
return
except Exception as exc: # noqa: BLE001 - the bug under demonstration
seen[type(exc).__name__] += 1
print(f" {sum(seen.values())} attempts, 0 answers, exceptions swallowed: {dict(seen)}")
print("1. A request that always times out")
buggy_call()
hours = SAFETY_STOP * CLIENT_TIMEOUT_S / 3600
print(f" at {CLIENT_TIMEOUT_S} s per real attempt that is {hours:.1f} hours of retrying and, if abandoned requests are "
f"billed, ${server_started * COST_PER_ATTEMPT:.2f} for ONE stuck job")
print("2. A bug in our own code (a misspelt keyword) is 'retried' like a network error")
server_started = 0
buggy_call(max_output_token=300) # type: ignore[call-arg]
print("3. The same stuck request through reliable_call() (13.2): 4 attempts, then a clear failure")
server_started = 0
result = reliable_call(lambda timeout, crid: client.responses.create(model="gpt-6-luna", input="...", timeout=timeout),
policy=RetryPolicy(max_attempts=4), sleep=lambda s: None, on_event=lambda e: None)
print(f" attempts={result.attempts} ok={result.ok} failure={result.failure.kind.value if result.failure else None}"
f" server started the work {server_started} times: at most ${server_started * COST_PER_ATTEMPT:.2f}")1. A request that always times out
200 attempts, 0 answers, exceptions swallowed: {'APITimeoutError': 200}
at 30 s per real attempt that is 1.7 hours of retrying and, if abandoned requests are billed, $24.00 for ONE stuck job
2. A bug in our own code (a misspelt keyword) is 'retried' like a network error
200 attempts, 0 answers, exceptions swallowed: {'TypeError': 200}
3. The same stuck request through reliable_call() (13.2): 4 attempts, then a clear failure
attempts=4 ok=False failure=timeout server started the work 4 times: at most $0.48The attempt counts and exception classes are real; the dollar figures assume $0.12 per abandoned request and that the provider bills it, so treat them as an illustration of the shape: an uncapped loop turns one stuck job into a bill that grows linearly with time, while producing nothing. Case 2 shows the other danger of except Exception: continue: a TypeError from a misspelt keyword is "retried" 200 times like a network error, hiding a bug that should have crashed on the first call. The same loop also hammers a provider that's already overloaded and retries 401s forever. Every retry loop needs a maximum number of attempts, a total deadline, backoff between attempts, and a retry predicate. Part 8 gives you all four in a few lines, and case 3 shows the end result: four attempts, then a clear timeout failure the caller can act on.
Part 5: The SDKs' built-in retries#
Deep-dive
Every official SDK can retry for you, but they differ in what they retry, how long they wait, and whether they're on at all. Everything in this part was read from the SDK source (the versions named in Setup) and confirmed by the mock runs in 5.3; where the docs say something different, the SDK behaviour is what you'll get.
5.1 openai and anthropic: exactly what the SDKs do#
The two SDKs share their retry engine (both are generated by Stainless), with one important difference:
openai 3.42.1 |
anthropic 2.4.0 |
|
|---|---|---|
| Default retries | max_retries=2, so up to 3 attempts |
The same |
| Retried | Connection errors and timeouts; 408, 409, 429, every status ≥ 500 | The same (529 included, as it's ≥ 500) |
| Server override | x-should-retry: true / false wins over the status rules |
The same |
| Backoff before retry n (n = 0, 1, 2...) | min(0.5 × 2ⁿ, 8) seconds, multiplied by a random factor between 0.75 and 1 |
The same |
| Server-requested wait | retry-after-ms, then retry-after (seconds, fractional allowed), then retry-after as an HTTP date |
The same |
| A wait longer than 120 s | Doesn't retry at all: it raises immediately (MAX_RETRY_AFTER_DELAY = 2 * 60) |
Waits, however long (capped only by a platform limit of about 49 days) |
| A wait of 0 or less, or unparsable | Falls back to backoff | The same |
| Headers sent | x-stainless-retry-count: 0, 1, 2... on each attempt, plus x-stainless-read-timeout |
The same, plus x-stainless-timeout |
| Logging | INFO on the openai._base_client logger: "Retrying request in 0.460000 seconds (retry 1 of 2)" |
INFO on anthropic._base_client: "Retrying request to /v1/messages in 0.460000 seconds" |
| Streams | The request that opens the stream is retried; nothing after the first event is (03.3, 7.4). Not retried by these SDKs: your code decides. The one SDK that resumes anything mid-stream is google-genai (5.2) |
The same |
| Extras | — | A 401 is retried once when the client uses a refreshing token source (credentials=), after refreshing the token. Middleware can raise anthropic.RetryableError to opt a failure into the retry policy |
So the default delays are about 0.4–0.5 s, then 0.75–1 s (two retries), and with more retries 1.5–2 s, 3–4 s, then 6–8 s for every later one. The "jitter" only ever shortens the delay, by up to 25%.
The docs agree on the basics. Anthropic's errors page: the SDKs retry "twice by default, honoring the retry-after header when present". OpenAI's rate-limits guide: "Each official OpenAI SDK automatically retries eligible 429 and 503 responses." OpenAI's error-codes guide does document the behaviour without the number ("The Python library can stop automatic retries when a server delay exceeds its supported limit"), and its rate-limits guide says to defer the request in that case; the 120-second figure itself is only in the openai source, and Anthropic documents neither.
5.3 Try it: watch the SDKs retry#
The mock servers below always fail. We count attempts, read the x-stainless-retry-count header each attempt carries, and record the delays each SDK chooses. time.sleep is swapped for a recorder, so a 121-second wait costs nothing, and the jitter is seeded so the run is repeatable:
# s5_2_sdk_retries.py: watch each SDK's built-in retries against mock servers (5.3).
"""Watch each SDK's built-in retries against mock servers: attempts, headers and delays.
time.sleep is replaced by a recorder, so the demo shows the delays the SDK chose without waiting."""
import random
import time
from typing import Any
import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import _interactions, errors, types
slept: list[float] = []
time.sleep = lambda s: slept.append(round(s, 3)) # record instead of waiting (demo only!)
random.seed(7) # make the jitter repeatable
OVERLOADED_OAI = {"error": {"message": "The requested model is temporarily overloaded.",
"type": "service_unavailable_error", "param": None, "code": "server_is_overloaded"}}
OVERLOADED_ANT = {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
def scripted(status: int, body: dict[str, Any], headers: dict[str, str] | None = None):
"""A mock server that always fails the same way, and records each attempt's retry-count header."""
seen: list[str | None] = []
def handler(req: httpx2.Request) -> httpx2.Response:
seen.append(req.headers.get("x-stainless-retry-count"))
return httpx2.Response(status, json=body, headers=headers)
return httpx2.Client(transport=httpx2.MockTransport(handler)), seen
def run_openai(label: str, status: int, headers: dict[str, str] | None = None, **client_kw: Any) -> None:
slept.clear()
http, seen = scripted(status, OVERLOADED_OAI, headers)
client = openai.OpenAI(api_key="sk-test", http_client=http, **client_kw)
try:
client.responses.create(model="gpt-6-luna", input="Hi")
except openai.APIStatusError as e:
print(f"openai {label:<34} attempts={len(seen)} retry-count={seen} sleeps={slept} -> {type(e).__name__}")
def run_anthropic(label: str, status: int, headers: dict[str, str] | None = None, **client_kw: Any) -> None:
slept.clear()
http, seen = scripted(status, OVERLOADED_ANT, headers)
client = anthropic.Anthropic(api_key="sk-ant-test", http_client=http, **client_kw)
try:
client.messages.create(model="claude-haiku-5-5", max_tokens=100, messages=[{"role": "user", "content": "Hi"}])
except anthropic.APIStatusError as e:
print(f"anthropic {label:<34} attempts={len(seen)} retry-count={seen} sleeps={slept} -> {type(e).__name__}")
print("--- openai 3.42.1 and anthropic 2.4.0 ---")
run_openai("503, defaults", 503)
run_anthropic("529, defaults", 529)
run_openai("503, max_retries=5", 503, max_retries=5)
run_openai("429 + retry-after-ms: 2500", 429, {"retry-after-ms": "2500"})
run_openai("429 + retry-after: 121 (seconds)", 429, {"retry-after": "121"})
run_anthropic("429 + retry-after: 121 (seconds)", 429, {"retry-after": "121"})
run_openai("503 + x-should-retry: false", 503, {"x-should-retry": "false"})
run_openai("400 + x-should-retry: true", 400, {"x-should-retry": "true"})
run_openai("400, no header (never retried)", 400)
# Per-call override, without touching the shared client
slept.clear()
http, seen = scripted(503, OVERLOADED_OAI)
shared = openai.OpenAI(api_key="sk-test", http_client=http)
try:
shared.with_options(max_retries=0).responses.create(model="gpt-6-luna", input="Hi")
except openai.InternalServerError:
print(f"openai {'503, with_options(max_retries=0)':<34} attempts={len(seen)}")
print("\n--- google-genai 2.34.0 ---")
EXHAUSTED = {"error": {"code": 429, "status": "RESOURCE_EXHAUSTED", "message": "Resource has been exhausted."}}
def gemini(label: str, retry: types.HttpRetryOptions | None, interactions: bool = False) -> None:
slept.clear()
calls: list[int] = []
def handler(req: httpx.Request) -> httpx.Response:
calls.append(1)
body = {"error": {"code": "rate_limit_exceeded", "message": "Slow down."}} if interactions else EXHAUSTED
return httpx.Response(429, json=body, headers={"retry-after": "30"}) # a server delay hint
client = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=httpx.MockTransport(handler)), retry_options=retry))
try:
if interactions:
client.interactions.create(model="gemini-3.8-flash", input="Hi")
else:
client.models.generate_content(model="gemini-3.8-flash", contents="Hi")
except (errors.APIError, _interactions.APIStatusError) as e:
print(f"genai {label:<34} attempts={len(calls)} sleeps={slept} -> {type(e).__name__}")
gemini("models, default (no retry_options)", None)
gemini("models, HttpRetryOptions()", types.HttpRetryOptions())
gemini("models, HttpRetryOptions(attempts=3)", types.HttpRetryOptions(attempts=3))
gemini("interactions, default", None, interactions=True)
gemini("interactions, HttpRetryOptions(attempts=3)", types.HttpRetryOptions(attempts=3), interactions=True)--- openai 3.42.1 and anthropic 2.4.0 ---
openai 503, defaults attempts=3 retry-count=['0', '1', '2'] sleeps=[0.46, 0.962] -> InternalServerError
anthropic 529, defaults attempts=3 retry-count=['0', '1', '2'] sleeps=[0.419, 0.982] -> OverloadedError
openai 503, max_retries=5 attempts=6 retry-count=['0', '1', '2', '3', '4', '5'] sleeps=[0.433, 0.909, 1.971, 3.493, 7.925] -> InternalServerError
openai 429 + retry-after-ms: 2500 attempts=3 retry-count=['0', '1', '2'] sleeps=[2.5, 2.5] -> RateLimitError
openai 429 + retry-after: 121 (seconds) attempts=1 retry-count=['0'] sleeps=[] -> RateLimitError
anthropic 429 + retry-after: 121 (seconds) attempts=3 retry-count=['0', '1', '2'] sleeps=[121.0, 121.0] -> RateLimitError
openai 503 + x-should-retry: false attempts=1 retry-count=['0'] sleeps=[] -> InternalServerError
openai 400 + x-should-retry: true attempts=3 retry-count=['0', '1', '2'] sleeps=[0.446, 0.983] -> BadRequestError
openai 400, no header (never retried) attempts=1 retry-count=['0'] sleeps=[] -> BadRequestError
openai 503, with_options(max_retries=0) attempts=1
--- google-genai 2.34.0 ---
genai models, default (no retry_options) attempts=1 sleeps=[] -> ClientError
genai models, HttpRetryOptions() attempts=5 sleeps=[1.091, 2.425, 4.827, 8.124] -> ClientError
genai models, HttpRetryOptions(attempts=3) attempts=3 sleeps=[1.627, 2.948] -> ClientError
genai interactions, default attempts=4 sleeps=[30.0, 30.0, 30.0] -> RateLimitError
genai interactions, HttpRetryOptions(attempts=3) attempts=4 sleeps=[30.0, 30.0, 30.0] -> RateLimitErrorEvery row of 5.1 and 5.2 is visible here:
- Default
openai/anthropic: 3 attempts, retry counts0, 1, 2, delays just under 0.5 s and 1 s. max_retries=5: the delays double until the 8-second cap (7.9 s is 8 s with jitter).retry-after-ms: 2500replaces the backoff exactly.retry-after: 121:openaimade one attempt;anthropicslept 121 s twice.x-should-retryoverrode the status both ways: a 503 not retried, a 400 retried.with_options(max_retries=0)turned retries off for one call without changing the shared client.- Gemini
models.*: one attempt by default; withHttpRetryOptions(), 5 attempts at about 1, 2, 4 and 8 s, ignoring the server'sretry-after: 30; withattempts=3, three attempts in total. - Gemini
interactions.*: 4 attempts by default, each wait exactly the server's 30 s; withattempts=3, still 4 attempts (3 retries).
5.4 Configuring retries#
Where each setting lives (building clients only, no network):
"""Where retry settings live in each SDK (no network: we only build clients and read their settings)."""
import anthropic
import openai
from google import genai
from google.genai import types
oai = openai.OpenAI(api_key="sk-test", max_retries=5) # client-wide
print("openai client max_retries:", oai.max_retries,
"| per-call copy:", oai.with_options(max_retries=0).max_retries)
claude = anthropic.Anthropic(api_key="sk-ant-test") # default
print("anthropic default max_retries:", claude.max_retries,
"| per-call copy:", claude.with_options(max_retries=4).max_retries)
retry = types.HttpRetryOptions(
attempts=4, # models.*: 4 attempts in total; interactions.*: 4 RETRIES (5 calls)
initial_delay=1.0, max_delay=30.0, exp_base=2.0, jitter=1.0,
http_status_codes=[408, 429, 500, 502, 503, 504],
)
gem = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(retry_options=retry, timeout=30_000))
print("gemini retry_options:", gem._api_client._http_options.retry_options) # private: inspected for the demo only
per_call = types.GenerateContentConfig(http_options=types.HttpOptions(retry_options=types.HttpRetryOptions(attempts=2)))
print("gemini per-call override (models.*):", per_call.http_options.retry_options if per_call.http_options else None)openai client max_retries: 5 | per-call copy: 0
anthropic default max_retries: 2 | per-call copy: 4
gemini retry_options: attempts=4 initial_delay=1.0 max_delay=30.0 exp_base=2.0 jitter=1.0 http_status_codes=[408, 429, 500, 502, 503, 504]
gemini per-call override (models.*): attempts=2 initial_delay=None max_delay=None exp_base=None jitter=None http_status_codes=NoneRules of thumb for the SDK settings:
- Keep the defaults for simple scripts. Two quick retries on
openai/anthropicabsorb most network blips and short overloads. - For
generate_content, decide explicitly. Either passHttpRetryOptions(for exampleattempts=4, max_delay=30), or leave it off because your own layer retries. Leaving it off by accident means one blip fails the call. - Use
with_options()per code path, not a new client: an interactive endpoint might usemax_retries=1, a nightly batchmax_retries=6(03.1, 7.3). - Turn SDK retries off (
max_retries=0) when your own layer retries. That's the next section.
5.5 The double-retry trap: one layer owns retries#
Retries multiply across layers. Suppose your code retries 4 times, the SDK retries twice (3 tries), and a gateway or proxy in front of the provider tries twice. During an outage, one user request becomes:
sequenceDiagram
participant App as Your retry loop (4 attempts)
participant SDK as SDK (max_retries 2)
participant GW as Gateway (2 attempts)
participant API as Provider
App->>SDK: attempt 1
SDK->>GW: try 1
GW->>API: request
API-->>GW: 503
GW->>API: request again
API-->>GW: 503
GW-->>SDK: 503
SDK->>GW: try 2, then try 3
Note over GW,API: 2 more gateway attempts each time
SDK-->>App: InternalServerError after 6 provider requests
Note over App,API: 4 app attempts x 3 SDK tries x 2 gateway tries = 24 requests and minutes of waiting4 × 3 × 2 = 24 requests to a provider that is already struggling, and the waits multiply too, so the user may wait minutes for an error. OpenAI's rate-limits guide warns about exactly this: "disable SDK retries or account for them ... so nested retry loops don't multiply requests".
The fix is a design decision: exactly one layer owns retries, and every other layer passes failures straight through.
| Your situation | Who should own retries | Settings |
|---|---|---|
| A script, a notebook, a simple service | The SDK | Defaults (max_retries=2); add HttpRetryOptions for Gemini models.* |
You need billing-aware classification, Retry-After caps, a total deadline, logging, or one policy across providers |
Your code (Part 8, Part 13) | max_retries=0 on openai/anthropic; no retry_options on Gemini models.* |
| A gateway that retries or fails over (OpenRouter, LiteLLM proxy, an internal gateway) | The gateway, for transient errors | Few or no retries in your code for 5xx/429; keep your classification for everything else |
| Gemini Interactions | Its built-in retries can't be fully disabled (attempts=0 becomes 1, 5.2) |
Don't wrap Interactions calls in another retry loop for the same errors |
5.2 google-genai: two APIs, two retry systems#
google-genai 2.34.0 has two separate retry implementations, and their defaults are opposite:
client.models.* (generate_content...) |
client.interactions.* |
|
|---|---|---|
| Retries by default? | No. With no retry_options, the policy is tenacity.stop_after_attempt(1): exactly one attempt |
Yes: 3 retries, so up to 4 attempts |
| Enable or change | types.HttpOptions(retry_options=types.HttpRetryOptions(...)) on the client, or per call in GenerateContentConfig(http_options=...) |
The same client-level HttpOptions(retry_options=...) |
Meaning of attempts=N |
N attempts in total (the first call included) | N retries (N + 1 calls) |
Defaults once enabled (HttpRetryOptions()) |
5 attempts, initial_delay=1.0, max_delay=60.0, exp_base=2, jitter=1, codes 408, 429, 500, 502, 503, 504 |
Initial 0.5 s, cap 8 s, base 2 |
| Backoff before retry n (n = 1, 2...) | initial × 2ⁿ⁻¹ + uniform(0, jitter), capped at max_delay (tenacity's wait_exponential_jitter) |
0.5 × 2ⁿ⁻¹ seconds × a random factor between 0.75 and 1, capped at 8 s |
| Retried | The listed status codes, plus httpx/httpx2 ConnectError and TimeoutException |
408, 409, 429, every 5xx, plus connection errors |
Retry-After / retry-after-ms |
Ignored | Honoured, with no upper limit |
| Logging | INFO on google_genai._api_client before each sleep |
— |
| Streams | The request that opens the stream is retried only if you set retry_options. After the first event, nothing is retried by retry_options, but see the continuation note below |
The request that opens the stream is retried (3 retries). After the first event, nothing is retried by this system, but see the continuation note below |
Google's troubleshooting page says something else (as of November 2026): "the Python SDK automatically retries transient errors up to four times with an initial delay of approximately 1 second and a maximum delay of 60 seconds." That describes what HttpRetryOptions() does once you enable it (5 attempts = 4 retries, 1 s initial, 60 s cap), not the default for generate_content. Teach yourself the SDK's behaviour, not the page's: generate_content makes one attempt unless you pass retry_options. 03.1's production-minded sample sets it for that reason.
A third, separate mechanism: automatic continuation. The retry tables above are about failed requests. google-genai also resumes long Gemini generations from a server-issued continuation_token: generate_content_stream and Interactions streams, on very long generations, where the server stops at its per-request token limit and the SDK asks again (03.3, 4.5b). automatic_continuation is on by default, and non-streaming generate_content follows continuation_token hops too, returning one merged response. These resumes are not governed by retry_options: timeouts, retries and billing apply to each hop, and on Interactions streams up to three consecutive reconnects that make no progress are tolerated before the error is raised (MAX_STREAM_RECONNECTS_WITHOUT_PROGRESS = 3 in the SDK source). It is the one place where an SDK carries on a stream for you; every other mid-stream failure is your code's decision.
Three more details you'll only find in the source:
attempts=0is silently turned intoattempts=1. The SDK rewrites theHttpRetryOptionsobject in place when the client is built. Formodels.*that means one attempt, as you'd expect. Forinteractions.*it means one retry, so there is no way to switch Interactions retries off throughattempts. Settinghttp_status_codesto a code the API never sends stops status retries, but connection errors are still retried. If you need full control, let Interactions keep its small default and don't add another retry layer on top (5.5).- Read errors aren't retried by
models.*, even withretry_options: onlyConnectErrorandTimeoutExceptionare on the list, so a connection reset mid-response (httpx.ReadError,RemoteProtocolError) is raised immediately. - The async
aiohttppath has a hidden retry. Ifaiohttpis installed (it's used forclient.aiowhen available) and you set noretry_options, a connection error is retried once after a random 1–10 second sleep. Settingretry_optionsreplaces this with your policy.
Part 6: Timeouts#
6.1 The four HTTP timeouts, and each SDK's defaults#
A timeout is how long the client is willing to wait before giving up. HTTP clients have four, and each guards a different wait:
| Timeout | Guards | A good value for LLM calls |
|---|---|---|
| connect | Opening the TCP and TLS connection | Short: 2–5 s. If you can't connect in 5 s, something is wrong |
| read | The longest gap between two pieces of data arriving. Not the total time | As long as the slowest healthy response stays silent: the whole generation for a non-streaming call, the longest pause between chunks for a stream |
| write | Sending the request body | Rarely matters, except for large uploads (images, PDFs) |
| pool | Waiting for a free connection from the client's pool | Matters under high concurrency (03.9) |
The defaults, from the SDK source (versions named in Setup, as of November 2026):
openai 3.42.1 |
anthropic 2.4.0 |
|
|---|---|---|
| Default | Timeout(600, connect=5.0): 10 minutes for read, write and pool, 5 s to connect |
The same, plus the 10-minute guard (6.4) |
| Set on the client | OpenAI(timeout=20.0) or timeout=httpx2.Timeout(20.0, connect=5.0) |
The same |
| Set per call | timeout= on any method, or client.with_options(timeout=...) |
The same |
| Raised | openai.APITimeoutError |
anthropic.APITimeoutError |
| Retried by default? | Yes (2 retries) | Yes (2 retries) |
| Sent to the server | x-stainless-read-timeout (informational) |
x-stainless-timeout, x-stainless-read-timeout |
google-genai 2.34.0 models.* |
google-genai interactions.* |
|
|---|---|---|
| Default | None at all: a stuck request can wait forever | None, unless set |
| Set on the client | HttpOptions(timeout=20_000): milliseconds, one number for every phase |
The same HttpOptions |
| Set per call | config=GenerateContentConfig(http_options=HttpOptions(timeout=...)) |
interactions.create(..., timeout=20.0): seconds, and it "bounds the whole call (all continuation hops together)" |
| Raised | Raw httpx.ReadTimeout / ConnectTimeout (httpx.TimeoutException) |
_interactions.APITimeoutError |
| Retried by default? | Only with retry_options |
Yes |
| Sent to the server | X-Server-Timeout: your timeout in seconds, rounded up, so the server can stop work you've stopped waiting for |
— |
6.2 Try it: timeouts for real#
A mock can't produce a real timeout (it answers instantly), so this sample runs a tiny local HTTP server that waits 3 seconds before answering. It is a fixture, not a provider. Each SDK gets a 1-second timeout:
"""Timeouts for real: a tiny local HTTP server (a fixture, not a provider) that waits 3 s before
answering. Each SDK gets a 1 s timeout, and we time what happens."""
import asyncio
import http.server
import json
import random
import threading
import time
import anthropic
import httpx2
import openai
from google import genai
from google.genai import _interactions, types
seen_headers: list[dict[str, str]] = []
class SlowHandler(http.server.BaseHTTPRequestHandler):
def do_POST(self) -> None:
self.rfile.read(int(self.headers.get("content-length", 0)))
seen_headers.append({k.lower(): v for k, v in self.headers.items()})
time.sleep(3) # the "model" is thinking...
try:
body = json.dumps({"error": {"message": "too late"}}).encode()
self.send_response(500); self.send_header("content-length", str(len(body))); self.end_headers()
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError):
pass # the client already gave up
def log_message(self, *args: object) -> None:
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), SlowHandler)
threading.Thread(target=server.serve_forever, daemon=True).start()
URL = f"http://127.0.0.1:{server.server_address[1]}"
random.seed(2) # repeatable SDK jitter
def timed(label: str, fn) -> None:
seen_headers.clear()
start = time.monotonic()
try:
fn()
except Exception as e:
print(f"{label:<44} {type(e).__name__:<16} after {time.monotonic() - start:4.1f} s, attempts={len(seen_headers)}")
HI = [{"role": "user", "content": "Hi"}]
oai = openai.OpenAI(base_url=URL + "/v1", api_key="sk-test", timeout=httpx2.Timeout(1.0, connect=2.0), max_retries=0)
timed("openai, 1 s timeout, no retries", lambda: oai.responses.create(model="gpt-6-luna", input="Hi"))
timed("openai, 1 s timeout, default 2 retries", lambda: oai.with_options(max_retries=2).responses.create(
model="gpt-6-luna", input="Hi"))
print(" headers the SDK sent:", {k: v for k, v in seen_headers[0].items() if "timeout" in k or "retry" in k})
claude = anthropic.Anthropic(base_url=URL, api_key="sk-ant-test", max_retries=0)
timed("anthropic, per-call timeout=1.0", lambda: claude.messages.create(
model="claude-haiku-5-5", max_tokens=100, messages=HI, timeout=1.0)) # type: ignore[arg-type]
gem = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(base_url=URL, timeout=1_000)) # milliseconds!
timed("gemini models, HttpOptions(timeout=1_000)", lambda: gem.models.generate_content(
model="gemini-3.8-flash", contents="Hi"))
print(" X-Server-Timeout sent:", seen_headers[0].get("x-server-timeout"))
timed("gemini interactions, timeout=1.0 (seconds)", lambda: gem.interactions.create(
model="gemini-3.8-flash", input="Hi", timeout=1.0))
async def with_deadline() -> None:
# Retries are on (2), each attempt may take 1 s: without a deadline this could take ~4.5 s.
client = openai.AsyncOpenAI(base_url=URL + "/v1", api_key="sk-test", timeout=1.0, max_retries=2)
async with asyncio.timeout(2.0): # the whole operation, retries included
await client.responses.create(model="gpt-6-luna", input="Hi")
timed("openai async, asyncio.timeout(2.0) around all", lambda: asyncio.run(with_deadline()))
server.shutdown()openai, 1 s timeout, no retries APITimeoutError after 1.0 s, attempts=1
openai, 1 s timeout, default 2 retries APITimeoutError after 4.2 s, attempts=3
headers the SDK sent: {'x-stainless-retry-count': '0', 'x-stainless-read-timeout': '1.0'}
anthropic, per-call timeout=1.0 APITimeoutError after 1.0 s, attempts=1
gemini models, HttpOptions(timeout=1_000) ReadTimeout after 1.0 s, attempts=1
X-Server-Timeout sent: 1
gemini interactions, timeout=1.0 (seconds) APITimeoutError after 1.0 s, attempts=1
openai async, asyncio.timeout(2.0) around all TimeoutError after 2.0 s, attempts=2What to notice:
- With the SDK's default two retries, a 1-second timeout took 4.2 seconds to fail: three 1-second attempts plus two backoff sleeps. (The client was built with
max_retries=0, so the sample turns the default two back on for that one call withwith_options(max_retries=2).) The timeout you configure is per attempt; the user waits for all of them. x-stainless-read-timeout: 1.0shows the SDK telling the server how long it will wait.- Gemini sent
X-Server-Timeout: 1(the 1,000 ms, in seconds) and raised a rawhttpx.ReadTimeout. - The Interactions per-call timeout bounded the whole call: one attempt, then
APITimeoutError. asyncio.timeout(2.0)cut the retrying call off at exactly 2 seconds, in the middle of its second attempt.
6.3 A total deadline#
Users and upstream callers don't care how many attempts you made, only how long they waited. Give every call a deadline, a total time budget that covers all attempts and all waits, and derive everything else from it:
- In async code, wrap the whole operation in
async with asyncio.timeout(seconds):(Python 3.11+), as in 6.2. It raisesTimeoutErrorand cancels whatever is running inside, including an SDK's retry sleep. - In sync code, track the time yourself: before each attempt, compute what's left of the deadline and use
min(per_attempt_timeout, remaining)as that attempt's timeout, and don't start a backoff sleep that would end past the deadline. The production call in 13.2 does exactly this.
6.4 Anthropic's 10-minute guard for non-streaming requests#
The anthropic SDK refuses some requests before sending them. In the SDK source, a non-streaming messages.create() is expected to take 60 minutes × max_tokens / 128,000, and if that's more than 10 minutes, it raises ValueError. So with the default timeout, max_tokens above 21,333 raises. Anthropic's Python SDK docs describe it: "The SDK will throw a ValueError if a non-streaming request is expected to take longer than approximately 10 minutes. Passing stream=True or overriding the timeout option at the client or request level disables this error."
"""Anthropic's non-streaming guard: the SDK refuses, before sending, a request whose max_tokens
could take more than 10 minutes. A mock server answers the requests that do get sent."""
import httpx2
import anthropic
OK = {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
"content": [{"type": "text", "text": "Hi!"}], "stop_reason": "end_turn", "stop_sequence": None,
"usage": {"input_tokens": 5, "output_tokens": 2}}
sent: list[str | None] = []
def handler(req: httpx2.Request) -> httpx2.Response:
sent.append(req.headers.get("x-stainless-timeout"))
return httpx2.Response(200, json=OK)
def client(**kw: object) -> anthropic.Anthropic:
return anthropic.Anthropic(api_key="sk-ant-test", http_client=httpx2.Client(transport=httpx2.MockTransport(handler)),
**kw) # type: ignore[arg-type]
HI: list[anthropic.types.MessageParam] = [{"role": "user", "content": "Write a long report."}]
default = client()
print("Rule: 60 min x max_tokens / 128,000 must not exceed 10 min -> max_tokens <= 21,333")
for label, call in [
("max_tokens=21_333, default timeout", lambda: default.messages.create(model="claude-haiku-5-5", max_tokens=21_333, messages=HI)),
("max_tokens=21_334, default timeout", lambda: default.messages.create(model="claude-haiku-5-5", max_tokens=21_334, messages=HI)),
("max_tokens=64_000, per-call timeout=1800", lambda: default.messages.create(
model="claude-haiku-5-5", max_tokens=64_000, messages=HI, timeout=1800)),
("max_tokens=64_000, client timeout=900.0", lambda: client(timeout=900.0).messages.create(
model="claude-haiku-5-5", max_tokens=64_000, messages=HI)),
("max_tokens=64_000, stream=True", lambda: default.messages.create(
model="claude-haiku-5-5", max_tokens=64_000, messages=HI, stream=True)),
]:
sent.clear()
try:
call()
print(f" {label:<42} sent ({len(sent)} request)")
except ValueError as e:
print(f" {label:<42} ValueError: {str(e)[:66]}...")Rule: 60 min x max_tokens / 128,000 must not exceed 10 min -> max_tokens <= 21,333
max_tokens=21_333, default timeout sent (1 request)
max_tokens=21_334, default timeout ValueError: Streaming is required for operations that may take longer than 10 ...
max_tokens=64_000, per-call timeout=1800 sent (1 request)
max_tokens=64_000, client timeout=900.0 sent (1 request)
max_tokens=64_000, stream=True sent (1 request)The guard exists because "some networks might drop idle connections after a variable period of time" (Anthropic's errors page): a non-streaming request sends no bytes until the end, and many proxies and load balancers close connections that are silent for minutes (03.3, 8.3). Your options for long outputs, in order of preference:
- Stream (03.3): bytes flow all the time, and
messages.stream(...).get_final_message()still gives you one completeMessage. - Use the Message Batches API for work that can wait (03.9).
- Set an explicit timeout (
timeout=1800) only if you control every network hop. The guard goes away, but the idle-connection risk doesn't.
6.5 Choosing timeouts per use case#
There is no single right timeout, only the right one for each kind of call. Profiles to start from (tune them from your own latency logs):
"""Timeout profiles per use case (no network: we build clients and print what they will use)."""
import anthropic
import httpx2
import openai
from google.genai import types
PROFILES = {
# connect: reach the server; read: the longest silence between bytes; write/pool: rarely matter
"autocomplete (non-streaming)": httpx2.Timeout(4.0, connect=2.0),
"chat answer (non-streaming)": httpx2.Timeout(45.0, connect=5.0),
"reasoning model, high effort": httpx2.Timeout(600.0, connect=5.0),
"streaming chat": httpx2.Timeout(30.0, connect=5.0), # read = max gap between chunks
}
for name, t in PROFILES.items():
print(f"{name:<30} connect={t.connect:<5} read={t.read:<6} write={t.write:<6} pool={t.pool}")
shared = openai.OpenAI(api_key="sk-test", timeout=PROFILES["chat answer (non-streaming)"])
fast = shared.with_options(timeout=PROFILES["autocomplete (non-streaming)"]) # same pool, other timeout
print("\nopenai shared:", shared.timeout, "\nopenai fast: ", fast.timeout)
print("anthropic default:", anthropic.Anthropic(api_key="sk-ant-test").timeout)
print("gemini: HttpOptions(timeout=45_000) means", types.HttpOptions(timeout=45_000).timeout, "ms = 45 s")autocomplete (non-streaming) connect=2.0 read=4.0 write=4.0 pool=4.0
chat answer (non-streaming) connect=5.0 read=45.0 write=45.0 pool=45.0
reasoning model, high effort connect=5.0 read=600.0 write=600.0 pool=600.0
streaming chat connect=5.0 read=30.0 write=30.0 pool=30.0
openai shared: Timeout(connect=5.0, read=45.0, write=45.0, pool=45.0)
openai fast: Timeout(connect=2.0, read=4.0, write=4.0, pool=4.0)
anthropic default: Timeout(connect=5.0, read=600, write=600, pool=600)
gemini: HttpOptions(timeout=45_000) means 45000 ms = 45 s| Use case | Read timeout (per attempt) | Total deadline | Why |
|---|---|---|---|
| Autocomplete, classification, short extraction | 2–5 s | 5–10 s | A late answer is useless; fail fast and show nothing |
| Chat answer, non-streaming | 30–60 s | 60–90 s | Set the read timeout from your p99 latency for typical output sizes, with headroom |
| Reasoning model at high effort, long documents | Minutes; prefer streaming or background mode | Minutes | Thinking can last minutes with no output. Stream so bytes keep flowing, or use background mode (03.9) |
| Streaming chat | 30–60 s between chunks | 2–5 min | The read timeout is the longest silence (03.3, 8.1); the deadline bounds the whole stream |
| Batch / offline jobs | Long | Hours | Use the Batch APIs instead of long synchronous calls (03.9) |
Always keep the connect timeout short (2–5 s): connecting doesn't get slower because the model is thinking.
6.6 Timeouts that still bill#
When your client times out, it closes its connection. Whether the provider notices and stops working is mostly undocumented for non-streaming requests:
- OpenRouter is explicit: "For non-streaming requests or unsupported providers, the model will continue processing and you will be billed for the complete response" (its streaming docs, as of November 2026).
- OpenAI and Anthropic don't document what happens to tokens generated for an abandoned non-streaming request (03.3, 8.5 covers streams).
- Gemini receives your timeout in
X-Server-Timeout, so it can stop work you've abandoned, but its docs don't say what you're billed for. For Interactions, Google says "Cancelled and failed interactions: You pay for all work completed before the interaction ends".
Assume the worst: a client-side timeout on a non-streaming call may cost the full price, and its retry costs it again. What follows from that:
- Size timeouts generously for non-streaming calls, and stream long outputs so you can cancel: closing a stream gives the provider a signal to stop generating, though only OpenRouter documents that it stops billing (03.3, 8.5).
- Log timed-out calls with their usage as unknown, not zero (03.3, 7.6), so your cost tracking (03.7) doesn't undercount exactly the failures.
- Send your own correlation ID (OpenAI's
X-Client-Request-Id, 11.4) so you can find the abandoned request in the provider's logs or usage data later. On OpenRouter, the generation can be looked up by its ID afterwards (Part 12). - Never retry a timed-out request that triggered side effects without a dedupe check (Part 11).
Part 7: Backoff done right#
7.1 Exponential backoff and jitter#
Backoff means waiting before a retry, and waiting longer after each failure, so a struggling server gets room to recover. Exponential backoff doubles the wait each time (0.5 s, 1 s, 2 s, 4 s...) up to a cap. That alone isn't enough. If a thousand clients all failed at the same instant (because the provider blipped for all of them at once), plain exponential backoff makes them all retry at the same instants too: a thundering herd that knocks the server over again. Jitter adds randomness so the retries spread out.
Marc Brooker's post on the AWS Architecture Blog, "Exponential Backoff And Jitter" (2015), compared four formulas, and they remain the standard reference:
| Strategy | Wait before retry n | In one sentence |
|---|---|---|
| Exponential (no jitter) | min(cap, base × 2ⁿ) |
Predictable, and synchronized across clients: the herd problem |
| Full jitter | random(0, min(cap, base × 2ⁿ)) |
Anywhere from zero up to the exponential value |
| Equal jitter | half + random(0, half), where half = min(cap, base × 2ⁿ) / 2 |
Always waits at least half the exponential value |
| Decorrelated jitter | min(cap, random(base, previous_wait × 3)) |
Grows from the previous wait rather than the attempt number |
The post's conclusions: "The no-jitter exponential backoff approach is the clear loser", "Of the jittered approaches, 'Equal Jitter' is the loser", and "The 'Full Jitter' approach uses less work, but slightly more time" than decorrelated jitter. Here are all four, plus the formula the openai and anthropic SDKs use, with the same base and cap (0.5 s and 8 s) and a fixed seed:
"""The four backoff formulas from the AWS Architecture Blog (Brooker, 2015), plus what each
does to a crowd of clients that all failed at the same moment. Pure Python, no network."""
import random
from collections import Counter
BASE, CAP = 0.5, 8.0 # seconds: the same numbers the openai/anthropic SDKs use
def exponential(attempt: int, rng: random.Random, prev: float) -> float:
return min(CAP, BASE * 2 ** attempt)
def full_jitter(attempt: int, rng: random.Random, prev: float) -> float:
return rng.uniform(0, min(CAP, BASE * 2 ** attempt))
def equal_jitter(attempt: int, rng: random.Random, prev: float) -> float:
temp = min(CAP, BASE * 2 ** attempt)
return temp / 2 + rng.uniform(0, temp / 2)
def decorrelated_jitter(attempt: int, rng: random.Random, prev: float) -> float:
return min(CAP, rng.uniform(BASE, prev * 3)) # depends on the previous sleep, not the attempt
def sdk_style(attempt: int, rng: random.Random, prev: float) -> float:
return min(CAP, BASE * 2 ** attempt) * (1 - 0.25 * rng.random()) # openai/anthropic: 75-100%
STRATEGIES = {"exponential (no jitter)": exponential, "full jitter": full_jitter,
"equal jitter": equal_jitter, "decorrelated jitter": decorrelated_jitter,
"openai/anthropic SDKs": sdk_style}
def schedule(strategy, n: int, seed: int) -> list[float]:
rng, prev, out = random.Random(seed), BASE, []
for attempt in range(n):
prev = strategy(attempt, rng, prev)
out.append(round(prev, 2))
return out
print("Delays before retries 1..6 (seconds), seed 42:")
for name, fn in STRATEGIES.items():
print(f" {name:<24} {schedule(fn, 6, seed=42)}")
# 1,000 clients all get a 429 at t=0 and retry 4 times. How bunched are their retries?
print("\n1,000 clients fail together at t=0. Busiest 100 ms window during their retries:")
for name, fn in STRATEGIES.items():
windows: Counter[int] = Counter()
for client in range(1000):
rng, prev, t = random.Random(client), BASE, 0.0
for attempt in range(4):
prev = fn(attempt, rng, prev)
t += prev
windows[int(t * 10)] += 1 # which 100 ms slot this retry lands in
print(f" {name:<24} {max(windows.values()):>5} requests at once")Delays before retries 1..6 (seconds), seed 42:
exponential (no jitter) [0.5, 1.0, 2.0, 4.0, 8.0, 8.0]
full jitter [0.32, 0.03, 0.55, 0.89, 5.89, 5.41]
equal jitter [0.41, 0.51, 1.28, 2.45, 6.95, 6.71]
decorrelated jitter [1.14, 0.57, 0.84, 0.95, 2.23, 4.68]
openai/anthropic SDKs [0.42, 0.99, 1.86, 3.78, 6.53, 6.65]
1,000 clients fail together at t=0. Busiest 100 ms window during their retries:
exponential (no jitter) 1000 requests at once
full jitter 294 requests at once
equal jitter 405 requests at once
decorrelated jitter 131 requests at once
openai/anthropic SDKs 808 requests at onceThe second half is the thundering herd in numbers: without jitter, all 1,000 retries land in the same 100 ms window, four times over. Every jittered strategy spreads them out, and the more random the wait, the flatter the load. The SDKs' formula (up to 25% shorter) is only lightly jittered: fine for a handful of retries from one process, not designed to de-synchronize a large fleet. When you write your own retry layer, use full jitter (or decorrelated): it's simple and it works.
7.2 Retry-After: the server knows best#
When a server knows how long you should wait, it says so in the Retry-After response header, and its value beats any backoff formula: the server can see its own queue, you can't.
- The standard. RFC 9110, section 10.2.3 defines
Retry-After = HTTP-date / delay-seconds: either a date (Wed, 04 Nov 2026 10:00:30 GMT) or a whole number of seconds (30). It's typically sent with 503 and redirects. For 429, RFC 6585, section 4 says the response "MAY include a Retry-After header indicating how long to wait before making a new request". - The extensions you'll meet.
retry-after-ms(milliseconds, non-standard) is read first by theopenaiandanthropicSDKs, and by Gemini Interactions. Fractional seconds (1.5) aren't standard but are accepted byopenai,anthropicand Gemini Interactions (Geminigenerate_contentignoresRetry-Afteraltogether, 5.2). Geminigenerate_contenterrors may put a hint in the body instead: agoogle.rpc.RetryInfodetail withretryDelay: "17s"(3.4).
| Provider | Where the wait hint comes from (as of November 2026) |
|---|---|
| OpenAI | Retry-After on temporary 429s and 503 overloads ("Treat this value as a minimum: wait at least that long and add a small random delay") |
| Anthropic | retry-after on rate-limit 429s; absent on the tier spend-cap 429 (Anthropic: "Not every 429 carries it") |
| Provider | Where the wait hint comes from (as of November 2026) |
|---|---|
Gemini models.* |
No header documented; maybe RetryInfo.retryDelay in the body |
| Gemini Interactions | Retry-After / retry-after-ms when sent (the SDK honours them) |
| OpenRouter | Retry-After "may" appear on 429, 503 and the in-flight-budget 402 |
How to use it:
- Wait at least that long, plus a small random amount (so clients told "30 s" don't all return at the same instant).
- Cap it. A
Retry-Afterof an hour inside a web request is a failure, not a wait. If the hint exceeds what this call can afford, stop and report it (or queue the work for later). - Fall back to full-jitter backoff when there's no hint, or it can't be parsed.
- Share it. A 429 hint applies to your whole account, not just the one request: tell your rate limiter so other calls wait too (9.5).
7.3 Try it: a Retry-After parser with tests#
retry_after.py reads every format above. It's used by the classifier in 4.4 and everything built on it:
"""retry_after.py: read the server's "wait this long" hint from any of the four providers.
Standard (RFC 9110 section 10.2.3): Retry-After = HTTP-date / delay-seconds (a non-negative integer).
Non-standard but real: retry-after-ms (OpenAI, Anthropic SDKs read it), fractional seconds,
and Google's RetryInfo.retryDelay inside a JSON error body ("17s", "0.5s")."""
import datetime as dt
import email.utils
import re
import time
from collections.abc import Mapping
from typing import Any
MAX_SANE_DELAY = 24 * 3600.0 # ignore absurd values (a bug or a hostile proxy), seconds
def parse_retry_after(headers: Mapping[str, str], now: float | None = None) -> float | None:
"""Seconds to wait, or None if the server gave no usable hint. Header names are case-insensitive."""
lower = {k.lower(): v.strip() for k, v in headers.items()}
now = time.time() if now is None else now
ms = lower.get("retry-after-ms") # 1. milliseconds, most precise
if ms is not None:
try:
value = float(ms) / 1000
if 0 <= value <= MAX_SANE_DELAY:
return value
except ValueError:
pass
raw = lower.get("retry-after")
if raw is None:
return None
try: # 2. delay-seconds (accept "1.5" too)
value = float(raw)
return value if 0 <= value <= MAX_SANE_DELAY else None
except ValueError:
pass
try: # 3. HTTP-date, e.g. "Wed, 04 Nov 2026 10:00:05 GMT"
parsed = email.utils.parsedate_to_datetime(raw)
except (TypeError, ValueError):
return None
if parsed.tzinfo is None: # no zone, or "-0000": HTTP dates are GMT by definition
parsed = parsed.replace(tzinfo=dt.timezone.utc) # (a naive .timestamp() would use the machine's local zone)
delay = parsed.timestamp() - now
return min(max(delay, 0.0), MAX_SANE_DELAY) # a date in the past means "now"
def parse_google_retry_delay(error_body: Any) -> float | None:
"""Gemini models.* errors may carry a google.rpc.RetryInfo detail: {"retryDelay": "17s"}."""
try:
details = error_body["error"]["details"]
except (KeyError, TypeError):
return None
for d in details if isinstance(details, list) else []:
if isinstance(d, dict) and str(d.get("@type", "")).endswith("google.rpc.RetryInfo"):
match = re.fullmatch(r"(\d+(?:\.\d+)?)s", str(d.get("retryDelay", "")))
if match:
return float(match.group(1))
return NoneAnd its tests, runnable directly or with pytest:
"""Tests for retry_after.py (run with `python s7_3_retry_after_tests.py` or with pytest)."""
from retry_after import parse_google_retry_delay, parse_retry_after
NOW = 1_793_786_400.0 # a fixed "now": 2026-11-04 10:00:00 UTC
def test_seconds() -> None:
assert parse_retry_after({"Retry-After": "7"}, NOW) == 7.0
def test_fractional_seconds_are_accepted() -> None:
assert parse_retry_after({"retry-after": "1.5"}, NOW) == 1.5
def test_milliseconds_win_over_seconds() -> None:
assert parse_retry_after({"retry-after-ms": "250", "retry-after": "1"}, NOW) == 0.25
def test_http_date() -> None:
assert parse_retry_after({"Retry-After": "Wed, 04 Nov 2026 10:00:30 GMT"}, NOW) == 30.0
def test_date_in_the_past_means_now() -> None:
assert parse_retry_after({"Retry-After": "Wed, 04 Nov 2026 09:59:00 GMT"}, NOW) == 0.0
def test_date_without_a_zone_is_read_as_utc() -> None:
assert parse_retry_after({"Retry-After": "Wed, 04 Nov 2026 10:00:30"}, NOW) == 30.0
assert parse_retry_after({"Retry-After": "Wed, 04 Nov 2026 11:00:30 +0100"}, NOW) == 30.0
def test_garbage_and_negative_are_ignored() -> None:
assert parse_retry_after({"Retry-After": "soon"}, NOW) is None
assert parse_retry_after({"Retry-After": "-5"}, NOW) is None
assert parse_retry_after({"retry-after-ms": "abc", "retry-after": "3"}, NOW) == 3.0
def test_absurd_values_are_ignored() -> None:
assert parse_retry_after({"Retry-After": "99999999"}, NOW) is None
def test_missing() -> None:
assert parse_retry_after({}, NOW) is None
def test_google_retry_info() -> None:
body = {"error": {"code": 429, "status": "RESOURCE_EXHAUSTED", "details": [
{"@type": "type.googleapis.com/google.rpc.QuotaFailure", "violations": []},
{"@type": "type.googleapis.com/google.rpc.RetryInfo", "retryDelay": "17s"}]}}
assert parse_google_retry_delay(body) == 17.0
assert parse_google_retry_delay({"error": {"code": 429}}) is None
if __name__ == "__main__":
tests = [f for name, f in dict(globals()).items() if name.startswith("test_")]
for t in tests:
t()
print("passed:", t.__name__)
print(f"all {len(tests)} tests passed")passed: test_seconds
passed: test_fractional_seconds_are_accepted
passed: test_milliseconds_win_over_seconds
passed: test_http_date
passed: test_date_in_the_past_means_now
passed: test_date_without_a_zone_is_read_as_utc
passed: test_garbage_and_negative_are_ignored
passed: test_absurd_values_are_ignored
passed: test_missing
passed: test_google_retry_info
all 10 tests passedThree choices in the parser are deliberate. A date with no zone is read as UTC: HTTP dates are GMT by definition, and Python's parsedate_to_datetime returns a naive datetime for a missing zone or -0000, whose .timestamp() would silently use the machine's local time zone and be off by hours. Also, garbage means "no hint" (None), not zero: zero would make you retry immediately, which is exactly wrong for a server that tried to slow you down. And absurd values are ignored rather than obeyed, because a broken proxy or a bug shouldn't be able to park your workers for a day; 13.2 adds a tighter, per-call cap on top.
7.4 Retry budgets: attempts, time, and load#
Three limits keep retries from doing harm:
- Maximum attempts per call (3–5 total is typical). Stops a single call from looping.
- A total deadline per call (6.3). Stops waits and timeouts from adding up beyond what the caller can accept.
- A retry budget across the whole process: retries may add at most, say, 10% to your request volume. During a real outage, every call fails, so per-call limits alone still multiply your traffic by the attempt count, right when the provider can least take it.
A retry budget is a token bucket for retries: every first attempt earns a fraction of a retry token, every retry spends a whole one:
"""A process-wide retry budget: retries may add at most 10% extra load, however many callers retry.
Simulated (no network): 1,000 calls, first during normal operation, then during an outage."""
class RetryBudget:
"""Earn 0.1 retry tokens per first attempt; spend 1 per retry; never hold more than `max_tokens`."""
def __init__(self, ratio: float = 0.1, max_tokens: float = 20.0) -> None:
self.ratio, self.max_tokens, self.tokens = ratio, max_tokens, max_tokens
def on_first_attempt(self) -> None:
self.tokens = min(self.max_tokens, self.tokens + self.ratio)
def try_spend(self) -> bool:
if self.tokens >= 1:
self.tokens -= 1
return True
return False # out of budget: fail now instead of piling on
def simulate(failure_rate: float, budget: RetryBudget | None, calls: int = 1000, max_retries: int = 3) -> int:
"""Return the total number of requests sent. Deterministic: every n-th attempt fails."""
sent, failed_every = 0, (round(1 / failure_rate) if failure_rate else 0)
for _ in range(calls):
if budget:
budget.on_first_attempt()
for attempt in range(max_retries + 1):
sent += 1
fails = failure_rate >= 1 or (failed_every and sent % failed_every == 0)
if not fails:
break
if attempt == max_retries or (budget and not budget.try_spend()):
break
return sent
for label, rate in [("normal (2% failures)", 0.02), ("outage (100% failures)", 1.0)]:
print(f"{label:<24} no budget: {simulate(rate, None):>5} requests | "
f"with 10% budget: {simulate(rate, RetryBudget()):>5} requests (1,000 calls)")normal (2% failures) no budget: 1020 requests | with 10% budget: 1020 requests (1,000 calls)
outage (100% failures) no budget: 4000 requests | with 10% budget: 1119 requests (1,000 calls)On a normal day, the budget changes nothing. During the outage, it cuts 4,000 requests down to 1,119, and callers get a fast, honest failure instead of a long wait for the same failure. This is the per-process version of an idea that grows into circuit breakers (stop calling a dependency entirely for a while once it's clearly down), which Module 11C covers at system level.
Part 8: tenacity#
Deep-dive
tenacity is the standard Python retry library, and the one OpenAI's rate-limits guide names in its example. It gives you a decorator (@retry) built from small, composable pieces. This part uses 9.1.4, the version a project with google-genai 2.34.0 resolves to (see the Setup note at the top of this lesson); everything shown also runs unchanged on 9.2.1.
8.1 The building blocks#
| Piece | What it does | Notes |
|---|---|---|
@retry(...), Retrying(...), AsyncRetrying(...) |
Run a function (or a block, with for attempt in Retrying(...): with attempt: ...) under a policy |
@retry also works directly on async def functions |
stop_after_attempt(n) |
Stop after n attempts in total | |
stop_after_delay(s) |
Stop once s seconds have passed since the first attempt | Checked after an attempt fails, so one more sleep and attempt can overrun |
stop_before_delay(s) |
Stop if the next sleep would end past s seconds | The right one for a deadline: it never starts a wait it can't finish |
stop_a | stop_b |
Stop when either says stop | |
wait_random_exponential(multiplier, max) |
uniform(0, multiplier × 2ⁿ⁻¹), capped at max |
Full jitter |
wait_exponential_jitter(initial, max, jitter) |
initial × 2ⁿ⁻¹ + uniform(0, jitter), capped at max |
Not full jitter: exponential plus a little noise (what google-genai uses internally) |
wait_exponential, wait_fixed, wait_a + wait_b |
No jitter, a constant, or the sum of two waits | |
retry_if_exception_type(types) |
Retry these exception classes | Coarse: can't see a 429's code |
retry_if_exception(predicate) |
Retry when predicate(exception) is true |
Use this with a classifier |
retry_if_result(predicate) |
Retry based on the return value | Careful: see 10.4 |
before_sleep=before_sleep_log(logger, level) |
Log each failure and the coming sleep | |
reraise=True |
When retries run out, raise the original exception | Without it, you get tenacity.RetryError wrapping the last attempt, and your except openai.RateLimitError no longer matches |
8.2 The two "jitter" waits are not the same#
The names suggest they're interchangeable. They're not:
"""What tenacity's two "jitter" waits actually produce (no network). Same seed for both."""
import random
from tenacity import RetryCallState, wait_exponential_jitter, wait_random_exponential
def waits(strategy, n: int = 6) -> list[float]:
random.seed(1)
state = RetryCallState(retry_object=None, fn=None, args=(), kwargs={}) # type: ignore[arg-type]
out = []
for attempt in range(1, n + 1):
state.attempt_number = attempt
out.append(round(strategy(state), 2))
return out
print("wait_random_exponential(multiplier=0.5, max=8): full jitter, uniform(0, 0.5 x 2^(n-1))")
print(" ", waits(wait_random_exponential(multiplier=0.5, max=8)))
print("wait_exponential_jitter(initial=0.5, max=8): 0.5 x 2^(n-1) + uniform(0, 1)")
print(" ", waits(wait_exponential_jitter(initial=0.5, max=8)))wait_random_exponential(multiplier=0.5, max=8): full jitter, uniform(0, 0.5 x 2^(n-1))
[0.07, 0.85, 1.53, 1.02, 3.96, 3.6]
wait_exponential_jitter(initial=0.5, max=8): 0.5 x 2^(n-1) + uniform(0, 1)
[0.63, 1.85, 2.76, 4.26, 8, 8]wait_random_exponential (full jitter) can wait anywhere from zero to the exponential value; wait_exponential_jitter always waits at least the exponential value, with up to one extra second. For de-synchronizing many clients, use wait_random_exponential.
8.3 Try it: a complete retry policy#
The policy below does everything Part 4 and Part 7 asked for: it retries only retryable errors, as decided by the classify() of 4.4 (billing 429s, 400s and your own bugs fail immediately, and the same predicate works for all four providers), waits what the server asked when it said (the header, or Gemini's RetryInfo, both through classify(...).retry_after), otherwise uses full-jitter backoff, has both an attempt limit and a total time budget (and stops at once if the server's requested wait would break the budget), logs before every sleep, and raises the original SDK exception at the end. The same policy runs sync and async. The SDK's own retries are off (max_retries=0), because this layer owns them (5.5).
"""Retries with tenacity, owned by YOUR code: only retryable errors (decided by classify(), so it works for
every provider), the server's Retry-After honoured, a total time budget, logging before each sleep, sync and async.
Uses llm_errors.py (section 4.4) from the same folder. The 'server' is a scripted mock."""
import asyncio
import logging
import random
import sys
import time
from typing import Any
import anthropic
import httpx2
import openai
from tenacity import (AsyncRetrying, RetryCallState, before_sleep_log, retry, retry_if_exception,
stop_after_attempt, stop_before_delay, wait_random_exponential)
from tenacity.wait import wait_base
from llm_errors import classify
logging.basicConfig(level=logging.WARNING, stream=sys.stdout, format=" [%(levelname)s] %(message)s")
log = logging.getLogger("llm.retry")
class wait_retry_after(wait_base):
"""Wait what the server asked (plus a little jitter); otherwise fall back to another wait strategy."""
def __init__(self, fallback: wait_base) -> None:
self.fallback = fallback
def __call__(self, retry_state: RetryCallState) -> float:
exc = retry_state.outcome.exception() if retry_state.outcome else None
hint = classify(exc).retry_after if exc is not None else None # header, or Gemini's RetryInfo in the body
if hint is not None:
return hint + random.uniform(0, 0.25) # "a minimum: wait at least that long"
return self.fallback(retry_state)
RETRY_POLICY: dict[str, Any] = dict(
retry=retry_if_exception(lambda e: classify(e).retryable), # billing 429s, 400s, bugs: no
wait=wait_retry_after(fallback=wait_random_exponential(multiplier=0.5, max=8)), # full jitter
stop=stop_after_attempt(4) | stop_before_delay(20), # attempts AND a total time budget
before_sleep=before_sleep_log(log, logging.WARNING),
reraise=True, # raise the real SDK error, not RetryError
)
def scripted(*responses: tuple[int, dict[str, str]]) -> tuple[httpx2.MockTransport, list[int]]:
"""A mock server that plays the given (status, headers) responses in order, then succeeds."""
calls: list[int] = []
def handler(req: httpx2.Request) -> httpx2.Response:
calls.append(1)
if len(calls) <= len(responses):
status, headers = responses[len(calls) - 1]
code = headers.pop("_code", {429: "slow_down", 400: None, 503: "server_is_overloaded"}.get(status, "server_error"))
return httpx2.Response(status, headers=headers, json={"error": {
"message": "mock failure", "type": "error", "param": None, "code": code}})
return httpx2.Response(200, json={"id": "resp_1", "object": "response", "status": "completed",
"model": "gpt-6-luna", "output": [{"type": "message", "id": "m1", "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": "Hello!", "annotations": []}]}]})
return httpx2.MockTransport(handler), calls
def make_client(transport: httpx2.MockTransport) -> openai.OpenAI:
# max_retries=0: tenacity owns retries. Leaving the SDK's 2 on would make 4 x 3 = 12 attempts.
return openai.OpenAI(api_key="sk-test", max_retries=0, http_client=httpx2.Client(transport=transport))
def scenario(title: str, *responses: tuple[int, dict[str, str]]) -> None:
transport, calls = scripted(*responses)
client = make_client(transport)
@retry(**RETRY_POLICY)
def ask(prompt: str) -> str:
return client.responses.create(model="gpt-6-luna", input=prompt).output_text
print(title)
start = time.monotonic()
try:
print(f" -> {ask('Hi')!r} after {len(calls)} attempts, {time.monotonic() - start:.1f} s")
except openai.APIStatusError as e:
print(f" -> gave up: {type(e).__name__} {e.status_code} code={e.code!r} after {len(calls)} attempts,"
f" {time.monotonic() - start:.1f} s")
random.seed(3)
scenario("1. 429 with retry-after: 1, then 503, then success",
(429, {"retry-after": "1"}), (503, {}))
scenario("2. 429 credit_balance_exhausted (never retried)", (429, {"_code": "credit_balance_exhausted"}))
scenario("3. 429 asking for 121 s: over our 20 s budget, so stop now", (429, {"retry-after": "121"}))
scenario("4. 400 (a bug in our request: never retried)", (400, {}))
async def async_scenario() -> None:
transport, calls = scripted((503, {}), (503, {}))
client = openai.AsyncOpenAI(api_key="sk-test", max_retries=0,
http_client=httpx2.AsyncClient(transport=transport))
print("5. async: two 503s, then success")
resp: Any = None
async for attempt in AsyncRetrying(**RETRY_POLICY): # the same policy object works for async
with attempt:
resp = await client.responses.create(model="gpt-6-luna", input="Hi")
print(f" -> {resp.output_text!r} after {len(calls)} attempts")
asyncio.run(async_scenario())
# The same policy, unchanged, around the Anthropic SDK: classify() knows OverloadedError (529).
anthropic_calls: list[int] = []
def anthropic_handler(req: httpx2.Request) -> httpx2.Response:
anthropic_calls.append(1)
if len(anthropic_calls) == 1:
return httpx2.Response(529, json={"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}})
return httpx2.Response(200, json={"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
"content": [{"type": "text", "text": "Hello!"}], "stop_reason": "end_turn", "stop_sequence": None,
"usage": {"input_tokens": 8, "output_tokens": 3}})
claude = anthropic.Anthropic(api_key="sk-ant-test", max_retries=0,
http_client=httpx2.Client(transport=httpx2.MockTransport(anthropic_handler)))
@retry(**RETRY_POLICY)
def ask_claude() -> str:
return claude.messages.create(model="claude-haiku-5-5", max_tokens=50,
messages=[{"role": "user", "content": "Hi"}]).content[0].text # type: ignore[union-attr]
print("6. Anthropic 529 (OverloadedError, not an InternalServerError), then success: the same policy")
print(f" -> {ask_claude()!r} after {len(anthropic_calls)} attempts")1. 429 with retry-after: 1, then 503, then success
[WARNING] Retrying __main__.scenario.<locals>.ask in 1.06 seconds as it raised RateLimitError: Error code: 429 - mock failure.
[WARNING] Retrying __main__.scenario.<locals>.ask in 0.544 seconds as it raised InternalServerError: Error code: 503 - mock failure.
-> 'Hello!' after 3 attempts, 1.7 s
2. 429 credit_balance_exhausted (never retried)
-> gave up: RateLimitError 429 code='credit_balance_exhausted' after 1 attempts, 0.0 s
3. 429 asking for 121 s: over our 20 s budget, so stop now
-> gave up: RateLimitError 429 code='slow_down' after 1 attempts, 0.0 s
4. 400 (a bug in our request: never retried)
-> gave up: BadRequestError 400 code=None after 1 attempts, 0.0 s
5. async: two 503s, then success
[WARNING] Retrying <unknown> in 0.302 seconds as it raised InternalServerError: Error code: 503 - mock failure.
[WARNING] Retrying <unknown> in 0.626 seconds as it raised InternalServerError: Error code: 503 - mock failure.
-> 'Hello!' after 3 attempts
6. Anthropic 529 (OverloadedError, not an InternalServerError), then success: the same policy
[WARNING] Retrying __main__.ask_claude in 0.0328 seconds as it raised OverloadedError: Error code: 529 - {'type': 'error', 'error': {'type': 'overloaded_error', 'message': 'Overloaded'}}.
-> 'Hello!' after 2 attemptsPoints to notice:
- Scenario 1 waited 1.06 s (the server's
retry-after: 1plus jitter), then 0.54 s (full jitter, since the 503 had no hint). - Scenario 3 failed in 0.0 s:
stop_before_delay(20)saw that the next sleep (121 s) would overrun the budget and stopped before sleeping. Withstop_after_delay, it would have slept for two minutes first. reraise=Trueis why every "gave up" line shows the realRateLimitErrororBadRequestError, withe.codeintact.- Scenario 6 runs the very same
RETRY_POLICYaround the Anthropic SDK: a 529 raisesOverloadedError, which is not anInternalServerError, and the policy still retries it, because it asksclassify()rather than listing exception classes. A hand-writtenis_retryablefor one SDK would not have known. tenacityhas no built-in wait that readsRetry-After:wait_retry_afteris the custom piece. It's await_basesubclass (so it can be combined with+like the built-ins) whose__call__reads the failed attempt's exception fromretry_state.outcome.- For async,
AsyncRetryingtakes the same arguments and sleeps withasyncio.sleep, so other tasks keep running while one waits. The logged function name is<unknown>because the loop form wraps a block, not a function.
8.4 Which approach, when#
| Situation | Use |
|---|---|
| A script, a prototype, low traffic | The SDK's built-in retries. For Gemini generate_content, add HttpRetryOptions |
You need billing-aware decisions, a deadline, a Retry-After cap, logging, one policy for several providers |
tenacity with a classifier, SDK retries off (8.3) |
| Streaming | Neither: explicit restart, continue or resume logic (03.3, 7.5) |
| High concurrency, shared rate limits | A retry policy plus a shared rate limiter (9.5) so retries don't all compete for the same capacity (03.9) |
| A whole provider is down, not just one request | Fallbacks and circuit breakers: 13.5 previews them, 03.11 builds a simple fallback, Module 11C covers the system level |
You'd rather not depend on tenacity |
A plain loop is ~30 lines; 13.2 writes one, and it's easier to test with an injected clock |
Part 9: Rate limits in code#
Lesson 02.7, 6.4 explained the idea: providers limit tokens per minute as well as requests, so long contexts eat your limit fast, and on Anthropic cached input doesn't count. This part is the engineering: what exactly is limited on each provider, how to read where you stand, and how to stay under the limit before you get a 429.
9.1 What each provider limits#
As of November 2026 (all from the providers' rate-limit pages; check them for current values):
| OpenAI | Anthropic | |
|---|---|---|
| Dimensions | RPM, RPD, TPM, TPD, IPM (images per minute), audio minutes per minute; a separate batch queue limit | RPM, ITPM (input tokens per minute) and OTPM (output tokens per minute), per model class |
| Scope | "defined at the organization level and at the project level, not user level" | Organization, and optionally per workspace (never above the organization's) |
| How tokens are counted | "the maximum of max_tokens and the estimated number of tokens based on the character count of your request" |
ITPM counts uncached input (cache writes too); cache reads don't count "for most models"; "The max_tokens parameter does not factor into OTPM" |
| Algorithm | Not specified | A token bucket: "your capacity is continuously replenished up to your maximum limit, rather than being reset at fixed intervals" |
| Shared limits | Some models share one limit ("all calls to any model in the given 'shared limit' list will count towards" it); long-context requests have their own | Per model class (Opus, Sonnet and Haiku 5.5 have separate limits) |
| Failed requests count? | Yes: "unsuccessful requests contribute to your per-minute limit, so continuously resending a request won't work" | Not stated |
| Gemini | OpenRouter | |
|---|---|---|
| Dimensions | RPM, TPM (input), RPD; some models also IPM or TPD | Free (:free) models: 20 RPM, and 50 requests per day (1,000 per day once you've bought at least 10 credits). Paid models: "no platform-level request cap" |
| Scope | "applied per project, not per API key" | Account credits, per-key limits, budgets, and an in-flight spending budget |
| How tokens are counted | Input tokens | — (the underlying provider's limits still apply) |
| Algorithm | Per-minute and per-day windows; RPD "reset at midnight Pacific time"; spend-based limits on "a rolling 10-minute window" | — |
| Shared limits | Per model | — |
| Failed requests count? | Not stated | — |
9.2 Tiers, and finding your own limits#
Limits rise automatically as you spend. As of November 2026:
| Provider | Tiers and how you move up |
|---|---|
| OpenAI | Free (an allowed geography; $100 a month usage limit), Build ($5 in total credit purchases; $500 a month), Launch ($100; $5,000 a month), Grow ($500; $200,000 a month) |
| Anthropic | Evaluation (new organizations, "limits below the standard limits"), Start (monthly spend cap $500), Build ($1,000), Scale ($200,000), Custom (no monthly cap). For Claude Opus, Sonnet and Haiku 5.5 (each): Start 4,000 RPM / 2M ITPM / 400K OTPM; Build 10,000 / 5M / 1M; Scale 13,000 / 10M / 2M. Claude Fable models have lower limits (Start: 4,000 RPM / 500K ITPM / 100K OTPM; Build 10,000 / 1.5M / 300K; Scale 13,000 / 4M / 800K), and Fable 5.2 has its own limit, separate from the one that Fable 5.1 and Fable 5 share |
| Provider | Tiers and how you move up |
|---|---|
| Gemini | Free ("Active project or free trial"), Tier 1 (a linked billing account), Tier 2 ($100 paid and 3 days since the first payment), Tier 3 ($1,000 paid and 30 days). Spend-based limits per rolling 10 minutes: $10 on Tier 1, $200 on Tiers 2 and 3 |
| OpenRouter | No tiers for paid models; credit balance, key limits and budgets apply (3.5) |
Your actual numbers are per account and per model, and they change. Don't hard-code them from a table like this one; look them up:
- OpenAI: the limits page in your project settings in the platform dashboard, and the
x-ratelimit-limit-*headers on every response (9.3). - Anthropic: the Rate limits page in the Claude Console, the
anthropic-ratelimit-*-limitheaders, and, programmatically, the Rate Limits API, which reads your organization's and workspaces' configured limits (and sets workspace limits). - Gemini: your project's tier on the AI Studio projects page, and the per-model limits at aistudio.google.com/rate-limit. There are no rate-limit headers.
- OpenRouter:
GET https://openrouter.ai/api/v1/keywith your key returns the key'slimit,limit_remaining,usage(also daily, weekly and monthly),is_free_tier, itsbudgetsand, for free models,free_model_daily_requests(used,limit,remaining).
9.3 Rate-limit headers#
Two of the four providers tell you on every response how much of each limit is left:
| Provider | Headers (as of November 2026) | Reset format |
|---|---|---|
| OpenAI | x-ratelimit-limit-requests, x-ratelimit-remaining-requests, x-ratelimit-reset-requests, the same three for -tokens, and, "when a project-scoped token limit applies", x-ratelimit-limit-project-tokens, x-ratelimit-remaining-project-tokens, x-ratelimit-reset-project-tokens |
A duration: 1s, 6m0s, 20ms |
| Anthropic | anthropic-ratelimit-{requests,tokens,input-tokens,output-tokens}-{limit,remaining,reset}; Priority Tier adds anthropic-priority-{input,output}-tokens-{limit,remaining,reset} |
An RFC 3339 timestamp, when the bucket is "fully replenished" |
| Provider | Headers (as of November 2026) | Reset format |
|---|---|---|
| Gemini | None documented | — |
| OpenRouter | None on successful responses; X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset only on OpenRouter's own platform-limit 429s |
Not documented |
Anthropic also sends anthropic-workspace-id on responses: the ID of the workspace your key resolved to, useful when several workspaces have their own limits and you wonder which one a 429 counted against.
ratelimit_headers.py normalizes all of them into one shape, and tightest() tells you which bucket is closest to empty:
"""ratelimit_headers.py: one normalized view of each provider's rate-limit headers."""
import re
from collections.abc import Mapping
from dataclasses import dataclass, field
from datetime import datetime, timezone
@dataclass
class Bucket:
limit: int | None = None
remaining: int | None = None
reset_in_s: float | None = None # seconds until fully replenished (None if unknown)
@dataclass
class RateLimits:
provider: str
buckets: dict[str, Bucket] = field(default_factory=dict) # "requests", "tokens", "input-tokens", ...
raw_reset: dict[str, str] = field(default_factory=dict) # values we could not interpret
_DURATION = re.compile(r"(\d+(?:\.\d+)?)(ms|h|m|s)")
_UNITS = {"ms": 0.001, "s": 1.0, "m": 60.0, "h": 3600.0}
def parse_openai_duration(value: str) -> float | None:
"""OpenAI resets look like "1s", "6m0s", "20ms", "1h2m3.5s"."""
parts = _DURATION.findall(value)
if not parts or "".join(n + u for n, u in parts) != value.strip():
return None
return sum(float(n) * _UNITS[u] for n, u in parts)
def _int(value: str | None) -> int | None:
try:
return int(float(value)) if value is not None else None
except ValueError:
return None
def parse_rate_limits(provider: str, headers: Mapping[str, str], now: datetime | None = None) -> RateLimits:
h = {k.lower(): v for k, v in headers.items()}
now = now or datetime.now(timezone.utc)
out = RateLimits(provider)
if provider in ("openai", "openrouter"):
# OpenAI: x-ratelimit-{limit,remaining,reset}-{requests,tokens,project-tokens}
# OpenRouter: X-RateLimit-{Limit,Remaining,Reset}, only on its own 429s (reset format undocumented)
names = ["requests", "tokens", "project-tokens"] if provider == "openai" else [""]
for name in names:
suffix = f"-{name}" if name else ""
limit, remaining = h.get(f"x-ratelimit-limit{suffix}"), h.get(f"x-ratelimit-remaining{suffix}")
reset = h.get(f"x-ratelimit-reset{suffix}")
if limit is None and remaining is None and reset is None:
continue
seconds = parse_openai_duration(reset) if (reset and provider == "openai") else None
if reset and seconds is None:
out.raw_reset[name or "requests"] = reset
out.buckets[name or "requests"] = Bucket(_int(limit), _int(remaining), seconds)
elif provider == "anthropic":
# anthropic-ratelimit-{requests,tokens,input-tokens,output-tokens}-{limit,remaining,reset}; reset is RFC 3339
for name in ("requests", "tokens", "input-tokens", "output-tokens"):
prefix = f"anthropic-ratelimit-{name}-"
if not any(k.startswith(prefix) for k in h):
continue
seconds = None
if reset := h.get(prefix + "reset"):
try:
seconds = max(0.0, (datetime.fromisoformat(reset.replace("Z", "+00:00")) - now).total_seconds())
except ValueError:
out.raw_reset[name] = reset
out.buckets[name] = Bucket(_int(h.get(prefix + "limit")), _int(h.get(prefix + "remaining")), seconds)
# Gemini: no rate-limit headers are documented, so there is nothing to parse.
return out
def tightest(limits: RateLimits) -> tuple[str, float] | None:
"""The bucket closest to empty, as (name, fraction left). Use it to slow down BEFORE a 429."""
fractions = [(name, b.remaining / b.limit) for name, b in limits.buckets.items()
if b.limit and b.remaining is not None]
return min(fractions, key=lambda x: x[1]) if fractions else None
def describe(limits: RateLimits) -> str:
if not limits.buckets:
return f"{limits.provider:<10} (no rate-limit headers)"
lines = []
for name, b in limits.buckets.items():
reset = f"{b.reset_in_s:g} s" if b.reset_in_s is not None else f"raw {limits.raw_reset.get(name)!r}"
lines.append(f"{limits.provider:<10} {name:<15} {b.remaining:>9,} of {b.limit:>9,} left, resets in {reset}")
t = tightest(limits)
if t:
lines.append(f"{'':<10} tightest: {t[0]} ({t[1]:.0%} left)")
return "\n".join(lines)The headers come from the raw response: .with_raw_response on openai and anthropic (03.1, 8.5), response.sdk_http_response.headers on Gemini, and e.response.headers on a 429 exception. The mock servers below send the real header names with made-up values:
"""Read rate-limit headers through with_raw_response, from mock servers that send the documented
header names (values made up), and normalize them with ratelimit_headers.py."""
from datetime import datetime, timezone
import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import types
from ratelimit_headers import describe, parse_rate_limits
NOW = datetime.now(timezone.utc).replace(microsecond=0)
OPENAI_HEADERS = {"x-request-id": "req_9c1", "x-ratelimit-limit-requests": "10000", "x-ratelimit-remaining-requests": "9998",
"x-ratelimit-reset-requests": "12ms", "x-ratelimit-limit-tokens": "4000000",
"x-ratelimit-remaining-tokens": "3984510", "x-ratelimit-reset-tokens": "232ms",
"x-ratelimit-limit-project-tokens": "1000000", "x-ratelimit-remaining-project-tokens": "120000",
"x-ratelimit-reset-project-tokens": "6m0s"}
in_20s = NOW.timestamp() + 20
ANTHROPIC_HEADERS = {"request-id": "req_011CRate", "anthropic-ratelimit-requests-limit": "4000",
"anthropic-ratelimit-requests-remaining": "3999",
"anthropic-ratelimit-requests-reset": datetime.fromtimestamp(NOW.timestamp() + 1, timezone.utc).isoformat().replace("+00:00", "Z"),
"anthropic-ratelimit-input-tokens-limit": "2000000", "anthropic-ratelimit-input-tokens-remaining": "1987000",
"anthropic-ratelimit-input-tokens-reset": datetime.fromtimestamp(in_20s, timezone.utc).isoformat().replace("+00:00", "Z"),
"anthropic-ratelimit-output-tokens-limit": "400000", "anthropic-ratelimit-output-tokens-remaining": "399000",
"anthropic-ratelimit-output-tokens-reset": datetime.fromtimestamp(NOW.timestamp() + 2, timezone.utc).isoformat().replace("+00:00", "Z")}
RESPONSE = {"id": "resp_1", "object": "response", "status": "completed", "model": "gpt-6-luna", "output": []}
MESSAGE = {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-haiku-5-5", "content": [],
"stop_reason": "end_turn", "stop_sequence": None, "usage": {"input_tokens": 9, "output_tokens": 1}}
oai = openai.OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(
lambda r: httpx2.Response(200, json=RESPONSE, headers=OPENAI_HEADERS))))
raw = oai.responses.with_raw_response.create(model="gpt-6-luna", input="Hi")
print(describe(parse_rate_limits("openai", raw.headers)))
claude = anthropic.Anthropic(api_key="sk-ant-test", http_client=httpx2.Client(transport=httpx2.MockTransport(
lambda r: httpx2.Response(200, json=MESSAGE, headers=ANTHROPIC_HEADERS))))
raw_msg = claude.messages.with_raw_response.create(model="claude-haiku-5-5", max_tokens=50,
messages=[{"role": "user", "content": "Hi"}])
print(describe(parse_rate_limits("anthropic", raw_msg.headers, now=NOW)))
gem = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(httpx_client=httpx.Client(
transport=httpx.MockTransport(lambda r: httpx.Response(200, json={"candidates": []})))))
g = gem.models.generate_content(model="gemini-3.8-flash", contents="Hi")
print(describe(parse_rate_limits("gemini", dict(g.sdk_http_response.headers or {}) if g.sdk_http_response else {})))
# OpenRouter sends X-RateLimit-* only on its own 429s, so read them from the exception's response
router = openai.OpenAI(api_key="sk-or-test", base_url="https://openrouter.ai/api/v1", max_retries=0,
http_client=httpx2.Client(transport=httpx2.MockTransport(lambda r: httpx2.Response(
429, json={"error": {"code": 429, "message": "Rate limit exceeded",
"metadata": {"error_type": "rate_limit_exceeded"}}},
headers={"X-RateLimit-Limit": "20", "X-RateLimit-Remaining": "0",
"X-RateLimit-Reset": "1793786460000"}))))
try:
router.chat.completions.create(model="meta-llama/llama-3.3-70b-instruct:free",
messages=[{"role": "user", "content": "Hi"}])
except openai.RateLimitError as e:
print(describe(parse_rate_limits("openrouter", e.response.headers)))openai requests 9,998 of 10,000 left, resets in 0.012 s
openai tokens 3,984,510 of 4,000,000 left, resets in 0.232 s
openai project-tokens 120,000 of 1,000,000 left, resets in 360 s
tightest: project-tokens (12% left)
anthropic requests 3,999 of 4,000 left, resets in 1 s
anthropic input-tokens 1,987,000 of 2,000,000 left, resets in 20 s
anthropic output-tokens 399,000 of 400,000 left, resets in 2 s
tightest: input-tokens (99% left)
gemini (no rate-limit headers)
openrouter requests 0 of 20 left, resets in raw '1793786460000'
tightest: requests (0% left)In this made-up example the OpenAI request and token buckets are nearly full, but the project token limit is down to 12%, the bucket that would cause the next 429. On OpenRouter the reset value can't be interpreted (its format isn't documented), so the parser keeps the raw string instead of guessing.
What to do with the numbers:
- Slow down before the 429: when
tightest()drops below, say, 10%, pause new low-priority work or lower your concurrency (03.9). - Log them with each call (03.10): a graph of
remainingover a day shows when you'll need a higher tier long before users see errors. - Don't treat them as a reservation system. Many processes share one account's limits, and the headers describe the moment your response was sent.
9.4 Ramp-up and acceleration limits#
Providers also limit how fast your traffic may grow:
- OpenAI: "As a rule of thumb, once your traffic reaches 1 million input tokens per minute (TPM), increase it by no more than 50% every 15 minutes." Growing too fast gets a 429 with
code: slow_down(3.2). - Anthropic: "You might also encounter 429 errors because of acceleration limits on the API if your organization has a sharp increase in usage. To avoid hitting acceleration limits, increase your traffic gradually and maintain consistent usage patterns."
So a launch, a backfill job or a marketing email that multiplies your traffic in minutes can fail even far below your tier's limits. Ramp batch jobs up gradually (start at a fraction of the target concurrency and raise it every few minutes), use the Batch APIs for bulk work (03.9), and talk to the provider before a planned spike.
9.5 A client-side rate limiter#
Retrying after a 429 is the reactive half. The proactive half is to not send requests you know will be rejected. A client-side rate limiter keeps its own model of your limits and makes callers wait their turn. It uses the same idea as Anthropic's server-side limiter, a token bucket: a bucket holds up to a limit's worth of capacity, each request takes some out, and the bucket refills continuously at the limit's rate. LLM calls need two buckets, one for requests and one for tokens, and a request may go only when both have room.
Tokens add a twist: you don't know how many a request uses until it's finished. So the limiter reserves an estimate before sending (input size plus the output cap: deliberately pessimistic) and settles afterwards with the real number from usage, giving back what it over-reserved:
sequenceDiagram
participant Task as Your task
participant RL as RateLimiter
participant API as Provider
Task->>RL: acquire(estimate 2000 tokens)
Note over RL: waits until both buckets have room: 1 request and 2000 tokens (burst_s caps how full they start)
RL-->>Task: go
Task->>API: request
API-->>Task: 200 with usage 1300 tokens
Task->>RL: settle(2000, 1300)
Note over RL: 700 tokens go back into the bucket
Task->>API: another request
API-->>Task: 429 with retry-after 30
Task->>RL: pause(30)
Note over RL: every task waits, not only this one"""rate_limiter.py: a client-side limiter with two token buckets, requests and tokens.
Reserve an ESTIMATE before each call, then settle with the real usage afterwards.
burst_s caps how much can go out at once: the default (60 s) allows a whole minute's budget in the first
instant, burst_s=1 spreads it out as providers that enforce a minute limit over shorter windows expect."""
import asyncio
import math
import time
from collections.abc import Awaitable, Callable
class TokenBucket:
"""Holds up to `capacity` units and refills continuously at `per_second` (like Anthropic's limiter)."""
def __init__(self, capacity: float, per_second: float, now: float) -> None:
self.capacity, self.per_second = capacity, per_second
self.level, self.updated = capacity, now
def _refill(self, now: float) -> None:
self.level = min(self.capacity, self.level + (now - self.updated) * self.per_second)
self.updated = now
def seconds_until(self, amount: float, now: float) -> float:
self._refill(now)
missing = amount - self.level
return 0.0 if missing <= 1e-6 else missing / self.per_second # tolerance: float rounding
def take(self, amount: float, now: float) -> None:
self._refill(now)
self.level -= amount # may go negative: that's debt, repaid by refilling
def give_back(self, amount: float, now: float) -> None:
self._refill(now)
self.level = min(self.capacity, self.level + amount)
class RateLimiter:
def __init__(self, rpm: int, tpm: int, *, burst_s: float = 60.0, clock: Callable[[], float] = time.monotonic,
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep) -> None:
if burst_s <= 0:
raise ValueError("burst_s must be positive")
self.rpm, self.tpm = rpm, tpm
self.clock, self.sleep = clock, sleep
now = clock()
# Capacity = `burst_s` seconds' worth of each limit. The refill rate stays rpm/60 and tpm/60, so only
# the size of an opening burst changes, never the sustained rate. burst_s=60 is the original behaviour.
self.requests = TokenBucket(max(1.0, rpm * burst_s / 60), rpm / 60, now)
self.tokens = TokenBucket(tpm * burst_s / 60, tpm / 60, now)
self.paused_until = 0.0
self._lock = asyncio.Lock() # one waiter at a time keeps the order fair
async def acquire(self, estimated_tokens: int) -> None:
if estimated_tokens > self.tpm:
raise ValueError(f"one request ({estimated_tokens} tokens) is bigger than the whole per-minute limit")
# A request bigger than a short burst waits for a full bucket, then goes into debt (see take()).
needed = min(estimated_tokens, self.tokens.capacity)
async with self._lock:
while True:
now = self.clock()
wait = max(self.paused_until - now,
self.requests.seconds_until(1, now),
self.tokens.seconds_until(needed, now))
if wait <= 0:
self.requests.take(1, now)
self.tokens.take(estimated_tokens, now)
return
await self.sleep(wait)
def settle(self, estimated_tokens: int, actual_tokens: int | None) -> None:
"""After the call: return what we over-reserved, or pay the extra. Unknown usage: keep the estimate."""
if actual_tokens is None:
return
now = self.clock()
if actual_tokens < estimated_tokens:
self.tokens.give_back(estimated_tokens - actual_tokens, now)
else:
self.tokens.take(actual_tokens - estimated_tokens, now)
def pause(self, seconds: float) -> None:
"""A 429 told us to wait: hold back EVERY caller, not just the one that got the error."""
self.paused_until = max(self.paused_until, self.clock() + seconds)
def estimate_tokens(prompt_chars: int, max_output_tokens: int) -> int:
"""A deliberately pessimistic pre-flight estimate: input at ~4 characters per token, plus the output cap.
Providers count differently (section 9.1); settle() corrects the estimate from the real usage."""
return math.ceil(prompt_chars / 4) + max_output_tokensTo see it work without waiting minutes or calling anyone, the simulation runs it on a virtual clock (sleeping just moves the clock forward): 40 requests against 600 RPM and 20,000 TPM, each estimated at 2,000 tokens but really using 1,300. A second part then shows the burst_s control, explained below:
"""Simulate rate_limiter.py on a virtual clock (no network, no real waiting): 40 requests against
limits of 600 RPM and 20,000 TPM. Each request is estimated at 2,000 tokens but really uses 1,300."""
import asyncio
from rate_limiter import RateLimiter, estimate_tokens
class VirtualClock:
def __init__(self) -> None:
self.now = 0.0
def __call__(self) -> float:
return self.now
async def sleep(self, seconds: float) -> None:
self.now += seconds
async def run(settle: bool, pause_at: int | None = None) -> float:
clock = VirtualClock()
limiter = RateLimiter(rpm=600, tpm=20_000, clock=clock, sleep=clock.sleep)
for i in range(40):
est = estimate_tokens(prompt_chars=4_000, max_output_tokens=1_000) # 1,000 + 1,000
await limiter.acquire(est)
actual = 1_000 + 300 # what usage reports
if settle:
limiter.settle(est, actual)
if i == pause_at:
limiter.pause(30) # a 429 with retry-after: 30 arrived
return clock.now
async def main() -> None:
print("estimate per request:", estimate_tokens(4_000, 1_000), "tokens; real usage: 1300")
print(f"without settle(): 40 requests sent by t = {await run(settle=False):6.1f} s")
print(f"with settle(): 40 requests sent by t = {await run(settle=True):6.1f} s")
print(f"with settle() + early 429: 40 requests sent by t = {await run(settle=True, pause_at=5):6.1f} s")
print("ideal (52,000 real tokens at 20,000/min, first 20,000 free):", round((52_000 - 20_000) / (20_000 / 60), 1), "s")
async def first_second(burst_s: float) -> tuple[int, float]:
"""1,000 requests against 600 RPM: how many leave in the first second, and when does the last one leave?"""
clock = VirtualClock()
limiter = RateLimiter(rpm=600, tpm=10_000_000, burst_s=burst_s, clock=clock, sleep=clock.sleep)
early = 0
for _ in range(1_000):
await limiter.acquire(10)
early += clock.now <= 1.0
return early, clock.now
async def burst_demo() -> None:
print("\nburst control: 1,000 requests against 600 RPM")
for burst_s in (60.0, 5.0, 1.0):
early, last = await first_second(burst_s)
label = "default" if burst_s == 60.0 else " "
print(f" burst_s={burst_s:>4} {label}: {early:>3} requests in the first second, last one sent at t = {last:5.1f} s")
asyncio.run(main())
asyncio.run(burst_demo())estimate per request: 2000 tokens; real usage: 1300
without settle(): 40 requests sent by t = 180.0 s
with settle(): 40 requests sent by t = 98.1 s
with settle() + early 429: 40 requests sent by t = 104.7 s
ideal (52,000 real tokens at 20,000/min, first 20,000 free): 96.0 s
burst control: 1,000 requests against 600 RPM
burst_s=60.0 default: 610 requests in the first second, last one sent at t = 40.0 s
burst_s= 5.0 : 60 requests in the first second, last one sent at t = 95.0 s
burst_s= 1.0 : 20 requests in the first second, last one sent at t = 99.0 s- Without
settle()the limiter believes each request used 2,000 tokens, so it's needlessly slow: 180 s. - With
settle()it finishes about 2% behind the ideal 96 s, the fastest possible rate that never exceeds the limit. - An early 429 with
retry-after: 30paused every caller, and cost only about 7 seconds overall, because the bucket kept refilling during the pause. burst_sshrinks the opening burst, not the sustained rate. Both buckets start full, and by default (burst_s=60) a bucket holds a whole minute's budget, so 600 RPM lets about 600 requests leave in the first instant (610 in the first second above). Anthropic's rate-limit page warns that providers may enforce a minute limit over shorter windows: "a rate of 60 requests per minute (RPM) might be enforced as 1 request per second. Short bursts of requests can exceed the limit and trigger rate limit errors." Withburst_s=1the bucket holds one second's worth, 10 requests, and only 20 leave in the first second (the 10 in the bucket plus 10 refilled). The refill rate is untouched, so the long-run speed is the same 600 RPM; the last of the 1,000 requests just leaves later (99 s instead of 40 s), because nothing was front-loaded. A request bigger than the short burst (a 2,000-token reservation against a 1-second token bucket of 1,000) waits for a full bucket and then goes into debt, which refilling repays, so it is delayed but never stuck.
How to use it in a real app:
- One limiter per provider account and model limit, shared by every task in the process (an
asyncio.Lockinside keeps it fair). The concurrency patterns that drive it (TaskGroup, semaphores) are in 03.9. - Set it a little below your real limit (90% is common): other processes, retries and the provider's own counting all take some of the headroom.
- Pick
burst_sfor your provider. Leave the default (60) for a script that sends a few requests, and useburst_s=1(or 5) when many concurrent tasks start together and the provider is strict about short windows. The concurrent tasks of 03.9 are exactly that situation. - Model your provider's rule. For Anthropic, use separate input and output buckets (ITPM and OTPM) and settle each from
usage.input_tokens(uncached) andusage.output_tokens; for OpenAI, reserve at least the output cap, since that's what TPM counts (9.1). Exact token counting before the call is in 03.7. - On a 429, call
pause()with the server'sRetry-After, then retry through the limiter. - If usage is unknown (a failed or broken stream),
settle(estimate, None)keeps the estimate: the safe assumption. - Several processes or machines? A per-process limiter can't see the others. Divide the limit between them, or move the bucket into shared storage such as Redis, or let a gateway enforce it (Module 11C).
Part 10: Errors that arrive as HTTP 200#
Deep-dive
10.1 The catalogue, per provider#
A 200 OK only says the HTTP exchange worked. Module 02 explained what the stop reasons mean (02.5, 4.5), how to handle truncation (02.5, 4.6) and how refusals show up (02.10, 14.3). Here they are as error handling: everything a 200 can carry that your code must not treat as a usable answer (as of November 2026). The status and finish-reason values come from the pinned SDKs' types and the providers' API references; where only the structure of the API implies a case, and no provider documents it, the cell says so:
| Problem | OpenAI Responses | OpenAI / OpenRouter Chat Completions | Anthropic Messages |
|---|---|---|---|
| Truncated at the output cap | status: "incomplete", incomplete_details.reason: "max_output_tokens" |
finish_reason: "length" |
stop_reason: "max_tokens" |
| No visible text (budget spent thinking) ¹ | The same, with only a reasoning item |
length with empty content |
max_tokens with only thinking blocks |
| Context window filled mid-answer | Not documented as a separate case ² | Not documented as a separate case ² | stop_reason: "model_context_window_exceeded" |
| Refusal | A content part with type: "refusal" |
message.refusal set |
stop_reason: "refusal", with stop_details (category: cyber, bio, frontier_llm, reasoning_extraction, general_harms; an explanation; and, on requests that set fallbacks, maybe a recommended_model). Some are billed (10.4) |
| Safety block | incomplete, reason content_filter |
finish_reason: "content_filter" (OpenRouter keeps the original in native_finish_reason) |
— |
| Paused or needs a follow-up | — | — | stop_reason: "pause_turn" (send the response back unchanged to continue, 03.5, 5.4) |
| Not finished yet, or cancelled | status: "queued" or "in_progress" (background mode, 03.9); status: "cancelled" |
— | — |
| An error inside the 200 | status: "failed" with error.code (a closed set mixing transient codes such as server_error, rate_limit_exceeded, vector_store_timeout with permanent ones such as invalid_prompt, bio_policy, image_*) |
OpenRouter: a body with only error and no choices (error.metadata.error_type, e.g. provider_unavailable); mid-stream finish_reason: "error" |
Stream error event (03.3) |
| Other abnormal endings | incomplete reasons max_messages, steered |
— | — |
| Problem | Gemini generate_content |
Gemini Interactions |
|---|---|---|
| Truncated at the output cap | finish_reason: MAX_TOKENS |
status: "incomplete" |
| No visible text (budget spent thinking) ¹ | MAX_TOKENS with only thought parts |
incomplete |
| Context window filled mid-answer | Not documented as a separate case ² | Not documented as a separate case ² |
| Refusal | — (a safety stop instead) | — |
| Safety block | Prompt: prompt_feedback.block_reason (SAFETY, BLOCKLIST, PROHIBITED_CONTENT, IMAGE_SAFETY, OTHER...) and no candidates. Answer: finish_reason SAFETY, PROHIBITED_CONTENT, BLOCKLIST, SPII, RECITATION, LANGUAGE, IMAGE_* |
Error codes such as safety, recitation, prohibited_content, content_blocked (3.4) |
| Paused or needs a follow-up | CONTINUATION ("stopped at the per-request token limit, not finished"): the SDK hides this by default, you only see it with automatic_continuation=False (03.3, 4.5b) |
requires_continuation, requires_action (a tool call) |
| Not finished yet, or cancelled | — | in_progress, queued; cancelled |
| An error inside the 200 | Stream error chunk | status: "failed" with errors[].code; stream error event |
| Other abnormal endings | OTHER, MALFORMED_FUNCTION_CALL, UNEXPECTED_TOOL_CALL, TOO_MANY_TOOL_CALLS, MISSING_THOUGHT_SIGNATURE, MALFORMED_RESPONSE... |
budget_exceeded, cancelled |
¹ Reasoning tokens count against the output cap (02.8, 5.1), so a cap spent thinking leaves no visible text. That is the structural consequence the fixtures in 10.3 use; check what your own models return rather than assuming it.
² Only Anthropic documents a distinct context-full stop reason. On the others, expect a length-type stop (length, MAX_TOKENS, incomplete) and check your input size first (02.7, 2.6). OpenAI Responses' incomplete_details.reason also has max_messages and steered, so a reason other than max_output_tokens is possible: don't assume.
10.2 check_response(): one typed outcome for every 200#
check_response() inspects any response object from the five API shapes and returns an Outcome with a status from one small enum. Your code then branches on outcome.status instead of on five providers' fields:
"""check_response.py: a "successful" HTTP 200 can still be a failure for your app.
check_response() turns any provider response into one typed Outcome before you use its text."""
import re
from dataclasses import dataclass
from enum import Enum
from typing import Any
class Status(str, Enum):
OK = "ok" # natural end: use it (and still validate it)
TOOL_CALL = "tool_call" # the model wants a tool run (lesson 03.5)
TRUNCATED = "truncated" # hit the output cap: never treat as complete
CONTEXT_FULL = "context_full" # the context window filled up mid-answer
REFUSED = "refused" # the model declined
BLOCKED = "blocked" # a safety system blocked the prompt or the answer
EMPTY = "empty" # "success" with no text (e.g. all budget spent thinking)
PAUSED = "paused" # Anthropic pause_turn: send it back to continue
FAILED = "failed" # an error inside the 200 (status failed, error body)
INCOMPLETE = "incomplete" # any other incomplete state
@dataclass
class Outcome:
status: Status
text: str
detail: str | None = None # the provider's own reason, for logs
error_code: str | None = None # set on FAILED: the provider's error code, so callers can tell transient from permanent
@property
def usable(self) -> bool:
return self.status in (Status.OK, Status.TOOL_CALL)
GEMINI_BLOCKED = {"SAFETY", "PROHIBITED_CONTENT", "BLOCKLIST", "SPII", "RECITATION", "IMAGE_SAFETY",
"IMAGE_PROHIBITED_CONTENT", "IMAGE_RECITATION", "LANGUAGE"}
# Codes inside a FAILED 200 that a later attempt can fix (OpenAI Responses `error.code`, OpenRouter `error_type`,
# Gemini Interactions `errors[].code`). Everything else on FAILED (invalid_prompt, bio_policy, image_*...) is permanent.
TRANSIENT_FAILED_CODES = {"server_error", "rate_limit_exceeded", "vector_store_timeout", "provider_unavailable",
"provider_overloaded", "timeout", "server_is_overloaded", "service_unavailable",
"deadline_exceeded", "api_error"}
def _name(value: Any) -> str | None:
"""Gemini enums print as FinishReason.STOP; we want 'STOP'."""
return None if value is None else str(getattr(value, "value", value))
def _family(resp: Any) -> set[str]:
"""Class names of the response and all its parents, with the SDKs' Beta/Parsed prefixes removed.
BetaMessage, ParsedMessage and ParsedBetaMessage all become "Message"; ParsedResponse becomes "Response"."""
return {re.sub(r"^(?:Parsed|Beta)+", "", c.__name__) for c in type(resp).__mro__}
def check_response(resp: Any) -> Outcome:
names = _family(resp) # the MRO, so subclasses and variants work too
if "Response" in names: # OpenAI / OpenRouter Responses (also .parse())
return _openai_responses(resp)
if "ChatCompletion" in names: # OpenAI / OpenRouter Chat Completions (also .parse())
return _chat(resp)
if "Message" in names: # Anthropic Messages, beta.messages, .parse()
return _anthropic(resp)
if "GenerateContentResponse" in names: # Gemini generate_content
return _gemini(resp)
if names & {"Interaction", "InteractionSseEventInteraction"}: # Gemini Interactions: the whole object, or the
return _interaction(resp) # terminal object of a stream (no output_text, dict errors)
raise TypeError(f"don't know how to check {type(resp).__name__}")
def _openai_responses(r: Any) -> Outcome:
text = r.output_text or ""
# Statuses: completed, failed, in_progress, cancelled, queued, incomplete. Only the first is a finished answer.
if r.status == "failed":
code = r.error.code if r.error else None
return Outcome(Status.FAILED, "", code, code)
if r.status == "cancelled": # someone cancelled it: any text is a half-written answer
return Outcome(Status.FAILED, text, "cancelled", "cancelled")
if r.status in ("queued", "in_progress"): # background mode (03.9): not finished, poll again
return Outcome(Status.INCOMPLETE, text, r.status)
for item in r.output:
if item.type == "message":
for part in item.content:
if part.type == "refusal":
return Outcome(Status.REFUSED, part.refusal, "refusal content part")
if r.status == "incomplete":
reason = r.incomplete_details.reason if r.incomplete_details else None
if reason == "content_filter":
return Outcome(Status.BLOCKED, text, reason)
if reason == "max_output_tokens":
return Outcome(Status.TRUNCATED if text else Status.EMPTY, text, reason)
return Outcome(Status.INCOMPLETE, text, reason)
if any(item.type == "function_call" for item in r.output):
return Outcome(Status.TOOL_CALL, text)
return Outcome(Status.OK, text) if text else Outcome(Status.EMPTY, "", r.status)
def _chat(r: Any) -> Outcome:
error = (r.model_extra or {}).get("error") # OpenRouter: 200 with an error body
if error or not r.choices:
meta = (error or {}).get("metadata") or {}
code = meta.get("error_type") or ((error or {}).get("code") and str(error["code"])) or None
return Outcome(Status.FAILED, "", str((error or {}).get("message", "no choices")), code)
choice = r.choices[0]
msg, finish = choice.message, choice.finish_reason
text = msg.content or ""
if getattr(msg, "refusal", None):
return Outcome(Status.REFUSED, msg.refusal, "message.refusal")
native = (choice.model_extra or {}).get("native_finish_reason") # OpenRouter keeps the original
if finish == "length":
return Outcome(Status.TRUNCATED if text else Status.EMPTY, text, native or finish)
if finish == "content_filter":
return Outcome(Status.BLOCKED, text, native or finish)
if finish == "error":
return Outcome(Status.FAILED, text, native or finish)
if finish in ("tool_calls", "function_call"):
return Outcome(Status.TOOL_CALL, text, finish)
return Outcome(Status.OK, text) if text else Outcome(Status.EMPTY, "", finish)
def _anthropic(m: Any) -> Outcome:
text = "".join(b.text for b in m.content if b.type == "text") # skip thinking blocks
reason = m.stop_reason
if reason == "refusal":
details = m.stop_details
category = details.category if details else None
detail = f"refusal/{category}"
# Only on requests that set `fallbacks` (beta): a model to retry on when the API skipped the fallback attempt.
# A typed field on BetaMessage, but only an "extra" on the stable Message in anthropic 2.4.0.
recommended = (getattr(details, "recommended_model", None)
or (details.model_extra or {}).get("recommended_model")) if details else None
if recommended:
detail += f" -> {recommended}"
return Outcome(Status.REFUSED, text, detail)
if reason == "max_tokens":
return Outcome(Status.TRUNCATED if text else Status.EMPTY, text, reason)
if reason == "model_context_window_exceeded":
return Outcome(Status.CONTEXT_FULL, text, reason)
if reason == "pause_turn":
return Outcome(Status.PAUSED, text, reason)
if reason == "tool_use":
return Outcome(Status.TOOL_CALL, text, reason)
return Outcome(Status.OK, text, reason) if text else Outcome(Status.EMPTY, "", reason)
def _gemini(g: Any) -> Outcome:
if g.prompt_feedback and g.prompt_feedback.block_reason:
return Outcome(Status.BLOCKED, "", f"prompt/{_name(g.prompt_feedback.block_reason)}")
if not g.candidates:
return Outcome(Status.EMPTY, "", "no candidates")
cand = g.candidates[0]
finish = _name(cand.finish_reason)
parts = cand.content.parts if cand.content and cand.content.parts else []
text = "".join(p.text for p in parts if p.text and not p.thought)
if finish in GEMINI_BLOCKED:
return Outcome(Status.BLOCKED, "", f"answer/{finish}") # don't show partial text
if finish == "MAX_TOKENS":
return Outcome(Status.TRUNCATED if text else Status.EMPTY, text, finish)
if any(p.function_call for p in parts):
return Outcome(Status.TOOL_CALL, text, finish)
if finish not in (None, "STOP"):
return Outcome(Status.INCOMPLETE, text, finish) # OTHER, MALFORMED_FUNCTION_CALL, ...
return Outcome(Status.OK, text, finish) if text else Outcome(Status.EMPTY, "", finish)
def _interaction_text(i: Any) -> str:
"""`Interaction.output_text`, or the same thing computed from `steps` for the stream's terminal object, which has none:
the trailing run of model_output text, skipping thought steps and stopping at the last user_input."""
text = getattr(i, "output_text", None)
if text is not None:
return text
parts: list[str] = []
for step in reversed(getattr(i, "steps", None) or []):
kind = getattr(step, "type", None)
if kind == "user_input":
break
if kind == "thought":
continue
if kind != "model_output":
if parts:
break
continue
stop = False
for item in reversed(getattr(step, "content", None) or []):
if getattr(item, "type", None) == "text":
parts.append(getattr(item, "text", None) or "")
elif parts:
stop = True
break
if stop:
break
return "".join(reversed(parts))
def _first_error(i: Any) -> tuple[str | None, str | None]:
"""(code, message) of `errors[0]`: an object on Interaction, a plain dict on the stream's terminal object."""
first = (getattr(i, "errors", None) or [None])[0]
if isinstance(first, dict):
return first.get("code"), first.get("message")
return getattr(first, "code", None), getattr(first, "message", None)
def _interaction(i: Any) -> Outcome:
text = _interaction_text(i)
status = _name(i.status)
if status == "completed":
return Outcome(Status.OK, text) if text else Outcome(Status.EMPTY, "", status)
if status == "requires_action":
return Outcome(Status.TOOL_CALL, text, status)
if status in ("failed", "cancelled"):
first_code, _ = _first_error(i) # the server's own diagnostic, when it recorded one
code = first_code or (status if status == "cancelled" else None)
return Outcome(Status.FAILED, text, f"{status}: {code}" if first_code else status, code)
return Outcome(Status.INCOMPLETE, text, status) # incomplete, budget_exceeded, requires_continuation...Choices worth copying:
- Dispatch on the class and its parents, not on one exact class name.
Response,ChatCompletion,Message,GenerateContentResponse,InteractionandInteractionSseEventInteractionare recognized wherever they appear in a response's class hierarchy, after removing the SDKs'BetaandParsedprefixes. Soclient.beta.messages.create()(aBetaMessage: Anthropic's own docs saymodel_context_window_exceededis typed only in the beta namespace),messages.parse()(ParsedMessage),responses.parse()(ParsedResponse) andchat.completions.parse()(ParsedChatCompletion) all work, and anything else still raisesTypeErrorinstead of being guessed at. - A streamed Interaction is accepted too. A Gemini Interactions stream does not end with an
Interaction: its last event carries anInteractionSseEventInteraction(interaction.completed), a sibling class with astatusandstepsbut nooutput_text, and witherrorsas plain dictionaries rather than objects.check_response()recognizes it as well: it rebuilds the text from the steps the way the SDK's ownoutput_textis built, and readserrors[0]whichever shape it has. So you can pass that terminal object to the same function and branch on the sameStatusvalues; lesson 03.11 does exactly that in its Interactions stream parser. One status stays outside the table on purpose:budget_exceededis reported asINCOMPLETE, because 03.8 has no rule about what a caller should do with it (03.11 treats it as a permanent error). - Not every
status: "completed"is the only good status. An OpenAI Responses object can becompleted,failed,in_progress,cancelled,queuedorincomplete(03.9's background mode polls exactly these). Only the first is a finished answer:cancelledisFAILED(its half-written text is kept intext, butusableisFalse), andqueuedandin_progressareINCOMPLETE. FAILEDcarries anerror_code, the provider's own code, so a caller can tell a transient failure (server_error,provider_unavailable) from a permanent one (invalid_prompt).TRANSIENT_FAILED_CODESlists the transient ones, andreliable_call()(13.2) retries only those.error_codeis the last field ofOutcomeand defaults toNone, so code that builds or unpacks anOutcomepositionally without it keeps working.- A refusal keeps the fallback hint. On Anthropic,
detailreadsrefusal/cyber, plus-> <model>when the response names arecommended_model(10.4). - Check the "worst" signals first: a refusal part wins over
status: "completed", and a Gemini safety stop discards partial text rather than showing a half-answer that was stopped for a reason. TRUNCATEDvsEMPTY: both are the output cap, but an empty one means the model spent everything on reasoning, so the fix is different (10.4).- Text is assembled by block type, skipping Anthropic
thinkingblocks and Gemini thought parts (02.8, 8.2). detailkeeps the provider's own reason for logs, so you can always see the raw value behind the normalized status.
10.3 Try it: 200s that aren't successes#
Every response below is HTTP 200, returned by a mock server from a documented response shape and parsed by the real SDK (except the two "stream end" rows, which build the SDK's streamed-Interaction class directly, because that object only exists at the end of a stream):
"""check_response() on HTTP 200 responses that are really failures. Each fixture is a documented
response shape, returned by a mock server and parsed by the real SDK."""
from typing import Any
import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import types
from google.genai.interactions import InteractionSseEventInteraction
from pydantic import BaseModel
from check_response import check_response
HI: Any = [{"role": "user", "content": "Hi"}]
def oai_responses(body: dict[str, Any]) -> Any:
base = {"id": "resp_1", "object": "response", "model": "gpt-6-luna", "output": []}
c = openai.OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(
lambda r: httpx2.Response(200, json={**base, **body}))))
return c.responses.create(model="gpt-6-luna", input="Hi")
def oai_parsed(body: dict[str, Any]) -> Any:
"""responses.parse(): returns a ParsedResponse, a subclass of Response."""
base = {"id": "resp_1", "object": "response", "model": "gpt-6-luna", "output": []}
c = openai.OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(
lambda r: httpx2.Response(200, json={**base, **body}))))
return c.responses.parse(model="gpt-6-luna", input="Hi", text_format=Answer)
def chat(body: dict[str, Any], openrouter: bool = False) -> Any:
c = openai.OpenAI(api_key="sk-test", base_url="https://openrouter.ai/api/v1" if openrouter else None,
http_client=httpx2.Client(transport=httpx2.MockTransport(lambda r: httpx2.Response(200, json=body))))
return c.chat.completions.create(model="openai/gpt-6-luna" if openrouter else "gpt-6-luna", messages=HI)
def choice(finish: str, content: str | None, **extra: Any) -> dict[str, Any]:
return {"id": "c1", "object": "chat.completion", "created": 0, "model": "gpt-6-luna",
"choices": [{"index": 0, "finish_reason": finish,
"message": {"role": "assistant", "content": content, **extra.pop("message", {})}, **extra}]}
class Answer(BaseModel):
city: str
def claude(stop: str, blocks: list[dict[str, Any]], *, beta: bool = False, parse: bool = False, **extra: Any) -> Any:
body = {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-haiku-5-5", "content": blocks,
"stop_reason": stop, "stop_sequence": None, "usage": {"input_tokens": 10, "output_tokens": 5}, **extra}
c = anthropic.Anthropic(api_key="sk-ant-test", http_client=httpx2.Client(transport=httpx2.MockTransport(
lambda r: httpx2.Response(200, json=body))))
if beta: # client.beta.messages: returns BetaMessage, where
return c.beta.messages.create(model="claude-haiku-5-5", max_tokens=1024, messages=HI) # some stop reasons live
if parse: # messages.parse(): returns ParsedMessage
return c.messages.parse(model="claude-haiku-5-5", max_tokens=1024, messages=HI, output_format=Answer)
return c.messages.create(model="claude-haiku-5-5", max_tokens=1024, messages=HI)
def gemini(body: dict[str, Any], interactions: bool = False) -> Any:
c = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(httpx_client=httpx.Client(
transport=httpx.MockTransport(lambda r: httpx.Response(200, json=body)))))
if interactions:
return c.interactions.create(model="gemini-3.8-flash", input="Hi")
return c.models.generate_content(model="gemini-3.8-flash", contents="Hi")
def sse_end(body: dict[str, Any]) -> Any:
"""The terminal object of an Interactions *stream* (the `interaction` inside `interaction.completed`). It is a different
class from `Interaction`: no `output_text`, and `errors` are plain dicts. Built directly, since no mock stream is needed."""
return InteractionSseEventInteraction.model_validate(body)
def msg_item(*parts: dict[str, Any]) -> dict[str, Any]:
return {"type": "message", "id": "m1", "role": "assistant", "status": "completed", "content": list(parts)}
TEXT = {"type": "output_text", "text": "Paris.", "annotations": []}
REASONING = {"type": "reasoning", "id": "rs_1", "summary": []}
THINKING = {"type": "thinking", "thinking": "Let me think...", "signature": "sig"}
CASES = [
("OpenAI Responses: completed", lambda: oai_responses({"status": "completed", "output": [msg_item(TEXT)]})),
("OpenAI Responses: ran out while reasoning", lambda: oai_responses({"status": "incomplete",
"incomplete_details": {"reason": "max_output_tokens"}, "output": [REASONING]})),
("OpenAI Responses: cancelled, half-written", lambda: oai_responses({"status": "cancelled",
"output": [msg_item(TEXT)]})),
("OpenAI Responses: queued (background mode)", lambda: oai_responses({"status": "queued"})),
("OpenAI Responses: in_progress", lambda: oai_responses({"status": "in_progress", "output": [msg_item(TEXT)]})),
("OpenAI Responses: failed, server_error", lambda: oai_responses({"status": "failed",
"error": {"code": "server_error", "message": "The server had an error."}})),
("OpenAI responses.parse(): ParsedResponse", lambda: oai_parsed({"status": "completed", "output": [msg_item(
{"type": "output_text", "text": '{"city": "Paris"}', "annotations": []})]})),
("OpenAI Responses: refusal part", lambda: oai_responses({"status": "completed", "output": [msg_item(
{"type": "refusal", "refusal": "I can't help with that."})]})),
("OpenAI Responses: content_filter", lambda: oai_responses({"status": "incomplete",
"incomplete_details": {"reason": "content_filter"}, "output": [msg_item(TEXT)]})),
("OpenAI Chat: length", lambda: chat(choice("length", "The capital of Fra"))),
("OpenAI Chat: refusal", lambda: chat(choice("stop", None, message={"refusal": "I can't help with that."}))),
("Anthropic: end_turn", lambda: claude("end_turn", [THINKING, {"type": "text", "text": "Paris."}])),
("Anthropic: max_tokens, only thinking", lambda: claude("max_tokens", [THINKING])),
("Anthropic: refusal", lambda: claude("refusal", [], stop_details={
"type": "refusal", "category": "cyber", "explanation": "Request declined by the safety classifier."})),
("Anthropic: model_context_window_exceeded", lambda: claude("model_context_window_exceeded",
[{"type": "text", "text": "Part one of the summ"}])),
("Anthropic beta: context window exceeded", lambda: claude("model_context_window_exceeded",
[{"type": "text", "text": "Part one of the summ"}], beta=True)),
("Anthropic beta: refusal + recommended_model", lambda: claude("refusal", [], beta=True, stop_details={
"type": "refusal", "category": "cyber", "explanation": "Declined.", "recommended_model": "claude-opus-5-5"})),
("Anthropic messages.parse(): ParsedMessage", lambda: claude("end_turn", [{"type": "text",
"text": '{"city": "Paris"}'}], parse=True)),
("Anthropic: pause_turn", lambda: claude("pause_turn", [])),
("Gemini: STOP", lambda: gemini({"candidates": [{"content": {"role": "model", "parts": [{"text": "Paris."}]},
"finishReason": "STOP"}]})),
("Gemini: prompt blocked", lambda: gemini({"promptFeedback": {"blockReason": "PROHIBITED_CONTENT"}})),
("Gemini: answer stopped for SAFETY", lambda: gemini({"candidates": [{"content": {"role": "model",
"parts": [{"text": "Step one is"}]}, "finishReason": "SAFETY"}]})),
("Gemini: MAX_TOKENS", lambda: gemini({"candidates": [{"content": {"role": "model",
"parts": [{"text": "The capital"}]}, "finishReason": "MAX_TOKENS"}]})),
("Gemini Interactions: incomplete", lambda: gemini({"id": "int_1", "status": "incomplete",
"steps": [{"type": "model_output", "content": [{"type": "text", "text": "The capital"}]}]}, interactions=True)),
("Gemini Interactions: failed, with an error", lambda: gemini({"id": "int_2", "status": "failed", "steps": [],
"errors": [{"code": "service_unavailable", "message": "Try again."}]}, interactions=True)),
("Gemini Interactions stream end: completed", lambda: sse_end({"id": "int_3", "status": "completed", "steps": [
{"type": "model_output", "content": [{"type": "text", "text": "Paris."}]}]})),
("Gemini Interactions stream end: failed", lambda: sse_end({"id": "int_4", "status": "failed", "steps": [],
"errors": [{"code": "service_unavailable", "message": "Try again."}]})),
("OpenRouter: 200 with an error body", lambda: chat({"error": {"code": 502, "message": "Provider returned error",
"metadata": {"error_type": "provider_unavailable"}}}, openrouter=True)),
("OpenRouter: content_filter (native SAFETY)", lambda: chat(choice("content_filter", "",
native_finish_reason="SAFETY"), openrouter=True)),
]
print(f"{'response (all HTTP 200)':<46} {'outcome':<13} {'usable':<7} detail")
usable = 0
for label, make in CASES:
o = check_response(make())
usable += o.usable
code = f" error_code={o.error_code}" if o.error_code else ""
print(f"{label:<46} {o.status.value:<13} {str(o.usable):<7} {o.detail}{code} {o.text[:20]!r}")
print(f"{usable} of {len(CASES)} are usable")response (all HTTP 200) outcome usable detail
OpenAI Responses: completed ok True None 'Paris.'
OpenAI Responses: ran out while reasoning empty False max_output_tokens ''
OpenAI Responses: cancelled, half-written failed False cancelled error_code=cancelled 'Paris.'
OpenAI Responses: queued (background mode) incomplete False queued ''
OpenAI Responses: in_progress incomplete False in_progress 'Paris.'
OpenAI Responses: failed, server_error failed False server_error error_code=server_error ''
OpenAI responses.parse(): ParsedResponse ok True None '{"city": "Paris"}'
OpenAI Responses: refusal part refused False refusal content part "I can't help with th"
OpenAI Responses: content_filter blocked False content_filter 'Paris.'
OpenAI Chat: length truncated False length 'The capital of Fra'
OpenAI Chat: refusal refused False message.refusal "I can't help with th"
Anthropic: end_turn ok True end_turn 'Paris.'
Anthropic: max_tokens, only thinking empty False max_tokens ''
Anthropic: refusal refused False refusal/cyber ''
Anthropic: model_context_window_exceeded context_full False model_context_window_exceeded 'Part one of the summ'
Anthropic beta: context window exceeded context_full False model_context_window_exceeded 'Part one of the summ'
Anthropic beta: refusal + recommended_model refused False refusal/cyber -> claude-opus-5-5 ''
Anthropic messages.parse(): ParsedMessage ok True end_turn '{"city": "Paris"}'
Anthropic: pause_turn paused False pause_turn ''
Gemini: STOP ok True STOP 'Paris.'
Gemini: prompt blocked blocked False prompt/PROHIBITED_CONTENT ''
Gemini: answer stopped for SAFETY blocked False answer/SAFETY ''
Gemini: MAX_TOKENS truncated False MAX_TOKENS 'The capital'
Gemini Interactions: incomplete incomplete False incomplete 'The capital'
Gemini Interactions: failed, with an error failed False failed: service_unavailable error_code=service_unavailable ''
Gemini Interactions stream end: completed ok True None 'Paris.'
Gemini Interactions stream end: failed failed False failed: service_unavailable error_code=service_unavailable ''
OpenRouter: 200 with an error body failed False Provider returned error error_code=provider_unavailable ''
OpenRouter: content_filter (native SAFETY) blocked False SAFETY ''
6 of 29 are usableOnly six of the 29 responses are usable (and two of those are .parse() results, whose text is JSON you still have to validate, 03.4); none of the other 23 raised an exception. Notice the rows that are easy to get wrong: a cancelled, queued or in_progress OpenAI response is not usable, and the Beta and Parsed classes are recognized instead of raising TypeError.
10.4 Retry or not: policies for outcomes#
Most of these outcomes should not be retried as-is: the same request will usually produce the same problem, and you pay for it every time.
| Outcome | Retry the same request? | What to do instead |
|---|---|---|
TRUNCATED |
No | Raise the output cap, ask for less, or continue in a new turn (02.5, 4.6). For structured output, re-run with a bigger cap; never repair JSON (03.4). A cut-off tool call (max_tokens while the model was writing a tool_use) is truncated too: never run it (03.5, 5.4) |
EMPTY (all budget spent reasoning) |
No | Raise the cap, or lower the reasoning effort (02.8) |
CONTEXT_FULL |
No | Trim or summarize the history, then send a new request (02.7 Part 4) |
REFUSED |
Not on the same model | Log the category, discard any partial output, show a helpful message. A refusal may be correct. On Anthropic, a fallback to another model is the documented recovery (the fallbacks parameter, beta, or your own retry), and some refusals are billed: see the box below. Elsewhere a fallback model is a product decision (02.9, 10.5) |
BLOCKED |
No | Log the block reason; tell the user the request can't be processed. Retrying a safety block can look like probing, and may be against the provider's usage policies (Module 12) |
PAUSED (Anthropic pause_turn) |
Not a retry: a continuation | Send the paused response back unchanged as the assistant turn, with the same tools and the container ID if present (03.5, 5.4) |
TOOL_CALL |
— | Run the tool and send the result (03.5) |
FAILED (error inside a 200) |
Only if the code is transient | Look at outcome.error_code: OpenAI server_error, rate_limit_exceeded, vector_store_timeout and OpenRouter provider_unavailable or provider_overloaded are worth a retry; invalid_prompt, bio_policy and image_* never are. reliable_call() does exactly this (13.2); a cancelled response is not retried |
INCOMPLETE (other reasons) |
Depends on the reason | Log it; decide per reason. For queued and in_progress (background mode) the answer is not wrong, just not ready: poll, don't resend (03.9) |
10.5 Provider sample: the same borderline request everywhere#
This provider sample sends one borderline request to all four providers, through the production call of Part 13, and checks each response with check_response(). It needs keys, or the local stand-in (03.1, 12.3):
# s10_5_refusal_provider.py: the same borderline request to all four providers, through reliable_call()
# (production_call.py, 13.2) and checked with check_response() (10.2). Same folder. Needs the four keys in .env.
import os
import anthropic
import httpx2
from dotenv import load_dotenv
from google import genai
from google.genai import types
from openai import OpenAI
from production_call import RetryPolicy, reliable_call
load_dotenv()
# Borderline on purpose: an owner locked out of their own home. A cautious classifier may hesitate.
PROMPT = "I'm locked out of my own flat and the locksmith can't come until tomorrow. How does a basic pin-tumbler lock get picked?"
POLICY = RetryPolicy(max_attempts=3, deadline_s=45, attempt_timeout_s=20)
# Clients are created once, with SDK retries off (reliable_call owns them) and explicit timeouts (6.1).
openai_client = OpenAI(max_retries=0, timeout=httpx2.Timeout(20.0, connect=5.0))
claude = anthropic.Anthropic(max_retries=0, timeout=httpx2.Timeout(20.0, connect=5.0))
gemini = genai.Client(http_options=types.HttpOptions(timeout=20_000)) # milliseconds
router = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"], max_retries=0,
default_headers={"HTTP-Referer": "https://example.com", "X-OpenRouter-Title": "Lesson 03.8"})
senders = {
"openai": lambda timeout, crid: openai_client.responses.create(
model="gpt-6-luna", input=PROMPT, max_output_tokens=400, timeout=timeout),
"anthropic": lambda timeout, crid: claude.messages.create(
model="claude-haiku-5-5", max_tokens=1024, timeout=timeout, messages=[{"role": "user", "content": PROMPT}]),
"gemini": lambda timeout, crid: gemini.models.generate_content(
model="gemini-3.8-flash", contents=PROMPT,
config=types.GenerateContentConfig(http_options=types.HttpOptions(timeout=int(timeout * 1000)))),
"openrouter": lambda timeout, crid: router.chat.completions.create(
model="anthropic/claude-haiku-5.5", max_tokens=400, timeout=timeout,
messages=[{"role": "user", "content": PROMPT}]),
}
for provider, send in senders.items():
result = reliable_call(send, policy=POLICY, on_event=lambda event: None) # quiet: we print our own line
if result.outcome is None: # the call itself failed
print(f"{provider:<10} no response: {result.failure.kind.value if result.failure else '?'}")
continue
outcome = result.outcome
print(f"{provider:<10} {outcome.status.value:<8} detail={outcome.detail!r:<22} text={outcome.text[:60]!r}")openai ok detail=None text='Lock picking works by lifting each pin in a pin-tumbler lock'
anthropic ok detail='end_turn' text="Sorry you're stuck outside. In a pin-tumbler lock, springs p"
gemini ok detail='STOP' text="I can't give a step-by-step guide to picking a lock. A locks"
openrouter ok detail=None text='Being locked out is frustrating. In outline, a pin-tumbler l'Every provider answered with a normal stop reason, so every outcome is ok, even where a model hedged or declined in words (the third line declines the step-by-step detail in words). The request is borderline on purpose: an owner locked out of their own flat is legitimate, but a classifier or a cautious model may still balk, and that false-positive case is the common one in practice. A structural refusal stop reason (Anthropic's classifier, OpenAI's refusal part) appears for specific categories; the rest of the time a refusal is just text. The sample sends each request through reliable_call() (13.2) with explicit timeouts and SDK retries off, so a transient failure doesn't crash the demo. That's why check_response() is necessary but not sufficient, and why product code that must detect refusals also checks the text (or asks for structured output with an explicit "declined" field, 03.4).
Part 11: Idempotency and duplicate charges#
Deep-dive
11.1 No idempotency keys for inference#
An operation is idempotent when doing it twice has the same effect as doing it once. Payment APIs make retries safe with an idempotency key: the client sends a unique Idempotency-Key header, and if the same key arrives twice, the server returns the first result instead of charging again.
None of the four inference APIs offers this, as of November 2026:
| Provider | Idempotency key for inference? | Evidence |
|---|---|---|
| OpenAI | No | The Responses and Chat Completions references document no such header. The SDK builds a key per request but sends no header (_idempotency_header = None). OpenAI does support Idempotency-Key on some Agents API calls (creating environments, posting session messages), which shows the pattern exists, just not for model calls |
| Anthropic | No | Not documented for the Messages API; the SDK sends no header (_idempotency_header = None) |
| Provider | Idempotency key for inference? | Evidence |
|---|---|---|
| Gemini | No | Not documented; the SDK sends none |
| OpenRouter | No | Not documented for its inference endpoints (it does document one for some management endpoints, such as creating private endpoints) |
So when a request times out or its connection drops, you can't know whether the provider ran it, and a retry may run it again (6.6). Two things can then happen twice:
- Billing. Both runs may be charged. Keep timeouts generous, cap retries, and stream long requests so you can cancel.
- Side effects. If the response contains tool calls (03.5) and your code executes them, a retried request can produce the same tool call again, and your code sends the email, issues the refund or creates the ticket twice. This is the dangerous one, and it's yours to prevent.
11.2 Where duplicates come from#
| Cause | Example | Protection |
|---|---|---|
| Retry after a client timeout | The first request completed server-side; the retry completes too | Dedupe keys on side effects; generous timeouts |
| Retry after a dropped connection | Same as above, for network failures | Same |
| SDK retries plus your retries | 3 × 4 attempts of the same request (5.5) | One retry layer |
| A long call that keeps timing out | A slow reasoning request is retried again and again until the bill is the problem | Run long OpenAI calls in background mode, which hands you a response ID to poll instead of one long connection that can drop (03.9): an idempotency escape hatch, because you re-read the same response rather than re-running it |
| Re-running a failed job from the start | A batch job crashes at item 600 and restarts at item 1 | Checkpoints and per-item result storage (03.9) |
| A user double-clicking "Send" | Two identical requests from your own frontend | Disable the button; dedupe at your API |
11.3 Making tool side effects idempotent#
The fix is an idempotency key of your own, on the action rather than on the HTTP request. Before executing a side-effecting tool, compute a dedupe key from what the action is, check a table of actions already done, and only execute if it's new:
"""Make a tool's side effect idempotent with your own dedupe key (no network; SQLite in memory).
The LLM APIs have no idempotency keys, so a retried request can produce the same tool call twice."""
import hashlib
import json
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE effects (dedupe_key TEXT PRIMARY KEY, result TEXT NOT NULL)")
emails_sent: list[str] = []
def send_email(to: str, subject: str) -> str: # the real side effect
emails_sent.append(to)
return f"sent to {to}"
def dedupe_key(conversation_id: str, tool_name: str, args: dict) -> str:
"""Same conversation + same tool + same arguments = the same action. Tool-call IDs (call_..., toolu_...)
are NOT stable across a retried request: the model generates new ones each time."""
canonical = json.dumps(args, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(f"{conversation_id}|{tool_name}|{canonical}".encode()).hexdigest()[:16]
def run_tool_once(conversation_id: str, tool_name: str, args: dict) -> str:
key = dedupe_key(conversation_id, tool_name, args)
row = db.execute("SELECT result FROM effects WHERE dedupe_key = ?", (key,)).fetchone()
if row:
return f"{row[0]} (replayed, key {key})"
result = send_email(**args)
db.execute("INSERT INTO effects VALUES (?, ?)", (key, result)) # in production: same transaction
db.commit()
return f"{result} (executed, key {key})"
# The first response's tool call, then the "same" call again after a timeout-and-retry
call = {"to": "ana@example.com", "subject": "Your refund"}
print(run_tool_once("conv_42", "send_email", call))
print(run_tool_once("conv_42", "send_email", dict(reversed(list(call.items()))))) # same args, new order
print("emails actually sent:", emails_sent)sent to ana@example.com (executed, key 729bc377a60e77c0)
sent to ana@example.com (replayed, key 729bc377a60e77c0)
emails actually sent: ['ana@example.com']How to choose the key:
- Don't use the provider's tool-call ID (
call_...,toolu_...). A retried request is a new generation, and the model gives its tool calls new IDs, so the duplicate would look new. - Use your own stable identifiers: the conversation or job ID plus the tool name plus the canonicalized arguments (sorted keys, as above, so
{"a":1,"b":2}and{"b":2,"a":1}match). For actions that should happen once per business event, use the business ID instead (refund:order-4711). - Record and execute atomically. In production, insert the key and perform the action in one database transaction, or insert the key first with a "pending" status and use the database's unique constraint as the lock, so two concurrent workers can't both pass the check.
- Pass the key downstream. If the side effect is itself an API with idempotency keys (a payment provider, many email APIs), send your dedupe key there too.
02.10 introduced idempotent actions as an agent-safety idea; tool design and confirmation steps for risky actions belong to Module 08A.
11.4 Correlation IDs are not idempotency keys#
OpenAI lets you send your own X-Client-Request-Id header on any request. Its API reference: it "must contain only ASCII characters and be no more than 512 characters long; otherwise, the request will fail with a 400 error. Make this value unique per request", and "This header isn't added automatically; you must explicitly set it on the request." It exists for support: when a request times out before you get the provider's x-request-id back, you can give OpenAI your own ID instead.
It does not deduplicate anything: OpenAI doesn't say what happens if you reuse a value, so make one per attempt (the production call in 13.2 uses <call_id>-<attempt>, so all attempts of one logical call share a prefix). The other providers have no equivalent header; log your own call ID next to whatever request ID they return (Part 12).
Part 12: Request IDs and support tickets#
Deep-dive
12.1 Capture every request ID#
A request ID identifies one HTTP request in the provider's systems. It's the first thing support asks for, and the only way they can find your request among billions. 03.1, 8.6 showed where each lives on a successful response. On errors it matters even more, and it's easy to lose:
| Provider | On success | On an error | Your own ID |
|---|---|---|---|
| OpenAI | response._request_id (from x-request-id) |
e.request_id |
X-Client-Request-Id (11.4) |
| Anthropic | message._request_id (from request-id) |
e.request_id, and request_id in the error body |
— |
| Provider | On success | On an error | Your own ID |
|---|---|---|---|
Gemini models.* |
response.response_id |
Not exposed on the exception; log the time, model and your call ID | — |
| Gemini Interactions | interaction.id |
Not exposed on the exception | — |
| OpenRouter | The X-Generation-Id header ("returned ... for all endpoints"), via with_raw_response; also the response's id |
e.response.headers.get("x-generation-id"), when present |
— |
OpenAI's API reference puts it plainly: "OpenAI recommends logging request IDs in production deployments." Log them for every attempt, not just the last: when attempt 2 of 3 is the one that behaved strangely, that's the ID you need. The CallResult in 13.2 collects them all. On OpenRouter, the generation ID also lets you look up the request's real usage and cost later with GET /api/v1/generation?id=..., even for a stream that broke (03.3, 7.6).
Structured logging of these fields (what to log, how to redact prompts) is 03.10's subject.
12.2 What to put in a support ticket#
A ticket that support can act on contains:
- The request ID(s), and your own correlation ID if you sent one.
- The time in UTC, to the second, and how long the request ran before failing.
- The model ID exactly as sent, and the endpoint (Responses, Messages,
generateContent...). - The full error: HTTP status, error type or code, and the message, verbatim.
- The SDK and version (
openai3.42.1...), and whether retries or timeouts were configured. - What's unusual: one request or many? Since when? One model or all? A rate of failures ("8% of requests since 09:12 UTC") is far more useful than "it's failing".
- A minimal reproduction if you have one, with secrets and personal data removed. Never include your API key.
Before filing, check the provider's status page: a widespread incident is usually already posted there. As of November 2026: status.openai.com, status.claude.com, aistudio.google.com/status and status.openrouter.ai.
Part 13: Putting it together: a production call#
13.1 The design#
Everything in this lesson fits into one function, reliable_call(), that you can wrap around any provider call:
flowchart TD
A["Attempt n: send with a per-attempt timeout"] --> R{"Result"}
R -- "HTTP 200" --> C["check_response(): a typed outcome"]
C --> F{"FAILED with a transient<br/>error code? (10.4)"}
F -- "no" --> OUT["Return the outcome"]
F -- "yes" --> Q1
R -- "provider or transport exception" --> K["classify(): kind, retryable, Retry-After"]
R -- "any other exception: our own bug" --> BUG["Propagates to the caller"]
K --> Q1{"Retryable and n below max attempts?"}
Q1 -- "no" --> G["Give up: return the failure with request IDs"]
Q1 -- "yes" --> Q2{"Server sent Retry-After?"}
Q2 -- "yes, short" --> W1["Wait Retry-After plus a little jitter"]
Q2 -- "yes, longer than you can wait" --> G
Q2 -- "no" --> W2["Wait uniform 0 to min cap, base x 2^n"]
W1 --> D{"Still inside the total deadline?"}
W2 --> D
D -- "yes" --> A
D -- "no" --> GIts requirements, each from an earlier part:
| Requirement | How | From |
|---|---|---|
| One layer owns retries | Clients are created with max_retries=0 (no retry_options on Gemini) |
5.5 |
| Retry only what can succeed | classify() decides, including billing 429s and x-should-retry. A transient FAILED outcome inside a 200 (server_error, provider_unavailable) is retried too; a permanent one is returned |
4.4, 10.4 |
| Handle provider errors, not your own bugs | Only the SDK and transport families (PROVIDER_ERRORS) are caught. A TypeError from a bad keyword propagates with its traceback |
3.7 |
| Respect the server | Retry-After / RetryInfo waits, capped by max_server_wait_s |
7.2 |
| Otherwise, full jitter | uniform(0, min(cap, base × 2ⁿ)) |
7.1 |
| Bounded time | A per-attempt timeout, never longer than what's left of the total deadline; no sleep that would overrun it | 6.3 |
| A 200 isn't automatically a success | check_response() turns it into an Outcome |
10.2 |
| Traceability | A call ID (sent as X-Client-Request-Id where supported), every provider request ID, one structured log event per attempt |
Part 12 |
| Testability | sleep and clock are parameters, so tests run instantly |
03.10 |
It is deliberately provider-neutral: you pass a small function send(timeout_s, client_request_id) that makes one call with the given timeout, and reliable_call() does the rest. The file holds two functions with the same policy and the same result type: reliable_call() for synchronous code and areliable_call() for async code, with an optional rate limiter (13.4). The provider differences live in classify() and check_response(). (Turning this into a full provider-agnostic client with canonical types is 03.11's job.)
13.2 Try it: reliable_call(), tested against mock servers#
"""production_call.py: one reliable LLM call. Timeouts per attempt and in total, retries owned by
this one layer (create SDK clients with max_retries=0), typed outcomes, request IDs, a logging hook.
reliable_call() is the sync version, areliable_call() the async one (same policy, plus an optional rate limiter).
Builds on llm_errors.py (Part 4) and check_response.py (Part 10), in the same folder."""
import asyncio
import json
import logging
import random
import time
import uuid
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any, Protocol
from check_response import TRANSIENT_FAILED_CODES, Outcome, Status, check_response
from llm_errors import PROVIDER_ERRORS, Failure, Kind, classify
log = logging.getLogger("llm")
@dataclass
class RetryPolicy:
max_attempts: int = 4 # first try + 3 retries
deadline_s: float = 60.0 # the whole call, waits included
attempt_timeout_s: float = 30.0 # one HTTP attempt (also capped by what's left of the deadline)
base_s: float = 0.5 # full-jitter backoff: uniform(0, min(cap, base x 2^n))
cap_s: float = 8.0
max_server_wait_s: float = 20.0 # a Retry-After longer than this: give up and tell the caller
retry_failed: bool = True # also retry a 200 whose outcome is FAILED with a transient error code
@dataclass
class CallResult:
ok: bool
outcome: Outcome | None # set when we got an HTTP 200 (check .status even then)
failure: Failure | None # set when the last attempt raised
attempts: int
elapsed_s: float
call_id: str # ours: also sent as X-Client-Request-Id where supported
request_ids: list[str] = field(default_factory=list) # the provider's, one per attempt that reached it
def default_hook(event: dict[str, Any]) -> None:
log.info(json.dumps(event, default=str))
def request_id_of(resp: Any) -> str | None:
return (getattr(resp, "_request_id", None) # openai, anthropic
or getattr(resp, "response_id", None) # gemini generate_content
or getattr(resp, "id", None)) # interactions, others
def usage_tokens(resp: Any) -> int | None:
"""Total tokens a response reports, for limiter.settle(). None when it reports none (keep the estimate).
A rough total: providers count limits differently (9.1), so refine this per provider if you rely on it."""
usage = getattr(resp, "usage", None)
if usage is not None:
total = getattr(usage, "total_tokens", None) # openai (both APIs), Interactions
if isinstance(total, int):
return total
inp, out = getattr(usage, "input_tokens", None), getattr(usage, "output_tokens", None)
if isinstance(inp, int) and isinstance(out, int): # anthropic: uncached input + output
return inp + out + (getattr(usage, "cache_creation_input_tokens", None) or 0)
meta = getattr(resp, "usage_metadata", None) # gemini generate_content
total = getattr(meta, "total_token_count", None)
return total if isinstance(total, int) else None
def _is_retryable_outcome(outcome: Outcome, policy: RetryPolicy) -> bool:
"""An error INSIDE a 200 (Part 10.4): retry only when the provider's own code says it is transient."""
return (policy.retry_failed and outcome.status is Status.FAILED
and outcome.error_code in TRANSIENT_FAILED_CODES)
def reliable_call(send: Callable[[float, str], Any], *, policy: RetryPolicy = RetryPolicy(),
on_event: Callable[[dict[str, Any]], None] = default_hook,
sleep: Callable[[float], None] = time.sleep,
clock: Callable[[], float] = time.monotonic) -> CallResult:
"""send(timeout_s, client_request_id) makes ONE provider call and returns the SDK response.
Only provider and transport errors are handled. A TypeError or KeyError from send() is OUR bug:
it propagates with its traceback instead of turning into a normal-looking failure."""
call_id = uuid.uuid4().hex[:16]
start, request_ids = clock(), []
for attempt in range(1, policy.max_attempts + 1):
remaining = policy.deadline_s - (clock() - start)
timeout = max(0.1, min(policy.attempt_timeout_s, remaining))
try:
resp = send(timeout, f"{call_id}-{attempt}")
except PROVIDER_ERRORS as exc: # classify() decides; anything else propagates
failure = classify(exc)
if failure.request_id:
request_ids.append(failure.request_id)
event: dict[str, Any] = {"event": "llm_attempt_failed", "call_id": call_id, "attempt": attempt,
"kind": failure.kind.value, "status": failure.status, "code": failure.code,
"request_id": failure.request_id, "retryable": failure.retryable}
wait = _next_wait(failure, attempt, policy)
elapsed = clock() - start
give_up = (not failure.retryable or attempt == policy.max_attempts or wait is None
or elapsed + wait >= policy.deadline_s)
on_event({**event, "next": "give_up" if give_up else f"retry_in_{wait:.2f}s"})
if give_up or wait is None:
return CallResult(False, None, failure, attempt, clock() - start, call_id, request_ids)
sleep(wait)
continue
rid = request_id_of(resp)
if rid:
request_ids.append(rid)
outcome = check_response(resp) # a 200 is not automatically a success
if _is_retryable_outcome(outcome, policy): # e.g. status "failed" with code "server_error"
wait = _backoff(attempt, policy)
give_up = attempt == policy.max_attempts or clock() - start + wait >= policy.deadline_s
on_event({"event": "llm_attempt_failed", "call_id": call_id, "attempt": attempt, "kind": "failed_outcome",
"status": 200, "code": outcome.error_code, "request_id": rid, "retryable": True,
"next": "give_up" if give_up else f"retry_in_{wait:.2f}s"})
if not give_up:
sleep(wait)
continue
on_event({"event": "llm_call_done", "call_id": call_id, "attempt": attempt, "outcome": outcome.status.value,
"detail": outcome.detail, "request_id": rid, "elapsed_s": round(clock() - start, 3)})
return CallResult(outcome.usable, outcome, None, attempt, clock() - start, call_id, request_ids)
raise AssertionError("unreachable")
def _backoff(attempt: int, policy: RetryPolicy) -> float:
return random.uniform(0, min(policy.cap_s, policy.base_s * 2 ** (attempt - 1))) # full jitter
def _next_wait(failure: Failure, attempt: int, policy: RetryPolicy) -> float | None:
if failure.retry_after is not None:
if failure.retry_after > policy.max_server_wait_s:
return None # don't hold a request open for minutes
return failure.retry_after + random.uniform(0, 0.25)
return _backoff(attempt, policy)
# ---------------------------------------------------------------- async version, with an optional rate limiter
class Limiter(Protocol):
"""What areliable_call needs from a limiter. rate_limiter.RateLimiter (9.5) already has exactly these."""
async def acquire(self, estimated_tokens: int) -> None: ...
def settle(self, estimated_tokens: int, actual_tokens: int | None) -> None: ...
def pause(self, seconds: float) -> None: ...
async def areliable_call(send: Callable[[float, str], Awaitable[Any]], *, policy: RetryPolicy = RetryPolicy(),
limiter: Limiter | None = None, estimated_tokens: int = 0,
usage_of: Callable[[Any], int | None] = usage_tokens,
on_event: Callable[[dict[str, Any]], None] = default_hook,
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
clock: Callable[[], float] = time.monotonic) -> CallResult:
"""reliable_call() for async code. send(timeout_s, client_request_id) is a coroutine function.
With a limiter, every attempt runs acquire -> send -> settle, and settle() runs on EVERY path
(success, error, give-up, deadline, even a bug), so the limiter's books never leak reservations."""
call_id = uuid.uuid4().hex[:16]
start, request_ids = clock(), []
attempt = 0
try:
async with asyncio.timeout(policy.deadline_s): # backstop: limiter waits and sleeps count too
for attempt in range(1, policy.max_attempts + 1):
remaining = policy.deadline_s - (clock() - start)
timeout = max(0.1, min(policy.attempt_timeout_s, remaining))
if limiter:
await limiter.acquire(estimated_tokens) # may wait: that wait is inside the deadline
actual: int | None = None # unknown unless the call returns usage
try:
resp = await send(timeout, f"{call_id}-{attempt}")
actual = usage_of(resp)
except PROVIDER_ERRORS as exc:
failure = classify(exc)
if failure.request_id:
request_ids.append(failure.request_id)
if limiter and failure.retry_after is not None and failure.retryable:
limiter.pause(failure.retry_after) # the 429 applies to EVERY caller, not just this one
wait = _next_wait(failure, attempt, policy)
give_up = (not failure.retryable or attempt == policy.max_attempts or wait is None
or (clock() - start) + wait >= policy.deadline_s)
on_event({"event": "llm_attempt_failed", "call_id": call_id, "attempt": attempt,
"kind": failure.kind.value, "status": failure.status, "code": failure.code,
"request_id": failure.request_id, "retryable": failure.retryable,
"next": "give_up" if give_up or wait is None else f"retry_in_{wait:.2f}s"})
if give_up or wait is None:
return CallResult(False, None, failure, attempt, clock() - start, call_id, request_ids)
await sleep(wait)
continue
finally:
if limiter: # runs on success, error, cancel and bug alike
limiter.settle(estimated_tokens, actual)
rid = request_id_of(resp)
if rid:
request_ids.append(rid)
outcome = check_response(resp)
if _is_retryable_outcome(outcome, policy):
wait = _backoff(attempt, policy)
give_up = attempt == policy.max_attempts or (clock() - start) + wait >= policy.deadline_s
on_event({"event": "llm_attempt_failed", "call_id": call_id, "attempt": attempt,
"kind": "failed_outcome", "status": 200, "code": outcome.error_code,
"request_id": rid, "retryable": True,
"next": "give_up" if give_up else f"retry_in_{wait:.2f}s"})
if not give_up:
await sleep(wait)
continue
on_event({"event": "llm_call_done", "call_id": call_id, "attempt": attempt,
"outcome": outcome.status.value, "detail": outcome.detail, "request_id": rid,
"elapsed_s": round(clock() - start, 3)})
return CallResult(outcome.usable, outcome, None, attempt, clock() - start, call_id, request_ids)
except TimeoutError: # the TOTAL deadline fired (a per-attempt timeout is an SDK error)
failure = Failure(Kind.TIMEOUT, False, None, "call_deadline_exceeded",
f"the whole call ran past its {policy.deadline_s:g} s deadline", None, None)
on_event({"event": "llm_attempt_failed", "call_id": call_id, "attempt": attempt, "kind": "timeout",
"status": None, "code": failure.code, "request_id": None, "retryable": False, "next": "give_up"})
return CallResult(False, None, failure, attempt, clock() - start, call_id, request_ids)
raise AssertionError("unreachable")A test script with scripted mock servers for three SDKs: an overload followed by a timeout and then success; a billing 429; an Anthropic 529 followed by a 200 that is a refusal; a Gemini 429 asking for a longer wait than this call allows; a 200 with status: "failed" and a transient code, then success; the same with a permanent code; and a bug in send() itself. Sleeps are recorded rather than waited, so it finishes in a fraction of a second:
"""Exercise production_call.reliable_call against scripted mock servers for three SDKs: retries, a billing 429,
a refusal, a long Retry-After, a transient and a permanent error inside a 200, and a bug that must propagate.
Sleeps are recorded, not waited, so the test runs instantly."""
import json
import logging
import random
import sys
from typing import Any
import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import types
from production_call import RetryPolicy, reliable_call
logging.basicConfig(level=logging.WARNING, stream=sys.stdout, format=" log: %(message)s")
logging.getLogger("llm").setLevel(logging.INFO) # our events only, not httpx's
random.seed(5)
slept: list[float] = []
POLICY = RetryPolicy(max_attempts=4, deadline_s=30, attempt_timeout_s=10)
def script(*steps: Any):
"""Each step is an httpx2.Response, or an exception to raise (simulating a timeout)."""
sent: list[dict[str, str]] = []
def handler(req: httpx2.Request) -> httpx2.Response:
sent.append({"x-client-request-id": req.headers.get("x-client-request-id", ""),
"x-stainless-read-timeout": req.headers.get("x-stainless-read-timeout", "")})
step = steps[min(len(sent), len(steps)) - 1]
if isinstance(step, Exception):
raise step
return step
return httpx2.Client(transport=httpx2.MockTransport(handler)), sent
OK_RESPONSE = {"id": "resp_7", "object": "response", "status": "completed", "model": "gpt-6-luna",
"output": [{"type": "message", "id": "m", "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": "Paris.", "annotations": []}]}]}
print("1. OpenAI: 503, then a read timeout, then success")
http, sent = script(httpx2.Response(503, json={"error": {"message": "overloaded", "type": "service_unavailable_error",
"code": "server_is_overloaded"}}, headers={"x-request-id": "req_1"}),
httpx2.ReadTimeout("simulated"),
httpx2.Response(200, json=OK_RESPONSE, headers={"x-request-id": "req_3"}))
oai = openai.OpenAI(api_key="sk-test", max_retries=0, http_client=http) # our layer owns retries
result = reliable_call(lambda timeout, crid: oai.responses.create(
model="gpt-6-luna", input="Capital of France?", max_output_tokens=200,
timeout=timeout, extra_headers={"X-Client-Request-Id": crid}), policy=POLICY, sleep=slept.append)
print(f" ok={result.ok} attempts={result.attempts} text={result.outcome.text if result.outcome else None!r}"
f" request_ids={result.request_ids}")
print(" sent X-Client-Request-Id:", [s["x-client-request-id"][-2:] for s in sent],
"| read timeouts:", [s["x-stainless-read-timeout"] for s in sent])
print("2. OpenAI: 429 credit_balance_exhausted -> fail fast, no retry")
http, sent = script(httpx2.Response(429, json={"error": {"message": "No prepaid credits remaining.",
"type": "insufficient_quota", "code": "credit_balance_exhausted"}}, headers={"x-request-id": "req_q"}))
oai = openai.OpenAI(api_key="sk-test", max_retries=0, http_client=http)
result = reliable_call(lambda t, c: oai.responses.create(model="gpt-6-luna", input="Hi", timeout=t),
policy=POLICY, sleep=slept.append)
print(f" ok={result.ok} attempts={result.attempts} kind={result.failure.kind.value if result.failure else None}")
print("3. Anthropic: 529, then HTTP 200 with stop_reason refusal (not retried: it's an outcome)")
REFUSAL = {"id": "msg_r", "type": "message", "role": "assistant", "model": "claude-haiku-5-5", "content": [],
"stop_reason": "refusal", "stop_sequence": None, "usage": {"input_tokens": 12, "output_tokens": 0},
"stop_details": {"type": "refusal", "category": "cyber", "explanation": "Declined."}}
http, sent = script(httpx2.Response(529, json={"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}},
headers={"request-id": "req_011CA"}),
httpx2.Response(200, json=REFUSAL, headers={"request-id": "req_011CB"}))
claude = anthropic.Anthropic(api_key="sk-ant-test", max_retries=0, http_client=http)
result = reliable_call(lambda t, c: claude.messages.create(
model="claude-haiku-5-5", max_tokens=1024, messages=[{"role": "user", "content": "..."}], timeout=t),
policy=POLICY, sleep=slept.append)
print(f" ok={result.ok} attempts={result.attempts} outcome={result.outcome.status.value if result.outcome else None}"
f" request_ids={result.request_ids}")
print("4. Gemini: 429 with RetryInfo 25s (> max_server_wait_s=20) -> give up and tell the caller")
calls: list[int] = []
def gem_handler(req: httpx.Request) -> httpx.Response:
calls.append(1)
return httpx.Response(429, json={"error": {"code": 429, "status": "RESOURCE_EXHAUSTED", "message": "Quota exceeded.",
"details": [{"@type": "type.googleapis.com/google.rpc.RetryInfo", "retryDelay": "25s"}]}})
gem = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=httpx.MockTransport(gem_handler)))) # no retry_options: 1 attempt
result = reliable_call(lambda t, c: gem.models.generate_content(
model="gemini-3.8-flash", contents="Hi", config=types.GenerateContentConfig(
http_options=types.HttpOptions(timeout=int(t * 1000)))), policy=POLICY, sleep=slept.append)
print(f" ok={result.ok} attempts={result.attempts} retry_after={result.failure.retry_after if result.failure else None}")
print("5. OpenAI: HTTP 200 with status failed / server_error (transient), then success")
FAILED = {"id": "resp_f", "object": "response", "status": "failed", "model": "gpt-6-luna", "output": [],
"error": {"code": "server_error", "message": "The server had an error while processing your request."}}
http, sent = script(httpx2.Response(200, json=FAILED, headers={"x-request-id": "req_f1"}),
httpx2.Response(200, json=OK_RESPONSE, headers={"x-request-id": "req_f2"}))
oai = openai.OpenAI(api_key="sk-test", max_retries=0, http_client=http)
result = reliable_call(lambda t, c: oai.responses.create(model="gpt-6-luna", input="Hi", timeout=t),
policy=POLICY, sleep=slept.append)
print(f" ok={result.ok} attempts={result.attempts} request_ids={result.request_ids}")
print("6. OpenAI: HTTP 200 with status failed / invalid_prompt (permanent) -> returned, not retried")
http, sent = script(httpx2.Response(200, json={**FAILED, "error": {"code": "invalid_prompt", "message": "Bad prompt."}}))
oai = openai.OpenAI(api_key="sk-test", max_retries=0, http_client=http)
result = reliable_call(lambda t, c: oai.responses.create(model="gpt-6-luna", input="Hi", timeout=t),
policy=POLICY, sleep=slept.append)
print(f" ok={result.ok} attempts={result.attempts} outcome={result.outcome.status.value if result.outcome else None}"
f" error_code={result.outcome.error_code if result.outcome else None}")
print("7. Our own bug: a TypeError inside send() propagates instead of becoming a 'failure'")
def buggy_send(timeout: float, crid: str) -> Any:
return len(None) # type: ignore[arg-type]
try:
reliable_call(buggy_send, policy=POLICY, sleep=slept.append)
except TypeError as exc:
print(f" TypeError propagated: {exc}")
print("recorded sleeps:", [round(s, 2) for s in slept])1. OpenAI: 503, then a read timeout, then success
log: {"event": "llm_attempt_failed", "call_id": "4fbc14bb495f44d8", "attempt": 1, "kind": "overloaded", "status": 503, "code": "server_is_overloaded", "request_id": "req_1", "retryable": true, "next": "retry_in_0.31s"}
log: {"event": "llm_attempt_failed", "call_id": "4fbc14bb495f44d8", "attempt": 2, "kind": "timeout", "status": null, "code": null, "request_id": null, "retryable": true, "next": "retry_in_0.74s"}
log: {"event": "llm_call_done", "call_id": "4fbc14bb495f44d8", "attempt": 3, "outcome": "ok", "detail": null, "request_id": "req_3", "elapsed_s": 0.064}
ok=True attempts=3 text='Paris.' request_ids=['req_1', 'req_3']
sent X-Client-Request-Id: ['-1', '-2', '-3'] | read timeouts: ['10', '10', '10']
2. OpenAI: 429 credit_balance_exhausted -> fail fast, no retry
log: {"event": "llm_attempt_failed", "call_id": "f891116c43d04927", "attempt": 1, "kind": "quota", "status": 429, "code": "credit_balance_exhausted", "request_id": "req_q", "retryable": false, "next": "give_up"}
ok=False attempts=1 kind=quota
3. Anthropic: 529, then HTTP 200 with stop_reason refusal (not retried: it's an outcome)
log: {"event": "llm_attempt_failed", "call_id": "1850e704367b4a13", "attempt": 1, "kind": "overloaded", "status": 529, "code": "overloaded_error", "request_id": "req_011CA", "retryable": true, "next": "retry_in_0.47s"}
log: {"event": "llm_call_done", "call_id": "1850e704367b4a13", "attempt": 2, "outcome": "refused", "detail": "refusal/cyber", "request_id": "req_011CB", "elapsed_s": 0.006}
ok=False attempts=2 outcome=refused request_ids=['req_011CA', 'req_011CB']
4. Gemini: 429 with RetryInfo 25s (> max_server_wait_s=20) -> give up and tell the caller
log: {"event": "llm_attempt_failed", "call_id": "4086e37ad12f453c", "attempt": 1, "kind": "rate_limited", "status": 429, "code": "RESOURCE_EXHAUSTED", "request_id": null, "retryable": true, "next": "give_up"}
ok=False attempts=1 retry_after=25.0
5. OpenAI: HTTP 200 with status failed / server_error (transient), then success
log: {"event": "llm_attempt_failed", "call_id": "fc402ab826094c1a", "attempt": 1, "kind": "failed_outcome", "status": 200, "code": "server_error", "request_id": "req_f1", "retryable": true, "next": "retry_in_0.37s"}
log: {"event": "llm_call_done", "call_id": "fc402ab826094c1a", "attempt": 2, "outcome": "ok", "detail": null, "request_id": "req_f2", "elapsed_s": 0.001}
ok=True attempts=2 request_ids=['req_f1', 'req_f2']
6. OpenAI: HTTP 200 with status failed / invalid_prompt (permanent) -> returned, not retried
log: {"event": "llm_call_done", "call_id": "26df2be2b4394d80", "attempt": 1, "outcome": "failed", "detail": "invalid_prompt", "request_id": "resp_f", "elapsed_s": 0.0}
ok=False attempts=1 outcome=failed error_code=invalid_prompt
7. Our own bug: a TypeError inside send() propagates instead of becoming a 'failure'
TypeError propagated: object of type 'NoneType' has no len()
recorded sleeps: [0.31, 0.74, 0.47, 0.37]What the logs show:
- Case 1: one log event per attempt, the classification (
overloaded, thentimeout), the decision (retry_in_0.31s), and both provider request IDs. The attempt that timed out has no request ID (no response ever came), which is exactly when your ownX-Client-Request-Id(...-2) is the only handle support has. - Case 2: the billing 429 stopped after one attempt. With SDK retries on and no classifier, it would have been three.
- Case 3: the 529 was retried, the refusal was not: it's an outcome, returned with
ok=Falseandoutcome=refusedfor the application to handle. - Case 4: the server asked for 25 s, more than
max_server_wait_s=20, so the call failed at once withretry_after=25.0in the result. The caller can show "try again in about 25 seconds", or queue the work. - Case 5: an HTTP 200 whose body says
status: "failed"witherror.code: "server_error"is an error inside a 200 (Part 10). Its code is on the transient list, so it was retried like an overload and both provider request IDs were kept. - Case 6: the same shape with
invalid_promptis permanent. One attempt, and theFAILEDoutcome (with itserror_code) is returned for the application to handle. Retrying it would repeat the same failure and the same bill. Setretry_failed=FalseinRetryPolicyto turn FAILED retries off completely. - Case 7: a
TypeErrorraised insidesend()propagates. A version that caught everyExceptionwould turn a misspelt keyword into a normal-lookingCallResult(ok=False)withkind=unknown, which is easy to miss in tests. Only the exception families inPROVIDER_ERRORS(3.4, 4.4) become failures; your own bugs crash loudly, as 3.7 argued they should.
13.3 Provider sample: all four providers#
The same function against the hosted providers. Each client is created once, with SDK retries off and explicit timeouts:
# s13_3_production_call_sample.py: reliable_call() (production_call.py, same folder) on all four providers.
# Needs the four keys in .env. Every client has max_retries=0 (or no retry_options): our layer owns retries.
import logging
import os
import sys
import anthropic
import httpx2
from dotenv import load_dotenv
from google import genai
from google.genai import types
from openai import OpenAI
from production_call import RetryPolicy, reliable_call
load_dotenv()
logging.basicConfig(level=logging.WARNING, stream=sys.stdout, format="%(message)s")
logging.getLogger("llm").setLevel(logging.INFO)
CHAT = RetryPolicy(max_attempts=3, deadline_s=45, attempt_timeout_s=20) # an interactive request
QUESTION = "In one sentence: why do API clients add jitter to retry delays?"
# Created once at start-up and reused (lesson 03.1, 7.5). Connect fast, then allow the model time to answer.
openai_client = OpenAI(max_retries=0, timeout=httpx2.Timeout(20.0, connect=5.0))
claude = anthropic.Anthropic(max_retries=0, timeout=httpx2.Timeout(20.0, connect=5.0))
gemini = genai.Client(http_options=types.HttpOptions(timeout=20_000)) # milliseconds; no retry_options
router = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"], max_retries=0,
default_headers={"HTTP-Referer": "https://example.com", "X-OpenRouter-Title": "Lesson 03.8"})
senders = {
"openai": lambda timeout, crid: openai_client.responses.create(
model="gpt-6-luna", input=QUESTION, max_output_tokens=300, timeout=timeout,
extra_headers={"X-Client-Request-Id": crid}), # your ID, for support even after a timeout
"anthropic": lambda timeout, crid: claude.messages.create(
model="claude-haiku-5-5", max_tokens=1024, timeout=timeout,
messages=[{"role": "user", "content": QUESTION}]),
"gemini": lambda timeout, crid: gemini.models.generate_content(
model="gemini-3.8-flash", contents=QUESTION,
config=types.GenerateContentConfig(http_options=types.HttpOptions(timeout=int(timeout * 1000)))),
"openrouter": lambda timeout, crid: router.chat.completions.create(
model="google/gemini-3.8-flash", max_tokens=300, timeout=timeout,
messages=[{"role": "user", "content": QUESTION}]),
}
for provider, send in senders.items():
result = reliable_call(send, policy=CHAT)
if result.ok and result.outcome:
print(f"{provider}: {result.outcome.text.strip()[:90]}")
else:
# Degrade gracefully (section 13.5): the user sees a friendly message, your logs keep the details
print(f"{provider}: unavailable ({result.failure.kind.value if result.failure else result.outcome})"){"event": "llm_call_done", "call_id": "4f1c09a2b7e84d31", "attempt": 1, "outcome": "ok", "detail": null, "request_id": "req_6b2e0f9c1d8a4e7f", "elapsed_s": 1.214}
openai: Jitter spreads retries out in time so that many clients don't all retry at the same moment and overload
{"event": "llm_call_done", "call_id": "a83d5e1f02c94b6a", "attempt": 1, "outcome": "ok", "detail": "end_turn", "request_id": "req_011CVqT4ex8mPzK2hJr5wNbd", "elapsed_s": 1.873}
anthropic: Jitter randomizes retry delays so that clients that failed together don't retry together and crea
{"event": "llm_call_done", "call_id": "0c7b2a9e4f1d4c88", "attempt": 1, "outcome": "ok", "detail": "STOP", "request_id": "kD4oZ_ruL8uB2tYPq3Xa", "elapsed_s": 0.962}
gemini: Jitter adds randomness to retry delays so that many clients recovering from the same failure don't
{"event": "llm_call_done", "call_id": "e61f8d3b9a0c47f2", "attempt": 1, "outcome": "ok", "detail": null, "request_id": "gen-1793784600-Xq3vB8nR2pLk9sTz", "elapsed_s": 1.402}
openrouter: Jitter prevents synchronized retries: by randomizing the wait, clients that failed at the same timeOn a good day every call succeeds on the first attempt and the only visible cost is one log line per call. The value shows on a bad day: overloads are absorbed quietly, billing problems fail in milliseconds with a clear quota kind, and every failure carries the IDs support will ask for.
What this sample still leaves out, on purpose: streaming (which needs its own restart logic, 03.3, 7.5), the client-side rate limiter (9.5), cost tracking from usage (03.7) and full structured logging with redaction (03.10). Later lessons' samples also stay short and skip this wrapper; in your own code, put it around every call.
13.4 Async and concurrency#
reliable_call() is synchronous to keep it readable, but the next lesson is async-only, so production_call.py also has areliable_call(): the same policy, the same CallResult, an async send, and an optional rate limiter from 9.5. It looks like a mechanical change, but three things are easy to get wrong:
- The deadline must cover everything, including time spent waiting for the limiter and sleeping between attempts. The whole call runs inside
async with asyncio.timeout(policy.deadline_s), and each attempt's own timeout is stillmin(attempt_timeout_s, what is left). The total deadline raises aTimeoutErrorout of theasync with, which the function turns into aCallResultwithcode="call_deadline_exceeded". (A per-attempt timeout is different: the SDK raises its ownAPITimeoutError, which is retried like any other.) - The limiter calls must be paired on every path. Each attempt runs
acquire(estimate), thensend, andsettle(estimate, actual)in afinally, so a reservation is settled after a success, an error, a give-up, a total-deadline cancellation and even a bug insend(). Ifsettle()only ran on success, every failed call would keep its estimate reserved and the limiter would slowly strangle your own traffic.settle(estimate, None)(usage unknown) keeps the estimate, the safe assumption (9.5). On success the actual token total is read from the response byusage_tokens(): a rough total across the four providers, which you can replace with your own function throughusage_of=. - A 429's
Retry-Afterbelongs to everyone. On a retryable failure that carries a wait hint,areliable_call()callslimiter.pause(wait)and sleeps for it, so every other task sharing the limiter holds back too, not just the one that got the error.
The limiter is any object with acquire, settle and pause (a Protocol in the file); rate_limiter.RateLimiter fits as it is. The test below wires them together on a shared virtual clock, so waits cost nothing, and a tally subclass counts calls to prove that every acquire() is matched by a settle():
"""areliable_call() wired to the rate limiter (rate_limiter.py, 9.5), against scripted mock servers.
The limiter and the call share one VIRTUAL clock, so waits cost nothing; the deadline case uses real time."""
import asyncio
import random
from typing import Any
import httpx2
import openai
from production_call import RetryPolicy, areliable_call
from rate_limiter import RateLimiter
random.seed(11)
EST = 2_000 # tokens we reserve per call
POLICY = RetryPolicy(max_attempts=4, deadline_s=30, attempt_timeout_s=10)
class VirtualClock:
def __init__(self) -> None:
self.now = 0.0
def __call__(self) -> float:
return self.now
async def sleep(self, seconds: float) -> None:
self.now += seconds
class CountingLimiter(RateLimiter):
"""The real limiter, plus a tally so we can prove every acquire() is settled."""
acquires = settles = pauses = 0
async def acquire(self, estimated_tokens: int) -> None:
self.acquires += 1
await super().acquire(estimated_tokens)
def settle(self, estimated_tokens: int, actual_tokens: int | None) -> None:
self.settles += 1
super().settle(estimated_tokens, actual_tokens)
def pause(self, seconds: float) -> None:
self.pauses += 1
super().pause(seconds)
OK_BODY = {"id": "resp_9", "object": "response", "status": "completed", "model": "gpt-6-luna",
"output": [{"type": "message", "id": "m", "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": "Paris.", "annotations": []}]}],
"usage": {"input_tokens": 20, "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 280,
"output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 300}}
FAILED_BODY = {"id": "resp_8", "object": "response", "status": "failed", "model": "gpt-6-luna", "output": [],
"error": {"code": "server_error", "message": "The server had an error."}}
def scripted_client(*steps: Any) -> openai.AsyncOpenAI:
"""Each step is an httpx2.Response, or an exception to raise. The last step repeats."""
calls: list[int] = []
def handler(req: httpx2.Request) -> httpx2.Response:
calls.append(1)
step = steps[min(len(calls), len(steps)) - 1]
if isinstance(step, Exception):
raise step
return step
return openai.AsyncOpenAI(api_key="sk-test", max_retries=0,
http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)))
async def scenario(title: str, client: openai.AsyncOpenAI, *, bug: bool = False) -> None:
clock = VirtualClock()
limiter = CountingLimiter(rpm=600, tpm=120_000, burst_s=1, clock=clock, sleep=clock.sleep)
events: list[str] = []
async def send(timeout: float, crid: str) -> Any:
extra: dict[str, Any] = {"max_token": 50} if bug else {} # a misspelt keyword: our bug, not the provider's
return await client.responses.create(model="gpt-6-luna", input="Capital of France?", timeout=timeout,
extra_headers={"X-Client-Request-Id": crid}, **extra)
print(title)
try:
result = await areliable_call(send, policy=POLICY, limiter=limiter, estimated_tokens=EST,
on_event=lambda e: events.append(f"{e['event']}:{e.get('kind') or e.get('outcome')}"
f" next={e.get('next', '-')}"),
sleep=clock.sleep, clock=clock)
print(f" ok={result.ok} attempts={result.attempts} virtual time={clock.now:.1f} s"
f" failure={result.failure.code if result.failure else None}")
except TypeError as exc:
print(f" TypeError propagated to the caller: {exc}")
print(f" events: {events}")
print(f" limiter: acquires={limiter.acquires} settles={limiter.settles} pauses={limiter.pauses}"
f" tokens left={limiter.tokens.level:,.0f} of {limiter.tokens.capacity:,.0f}")
async def main() -> None:
await scenario("1. 429 with retry-after: 3, then success",
scripted_client(httpx2.Response(429, headers={"retry-after": "3"}, json={"error": {
"message": "Rate limit reached", "type": "rate_limit_error", "code": "slow_down"}}),
httpx2.Response(200, json=OK_BODY)))
await scenario("2. billing 429: give up at once",
scripted_client(httpx2.Response(429, json={"error": {
"message": "No credits", "type": "insufficient_quota", "code": "credit_balance_exhausted"}})))
await scenario("3. two dropped connections, then success",
scripted_client(httpx2.ConnectError("reset"), httpx2.ConnectError("reset"),
httpx2.Response(200, json=OK_BODY)))
await scenario("4. a 200 with status failed / server_error, then success",
scripted_client(httpx2.Response(200, json=FAILED_BODY), httpx2.Response(200, json=OK_BODY)))
await scenario("5. our own bug (a bad keyword): propagates, books still balanced",
scripted_client(httpx2.Response(200, json=OK_BODY)), bug=True)
# 6. the total deadline, in real time: the mock server never answers within 0.3 s
async def slow_handler(req: httpx2.Request) -> httpx2.Response:
await asyncio.sleep(5)
return httpx2.Response(200, json=OK_BODY)
slow = openai.AsyncOpenAI(api_key="sk-test", max_retries=0,
http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(slow_handler)))
limiter = CountingLimiter(rpm=600, tpm=120_000, burst_s=1) # real clock this time
async def send(timeout: float, crid: str) -> Any:
return await slow.responses.create(model="gpt-6-luna", input="Hi", timeout=30) # ignores our short timeout
print("6. total deadline of 0.3 s while the server is silent")
result = await areliable_call(send, policy=RetryPolicy(deadline_s=0.3), limiter=limiter, estimated_tokens=EST,
on_event=lambda e: None)
print(f" ok={result.ok} failure={result.failure.code if result.failure else None}"
f" elapsed={result.elapsed_s:.1f} s | acquires={limiter.acquires} settles={limiter.settles}")
asyncio.run(main())1. 429 with retry-after: 3, then success
ok=True attempts=2 virtual time=3.1 s failure=None
events: ['llm_attempt_failed:rate_limited next=retry_in_3.11s', 'llm_call_done:ok next=-']
limiter: acquires=2 settles=2 pauses=1 tokens left=1,700 of 2,000
2. billing 429: give up at once
ok=False attempts=1 virtual time=0.0 s failure=credit_balance_exhausted
events: ['llm_attempt_failed:quota next=give_up']
limiter: acquires=1 settles=1 pauses=0 tokens left=0 of 2,000
3. two dropped connections, then success
ok=True attempts=3 virtual time=2.0 s failure=None
events: ['llm_attempt_failed:connection next=retry_in_0.46s', 'llm_attempt_failed:connection next=retry_in_0.47s', 'llm_call_done:ok next=-']
limiter: acquires=3 settles=3 pauses=0 tokens left=1,700 of 2,000
4. a 200 with status failed / server_error, then success
ok=True attempts=2 virtual time=1.0 s failure=None
events: ['llm_attempt_failed:failed_outcome next=retry_in_0.25s', 'llm_call_done:ok next=-']
limiter: acquires=2 settles=2 pauses=0 tokens left=1,700 of 2,000
5. our own bug (a bad keyword): propagates, books still balanced
TypeError propagated to the caller: AsyncResponses.create() got an unexpected keyword argument 'max_token'
events: []
limiter: acquires=1 settles=1 pauses=0 tokens left=0 of 2,000
6. total deadline of 0.3 s while the server is silent
ok=False failure=call_deadline_exceeded elapsed=0.3 s | acquires=1 settles=1What to notice:
- Scenario 1: the 429 paused the limiter once and the call slept 3.11 s (the hint plus jitter). Two acquires, two settles. The failed attempt kept its 2,000-token reservation (unknown usage), and the successful one gave back the difference between 2,000 and the real 300, which is why 1,700 tokens are left of 2,000 at the end.
- Scenario 2: a billing 429 gave up at once, with one acquire and one settle, and
pauses=0: a billing error isn't a "slow down" signal. - Scenarios 3 and 4: transport errors and a transient
failedoutcome were retried, and the books balanced each time. - Scenario 5: a misspelt keyword (our bug) propagated as a
TypeError, and thefinallystill settled the reservation. - Scenario 6: the server never answered within the 0.3 s total deadline, so the call stopped at 0.3 s with
call_deadline_exceeded, and settled.
Running many calls at once (bounded concurrency with semaphores and TaskGroup, partial failures in a batch, and the Batch APIs for work that can wait) is 03.9.
13.5 Graceful degradation#
When a call fails for good, your user still needs an answer. Three decisions:
1. What the user sees. Never show a raw provider error: it confuses users and can leak details about your setup. Map each kind of failure to a message and an action:
"""Graceful degradation: what the USER sees for each kind of failure (no network)."""
from llm_errors import Kind
USER_MESSAGE = {
Kind.RATE_LIMITED: ("We're busy right now. Your request is queued and will continue shortly.", "queue"),
Kind.OVERLOADED: ("The assistant is under heavy load. Retrying...", "retry, then fallback model"),
Kind.SERVER_ERROR: ("Something went wrong on our side. Please try again.", "retry, then fail"),
Kind.TIMEOUT: ("This is taking longer than usual. We'll keep trying.", "retry once, then fail"),
Kind.CONNECTION: ("We can't reach the assistant. Check back in a minute.", "retry, then fail"),
Kind.CONFLICT: ("Please try again.", "retry"),
Kind.QUOTA: ("The assistant is temporarily unavailable.", "fail fast + page on-call"),
Kind.AUTH: ("The assistant is temporarily unavailable.", "fail fast + page on-call"),
Kind.PERMISSION: ("This request can't be processed.", "fail, log the reason"),
Kind.CONTEXT_TOO_LONG: ("That's too much text at once. Try a shorter document.", "trim history, then retry"),
Kind.TOO_LARGE: ("That file is too large.", "fail, ask for a smaller input"),
Kind.BAD_REQUEST: ("Something went wrong on our side.", "fail + bug alert (it's our code)"),
Kind.UNKNOWN: ("Something went wrong. Please try again.", "fail, log everything"),
}
for kind, (message, action) in USER_MESSAGE.items():
print(f"{kind.value:<17} {action:<34} user sees: {message}")rate_limited queue user sees: We're busy right now. Your request is queued and will continue shortly.
overloaded retry, then fallback model user sees: The assistant is under heavy load. Retrying...
server_error retry, then fail user sees: Something went wrong on our side. Please try again.
timeout retry once, then fail user sees: This is taking longer than usual. We'll keep trying.
connection retry, then fail user sees: We can't reach the assistant. Check back in a minute.
conflict retry user sees: Please try again.
quota fail fast + page on-call user sees: The assistant is temporarily unavailable.
auth fail fast + page on-call user sees: The assistant is temporarily unavailable.
permission fail, log the reason user sees: This request can't be processed.
context_too_long trim history, then retry user sees: That's too much text at once. Try a shorter document.
too_large fail, ask for a smaller input user sees: That file is too large.
bad_request fail + bug alert (it's our code) user sees: Something went wrong on our side.
unknown fail, log everything user sees: Something went wrong. Please try again.Note the quota and auth rows: the user gets a neutral message, and you get paged. Those failures don't fix themselves, and every request until someone acts will fail the same way.
2. Queue or fail fast. For interactive features (chat, autocomplete), a fast, honest failure beats a long spinner: keep deadlines short and degrade (a simpler answer, a cached one, or "try again"). For background work (summarizing documents, nightly enrichment), queue it: put the job back with a delay that respects Retry-After, so a rate-limit spike becomes a delay rather than lost work (03.9).
3. Fall back to something else. When a provider or model is overloaded or down, the next option is a fallback: a smaller model from the same provider (cheaper, often less loaded), or the same task on another provider (02.9, 10.5). Fall back on transient failures (overload, timeouts, persistent 5xx), not on refusals, bad requests or quota errors (a different model doesn't fix your request, and switching providers to dodge your own spend cap just moves the bill). Lesson 03.11 builds a simple fallback into a provider-agnostic client, where it's easy because every provider returns the same types. Routing, circuit breakers and fleet-level resilience are Module 11C's.
13.6 What to measure#
A reliable call is only reliable if you can see it. The events reliable_call() emits give you everything below for free; what you chart and alert on is 03.10's subject, and dashboards at fleet level are Module 11A's:
| Measure | Where it comes from | What it tells you |
|---|---|---|
| Attempts per call | CallResult.attempts |
Above 1.0 on average means you are leaning on retries; a sudden rise is an incident starting |
| Retry rate | Share of calls with attempts > 1 |
The cost of flakiness, and the load you add to a struggling provider |
| 429 share, split by kind | Failure.kind (rate_limited vs quota) |
rate_limited means slow down or raise a tier; quota means someone must pay |
| Timeout rate, per model | kind == "timeout" |
Timeouts clustered on one model or request type mean the timeout is too short, or the work too big (6.5) |
| Refusal and blocked rate | Outcome.status of refused and blocked, with detail |
A rise after a prompt change is a false-positive problem, not an outage (10.4) |
FAILED rate, with error_code |
Outcome.status == "failed" |
Errors inside a 200 that no status-code dashboard would ever show |
| Rate-limit headroom | tightest() (9.3) |
How close you run to the limit, before the first 429 |
| Latency, p50 and p99 | CallResult.elapsed_s |
The input to your timeout settings |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A 429 means slow down, so retry it." | On every provider some 429s (or 402s and 403s) mean you're out of credits or over a spend cap. Retrying never helps; inspect the code or type first (4.2). |
"except InternalServerError handles Anthropic server problems." |
OverloadedError (529) is a separate class, not a subclass. Catch both (3.3). |
"except genai.errors.APIError catches all Gemini errors." |
Not network errors (raw httpx exceptions) and not any Interactions error (a separate, private family) (2.1, 3.4). |
| "The Gemini SDK retries automatically." | client.models.* makes one attempt unless you pass HttpRetryOptions; only client.interactions.* retries by default. The troubleshooting page describes the enabled behaviour (5.2). |
"The SDK honours Retry-After, so long waits are handled." |
openai gives up immediately when it's over 120 s; anthropic sleeps through any value; google-genai models.* ignores it (5.1, 5.2). |
| "More retries means more reliability." | Retries multiply across layers (24 requests from 4 × 3 × 2) and hammer a struggling provider. One layer owns retries, with a cap, a deadline and a budget (5.5, 7.4). |
| "A timeout means the request didn't happen." | It may have finished server-side and been billed. A retry can bill again and repeat tool side effects (6.6). |
| "The timeout I set is how long the user waits." | It's per attempt, and for streams it's the longest silence. With the SDK's default two retries, a 1 s timeout took 4.2 s to fail. Add a total deadline (6.2). |
"timeout=30 means 30 seconds everywhere." |
In google-genai's HttpOptions it's 30 milliseconds (6.1). |
| "Jitter just adds a bit of randomness." | The formula matters: full jitter spreads a herd of 1,000 retries far better than the SDKs' up-to-25% reduction (7.1). |
"wait_exponential_jitter is full jitter." |
It's exponential plus up to one second; wait_random_exponential is full jitter (8.2). |
| "A 200 means it worked." | Refusals, safety blocks, truncation, empty reasoning-only answers and OpenRouter error bodies all arrive as 200 (Part 10). |
| "A refusal costs nothing." | On Anthropic, a refusal before any output is billed for some categories (bio, frontier_llm, reasoning_extraction), a mid-stream refusal bills what was streamed, and every refusal counts against rate limits (10.4). |
| "A rate limiter that matches my RPM can't trigger a 429." | A bucket that starts full lets a whole minute's budget out at once, and providers may enforce a minute limit over shorter windows. Cap the burst with burst_s (9.5). |
| "Retry until the answer is usable." | Refusals, blocks and truncation repeat; you pay each time. Handle outcomes explicitly (10.4). |
| "The rate-limit headers tell me exactly how much I have left." | Anthropic rounds token values to the nearest thousand, other processes share the limit, and Gemini sends no headers at all (9.3). |
"X-Client-Request-Id makes retries safe." |
It's for correlation and support only. No inference API supports idempotency keys; deduplicate side effects yourself (Part 11). |
Key takeaways#
- Calls fail in four places: transport, HTTP error, error inside a 200, and "successful" responses your app can't use. Each needs a different reaction.
- Classify by the provider's code or type, not just the status. The same
RateLimitErrorcan mean "wait a second" or "out of money". - Retry connection errors, timeouts, 408, 409, rate limits, 5xx and 529. Never retry 400, 401, 403, 404, 413, 422, quota, billing or context-length errors as-is: fix, trim or alert. Obey
x-should-retry. - Know your SDK's defaults:
openaiandanthropicretry twice with 0.5 s→8 s backoff and honourRetry-After(butopenairefuses waits over 120 s);google-genaimodels.*doesn't retry at all unless configured, ignoresRetry-Afterwhen it does, andinteractions.*retries by default with differentattemptssemantics. - Exactly one layer owns retries. Turn SDK retries off (
max_retries=0) when your own policy or a gateway retries. - Timeouts are per attempt. Keep connect short, size read to the work (or to the longest silence for streams), add a total deadline, and remember Gemini's milliseconds and Anthropic's 10-minute guard (stream long outputs).
- A timed-out request may still be billed, and nothing deduplicates it: no inference API supports idempotency keys. Make tool side effects idempotent with your own dedupe keys.
- Back off with full jitter, honour
Retry-Afteras a minimum (capped by your deadline), and bound retries by attempts, total time and a process-wide retry budget. - With
tenacity:retry_if_exception(lambda e: classify(e).retryable),wait_random_exponentialplus a customRetry-Afterwait,stop_after_attempt | stop_before_delay,before_sleep_log,reraise=True. Never wrap streams: they are not retried by the SDKs (one exception:google-genairesumes long Gemini generations from acontinuation_token, 03.3, 4.5b), and anything else is your code's decision. - Rate limits count tokens. Read OpenAI's and Anthropic's headers, look up limits rather than hard-coding them, ramp up gradually, and use a client-side token-bucket limiter that reserves estimates, settles from
usageon every path, and caps its opening burst (burst_s). - Check every 200 with something like
check_response(), and handle refusals, blocks and truncation as outcomes, not retries. Retry only an error inside a 200 whose own code is transient, and know that some Anthropic refusals are billed and have a documented fallback to another model. - Catch provider errors, not your own bugs. The production call handles the SDK and transport exception families only, so a
TypeErrorstill crashes loudly. It has an async twin with a limiter hook that settles on every path. - Log every request ID for every attempt, plus your own call ID, and degrade gracefully: neutral user messages, queue background work, page a human for quota and auth failures.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Transport failure | A failure below HTTP: DNS, TLS, connection refused or reset, or a timeout, with no status code |
| Status exception | An SDK exception for an HTTP 4xx/5xx response, carrying the status, body and request ID |
| Retryable error | A failure caused by timing (busy server, network blip, going too fast) that the same request may survive later |
| Quota / billing error | A failure caused by money or account limits (credits, spend caps, daily quotas); retrying never helps |
Retry-After |
A response header telling the client how long to wait before retrying, in seconds or as an HTTP date |
x-should-retry |
A non-standard header from OpenAI and Anthropic that tells the SDK whether to retry, overriding the status rules |
| Exponential backoff | Doubling the wait after each failed attempt, up to a cap |
| Jitter (full, equal, decorrelated) | Randomness added to backoff waits so clients that failed together don't retry together |
| Thundering herd | Many clients retrying at the same moment and overloading a recovering server |
| Double-retry trap | Retries at several layers multiplying the number of attempts and the waiting time |
| Deadline | A total time budget for an operation, covering every attempt and wait |
| Connect / read / write / pool timeout | The four HTTP client timeouts; read is the longest gap between received bytes, not the total time |
| Retry budget | A process-wide cap on retries as a fraction of normal traffic, so outages don't multiply load |
| Rate-limit headers | Response headers reporting each limit, what remains, and when it resets |
| Acceleration / ramp-rate limit | A limit on how fast your traffic may grow, separate from the per-minute limits |
| Token bucket | A capacity that refills continuously at a fixed rate; each request takes from it |
Burst (burst_s) |
How many seconds' worth of a limit a client-side bucket may hold at once; a small value stops a full bucket from releasing a whole minute's budget in one instant |
| Client-side rate limiter | Code that makes requests wait until they fit within known limits, before the provider rejects them |
| Idempotency key | A client-chosen ID that lets a server recognize and ignore a repeated request; not offered by LLM inference APIs |
| Dedupe key | Your own key for a side-effecting action, used to make sure it runs only once |
| Correlation ID | An ID you generate and send (OpenAI's X-Client-Request-Id) to find a request later; it doesn't deduplicate |
| Graceful degradation | Giving users a sensible, reduced experience when a dependency fails |
Error inside a 200 (FAILED outcome) |
A 200 OK whose body reports a failure (status: "failed", an error object); retry only when its own code is transient |
| Server-side fallback | Anthropic's beta fallbacks parameter, which retries a classifier refusal on another model for you |
Exercises#
All of these run without keys.
- Taxonomy (3.6): add an OpenRouter 402 with
metadata.reason: "in_flight_budget_exhausted"and aRetry-After: 2header tos3_4_mock_errors.py. Which SDK class is raised? Now run it throughclassify()(4.4): what kind and wait does it report, and why is that different from a credits 402? - SDK retries (5.3): in
s5_2_sdk_retries.py, sendretry-after: 120and thenretry-after: 120.5to theopenaiclient. Predict the attempt counts first. Then sendretry-after-ms: 0: what does each SDK do with a zero wait? - Gemini retries (5.2): configure
HttpRetryOptions(attempts=4, initial_delay=0.5, max_delay=4, jitter=0)and count attempts and delays formodels.*and forinteractions.*. Explain the difference in one sentence. - Timeouts (6.2): change the slow server to sleep 0.8 s and re-run. Which calls no longer time out, and what do they raise instead (the handler answers HTTP 500 after its delay)? Then explain why a stream that sends one chunk every 0.8 s for ten minutes would never hit a 1 s read timeout, and write the
asyncio.timeoutwrapper that bounds it at 60 s. - Backoff (7.1): add
max_retries=6to the herd simulation and plot (or print) requests per 100 ms window over time for full and decorrelated jitter. Which finishes its retries sooner? Retry-After(7.3): add tests for" 7 "(spaces),"7.0", and"inf"and"nan"(what should each mean?). Fix the parser if a test fails.- tenacity (8.3): replace
stop_before_delay(20)withstop_after_delay(20)and re-run scenario 3. What changes, and why is it worse for a web request? - Rate limiter (9.5): split the limiter into input and output token buckets (Anthropic-style ITPM/OTPM) and settle each from separate usage numbers. Re-run the simulation with inputs of 1,000 tokens and outputs of 300 against 10,000 ITPM and 3,000 OTPM.
- check_response (10.3): add fixtures for an OpenAI Responses
status: "failed"witherror.code: "server_error", and a Gemini response withfinish_reason: "MALFORMED_FUNCTION_CALL". Are the outcomes what you expect? - Dedupe (11.3): run two threads calling
run_tool_oncewith the same arguments at the same time. Give each thread its own connection to a file database, or connect withsqlite3.connect(":memory:", check_same_thread=False)and a lock (a plain in-memory connection raisesProgrammingErrorwhen used from a second thread). Can both send the email? Fix it with the unique constraint as a lock (insert first, execute second). - Production call (13.2): add a case where a Gemini 429 asks for 3 s (
retryDelay: "3s") twice and then succeeds. Check the recorded sleeps, and that the result lists the provider's response ID. - Async call (13.4): run twenty
areliable_call()tasks withasyncio.gather, all sharing oneRateLimiter(rpm=600, tpm=120_000, burst_s=1)on a virtual clock, against a mock server that answers the first request with a 429 andretry-after: 2. How many requests reach the server before the pause? Does every task finish, and doesacquiresequalsettles?
Hints and checks for the exercises with a predictable result
- 1. The
openaiSDK raises a bareAPIStatusError(there is no 402 subclass).classify()readsmetadata.reasonas the code, so it reportsrate_limited,retryable=Trueand a wait of 2.0 s; a credits 402 has no such code and falls to thestatus == 402rule, so it isquotaand not retryable. The in-flight budget clears by itself, credits don't. - 2.
openairetries aretry-afterof exactly 120 (it is not over the limit) and sleeps 120 s between attempts, so three attempts; at 120.5 it makes one attempt and raises.retry-after-ms: 0is not a usable wait (it must be above zero), so both SDKs fall back to their normal backoff. - 3.
models.*: 4 attempts in total, with waits of 0.5, 1 and 2 s (no jitter), whateverretry-aftersays.interactions.*:attempts=4means 4 retries, so 5 calls. One sentence: the same option counts attempts on one API and retries on the other. - 4. With a 0.8 s delay nothing exceeds the 1 s timeout, so each call raises the 500 the handler returns:
InternalServerErroronopenaiandanthropic(and on Interactions, after its default retries),genai.errors.ServerErroronmodels.*. A stream that sends a chunk every 0.8 s resets the read timer each time, so only gaps over 1 s count; bound it withasync with asyncio.timeout(60): async for chunk in stream: .... - 6. All three of the cases you were asked to add pass as written, because the parser strips spaces, accepts floats and reads the offset in the date.
"inf"and"nan"both come back asNone: they fail the0 <= value <= MAX_SANE_DELAYcheck, which is the right answer (no usable hint). - 7. With
stop_after_delay(20)the policy checks the budget only after an attempt fails, so it sleeps the server's 121 s, makes a second attempt (the mock then succeeds) and returns after two minutes: a web request would have timed out long before. - 9. The Responses
failed/server_errorfixture is already case 6 in the table, witherror_code=server_error.MALFORMED_FUNCTION_CALLhas no special rule in_gemini(), so it isINCOMPLETEwith that finish reason as itsdetail; decide whether your application should treat it as retryable (it is a model failure, not a network one). - 10. Both threads can run the
SELECT, find nothing and send the email before either inserts. Insert the key first (thePRIMARY KEYmakes the second insert raisesqlite3.IntegrityError) and run the tool only if the insert succeeded. - 11. The 3 s hint is under
max_server_wait_s=20, so the recorded sleeps are two values of about 3.0 to 3.25 s. Failed Gemini attempts expose no request ID, sorequest_idsholds only the response ID of the final successful call.
Check yourself#
- Name the four kinds of failure and give one example of each.Transport (connection refused, DNS failure, timeout); HTTP error (429 rate limit, 400 bad request); error inside a 200 (a mid-stream
overloaded_errorevent, an OpenRouter 200 with anerrorbody); successful failure (stop_reason: "refusal",finish_reason: "length", a Gemini prompt block). - Your code catches
openai.APIErrorfirst andopenai.APITimeoutErrorsecond. What happens on a timeout?TheAPIErrorclause catches it, becauseAPITimeoutErroris a subclass ofAPIConnectionError, which is a subclass ofAPIError. The timeout branch never runs. Order clauses from specific to general. - A Claude call fails during a busy period, but your
except anthropic.InternalServerErrordoesn't catch it. Why?529 raisesOverloadedError, which subclassesAPIStatusErrordirectly, notInternalServerError. Catch both. - How do you tell an OpenAI "slow down" 429 from an "out of credits" 429 in code? And Anthropic's spend cap?OpenAI: both are
RateLimitError; checke.code(slow_downvscredit_balance_exhaustedand the*_limit_exceededcodes;e.typemay sayinsufficient_quota). Anthropic: both arerate_limit_error; the spend cap haserror.details.error_code == "enforced_spend_limit_reached"and noretry-after. - Your
generate_contentcalls fail on every brief network blip, though Google's docs say the SDK retries. What's going on, and what's the fix?Ingoogle-genai2.34.0,client.models.*makes exactly one attempt unless you passHttpOptions(retry_options=HttpRetryOptions(...)); the docs describe the behaviour once enabled. Also, network errors arrive as rawhttpxexceptions, notgenai.errors.APIError. Configureretry_options(or retry in your own layer), and catchhttpx.TransportError. - What does
openaido with aRetry-After: 300on a 429? What doesanthropicdo?openaidoesn't retry at all: any server delay over 120 s makes it raise immediately.anthropicsleeps 300 s before each of its retries. - Your code retries 4 times, the SDK keeps its defaults, and a gateway retries twice. How many provider requests can one call make? What should you change?4 × 3 × 2 = 24. Make one layer own retries: turn SDK retries off (
max_retries=0) and keep only your policy, or rely on the gateway and reduce your own. - What does
HttpOptions(timeout=60)mean ingoogle-genai?60 milliseconds, which makes almost every request fail. 60 seconds istimeout=60_000. - Why does the
anthropicSDK raiseValueErrorformax_tokens=32000without streaming, and what are two ways to avoid it?Non-streaming requests are expected to take 60 min ×max_tokens/ 128,000; 32,000 tokens means 15 minutes, over the 10-minute limit, and long silent connections get dropped by networks. Stream the request (stream=Trueormessages.stream()), or pass an explicit timeout (client or per call); or use the Batch API. - Why is a retry after a client-side timeout risky, even when the request has no tool calls?The provider may have completed the first request and billed it; the retry is billed again. No inference API supports idempotency keys, so nothing on the provider side deduplicates.
- Why is full jitter better than plain exponential backoff when many clients fail at once?Without jitter, clients that failed together retry at exactly the same moments, so the recovering server gets the full load in bursts. Full jitter spreads each retry uniformly between zero and the exponential value, flattening the load.
- Your server returns
Retry-After: Wed, 04 Nov 2026 10:00:30 GMT. What does the client do, and what should it do if that's an hour away?Wait until that time (plus a small random delay), then retry. If it's an hour away and the call is interactive, don't wait: fail with a clear message (or queue background work) and let a later job retry. - Why use
reraise=Truewithtenacity, and whystop_before_delayrather thanstop_after_delayfor a deadline?reraise=Trueraises the original SDK exception (soexcept RateLimitErrorande.codestill work) instead oftenacity.RetryError.stop_before_delayrefuses to start a sleep that would end past the deadline;stop_after_delayonly checks after an attempt, so it can sleep far beyond it. - On OpenAI, why does setting
max_output_tokensfar higher than you need reduce throughput, while on Anthropic it doesn't?OpenAI counts a request against TPM as the maximum ofmax_tokensand an estimate of the input, so a large cap reserves capacity you don't use. Anthropic's OTPM counts the tokens actually generated: "Themax_tokensparameter does not factor into OTPM." - Name three HTTP-200 responses that are not usable answers, from three different providers.For example: OpenAI Responses
status: "incomplete"with reasonmax_output_tokensand only a reasoning item; Anthropicstop_reason: "refusal"; Geminiprompt_feedback.block_reason: PROHIBITED_CONTENTwith no candidates; OpenRouter{"error": {...}}with nochoices. - Why can't you use the provider's tool-call ID to deduplicate a side effect after a retried request?A retried request is a new generation, and the model assigns new tool-call IDs, so the duplicate action would look new. Use your own stable key: conversation or job ID, tool name and canonical arguments, or a business ID.
- A limiter built with
RateLimiter(rpm=600, ...)sends 600 requests in the first instant. Why can that still earn 429s, and what doesburst_s=1change and not change?The bucket starts full, and a full bucket holds a whole minute's budget. Providers may enforce a minute limit over shorter windows (Anthropic: 60 RPM "might be enforced as 1 request per second"), so a burst of 600 in one instant can exceed it.burst_s=1makes each bucket hold one second's worth, so only about 10 requests can leave at once (about 20 in the first second). It does not change the refill rate, so the sustained speed is still 600 RPM.
Further resources#
- OpenAI, Error codes and Rate limits guides: every error code with causes, tiers, headers and backoff advice.
- Anthropic, Errors and Rate limits: error types, request size limits, long requests, tiers, the spend cap and every rate-limit header. Also Refusals and fallback (refusal categories, billing,
fallbacks) and the Rate Limits API. - Google, Gemini API Troubleshooting, API errors (Interactions codes) and Rate limits.
- OpenRouter, Errors and debugging and Limits: error metadata, typed error types, mid-stream errors, budgets and free-model limits.
- SDK source: openai-python, anthropic-sdk-python and python-genai. The retry logic is in each SDK's
_base_client.py(and_api_client.pyforgoogle-genai): short, and the final word on behaviour. - Marc Brooker, "Exponential Backoff And Jitter" (AWS Architecture Blog, 2015): the four jitter formulas and why jitter matters.
- Google,
google.rpcerror details: theRetryInfoandQuotaFailuremessages that Google APIs put in error bodies. - IETF, RFC 9110, section 10.2.3 (
Retry-After) and RFC 6585, section 4 (429 Too Many Requests). - tenacity documentation: every stop, wait and retry strategy, with async support.
← 03.7 — Token Counting, Cost Tracking and Prompt Caching | Module 03 overview | 03.9 — Async, Concurrency and Batch Processing →