Sub topic 10
Using the retry settings built into provider SDKs
Most hosted LLM providers ship an official Python SDK that already retries failed requests. Before you write a retry loop, check what your SDK does and configure it. This chapter covers what SDK retries typically include, which settings to change, and where they fall short.
This chapter assumes you have read the earlier chapters on retryable errors, exponential backoff, jitter, Retry-After, timeouts, and retry limits. It also assumes you have called an LLM API from Python.
What SDK retries usually cover
Provider SDKs implement the same ideas you built by hand. The details differ by vendor and version, so check your SDK's documentation. The OpenAI and Anthropic Python SDKs behave like this:
- They retry connection errors, request timeouts (408), conflicts (409, in the OpenAI SDK), rate limits (429), and server errors (5xx).
- They do not retry other 4xx errors such as 400, 401, 403, and 404. These raise an exception immediately.
- They wait with exponential backoff and a small amount of jitter between attempts.
- They honor a
Retry-Afterheader when its value is short enough. The OpenAI SDK, for example, uses it only when it is at most 60 seconds, and otherwise falls back to its own backoff. - They stop after a fixed number of retries and raise the last error.
Both SDKs default to 2 retries and a timeout of 10 minutes. Treat those numbers as starting points to verify, not as settings to trust. A 10-minute timeout is far too long for most interactive applications.
Replace that block with the diagram below.
Configuring the client
Set max_retries and timeout when you create the client. You can override them for a single call with with_options.
from openai import OpenAI
# The SDK retries connection errors, 408, 429, and 5xx responses with backoff.
client = OpenAI(max_retries=5, timeout=20.0)
# Settings can also be overridden for a single call.
response = client.with_options(max_retries=2, timeout=10.0).chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Say hello."}],
)
print(response.choices[0].message.content)This code reads your API key from the OPENAI_API_KEY environment variable. with_options returns a copy of the client, so the original keeps its settings.
The Anthropic SDK uses the same parameter names:
import anthropic
client = anthropic.Anthropic(max_retries=3, timeout=20.0)
message = client.messages.create(
model="claude-3-5-haiku-latest",
max_tokens=100,
messages=[{"role": "user", "content": "Say hello."}],
)
print(message.content[0].text)Setting max_retries=0 turns SDK retries off. You need this when you manage retries yourself, as described below.
Other SDKs name things differently
Not every SDK follows this pattern. AWS's boto3, used for Amazon Bedrock, configures retries through a Config object with a retry mode.
import boto3
from botocore.config import Config
config = Config(
retries={"mode": "standard", "total_max_attempts": 5},
read_timeout=60,
connect_timeout=5,
)
bedrock = boto3.client("bedrock-runtime", config=config)Here total_max_attempts counts the first try plus retries, so 5 means at most 4 retries. The related max_attempts key counts retries only. The adaptive mode adds client-side rate limiting on top of standard. Mixing up "attempts" and "retries" is a common source of off-by-one surprises, so read each SDK's definition.
| Setting | Meaning in most SDKs | Common pitfall |
|---|---|---|
| `max_retries` | Extra attempts after the first | Total calls are `max_retries + 1` |
| `timeout` | Limit for one attempt | Does not bound the whole operation |
| Retry mode (boto3) | Rules for which errors and delays apply | `legacy` is the default in older setups, so choose a mode explicitly |
Timeouts apply per attempt
SDK timeouts normally apply to each attempt, not to the whole call. With max_retries=5 and timeout=20.0, a call that always times out can take six attempts of 20 seconds each plus backoff, which is more than two minutes. The SDK does not know about your request's deadline.
To bound the total, either lower both settings or wrap the call in your own deadline. In async code, asyncio.timeout works well:
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(max_retries=3, timeout=15.0)
async def ask(prompt: str) -> str:
# Hard ceiling for the whole operation, including all SDK retries.
async with asyncio.timeout(45):
response = await client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content
print(asyncio.run(ask("Say hello.")))asyncio.timeout needs Python 3.11 or later. When it fires, it cancels the in-flight attempt and raises TimeoutError.
You can also use a finer-grained timeout object. The SDKs accept httpx.Timeout, which lets you fail fast when a connection cannot be made but allow a long read for a slow generation:
import httpx
from openai import OpenAI
client = OpenAI(
max_retries=3,
timeout=httpx.Timeout(60.0, connect=5.0),
)Do not stack retry layers
The most common mistake is adding your own retry loop around an SDK that already retries. Retries multiply. An SDK that makes 3 attempts inside a loop of 5 attempts makes up to 15 requests for one logical call. Against a rate-limited service, those extra requests can keep you throttled for longer.
Pick one layer:
- Use the SDK's retries and keep your code simple. This suits most applications.
- Set
max_retries=0and write your own loop. Do this when you need a shared retry budget, a circuit breaker, custom logging, or retries across several providers.
If you take option 2, handle the SDK's exception types rather than raw status codes:
import openai
client = openai.OpenAI(max_retries=0, timeout=20.0)
try:
client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Say hello."}],
)
except openai.RateLimitError as exc:
print("429, Retry-After:", exc.response.headers.get("retry-after"))
except openai.APIConnectionError as exc:
# Includes openai.APITimeoutError, a subclass for timeouts.
print("network problem:", type(exc).__name__)
except openai.APIStatusError as exc:
print("HTTP error:", exc.status_code)Order matters here. RateLimitError and APIConnectionError are both caught before the more general APIStatusError, and your loop would decide which of them to retry.
What the SDK does not give you
Built-in retries are a good default, but they leave gaps.
- They are silent. A call that succeeds on the third attempt looks identical to one that succeeds on the first, except for latency. You cannot see how often you are being throttled.
- They cannot recover a stream. Retries happen before the response begins. If a connection drops halfway through a streamed answer, the SDK raises an error. It does not replay the stream, because the partial text has already reached your code.
- They have no shared budget. Each client call retries independently. If 100 concurrent requests all hit 429, all 100 retry, which adds load.
- They have no circuit breaker or fallback. The SDK keeps trying every call for as long as you keep calling.
- They do not check idempotency. The SDK retries your
POST. For plain text generation this is safe, but if your call has side effects, such as a tool that sends an email, a retry may repeat them.
You can make retries visible without rewriting them. Both SDKs let you pass a custom httpx client, and an event hook on it runs for every attempt:
import httpx
from openai import OpenAI
def log_response(response: httpx.Response) -> None:
print("attempt:", response.request.url, response.status_code)
client = OpenAI(
max_retries=3,
timeout=20.0,
http_client=httpx.Client(event_hooks={"response": [log_response]}),
)Each retry that receives an HTTP response prints a line, so a 429 followed by a 200 shows up as two lines. Attempts that fail with a connection error never get a response, so this hook does not see them. The observability chapter covers that case.
Choosing settings
Start from the user's patience, then work backward.
- Interactive requests: a total deadline of 30 to 60 seconds, a per-attempt timeout of 10 to 20 seconds, and 2 to 3 retries.
- Background jobs: a longer deadline and more retries are acceptable, since nobody waits on the result. Add client-side throttling so retries do not make a rate limit worse.
- Long generations: allow a long read timeout, but keep the connect timeout short.
Exercise
An application sets OpenAI(max_retries=4, timeout=15.0) and wraps each call in its own loop of 3 attempts that catches openai.APIError. The API is returning 503 for every request. What is the largest number of HTTP requests one logical call can send, and what is the fix?
Show answer
The SDK makes 5 requests per call (1 first try plus 4 retries), and the outer loop makes 3 calls, so up to 15 requests. Worst-case time is also large: 15 attempts of up to 15 seconds each, plus backoff. The fix is to keep only one retry layer. Either remove the outer loop and rely on the SDK, or set max_retries=0 and keep the loop, which then gives 3 requests per logical call. Adding an overall deadline, such as asyncio.timeout, bounds the total time in both cases.