Sub topic 8
Understanding errors and rate limits
This chapter assumes you can already send a chat request and read the response, as covered in the earlier chapters. You should also know what HTTP status codes are and be comfortable reading JSON in Python. By the end you will be able to read an error response, decide whether to retry it, and explain why a request that looked fine was rejected with a 429.
Three places a call can fail
A failed LLM call is not always an HTTP error. Failures show up in three layers, and each needs different handling.
- Transport failures. No HTTP response arrives. Examples are a DNS failure, a refused connection, a dropped connection, or a timeout. Your HTTP library raises an exception.
- HTTP errors. The server answers with a 4xx or 5xx status and usually a JSON error body.
- Problems inside a successful response. The status is 200, but the result is not what you wanted. The most common case is
finish_reasonequal to"length", which means the reply was cut off at yourmax_tokenslimit. Some providers also return"content_filter"or a refusal.
Calling raise_for_status() only covers layer 2. This chapter covers layers 1 and 2 and the rate-limit behavior that causes most of the errors you will see in practice. The next chapter builds the retry loop on top of this classification.
Status codes and what to do with them
The codes below follow the widely used chat-completions convention. Providers differ in details, so check your provider's error documentation.
| Status | Typical meaning | Retry? | What to do |
|---|---|---|---|
| 400 | Malformed request, bad parameter, or context length exceeded | No | Fix the payload or shorten the prompt |
| 401 | Missing, wrong, or revoked API key | No | Check the key and the `Authorization` header |
| 403 | Key is valid but not allowed (region, model access, organization policy) | No | Check permissions and model access |
| 404 | Unknown model name or endpoint path | No | Check the model name and URL |
| 413 | Request body too large | No | Reduce the payload |
| 422 | Well-formed JSON with invalid values | No | Fix the field the error names |
| 429 | Rate limit hit, or quota exhausted | Sometimes | Read the error code, then wait or stop |
| 500 | Server-side failure | Yes | Retry with backoff |
| 502, 503, 504 | Gateway failure, overload, or upstream timeout | Yes | Retry with backoff |
The rule behind the table is simple. A 4xx error means the request itself was rejected, so sending the same bytes again gives the same answer. The one exception is 429, because the same request can succeed once the limit window moves on. A 5xx error means the server had a problem, so a retry may succeed.
Reading the error body
Most chat-completions-style APIs return a JSON body shaped like this:
{
"error": {
"message": "This model's maximum context length is 128000 tokens. However, your messages resulted in 131002 tokens.",
"type": "invalid_request_error",
"param": "messages",
"code": "context_length_exceeded"
}
}The message is for humans. The code and type are meant for programs, so branch on those and log the message. Two cautions apply. First, the exact field names and code strings vary between providers. Second, gateways and proxies in front of the API can return HTML or plain text instead of JSON, especially for 502 and 504. Your code must not assume the body parses as JSON.
Two kinds of 429
A 429 status means "too many requests", but it covers two different situations.
- Rate limit exceeded. You sent too much in a short window. Waiting fixes it.
- Quota exceeded. Your account has no credit left or has hit a monthly spending cap. Waiting does not fix it, and retrying only wastes time. Some providers signal this with a distinct code such as
insufficient_quota.
Treat these differently. Retrying a quota error in a loop hides a billing problem behind a stream of delayed failures.
How rate limits work
Providers limit usage along several dimensions at once. You are blocked when you exceed any one of them.
- Requests per minute (RPM). The number of calls, regardless of size.
- Tokens per minute (TPM). The total tokens processed. Providers often count your prompt tokens plus the output budget you reserved with
max_tokens, and the count may be an estimate made before generation starts. A largemax_tokenscan therefore trigger a limit even when the actual reply is short. - Daily or monthly caps. Limits on requests, tokens, or spend over longer windows.
- Concurrency. A cap on simultaneous in-flight requests.
Limits are usually tied to your account tier and the model. A bigger model often has lower limits, and limits typically rise as your usage history and spending grow.
Many providers report the limits in response headers. The names vary, but you will often see ones like these:
Retry-After: seconds to wait before trying again. Honor it when present.x-ratelimit-remaining-requestsandx-ratelimit-remaining-tokens: how much budget is left in the current window.x-ratelimit-reset-requestsandx-ratelimit-reset-tokens: when the budget refills.
The rate-limit headers are not guaranteed on every response. Read them defensively with resp.headers.get(...), and log them so you can see how close to the limit you run.
Classifying errors in code
The function below turns a response into a decision: a category, whether a retry makes sense, and a message to log. It tolerates bodies that are not JSON.
import os
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
def classify(resp):
"""Return (category, retryable, message) for a non-2xx response."""
try:
body = resp.json()
except ValueError:
body = None
err = body.get("error") if isinstance(body, dict) else None
if not isinstance(err, dict):
err = {}
code = err.get("code")
message = err.get("message") or resp.text[:200]
status = resp.status_code
if status == 429:
if code == "insufficient_quota":
return "quota", False, message
return "rate_limit", True, message
if status == 401:
return "auth", False, message
if status == 403:
return "forbidden", False, message
if code == "context_length_exceeded":
return "context_too_long", False, message
if 400 <= status < 500:
return "bad_request", False, message
if status >= 500:
return "server", True, message
return "unknown", False, message
payload = {
"model": os.environ["LLM_MODEL"],
"messages": [{"role": "user", "content": "Say hello."}],
}
try:
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
except (requests.ConnectionError, requests.Timeout) as exc:
print("transport error, retryable:", exc)
else:
if resp.ok:
choice = resp.json()["choices"][0]
print(choice["message"]["content"])
if choice["finish_reason"] == "length":
print("warning: reply was truncated by max_tokens")
else:
category, retryable, message = classify(resp)
print(f"{resp.status_code} {category} retryable={retryable}: {message}")
print("Retry-After:", resp.headers.get("Retry-After"))The function checks the insufficient_quota code before the generic 429 branch, so a billing problem is never treated as a temporary limit. It also checks the context-length code before the generic 4xx branch, so you can respond to that case by trimming history instead of showing a vague "bad request".
The decision flow
Common mistakes
- Retrying every error. Retrying a 401 or a 400 never helps. It delays the failure and can burn through a rate limit while doing nothing useful.
- Retrying instantly. A 429 means you are already over the limit. Immediate retries keep you over it. Wait first, and use the delay from
Retry-Afterwhen the server provides one. - Ignoring
finish_reason. A truncated JSON reply passesraise_for_status()and then fails later in your parser with a confusing message. - Setting
max_tokensfar above what you need. On providers that count the reserved output budget against TPM, this lowers your effective throughput. - Assuming the body is JSON. A gateway timeout may return an HTML page. Guard the parse, as
classifydoes. - Logging the full request on error. The payload can contain user data. Log the status, the error code, and a request ID if the provider returns one in a header, and avoid dumping prompts into shared logs.
Staying under the limit
Better error handling does not remove the need to avoid errors in the first place.
- Cap concurrency to a number you have measured, and raise it gradually.
- Set
max_tokensclose to the real need. - Track tokens used per minute from the
usagefield and slow down before you reach the limit. - Move non-urgent work, such as bulk classification, to a batch interface if your provider offers one. Batch interfaces usually have separate and higher limits.
- Request a higher tier or limit increase from the provider when your steady workload needs it.
Exercise
Your service gets a 429 response with the error code insufficient_quota. A teammate proposes adding exponential backoff and retrying for up to ten minutes. Explain why that is the wrong fix, and name what the service should do instead.
Show answer
A quota error means the account has no credit left or has reached a spending cap. Waiting does not change that, so every retry fails and the requests only pile up. The service should not retry. It should stop sending requests, raise an alert to whoever manages billing, and return a clear failure to its callers. Backoff is correct for rate-limit 429s, where the limit window resets on its own.
Exercise
A request returns HTTP 200, but your JSON parser fails on the generated text. The response shows "finish_reason": "length". What happened, and what are two ways to fix it?
Show answer
The model reached the max_tokens limit before it finished, so the output was cut off in the middle of the JSON. Two fixes are to raise max_tokens so the full reply fits, and to shorten the requested output, for example by asking for fewer fields or less text. Checking finish_reason before parsing lets the program detect truncation and handle it instead of failing later.