Skip to content

错误与调试

了解 API 返回的错误类型和调试方法,可以帮助你快速定位和解决问题。

错误响应格式

所有错误响应遵循统一格式:

json
{
  "error": {
    "message": "错误描述",
    "type": "错误类型",
    "code": "错误代码",
    "param": "相关参数(可选)"
  }
}

HTTP 状态码

状态码说明
200成功
400请求参数错误
401认证失败
403权限不足
404资源不存在
429速率限制超出
500服务器内部错误
503服务暂时不可用

常见错误代码

认证错误 (401)

错误代码说明解决方案
invalid_api_keyAPI Key 无效检查 Key 是否正确
expired_api_keyAPI Key 已过期重新创建 Key
revoked_api_keyAPI Key 已撤销重新创建 Key

请求错误 (400)

错误代码说明解决方案
missing_required_field缺少必填参数添加缺少的参数
invalid_value参数值无效检查参数格式和范围
model_not_supported不支持的模型使用支持的模型 ID
context_length_exceededToken 超限减少 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 // 4

4. 实现详细日志

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

获取帮助

如果遇到无法解决的问题:

  1. 查看错误响应中的 message 字段
  2. 检查控制台的 API 使用日志
  3. 联系技术支持