页面简介
API Errors and Debugging
正文摘录
For errors, OpenRouter returns a JSON response with the following shape: type ErrorResponse = { error: { code: number; message: string; metadata?: Record<string, unknown>; }; }; The HTTP Response will have the same status code as error.code, forming a request error if: Your original request is invalid Your API key/account is out of credits Otherwise, the returned HTTP response status will be 200 and any error occurred while the LLM is producing the output will be emitted in the response body or as an SSE data event. Example code for printing errors in JavaScript: PythonGocURLcURLconst request = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o-mini', messages: [{ role: 'user', content: 'Hello' }], }), }); console.log(request.status); // An error code unless the model started processing your request const response = await request.json(); // Errors before processing return a non-200 status; errors during generation // can still appear in the body of a 200 response, at the top level or on the // choice next to partial content. const error = response.error ?? response.choices?.[0]?.error; if (error) { console.error(error.code); console.error(error.message); } else { console.log(response.choices[0].message.content); } Output200 Hello! How can I assist you today? Error codes 400: Bad Request (invalid or missing params, CORS) 401: Invalid credentials (OAuth session expired, disabled/invalid API key) 402: Your account or API key has insufficient credits. Add more credits and retry the request. 403: Forbidden (insufficient permissions, guardrail block, or moderation flag) 408: Your request timed out 429: You are being rate limited 502: Your chosen model is down or we received an invalid response from it 503: There is no available model provider that meets your routing requirements If POST /api/v1/chat/completions rejects your video-only model, submit a new request to POST /api/v1/videos without a messages array. To generate a video from text, send a top-level prompt. To upscale a video, send the source video in input_references as shown in the video upscale request example. Runway video upscale requires one video_url entry and rejects prompt. The Video Generation guide shows how to submit a job, poll for completion, and download the video. The asynchronous video API has its own statuses for job retrieval, such as 404 before a job completes and 410 after its content expires. See the Video API error reference. Retry-After header On 429 and 503 responses, and on 402 responses whose error.metadata.limit_source is openrouter_in_flight_budget (see In-flight spending budget), OpenRouter may include a standard HTTP Retry-After response header indicating how many seconds to wait before retrying. A 402 without the header is not a wait-and-retry case; see Handling 402 errors. HTTP/1.1 429 Too Many Requests Retry-After: 60 The OpenAI SDK, Anthropic SDK, Vercel AI SDK, and OpenRouter SDK already respect this header for backoff on the statuses each SDK retries automatically. None of them retries a 402 on its own, so for the in-flight budget case catch the error, read Retry-After, and retry explicitly. If you’re using fetch directly, honor it before retrying: PythonGocURLconst request = () => fetch('https://openrouter.ai/api/v1/responses', { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o-mini', input: 'Hello' }), }); let res = await request(); if (res.status === 429 || res.status === 503 || res.status === 402) { const retryAfter = Number(res.headers.get('Retry-After')); if (Number.isFinite(retryAfter) && retryAfter > 0) { await new Promise((r) => setTimeout(r, retryAfter * 1000)); await res.body?.cancel(); // release the rejected response before retrying res = await request(); // retry the request } } console.log(res.status); console.log(JSON.stringify(await res.json(), null, 2)); Output200 { "id": "gen-1794947361-xGTFZYnUpZTVSMDbfHvy", "object": "response", "created_at": 1794947361, "model": "openai/gpt-4o-mini", "status": "completed", "completed_at": 1794947362, "output": [ { "id": "msg_tmp_0h0lrl20rbzp", "type": "message", "role": "assistant", "status": "completed", "content": [ { "type": "output_text", "text": "Hello! How can I assist you today?", "annotations": [], "logprobs": [] } ] } ], "error": null, "incomplete_details": null, "access_programs": null, "tools": [], "tool_choice": "auto", "parallel_tool_calls": true, "max_output_tokens": null, "temperature": 1, "top_p": 1, "presence_penalty": 0, "frequency_penalty": 0, "top_logprobs": 0, "max_tool_calls": null, "metadata": {}, "background": false, "previous_response_id": null, Moderation errors If your input was flagged, the error.metadata will contain information about the issue. The shape of the metadata is as follows: type ModerationErrorMetadata = { reasons: string[]; // Why your input was flagged flagged_input: string; // The text segment that was flagged, limited to 100 characters. If the flagged input is longer than 100 characters, it will be truncated in the middle and replaced with ... provider_name: string; // The name of the provider that requested moderation model_slug: string; }; Budget errors When a guardrail budget, a workspace budget, or the key’s own limit is spent, the request is rejected with a 403 before it reaches a provider. The message ends with the figures ($X of $Y used; resets <ISO instant>.), and error.metadata carries the same values as fields so you can branch on them: { "error": { "code": 403, "message": "Budget limit exceeded (weekly limit). Contact your org admin. $52.00 of $50.00 used; resets 2026-10-12T00:00:00.000Z.", "metadata": { "limit_source": "openrouter_guardrail_budget", "remedy_hint": "Wait for the budget window to reset (see metadata.resets_at), or ask your org admin to raise the guardrail budget.", "scope": "workspace_default_member", "limit_usd": 50, "spend_usd": 52, "resets_at": "2026-10-12T00:00:00.000Z" } } } FieldMeaninglimit_sourceopenrouter_guardrail_budget, openrouter_workspace_budget, or openrouter_key_limitscopeWhich layer blocked: workspace_default_member, workspace_default_key, member, api_key, workspace, or key_limit, as listed by GET /api/v1/keylimit_usdThe budget’s limit in USDspend_usdThe spend counted against it in the current windowresets_atISO 8601 UTC instant the window rolls over, or null for a lifetime budgetremedy_hintA one-line next step for people reading logs; branch on limit_source, not on this text GET /api/v1/key reports the same budgets before they block, under budgets and effective_budget; see Budget limits. Guardrail errors On inference endpoints (/chat/completions, /responses, /messages), a request can be blocked before it reaches a provider — for example by a content filter or prompt-injection detector configured via guardrails. When this happens, the response is a 403 with a message describing the block reason. The OpenRouter-shaped body below applies to /chat/completions and /responses; on /messages the block is returned as an Anthropic permission_error envelope (see Anthropic Messages below), with openrouter_metadata still carried at the top level when opted in: { "error": { "code": 403, "message": "Request blocked: prompt injection patterns detected", "metadata": { "patterns": ["ignore all previous instructions"] } } } When you opt in to router metadata via the X-OpenRouter-Experimental-Metadata: enabled header, the 403 response also includes the full openrouter_metadata object with routing context and a pipeline array detailing the guardrail stages that ran: { "error": { "code": 403, "message": "Request blocked: prompt injection patterns detected", "metadata": { "patterns": ["ignore all previous instructions"] } }, "openrouter_metadata": { "requested": "openai/gpt-4o", "strategy": "direct", "region": "iad", "summary": "available=1", "attempt": 1, "is_byok": false, "endpoints": { "total": 1, "available": [ { "provider": "OpenAI", "model": "openai/gpt-4o", "selected": false } ] }, "pipeline": [ { "type": "guardrail", "name": "regex_pi_detection", "guardrail_id": "grd_abc123", "guardrail_scope": "api-key", "summary": "Blocked: prompt injection detected (1 pattern matched)", "data": { "action": "blocked", "detected": true, "engines": ["regex"], "patterns": ["ignore all previous instructions"] } } ] } } See all 38 lines The openrouter_metadata object follows the same shape as on successful responses — see Pipeline Stages for the full stage type and field reference. Provider errors OpenRouter normalizes every upstream provider error into the stable, typed error_type vocabulary documented under Typed Error Codes. The same error_type values describe what went wrong whether the provider error arrives in a non-streaming response body or as a mid-stream SSE event. Native protocol codes (the Anthropic error.type, the Responses error.code) are best-effort and can differ between formats — error_type is the field to rely on across all of them. For Chat Completions, a provider error that interrupts generation carries error_type inside error.metadata: { "error": { "code": 429, "message": "Rate limit exceeded", "metadata": { "error_type": "rate_limit_exceeded", "provider_code": "rate_limited" } } } The same value is carried on mid-stream errors and on the Anthropic and Responses skins — see Skin-Specific Error Formats for the exact wire location in each format. Masking and raw provider details When a request fails with a 500, the message is replaced with a generic string and provider_code and openrouter_metadata are omitted, but error_type is still present (server). For non-500 errors, the upstream provider’s own error code is surfaced in error.metadata.provider_code when available. Opt-in routing context (whic