use-case
Common AI API error codes and troubleshooting
Direct answerHandle AI API failures by parsing the HTTP status, provider code, error type, message, retry hints, and request ID together. Fix request, authentication, billing, and hard-quota causes first; retry only transient throttling, network failures, and selected 5xx errors with strict bounds.
Updated · Reviewed
Separate HTTP status from provider codes
An HTTP status classifies a failure but does not determine its root cause or retry policy. Read the HTTP status, provider type/code/status, message, parameter, retry headers, and request ID together. OpenAI-style errors commonly expose error.type/code/param/message; Anthropic nests error.type/message and adds a top-level request_id; Gemini Interactions uses a string error.code, while GenerateContent uses a numeric code, string status, and optional details. Tencent Cloud API 3.0 can keep HTTP 200 for a business failure, so clients must inspect Response.Error.Code.
Normalize different provider responses into internal log fields instead of inventing one upstream JSON contract that every provider supposedly implements:
http_status=429
provider_error_type=rate_limit_error
provider_error_code=rate_limit_exceeded
gateway_request_id=...
provider_request_id=...
retry_after=2s
attempt=1
Common error-code reference
400Bad Request: invalid JSON, required fields, ranges, context, model capability, or safety validation. Correct the request instead of retrying it unchanged.401Unauthorized: missing, invalid, expired, or revoked credentials, or a failed signature. Fix authentication first.402Payment Required: Anthropic, DeepSeek, and others use this for billing or balance failures. A retry cannot help before payment is fixed.403Forbidden: credentials can be valid but lack model, region, resource, or account access, or a model agreement is missing.404Not Found: wrong host, route, API version, deployment, model, or task. Marketplace labels, native model IDs, cloud deployment names, and gateway aliases are not interchangeable.405Method Not Allowed and415Unsupported Media Type: verify the method, endpoint, andContent-Type. Some platforms also map an unsupported SDK or model capability to 405, so still inspect the provider code.408Request Timeout: the request or model timed out;499Client Closed Request records a client cancellation or disconnect. Execution can be uncertain, so check job state before retrying.409Conflict: a concurrent update, duplicate creation, or resource-state conflict. Refresh state and resolve the conflict before resubmission.413Payload Too Large: the HTTP body exceeds a byte limit, commonly because of Base64 media. Compress, resize, split, or use a file reference only when the target route supports it.422Unprocessable Entity: the request parsed but its parameter semantics are invalid; DeepSeek and Mistral are representative users. Correct the field combination first.424Failed Dependency: an upstream model or dependency failed. Amazon Bedrock'sModelErrorExceptionis a representative use; inspect its original status and resource instead of blindly retrying every 424.429Too Many Requests: it can mean RPM, TPM, concurrency, burst traffic, balance, plan, daily quota, free allocation, or platform capacity. Continue classification with the provider code.500Internal Server Error: a provider internal failure that can also mask an input boundary. Preserve the original error and retry only a confirmed transient case.502Bad Gateway,503Service Unavailable, and504Gateway Timeout: gateway, regional capacity, upstream availability, or processing timeout. Persistent failures require throttling, a circuit breaker, a verified region or model fallback, or a status-page check.529Overloaded: Anthropic explicitly uses this for temporary global overload. In a stream, anoverloaded_errorcan arrive after the initial 200 response.
A 429 requires provider-code classification
Honor Retry-After for temporary rate limits when it is present. Azure can also return millisecond retry-after-ms. Without a usable hint, apply exponential backoff with random jitter, a maximum attempt count, and an overall deadline. Failed attempts can consume quota, so a hot retry loop delays recovery.
Credits, plan expiry, spend caps, daily quota, and exhausted free allocation require payment, renewal, a quota change, or a reset; fast retries cannot repair them. Representative differences include DeepSeek using 402 for insufficient balance; Kimi placing overload, balance, and RPM/TPM under 429; Zhipu distinguishing arrears, account throttling, model congestion, and plan caps through separate business codes under 429; and Cloudflare using 3036 for exhausted free Neurons versus 3040 for no available data center. Match stable codes, not message strings that can be reworded or localized.
Provider protocol differences
- OpenAI: preserve
error.typeanderror.code; distinguish transient429from credit, organization, or project spend limits. Official SDKs can already retry connection failures,408,409,429, and 5xx errors, so avoid accidental retry multiplication. - Anthropic: it additionally defines
402,409, and529; every response has arequest-id, and error bodies includerequest_id. Error types and stream events can expand, so parsers must tolerate unknown values. - Gemini: Interactions and GenerateContent use different error models and fields. Interactions separates
rate_limit_exceededfromquota_exceeded; a GenerateContent safety block, finish reason, or empty candidate set might not be an HTTP error. - Model Studio, Kimi, Zhipu, and Baidu Qianfan: they combine HTTP status with finer business codes. The same
400or429can identify parameters, safety, credits, plans, hard quota, or transient congestion. Native Model Studio responses often containrequest_id, but that does not prove every compatibility route shares the same shape. - Tencent Hunyuan native protocol: a normally processed request often returns HTTP 200, with business failure in
Response.Error.Code. Branch on the stable code rather than the changeable message. - Amazon Bedrock: SDKs expose exception names such as
ValidationException,ModelTimeoutException,ModelErrorException, andThrottlingException;424,429, and503have different causes. - Azure OpenAI: a
429can reflect deployment TPM/RPM or temporary capacity. Preferretry-after-msandx-ratelimit-*; do not treat a content-policy signal as a transient 400. - Cloudflare Workers AI and Mistral: Cloudflare needs its internal numeric code to distinguish free allocation from capacity. Mistral classifies
429/500/502/503/504as transient backoff candidates, while request, authentication, and access failures still require correction.
HTTP 200 can still end in failure
Once SSE or NDJSON starts, the HTTP status normally cannot change. OpenAI Responses, Anthropic Messages, and Gemini Interactions can send error events in the stream. Gemini GenerateContent also requires checking promptFeedback, candidate finishReason, and candidate presence. A 200 or 202 from an asynchronous image, video, or Batch create call means accepted, not successfully completed.
Parse complete events according to protocol boundaries, tolerate unknown event types, and mark success only after an explicit completion event or terminal state. Do not automatically replay a side-effecting or potentially billed create request after a broken stream; determine upstream state from the job ID, idempotency key, and logs first.
Retain request IDs and minimal evidence
This gateway returns X-Oneapi-Request-Id. Also preserve provider x-request-id, request-id, apim-request-id, x-amzn-requestid, or body request_id/RequestId values when present. Do not confuse an asynchronous job ID with a universal synchronous trace ID, and do not assume every provider supplies the same header.
A diagnosable failure includes UTC time, gateway request ID, provider request ID, path, model, HTTP status, business code, streaming mode, attempt count, and elapsed time. Mask all but a few key characters and collect payloads, files, and personal data only when necessary. Never send a complete key or sensitive input in a support ticket.
Production retry and fallback rules
- Do not automatically retry
400/401/402/403/404/405/413/415/422, safety, billing, plan, or hard-quota errors. Resubmit only after the root cause changes. - For
409, refresh and resolve state. For408/499, determine whether execution already happened; retry only idempotent or safely deduplicated operations. - Apply bounded exponential backoff, random jitter, an overall deadline, and concurrency caps only to transient
429, network failures, and confirmed transient500/502/503/504/529errors. - Honor a valid
Retry-Afterand check whether the SDK already retries. Add circuit breakers, verified model fallbacks, and alerts to prevent retry storms. - Use a business idempotency key for asynchronous creation. Query after a timeout and route uncertain outcomes into compensation or manual review instead of blindly repeating a billed action.
Minimal reproduction and escalation
Re-run the quickstart curl with the same base URL, gateway key, endpoint, and model, then add media, tools, and optional fields one at a time. If curl succeeds, capture the SDK's redacted effective URL, version, proxy, timeout, and retry settings. If minimal curl fails, contact support with request IDs, time, path, model, status, and the provider error object.
Use cases
- Diagnosing a failed first request
- Designing production retries, circuit breakers, and fallbacks
- Giving support enough evidence to locate a request
API protocols
/v1/chat/completions/v1/responses/v1/messages/v1beta/models/{model}:generateContent/v1beta/models/{model}:streamGenerateContent
FAQ
Does 429 always mean requests arrived too quickly?
No. OpenAI, Kimi, Zhipu, Model Studio, Azure, and Cloudflare can also use 429 for credits, plans, daily quotas, concurrency, or platform capacity. Inspect the provider code, error type, message, and retry headers; only transient throttling or capacity failures merit backoff.
What is the difference between 400, 413, and 422?
A 400 normally indicates invalid format, fields, or model capability; 413 is an HTTP byte-size limit; 422 means the request parsed but is semantically invalid. Change the request first because retrying it unchanged normally fails again.
Can every 500, 502, 503, 504, or 529 be retried?
No. Overload, gateway, and temporary service failures can merit bounded backoff, but some 500 or 504 responses can hide deterministic input problems. Anthropic uses 529 for temporary overload. Inspect provider details and retry only idempotent or safely deduplicated operations.
Is HTTP 200 a success when no text is present?
Not necessarily. A stream can report an error after 200, GenerateContent can report a safety block or finish reason, and Tencent Cloud native APIs can return a business error inside an HTTP 200 body. Treat only the protocol-defined completion state as success.
Should a content-safety error be retried automatically?
Not unchanged. Inspect content_filter, safety, ResponsibleAIPolicyViolation, or the provider safety code, then change the input, media, or workflow. Exponential backoff on identical content is ineffective and can multiply cost and moderation load.
Why must I retain the request ID?
It links the client failure to gateway and provider logs. This gateway returns X-Oneapi-Request-Id, while providers may use x-request-id, request-id, apim-request-id, x-amzn-requestid, or a request_id body field. Include UTC time, path, model, and a redacted error object when escalating.
Does a client timeout mean the model did not execute?
No. A disconnected client does not necessarily cancel upstream work. After an image, video, Batch, or other side-effecting submission times out, query by task ID, request ID, or business idempotency key before creating another potentially billed job.
What should I inspect when curl succeeds but an SDK fails?
Compare the SDK's effective base URL, path, proxy, model, API version, and JSON, then check its version, default timeout, automatic retries, and environment variables. Official SDK retries can combine with application retries and amplify traffic.
Related guides
Official sources
- OpenAI Error Codes Official
- OpenAI Rate Limits Official
- Claude API Errors Official
- Gemini API Errors Official
- Gemini API Troubleshooting Official
- DeepSeek Error Codes Official
- Alibaba Cloud Model Studio Error Codes Official
- Kimi API Errors Official
- Zhipu API Error Codes Official
- Baidu Qianfan Error Codes Official
- Tencent Hunyuan Error Codes Official
- Amazon Bedrock API Error Troubleshooting Official
- Azure OpenAI Quota and 429 Guidance Official
- Cloudflare Workers AI Errors Official
- Mistral Error Glossary Official
兔子API