Sub topic 8
Understanding errors and rate limits
This chapter assumes you can send a chat request (see the earlier chapters), read HTTP status codes, and parse JSON in Python. It covers what the API returns when a call fails and how rate limits work. The next chapter covers retrying.
Where errors come from
A failed call can break at three levels:
- Network. The request never reaches the server, or the reply never comes back. You get an exception such as a connection error or timeout, and no status code.
- HTTP. The server answers with a 4xx or 5xx status code.
- Model. The HTTP status is 200, but the result is not what you wanted. For example,
finish_reasonislength, so the reply was cut off.
Check all three. Many bugs come from checking only the first.
Common status codes
Codes follow standard HTTP meaning, but providers differ in details. Check your provider's documentation.
| Code | Meaning | Retry? |
|---|---|---|
| 400 | Malformed request, bad parameter, or input too long for the context window | No. Fix the request. |
| 401 | Missing or invalid API key | No. Fix the key. |
| 403 | Key is valid but not allowed to use this model or region | No. Change permissions. |
| 404 | Unknown endpoint or model name | No. Check the URL and model. |
| 429 | Rate limit hit, or quota used up | Sometimes. See below. |
| 500, 502, 503, 504 | Server problem or overload | Yes, with backoff. |
Only the last row and some 429 responses are worth retrying. Sending the same bad request again never fixes a 400 or 401.
Reading the error body
Most providers return a JSON body that explains the failure. In the chat-completions shape it looks like this:
{
"error": {
"message": "Incorrect API key provided.",
"type": "invalid_request_error",
"code": "invalid_api_key"
}
}The message is for people. The code or type is for your program. Branch on those fields and log the message. Field names vary by provider.
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",
}
payload = {
"model": os.environ["LLM_MODEL"],
"messages": [{"role": "user", "content": "Hello"}],
}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
if resp.status_code >= 400:
try:
err = resp.json().get("error", {})
except ValueError:
err = {}
print("status:", resp.status_code)
print("code:", err.get("code"))
print("message:", err.get("message") or resp.text[:200])
else:
choice = resp.json()["choices"][0]
if choice["finish_reason"] == "length":
print("Warning: reply was cut off by the length limit")
print(choice["message"]["content"])The try block matters. A gateway or proxy in front of the API can return an HTML error page, and calling .json() on it raises an exception.
Rate limits
A rate limit caps how much you can use the API in a time window. Providers usually measure two things:
- Requests per minute (RPM): how many calls you make.
- Tokens per minute (TPM): how many tokens your requests and replies use.
You can hit TPM while staying far below RPM, because a few large prompts use many tokens. Limits often differ by model and by account tier.
When you exceed a limit, you get a 429. Two kinds look alike:
- Rate limit: you are going too fast. Waiting a short time fixes it.
- Quota exhausted: your spending cap or credit is used up. Waiting does not help. The
codefield usually tells the two apart.
Many providers send headers that show your remaining allowance, and Retry-After says how many seconds to wait. Header names vary, so print resp.headers once and see what yours sends.
Exercise
Your program gets a 400 response with a message saying the prompt exceeds the model's context window. Should it retry the same request after waiting? What should it do instead?
Show answer
No. A 400 means the request itself is invalid, so retrying gives the same result. Shorten the input, for example by trimming old messages or splitting the document, and then send a new request.
Exercise
A call returns HTTP 200, but finish_reason is length. Is this an error, and how do you find out?
Show answer
It is not an HTTP error, but the reply is incomplete. You find out only by reading finish_reason in the response body. Raise max_tokens (or the equivalent setting) or ask for a shorter answer.