Errors and retries
Understand API error responses and retry the ones worth retrying
Requests fail for different reasons, and the correct response differs by reason. A brief capacity limit is worth retrying. An exhausted budget or an invalid model ID is not, and retrying it wastes time while hiding the real problem.
This page explains what NaviGator AI Toolkit returns, which failures are temporary and how to retry them safely.
Error format
NaviGator AI Toolkit provides OpenAI-compatible endpoints, so errors follow the OpenAI error shape and map to the exception types your client already defines. Existing OpenAI error handling generally works without changes.
An error response contains an error object:
{
"error": {
"message": "A description of what went wrong",
"type": "the error category",
"code": "the status code"
}
}Read message when diagnosing a failure. Branch your code on the status code rather than on message text, which can change without notice.
Status codes
| Status | Meaning | Retry |
|---|---|---|
| 400 | Malformed request | No |
| 401 | Authentication failed | No |
| 403 | Not permitted for this key | No |
| 404 | Model or endpoint not found | No |
| 408 | Request timed out | Yes |
| 422 | Request understood but rejected | No |
| 429 | Rate limit reached | Yes, with backoff |
| 500 | Upstream or internal failure | Yes, with backoff |
| 503 | Service temporarily unavailable | Yes, with backoff |
A 4xx status other than 408 and 429 means the request itself needs to change. Sending it again unchanged produces the same result.
Common causes
- 401 — the key is missing, mistyped, revoked or not sent as a bearer token.
- 403 — the key is valid but the model is not assigned to it. List the models available to your key before assuming a model is available.
- 404 — the model ID does not exist. Model IDs are exact and case-sensitive; confirm the ID on the model page.
- 422 — the request is structurally valid but rejected, often because a model does not accept a parameter you sent. Some models reject sampling parameters or manual thinking configuration.
- 429 — you reached a rate limit or a budget was exhausted. These are different situations that can share a status code; see below.
Rate limits and budgets
Both conditions can surface as 429, but they require opposite responses.
A rate limit is a ceiling on how fast requests are processed, typically as requests per minute, tokens per minute or requests in flight at once. It clears on its own. Waiting and retrying is the correct response.
A budget is a spending cap on a key, team or user. It does not clear by waiting for a few seconds. Retrying cannot succeed and only delays the fix, which is a budget increase or a new budget period.
Distinguish them by reading message. Budget exhaustion names the exceeded budget, using wording such as ExceededBudget. It can also surface as an authentication-style error rather than a plain rate-limit error.
Treat a budget failure as terminal:
except openai.RateLimitError as error:
if "budget" in str(error).lower():
raise # A budget will not clear by retrying
# Otherwise wait and retryAn application that retries every 429 indefinitely will loop against an exhausted budget while appearing to hang. Log the message rather than only the status code so this is visible.
Your specific limits depend on how your key and team are configured. Review them on the key's detail view in Getting Started and with your team administrator. Confirm current values there rather than assuming a fixed number.
Retry with exponential backoff
Retrying immediately makes congestion worse. Wait longer after each failure, and add a small random amount so that many clients do not retry in unison. That randomness is called jitter.
Cap both the delay and the number of attempts so a failure eventually surfaces instead of retrying forever.
import random
import time
import openai
RETRYABLE = (408, 429, 500, 503)
def with_retry(send, attempts=5):
for attempt in range(attempts):
try:
return send()
except openai.APIStatusError as error:
budget_reached = "budget" in str(error).lower()
last_attempt = attempt == attempts - 1
if error.status_code not in RETRYABLE or budget_reached or last_attempt:
raise
delay = min(2**attempt, 30) + random.uniform(0, 1)
time.sleep(delay)This waits about 1, 2, 4, 8 and 16 seconds plus jitter, stops at 30 seconds between attempts and re-raises budget failures immediately.
If a response includes a Retry-After header, prefer that value over your calculated delay.
Official OpenAI clients retry some failures automatically. Check your client's default before adding your own logic, or you may multiply the attempts.
Retry safely
A retry sends the request again. Confirm that is harmless before enabling it.
- A completion request that only returns text is safe to repeat.
- A request whose result is stored, billed, emailed or acted on by another system is not automatically safe.
When a retry could repeat an external effect, make the surrounding operation idempotent so repeating it does not repeat the effect. Record a unique identifier for the unit of work and check it before acting on a result.
Every attempt that reaches the model consumes tokens and cost, including ones you discard. Bound retries so a persistent failure cannot generate unbounded spend.
Timeouts
Set an explicit timeout on every request. Without one, a stalled connection can hold a worker indefinitely.
Choose the timeout based on expected output length. Long generations, large context windows and reasoning models legitimately take longer. A timeout that is too aggressive turns working requests into failures and duplicate work.
A timeout is not proof the model did no work. If the request could have completed server-side, apply the same idempotency care used for retries.
Streaming
Streaming changes when errors appear. The connection can succeed and fail partway through delivery, after you have already received some output.
Handle a mid-stream failure explicitly. Decide whether to discard the partial result, present it as incomplete or retry from the beginning. Do not treat partial output as a finished answer.
Before going to production
- Branch on status codes rather than message text
- Retry only
408,429,500and503 - Treat budget exhaustion as terminal
- Use exponential backoff with jitter and a maximum delay
- Cap total attempts
- Honor
Retry-Afterwhen present - Set an explicit timeout on every request
- Confirm retries cannot duplicate an external action
- Log the error message, not only the status code
- Handle mid-stream failures if you stream
Related pages
- OpenAI-compatible SDKs — client configuration
- Teams — budgets, rate limits and model access
- Usage and costs — monitor consumption
- API key security — key handling requirements