错误格式
API 错误响应统一采用以下格式:
JSON
{
"error": {
"message": "错误描述信息",
"type": "错误类型",
"code": "错误码",
"param": "相关参数(可选)"
}
}
常见错误码
| HTTP 状态码 | 错误码 | 说明 | 解决方案 |
|---|---|---|---|
| 400 | invalid_request | 请求参数错误 | 检查请求参数格式 |
| 401 | invalid_api_key | API Key 无效 | 检查 API Key 是否正确 |
| 403 | permission_denied | 权限不足 | 检查账户权限 |
| 429 | rate_limit_exceeded | 请求频率超限 | 降低请求频率 |
| 500 | internal_error | 服务器内部错误 | 稍后重试 |
| 503 | service_unavailable | 服务不可用 | 稍后重试 |
重试策略
建议使用指数退避算法进行重试:
Python
import time
import random
from openai import OpenAI
client = OpenAI(
base_url="https://api.lingyuncx.com/v1",
api_key="sk-xxxxxxxx"
)
def retry_with_backoff(func, max_retries=3):
for i in range(max_retries):
try:
return func()
except Exception as e:
if i == max_retries - 1:
raise
# 指数退避:1s, 2s, 4s + 随机抖动
sleep_time = (2 ** i) + random.uniform(0, 1)
time.sleep(sleep_time)
# 使用示例
response = retry_with_backoff(
lambda: client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello"}]
)
)
最佳实践
- 设置超时:请求设置合理的超时时间
- 记录日志:记录错误信息便于排查
- 优雅降级:准备备用方案或降级策略
- 限流保护:客户端主动限流避免触发服务端限流