# 错误处理与重试机制

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

## 错误结构

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

## 常见 HTTP 状态码

| 状态码 | 含义 | 说明与处理建议 |
|---|---|---|
| `200` | OK | 请求成功 |
| `400` | Bad Request | 请求参数格式错误或缺失必填项 |
| `401` | Unauthorized | API Key 缺失、失效或格式错误 |
| `402` | Payment Required | 账户余额不足，请登录控制台充值 |
| `404` | Not Found | 请求的模型 ID 不存在或已下线 |
| `429` | Too Many Requests | 触发并发频率限制，网关支持自动加权旁路平滑切流 |
| `500/502` | Server / 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)
```
