跳转到主要内容

错误响应格式

所有错误都返回一致的 JSON 格式,并带有可选的 Agent-First 提示
{
  "error": {
    "message": "Human-readable error description",
    "type": "error_type",
    "code": "error_code",
    "param": "parameter_name",
    "did_you_mean": "suggested_model",
    "suggestions": [{"id": "model-id"}],
    "hint": "Next step guidance",
    "retryable": true,
    "retry_after": 30
  }
}
基础字段(messagetypecodeparam)始终存在。提示字段(did_you_meansuggestionshintretryableretry_afterbalance_usdestimated_cost_usd)是用于 AI agent 自我修正的可选扩展。详情请参阅 Agent-First API 指南

HTTP 状态码

代码描述
400Bad Request - 参数无效
401Unauthorized - API key 无效或缺失
402Payment Required - 余额不足
403Forbidden - 拒绝访问或模型不允许
404Not Found - 未找到模型或资源
413Payload Too Large - 输入或文件大小超出限制
429Too Many Requests - 超出速率限制
500Internal Server Error - 内部服务器错误
502Bad Gateway - 上游供应商错误
503Service Unavailable - 所有渠道均失败
504Gateway Timeout - 请求超时

错误类型

身份验证错误 (401)

类型代码描述
invalid_api_keyinvalid_api_keyAPI key 缺失或无效
expired_api_keyexpired_api_keyAPI key 已撤销
from openai import OpenAI, AuthenticationError

try:
    response = client.chat.completions.create(...)
except AuthenticationError as e:
    print(f"Authentication failed: {e.message}")

支付错误 (402)

类型代码描述
insufficient_quotainsufficient_quota账户余额过低
quota_exceededquota_exceeded已达到 API key 使用限制
from openai import OpenAI, APIStatusError

try:
    response = client.chat.completions.create(...)
except APIStatusError as e:
    if e.status_code == 402:
        print("Please top up your account balance")

访问错误 (403)

类型代码描述
access_deniedaccess_denied拒绝访问资源
access_deniedmodel_not_allowed此 API key 不允许使用该模型
{
  "error": {
    "message": "You don't have permission to access this model",
    "type": "access_denied",
    "code": "model_not_allowed"
  }
}

验证错误 (400)

类型描述
invalid_request_error请求参数无效
context_length_exceeded输入内容对模型而言过长
model_not_found请求的模型不存在
{
  "error": {
    "message": "Model 'invalid-model' not found",
    "type": "invalid_request_error",
    "param": "model",
    "code": "model_not_found",
    "did_you_mean": "gpt-4o",
    "suggestions": [{"id": "gpt-4o"}, {"id": "gpt-4o-mini"}],
    "hint": "Did you mean 'gpt-4o'? Use GET /v1/models to list all available models."
  }
}

速率限制错误 (429)

当您超出速率限制时:
{
  "error": {
    "message": "Rate limit: 60 rpm exceeded",
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "retryable": true,
    "retry_after": 8,
    "hint": "Rate limited. Retry after 8s. Current limit: 60/min for user role."
  }
}
包含的 Header:
Retry-After: 8
Retry-After header 和 retry_after 字段都指示了重试前需要等待的确切秒数。

有效负载过大 (413)

当输入或文件大小超出限制时:
{
  "error": {
    "message": "Input size exceeds maximum allowed",
    "type": "invalid_request_error",
    "code": "payload_too_large"
  }
}
常见原因:
  • 图像文件过大(最大 20MB)
  • 音频文件过大(最大 25MB)
  • 输入文本超出模型上下文长度

上游错误 (502, 503)

类型描述
upstream_error供应商返回错误
all_channels_failed无可用供应商
timeout_error请求超时
当所有渠道都失败时,响应将包含替代模型:
{
  "error": {
    "message": "Model claude-opus-4-6 temporarily unavailable",
    "code": "all_channels_failed",
    "retryable": true,
    "retry_after": 30,
    "alternatives": [
      {"id": "claude-sonnet-4-5", "status": "available", "tags": []},
      {"id": "gpt-4o", "status": "available", "tags": []}
    ],
    "hint": "Retry in 30s or switch to an available model."
  }
}

在 Python 中处理错误

from openai import OpenAI, APIError, RateLimitError, APIConnectionError

client = OpenAI(
    api_key="sk-your-api-key",
    base_url="https://api.lemondata.cc/v1"
)

def chat_with_retry(messages, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="gpt-4o",
                messages=messages
            )
        except RateLimitError as e:
            if attempt < max_retries - 1:
                import time
                time.sleep(2 ** attempt)  # Exponential backoff
                continue
            raise
        except APIConnectionError as e:
            print(f"Connection error: {e}")
            raise
        except APIError as e:
            print(f"API error: {e.status_code} - {e.message}")
            raise

在 JavaScript 中处理错误

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'sk-your-api-key',
  baseURL: 'https://api.lemondata.cc/v1'
});

async function chatWithRetry(messages, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await client.chat.completions.create({
        model: 'gpt-4o',
        messages
      });
    } catch (error) {
      if (error instanceof OpenAI.RateLimitError) {
        if (attempt < maxRetries - 1) {
          await new Promise(r => setTimeout(r, 2 ** attempt * 1000));
          continue;
        }
      }
      throw error;
    }
  }
}

最佳实践

当受到速率限制时,在重试之间逐渐延长等待时间:
wait_time = 2 ** attempt  # 1s, 2s, 4s, 8s...
始终设置合理的超时时间,以避免请求挂起:
client = OpenAI(timeout=60.0)  # 60 second timeout
记录完整的错误响应(包括用于支持的请求 ID):
except APIError as e:
    logger.error(f"API Error: {e.status_code} - {e.message}")
某些模型有特定要求(例如最大 token 数、图像格式)。在发起请求前验证输入。