错误与调试
了解 API 返回的错误类型和调试方法,可以帮助你快速定位和解决问题。
错误响应格式
所有错误响应遵循统一格式:
json
{
"error": {
"message": "错误描述",
"type": "错误类型",
"code": "错误代码",
"param": "相关参数(可选)"
}
}HTTP 状态码
| 状态码 | 说明 |
|---|---|
| 200 | 成功 |
| 400 | 请求参数错误 |
| 401 | 认证失败 |
| 403 | 权限不足 |
| 404 | 资源不存在 |
| 429 | 速率限制超出 |
| 500 | 服务器内部错误 |
| 503 | 服务暂时不可用 |
常见错误代码
认证错误 (401)
| 错误代码 | 说明 | 解决方案 |
|---|---|---|
| invalid_api_key | API Key 无效 | 检查 Key 是否正确 |
| expired_api_key | API Key 已过期 | 重新创建 Key |
| revoked_api_key | API Key 已撤销 | 重新创建 Key |
请求错误 (400)
| 错误代码 | 说明 | 解决方案 |
|---|---|---|
| missing_required_field | 缺少必填参数 | 添加缺少的参数 |
| invalid_value | 参数值无效 | 检查参数格式和范围 |
| model_not_supported | 不支持的模型 | 使用支持的模型 ID |
| context_length_exceeded | Token 超限 | 减少 messages 或 max_tokens |
限制错误 (429)
| 错误代码 | 说明 | 解决方案 |
|---|---|---|
| rate_limit_exceeded | 速率限制超出 | 降低请求频率,实现重试 |
| insufficient_quota | 额度不足 | 充值或等待额度恢复 |
| concurrent_limit_exceeded | 并发超限 | 控制并发请求数 |
服务器错误 (500/503)
| 错误代码 | 说明 | 解决方案 |
|---|---|---|
| internal_error | 内部错误 | 稍后重试 |
| service_unavailable | 服务不可用 | 等待恢复,使用备用模型 |
调试技巧
1. 检查请求格式
确保请求体是有效的 JSON:
python
import json
data = {
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Hello"}]
}
# 验证 JSON 格式
try:
json.dumps(data)
except json.JSONDecodeError as e:
print(f"JSON 格式错误: {e}")2. 检查参数范围
python
# 检查 temperature 范围
temperature = 1.5
if not 0 <= temperature <= 2:
print("temperature 必须在 0-2 范围内")
# 检查 messages 格式
for msg in messages:
if msg["role"] not in ["system", "user", "assistant"]:
print(f"无效角色: {msg['role']}")3. 计算 Token 数
估算请求 Token 数,避免超出限制:
python
# 简单估算(英文约 4 字符 = 1 token,中文约 1-2 字符 = 1 token)
def estimate_tokens(text):
# 中文
chinese_chars = len([c for c in text if '\u4e00' <= c <= '\u9fff'])
# 英文和其他
other_chars = len(text) - chinese_chars
return chinese_chars + other_chars // 44. 实现详细日志
python
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
try:
response = client.chat.completions.create(...)
logger.debug(f"请求成功: {response.id}")
except Exception as e:
logger.error(f"请求失败: {e}")
logger.debug(f"请求参数: {data}")5. 使用重试机制
python
import time
def call_api(messages, max_retries=3):
for attempt in range(max_retries):
try:
return client.chat.completions.create(
model="gpt-4o",
messages=messages
)
except Exception as e:
if attempt < max_retries - 1:
wait = (attempt + 1) * 2
print(f"重试 {attempt + 1}/{max_retries}, 等待 {wait}s")
time.sleep(wait)
else:
raise e获取帮助
如果遇到无法解决的问题:
- 查看错误响应中的
message字段 - 检查控制台的 API 使用日志
- 联系技术支持