# OpenVideo API 参考文档

> 版本：`0.1.0` · 接口风格：REST / JSON · 字符集：UTF-8
>
> 控制台：`/` · Swagger：`/docs` · 本页：`/api-docs`

OpenVideo 是一个视频 / 对话模型聚合网关。平台对外提供两套接口：

| 命名空间 | 用途 | 鉴权方式 |
| --- | --- | --- |
| `/v1/*` | 开放网关：模型、视频生成、对话 | API Key（也接受控制台 JWT） |
| `/api/*` | 控制台：登录、密钥、用量、账单、管理 | 控制台 JWT（管理员接口额外要求 admin 角色） |

[完整接口目录](#完整接口目录) · [错误码](#错误码) · [计费规则](#计费规则) · [并发说明](#并发与限流)

---

## 1. 基础信息

### 1.1 Base URL

开发环境默认：

```text
http://127.0.0.1:8000
```

所有示例中的域名都可以替换为你的部署域名。建议生产环境通过 Nginx / Caddy 走 HTTPS。

### 1.2 内容类型

- 请求：`Content-Type: application/json`
- 响应：`application/json; charset=utf-8`
- 视频文件本身不经过平台中转，`video_url` 指向上游 CDN；`/v1/videos/{id}/content` 仅做 `302` 跳转。

### 1.3 时间与金额

- 时间统一为 **UTC ISO 8601**，例如 `2026-12-04T07:25:00Z`；控制台会转换为浏览器本地时间。
- 金额单位为 **积分（credits）**，始终是整数，避免浮点误差。
- `cost` 表示本次请求最终扣费；失败任务在退款后 `cost = 0`。
- 账本中 `amount` 为带符号整数：消费为负、退款/充值为正。

### 1.4 ID 前缀

| 前缀 | 含义 |
| --- | --- |
| `task_` | 视频任务 ID |
| `chat_` | 对话调用记录 ID |
| `sk-live-` | API Key 明文（仅创建时返回） |

### 1.5 请求追踪

视频创建、查询、对话接口会返回以下响应头：

| Header | 说明 |
| --- | --- |
| `X-Request-Id` | 本次调用 ID（视频任务 ID / chat 记录 ID） |
| `X-Cost-Credits` | 本次扣费积分 |
| `X-Model` | 实际使用的平台模型 ID |

---

## 2. 鉴权

### 2.1 API Key（`/v1/*`）

在请求头中携带：

```http
Authorization: Bearer sk-live-xxxxxxxxxxxxxxxx
```

- Key 在「API 密钥」页面创建，**完整明文只显示一次**，数据库只保存 SHA-256。
- Key 可以被撤销、设置消费上限（`max_spend`）与限速（`rate_limit_per_min`，`0` 表示不限）。
- Key 状态为 `revoked`、所属用户被禁用时，调用返回 `401` / `403`。

### 2.2 控制台 JWT（`/api/*`，也可调用 `/v1/*`）

```http
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
```

JWT 通过登录接口获取，默认有效期 12 小时（`ACCESS_TOKEN_MINUTES=720`）。在线体验页就是用 JWT 调用 `/v1/videos`。

### 2.3 鉴权错误

```json
{
  "error": {
    "message": "API Key 无效",
    "type": "authentication_error",
    "code": "invalid_api_key",
    "param": null
  }
}
```

| HTTP | code | 场景 |
| --- | --- | --- |
| 401 | `missing_authorization` | 未携带 Authorization |
| 401 | `invalid_authorization` | 不是 `Bearer <token>` 格式 |
| 401 | `invalid_token` | JWT 过期或签名错误 |
| 401 | `invalid_api_key` | Key 不存在 |
| 401 | `api_key_revoked` | Key 已撤销 |
| 401 | `wrong_token_type` | 控制台接口用了 API Key |
| 403 | `user_disabled` | 账号被禁用 |
| 403 | `admin_required` | 非管理员访问 `/api/admin/*` |

---

## 3. 通用约定

### 3.1 成功响应

普通对象直接返回 JSON；列表统一返回：

```json
{
  "object": "list",
  "data": [],
  "total": 0,
  "limit": 50,
  "offset": 0
}
```

### 3.2 错误响应

所有业务错误使用统一结构：

```json
{
  "error": {
    "message": "人类可读的错误说明",
    "type": "invalid_request_error | authentication_error | permission_error | insufficient_quota | rate_limit_error | upstream_error | server_error",
    "code": "机器可读的错误码",
    "param": "出错的字段名或 null"
  }
}
```

HTTP 状态码含义：

| HTTP | 含义 |
| --- | --- |
| 200 | 成功 |
| 201 | 创建成功（注册、视频任务、密钥、充值码） |
| 400 | 参数错误 |
| 401 | 未认证 / 凭证无效 |
| 402 | 余额不足 |
| 403 | 无权限 / 密钥额度不足 / 模型停用 |
| 404 | 资源不存在 |
| 409 | 冲突（邮箱已存在、重复结算、任务未就绪） |
| 429 | 超出密钥限速 |
| 500 | 服务端内部错误 |
| 502 | 上游调用失败（会自动退款） |

### 3.3 分页

列表接口使用 `limit` + `offset`：

| 参数 | 类型 | 默认 | 范围 | 说明 |
| --- | --- | --- | --- | --- |
| `limit` | int | 50 | 1–200（后台 1–500） | 每页数量 |
| `offset` | int | 0 | ≥ 0 | 偏移量 |

返回中的 `total` 是过滤后的总条数，可用 `offset + len(data) < total` 判断是否还有下一页。

### 3.4 幂等

`POST /v1/videos` 支持请求头：

```http
Idempotency-Key: order-20261204-0001
```

- 同一个用户 + 同一个 `Idempotency-Key`，重复提交会返回**第一次创建的任务**，不会重复扣费。
- 建议使用订单号、业务唯一 ID；最大 128 字符。
- 若首次请求因余额不足失败，不会留下幂等记录，可以修正后重试。
- 对话接口暂不支持幂等键。

### 3.5 限速

- 限速按 API Key 独立计算，默认 `0`（不限）。
- 创建 / 修改 Key 时可设置 `rate_limit_per_min`（0–100000，`0` = 不限）。
- 超限返回 `429 rate_limit_exceeded`，并带 `Retry-After` 响应头。
- 控制台 JWT 调用不经过 Key 限速。

### 3.6 计费规则

视频任务：

```text
按秒计费：cost = ceil(max(min_charge, price × duration))
按次计费：cost = ceil(max(min_charge, price))
```

- `price` / `min_charge` 支持小数（例如 `0.2` 积分/秒）。
- 钱包和账本使用整数积分，因此最终 `cost` **向上取整**；`0.2 × 5 = 1.0`、最低 1.2 时扣 2 积分。

- 创建任务时预先扣费；上游失败、提交失败或超时（默认 3600 秒）会**自动全额退款**。
- 退款写入账本，`kind = refund`，任务的 `cost` 置为 0。
- 同一个用户并发扣费使用条件更新，保证余额不会被扣成负数；不同用户互不阻塞。

---

## 4. 快速开始

### 4.1 创建视频任务

```bash
curl -X POST http://127.0.0.1:8000/v1/videos \
  -H "Authorization: Bearer sk-live-你的密钥" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: demo-001" \
  -d '{
    "model": "wan-3.0-480p",
    "prompt": "一只橘猫在雪地里奔跑，慢镜头，电影质感",
    "duration": 5,
    "size": "16:9"
  }'
```

```json
{
  "id": "task_1f3c9a2b4d5e6f708192a3b4",
  "object": "video.task",
  "kind": "video",
  "model": "wan-3.0-480p",
  "status": "queued",
  "upstream_status": "queued",
  "cost": 10,
  "duration": 5,
  "size": "832x480",
  "prompt": "一只橘猫在雪地里奔跑，慢镜头，电影质感",
  "video_url": null,
  "error": null,
  "created_at": "2026-12-04T07:25:00Z",
  "updated_at": "2026-12-04T07:25:00Z",
  "completed_at": null
}
```

### 4.2 轮询任务

```bash
curl http://127.0.0.1:8000/v1/videos/task_1f3c9a2b4d5e6f708192a3b4 \
  -H "Authorization: Bearer sk-live-你的密钥"
```

完成时：

```json
{
  "id": "task_1f3c9a2b4d5e6f708192a3b4",
  "status": "succeeded",
  "cost": 10,
  "video_url": "https://cdn.example.com/video.mp4",
  "completed_at": "2026-12-04T07:27:12Z"
}
```

### 4.3 Python

```python
import time
import requests

BASE = "http://127.0.0.1:8000"
KEY = "sk-live-你的密钥"
headers = {"Authorization": f"Bearer {KEY}"}

task = requests.post(
    f"{BASE}/v1/videos",
    headers=headers,
    json={
        "model": "wan-3.0-480p",
        "prompt": "一只橘猫在雪地里奔跑",
        "duration": 5,
        "size": "16:9",
    },
    timeout=60,
).json()

while True:
    result = requests.get(f"{BASE}/v1/videos/{task['id']}", headers=headers, timeout=30).json()
    if result["status"] in ("succeeded", "failed"):
        break
    time.sleep(3)

print(result["status"], result.get("video_url"))
```

### 4.4 JavaScript

```js
const BASE = "http://127.0.0.1:8000";
const headers = {
  Authorization: "Bearer sk-live-你的密钥",
  "Content-Type": "application/json",
};

const task = await fetch(`${BASE}/v1/videos`, {
  method: "POST",
  headers,
  body: JSON.stringify({
    model: "wan-3.0-480p",
    prompt: "一只橘猫在雪地里奔跑",
    duration: 5,
    size: "16:9",
  }),
}).then((r) => r.json());

let result = task;
while (!["succeeded", "failed"].includes(result.status)) {
  await new Promise((r) => setTimeout(r, 3000));
  result = await fetch(`${BASE}/v1/videos/${task.id}`, { headers }).then((r) => r.json());
}
```

---

## 5. 模型

### 5.1 默认模型与价格

| 模型 ID | 能力 | 默认价格 |
| --- | --- | --- |
| `minimax-h3-flash` | 图片 | 3 积分/秒，最低 10 |
| `minimax-h3` | 图片 / 音频 | 6 积分/秒，最低 20 |
| `minimax-h3-ref` | 图片 / 音频 / 参考视频 | 6 积分/秒，最低 20 |
| `minimax-h3-2k` | 2K 输出 | 12 积分/秒，最低 40 |
| `wan-3.0` | 720p，支持参考素材 | 5 积分/秒，最低 15 |
| `wan-3.0-480p` | 480p 草稿档 | 2 积分/秒，最低 8 |
| `wan-3.0-1080p` | 1080p | 10 积分/秒，最低 30 |
| `file-transfer-temp` | Chat | 2 积分/次 |

`model` 字段支持平台模型 ID 或已配置的别名，网关会自动映射。

价格不是写死的：管理员可以在后台实时修改，新任务立即生效；修改不影响已经创建的任务。

### 5.2 `GET /v1/models`

公开接口，无需鉴权。

**响应字段**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `object` | string | 固定 `list` |
| `data[]` | Model[] | 模型列表（包含已停用模型，`enabled=false`） |

Model 对象：

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `id` | string | 平台模型 ID |
| `object` | string | `model` |
| `label` | string | 展示名称 |
| `kind` | string | `video` / `chat` |
| `owned_by` | string | 固定 `openvideo` |
| `description` | string | 中文描述 |
| `pricing.currency` | string | `credits` |
| `pricing.unit` | string | `second` / `call` |
| `pricing.price` | number | 单价，可带小数 |
| `pricing.min_charge` | number | 最低消费，可带小数 |
| `capabilities.images` | bool | 是否支持图片 |
| `capabilities.audio` | bool | 是否支持音频 |
| `capabilities.reference_videos` | bool | 是否支持参考视频 |
| `sizes` | string[] | 支持的画面比例（视频模型） |
| `enabled` | bool | 是否启用 |
| `duration` | object | 视频模型：`{min,max,default}` |

示例：

```json
{
  "object": "list",
  "data": [
    {
      "id": "wan-3.0-480p",
      "object": "model",
      "label": "Wan 3.0 480p",
      "kind": "video",
      "owned_by": "openvideo",
      "description": "极速低价档，适合草稿预览。",
      "pricing": { "currency": "credits", "unit": "second", "price": 2, "min_charge": 8 },
      "capabilities": { "images": true, "audio": true, "reference_videos": true },
      "sizes": ["1:1", "9:16", "16:9", "auto"],
      "duration": { "min": 1, "max": 60, "default": 5 },
      "enabled": true
    }
  ]
}
```

### 5.3 `GET /v1/models/{model_id}`

返回单个模型。`model_id` 支持平台 ID、上游模型名和展示名别名。

---

## 6. 视频生成

### 6.1 创建任务：`POST /v1/videos`

**请求头**

| Header | 必填 | 说明 |
| --- | --- | --- |
| `Authorization` | 是 | `Bearer <API Key>` 或控制台 JWT |
| `Content-Type` | 是 | `application/json` |
| `Idempotency-Key` | 否 | 幂等键，≤128 字符 |

**请求体**

| 字段 | 类型 | 必填 | 默认 | 说明 |
| --- | --- | --- | --- | --- |
| `model` | string | 是 | — | 模型 ID 或别名 |
| `prompt` | string | 否 | `""` | 提示词，≤8000 字符；与 `images` 至少提供一个 |
| `duration` | int / string | 否 | `5` | 时长（秒），1–60 |
| `seconds` | int / string | 否 | — | `duration` 的旧版别名 |
| `size` | string | 否 | `auto` | `auto` / `16:9` / `9:16` / `1:1`，或显式 `1280x720` |
| `aspect_ratio` | string | 否 | — | `size` 的旧版别名 |
| `images` | string[] | 否 | `[]` | 参考图片 URL，最多 8 个 |
| `image_urls` | string[] | 否 | `[]` | `images` 的别名，两个字段会合并去重 |
| `audio_urls` | string[] | 否 | `[]` | 参考音频 URL，最多 8 个 |
| `reference_videos` | string[] | 否 | `[]` | 参考视频 URL，最多 8 个 |

**资源 URL 规则**

- 支持 `http://`、`https://`、`data:` 前缀。
- 单个 URL ≤4000 字符；图片 + 别名合并后最多 8 个。
- 模型不支持某类素材时，传入会返回 `400 unsupported_asset`。

**尺寸映射**

平台接受统一比例，适配器根据模型映射为上游尺寸：

| 输入 | wan-3.0-480p | wan-3.0-1080p | minimax-h3 |
| --- | --- | --- | --- |
| `16:9` | `832x480` | `1920x1080` | `1366x768` |
| `9:16` | `480x832` | `1080x1920` | `768x1366` |
| `1:1` | `auto` | `auto` | `auto` |
| `auto` | `auto` | `auto` | `auto` |
| `1280x720` | 原样传递 | 原样传递 | 原样传递 |

**费用计算**

```text
cost = max(min_charge, price × duration)   # unit = second
cost = max(min_charge, price)               # unit = call
```

例如 `wan-3.0-480p` 5 秒：`max(8, 2×5) = 10` 积分。

**响应：201 Created**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `id` | string | 任务 ID，`task_...` |
| `object` | string | `video.task` |
| `kind` | string | `video` |
| `model` | string | 平台模型 ID |
| `status` | string | `queued` / `processing` / `succeeded` / `failed` |
| `upstream_status` | string | 上游原始状态 |
| `cost` | int | 本次预扣积分 |
| `duration` | int | 实际时长 |
| `size` | string | 实际提交给上游的尺寸 |
| `prompt` | string | 提示词 |
| `video_url` | string / null | 成功后视频地址 |
| `error` | string / null | 失败原因（仅失败时） |
| `created_at` | string | 创建时间 |
| `updated_at` | string | 更新时间 |
| `completed_at` | string / null | 完成 / 失败时间 |

**常见错误**

| HTTP | code | 说明 |
| --- | --- | --- |
| 400 | `empty_request` | `prompt` 与 `images` 都为空 |
| 400 | `invalid_duration` | 时长不在 1–60 |
| 400 | `unsupported_asset` | 模型不支持该素材类型 |
| 400 | `too_many_assets` | 素材超过 8 个 |
| 400 | `prompt_too_long` | 提示词超过 8000 字符 |
| 400 | `invalid_asset` | URL 格式不合法 |
| 400 | `cost_limit_exceeded` | 单次费用超过上限 |
| 402 | `insufficient_balance` | 积分不足 |
| 403 | `key_quota_exceeded` | 密钥消费上限不足 |
| 403 | `model_disabled` | 模型已停用 |
| 404 | `model_not_found` | 模型不存在 |
| 502 | `upstream_error` | 上游提交失败（已退款） |

### 6.2 查询任务：`GET /v1/videos/{task_id}`

**鉴权**：任务所有者，或管理员。

服务端对同一任务有 1 秒的轮询节流：1 秒内重复请求会直接返回当前状态，不会重复请求上游。

**任务状态机**

```text
queued ──> processing ──> succeeded
   │            │
   └────────────┴──────> failed
```

| status | 含义 |
| --- | --- |
| `queued` | 已创建，等待上游开始 |
| `processing` | 上游生成中 |
| `succeeded` | 成功，`video_url` 可用 |
| `failed` | 失败，费用已退回，`error` 有原因 |

建议每 2–5 秒轮询一次。任务超过 `TASK_TTL_SECONDS`（默认 3600 秒）仍未完成会自动标记失败并退款。

**成功响应示例**

```json
{
  "id": "task_1f3c9a2b4d5e6f708192a3b4",
  "object": "video.task",
  "kind": "video",
  "model": "wan-3.0-480p",
  "status": "succeeded",
  "upstream_status": "completed",
  "cost": 10,
  "duration": 5,
  "size": "832x480",
  "prompt": "一只橘猫在雪地里奔跑",
  "video_url": "https://cdn.example.com/video.mp4",
  "error": null,
  "created_at": "2026-12-04T07:25:00Z",
  "updated_at": "2026-12-04T07:27:12Z",
  "completed_at": "2026-12-04T07:27:12Z"
}
```

**失败响应示例**

```json
{
  "id": "task_1f3c9a2b4d5e6f708192a3b4",
  "status": "failed",
  "cost": 0,
  "video_url": null,
  "error": "上游任务失败：content moderation",
  "completed_at": "2026-12-04T07:26:01Z"
}
```

### 6.3 获取视频内容：`GET /v1/videos/{task_id}/content`

- 任务成功：返回 `302`，`Location` 为 `video_url`，可直接放入 `<video src>`。
- 任务进行中：返回 `409 task_not_ready`。
- 任务失败：返回 `409 task_failed`，并在 `message` 中带上失败原因。

> 平台不代理视频字节流，避免占用带宽；如果需要鉴权下载，请使用 `video_url` 自行处理。

### 6.4 计费与退款时序

1. 创建任务时按预估价扣费，写一条 `charge` 账本。
2. 上游提交失败：立即退款，写 `refund`，任务 `failed`、`cost=0`。
3. 上游生成失败：轮询发现失败后退款。
4. 超时：清扫任务退款。
5. 成功：任务 `succeeded`，预扣费用即为最终费用。

并发轮询 / 多 worker 同时到达时，使用条件 UPDATE 抢占任务；只有一个请求能完成结算，因此不会重复退款。

---

## 7. 对话接口

### 7.1 `POST /v1/chat/completions`

OpenAI 风格的对话通道。请求体会被转发到上游对话模型，适用于文件转存、轻量对话等场景。

**请求体**

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `model` | string | 是 | 对话模型 ID，如 `file-transfer-temp` |
| `messages` | array | 是 | 消息数组，至少一条；最后一条的 `content` 会存入用量记录预览 |
| `stream` | bool | 否 | 当前必须为 `false` 或省略；`true` 返回 400 |
| 其他字段 | any | 否 | 原样转发给上游（如 `temperature`、`max_tokens`） |

**计费**：`file-transfer-temp` 每次 2 积分；失败自动退款。

**响应**

原样返回上游的 OpenAI 风格 JSON，例如：

```json
{
  "id": "chatcmpl-...",
  "object": "chat.completion",
  "created": 1764825600,
  "model": "file-transfer-temp",
  "choices": [
    {
      "index": 0,
      "message": { "role": "assistant", "content": "..." },
      "finish_reason": "stop"
    }
  ],
  "usage": { "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0 }
}
```

**错误**

| HTTP | code | 说明 |
| --- | --- | --- |
| 400 | `invalid_messages` | `messages` 为空或不是数组 |
| 400 | `stream_not_supported` | 请求了流式响应 |
| 400 | `model_not_found` / `model_disabled` | 模型不可用 |
| 502 | `upstream_error` | 上游调用失败（已退款） |

> 当前网关不代理 SSE 流式响应。如果需要流式，可在 `providers.py` 增加流式适配器，并让路由返回 `StreamingResponse`。

---

## 8. 控制台 API

控制台接口统一使用 JWT：

```http
Authorization: Bearer <登录返回的 access_token>
```

### 8.1 认证

#### `POST /api/auth/register`

创建账号。`ALLOW_REGISTRATION=false` 时返回 403。

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `email` | string | 是 | 合法邮箱，最长 255 |
| `password` | string | 是 | 8–128 位 |
| `note` | string | 否 | 备注，最长 255 |

响应 `201`：

```json
{
  "access_token": "eyJ...",
  "token_type": "bearer",
  "expires_in": 43200,
  "user": {
    "id": 3,
    "email": "user@example.com",
    "role": "user",
    "status": "active",
    "balance": 0,
    "note": "",
    "created_at": "2026-12-04T07:30:00Z",
    "last_login_at": null
  }
}
```

#### `POST /api/auth/login`

| 字段 | 类型 | 必填 |
| --- | --- | --- |
| `email` | string | 是 |
| `password` | string | 是 |

成功返回同注册。错误：`401 invalid_credentials`、`403 user_disabled`。

#### `GET /api/me`

返回当前用户对象（不含密码哈希）。

#### `POST /api/me/password`

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `old_password` | string | 是 | 原密码 |
| `new_password` | string | 是 | 8–128 位 |

成功：`{"status":"ok"}`；原密码错误返回 `400 invalid_password`。

### 8.2 元信息与概览

#### `GET /api/meta`（公开）

```json
{
  "name": "OpenVideo API",
  "version": "0.1.0",
  "mode": "mock",
  "registration": true,
  "currency": "credits",
  "max_cost_per_request": 5000,
  "max_duration": 60,
  "default_rate_limit": 0,
  "base_url": "http://127.0.0.1:8000"
}
```

#### `GET /api/dashboard`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `balance` | int | 可用积分 |
| `spent` | int | 累计净消耗 |
| `recharged` | int | 累计充值 / 调整 |
| `today_spent` | int | 今日净消耗 |
| `keys` | int | 可用 Key 数 |
| `usage` | object | `{total,pending,succeeded,failed}` |
| `daily` | array | 近 7 天 `{date,requests,credits}` |
| `recent` | UsageEvent[] | 最近 6 条调用 |

### 8.3 API 密钥

#### `GET /api/keys`

返回当前用户的全部 Key（按创建时间倒序）：

```json
{
  "data": [
    {
      "id": 1,
      "name": "生产环境",
      "prefix": "sk-live-abcd...wxyz",
      "status": "active",
      "max_spend": null,
      "spent": 237,
      "rate_limit_per_min": 0,
      "created_at": "2026-12-04T07:00:00Z",
      "last_used_at": "2026-12-04T08:00:00Z"
    }
  ]
}
```

#### `POST /api/keys`

| 字段 | 类型 | 必填 | 默认 | 说明 |
| --- | --- | --- | --- | --- |
| `name` | string | 否 | `default` | 名称，最长 40 |
| `max_spend` | int / null | 否 | `null` | 累计消费上限，`null` = 不限 |
| `rate_limit_per_min` | int | 否 | 系统默认（0） | 每分钟请求数，`0` = 不限 |

响应 `201`：

```json
{
  "key": "sk-live-完整明文只出现这一次",
  "data": { "id": 2, "name": "生产环境", "prefix": "sk-live-...", "status": "active" }
}
```

限制：每个用户最多 20 个 Key；`max_spend` 不能为负；`rate_limit_per_min` 范围 0–100000。

#### `PATCH /api/keys/{key_id}`

可选字段：`name`、`max_spend`、`rate_limit_per_min`、`status`（`active` / `revoked`）。返回更新后的 Key 对象。

#### `POST /api/keys/{key_id}/revoke`

撤销 Key，立即生效。已撤销 Key 调用 `/v1` 返回 `401 api_key_revoked`。

#### `DELETE /api/keys/{key_id}`

软删除（等同撤销），返回 `{"id":1,"status":"revoked"}`。

### 8.4 用量记录

#### `GET /api/usage`

| 参数 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `limit` | int | 50 | 1–200 |
| `offset` | int | 0 | 偏移 |
| `kind` | string | — | `video` / `chat` |
| `status` | string | — | `succeeded` / `failed` / `pending`（也接受 `queued`、`processing`） |

返回 `object: "list"`，`data[]` 为 UsageEvent，额外包含 `payload` 与 `upstream_id`。

#### `GET /api/usage/{usage_id}`

返回单条记录；只能查看自己的记录（管理员可查看任意记录）。

### 8.5 账单与充值

#### `GET /api/billing/summary`

```json
{
  "balance": 4753,
  "spent": 237,
  "recharged": 5000,
  "today_spent": 22,
  "currency": "credits",
  "daily": [{ "date": "2026-11-28", "requests": 2, "credits": 40 }]
}
```

#### `GET /api/billing/ledger`

参数：`limit`、`offset`、`kind`（`charge` / `refund` / `topup` / `adjust` / `redeem`）。

账本条目：

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `id` | int | 自增 ID |
| `kind` | string | 变动类型 |
| `amount` | int | 带符号金额 |
| `balance_after` | int | 变动后余额 |
| `ref_type` / `ref_id` | string | 关联对象类型 / ID |
| `note` | string | 说明 |
| `created_at` | string | 时间 |

#### `POST /api/billing/redeem`

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `code` | string | 是 | 充值码，如 `OV-ABCD-EFGH-IJKL` |

响应：`{"code":"...","amount":1000,"balance":5753}`。

错误：`404 invalid_redeem_code`、`409 redeem_code_used`、`400 invalid_code`。

### 8.6 管理后台

以下接口都要求 `role=admin`，否则返回 `403 admin_required`。

#### `GET /api/admin/overview`

| 字段 | 说明 |
| --- | --- |
| `mode` | `mock` / `live` |
| `users` | `{total,active,admins}` |
| `keys_active` | 可用 Key 数 |
| `balance_total` | 全站用户余额合计 |
| `revenue` | 净收入（扣费 - 退款） |
| `charged` / `refunded` | 总扣费 / 总退款 |
| `recharged` | 总充值 / 调整 |
| `usage` | 任务统计 |
| `daily` | 近 7 天趋势 |

#### 用户管理

| 方法 | 路径 | 说明 |
| --- | --- | --- |
| `GET` | `/api/admin/users?q=&limit=&offset=` | 用户列表，`q` 搜索邮箱 / 备注；返回用户对象 + `keys` 数量 |
| `POST` | `/api/admin/users` | 创建用户 |
| `PATCH` | `/api/admin/users/{id}` | 修改 `status` / `role` / `note` |
| `POST` | `/api/admin/users/{id}/balance` | 调整余额 |
| `POST` | `/api/admin/users/{id}/password` | 重置密码 |

创建用户请求：

```json
{
  "email": "alice@example.com",
  "password": "Alice@12345",
  "role": "user",
  "balance": 3200,
  "note": "设计团队"
}
```

调整余额：

```json
{ "amount": 1000, "note": "线下转账" }
```

`amount` 可为负（扣减）；不能把余额扣成负数。响应返回更新后的用户与余额。

管理员不能修改自己的 `role` / `status`（`400 cannot_modify_self`）。

#### `GET /api/admin/usage`

参数：`user_id`、`model`、`kind`、`status`、`limit`（1–500）、`offset`。返回记录额外带 `user_email`。

#### 定价

| 方法 | 路径 | 说明 |
| --- | --- | --- |
| `GET` | `/api/admin/pricing` | 所有模型 + 当前价格 + `upstream_model` |
| `PATCH` | `/api/admin/pricing/{model_id}` | 修改 `price`、`min_charge`、`enabled` |

价格修改立即影响新任务；进行中的任务按创建时价格结算。`price` / `min_charge` 支持小数，扣费按整数积分向上取整。

#### 充值码

| 方法 | 路径 | 说明 |
| --- | --- | --- |
| `GET` | `/api/admin/redeem-codes` | 列表，包含使用者、状态、时间 |
| `POST` | `/api/admin/redeem-codes` | 批量生成 |

```json
{ "amount": 1000, "count": 5, "note": "双十二活动" }
```

响应：

```json
{
  "data": [{ "code": "OV-KNC3-QX86-YG9K", "amount": 1000 }],
  "count": 1
}
```

#### `GET /api/admin/providers`

管理员可在后台查看上游连接状态；该接口仅管理员可用，密钥始终脱敏，不会出现在用户端模型列表或任务响应中。

---

## 9. 数据对象

### 9.1 User

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `id` | int | 用户 ID |
| `email` | string | 邮箱（唯一） |
| `role` | string | `admin` / `user` |
| `status` | string | `active` / `disabled` |
| `balance` | int | 可用积分 |
| `note` | string | 备注 |
| `created_at` | string | 注册时间 |
| `last_login_at` | string / null | 最近登录 |

### 9.2 ApiKey

见 8.3。`spent` 是累计净消费（退款会扣回）。

### 9.3 UsageEvent

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `id` | string | `task_...` / `chat_...` |
| `object` | string | `video.task` / `chat.usage` |
| `kind` | string | `video` / `chat` |
| `model` | string | 平台模型 ID |
| `status` | string | 见状态机 |
| `upstream_status` | string / null | 上游原始状态 |
| `cost` | int | 最终扣费（失败为 0） |
| `duration` / `size` | int / string | 视频参数 |
| `prompt` | string | 提示词或对话预览 |
| `video_url` | string / null | 视频地址 |
| `error` | string / null | 失败原因 |
| `created_at` / `updated_at` / `completed_at` | string | 时间 |
| `payload` | object | 详情接口返回：`images`、`audio_urls`、`reference_videos` |
| `upstream_id` | string | 详情接口返回：上游任务 ID |

### 9.4 LedgerEntry

见 8.5。

---

## 10. 错误码

| HTTP | code | 说明 |
| --- | --- | --- |
| 400 | `invalid_request` | 请求体 / 参数校验失败 |
| 400 | `invalid_email` | 邮箱格式错误 |
| 400 | `weak_password` | 密码少于 8 位 |
| 400 | `empty_request` | prompt 与 images 都为空 |
| 400 | `invalid_asset` | 素材 URL 不合法 |
| 400 | `too_many_assets` | 素材数量超限 |
| 400 | `prompt_too_long` | prompt 超长 |
| 400 | `invalid_duration` | 时长不在范围 |
| 400 | `cost_limit_exceeded` | 单次费用超上限 |
| 400 | `invalid_messages` | messages 为空 / 非数组 |
| 400 | `stream_not_supported` | 请求了流式对话 |
| 400 | `invalid_amount` | 金额为 0 / 非法 |
| 400 | `invalid_password` | 原密码错误 |
| 400 | `invalid_idempotency_key` | 幂等键过长 |
| 400 | `invalid_code` | 充值码为空 |
| 400 | `cannot_modify_self` | 管理员修改自己的角色 / 状态 |
| 401 | `missing_authorization` | 未带认证头 |
| 401 | `invalid_authorization` | 认证头格式错误 |
| 401 | `invalid_token` | JWT 无效 |
| 401 | `invalid_api_key` | API Key 不存在 |
| 401 | `api_key_revoked` | API Key 已撤销 |
| 401 | `wrong_token_type` | 控制台接口用了 API Key |
| 401 | `invalid_credentials` | 登录邮箱 / 密码错误 |
| 402 | `insufficient_balance` | 余额不足 |
| 403 | `registration_disabled` | 站点关闭注册 |
| 403 | `user_disabled` | 用户被禁用 |
| 403 | `admin_required` | 需要管理员 |
| 403 | `key_quota_exceeded` | Key 消费上限不足 |
| 403 | `model_disabled` | 模型停用 |
| 404 | `model_not_found` | 模型不存在 |
| 404 | `key_not_found` | Key 不存在 / 不属于当前用户 |
| 404 | `usage_not_found` | 用量记录不存在 |
| 404 | `task_not_found` | 视频任务不存在 / 无权限 |
| 404 | `user_not_found` | 用户不存在 |
| 404 | `invalid_redeem_code` | 充值码无效 |
| 409 | `email_exists` | 邮箱已注册 |
| 409 | `conflict` | 并发幂等冲突 |
| 409 | `redeem_code_used` | 充值码已使用 |
| 409 | `task_not_ready` | 视频尚未完成 |
| 409 | `task_failed` | 视频任务失败 |
| 429 | `rate_limit_exceeded` | 超出 Key 限速 |
| 500 | `provider_unknown` | 配置了未知上游 |
| 500 | `internal_error` | 未捕获异常 |
| 502 | `upstream_error` | 上游调用失败 |

> 未匹配的 `/v1/*`、`/api/*` 路由也会返回上述错误结构，`code = http_error`。

---

## 11. 并发与限流

- 数据库：生产推荐 PostgreSQL 16 / MySQL 8 InnoDB；本仓库开发实例使用 MySQL 5.7 InnoDB（`127.0.0.1:3307`）。
- 数据库连接池：`DB_POOL_SIZE`（默认 20）+ `DB_MAX_OVERFLOW`（默认 40）。
- 同步端点线程池：`THREADPOOL_TOKENS`（默认 200），决定单进程同时在途的上游调用数。
- 上游 HTTP 连接池：`UPSTREAM_MAX_CONNECTIONS`（默认 200）/ `UPSTREAM_MAX_KEEPALIVE`（默认 50）。
- 同一用户的余额扣减会短暂锁住该用户的余额行，这是防止并发超扣的必要逻辑；不同用户互不阻塞。
- 视频任务结算、超时退款使用条件 UPDATE 抢占，避免多 worker / 并发轮询重复退款。
- 密钥限速为进程内计数；多 worker 时需要 Redis 才能全局精确。

压测脚本：

```bash
python scripts/concurrency_test.py 100
```

---

## 12. 版本

| 版本 | 变更 |
| --- | --- |
| 0.1.0 | 初始版本：视频 / 对话网关、用户与密钥、余额计费、管理后台、MySQL/PostgreSQL 支持 |

---

## 完整接口目录

| 方法 | 路径 | 鉴权 | 说明 |
| --- | --- | --- | --- |
| GET | `/healthz` | 公开 | 健康检查 |
| GET | `/v1/models` | 公开 | 模型列表 |
| GET | `/v1/models/{model_id}` | 公开 | 单个模型 |
| POST | `/v1/videos` | Key / JWT | 创建视频任务 |
| GET | `/v1/videos/{task_id}` | Key / JWT | 查询任务 |
| GET | `/v1/videos/{task_id}/content` | Key / JWT | 302 视频地址 |
| POST | `/v1/chat/completions` | Key / JWT | 对话 / 文件转存 |
| POST | `/api/auth/register` | 公开 | 注册 |
| POST | `/api/auth/login` | 公开 | 登录 |
| GET | `/api/meta` | 公开 | 站点元信息 |
| GET | `/api/me` | JWT | 当前用户 |
| POST | `/api/me/password` | JWT | 修改密码 |
| GET | `/api/dashboard` | JWT | 控制台概览 |
| GET | `/api/keys` | JWT | 密钥列表 |
| POST | `/api/keys` | JWT | 创建密钥 |
| PATCH | `/api/keys/{id}` | JWT | 修改密钥 |
| POST | `/api/keys/{id}/revoke` | JWT | 撤销密钥 |
| DELETE | `/api/keys/{id}` | JWT | 删除（软撤销） |
| GET | `/api/usage` | JWT | 用量列表 |
| GET | `/api/usage/{id}` | JWT | 用量详情 |
| GET | `/api/billing/summary` | JWT | 计费汇总 |
| GET | `/api/billing/ledger` | JWT | 账本 |
| POST | `/api/billing/redeem` | JWT | 兑换充值码 |
| GET | `/api/admin/overview` | Admin | 全站概览 |
| GET | `/api/admin/users` | Admin | 用户列表 |
| POST | `/api/admin/users` | Admin | 创建用户 |
| PATCH | `/api/admin/users/{id}` | Admin | 修改用户 |
| POST | `/api/admin/users/{id}/balance` | Admin | 调整余额 |
| POST | `/api/admin/users/{id}/password` | Admin | 重置密码 |
| GET | `/api/admin/usage` | Admin | 全站用量 |
| GET | `/api/admin/pricing` | Admin | 价格列表 |
| PATCH | `/api/admin/pricing/{model_id}` | Admin | 修改价格 |
| GET | `/api/admin/redeem-codes` | Admin | 充值码列表 |
| POST | `/api/admin/redeem-codes` | Admin | 生成充值码 |
| GET | `/api/admin/providers` | Admin | 上游配置状态 |
| GET | `/docs` | 公开 | Swagger UI |
| GET | `/api-docs` | 公开 | 本文档 |

