BufferAPI 使用标准 HTTP 状态码,错误响应体遵循 OpenAI 格式。
{
"error": {
"message": "Invalid API key provided",
"type": "authentication_error",
"code": "invalid_api_key"
}
}
| HTTP 状态码 | 错误类型 | 说明 | 处理方式 |
|---|---|---|---|
400 | invalid_request | 请求参数错误 | 检查请求参数格式 |
401 | authentication_error | API Key 无效或过期 | 检查 Key 是否正确 |
403 | permission_denied | 无权访问该资源 | 检查 Key 权限 |
404 | not_found | 模型或端点不存在 | 检查模型 ID 拼写 |
429 | rate_limit | 请求频率超限 | 降低请求频率或升级套餐 |
500 | server_error | 服务器内部错误 | 重试,如持续出现联系支持 |
502 | bad_gateway | 上游供应商错误 | 重试,系统自动切换节点 |
503 | service_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")