Skip to content

错误处理与重试机制 ​

Tokenlio 返回标准的 HTTP 响应状态码与格式一致的 JSON 错误负载。

错误结构 ​

json
{
  "error": {
    "message": "Insufficient balance. Please top up your workspace wallet.",
    "type": "insufficient_balance",
    "param": null,
    "code": 402
  }
}

常见 HTTP 状态码 ​

状态码含义说明与处理建议
200OK请求成功
400Bad Request请求参数格式错误或缺失必填项
401UnauthorizedAPI Key 缺失、失效或格式错误
402Payment Required账户余额不足,请登录控制台充值
404Not Found请求的模型 ID 不存在或已下线
429Too Many Requests触发并发频率限制,网关支持自动加权旁路平滑切流
500/502Server / Gateway Error上游服务异常,建议实施指数退避重试

推荐的重试模式 (Exponential Backoff) ​

python
import time
from openai import OpenAI, RateLimitError, APIError

def call_with_retry(client, **kwargs):
    max_retries = 3
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(**kwargs)
        except (RateLimitError, APIError) as e:
            if attempt == max_retries - 1:
                raise e
            wait = 2 ** attempt
            time.sleep(wait)

通过统一接口访问领先的 AI 模型