Errors, Timeouts and Retries
A call to a language model travels over a network to a service you do not control, so sooner or later one of them fails. Some failures clear up if you simply try again a moment later, others repeat until you change something, and a few leave a person staring at a frozen terminal for minutes. This page sorts those failures, shows how a Python client library reports each one, and explains how retries, waiting and time limits turn them into a program that either answers or says clearly why it cannot.
The ways a model call can fail
A model call is one HTTP request: your program sends it to the provider's address, the provider checks it, the model writes a reply, and the reply travels back. A failure can happen at two very different places along that path, and the difference decides everything that follows.
Either no answer arrives at all: the connection could not be opened, it broke halfway, or the answer took longer than your program was willing to wait. Or an answer arrives, but it is an error: the provider received the request and replied with an HTTP status code that says what went wrong. A status code in the 400s says the problem lies with the request or the caller; one in the 500s says the problem lies with the server.
- your program
- model provider
- No answer arrives
- lost connection, timeout
- An error status comes back
- 400 request, 401 key, 429 limit, 5xx server
Six failures cover nearly everything a model call runs into. Each one has a cause you can name and a status code, or none when nothing came back.
| Failure | Status | What happened |
|---|---|---|
| Rejected request | 400 | The request is malformed or misses a required parameter, or names a setting the model does not accept. |
| Bad key | 401 | The API key is wrong, expired or revoked. |
| Rate limit | 429 | Too many requests or tokens in a short time, or the account ran out of credit. |
| Server error | 500 and above | Something broke or was overloaded on the provider's side. |
| Lost connection | none | The network, a proxy, a firewall or a wrong address stopped the request before any answer came. |
| Timeout | none | The answer did not arrive within the time limit the client set. |
Three more codes show up less often: 403 when the key is valid but has no access to what it asked for, 404 when the address or the model name points to nothing, and 422 when the request is well formed but its content cannot be processed.
One exception type per failure
A client library turns each of these failures into a Python exception, and it gives each kind its own class, so your code can tell them apart with ordinary except clauses. The openai package, which also talks to the many providers and local servers that accept the same Chat Completions format, arranges its exceptions as a family tree. Every one of them inherits from openai.APIError, and below that the tree splits along the same line as the picture of the path: no answer, or an error answer.
- APIError
- APIConnectionError no response
- APITimeoutError no response
- APIStatusError has status_code
- BadRequestError 400
- AuthenticationError 401
- PermissionDeniedError 403
- NotFoundError 404
- UnprocessableEntityError 422
- RateLimitError 429
- InternalServerError 500 and above
- APIError to APIConnectionError
- APIConnectionError to APITimeoutError
- APIError to APIStatusError
- APIStatusError to BadRequestError
- APIStatusError to AuthenticationError
- APIStatusError to PermissionDeniedError
- APIStatusError to NotFoundError
- APIStatusError to UnprocessableEntityError
- APIStatusError to RateLimitError
- APIStatusError to InternalServerError
On the status side, APIStatusError carries the answer that came back: status_code, the full response, and request_id, the identifier a provider's support team can look up. Each subclass stands for one fixed code, except InternalServerError, which covers every code from 500 up.
On the connection side there is no status code, because no response ever arrived. A timeout sits inside this branch: APITimeoutError is a subclass of APIConnectionError.
That matters for the order of your except clauses. Python runs the first clause that matches, and a clause for a class also matches all its subclasses. So if you want a different message for a timeout, its clause has to come before the clause for connection errors. In the same way, the specific status errors have to come before APIStatusError.
import openai
try:
response = client.chat.completions.create(model=model_name, messages=messages)
except openai.APITimeoutError:
print("The model took too long to answer.")
except openai.APIConnectionError as e:
print("Could not reach the model:", e.__cause__)
except openai.RateLimitError as e:
print("Rate limit reached:", e.message)
except openai.APIStatusError as e:
print("The provider answered", e.status_code, e.message)For a connection error, e.__cause__ holds the lower-level exception raised by the HTTP library underneath, which often names the real reason, such as a name that could not be resolved.
True or false?
An except clause for APIConnectionError also catches a timeout.
True. APITimeoutError is a subclass of APIConnectionError, so the broader clause matches it too. Put the timeout clause first when the two need different handling.
Every exception the client raises has a status_code you can read.
False. Only APIStatusError and its subclasses carry one. A lost connection or a timeout has no status code, because no response arrived.
Retry or fix
Once a failure has a name, the most useful question about it is whether trying again could change the result. Some failures are transient: they depend on the moment, such as a busy server, a network glitch, or a burst of traffic that pushed you over a limit. A second attempt a little later may well succeed. Others are permanent for the request as it stands: a wrong key is still wrong a second later, and a malformed request is rejected the same way every time. Retrying those only wastes time and, with a rate limit, part of your allowance. They are fixed by changing the request or the settings.
| Failure | Retry or fix | What helps |
|---|---|---|
| Lost connection | Retry | Try again; if it keeps failing, check the network, proxy and base URL. |
| Timeout | Retry | Try again after a short wait. |
| Server error (500 and above) | Retry | Try again after a short wait. |
| Rate limit (429) | Retry, after waiting | Wait as long as the provider asks, then try again; slow down if it recurs. |
| Quota or credit used up (429) | Fix | Add credit or raise the spending limit; no retry restores access. |
| Bad key (401), no access (403) | Fix | Correct the key or its permissions. |
| Rejected request (400, 404, 422) | Fix | Correct the request: parameters, model name, address. |
One status code needs a closer look. A 429 usually means a temporary limit, but some providers also send 429 when the account's credit or spending limit is used up, and that one does not pass with time. The status code alone cannot tell them apart; the error's code field can (OpenAI, for example, uses credit_balance_exhausted for an empty balance), so read e.code before deciding to wait.
True or false?
A 401 from the provider is worth retrying a few times, because keys are sometimes checked slowly.
False. A 401 means the key itself was refused. It comes back the same on every attempt until the key in the settings changes.
A 503 from an overloaded server can succeed when the same request is sent again a little later.
True. A server error depends on the state of the server at that moment, so it is a failure worth retrying after a short wait.
Rate limits
A provider shares its servers among many customers, so it caps how much each account or project may use in a stretch of time. The usual measures are requests per minute and tokens per minute, and some providers add daily limits too. Whichever limit you reach first applies: a few very long requests can exhaust the token limit while the request count is still low.
The token count of a request is reserved before the reply is written, so it includes the reply cap you set. A generous cap on every call uses up the tokens-per-minute budget faster, even when the actual replies are short.
When a request goes over a limit, the provider answers with status 429 Too Many Requests. Along with the response come headers: pairs of a name and a value that describe it. Many providers use headers to say how long to wait and how much of each limit remains. In the example below the values are invented, and the x-ratelimit names are the ones OpenAI uses (other providers name theirs differently, or send none).
HTTP/1.1 429 Too Many Requests
retry-after: 20
x-ratelimit-limit-requests: 500
x-ratelimit-remaining-requests: 0
x-ratelimit-reset-requests: 20s
x-ratelimit-limit-tokens: 200000
x-ratelimit-remaining-tokens: 184000Retry-After is a standard HTTP header: a number of seconds, or a date, before which a retry is pointless. Treat it as a minimum. Sending the request again right away does not help either, because failed requests count against the per-minute limit as well, so rapid retries keep you over it.
True or false?
Retrying immediately and repeatedly is the fastest way past a rate limit.
False. Failed requests count toward the per-minute limit too, so quick retries keep the account over it. Waiting at least the time the provider asks is what lets the next request through.
An account can hit its tokens-per-minute limit while it is still well under its requests-per-minute limit.
True. The limits are counted separately and the first one reached applies. A few requests with long prompts or large reply caps can use up the token budget first.
Backoff, and the retries the client already makes
A retry that fires at once usually meets the same busy server or the same full limit. Backoff means waiting before each new attempt, and waiting longer each time. In exponential backoff the wait doubles after every failure. A short hiccup then costs little, and a longer outage is not hammered with requests.
One problem remains. When a server fails, many clients fail at the same moment, and if they all wait the same time, they all retry at the same moment too. A small random change to each wait, called jitter, spreads their retries apart.
The openai client does all of this on its own, before your code sees any exception. By default it retries a failed call 2 times, so a call makes up to 3 attempts. It retries only the failures that may pass: lost connections and timeouts, 408 (the server gave up waiting for the request), 409 (the request clashed with another one in progress), 429 and every code from 500 up. It never retries 400, 401, 403, 404 or 422.
How long it waits depends on the response. When the response carries Retry-After (up to two minutes), it waits that long. When the server asks for more than two minutes, it does not retry at all and raises the error. Otherwise it waits \( \min(0.5 \cdot 2^{n},\ 8) \) seconds, where \( n \) counts the retries already made, and takes off a random amount of up to a quarter as jitter.
seconds against n
- n = 0 0.5
- n = 1 1
- n = 2 2
- n = 3 4
- n = 4 8
- n = 5 8 (cap)
You choose the number of retries with max_retries, on the client for every call or on one call with with_options. 0 switches the automatic retries off.
from openai import OpenAI
client = OpenAI(max_retries=3) # every call: up to 4 attempts
response = client.with_options(max_retries=0).chat.completions.create(
model=model_name,
messages=messages,
) # this call: one attempt onlyBecause the client already retries, a retry loop of your own around the call multiplies the attempts instead of adding to them. Three attempts of your own around a client that makes three attempts each send up to nine requests, and each round waits through the client's backoff first. Keep one layer: either trust the client's retries and set their number on purpose, or set max_retries=0 and write your own loop with backoff, a limit on the attempts and a limit on the total time spent.
True or false?
A call with no retry code of your own fails on the first 429 it receives.
False. The client retries a 429 twice by default, with backoff, before it raises RateLimitError. Your code sees the exception only after those attempts are used up.
Wrapping the call in your own loop of 3 attempts, with the client left at its defaults, can send 9 requests.
True. Each of your attempts makes up to 3 requests of its own (1 plus 2 automatic retries), so 3 times 3 gives 9.
A time limit on every call
A request that never fails can still never finish: a server stalls, a connection hangs without breaking, and the program waits. A timeout is the longest a client waits before it gives up on the request and raises APITimeoutError.
The openai client's default is generous: 10 minutes, with 5 seconds to open the connection. That suits a batch job that runs unattended and must not give up on a slow, long reply. It does not suit a program a person is sitting in front of. With the default timeout and the default 2 retries, a stalled call can keep a terminal silent for half an hour before any message appears.
minutes
- default, 600 s each about 30 min
- 20 s each about 1 min
Set the limit on purpose, from how long your reply can reasonably take. A number sets one limit for each phase of the request, on the client or on a single call; an httpx2.Timeout object (the HTTP library the current client is built on) sets the phases separately.
import httpx2
from openai import OpenAI
client = OpenAI(timeout=20.0) # 20 seconds for each phase
client = OpenAI(
timeout=httpx2.Timeout(30.0, connect=3.0),
) # 3 s to connect, 30 s for the rest
client.with_options(timeout=60.0).chat.completions.create(
model=model_name,
messages=messages,
) # one slow call gets longerThe phases are connect (opening the connection), write (sending the request), read (waiting for data to come back) and pool (waiting for a free connection).
The read timeout is the longest wait for the next piece of data, not a deadline for the whole call. For an ordinary call that is not streamed, the server usually sends nothing until the reply is finished. In practice, then, the read timeout limits how long the model may take to write its reply.
The connect timeout can be short. When the address is right, opening a connection takes well under a second, so a long wait there means the address is wrong or the network is down.
A timeout counts as a failure worth retrying, so the client retries a timed-out call too. The longest wait is therefore roughly the timeout times the number of attempts, plus the backoff between them; choose the two numbers together.
True or false?
With timeout=20.0, a call can never take longer than 20 seconds in total.
False. The number limits each phase, and the read timeout is the wait for the next piece of data. The client also retries a timed-out call, so the total can be several times 20 seconds.
A client left at its default timeout can wait 10 minutes on a single attempt before it gives up.
True. The default is 600 seconds (5 seconds to connect), long enough for unattended jobs and far too long for someone waiting at a terminal.
When the model cannot be reached
Put together, a program a person waits on sets a timeout it can defend, leaves the retries to the client at a number it chose, and catches what still comes through after those retries are spent. By then a retryable failure has already been retried, so the program's job is no longer to try again but to stop with a message that says what happened and what the person can do about it.
import sys
import openai
from openai import OpenAI
client = OpenAI(timeout=20.0, max_retries=2)
def ask(model_name, messages):
try:
response = client.chat.completions.create(model=model_name, messages=messages)
except openai.APITimeoutError:
sys.exit("The model did not answer in time, even after retrying. Try again later.")
except openai.APIConnectionError:
sys.exit("Could not reach the model. Check the network and the base URL.")
except openai.AuthenticationError:
sys.exit("The API key was refused. Check the key in your settings.")
except openai.RateLimitError as e:
sys.exit(f"Rate limit or quota reached ({e.code}). Wait, or check your plan.")
except openai.APIStatusError as e:
sys.exit(f"The provider refused the request ({e.status_code}): {e.message}")
return response.choices[0].message.contentsys.exit with a string prints the string to the error output and ends the program with exit status 1, so a script that calls this one can also see that it failed. Each message names the failure in plain words and points to the fix: a person reading "the API key was refused" knows to check the key, while a traceback ending in a status code leaves them guessing.