错误处理
了解 UloveGPT API 常见错误类型、HTTP 状态码含义和重试策略,构建健壮的 AI 应用。
错误响应格式
所有错误都返回标准 JSON 格式:
错误响应示例Json
{
"error": {
"message": "Invalid API key provided",
"type": "invalid_request_error",
"param": null,
"code": "invalid_api_key"
}
}HTTP 状态码
| 状态码 | 含义 | 常见原因 | 处理方式 |
|---|---|---|---|
400 | Bad Request | 参数错误、模型不支持、格式无效 | 检查请求参数 |
401 | Unauthorized | API Key 无效或缺失 | 检查 API Key |
403 | Forbidden | 余额不足、IP 被限 | 充值或配置 IP |
404 | Not Found | 模型不存在、端点错误 | 检查模型名 |
429 | Rate Limited | 请求频率超限 | 指数退避重试 |
500 | Server Error | 后端服务异常 | 短暂等待后重试 |
503 | Service Unavailable | 后端模型维护或过载 | 使用 fallback 模型 |
错误类型详解
400 - 请求错误
| 错误码 | 说明 |
|---|---|
invalid_api_key | API Key 格式错误 |
model_not_found | 指定的模型不存在 |
context_length_exceeded | 超出模型上下文长度限制 |
invalid_request_error | 请求参数不符合规范 |
重试策略
对于可恢复的错误(429、500、503),建议使用指数退避算法重试:
带重试的聊天调用Python
import time
from openai import OpenAI, APIError, RateLimitError, APITimeoutError
client = OpenAI(
base_url="https://www.ulovegpt.com/v1",
api_key="<你的 API_KEY>"
)
def chat_with_retry(messages, model="openai/gpt-5.4-mini", max_retries=3):
"""带重试的聊天调用"""
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model=model,
messages=messages,
timeout=30 # 设置超时
)
return response
except RateLimitError as e:
# 429: 速率限制,等待后重试
retry_after = int(e.response.headers.get("Retry-After", 2 ** attempt))
print(f"速率限制,等待 {retry_after}s 后重试 (第 {attempt + 1} 次)")
time.sleep(retry_after)
except APITimeoutError:
# 超时,指数退避重试
wait = 2 ** attempt
print(f"请求超时,等待 {wait}s 后重试 (第 {attempt + 1} 次)")
time.sleep(wait)
except APIError as e:
if e.status_code == 500:
# 服务端错误,短暂等待后重试
wait = 2 ** attempt
print(f"服务端错误,等待 {wait}s 后重试 (第 {attempt + 1} 次)")
time.sleep(wait)
else:
# 其他错误,直接抛出
raise
raise Exception(f"达到最大重试次数 {max_retries}")最佳实践
- 设置超时:所有请求都应设置
timeout,避免无限等待 - 读取 Retry-After:429 响应的 Header 中包含
Retry-After,按此值等待 - 指数退避:重试间隔按 2^n 增长,避免密集重试
- Fallback:对于 503 错误,考虑自动切换到备用模型
- 日志记录:记录错误信息便于排查问题
- 不要重试 4xx:除 429 外的 4xx 错误重试无意义,应修正请求