Grok API 错误
更新于:
Grok AI:Grok API HTTP 错误代码、产生原因与解决方法。
错误响应格式
Grok API Dev 以 OpenAI 兼容格式返回错误。响应是一个包含 code、message 和 type 字段的 error 对象。
JSON
{
"error": {
"message": "Invalid model ID",
"type": "invalid_request_error",
"code": "invalid_model"
}
}Grok API 错误代码
400、401、403、404、405、415、422 和 429 与 xAI 官方调试文档一致。下方标准 5xx 项用于防御性处理临时 gateway 与 upstream 故障。
| 代码 | 原因 | 处理方法 | 重试 |
|---|---|---|---|
400Bad Request | JSON、参数或请求正文无效。密钥格式错误有时也会触发此代码。 | 检查 JSON、必填字段、值类型和 Authorization 请求头。 | 修复前不要重试 |
401Unauthorized | API 密钥缺失、无效或格式错误。 | 发送 Authorization: Bearer sk-lg-...,并删除意外空格。 | 否 |
403Forbidden | 密钥已识别,但无权访问资源。 | 检查账户和模型权限。请求无误时请联系支持。 | 否 |
404Not Found | base URL、endpoint 或模型 ID 错误。 | 核对 https://api.llm-gate.tech/v1、/v1/chat/completions 和模型名称。 | 否 |
405Method Not Allowed | endpoint 收到了错误的 HTTP 方法。 | 使用文档指定的方法,生成请求通常为 POST。 | 否 |
415Unsupported Media Type | 正文为空,或缺少 Content-Type: application/json。 | 发送 JSON 正文并设置正确的 Content-Type。 | 否 |
422Unprocessable Entity | JSON 可解析,但字段未通过格式校验。 | 检查 messages 结构、参数类型和允许值。 | 否 |
429Too Many Requests | 超过当前速率限制。 | 降低并发和请求频率,并遵循 Retry-After。 | 是,使用 backoff 和 jitter |
500Internal Server Error | 服务发生临时内部故障。 | 保存 request ID,并限制重试次数。 | 是 |
502/503/504Gateway or upstream | gateway 或 upstream 暂时不可用或超时。 | 查看状态页,并逐步增加重试延迟。 | 是 |
安全重试
- 修复请求前,不要重试 400、401、403、404、405、415 或 422。
- 限制尝试次数并加入随机 jitter,避免多个客户端同时重试。
- 存在 Retry-After 时优先遵循,否则使用 exponential backoff。
- 有副作用的操作需要预先设计 idempotency,否则重试可能重复执行操作。
JavaScript
const retryable = new Set([429, 500, 502, 503, 504]);
function retryAfterMs(value) {
if (!value) return null;
const seconds = Number(value);
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);
const date = Date.parse(value);
return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
}
async function fetchWithRetry(url, init, maxAttempts = 4) {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const response = await fetch(url, init);
if (!retryable.has(response.status) || attempt === maxAttempts - 1) {
return response;
}
const retryAfter = retryAfterMs(response.headers.get("retry-after"));
const backoff = 500 * 2 ** attempt;
const jitter = Math.random() * 250;
const delayMs = retryAfter !== null
? retryAfter
: backoff + jitter;
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
throw new Error("unreachable");
}