openapi: 3.1.0
info:
  title: PixGT / 流光AI Open API
  version: 1.0.0-draft
  summary: 面向电商商品套图、自由生图与生视频的企业级开放接口。
  description: |-
    # 概览

    PixGT（流光AI）Open API 让你的 ERP、PIM、铺货软件或自研 Agent 直接调用流光AI 的电商视觉生成能力：**商品套图、自由生图、生视频**。

    - **企业版能力**：API Key 由企业所有者 / 管理员在企业管理面板签发，调用消耗**企业共享算力（点）**，与站内同价。
    - **统一异步任务**：所有生成能力都走 `POST /tasks` 创建，再通过 `GET /tasks/{task_id}` 轮询或 Webhook 获取结果。
    - **重试安全**：创建任务支持 `Idempotency-Key`，网络重试不会重复扣点。
    - **能力可发现**：模型、套图模块、发布平台、平台尺寸预设都可以通过接口获取，不必写死。

    ## 环境

    | 环境 | Base URL | Key 前缀 |
    | :--- | :--- | :--- |
    | 预览（沙箱） | `https://tapi.pixgt.cn/open/v1` | `pgk_test_` |
    | 正式 | `https://api.pixgt.cn/open/v1` | `pgk_live_` |

    - 请先在**沙箱**联调；本站在线调试面板默认指向沙箱。
    - 国内版（pixgt.cn）与国际版（pixgt.com）是两套独立系统，Key 不互通。
    - 兼容域名：`api.liuguangai.com` / `tapi.liuguangai.com` 与上表域名指向同一服务，Key 通用。

    ## 基础约定

    - 请求与响应均为 `application/json; charset=utf-8`（上传素材使用 `multipart/form-data`），字段一律 `snake_case`。
    - 时间统一为 ISO 8601 UTC，例如 `2026-11-28T15:00:00Z`。
    - 每个响应都带 `X-Request-Id`，报障时提供即可快速定位。
    - 计费单位为**点（points）**。

    ## 给 AI 编程工具

    把下面任意一个链接发给 Cursor、Claude Code 等 AI 编程工具，即可让它读懂全部接口并生成对接代码：

    - [llms.txt](https://docs.pixgt.cn/llms.txt)：文档目录
    - [llms-full.txt](https://docs.pixgt.cn/llms-full.txt)：全部指南 + 全部接口的 Markdown 全文
    - [openapi.yaml](https://docs.pixgt.cn/openapi.yaml) / [openapi.json](https://docs.pixgt.cn/openapi.json)：OpenAPI 3.1 机器可读规范

    # 快速开始

    5 分钟内用 `curl` 跑通第一组**商品套图**：上传商品图 → 价格预估 → 创建任务（带幂等键）→ 轮询或接收 Webhook → 下载结果。

    ## 准备工作

    1. **拿到 API Key**：企业所有者或管理员登录流光AI，进入 **企业管理面板 →「开发者 / API」**，点「创建 Key」。联调请在**预览（沙箱）环境**创建，Key 以 `pgk_test_` 开头；正式环境的 Key 以 `pgk_live_` 开头。详见 [鉴权与 API Key](#description/鉴权与-api-key)。
    2. **选择环境**：

    | 环境 | Base URL | 说明 |
    | :--- | :--- | :--- |
    | 预览（沙箱） | `https://tapi.pixgt.cn/open/v1` | 独立库、独立 Key，先在这里联调 |
    | 正式 | `https://api.pixgt.cn/open/v1` | 生产环境，按实际消耗扣企业算力（点） |

    3. 在终端里设置两个环境变量（下文所有命令都会用到）：

    ```bash
    export PIXGT_API_KEY="pgk_test_xxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    export PIXGT_BASE="https://tapi.pixgt.cn/open/v1"
    ```

    > 本页右侧的在线调试面板默认指向**沙箱**。填入 Key 后可以直接点「发送」调用；Key 只在你的浏览器与 PixGT 服务器之间传输，不经过任何第三方代理。

    ## 第 1 步：上传商品图

    ```bash
    curl -s "$PIXGT_BASE/assets" \
      -H "Authorization: Bearer $PIXGT_API_KEY" \
      -F file=@./sku-10086.jpg
    ```

    返回 `201`：

    ```json
    {
      "id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0",
      "object": "asset",
      "mime_type": "image/jpeg",
      "width": 1600,
      "height": 1600,
      "bytes": 834221,
      "expires_at": "2026-12-28T15:00:00Z"
    }
    ```

    - 支持 png / jpg / jpeg / webp，单张 ≤ 20MB；素材 **30 天**后自动清理。
    - 也可以不上传，直接在任务里传公网 `https` 图片地址（见 [任务与状态](#description/任务与状态)）。

    ## 第 2 步（可选）：查可选项

    套图模块、发布平台、文字语言、节日主题、平台尺寸预设都可以通过接口获取，不要在代码里写死：

    ```bash
    curl -s "$PIXGT_BASE/options/product-suite" -H "Authorization: Bearer $PIXGT_API_KEY"
    curl -s "$PIXGT_BASE/models?type=image"      -H "Authorization: Bearer $PIXGT_API_KEY"
    ```

    ## 第 3 步：价格预估（不扣点）

    ```bash
    curl -s "$PIXGT_BASE/tasks/estimate" \
      -H "Authorization: Bearer $PIXGT_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "type": "product_suite",
        "input": {
          "images": [{ "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" }],
          "product_description": "便携式榨汁杯，350ml，USB-C 充电",
          "platform": "taobao",
          "language": "zh",
          "modules": ["main_image", "selling_points", "scene", "spec"],
          "size": { "preset_id": "tb_main" },
          "model": "auto"
        }
      }'
    ```

    返回：

    ```json
    { "object": "estimate", "type": "product_suite", "points": 480, "balance": 160000, "balance_after": 159520, "affordable": true,
      "breakdown": [{ "item": "main_image", "points": 120 }, { "item": "selling_points", "points": 120 }, { "item": "scene", "points": 120 }, { "item": "spec", "points": 120 }] }
    ```

    > 示例中的点数仅为示意，以接口实时返回为准。预估与实际扣费使用同一套计价函数。

    ## 第 4 步：创建任务（带幂等键）

    ```bash
    curl -s -i "$PIXGT_BASE/tasks" \
      -H "Authorization: Bearer $PIXGT_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: sku-10086-suite-v1" \
      -d '{
        "type": "product_suite",
        "input": {
          "images": [{ "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" }],
          "product_description": "便携式榨汁杯，350ml，USB-C 充电",
          "platform": "taobao",
          "language": "zh",
          "modules": ["main_image", "selling_points", "scene", "spec"],
          "size": { "preset_id": "tb_main" },
          "model": "auto"
        },
        "webhook_url": "https://erp.example.com/pixgt/callback",
        "client_reference_id": "SKU-10086"
      }'
    ```

    立即返回 `202 Accepted`（不等待出图）：

    ```json
    {
      "id": "task_01JDQ8Z3K7M2V9X4R6T1B5N8C0",
      "object": "task",
      "type": "product_suite",
      "status": "queued",
      "created_at": "2026-11-28T15:00:00Z",
      "cost": { "points_estimated": 480, "points_charged": 480, "points_refunded": 0 },
      "client_reference_id": "SKU-10086"
    }
    ```

    - 创建即**按预估预扣**点数，失败部分自动退点。
    - 网络超时重试时**带同一个 `Idempotency-Key`**，不会重复建任务、不会重复扣点（见 [幂等](#description/幂等)）。

    ## 第 5 步：获取结果

    **方式 A：轮询**（间隔 ≥ 5 秒）

    ```bash
    TASK_ID="task_01JDQ8Z3K7M2V9X4R6T1B5N8C0"
    while true; do
      RESP=$(curl -s "$PIXGT_BASE/tasks/$TASK_ID" -H "Authorization: Bearer $PIXGT_API_KEY")
      STATUS=$(echo "$RESP" | jq -r .status)
      echo "status=$STATUS"
      case "$STATUS" in succeeded|partially_succeeded|failed) break;; esac
      sleep 5
    done
    echo "$RESP" | jq '.outputs[] | {module, status, url, url_expires_at}'
    ```

    **方式 B：Webhook**：任务进入终态时，PixGT 向 `webhook_url`（或企业默认回调地址）推送 `task.succeeded` / `task.partially_succeeded` / `task.failed` 事件，`data` 与 `GET /tasks/{task_id}` 的响应完全一致。务必校验签名，见 [Webhook](#description/webhook)。

    ## 第 6 步：下载并转存

    `outputs[].url` 是**带签名的临时地址（约 24 小时有效）**。任务成功后请**立即下载转存**到你自己的存储，不要把它直接写进商品详情页。地址过期后重新 `GET /tasks/{task_id}` 即可拿到新地址，见 [结果地址有效期](#description/结果地址有效期)。

    ```bash
    echo "$RESP" | jq -r '.outputs[] | select(.status=="succeeded") | "\(.index) \(.url)"' |
    while read -r IDX URL; do curl -s -o "output-$IDX.png" "$URL"; done
    ```

    ## 下一步

    - 自由生图（`image_generation`）与生视频（`video_generation`）的入参见 [任务与状态](#description/任务与状态)。
    - 上线前把 `PIXGT_BASE` 换成 `https://api.pixgt.cn/open/v1`，并使用 `pgk_live_` 正式 Key。
    - 给 AI 编程工具：把 `https://docs.pixgt.cn/llms-full.txt` 或 `https://docs.pixgt.cn/openapi.yaml` 发给 Cursor / Claude Code 等工具，即可生成对接代码。

    # 鉴权与 API Key

    所有接口都使用 **Bearer Token** 鉴权：

    ```http
    Authorization: Bearer pgk_live_3fa9c0d1e2b4_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ```

    ## Key 的形态

    ```text
    pgk_<环境>_<12 位十六进制前缀>_<43 位随机串>
    ```

    | 前缀 | 环境 | 用途 |
    | :--- | :--- | :--- |
    | `pgk_test_` | 预览（沙箱）`https://tapi.pixgt.cn/open/v1` | 联调、测试 |
    | `pgk_live_` | 正式 `https://api.pixgt.cn/open/v1` | 生产 |

    - 沙箱与正式是**两套独立的系统**（独立数据库、独立 Key），Key 不互通。
    - 国内版（pixgt.cn）与国际版（pixgt.com）也是独立系统，Key 不互通。

    ## 在哪里创建 Key

    1. 企业**所有者**或**管理员**登录，进入 **企业管理面板 →「开发者 / API」**（普通成员看不到此入口）。
    2. 点「创建 Key」，填写：
       - **名称**（必填，如「ERP 生产」）与**备注**（选填，如「对接聚水潭，联系人张三」）；
       - **权限范围（Scope）**，默认全选，见下表；
       - **有效期**：90 天 / 180 天 / 1 年 / 永不过期；
       - **月度预算**（可选）：这把 Key 每月最多可消耗的点数，超出返回 `402 key_budget_exceeded`。
    3. 创建后 Key 直接出现在列表里。

    > 一期只开放**企业 Key**：调用消耗企业共享算力（点），不会动用任何成员的个人点数。

    ## 随时查看与复制

    - 列表中 Key 默认掩码显示（如 `pgk_live_3fa9c0d1e2b4••••••••••••Xq2Z`）。
    - 点 **👁 小眼睛**可查看完整明文；点 **📋 复制**直接复制完整 Key。
    - 每次查看明文都会留下审计记录（谁、何时、哪把 Key），列表显示「最近查看」。

    ## 泄露怎么办：删除

    - 发现 Key 泄露或不再使用，在列表中**删除**即可，**立即失效**，之后使用这把 Key 的请求返回 `401 invalid_api_key`。
    - 历史任务与账单仍可按这把 Key 追溯。
    - **轮换**：先新建一把 → 把你的系统切换到新 Key → 删除旧 Key。

    ## 权限范围（Scope）

    | Scope | 允许的接口 | 默认 |
    | :--- | :--- | :---: |
    | `tasks:write` | `POST /tasks`、`POST /tasks/estimate` | ✅ |
    | `tasks:read` | `GET /tasks`、`GET /tasks/{task_id}` | ✅ |
    | `assets:write` | `POST /assets` | ✅ |
    | `account:read` | `GET /account`、`GET /account/balance` | ✅ |

    - `GET /models` 与 `GET /options/product-suite` 只需一把有效 Key，不要求特定 Scope。
    - 缺少所需 Scope 返回 `403 insufficient_scope`。
    - 常见做法：给「生产系统」签一把全权限 Key，给「财务对账脚本」签一把只有 `account:read` 的只读 Key。

    ## 鉴权相关错误

    | HTTP | `code` | 含义 |
    | :---: | :--- | :--- |
    | 401 | `missing_api_key` | 没有带 `Authorization` 头 |
    | 401 | `invalid_api_key` | Key 格式不对、不存在或已删除 |
    | 401 | `api_key_expired` | Key 已过有效期 |
    | 403 | `insufficient_scope` | Key 缺少该接口所需的 Scope |
    | 403 | `enterprise_expired` | 企业套餐已到期（只读封存期），生成类接口不可用，查询类接口仍可用 |
    | 403 | `api_access_disabled` | 该企业尚未开通 API，或已被平台限制 |

    ## 安全建议

    - **只在服务端保存 Key**，不要写进网页前端、小程序或 App 安装包。
    - 不要把 Key 提交到代码仓库；使用环境变量或密钥管理服务。
    - 不同系统使用不同的 Key，并设置月度预算，便于定位与止损。
    - 本文档站的在线调试面板直接从你的浏览器请求 PixGT 接口（接口已开放跨域），**不经过任何第三方代理**；建议在调试面板中只使用沙箱 `pgk_test_` Key。

    # 任务与状态

    所有生成能力（商品套图 / 自由生图 / 生视频）都是**异步任务**，共用同一套接口与外层结构，只有 `type` 和 `input` 不同：

    ```text
    POST /tasks  ──202──▶  GET /tasks/{task_id}（轮询）  或  Webhook（推送）
    ```

    ## 任务类型

    | `type` | 能力 | 产出 |
    | :--- | :--- | :--- |
    | `product_suite` | 商品套图：一次生成主图、卖点图、场景图等多张电商图 | 每个模块 1 张 |
    | `image_generation` | 自由生图：提示词 + 可选参考图 | `n` 张（1–4） |
    | `video_generation` | 生视频：提示词 + 参考图 / 首帧 / 首尾帧 | 1 段视频 |

    > 后续版本会新增 `type`（如模特试穿、换背景），客户端应**容忍未知取值**。

    ## 状态机

    ```text
    queued ──▶ processing ──┬─▶ succeeded            （全部产出成功）
       │                    ├─▶ partially_succeeded  （部分产出失败，失败部分已退点）
       │                    └─▶ failed               （全部失败，全额退点）
       └──────────────────────▶ failed               （审核拦截 / 系统异常）
    ```

    | `status` | 含义 | 终态 |
    | :--- | :--- | :---: |
    | `queued` | 已受理、已预扣点数，等待开始 | |
    | `processing` | 正在规划 / 生成 | |
    | `succeeded` | 全部产出成功 | ✅ |
    | `partially_succeeded` | 任务结束，部分产出成功、部分失败 | ✅ |
    | `failed` | 任务失败 | ✅ |

    `partially_succeeded` 主要用于**商品套图**（一次出多张）：可以直接使用成功的几张，失败的模块单独再提交一次。

    ## 扣点：预扣与退点

    `cost` 字段：

    | 字段 | 含义 |
    | :--- | :--- |
    | `points_estimated` | 创建时的预估点数（与 `POST /tasks/estimate` 一致） |
    | `points_charged` | 创建时实际预扣的点数 |
    | `points_refunded` | 失败部分已退还的点数 |

    **净消耗 = `points_charged` − `points_refunded`**。例：4 张套图预扣 480 点，其中 1 张失败，任务结束后 `points_refunded = 120`，净消耗 360 点。

    - 余额不足时创建返回 `402 insufficient_balance`；Key 月度预算用尽返回 `402 key_budget_exceeded`。
    - API 调用与企业站内扣点**同价**，不另行定价。

    ## 查询任务

    `GET /tasks/{task_id}` 的响应与 Webhook 事件里的 `data` **完全同构**：

    ```json
    {
      "id": "task_01JDQ8Z3K7M2V9X4R6T1B5N8C0",
      "object": "task",
      "type": "product_suite",
      "status": "partially_succeeded",
      "progress": { "total": 4, "succeeded": 3, "failed": 1, "pending": 0 },
      "input": { "...": "规范化后的入参回显" },
      "outputs": [
        { "index": 0, "module": "main_image", "status": "succeeded",
          "url": "https://...签名地址...", "url_expires_at": "2026-11-29T15:00:00Z",
          "width": 800, "height": 800, "format": "png", "model": "seedream5.0" },
        { "index": 3, "module": "spec", "status": "failed",
          "error": { "code": "content_policy_violation", "message": "生成内容未通过安全审核", "retryable": false } }
      ],
      "cost": { "points_estimated": 480, "points_charged": 480, "points_refunded": 120 },
      "error": null,
      "created_at": "2026-11-28T15:00:00Z",
      "completed_at": "2026-11-28T15:02:41Z",
      "client_reference_id": "SKU-10086",
      "metadata": { "shop": "tmall-flagship" },
      "watermark": false
    }
    ```

    - **轮询间隔建议 ≥ 5 秒**。生图通常几十秒，视频可能需要数分钟。
    - 套图的 `outputs` 顺序固定为：`main_image` → `selling_points` → `scene` → `detail` → `spec` → `white_background` → `features` → `comparison`（只包含你选择的模块），与入参 `modules` 的书写顺序无关。
    - `outputs[].url` 是临时签名地址，见 [结果地址有效期](#description/结果地址有效期)。
    - 视频产出额外带 `duration`（秒）与 `cover_url`（首帧封面）。

    ## 任务列表

    `GET /tasks?status=succeeded&type=product_suite&client_reference_id=SKU-10086&limit=20`

    - 只返回**当前企业通过 API 创建**的任务，按创建时间倒序。
    - 游标分页：`has_more=true` 时，把本页最后一条的 `id` 作为下一页的 `starting_after`。
    - 单页 `limit` 最大 100；可按 `type`、`status`、`client_reference_id`、`created_after`、`created_before` 筛选。

    ## 通用字段

    | 字段 | 必填 | 说明 |
    | :--- | :---: | :--- |
    | `type` | ✅ | `product_suite` / `image_generation` / `video_generation` |
    | `input` | ✅ | 该类型的业务参数，见下文 |
    | `webhook_url` | | 覆盖企业默认回调地址；仅 `https`，≤ 512 字符 |
    | `client_reference_id` | | 你自己的业务单号（≤ 64 字符），可在列表中按它查询 |
    | `metadata` | | 最多 16 个键值对（键 ≤ 40 字符，值为 ≤ 256 字符的字符串），原样回传，不参与生成 |
    | `watermark` | | 默认 `false`，见 [水印](#description/水印-watermark) |

    > **严格校验**：请求体里出现未定义的字段会直接返回 `400 invalid_parameter`（`param` 指出是哪个字段），避免拼错字段名却以为生效了。

    ## 图片输入 `images[]`

    每一项二选一：

    - `{ "asset_id": "asset_..." }`：通过 `POST /assets` 上传得到（**推荐**，稳定）。
    - `{ "url": "https://..." }`：公网 `https` 地址，服务端下载转存后使用。要求：仅 `https`、不得指向内网地址、单张 ≤ 20MB、格式 png / jpg / jpeg / webp、下载超时 15 秒。失败返回 `400 invalid_image_url`，`param` 指向具体哪一张（如 `input.images[1].url`）。

    ## `product_suite` 商品套图

    | 字段 | 必填 | 说明 |
    | :--- | :---: | :--- |
    | `images` | ✅ | 商品图 1–6 张 |
    | `product_description` | | 商品名称、卖点、补充说明（≤ 2000 字符） |
    | `platform` | | 发布平台，取值见 `GET /options/product-suite`（如 `taobao`、`jd`、`pinduoduo`、`douyin`、`amazon`） |
    | `language` | | 图中文字语言（ISO 639-1，如 `zh`、`en`、`ja`） |
    | `modules` | ✅ | 至少 1 个、不可重复：`main_image` 主图、`selling_points` 卖点图、`scene` 场景图、`detail` 细节图、`spec` 规格参数图、`white_background` 白底图、`features` 功能图、`comparison` 对比图 |
    | `size` | | 统一尺寸对象，见 [尺寸 size](#description/尺寸-size) |
    | `model` | | 默认 `auto`，取值见 `GET /models?type=image` |
    | `module_options.spec.product_size` | | 规格图的真实尺寸 `{length, width, height, unit}`，`unit` 为 `cm` / `mm` / `in`；不填则只画方向线、不编数字 |
    | `module_options.scene.hint` | | 场景一句话描述（≤ 60 字符） |
    | `module_options.comparison.mode` | | `ordinary` / `before_after` / `pain_point` |
    | `festival.theme` | | 节日 / 大促氛围，取值见 `festival_themes`；`none` 或不传表示不加；`custom` 时配合 `festival.custom {name ≤24, prompt ≤200, palette_id}` |

    ## `image_generation` 自由生图

    ```json
    {
      "type": "image_generation",
      "input": {
        "prompt": "把这款香水放在大理石台面上，清晨柔光",
        "images": [{ "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" }],
        "n": 2,
        "size": { "width": 1200, "height": 1600 },
        "model": "auto"
      }
    }
    ```

    | 字段 | 必填 | 说明 |
    | :--- | :---: | :--- |
    | `prompt` | ✅ | 提示词，1–4000 字符 |
    | `images` | | 参考图，最多 10 张（以模型能力 `max_input_images` 为准） |
    | `n` | | 输出张数，1–4，默认 1 |
    | `size` | | 见 [尺寸 size](#description/尺寸-size) |
    | `model` | | 默认 `auto`；可选值见 `GET /models?type=image`（如 `seedream5.0`、`lumi-g2`、`lumi-npro`） |

    ## `video_generation` 生视频

    ```json
    {
      "type": "video_generation",
      "input": {
        "prompt": "镜头缓慢环绕榨汁杯，水果落入杯中溅起水花",
        "mode": "image_to_video",
        "images": [{ "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" }],
        "model": "seedance2.0-fast",
        "duration": 5,
        "aspect_ratio": "9:16",
        "resolution": "720p"
      }
    }
    ```

    | 字段 | 必填 | 说明 |
    | :--- | :---: | :--- |
    | `prompt` | ✅ | 视频描述，1–4000 字符 |
    | `model` | ✅ | 视频模型，取值见 `GET /models?type=video` |
    | `mode` | | `reference`（默认，多图参考，0–9 张）/ `image_to_video`（首帧，恰好 1 张）/ `first_last_frame`（首尾帧，恰好 2 张） |
    | `images` | | 数量按 `mode` 校验 |
    | `duration` | | 秒，取值以模型能力 `durations` 为准 |
    | `aspect_ratio` | | `16:9` / `9:16` / `1:1` / `4:3` / `3:4` / `21:9` |
    | `resolution` | | `480p` / `720p` / `1080p` / `2k`，以模型能力为准 |
    | `enhance` | | 自动超清增强（额外计费）；`1080p` / `2k` 不可用；不能与 `watermark` 同时开启 |

    ## 任务内失败原因

    单个产出失败时看 `outputs[].error`，整个任务失败时看顶层 `error`：

    | `code` | 含义 | 建议 |
    | :--- | :--- | :--- |
    | `content_policy_violation` | 输入或生成内容未通过安全审核 | 修改提示词 / 图片后重新提交 |
    | `generation_failed` | 生成失败 | 可重试 |
    | `timeout` | 生成超时 | 可重试 |
    | `watermark_failed` | 视频水印烧录失败 | 可重试 |
    | `internal_error` | 系统异常 | 可重试 |

    以 `retryable` 字段为准：`true` 时可以原样重新提交（请使用**新的** `Idempotency-Key`）。

    # 尺寸 size

    商品套图与自由生图都用**一个** `size` 对象描述输出尺寸，三种写法**只能选一种**，避免「分辨率」和「比例」分开传拼出矛盾组合。

    | 写法 | 示例 | 适合 |
    | :--- | :--- | :--- |
    | 平台预设 | `{ "preset_id": "tb_main" }` | **推荐**：直接按发布平台规范出图 |
    | 精确像素 | `{ "width": 1000, "height": 1000 }` | 有明确像素要求 |
    | 档位 + 比例 | `{ "tier": "2k", "aspect_ratio": "3:4" }` | 只关心清晰度与构图比例 |

    不传 `size` 时等同于 `{ "tier": "auto" }`，由模型自动决定。

    ## 1. 平台预设 `preset_id`

    取值来自 `GET /options/product-suite` 的 `size_presets`（按平台分组，每项带 `width`、`height`、`aspect_ratio`、`module_group`）。例如：

    | `preset_id` | 平台 | 尺寸 |
    | :--- | :--- | :--- |
    | `tb_main` | 淘宝/天猫 主图 | 800 × 800 |
    | `tb_main34` | 淘宝/天猫 3:4 主图 | 750 × 1000 |
    | `jd_main` | 京东 主图 | 800 × 800 |
    | `amz_main` | 亚马逊 主图 | 2000 × 2000 |

    > 以上仅为示例，完整列表以接口返回为准，请勿在代码中写死。未知的 `preset_id` 返回 `400 invalid_parameter`（`param: input.size.preset_id`）。

    预设本质上是精确像素，计价规则与下面的「精确像素」相同。

    ## 2. 精确像素 `width` + `height`

    ```json
    { "size": { "width": 1200, "height": 1600 } }
    ```

    - `width`、`height` 必须**同时**给出，且为整数，范围 **64–4096** 像素。
    - 长宽比不超过 **3:1**。
    - **计价档位按像素自动推算，只降不抬**：例如要 1000 × 1000，按 1K 档计价，不会出现「按 2K 收费却只交付 1000 × 1000」。

    ## 3. 档位 + 比例 `tier` + `aspect_ratio`

    ```json
    { "size": { "tier": "2k", "aspect_ratio": "3:4" } }
    ```

    - `tier`：`auto` / `1k` / `2k` / `4k`；省略时为 `auto`。
    - `aspect_ratio`：`W:H` 格式（如 `1:1`、`3:4`、`16:9`），长宽比不超过 3:1；省略时由模型决定。
    - 计价按 `tier` 档位，单价见 `GET /models` 的 `pricing`。

    ## 常见错误

    | 请求 | 结果 |
    | :--- | :--- |
    | `{ "preset_id": "tb_main", "tier": "2k" }` | `400`：只能使用一种写法 |
    | `{ "width": 1000 }` | `400`：width 与 height 必须同时给出 |
    | `{ "width": 4000, "height": 1000 }` | `400`：长宽比不能超过 3:1 |
    | `{ "tier": "8k" }` | `400`：tier 只能是 auto / 1k / 2k / 4k |

    ## 视频不使用 size

    视频任务使用 `aspect_ratio` 与 `resolution` 两个独立字段（见 [任务与状态](#description/任务与状态)），不接受 `size`。

    # 水印 watermark

    三类任务通用，写在请求体**顶层**（与 `type`、`input` 同级）：

    ```json
    { "type": "image_generation", "input": { "prompt": "..." }, "watermark": true }
    ```

    | 取值 | 效果 |
    | :--- | :--- |
    | 不传 / `false`（默认） | 输出**无水印**。直接上架商品图的对接大多使用这种方式 |
    | `true` | 输出带平台水印，适合发给下游审稿、预览、给终端用户试用等场景 |

    ## 规则

    - **不额外收费**：`true` 与 `false` 同价。
    - 任务对象的 `watermark` 字段回显本任务是否要求加水印，事后可查。
    - **图片**：水印在签发结果地址时叠加（国内结果地址会多一个 `x-oss-process` 参数，并被签进签名里，无法篡改去除），不重新生成、不增加耗时。
    - **视频**：水印需要烧录进视频，任务要等水印片就绪才进入终态，通常会多出几十秒。
      - 烧录失败时，该产出 `status=failed`、`error.code=watermark_failed`、`retryable=true`；**不会把无水印原片交给要求加水印的请求**。
      - 视频的 `watermark: true` 不能与 `enhance: true` 同时使用，否则返回 `400 invalid_parameter`（`param: watermark`）。
    - API 任务只认请求里的 `watermark` 参数，不受站内其他水印策略影响。

    # 结果地址有效期

    任务产出的 `outputs[].url`（视频还有 `cover_url`）是**带签名的临时地址**，有效期约 **24 小时**，精确的过期时间见同级字段 `url_expires_at`。

    ```json
    { "index": 0, "status": "succeeded",
      "url": "https://<bucket>.oss-cn-guangzhou.aliyuncs.com/.../20261127_ab12.png?x-oss-date=...&x-oss-expires=86400&x-oss-signature=...",
      "url_expires_at": "2026-11-29T15:00:00Z" }
    ```

    ## 为什么会过期

    1. **结果存放在私有存储桶**：企业的商品图在上架前属于商业机密，不能变成「谁拿到链接都能看、永久有效」的公开地址。
    2. **违规内容可以真正下架**：已发出的旧链接最多在有效期内可用，不会在外面永久流传。
    3. **防盗链与流量盗刷**：永久公开链接容易被当成免费图床。

    ## 正确的用法

    - 任务成功后**立即下载，转存到你自己的存储**（OSS / CDN / 图片空间），再把你自己的地址用于商品详情页。
    - **不要**把 PixGT 返回的地址直接写进商品页或长期保存的数据库字段。
    - 只要任务仍在保留期内，随时 `GET /tasks/{task_id}` 都能拿到**新的**地址。

    ## 过期后的新地址长什么样

    文件本身（对象路径）**不变**，变的只是 `?` 后面的签名参数（签发时间、有效期、签名值）：

    ```text
    旧：https://<bucket>.oss-cn-guangzhou.aliyuncs.com/1234/output/images/20261127_ab12.png
        ?x-oss-date=20261127T150000Z&x-oss-expires=86400&x-oss-credential=...&x-oss-signature=9f2c...
    新：https://<bucket>.oss-cn-guangzhou.aliyuncs.com/1234/output/images/20261127_ab12.png
        ?x-oss-date=20261128T160000Z&x-oss-expires=86400&x-oss-credential=...&x-oss-signature=41ad...
    ```

    - 服务端按时间窗口缓存签名：同一窗口内反复查询拿到的是**同一个地址**，跨窗口才换新。因此实际剩余有效期一般在 20～24 小时之间，**请以 `url_expires_at` 为准**，不要自行按 24 小时推算。
    - 要求加水印的图片，地址中还会多一个 `x-oss-process` 参数（同样被签名保护）。

    ## 过期后访问会返回什么

    返回 **HTTP 403**（不是 404，也不会跳转），响应体是存储服务的 XML 错误：

    ```xml
    <Error>
      <Code>AccessDenied</Code>
      <Message>Request has expired.</Message>
      <Expires>2026-11-28T15:00:00.000Z</Expires>
      <ServerTime>2026-11-28T15:20:31.000Z</ServerTime>
      <RequestId>6746...</RequestId>
    </Error>
    ```

    ## 标准处理流程

    下载时收到 **403** → 重新 `GET /tasks/{task_id}` 拿新地址 → 再下载。

    ```python
    import requests

    def download_output(base, api_key, task_id, index, path):
        for attempt in range(2):
            task = requests.get(f"{base}/tasks/{task_id}",
                                headers={"Authorization": f"Bearer {api_key}"}, timeout=30).json()
            url = next(o["url"] for o in task["outputs"] if o["index"] == index)
            r = requests.get(url, timeout=120)
            if r.status_code == 403 and attempt == 0:
                continue  # 地址过期：重新查询任务换新地址
            r.raise_for_status()
            with open(path, "wb") as f:
                f.write(r.content)
            return
    ```

    # Webhook

    Webhook 只做一件事：**异步任务进入终态时主动通知你**。它是可选的——不配置也可以用 `GET /tasks/{task_id}` 轮询，结果完全一样。它的价值是：不用写定时轮询、不会因轮询间隔晚拿到结果，批量跑大量 SKU 时也能省掉大量查询请求。

    ## 配置

    - **默认回调地址**：企业管理面板 →「开发者 / API」→ **Webhook 设置**，填写 `https` 回调地址。这里还可以：
      - 查看 / 复制 / 重置**签名密钥**（`whsec_...`，同样有 👁 查看与 📋 复制）；
      - 「发送测试事件」（`webhook.test`）；
      - 查看最近的投递记录，并手动重放。
    - **单个任务覆盖**：创建任务时传 `webhook_url`，优先于默认地址。签名使用同一个签名密钥。
    - 两者都没有配置时不投递。

    ## 事件

    | `type` | 触发时机 |
    | :--- | :--- |
    | `task.succeeded` | 任务全部产出成功 |
    | `task.partially_succeeded` | 任务结束，部分产出失败（失败部分已退点） |
    | `task.failed` | 任务失败（已全额退点） |
    | `webhook.test` | 在管理面板点「发送测试事件」时发出；`data` 为 `{"message": "..."}`，不是任务对象 |

    ## 投递格式

    ```http
    POST https://erp.example.com/pixgt/callback
    Content-Type: application/json
    User-Agent: PixGT-Webhook/1.0
    PixGT-Event-Id: evt_01JDQ8Z3K7M2V9X4R6T1B5N8C0
    PixGT-Signature: t=1764342161,v1=5f8c...e21
    ```

    ```json
    {
      "id": "evt_01JDQ8Z3K7M2V9X4R6T1B5N8C0",
      "object": "event",
      "type": "task.partially_succeeded",
      "created_at": "2026-11-28T15:02:41.000Z",
      "data": { "id": "task_01JDQ8Z3K7M2V9X4R6T1B5N8C0", "object": "task", "status": "partially_succeeded", "...": "与 GET /tasks/{task_id} 的响应完全一致" }
    }
    ```

    ## 签名校验

    ```text
    PixGT-Signature: t=<unix 秒>,v1=<hex>
    v1 = HEX( HMAC_SHA256( key = 完整的签名密钥字符串（含 whsec_ 前缀）, message = "{t}.{原始请求体}" ) )
    ```

    接收方必须：

    1. 使用**原始请求体字节**计算签名（不要先 JSON 解析再序列化，字段顺序和空白会变）；
    2. 使用**常量时间比较**（如 `timingSafeEqual` / `hmac.compare_digest` / `hash_equals`）；
    3. 拒绝 `|当前时间 − t| > 300 秒` 的请求，防止重放；
    4. 按 `PixGT-Event-Id` **去重**（同一事件可能因重试被投递多次）。

    ### 测试向量

    用于在你的单元测试里验证实现是否正确：

    ```text
    密钥:   whsec_dGVzdF9zZWNyZXRfZm9yX2RvY3Nfb25seQ
    t:      1764342161
    请求体: {"id":"evt_01JDQ8Z3K7M2V9X4R6T1B5N8C0","object":"event","type":"webhook.test","created_at":"2026-11-28T15:02:41.000Z","data":{"message":"This is a test event from PixGT Open API."}}
    签名头: t=1764342161,v1=2da0b6011106a10126964289ad9e27e8c65ae0f9fd0212122e38173ae64d818f
    ```

    （测试时把「当前时间」固定为 `t`，否则会因超过 300 秒容差而校验失败。）

    ### Node.js（Express）

    ```js
    const crypto = require('crypto');
    const express = require('express');

    const SECRET = process.env.PIXGT_WEBHOOK_SECRET; // whsec_...

    function verifyPixgtSignature(rawBody, header, secret, toleranceSec = 300) {
      const parts = {};
      for (const kv of String(header || '').split(',')) {
        const i = kv.indexOf('=');
        if (i > 0) parts[kv.slice(0, i).trim()] = kv.slice(i + 1).trim();
      }
      const t = parseInt(parts.t, 10);
      if (!Number.isFinite(t) || !parts.v1) return false;
      if (Math.abs(Math.floor(Date.now() / 1000) - t) > toleranceSec) return false;
      const expected = crypto.createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest('hex');
      const a = Buffer.from(expected, 'hex');
      const b = Buffer.from(parts.v1, 'hex');
      return a.length === b.length && crypto.timingSafeEqual(a, b);
    }

    const app = express();
    // 必须拿到原始请求体：这里用 express.raw，而不是 express.json
    app.post('/pixgt/callback', express.raw({ type: 'application/json' }), (req, res) => {
      if (!verifyPixgtSignature(req.body, req.get('PixGT-Signature'), SECRET)) {
        return res.status(400).send('invalid signature');
      }
      const event = JSON.parse(req.body.toString('utf8'));
      res.status(200).send('ok');           // 先快速返回 2xx
      setImmediate(() => handleEvent(event)); // 再异步处理（按 event.id 去重）
    });
    ```

    ### Python（Flask）

    ```python
    import hashlib
    import hmac
    import os
    import time

    from flask import Flask, request, abort

    SECRET = os.environ["PIXGT_WEBHOOK_SECRET"]  # whsec_...
    app = Flask(__name__)

    def verify_pixgt_signature(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
        try:
            parts = dict(kv.strip().split("=", 1) for kv in (header or "").split(","))
            t, v1 = int(parts["t"]), parts["v1"]
        except (KeyError, ValueError):
            return False
        if abs(int(time.time()) - t) > tolerance:
            return False
        expected = hmac.new(secret.encode("utf-8"), f"{t}.".encode("utf-8") + raw_body, hashlib.sha256).hexdigest()
        return hmac.compare_digest(expected, v1)

    @app.post("/pixgt/callback")
    def pixgt_callback():
        raw = request.get_data()  # 原始字节
        if not verify_pixgt_signature(raw, request.headers.get("PixGT-Signature", ""), SECRET):
            abort(400)
        event = request.get_json(force=True)
        # 按 event["id"] 去重后入队处理
        return "ok", 200
    ```

    ### Java

    ```java
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    import java.nio.charset.StandardCharsets;
    import java.security.MessageDigest;

    public final class PixgtWebhook {
        public static boolean verify(byte[] rawBody, String header, String secret) throws Exception {
            if (header == null) return false;
            String t = null, v1 = null;
            for (String kv : header.split(",")) {
                String[] p = kv.trim().split("=", 2);
                if (p.length != 2) continue;
                if (p[0].equals("t")) t = p[1];
                else if (p[0].equals("v1")) v1 = p[1];
            }
            if (t == null || v1 == null) return false;
            long ts;
            try { ts = Long.parseLong(t); } catch (NumberFormatException e) { return false; }
            if (Math.abs(System.currentTimeMillis() / 1000L - ts) > 300) return false;

            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            mac.update((t + ".").getBytes(StandardCharsets.UTF_8));
            byte[] digest = mac.doFinal(rawBody);
            StringBuilder hex = new StringBuilder();
            for (byte b : digest) hex.append(String.format("%02x", b));
            return MessageDigest.isEqual(
                hex.toString().getBytes(StandardCharsets.UTF_8),
                v1.toLowerCase().getBytes(StandardCharsets.UTF_8));
        }
    }
    ```

    Spring Boot 中请用 `@RequestBody byte[] body` 获取原始请求体。

    ### PHP

    ```php
    <?php
    function pixgt_verify_signature(string $rawBody, string $header, string $secret, int $tolerance = 300): bool {
        $parts = [];
        foreach (explode(',', $header) as $kv) {
            $p = explode('=', trim($kv), 2);
            if (count($p) === 2) { $parts[$p[0]] = $p[1]; }
        }
        if (!isset($parts['t'], $parts['v1']) || !ctype_digit($parts['t'])) return false;
        if (abs(time() - (int)$parts['t']) > $tolerance) return false;
        $expected = hash_hmac('sha256', $parts['t'] . '.' . $rawBody, $secret);
        return hash_equals($expected, strtolower($parts['v1']));
    }

    $raw = file_get_contents('php://input');            // 原始请求体
    $sig = $_SERVER['HTTP_PIXGT_SIGNATURE'] ?? '';
    if (!pixgt_verify_signature($raw, $sig, getenv('PIXGT_WEBHOOK_SECRET'))) {
        http_response_code(400);
        exit('invalid signature');
    }
    $event = json_decode($raw, true);
    // 按 $event['id'] 去重后处理
    http_response_code(200);
    echo 'ok';
    ```

    ## 投递与重试

    - 你的接口返回任意 **2xx** 即视为投递成功；**超时 10 秒**。请先返回 2xx，再异步处理业务。
    - 失败（非 2xx、超时、连接错误）后按 **1 分钟 / 5 分钟 / 30 分钟 / 2 小时 / 6 小时 / 12 小时 / 24 小时** 退避重试，**含首次共最多 8 次**。
    - 测试事件 `webhook.test` 只投递一次，不重试。
    - 管理面板可查看投递记录并手动重放。
    - Webhook 是**通知**而不是唯一通道：你随时可以用 `GET /tasks/{task_id}` 兜底查询（轮询间隔建议 ≥ 5 秒）。

    # 幂等

    网络超时后你不知道请求是否已经成功——这时**带同一个 `Idempotency-Key` 重试**，PixGT 保证不会重复创建任务、不会重复扣点。

    ```http
    POST /tasks
    Authorization: Bearer pgk_live_...
    Content-Type: application/json
    Idempotency-Key: sku-10086-suite-v1
    ```

    ## 规则

    | 情况 | 结果 |
    | :--- | :--- |
    | 首次请求 | 正常创建，返回 `202` |
    | 24 小时内，同一把 Key + 同一个 `Idempotency-Key` + **相同请求体** | 返回首次创建的任务（`202`），响应头 `Idempotent-Replayed: true`，**不重复扣点** |
    | 同一个 `Idempotency-Key` + **不同请求体** | `409 idempotency_conflict` |
    | 首次请求仍在处理中时又收到同一个 `Idempotency-Key` | `409 idempotency_conflict`，稍后再重试或直接查询任务 |

    - 适用接口：`POST /tasks`（创建任务）。`POST /tasks/estimate` 不扣点、无需幂等。
    - `Idempotency-Key` 为 1–64 个字符，否则返回 `400 invalid_parameter`（`param: Idempotency-Key`）。
    - 按 **API Key** 隔离：不同 Key 使用相同的值互不影响。
    - 「相同请求体」按 JSON 语义比较，与字段书写顺序无关。

    ## 怎么生成幂等键

    用**你自己的业务主键**拼出来，而不是每次随机生成——这样进程重启后重试也能命中：

    ```text
    sku-10086-suite-v1          # SKU + 任务用途 + 版本
    order-20261128-0042-video   # 订单号 + 类型
    ```

    需要对同一个 SKU **故意再生成一次**时，换一个新的键（如 `-v2`）。

    ## 推荐的重试策略

    | 响应 | 是否重试 |
    | :--- | :--- |
    | 网络错误 / 超时 / `500` / `503` | ✅ 指数退避重试，**带同一个 `Idempotency-Key`** |
    | `429` | ✅ 按 `Retry-After` 等待后重试 |
    | `409 idempotency_conflict` | 先 `GET /tasks?client_reference_id=...` 查询，确认是否已创建 |
    | 其他 `4xx` | ❌ 修正请求后再发（使用新的键） |

    # 限流与并发

    ## 请求频率（按 API Key）

    | 类别 | 接口 | 默认上限 |
    | :--- | :--- | :--- |
    | 写接口 | `POST /tasks`、`POST /tasks/estimate`、`POST /assets` | **60 次 / 分钟** |
    | 读接口 | `GET /tasks`、`GET /tasks/{task_id}`、`GET /account`、`GET /account/balance` 等 | **600 次 / 分钟** |
    | 无效 Key 尝试（按来源 IP） | 任意接口 | 30 次 / 分钟 |

    - 超限返回 `429`，`error.code = rate_limit_exceeded`，并带 `Retry-After` 响应头（建议等待的秒数）。请按 `Retry-After` 等待后再试。
    - 当前 Key 的上限可通过 `GET /account` 的 `limits.requests_per_minute` 查询。
    - 轮询任务请保持 **≥ 5 秒**间隔；大批量任务推荐使用 [Webhook](#description/webhook)，可大幅减少查询请求。

    ## 并发任务数（按企业）

    同一企业**进行中**（`queued` / `processing`）的 API 任务数有上限，按企业套餐：

    | 套餐 | 同时进行中的任务上限 |
    | :--- | :---: |
    | 启航版（starter） | 10 |
    | 专业版（pro） | 15 |
    | 旗舰版（flagship） | 20 |
    | 定制版（custom） | 30（可单独调高） |

    - API 任务与成员在网页上的任务**分别计数**，API 批处理不会挤占员工的日常生成。
    - 超出返回 `429`，`error.code = concurrency_limit_exceeded`：等待部分任务完成后再提交。
    - 当前上限见 `GET /account` 的 `limits.concurrent_tasks`。

    ## 批量提交建议

    1. 在你的系统里维护一个**并发不超过上限**的提交队列；
    2. 每个任务带 `Idempotency-Key` 与 `client_reference_id`；
    3. 收到 `429` 时按 `Retry-After`（或指数退避）重试，不要立即重发；
    4. 用 Webhook 接收结果，任务完成后再从队列补位。

    # 错误码

    ## 统一错误体

    所有错误都返回同一结构，并带 `X-Request-Id` 响应头：

    ```json
    {
      "error": {
        "type": "invalid_request_error",
        "code": "invalid_parameter",
        "message": "modules 至少需要包含 1 个模块",
        "param": "input.modules",
        "request_id": "req_01JDQ8Z3K7M2V9X4R6T1B5N8C0"
      }
    }
    ```

    | 字段 | 说明 |
    | :--- | :--- |
    | `type` | 错误大类 |
    | `code` | **稳定的错误码，程序判断只看它** |
    | `message` | 可读说明，语言跟随 `Accept-Language`（`zh` / `en`，国内默认中文）；措辞可能调整，不要用于程序判断 |
    | `param` | 出错的字段路径（如 `input.images[1].url`），仅参数类错误返回 |
    | `request_id` | 请求唯一 ID，联系技术支持时请提供 |

    ## 错误码表

    | HTTP | `type` | `code` | 说明 | 可重试 |
    | :---: | :--- | :--- | :--- | :---: |
    | 400 | `invalid_request_error` | `invalid_parameter` | 参数校验失败（含未知字段），见 `param` | |
    | 400 | `invalid_request_error` | `invalid_image_url` | 图片地址无法下载、过大或格式不支持 | |
    | 400 | `invalid_request_error` | `unsupported_task_type` | `type` 不存在或未对本企业开放 | |
    | 400 | `invalid_request_error` | `model_unavailable` | 模型不存在或已下架，见 `GET /models` | |
    | 400 | `content_policy_error` | `content_policy_violation` | 提示词或输入图未通过安全审核 | |
    | 401 | `authentication_error` | `missing_api_key` | 未携带 `Authorization` 头 | |
    | 401 | `authentication_error` | `invalid_api_key` | Key 无效或已删除 | |
    | 401 | `authentication_error` | `api_key_expired` | Key 已过期 | |
    | 402 | `billing_error` | `insufficient_balance` | 企业共享算力（点）不足 | |
    | 402 | `billing_error` | `key_budget_exceeded` | 当前 Key 的月度预算已用尽 | |
    | 403 | `permission_error` | `insufficient_scope` | Key 缺少该接口所需的 Scope | |
    | 403 | `permission_error` | `enterprise_expired` | 企业套餐已到期（只读封存期），续费后可继续生成 | |
    | 403 | `permission_error` | `api_access_disabled` | 未开通 API，或账号被平台限制 | |
    | 404 | `invalid_request_error` | `resource_not_found` | 接口、任务或素材不存在，或不属于本企业 | |
    | 405 | `invalid_request_error` | `method_not_allowed` | HTTP 方法不对 | |
    | 409 | `invalid_request_error` | `idempotency_conflict` | 幂等键已用于不同请求，或同键请求仍在处理中 | |
    | 413 | `invalid_request_error` | `file_too_large` | 上传文件超过 20MB | |
    | 415 | `invalid_request_error` | `unsupported_media_type` | 请求体格式不对：创建任务须 `application/json`，上传须 `multipart/form-data` | |
    | 429 | `rate_limit_error` | `rate_limit_exceeded` | 请求过于频繁，按 `Retry-After` 等待 | ✅ |
    | 429 | `rate_limit_error` | `concurrency_limit_exceeded` | 进行中的任务数已达上限 | ✅ |
    | 500 | `api_error` | `internal_error` | 服务端异常 | ✅ |
    | 503 | `api_error` | `service_unavailable` | 维护中或上游暂不可用 | ✅ |

    > 规范中的 `api_key_revoked` 为预留错误码，当前已删除的 Key 统一返回 `invalid_api_key`。

    ## 任务内错误

    已创建的任务在生成过程中失败时，不会以 HTTP 错误返回，而是体现在任务对象的 `error` 与 `outputs[].error` 中，见 [任务与状态](#description/任务与状态) 的「任务内失败原因」。

    ## 处理建议

    - 以 `code` 分支处理，`message` 只用于展示或记录日志。
    - 记录每次请求的 `X-Request-Id`，报障时提供即可快速定位。
    - 可重试的错误请使用指数退避，创建任务时带同一个 `Idempotency-Key`（见 [幂等](#description/幂等)）。

    # 更新日志

    ## 1.0.0-draft（2026-11-28）

    首个公开草案版本。

    - 统一异步任务接口：`POST /tasks`、`GET /tasks/{task_id}`、`GET /tasks`，支持三类任务：
      - `product_suite` 商品套图
      - `image_generation` 自由生图
      - `video_generation` 生视频
    - 价格预估 `POST /tasks/estimate`（不扣点）。
    - 素材上传 `POST /assets`（30 天自动清理）。
    - 能力发现 `GET /models`、`GET /options/product-suite`。
    - 账户与额度 `GET /account`、`GET /account/balance`。
    - 任务终态 Webhook（`task.succeeded` / `task.partially_succeeded` / `task.failed`），HMAC-SHA256 签名。
    - `Idempotency-Key` 幂等、按 Key 限流、按企业并发上限。
    - 统一尺寸对象 `size`（平台预设 / 精确像素 / 档位 + 比例）与 `watermark` 水印开关。

    ## 兼容性约定

    - 在 `v1` 内只做**向后兼容**的变更：新增接口、新增可选字段、新增枚举取值（如新的任务 `type`、错误码、事件类型）。请让你的代码**容忍未知字段与未知枚举值**。
    - 不兼容的变更会发布新的主版本路径（如 `/open/v2`），并提前公告。
  contact:
    name: PixGT 开发者支持
    url: https://docs.pixgt.cn
servers:
  - url: https://tapi.pixgt.cn/open/v1
    description: 国内预览（沙箱，使用 pgk_test_ Key）
  - url: https://api.pixgt.cn/open/v1
    description: 国内正式（使用 pgk_live_ Key）
security:
  - bearerAuth: []
tags:
  - name: Tasks
    description: 统一异步生成任务（商品套图 / 自由生图 / 生视频）
    x-displayName: 任务
  - name: Assets
    description: 输入素材上传
    x-displayName: 素材
  - name: Catalog
    description: 模型、能力与选项发现
    x-displayName: 能力发现
  - name: Account
    description: 企业账户、额度与当前 Key 信息
    x-displayName: 账户
paths:
  /assets:
    post:
      tags:
        - Assets
      operationId: uploadAsset
      summary: 上传图片素材
      description: 需要 scope `assets:write`。素材 30 天后自动清理。
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - file
              properties:
                file:
                  type: string
                  format: binary
                  description: png / jpg / jpeg / webp，≤ 20MB
                purpose:
                  type: string
                  enum:
                    - input
                  default: input
      responses:
        "201":
          description: 上传成功
          headers:
            X-Request-Id:
              $ref: "#/components/headers/XRequestId"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Asset"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "413":
          $ref: "#/components/responses/PayloadTooLarge"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /tasks:
    post:
      tags:
        - Tasks
      operationId: createTask
      summary: 创建生成任务
      description: |
        需要 scope `tasks:write`。创建即按预估预扣点数，失败部分自动退点。
        立即返回 `202`，通过 `GET /tasks/{task_id}` 轮询或 Webhook 获取结果。
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
        - $ref: "#/components/parameters/AcceptLanguage"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateTaskRequest"
            examples:
              productSuite:
                summary: 商品套图
                value:
                  type: product_suite
                  input:
                    images:
                      - asset_id: asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0
                    product_description: 便携式榨汁杯，350ml，USB-C 充电
                    platform: taobao
                    language: zh
                    modules:
                      - main_image
                      - selling_points
                      - scene
                      - spec
                    size:
                      preset_id: tb_main
                    model: auto
                    module_options:
                      spec:
                        product_size:
                          length: 8
                          width: 8
                          height: 22
                          unit: cm
                      scene:
                        hint: 户外露营野餐桌上
                  webhook_url: https://erp.example.com/pixgt/callback
                  client_reference_id: SKU-10086
              imageGeneration:
                summary: 自由生图
                value:
                  type: image_generation
                  input:
                    prompt: 把这款香水放在大理石台面上，清晨柔光
                    images:
                      - url: https://img.example.com/perfume.jpg
                    n: 2
                    size:
                      width: 1200
                      height: 1600
              videoGeneration:
                summary: 生视频
                value:
                  type: video_generation
                  input:
                    prompt: 镜头缓慢环绕榨汁杯，水果落入杯中溅起水花
                    mode: image_to_video
                    images:
                      - asset_id: asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0
                    model: seedance2.0-fast
                    duration: 5
                    aspect_ratio: 9:16
                    resolution: 720p
      responses:
        "202":
          description: 任务已受理
          headers:
            X-Request-Id:
              $ref: "#/components/headers/XRequestId"
            Idempotent-Replayed:
              description: 为 `true` 时表示幂等重放，返回的是首次创建结果
              schema:
                type: boolean
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Task"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          $ref: "#/components/responses/PaymentRequired"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          $ref: "#/components/responses/Conflict"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Tasks
      operationId: listTasks
      summary: 任务列表
      description: 需要 scope `tasks:read`。仅返回当前企业通过 Open API 创建的任务，按创建时间倒序。
      parameters:
        - name: type
          in: query
          schema:
            $ref: "#/components/schemas/TaskType"
        - name: status
          in: query
          schema:
            $ref: "#/components/schemas/TaskStatus"
        - name: client_reference_id
          in: query
          schema:
            type: string
            maxLength: 64
        - name: created_after
          in: query
          schema:
            type: string
            format: date-time
        - name: created_before
          in: query
          schema:
            type: string
            format: date-time
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
        - name: starting_after
          in: query
          description: 游标，传上一页最后一条的 `id`
          schema:
            type: string
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required:
                  - object
                  - data
                  - has_more
                properties:
                  object:
                    type: string
                    const: list
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Task"
                  has_more:
                    type: boolean
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /tasks/estimate:
    post:
      tags:
        - Tasks
      operationId: estimateTask
      summary: 价格预估
      description: 需要 scope `tasks:write`。入参与创建任务一致，不扣点、不建任务；计价函数与实际扣费共用。
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateTaskRequest"
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Estimate"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /tasks/{task_id}:
    get:
      tags:
        - Tasks
      operationId: getTask
      summary: 查询任务
      description: 需要 scope `tasks:read`。响应与 Webhook 事件中的 `data` 完全同构。建议轮询间隔 ≥ 5 秒。
      parameters:
        - name: task_id
          in: path
          required: true
          schema:
            type: string
            pattern: ^task_[0-9A-HJKMNP-TV-Z]{26}$
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Task"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
  /models:
    get:
      tags:
        - Catalog
      operationId: listModels
      summary: 可用模型、能力与单价
      description: 数值由服务端实时生成；已下架模型不出现。国内版仅返回流光系别名与国产模型 ID。
      parameters:
        - name: type
          in: query
          schema:
            type: string
            enum:
              - image
              - video
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                required:
                  - object
                  - data
                properties:
                  object:
                    type: string
                    const: list
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Model"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /options/product-suite:
    get:
      tags:
        - Catalog
      operationId: getProductSuiteOptions
      summary: 商品套图可选项
      description: 模块、发布平台、文字语言、节日主题、平台尺寸预设。与站内选项同源。
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ProductSuiteOptions"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /account:
    get:
      tags:
        - Account
      operationId: getAccount
      summary: 企业与当前 Key 信息
      description: 需要 scope `account:read`。
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Account"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /account/balance:
    get:
      tags:
        - Account
      operationId: getBalance
      summary: 共享算力余额
      description: 需要 scope `account:read`。
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Balance"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
webhooks:
  taskEvent:
    post:
      operationId: onTaskEvent
      summary: 任务终态事件
      description: |
        事件类型：`task.succeeded` / `task.partially_succeeded` / `task.failed`。
        签名：`PixGT-Signature: t=<unix秒>,v1=<hex>`，`v1 = HMAC_SHA256(whsec_密钥, "{t}.{原始请求体}")`。
        接收方应常量时间比较签名、拒绝 |now − t| > 300s 的请求，并按 `PixGT-Event-Id` 去重。
        2xx 视为成功；失败按 1m/5m/30m/2h/6h/12h/24h 退避，最多 8 次。
      parameters:
        - name: PixGT-Event-Id
          in: header
          required: true
          schema:
            type: string
        - name: PixGT-Signature
          in: header
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/WebhookEvent"
      responses:
        "200":
          description: 接收成功
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: pgk_live_<12 hex>_<43 chars>
      description: 企业所有者 / 管理员在企业管理面板 →「开发者 / API」签发，可随时查看与复制。沙箱使用 `pgk_test_` Key，正式使用 `pgk_live_` Key。请仅在服务端保存，泄露后立即删除。
  headers:
    XRequestId:
      description: 请求唯一 ID，报障时提供
      schema:
        type: string
    RetryAfter:
      description: 建议等待秒数
      schema:
        type: integer
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: ≤64 字符，24 小时内同 Key 同请求体返回首次结果，不重复扣点；不同请求体返回 409。
      schema:
        type: string
        maxLength: 64
    AcceptLanguage:
      name: Accept-Language
      in: header
      required: false
      description: 错误 `message` 语言，`zh` 或 `en`
      schema:
        type: string
        enum:
          - zh
          - en
  responses:
    BadRequest:
      description: 参数错误 / 内容审核未通过 / 模型不可用
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    Unauthorized:
      description: 鉴权失败
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    PaymentRequired:
      description: 余额不足或 Key 月预算用尽
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    Forbidden:
      description: Scope 不足 / 企业到期只读 / 未开通 API
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    NotFound:
      description: 资源不存在或不属于本企业
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    Conflict:
      description: 幂等键冲突
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    UnsupportedMediaType:
      description: 请求体格式不对（创建任务须 application/json，上传须 multipart/form-data）
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    PayloadTooLarge:
      description: 文件过大
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    TooManyRequests:
      description: 限流或并发超限
      headers:
        Retry-After:
          $ref: "#/components/headers/RetryAfter"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    InternalError:
      description: 服务端异常，可重试
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
  schemas:
    TaskType:
      type: string
      enum:
        - product_suite
        - image_generation
        - video_generation
      description: 后续版本会新增取值（如 try_on、background_replace），客户端应容忍未知值。
    TaskStatus:
      type: string
      enum:
        - queued
        - processing
        - succeeded
        - partially_succeeded
        - failed
    ImageInput:
      description: 二选一：`asset_id`（推荐）或公网 `https` 地址（服务端下载转存，拒绝内网地址）
      oneOf:
        - type: object
          required:
            - asset_id
          additionalProperties: false
          properties:
            asset_id:
              type: string
              pattern: ^asset_[0-9A-HJKMNP-TV-Z]{26}$
        - type: object
          required:
            - url
          additionalProperties: false
          properties:
            url:
              type: string
              format: uri
              pattern: ^https://
    Size:
      description: 三种写法三选一，避免分辨率与比例各传各的拼出矛盾组合。
      oneOf:
        - type: object
          title: Preset
          required:
            - preset_id
          additionalProperties: false
          properties:
            preset_id:
              type: string
              description: 平台尺寸预设 ID，见 `/options/product-suite`
        - type: object
          title: Exact
          required:
            - width
            - height
          additionalProperties: false
          properties:
            width:
              type: integer
              minimum: 64
              maximum: 4096
              description: 长宽比不超过 3:1
            height:
              type: integer
              minimum: 64
              maximum: 4096
        - type: object
          title: TierRatio
          required:
            - tier
          additionalProperties: false
          properties:
            tier:
              type: string
              enum:
                - auto
                - 1k
                - 2k
                - 4k
            aspect_ratio:
              type: string
              examples:
                - 1:1
                - 3:4
                - 16:9
    ProductSuiteModule:
      type: string
      enum:
        - main_image
        - selling_points
        - scene
        - detail
        - spec
        - white_background
        - features
        - comparison
    ProductSuiteInput:
      type: object
      required:
        - images
        - modules
      additionalProperties: false
      properties:
        images:
          type: array
          minItems: 1
          maxItems: 6
          items:
            $ref: "#/components/schemas/ImageInput"
        product_description:
          type: string
          maxLength: 2000
        platform:
          type: string
          description: 发布平台，取值见 `/options/product-suite`
          examples:
            - amazon
            - taobao
            - pinduoduo
            - douyin
            - jd
            - temu
            - shopee
            - tiktok_shop
        language:
          type: string
          description: 图中文字语言（ISO 639-1）
          examples:
            - zh
            - en
            - ja
        modules:
          type: array
          minItems: 1
          uniqueItems: true
          items:
            $ref: "#/components/schemas/ProductSuiteModule"
        size:
          $ref: "#/components/schemas/Size"
        model:
          type: string
          default: auto
          examples: &a1
            - auto
            - seedream5.0
            - lumi-g2
            - lumi-npro
        module_options:
          type: object
          additionalProperties: false
          properties:
            spec:
              type: object
              additionalProperties: false
              properties:
                product_size:
                  type: object
                  additionalProperties: false
                  properties:
                    length:
                      type: number
                      exclusiveMinimum: 0
                    width:
                      type: number
                      exclusiveMinimum: 0
                    height:
                      type: number
                      exclusiveMinimum: 0
                    unit:
                      type: string
                      enum:
                        - cm
                        - mm
                        - in
                      default: cm
            scene:
              type: object
              additionalProperties: false
              properties:
                hint:
                  type: string
                  maxLength: 60
            comparison:
              type: object
              additionalProperties: false
              properties:
                mode:
                  type: string
                  enum:
                    - ordinary
                    - before_after
                    - pain_point
        festival:
          type: object
          additionalProperties: false
          properties:
            theme:
              type: string
              description: 节日主题 ID，见 `/options/product-suite` 的 festival_themes；`none` 或不传表示不加节日氛围
            custom:
              type: object
              description: 仅 theme=custom 时可传
              additionalProperties: false
              properties:
                name:
                  type: string
                  maxLength: 24
                prompt:
                  type: string
                  maxLength: 200
                palette_id:
                  type: string
                  description: 见 `/options/product-suite` 的 festival_palettes
    ImageGenerationInput:
      type: object
      required:
        - prompt
      additionalProperties: false
      properties:
        prompt:
          type: string
          minLength: 1
          maxLength: 4000
        images:
          type: array
          maxItems: 10
          description: 参考图
          items:
            $ref: "#/components/schemas/ImageInput"
        n:
          type: integer
          minimum: 1
          maximum: 4
          default: 1
        size:
          $ref: "#/components/schemas/Size"
        model:
          type: string
          default: auto
          examples: *a1
    VideoGenerationInput:
      type: object
      required:
        - prompt
        - model
      additionalProperties: false
      properties:
        prompt:
          type: string
          minLength: 1
          maxLength: 4000
        mode:
          type: string
          enum:
            - reference
            - image_to_video
            - first_last_frame
          default: reference
        images:
          type: array
          maxItems: 9
          description: reference 模式 0~9 张；image_to_video 恰好 1 张（首帧）；first_last_frame 恰好 2 张（首帧、尾帧）
          items:
            $ref: "#/components/schemas/ImageInput"
        model:
          type: string
          description: 取值见 `/models?type=video`
        duration:
          type: integer
          description: 秒，白名单见模型能力
        aspect_ratio:
          type: string
          examples:
            - 16:9
            - 9:16
            - 1:1
        resolution:
          type: string
          examples:
            - 480p
            - 720p
            - 1080p
            - 2k
        enhance:
          type: boolean
          default: false
          description: 自动超清增强，额外计费；1080p / 2k 不可用；不能与 watermark 同时开启
    CreateTaskRequest:
      description: 按 `type` 区分的任务请求（discriminated union）
      oneOf:
        - $ref: "#/components/schemas/CreateProductSuiteTask"
        - $ref: "#/components/schemas/CreateImageGenerationTask"
        - $ref: "#/components/schemas/CreateVideoGenerationTask"
      discriminator:
        propertyName: type
        mapping:
          product_suite: "#/components/schemas/CreateProductSuiteTask"
          image_generation: "#/components/schemas/CreateImageGenerationTask"
          video_generation: "#/components/schemas/CreateVideoGenerationTask"
    CreateProductSuiteTask:
      allOf:
        - $ref: "#/components/schemas/TaskRequestCommon"
        - type: object
          required:
            - type
            - input
          properties:
            type:
              type: string
              const: product_suite
            input:
              $ref: "#/components/schemas/ProductSuiteInput"
    CreateImageGenerationTask:
      allOf:
        - $ref: "#/components/schemas/TaskRequestCommon"
        - type: object
          required:
            - type
            - input
          properties:
            type:
              type: string
              const: image_generation
            input:
              $ref: "#/components/schemas/ImageGenerationInput"
    CreateVideoGenerationTask:
      allOf:
        - $ref: "#/components/schemas/TaskRequestCommon"
        - type: object
          required:
            - type
            - input
          properties:
            type:
              type: string
              const: video_generation
            input:
              $ref: "#/components/schemas/VideoGenerationInput"
    TaskRequestCommon:
      type: object
      properties:
        watermark:
          type: boolean
          default: false
          description: 默认无水印；`true` 时输出带平台水印，不额外收费。视频需等待水印烧录完成才进入终态；国际区域暂不支持视频水印。
        webhook_url:
          type: string
          format: uri
          pattern: ^https://
          maxLength: 512
        client_reference_id:
          type: string
          maxLength: 64
        metadata:
          type: object
          maxProperties: 16
          additionalProperties:
            type: string
            maxLength: 256
    Cost:
      type: object
      required:
        - points_estimated
        - points_charged
        - points_refunded
      properties:
        points_estimated:
          type: integer
        points_charged:
          type: integer
          description: 创建时实际预扣
        points_refunded:
          type: integer
          description: 失败部分已退还；净消耗 = charged − refunded
    TaskError:
      type: object
      required:
        - code
        - message
      properties:
        code:
          type: string
          examples:
            - content_policy_violation
            - generation_failed
            - timeout
            - watermark_failed
            - internal_error
        message:
          type: string
        retryable:
          type: boolean
    TaskOutput:
      type: object
      required:
        - index
        - status
      properties:
        index:
          type: integer
        module:
          description: 仅 product_suite
          $ref: "#/components/schemas/ProductSuiteModule"
        status:
          type: string
          enum:
            - pending
            - succeeded
            - failed
        url:
          type: string
          format: uri
          description: 签名地址，默认 24 小时有效
        url_expires_at:
          type: string
          format: date-time
        cover_url:
          type: string
          format: uri
          description: 仅视频，首帧封面
        width:
          type: integer
        height:
          type: integer
        duration:
          type: number
          description: 仅视频，秒
        format:
          type: string
          examples:
            - png
            - jpg
            - mp4
        model:
          type: string
        error:
          $ref: "#/components/schemas/TaskError"
    Task:
      type: object
      required:
        - id
        - object
        - type
        - status
        - created_at
        - cost
      properties:
        id:
          type: string
          examples:
            - task_01JDQ8Z3K7M2V9X4R6T1B5N8C0
        object:
          type: string
          const: task
        type:
          $ref: "#/components/schemas/TaskType"
        status:
          $ref: "#/components/schemas/TaskStatus"
        progress:
          type: object
          properties:
            total:
              type: integer
            succeeded:
              type: integer
            failed:
              type: integer
            pending:
              type: integer
        input:
          type: object
          description: 规范化后的入参回显
        outputs:
          type: array
          items:
            $ref: "#/components/schemas/TaskOutput"
        cost:
          $ref: "#/components/schemas/Cost"
        error:
          oneOf:
            - $ref: "#/components/schemas/TaskError"
            - type: "null"
        created_at:
          type: string
          format: date-time
        completed_at:
          type:
            - string
            - "null"
          format: date-time
        client_reference_id:
          type:
            - string
            - "null"
        metadata:
          type: object
          additionalProperties:
            type: string
        watermark:
          type: boolean
          description: 本任务是否要求加水印
    Estimate:
      type: object
      required:
        - object
        - points
        - affordable
      properties:
        object:
          type: string
          const: estimate
        type:
          $ref: "#/components/schemas/TaskType"
        points:
          type: integer
        balance:
          type: integer
          description: 当前可用点数
        breakdown:
          type: array
          items:
            type: object
            properties:
              item:
                type: string
              points:
                type: integer
        balance_after:
          type: integer
        affordable:
          type: boolean
    Asset:
      type: object
      required:
        - id
        - object
      properties:
        id:
          type: string
          examples:
            - asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0
        object:
          type: string
          const: asset
        mime_type:
          type: string
        width:
          type: integer
        height:
          type: integer
        bytes:
          type: integer
        expires_at:
          type: string
          format: date-time
    Model:
      type: object
      required:
        - id
        - type
      properties:
        id:
          type: string
        object:
          type: string
          const: model
        type:
          type: string
          enum:
            - image
            - video
        display_name:
          type: object
          properties:
            zh:
              type: string
            en:
              type: string
        supported_task_types:
          type: array
          items:
            $ref: "#/components/schemas/TaskType"
        capabilities:
          type: object
          description: 图片：max_input_images / max_n / tiers / exact_size；视频：modes / durations / aspect_ratios / resolutions / enhance
          additionalProperties: true
        pricing:
          type: object
          description: 图片按张（按档位），视频按秒（按分辨率）
          additionalProperties: true
    LabeledOption:
      type: object
      required:
        - id
        - label
      properties:
        id:
          type: string
        label:
          type: object
          properties:
            zh:
              type: string
            en:
              type: string
    ProductSuiteOptions:
      type: object
      properties:
        modules:
          type: array
          items:
            $ref: "#/components/schemas/LabeledOption"
        platforms:
          type: array
          items:
            $ref: "#/components/schemas/LabeledOption"
        languages:
          type: array
          items:
            $ref: "#/components/schemas/LabeledOption"
        festival_themes:
          type: array
          items:
            $ref: "#/components/schemas/LabeledOption"
        festival_palettes:
          type: array
          items:
            $ref: "#/components/schemas/LabeledOption"
        size_presets:
          type: object
          description: 按平台 ID 分组
          additionalProperties:
            type: array
            items:
              allOf:
                - $ref: "#/components/schemas/LabeledOption"
                - type: object
                  properties:
                    module_group:
                      type: string
                    width:
                      type: integer
                    height:
                      type: integer
                    aspect_ratio:
                      type: string
    Account:
      type: object
      properties:
        object:
          type: string
          const: account
        owner_type:
          type: string
          enum:
            - enterprise
            - user
        edition:
          type: string
          enum:
            - cn
            - global
        user:
          type: object
          description: 仅个人 Key
          properties:
            id:
              type: integer
        enterprise:
          type: object
          properties:
            id:
              type: integer
            name:
              type: string
            plan:
              type: string
              enum:
                - starter
                - pro
                - flagship
                - custom
            status:
              type: string
            expires_at:
              type: string
              format: date-time
            read_only:
              type: boolean
        limits:
          type: object
          properties:
            concurrent_tasks:
              type: integer
              description: 仅企业 Key，同时进行中的任务上限
            requests_per_minute:
              type: object
              properties:
                write:
                  type: integer
                read:
                  type: integer
        api_key:
          type: object
          properties:
            id:
              type: string
            name:
              type: string
            prefix:
              type: string
            monthly_budget:
              type:
                - integer
                - "null"
            scopes:
              type: array
              items:
                type: string
                enum:
                  - tasks:write
                  - tasks:read
                  - assets:write
                  - account:read
            expires_at:
              type:
                - string
                - "null"
              format: date-time
    Balance:
      type: object
      properties:
        object:
          type: string
          const: balance
        points:
          type: object
          properties:
            total:
              type: integer
            remaining:
              type: integer
            used:
              type: integer
            frozen:
              type: integer
              description: 到期封存中的点数，续费可解冻（仅企业）
        api_key_budget:
          type:
            - object
            - "null"
          properties:
            monthly_limit:
              type: integer
            used_this_month:
              type: integer
            resets_at:
              type: string
              format: date-time
    WebhookEvent:
      type: object
      required:
        - id
        - type
        - created_at
        - data
      properties:
        id:
          type: string
          examples:
            - evt_01JDQ8Z3K7M2V9X4R6T1B5N8C0
        object:
          type: string
          const: event
        type:
          type: string
          enum:
            - task.succeeded
            - task.partially_succeeded
            - task.failed
            - webhook.test
        created_at:
          type: string
          format: date-time
        data:
          description: task.* 事件为任务对象（与 GET /tasks/{task_id} 同构）；webhook.test 为 { message }
          oneOf:
            - $ref: "#/components/schemas/Task"
            - type: object
              required:
                - message
              properties:
                message:
                  type: string
    ErrorResponse:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          required:
            - type
            - code
            - message
          properties:
            type:
              type: string
              enum:
                - invalid_request_error
                - content_policy_error
                - authentication_error
                - billing_error
                - permission_error
                - rate_limit_error
                - api_error
            code:
              type: string
              enum:
                - invalid_parameter
                - invalid_image_url
                - unsupported_task_type
                - model_unavailable
                - content_policy_violation
                - missing_api_key
                - invalid_api_key
                - api_key_expired
                - insufficient_balance
                - key_budget_exceeded
                - insufficient_scope
                - enterprise_expired
                - api_access_disabled
                - resource_not_found
                - method_not_allowed
                - idempotency_conflict
                - file_too_large
                - unsupported_media_type
                - rate_limit_exceeded
                - concurrency_limit_exceeded
                - internal_error
                - service_unavailable
            message:
              type: string
            param:
              type: string
              examples:
                - input.modules
            request_id:
              type: string
externalDocs:
  description: 给 AI 编程工具的全文 Markdown（llms-full.txt）
  url: https://docs.pixgt.cn/llms-full.txt
x-tagGroups:
  - name: 接口参考
    tags:
      - Tasks
      - Assets
      - Catalog
      - Account
