错误处理

BufferAPI 使用标准 HTTP 状态码,错误响应体遵循 OpenAI 格式。

错误响应格式

{
  "error": {
    "message": "Invalid API key provided",
    "type": "authentication_error",
    "code": "invalid_api_key"
  }
}

常见错误码

HTTP 状态码错误类型说明处理方式
400invalid_request请求参数错误检查请求参数格式
401authentication_errorAPI Key 无效或过期检查 Key 是否正确
403permission_denied无权访问该资源检查 Key 权限
404not_found模型或端点不存在检查模型 ID 拼写
429rate_limit请求频率超限降低请求频率或升级套餐
500server_error服务器内部错误重试,如持续出现联系支持
502bad_gateway上游供应商错误重试,系统自动切换节点
503service_unavailable服务暂不可用等待后重试

重试策略

import time

def call_with_retry(client, messages, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="gpt-4o",
                messages=messages
            )
        except openai.RateLimitError:
            wait = 2 ** attempt  # 指数退避
            time.sleep(wait)
        except openai.APIError as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(1)
    raise Exception("Max retries exceeded")
建议:对于 429 和 5xx 错误,使用指数退避策略重试。对于 4xx 客户端错误(除 429),不要重试,应修复请求。