Evidence tiers: [Verified] = backed by official documentation or credible source links; [Community Consensus] = shared user experience across the community, not officially confirmed; [Unverified / Speculative] = inferred or not yet verified—treat with caution.
1. Read API Errors Across Three Levels
[Community Consensus] Looking only at the HTTP status code is not enough. For example, an HTTP 429 from OpenAI can mean either "you are sending requests too fast" or "your account quota/balance is exhausted"—and the two require completely different fixes. [Verified: OpenAI Error codes]
2. Status Code Quick Reference: Meanings, Retry Rules, and Fixes
| Status Code | General Meaning | Safe to Retry Directly? | Common Causes (AI API Context) | Recommended Action |
|---|---|---|---|---|
| 400 Bad Request | Malformed request or invalid parameters | ❌ | Invalid JSON syntax, wrong field names, unsupported parameter for the target model, or protocol dialect mismatch | Read the error response body and fix the request payload against the official docs |
| 401 Unauthorized | Authentication failed | ❌ | Invalid, expired, or revoked API Key; malformed header (e.g., typo in Bearer); using a key from a different provider |
Check your API Key and the Authorization header |
| 402 Payment Required | Payment or balance required | ❌ | Insufficient account balance (for example, DeepSeek explicitly returns 402 when your balance runs out) | Top up your account balance; do not retry |
| 403 Forbidden | Permission denied | ❌ | Unsupported country/region (OpenAI uses 403 for unsupported regions), project/organization lacks access to the model, or permission rule rejected the call | Check account permissions, organization settings, and regional availability; do not attempt to bypass access controls |
| 404 Not Found | Endpoint path or resource does not exist | ❌ | Extra or missing /v1 in Base URL, misspelled endpoint path, or deprecated/retired model ID |
Verify the Base URL and exact model ID |
| 408 / Timeout | Request timed out | ⚠️ Bounded retries allowed | Unstable network connection, overly long input context, or very long generation output | Shorten the prompt, increase client timeout, and check network stability |
| 413 Payload Too Large | Request body exceeds size limit | ❌ | Uploaded file, image, or prompt context exceeds the maximum payload size | Compress inputs or split into smaller chunks |
| 422 Unprocessable | Semantic parameter validation error | ❌ | DeepSeek uses 422 to indicate invalid parameter values | Adjust parameter values according to the error message |
| 429 Too Many Requests | Rate limit or quota limit reached | ⚠️ Depends on subtype | RPM/TPM rate limit or concurrency limit exceeded; or account credit/monthly budget exhausted | For rate limits: exponential backoff respecting Retry-After; for quota exhaustion: do not retry—top up or raise your budget limit |
| 500 Internal Server Error | Upstream server internal error | ✅ Bounded retries | Transient server-side failure at the provider | Retry with exponential backoff; if persistent, check the provider's status page |
| 502 / 504 Bad Gateway / Timeout | Gateway or upstream timeout | ✅ Bounded retries | Intermediate proxy, gateway, or upstream server timed out | Check your self-hosted gateway or local proxy rules (see the 127.0.0.1 direct-connection note in Using magpie: Provider Configuration, Model Switching, and Config Recovery) |
| 503 Service Unavailable | Service temporarily unavailable or overloaded | ✅ Bounded retries | OpenAI server_is_overloaded or DeepSeek server congestion |
Retry later respecting Retry-After and prepare a fallback model |
| 529 Overloaded (Anthropic) | API-wide overload | ✅ Bounded retries | Global traffic spike across Anthropic's API | Retry with exponential backoff; this is not an issue with your account |
Sources:
- OpenAI: Error codes, 429 Troubleshooting
- Anthropic: Claude API errors
- DeepSeek: Error Codes
Different providers assign slightly different sub-meanings to the same HTTP status code. The table above consolidates common patterns; always consult the specific provider's error documentation when debugging.
3. Decision Flowchart: Triage Errors Methodically
4. How to Implement Retries Properly [Verified (Shared Best Practice Across Official Docs)]
import random, time
def call_with_retry(do_request, max_retries=5):
for attempt in range(max_retries):
resp = do_request()
if resp.status_code < 400:
return resp
# Non-retryable: authentication / permission / parameter / balance / quota exhaustion
if resp.status_code in (400, 401, 402, 403, 404, 422):
raise RuntimeError(resp.text)
if resp.status_code == 429 and "quota" in resp.text.lower():
raise RuntimeError("Quota exhausted; please top up or adjust your budget: " + resp.text)
# Retryable: 429 rate limit, 5xx, 529
retry_after = resp.headers.get("Retry-After")
wait = float(retry_after) if retry_after else min(60, (2 ** attempt) + random.random())
time.sleep(wait)
raise RuntimeError("Maximum retry attempts exhausted")
Key principles:
- Always enforce a maximum retry count (never loop indefinitely—it wastes money and can trigger stricter rate limiting);
- Add random jitter so multiple workers do not hammer the server at the exact same instant;
- Distinguish retryable errors from non-retryable ones.
5. "Pseudo-API Errors" in Coding Agent Workflows
| What You See | Actual Root Cause | Reference Guide |
|---|---|---|
MISSING_CREDENTIAL / UNKNOWN_MODEL (dsh) |
Local configuration issue rather than an upstream API response | DSH Daily Workflows, Profiles, and Advanced Usage |
| Gateway rejects every request even though Key and URL are valid | Protocol dialect mismatch (e.g., developer role, max_tokens field differences) |
Adding Models in DSH: Protocols, Endpoints, Keys, and Model IDs |
| Local gateway returns 502 with zero entries in routing logs | Local proxy client intercepted requests to 127.0.0.1 |
Using magpie: Provider Configuration, Model Switching, and Config Recovery |
| "Action denied" unrelated to a security rule | Classifier model unreachable (Qoder auto mode) |
Using Qoder: IDE, CLI, Permissions, and Custom Models |
| Every command prompts for approval on Linux | Sandbox requirements unmet, causing fallback to manual approval | Using Cursor: Project Rules, Execution Modes, and Bring Your Own Key |
6. Items Pending Verification & Usage Notes
- The exhaustive list of sub-error codes under 400, 403, and 429 across every provider (providers add and revise these over time).
- Third-party relays and aggregation gateways may rewrite upstream status codes, causing the returned code to diverge from official documentation.
- The Python snippet above illustrates general retry logic and is not tied to a specific provider SDK.
Hands-On Practice: Step-by-Step Verification
Exercise goal: Tell from an error response whether to fix your config, check your quota, or run bounded retries.
The sections above cover concepts, configuration, and operational examples. The steps below focus on the execution sequence, checkpoints, and verification for your first hands-on run; refer back to the relevant sections whenever you need specific parameters. Enter commands one at a time and verify each result before proceeding.
-
First log the request timestamp, provider name, HTTP status code, and raw error body—redacting your API Key, cookies, account identifiers, and any private prompt text.
-
Inspect
error.typeorerror.codeinside the response body. When you see HTTP 429, always check whether it is a transient rate limit or an exhausted balance/budget. -
For HTTP 401, verify which platform issued the credential and inspect the request headers; for HTTP 404, check the Base URL and endpoint path—changing only one field at a time.
-
If the error is a transient failure eligible for retry, inspect the
Retry-Afterheader first. Note thatRetry-Aftercan be either an integer number of seconds or an HTTP date string, so do not blindly cast it to a float in production code. -
Configure both a maximum retry count and a total elapsed wait cap, then test again with the same minimal request; keep in mind that if a timed-out request already reached the upstream server, retrying may incur duplicate token usage.
-
Once resolved, write down the exact fix that worked. Treat the Python code above as an educational sketch—when integrating into production services, use your SDK's built-in retry handling for timeouts, connection errors, and provider-specific exceptions.