# 错误

来源: https://docs.aicentos.com/billing/errors

Language: zh-CN

> HTTP 状态码、错误响应结构、常见错误与解决方案

aicentos 完全沿用 **OpenAI 错误响应格式**。SDK 抛错时直接 catch 对应异常即可。

## 错误响应结构

所有错误响应都是这个格式：

```bash
{
  "error": {
    "message": "你的 API Key 没有访问 gpt-5 的权限",
    "type": "permission_denied",
    "code": "model_not_allowed",
    "param": "model"
  }
}
```

| 字段        | 含义             |
| --------- | -------------- |
| `message` | 人类可读的错误描述      |
| `type`    | 错误类别（见下表）      |
| `code`    | 细粒度错误码（用于程序判断） |
| `param`   | 出错的字段名（如果有）    |

## HTTP 状态码速查

| 状态码   | 类型                       | 常见原因                   |
| ----- | ------------------------ | ---------------------- |
| `400` | `invalid_request_error`  | 请求体格式错、参数非法、model 名拼错  |
| `401` | `authentication_error`   | API Key 缺失 / 错误 / 已被吊销 |
| `402` | `insufficient_quota`     | 余额不足                   |
| `403` | `permission_denied`      | Key 被禁用、模型未授权、IP 不在白名单 |
| `404` | `not_found`              | 接口路径错、模型 ID 错          |
| `408` | `request_timeout`        | 上游超时（通常 > 60s 无响应）     |
| `413` | `payload_too_large`      | 请求体过大（图像、文件）           |
| `415` | `unsupported_media_type` | Content-Type 不对        |
| `422` | `invalid_request_error`  | 请求体能解析但语义不对            |
| `429` | `rate_limit_exceeded`    | 触发限流，降低请求频率后重试         |
| `500` | `server_error`           | 平台内部错（罕见）              |
| `502` | `bad_gateway`            | 上游服务异常                 |
| `503` | `service_unavailable`    | 上游过载，建议稍后重试            |
| `504` | `gateway_timeout`        | 上游响应超时                 |

## 常见错误与解决

### 401 — Invalid API key

```bash
{ "error": { "message": "Incorrect API key provided", "type": "authentication_error" } }
```

**排查清单**：

* `Authorization` 头是不是 `Bearer sk-xxx` 格式（注意有空格）
* Key 是不是从控制台复制时带了空格 / 换行
* Key 是不是已删除 / 已禁用 / 已过期
* 是不是把测试 Key 提交进生产了

### 402 — Insufficient quota

```bash
{ "error": { "message": "Insufficient quota", "type": "insufficient_quota" } }
```

充值 → 控制台「钱包管理」。开启 [余额预警](https://docs.aicentos.com/billing/pricing#%E4%BD%99%E9%A2%9D%E9%A2%84%E8%AD%A6) 避免再发生。

### 403 — Model not allowed

```bash
{ "error": { "message": "Model gpt-5 not allowed for this key", "code": "model_not_allowed" } }
```

创建令牌时勾了「**可用模型**」白名单，请求的 model 不在里面。改令牌设置或换 Key。

### 404 — Model not found

```bash
{ "error": { "message": "The model 'gpt-4-turbo-2024-04-09' does not exist", "code": "model_not_found" } }
```

模型 ID 拼错或已下线。去[模型广场](https://aicentos.com/pricing)确认当前可用 ID。

### 429 — Rate limit exceeded

响应头 `Retry-After` 告诉你多少秒后重试。降低并发与请求频率即可恢复。

### 500 / 502 / 503 — 服务异常

通常是上游波动。**自动重试 2-3 次**通常能成功。如果持续 5 分钟以上：

* 查 [状态页](https://status.aicentos.com)（如有）
* 联系客服

### 408 / 504 — 超时

请求超过 60s 无响应。常见原因：

* prompt 太长，让模型"思考"超时
* 流式输出未启用（长响应建议加 `stream: true`）

**解决**：

* 缩短 prompt
* 开启流式：`{ "model": "...", "messages": [...], "stream": true }`
* 切到更快的模型（如从 `gpt-4o` 换 `gpt-4o-mini`）

## SDK 错误处理示例

```bash
export AICENTOS_API_KEY="sk-your-aicentos-api-key"
```

### Python

```python
import os
from openai import OpenAI, APIError, RateLimitError, AuthenticationError

client = OpenAI(api_key=os.environ["AICENTOS_API_KEY"], base_url="https://aicentos.com/v1")

try:
    resp = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "hi"}],
    )
except AuthenticationError:
    print("Key 错了")
except RateLimitError as e:
    print(f"被限流，{e.response.headers.get('Retry-After')}s 后重试")
except APIError as e:
    print(f"其他 API 错误：{e.status_code} {e.message}")
```

### Node.js

```js
import OpenAI, { APIError } from 'openai';

const client = new OpenAI({
  apiKey: process.env.AICENTOS_API_KEY,
  baseURL: 'https://aicentos.com/v1',
});

try {
  const resp = await client.chat.completions.create({ ... });
} catch (err) {
  if (err instanceof APIError) {
    console.log(err.status, err.code, err.message);
  }
}
```

## 重试与降级建议

| 错误类型                                  | 建议处理                    |
| ------------------------------------- | ----------------------- |
| `400` / `401` / `402` / `403` / `404` | **不重试**，代码 / 配置错，先排查    |
| `429`                                 | 按 `Retry-After` 重试，指数退避 |
| `500` / `502` / `503` / `504` / `408` | 立刻重试 1-3 次，间隔 1-5s      |

OpenAI 官方 SDK 默认有合理的重试策略，**生产代码直接用 SDK 不要自己 fetch**。