openapi: 3.1.0
info:
  title: PixGT Open API
  version: 1.0.0-draft
  summary: Enterprise API for e-commerce product suites, image generation and video generation.
  description: |-
    # Overview

    The PixGT Open API lets your ERP, PIM, listing tool or in-house agent call PixGT's e-commerce visual generation directly: **product suites, image generation and video generation**.

    - **An enterprise feature**: API keys are issued by enterprise owners / admins in the enterprise admin panel. Calls consume the enterprise's **shared points** at the same price as the web app.
    - **One asynchronous task model**: every capability is created with `POST /tasks`; results come from polling `GET /tasks/{task_id}` or from webhooks.
    - **Safe retries**: task creation supports `Idempotency-Key`, so network retries never double-charge.
    - **Discoverable capabilities**: models, product suite modules, marketplaces and platform size presets are all available from the API, so nothing needs to be hard-coded.

    ## Environments

    | Environment | Base URL | Key prefix |
    | :--- | :--- | :--- |
    | Preview (sandbox) | `https://tapi.pixgt.com/open/v1` | `pgk_test_` |
    | Production | `https://api.pixgt.com/open/v1` | `pgk_live_` |

    - Integrate against the **sandbox** first; the interactive console on this site defaults to it.
    - The global edition (pixgt.com) and the China edition are separate systems; keys do not work across them.

    ## Conventions

    - Requests and responses use `application/json; charset=utf-8` (asset uploads use `multipart/form-data`); all fields are `snake_case`.
    - Timestamps are ISO 8601 UTC, e.g. `2026-11-28T15:00:00Z`.
    - Every response includes `X-Request-Id`; share it with support to locate a request quickly.
    - Billing is in **points**.

    ## For AI coding tools

    Give any of these links to Cursor, Claude Code or similar tools so they understand the whole API and can generate integration code:

    - [llms.txt](https://docs.pixgt.com/llms.txt): documentation index
    - [llms-full.txt](https://docs.pixgt.com/llms-full.txt): all guides plus every endpoint as Markdown
    - [openapi.yaml](https://docs.pixgt.com/openapi.yaml) / [openapi.json](https://docs.pixgt.com/openapi.json): machine-readable OpenAPI 3.1 specification

    # Quickstart

    Generate your first **product suite** with `curl` in about five minutes: upload a product photo → estimate the price → create a task (with an idempotency key) → poll or receive a webhook → download the results.

    ## Before you start

    1. **Get an API key**: an enterprise owner or admin signs in to PixGT and opens **Enterprise admin panel → Developer / API**, then clicks "Create key". Create integration keys in the **preview (sandbox) environment**; they start with `pgk_test_`. Production keys start with `pgk_live_`. See [Authentication & API keys](#description/authentication-api-keys).
    2. **Pick an environment**:

    | Environment | Base URL | Notes |
    | :--- | :--- | :--- |
    | Preview (sandbox) | `https://tapi.pixgt.com/open/v1` | Separate database and keys. Integrate here first |
    | Production | `https://api.pixgt.com/open/v1` | Live environment, consumes your enterprise points |

    3. Export two environment variables (used by every command below):

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

    > The interactive console on this site defaults to the **sandbox**. Paste your key and click "Send" to call the API directly. Your key only travels between your browser and PixGT servers; no third-party proxy is involved.

    ## Step 1: Upload a product photo

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

    Returns `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, up to 20 MB each. Assets are deleted automatically after **30 days**.
    - You can also skip the upload and pass a public `https` image URL in the task (see [Tasks & statuses](#description/tasks-statuses)).

    ## Step 2 (optional): Discover options

    Modules, platforms, text languages, festival themes and platform size presets are all available from the API. Do not hard-code them:

    ```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"
    ```

    ## Step 3: Estimate the price (free)

    ```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": "Portable blender bottle, 350 ml, USB-C charging",
          "platform": "amazon",
          "language": "en",
          "modules": ["main_image", "selling_points", "scene", "spec"],
          "size": { "preset_id": "amz_main" },
          "model": "auto"
        }
      }'
    ```

    Response:

    ```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 }] }
    ```

    > Point values in examples are illustrative; always rely on the live response. Estimates and actual charges use the same pricing function.

    ## Step 4: Create the task (with an idempotency key)

    ```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": "Portable blender bottle, 350 ml, USB-C charging",
          "platform": "amazon",
          "language": "en",
          "modules": ["main_image", "selling_points", "scene", "spec"],
          "size": { "preset_id": "amz_main" },
          "model": "auto"
        },
        "webhook_url": "https://erp.example.com/pixgt/callback",
        "client_reference_id": "SKU-10086"
      }'
    ```

    Returns `202 Accepted` immediately (it does not wait for generation):

    ```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"
    }
    ```

    - Points are **pre-charged at creation** based on the estimate; failed outputs are refunded automatically.
    - When retrying after a network timeout, **reuse the same `Idempotency-Key`**: no duplicate task, no double charge (see [Idempotency](#description/idempotency)).

    ## Step 5: Get the result

    **Option A: polling** (interval ≥ 5 seconds)

    ```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}'
    ```

    **Option B: webhook**: when the task reaches a final status, PixGT POSTs a `task.succeeded` / `task.partially_succeeded` / `task.failed` event to `webhook_url` (or your enterprise default URL). Its `data` is identical to the `GET /tasks/{task_id}` response. Always verify the signature; see [Webhooks](#description/webhooks).

    ## Step 6: Download and store

    `outputs[].url` is a **signed, temporary URL (valid for about 24 hours)**. Download the files **right after the task succeeds** and store them in your own storage; do not put PixGT URLs directly on product pages. If a URL expires, call `GET /tasks/{task_id}` again for a fresh one. See [Result URL expiry](#description/result-url-expiry).

    ```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
    ```

    ## Next steps

    - Inputs for free-form image generation (`image_generation`) and video generation (`video_generation`) are described in [Tasks & statuses](#description/tasks-statuses).
    - Before going live, switch `PIXGT_BASE` to `https://api.pixgt.com/open/v1` and use a `pgk_live_` production key.
    - For AI coding tools: give `https://docs.pixgt.com/llms-full.txt` or `https://docs.pixgt.com/openapi.yaml` to Cursor, Claude Code or similar tools to generate integration code.

    # Authentication & API keys

    Every endpoint uses **Bearer token** authentication:

    ```http
    Authorization: Bearer pgk_live_3fa9c0d1e2b4_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ```

    ## Key format

    ```text
    pgk_<env>_<12 hex prefix>_<43 random characters>
    ```

    | Prefix | Environment | Use |
    | :--- | :--- | :--- |
    | `pgk_test_` | Preview (sandbox) `https://tapi.pixgt.com/open/v1` | Integration and testing |
    | `pgk_live_` | Production `https://api.pixgt.com/open/v1` | Live traffic |

    - Sandbox and production are **separate systems** (separate databases and keys). Keys do not work across them.
    - The global edition (pixgt.com) and the China edition are also separate systems with separate keys.

    ## Where to create keys

    1. An enterprise **owner** or **admin** signs in and opens **Enterprise admin panel → Developer / API** (regular members do not see this page).
    2. Click "Create key" and fill in:
       - **Name** (required, e.g. "ERP production") and **note** (optional, e.g. "Shopify sync, contact: Alex");
       - **Scopes** (all selected by default, see below);
       - **Expiry**: 90 days / 180 days / 1 year / never;
       - **Monthly budget** (optional): the maximum points this key may consume per month. Exceeding it returns `402 key_budget_exceeded`.
    3. The new key appears in the list right away.

    > Phase one supports **enterprise keys** only: calls consume the enterprise's shared points and never touch any member's personal points.

    ## View and copy at any time

    - Keys are masked in the list (e.g. `pgk_live_3fa9c0d1e2b4••••••••••••Xq2Z`).
    - Click the **eye icon** to reveal the full key, or the **copy icon** to copy it directly.
    - Every reveal is audited (who, when, which key); the list shows "last viewed".

    ## If a key leaks: delete it

    - Delete a leaked or unused key from the list. It **stops working immediately**; requests using it return `401 invalid_api_key`.
    - Historical tasks and billing can still be traced to the deleted key.
    - **Rotation**: create a new key → switch your system to it → delete the old one.

    ## Scopes

    | Scope | Allowed endpoints | Default |
    | :--- | :--- | :---: |
    | `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` and `GET /options/product-suite` only require a valid key, no specific scope.
    - A missing scope returns `403 insufficient_scope`.
    - A common pattern: one full-access key for the production system, and a read-only `account:read` key for a finance reconciliation script.

    ## Authentication errors

    | HTTP | `code` | Meaning |
    | :---: | :--- | :--- |
    | 401 | `missing_api_key` | No `Authorization` header |
    | 401 | `invalid_api_key` | Malformed, unknown or deleted key |
    | 401 | `api_key_expired` | The key has expired |
    | 403 | `insufficient_scope` | The key lacks the scope required by this endpoint |
    | 403 | `enterprise_expired` | The enterprise plan has expired (read-only period). Generation endpoints are blocked; read endpoints still work |
    | 403 | `api_access_disabled` | API access is not enabled for this enterprise, or it has been restricted by the platform |

    ## Security recommendations

    - **Store keys on your server only.** Never ship them in web front-ends, mini programs or mobile app bundles.
    - Do not commit keys to source control; use environment variables or a secrets manager.
    - Use a separate key per system and set monthly budgets to limit the blast radius.
    - The interactive console on this site calls the PixGT API straight from your browser (the API allows cross-origin requests) **without any third-party proxy**. We recommend using only sandbox `pgk_test_` keys in the console.

    # Tasks & statuses

    All generation capabilities (product suite / image generation / video generation) are **asynchronous tasks** sharing the same endpoints and envelope; only `type` and `input` differ:

    ```text
    POST /tasks  ──202──▶  GET /tasks/{task_id} (polling)  or  webhook (push)
    ```

    ## Task types

    | `type` | Capability | Outputs |
    | :--- | :--- | :--- |
    | `product_suite` | Product suite: main image, selling points, scene and other e-commerce images in one task | 1 per module |
    | `image_generation` | Free-form image generation: prompt plus optional reference images | `n` images (1-4) |
    | `video_generation` | Video generation: prompt plus reference images / first frame / first and last frames | 1 video |

    > Future versions will add new `type` values (such as virtual try-on or background replacement). Clients must **tolerate unknown values**.

    ## Status machine

    ```text
    queued ──▶ processing ──┬─▶ succeeded            (all outputs succeeded)
       │                    ├─▶ partially_succeeded  (some outputs failed; refunded)
       │                    └─▶ failed               (all failed; fully refunded)
       └──────────────────────▶ failed               (moderation block / system error)
    ```

    | `status` | Meaning | Final |
    | :--- | :--- | :---: |
    | `queued` | Accepted, points pre-charged, waiting to start | |
    | `processing` | Planning / generating | |
    | `succeeded` | All outputs succeeded | ✅ |
    | `partially_succeeded` | Finished; some outputs succeeded and some failed | ✅ |
    | `failed` | The task failed | ✅ |

    `partially_succeeded` mainly applies to **product suites** (several images per task): use the successful images right away and resubmit only the failed modules.

    ## Points: pre-charge and refunds

    The `cost` object:

    | Field | Meaning |
    | :--- | :--- |
    | `points_estimated` | Estimated points at creation (same as `POST /tasks/estimate`) |
    | `points_charged` | Points actually pre-charged at creation |
    | `points_refunded` | Points refunded for failed outputs |

    **Net cost = `points_charged` − `points_refunded`**. Example: a 4-image suite pre-charges 480 points; one image fails, so after completion `points_refunded = 120` and the net cost is 360 points.

    - Insufficient balance at creation returns `402 insufficient_balance`; an exhausted monthly key budget returns `402 key_budget_exceeded`.
    - API usage costs **the same** as generating inside the PixGT web app; there is no separate API pricing.

    ## Retrieve a task

    The `GET /tasks/{task_id}` response is **identical** to the `data` of a webhook event:

    ```json
    {
      "id": "task_01JDQ8Z3K7M2V9X4R6T1B5N8C0",
      "object": "task",
      "type": "product_suite",
      "status": "partially_succeeded",
      "progress": { "total": 4, "succeeded": 3, "failed": 1, "pending": 0 },
      "input": { "...": "normalized echo of your input" },
      "outputs": [
        { "index": 0, "module": "main_image", "status": "succeeded",
          "url": "https://...signed URL...", "url_expires_at": "2026-11-29T15:00:00Z",
          "width": 2000, "height": 2000, "format": "png", "model": "seedream5.0" },
        { "index": 3, "module": "spec", "status": "failed",
          "error": { "code": "content_policy_violation", "message": "The generated content did not pass the safety review", "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": "amazon-us" },
      "watermark": false
    }
    ```

    - **Poll no more often than every 5 seconds.** Images usually take tens of seconds; videos may take several minutes.
    - Product suite `outputs` are always ordered `main_image` → `selling_points` → `scene` → `detail` → `spec` → `white_background` → `features` → `comparison` (only the modules you selected), regardless of the order in your `modules` array.
    - `outputs[].url` is a temporary signed URL; see [Result URL expiry](#description/result-url-expiry).
    - Video outputs also include `duration` (seconds) and `cover_url` (first-frame cover image).

    ## List tasks

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

    - Returns only tasks **created through the API by the current enterprise**, newest first.
    - Cursor pagination: when `has_more=true`, pass the last item's `id` as `starting_after` for the next page.
    - `limit` is at most 100. Filter by `type`, `status`, `client_reference_id`, `created_after`, `created_before`.

    ## Common fields

    | Field | Required | Description |
    | :--- | :---: | :--- |
    | `type` | ✅ | `product_suite` / `image_generation` / `video_generation` |
    | `input` | ✅ | Type-specific parameters, see below |
    | `webhook_url` | | Overrides the enterprise default webhook URL; `https` only, ≤ 512 characters |
    | `client_reference_id` | | Your own business ID (≤ 64 characters); filterable in the task list |
    | `metadata` | | Up to 16 key/value pairs (keys ≤ 40 characters, string values ≤ 256 characters), echoed back and never used for generation |
    | `watermark` | | Defaults to `false`; see [Watermark](#description/watermark) |

    > **Strict validation**: any undefined field in the request body returns `400 invalid_parameter` (with `param` naming the field), so a misspelled field never silently does nothing.

    ## Image inputs `images[]`

    Each item is exactly one of:

    - `{ "asset_id": "asset_..." }`: returned by `POST /assets` (**recommended**, most reliable).
    - `{ "url": "https://..." }`: a public `https` URL that the server downloads and stores. Requirements: `https` only, no private/internal addresses, ≤ 20 MB, png / jpg / jpeg / webp, 15-second download timeout. Failures return `400 invalid_image_url` with `param` pointing at the item (e.g. `input.images[1].url`).

    ## `product_suite`

    | Field | Required | Description |
    | :--- | :---: | :--- |
    | `images` | ✅ | 1-6 product photos |
    | `product_description` | | Product name, selling points, extra notes (≤ 2000 characters) |
    | `platform` | | Target marketplace, values from `GET /options/product-suite` (e.g. `amazon`, `shopify`, `tiktok_shop`, `temu`, `shopee`) |
    | `language` | | Language of text in the images (ISO 639-1, e.g. `en`, `ja`, `de`) |
    | `modules` | ✅ | At least one, no duplicates: `main_image`, `selling_points`, `scene`, `detail`, `spec` (specifications), `white_background`, `features`, `comparison` |
    | `size` | | Unified size object; see [Size](#description/size) |
    | `model` | | Defaults to `auto`; values from `GET /models?type=image` |
    | `module_options.spec.product_size` | | Real product dimensions `{length, width, height, unit}` for the spec image; `unit` is `cm` / `mm` / `in`. Without it, the image shows dimension lines but no invented numbers |
    | `module_options.scene.hint` | | One-line scene description (≤ 60 characters) |
    | `module_options.comparison.mode` | | `ordinary` / `before_after` / `pain_point` |
    | `festival.theme` | | Festival / sales-event mood from `festival_themes`; `none` or omitted means none; `custom` requires `festival.custom {name ≤24, prompt ≤200, palette_id}` |

    ## `image_generation`

    ```json
    {
      "type": "image_generation",
      "input": {
        "prompt": "Place this perfume on a marble countertop in soft morning light",
        "images": [{ "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" }],
        "n": 2,
        "size": { "width": 1200, "height": 1600 },
        "model": "auto"
      }
    }
    ```

    | Field | Required | Description |
    | :--- | :---: | :--- |
    | `prompt` | ✅ | Prompt, 1-4000 characters |
    | `images` | | Reference images, up to 10 (see the model's `max_input_images`) |
    | `n` | | Number of images, 1-4, default 1 |
    | `size` | | See [Size](#description/size) |
    | `model` | | Defaults to `auto`; available values from `GET /models?type=image` (e.g. `seedream5.0`) |

    ## `video_generation`

    ```json
    {
      "type": "video_generation",
      "input": {
        "prompt": "The camera slowly orbits the blender bottle as fruit drops in with a splash",
        "mode": "image_to_video",
        "images": [{ "asset_id": "asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0" }],
        "model": "seedance2.0-fast",
        "duration": 5,
        "aspect_ratio": "9:16",
        "resolution": "720p"
      }
    }
    ```

    | Field | Required | Description |
    | :--- | :---: | :--- |
    | `prompt` | ✅ | Video description, 1-4000 characters |
    | `model` | ✅ | Video model from `GET /models?type=video` |
    | `mode` | | `reference` (default, multi-image reference, 0-9 images) / `image_to_video` (first frame, exactly 1 image) / `first_last_frame` (first and last frames, exactly 2 images) |
    | `images` | | Count validated against `mode` |
    | `duration` | | Seconds; allowed values per the model's `durations` |
    | `aspect_ratio` | | `16:9` / `9:16` / `1:1` / `4:3` / `3:4` / `21:9` |
    | `resolution` | | `480p` / `720p` / `1080p` / `2k`, per model capabilities |
    | `enhance` | | Automatic upscaling (extra cost); not available for `1080p` / `2k` |

    ## Failure reasons inside a task

    Check `outputs[].error` for a single failed output and the top-level `error` for a failed task:

    | `code` | Meaning | Suggestion |
    | :--- | :--- | :--- |
    | `content_policy_violation` | Input or generated content failed the safety review | Change the prompt / images and resubmit |
    | `generation_failed` | Generation failed | Retryable |
    | `timeout` | Generation timed out | Retryable |
    | `watermark_failed` | Video watermarking failed | Retryable |
    | `internal_error` | System error | Retryable |

    Rely on the `retryable` flag: when `true`, you can resubmit the same request (with a **new** `Idempotency-Key`).

    # Size

    Product suites and image generation describe the output size with **one** `size` object. Use **exactly one** of three forms, so resolution and aspect ratio can never be combined into a contradictory request.

    | Form | Example | Best for |
    | :--- | :--- | :--- |
    | Platform preset | `{ "preset_id": "amz_main" }` | **Recommended**: follow marketplace specs directly |
    | Exact pixels | `{ "width": 1000, "height": 1000 }` | Strict pixel requirements |
    | Tier + aspect ratio | `{ "tier": "2k", "aspect_ratio": "3:4" }` | You care about sharpness and framing only |

    Omitting `size` is equivalent to `{ "tier": "auto" }`; the model decides.

    ## 1. Platform preset `preset_id`

    Values come from `size_presets` in `GET /options/product-suite` (grouped by platform; each item has `width`, `height`, `aspect_ratio` and `module_group`). For example:

    | `preset_id` | Platform | Size |
    | :--- | :--- | :--- |
    | `amz_main` | Amazon main image | 2000 × 2000 |
    | `amz_main_1k` | Amazon main image | 1000 × 1000 |
    | `shopify_main` | Shopify | 2048 × 2048 |
    | `tts_main` | TikTok Shop | 1200 × 1200 |

    > These are examples only. Use the live list from the API and do not hard-code it. An unknown `preset_id` returns `400 invalid_parameter` (`param: input.size.preset_id`).

    A preset is effectively an exact pixel size and is billed the same way as exact pixels below.

    ## 2. Exact pixels `width` + `height`

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

    - `width` and `height` must **both** be integers between **64 and 4096** pixels.
    - The aspect ratio must not exceed **3:1**.
    - **The billing tier is derived from the pixel size and is only ever lowered, never raised**: a 1000 × 1000 request is billed at the 1K tier, so you are never charged for 2K while receiving 1000 × 1000.

    ## 3. Tier + aspect ratio `tier` + `aspect_ratio`

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

    - `tier`: `auto` / `1k` / `2k` / `4k`; defaults to `auto`.
    - `aspect_ratio`: `W:H` (e.g. `1:1`, `3:4`, `16:9`), not exceeding 3:1; omitted means the model decides.
    - Billing follows `tier`; unit prices are listed in `pricing` from `GET /models`.

    ## Common mistakes

    | Request | Result |
    | :--- | :--- |
    | `{ "preset_id": "amz_main", "tier": "2k" }` | `400`: only one form allowed |
    | `{ "width": 1000 }` | `400`: width and height are both required |
    | `{ "width": 4000, "height": 1000 }` | `400`: aspect ratio exceeds 3:1 |
    | `{ "tier": "8k" }` | `400`: tier must be auto / 1k / 2k / 4k |

    ## Videos do not use size

    Video tasks use the separate `aspect_ratio` and `resolution` fields (see [Tasks & statuses](#description/tasks-statuses)) and do not accept `size`.

    # Watermark

    Available for all three task types, set at the **top level** of the request body (next to `type` and `input`):

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

    | Value | Effect |
    | :--- | :--- |
    | omitted / `false` (default) | Outputs have **no watermark**. Most integrations that publish product images directly use this |
    | `true` | Outputs carry the platform watermark; useful for downstream review, previews or end-user trials |

    ## Rules

    - **No extra charge**: `true` and `false` cost the same.
    - The task object's `watermark` field echoes whether the task requested a watermark.
    - **Images**: the watermark is applied when the result URL is issued; nothing is regenerated and no time is added.
    - **Videos**: video watermarking is **not yet supported in the global region**. Sending `watermark: true` with a `video_generation` task returns `400 invalid_parameter` (`param: watermark`).
    - API tasks follow only the `watermark` parameter in the request and are not affected by any other watermark policy in the web app.

    # Result URL expiry

    Task outputs' `outputs[].url` (and `cover_url` for videos) are **signed, temporary URLs** valid for about **24 hours**. The exact expiry time is in the sibling field `url_expires_at`.

    ```json
    { "index": 0, "status": "succeeded",
      "url": "https://<bucket>.s3.<region>.amazonaws.com/.../20261127_ab12.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=...&X-Amz-Expires=86400&X-Amz-Signature=...",
      "url_expires_at": "2026-11-29T15:00:00Z" }
    ```

    ## Why URLs expire

    1. **Results live in a private bucket**: product images are confidential before launch and must not become permanent public links that anyone can open.
    2. **Policy takedowns actually work**: links already handed out stop working at the latest when they expire, so removed content does not circulate forever.
    3. **No hotlinking or bandwidth abuse**: permanent public links tend to be reused as free image hosting.

    ## How to use them

    - **Download right after the task succeeds and store the files in your own storage** (S3 / CDN / media library), then use your own URLs on product pages.
    - **Do not** put PixGT URLs on product pages or persist them as long-term references.
    - As long as the task is within its retention period, `GET /tasks/{task_id}` always returns a **fresh** URL.

    ## What a refreshed URL looks like

    The file itself (object path) **does not change**; only the signature parameters after `?` (signing time, lifetime, signature) do:

    ```text
    https://<bucket>.s3.<region>.amazonaws.com/1234/output/images/20261127_ab12.png
        ?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=...&X-Amz-Date=20261128T160000Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=...
    ```

    - Signatures are cached per time window: repeated queries within one window return **the same URL**, and a new one is issued in the next window. The remaining lifetime is therefore usually between 20 and 24 hours. **Always rely on `url_expires_at`** rather than assuming 24 hours.

    ## What an expired URL returns

    **HTTP 403** (not 404, no redirect) with the storage service's XML error body:

    ```xml
    <Error>
      <Code>AccessDenied</Code>
      <Message>Request has expired</Message>
      <X-Amz-Expires>86400</X-Amz-Expires>
      <Expires>2026-11-28T15:00:00Z</Expires>
      <ServerTime>2026-11-28T15:20:31Z</ServerTime>
    </Error>
    ```

    ## Standard handling

    Got **403** while downloading → call `GET /tasks/{task_id}` again for a fresh URL → download again.

    ```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  # URL expired: fetch the task again for a fresh URL
            r.raise_for_status()
            with open(path, "wb") as f:
                f.write(r.content)
            return
    ```

    # Webhooks

    Webhooks do one thing: **notify you when an asynchronous task reaches a final status**. They are optional. Without them you can poll `GET /tasks/{task_id}` and get exactly the same result. Webhooks save you from writing polling loops, deliver results without polling delay, and eliminate a large number of status requests when processing many SKUs.

    ## Configuration

    - **Default webhook URL**: Enterprise admin panel → Developer / API → **Webhook settings**. Enter an `https` URL. Here you can also:
      - view / copy / reset the **signing secret** (`whsec_...`, with the same eye and copy icons);
      - "Send test event" (`webhook.test`);
      - review recent deliveries and redeliver manually.
    - **Per-task override**: pass `webhook_url` when creating a task; it takes precedence over the default URL. The same signing secret is used.
    - If neither is configured, nothing is delivered.

    ## Events

    | `type` | When |
    | :--- | :--- |
    | `task.succeeded` | All outputs of the task succeeded |
    | `task.partially_succeeded` | The task finished and some outputs failed (failed outputs refunded) |
    | `task.failed` | The task failed (fully refunded) |
    | `webhook.test` | Sent when you click "Send test event"; `data` is `{"message": "..."}`, not a task object |

    ## Delivery format

    ```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", "...": "identical to the GET /tasks/{task_id} response" }
    }
    ```

    ## Signature verification

    ```text
    PixGT-Signature: t=<unix seconds>,v1=<hex>
    v1 = HEX( HMAC_SHA256( key = the full signing secret string (including the whsec_ prefix), message = "{t}.{raw request body}" ) )
    ```

    Your endpoint must:

    1. Compute the signature over the **raw request body bytes** (do not parse and re-serialize JSON; key order and whitespace would change);
    2. Compare signatures in **constant time** (`timingSafeEqual` / `hmac.compare_digest` / `hash_equals`);
    3. Reject requests where `|now − t| > 300 seconds` to prevent replays;
    4. **Deduplicate** by `PixGT-Event-Id` (retries can deliver the same event more than once).

    ### Test vector

    Use this in your unit tests to validate your implementation:

    ```text
    secret:    whsec_dGVzdF9zZWNyZXRfZm9yX2RvY3Nfb25seQ
    t:         1764342161
    body:      {"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."}}
    signature: t=1764342161,v1=2da0b6011106a10126964289ad9e27e8c65ae0f9fd0212122e38173ae64d818f
    ```

    (Freeze "now" to `t` in the test; otherwise the 300-second tolerance check fails.)

    ### 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();
    // You need the raw body: use express.raw, not 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');           // acknowledge quickly with 2xx
      setImmediate(() => handleEvent(event)); // then process asynchronously (dedupe by 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()  # raw bytes
        if not verify_pixgt_signature(raw, request.headers.get("PixGT-Signature", ""), SECRET):
            abort(400)
        event = request.get_json(force=True)
        # dedupe by event["id"], then enqueue for processing
        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));
        }
    }
    ```

    In Spring Boot, read the raw body with `@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');            // raw request body
    $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);
    // dedupe by $event['id'], then process
    http_response_code(200);
    echo 'ok';
    ```

    ## Delivery and retries

    - Any **2xx** response counts as delivered; the **timeout is 10 seconds**. Return 2xx first and process asynchronously.
    - On failure (non-2xx, timeout, connection error) PixGT retries after **1 min / 5 min / 30 min / 2 h / 6 h / 12 h / 24 h**, for **at most 8 attempts including the first**.
    - `webhook.test` events are delivered once and never retried.
    - Delivery history and manual redelivery are available in the admin panel.
    - Webhooks are **notifications**, not the only channel: you can always fall back to `GET /tasks/{task_id}` (poll no more often than every 5 seconds).

    # Idempotency

    After a network timeout you cannot know whether the request succeeded. **Retry with the same `Idempotency-Key`** and PixGT guarantees no duplicate task and no double charge.

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

    ## Rules

    | Situation | Result |
    | :--- | :--- |
    | First request | Created normally, returns `202` |
    | Within 24 hours, same API key + same `Idempotency-Key` + **same body** | Returns the originally created task (`202`) with header `Idempotent-Replayed: true`; **no extra charge** |
    | Same `Idempotency-Key` + **different body** | `409 idempotency_conflict` |
    | Same `Idempotency-Key` while the first request is still being processed | `409 idempotency_conflict`; retry later or query the task |

    - Applies to `POST /tasks` (create task). `POST /tasks/estimate` never charges and needs no idempotency key.
    - `Idempotency-Key` must be 1-64 characters, otherwise `400 invalid_parameter` (`param: Idempotency-Key`).
    - Scoped per **API key**: different keys using the same value do not interfere.
    - "Same body" is compared semantically as JSON; field order does not matter.

    ## How to choose a key

    Build it from **your own business identifiers** instead of generating a random value each time, so retries still match after a process restart:

    ```text
    sku-10086-suite-v1          # SKU + purpose + version
    order-20261128-0042-video   # order number + type
    ```

    To **intentionally** generate again for the same SKU, use a new key (e.g. `-v2`).

    ## Recommended retry policy

    | Response | Retry? |
    | :--- | :--- |
    | Network error / timeout / `500` / `503` | ✅ Exponential backoff, **same `Idempotency-Key`** |
    | `429` | ✅ Wait for `Retry-After`, then retry |
    | `409 idempotency_conflict` | Check `GET /tasks?client_reference_id=...` first to see whether the task exists |
    | Other `4xx` | ❌ Fix the request and send it again (with a new key) |

    # Rate limits & concurrency

    ## Request rate (per API key)

    | Category | Endpoints | Default limit |
    | :--- | :--- | :--- |
    | Write | `POST /tasks`, `POST /tasks/estimate`, `POST /assets` | **60 requests / minute** |
    | Read | `GET /tasks`, `GET /tasks/{task_id}`, `GET /account`, `GET /account/balance`, etc. | **600 requests / minute** |
    | Invalid key attempts (per source IP) | Any | 30 requests / minute |

    - Exceeding a limit returns `429` with `error.code = rate_limit_exceeded` and a `Retry-After` header (seconds to wait). Wait that long before retrying.
    - Your key's limits are returned in `limits.requests_per_minute` from `GET /account`.
    - Poll tasks no more often than every **5 seconds**; for large batches use [Webhooks](#description/webhooks) to drastically cut status requests.

    ## Concurrent tasks (per enterprise)

    The number of **in-progress** (`queued` / `processing`) API tasks per enterprise is capped by plan:

    | Plan | Concurrent task limit |
    | :--- | :---: |
    | Starter | 10 |
    | Pro | 15 |
    | Flagship | 20 |
    | Custom | 30 (can be raised) |

    - API tasks and members' tasks in the web app are **counted separately**, so API batches never crowd out your team's day-to-day work.
    - Exceeding the cap returns `429` with `error.code = concurrency_limit_exceeded`; wait for some tasks to finish and resubmit.
    - The current cap is `limits.concurrent_tasks` in `GET /account`.

    ## Batch submission tips

    1. Keep a submission queue in your system whose **concurrency stays below the cap**;
    2. Send an `Idempotency-Key` and `client_reference_id` with every task;
    3. On `429`, retry after `Retry-After` (or exponential backoff); do not resend immediately;
    4. Receive results by webhook and refill the queue as tasks complete.

    # Errors

    ## Error body

    Every error uses the same structure and comes with an `X-Request-Id` response header:

    ```json
    {
      "error": {
        "type": "invalid_request_error",
        "code": "invalid_parameter",
        "message": "input.modules must contain at least one module",
        "param": "input.modules",
        "request_id": "req_01JDQ8Z3K7M2V9X4R6T1B5N8C0"
      }
    }
    ```

    | Field | Description |
    | :--- | :--- |
    | `type` | Error category |
    | `code` | **Stable error code. Branch on this only** |
    | `message` | Human-readable text; language follows `Accept-Language` (`zh` / `en`, English by default). Wording may change, so never parse it |
    | `param` | Path of the offending field (e.g. `input.images[1].url`), parameter errors only |
    | `request_id` | Unique request ID; include it when contacting support |

    ## Error codes

    | HTTP | `type` | `code` | Description | Retry |
    | :---: | :--- | :--- | :--- | :---: |
    | 400 | `invalid_request_error` | `invalid_parameter` | Validation failed (including unknown fields); see `param` | |
    | 400 | `invalid_request_error` | `invalid_image_url` | Image URL cannot be downloaded, is too large or has an unsupported format | |
    | 400 | `invalid_request_error` | `unsupported_task_type` | `type` does not exist or is not enabled for this enterprise | |
    | 400 | `invalid_request_error` | `model_unavailable` | Model does not exist or has been retired; see `GET /models` | |
    | 400 | `content_policy_error` | `content_policy_violation` | Prompt or input image failed the safety review | |
    | 401 | `authentication_error` | `missing_api_key` | No `Authorization` header | |
    | 401 | `authentication_error` | `invalid_api_key` | Invalid or deleted key | |
    | 401 | `authentication_error` | `api_key_expired` | The key has expired | |
    | 402 | `billing_error` | `insufficient_balance` | Not enough shared enterprise points | |
    | 402 | `billing_error` | `key_budget_exceeded` | The key's monthly budget is used up | |
    | 403 | `permission_error` | `insufficient_scope` | The key lacks the scope this endpoint requires | |
    | 403 | `permission_error` | `enterprise_expired` | Enterprise plan expired (read-only period); renew to keep generating | |
    | 403 | `permission_error` | `api_access_disabled` | API access not enabled, or the account is restricted | |
    | 404 | `invalid_request_error` | `resource_not_found` | Endpoint, task or asset not found, or not owned by this enterprise | |
    | 405 | `invalid_request_error` | `method_not_allowed` | Wrong HTTP method | |
    | 409 | `invalid_request_error` | `idempotency_conflict` | Idempotency key reused with a different body, or the same key is still in progress | |
    | 413 | `invalid_request_error` | `file_too_large` | Upload exceeds 20 MB | |
    | 415 | `invalid_request_error` | `unsupported_media_type` | Wrong body format: task creation requires `application/json`, uploads require `multipart/form-data` | |
    | 429 | `rate_limit_error` | `rate_limit_exceeded` | Too many requests; wait for `Retry-After` | ✅ |
    | 429 | `rate_limit_error` | `concurrency_limit_exceeded` | Too many tasks in progress | ✅ |
    | 500 | `api_error` | `internal_error` | Server error | ✅ |
    | 503 | `api_error` | `service_unavailable` | Maintenance or upstream temporarily unavailable | ✅ |

    > `api_key_revoked` in the specification is reserved; deleted keys currently return `invalid_api_key`.

    ## Errors inside tasks

    When a task that was already created fails during generation, there is no HTTP error. The failure appears in the task's `error` and `outputs[].error`; see "Failure reasons inside a task" in [Tasks & statuses](#description/tasks-statuses).

    ## Handling tips

    - Branch on `code`; use `message` only for display or logging.
    - Log the `X-Request-Id` of every request so support can locate it quickly.
    - Retry retryable errors with exponential backoff, reusing the same `Idempotency-Key` for task creation (see [Idempotency](#description/idempotency)).

    # Changelog

    ## 1.0.0-draft (2026-11-28)

    First public draft.

    - Unified asynchronous task API: `POST /tasks`, `GET /tasks/{task_id}`, `GET /tasks`, supporting three task types:
      - `product_suite`
      - `image_generation`
      - `video_generation`
    - Price estimates with `POST /tasks/estimate` (free).
    - Asset upload with `POST /assets` (deleted automatically after 30 days).
    - Capability discovery with `GET /models` and `GET /options/product-suite`.
    - Account and balance with `GET /account` and `GET /account/balance`.
    - Final-status webhooks (`task.succeeded` / `task.partially_succeeded` / `task.failed`) signed with HMAC-SHA256.
    - `Idempotency-Key`, per-key rate limits and per-enterprise concurrency limits.
    - Unified `size` object (platform preset / exact pixels / tier + aspect ratio) and the `watermark` switch.

    ## Compatibility policy

    - Within `v1` we only make **backward-compatible** changes: new endpoints, new optional fields and new enum values (such as new task `type` values, error codes or event types). Make your code **tolerate unknown fields and unknown enum values**.
    - Breaking changes ship under a new major version path (e.g. `/open/v2`) with advance notice.
  contact:
    name: PixGT Developer Support
    url: https://docs.pixgt.com
servers:
  - url: https://tapi.pixgt.com/open/v1
    description: Global preview (sandbox, use pgk_test_ keys)
  - url: https://api.pixgt.com/open/v1
    description: Global production (use pgk_live_ keys)
security:
  - bearerAuth: []
tags:
  - name: Tasks
    description: Unified asynchronous generation tasks (product suite / image generation / video generation)
    x-displayName: Tasks
  - name: Assets
    description: Input asset upload
    x-displayName: Assets
  - name: Catalog
    description: Discover models, capabilities and options
    x-displayName: Catalog
  - name: Account
    description: Enterprise account, balance and current key information
    x-displayName: Account
paths:
  /assets:
    post:
      tags:
        - Assets
      operationId: uploadAsset
      summary: Upload an image asset
      description: Requires scope `assets:write`. Assets are deleted automatically after 30 days.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - file
              properties:
                file:
                  type: string
                  format: binary
                  description: png / jpg / jpeg / webp, ≤ 20 MB
                purpose:
                  type: string
                  enum:
                    - input
                  default: input
      responses:
        "201":
          description: Uploaded
          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: Create a generation task
      description: |-
        Requires scope `tasks:write`. Points are pre-charged at creation based on the estimate; failed outputs are refunded automatically.
        Returns `202` immediately; get the result by polling `GET /tasks/{task_id}` or via webhook.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
        - $ref: "#/components/parameters/AcceptLanguage"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateTaskRequest"
            examples:
              productSuite:
                summary: Product suite
                value:
                  type: product_suite
                  input:
                    images:
                      - asset_id: asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0
                    product_description: Portable blender bottle, 350 ml, USB-C charging
                    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: On a picnic table at an outdoor campsite
                  webhook_url: https://erp.example.com/pixgt/callback
                  client_reference_id: SKU-10086
              imageGeneration:
                summary: Image generation
                value:
                  type: image_generation
                  input:
                    prompt: Place this perfume on a marble countertop in soft morning light
                    images:
                      - url: https://img.example.com/perfume.jpg
                    n: 2
                    size:
                      width: 1200
                      height: 1600
              videoGeneration:
                summary: Video generation
                value:
                  type: video_generation
                  input:
                    prompt: The camera slowly orbits the blender bottle as fruit drops in with a splash
                    mode: image_to_video
                    images:
                      - asset_id: asset_01JDQ8Z3K7M2V9X4R6T1B5N8C0
                    model: seedance2.0-fast
                    duration: 5
                    aspect_ratio: 9:16
                    resolution: 720p
      responses:
        "202":
          description: Task accepted
          headers:
            X-Request-Id:
              $ref: "#/components/headers/XRequestId"
            Idempotent-Replayed:
              description: "`true` means an idempotent replay: the response is the result of the original request"
              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: List tasks
      description: Requires scope `tasks:read`. Returns only tasks created through the Open API by the current enterprise, newest first.
      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: "Cursor: pass the `id` of the last item on the previous page"
          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: Estimate price
      description: Requires scope `tasks:write`. Same input as task creation; nothing is charged and no task is created. Uses the same pricing function as actual billing.
      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: Retrieve a task
      description: Requires scope `tasks:read`. The response is identical to the `data` of webhook events. Poll no more often than every 5 seconds.
      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: Available models, capabilities and prices
      description: Values are generated live by the server; retired models are not listed.
      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: Product suite options
      description: Modules, marketplaces, text languages, festival themes and platform size presets. Same source as the options in the web app.
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ProductSuiteOptions"
        "401":
          $ref: "#/components/responses/Unauthorized"
  /account:
    get:
      tags:
        - Account
      operationId: getAccount
      summary: Enterprise and current key information
      description: Requires 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: Shared points balance
      description: Requires 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: Task final-status event
      description: |-
        Event types: `task.succeeded` / `task.partially_succeeded` / `task.failed`.
        Signature: `PixGT-Signature: t=<unix seconds>,v1=<hex>`, `v1 = HMAC_SHA256(whsec_secret, "{t}.{raw request body}")`.
        Receivers should compare signatures in constant time, reject requests where |now − t| > 300s, and deduplicate by `PixGT-Event-Id`.
        Any 2xx counts as success; failures are retried with 1m/5m/30m/2h/6h/12h/24h backoff, at most 8 attempts.
      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: Received
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: pgk_live_<12 hex>_<43 chars>
      description: Issued by enterprise owners / admins in Enterprise admin panel → Developer / API; keys can be viewed and copied at any time. Use `pgk_test_` keys for the sandbox and `pgk_live_` keys for production. Store keys on your server only and delete a key immediately if it leaks.
  headers:
    XRequestId:
      description: Unique request ID; include it when reporting issues
      schema:
        type: string
    RetryAfter:
      description: Suggested number of seconds to wait
      schema:
        type: integer
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: ≤ 64 characters. Within 24 hours, the same key with the same request body returns the original result without charging again; a different body returns 409.
      schema:
        type: string
        maxLength: 64
    AcceptLanguage:
      name: Accept-Language
      in: header
      required: false
      description: "Language of the error `message`: `zh` or `en`"
      schema:
        type: string
        enum:
          - zh
          - en
  responses:
    BadRequest:
      description: Invalid parameters / content policy violation / model unavailable
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    Unauthorized:
      description: Authentication failed
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    PaymentRequired:
      description: Insufficient balance or the key's monthly budget is used up
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    Forbidden:
      description: Insufficient scope / enterprise expired (read-only) / API access not enabled
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    NotFound:
      description: Resource not found or not owned by this enterprise
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    Conflict:
      description: Idempotency key conflict
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    UnsupportedMediaType:
      description: Wrong body format (task creation requires application/json, uploads require multipart/form-data)
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    PayloadTooLarge:
      description: File too large
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    TooManyRequests:
      description: Rate limit or concurrency limit exceeded
      headers:
        Retry-After:
          $ref: "#/components/headers/RetryAfter"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    InternalError:
      description: Server error; safe to retry
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
  schemas:
    TaskType:
      type: string
      enum:
        - product_suite
        - image_generation
        - video_generation
      description: New values will be added in future versions (such as try_on, background_replace); clients must tolerate unknown values.
    TaskStatus:
      type: string
      enum:
        - queued
        - processing
        - succeeded
        - partially_succeeded
        - failed
    ImageInput:
      description: "Exactly one of: `asset_id` (recommended) or a public `https` URL (downloaded and stored by the server; private addresses are rejected)"
      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: Use exactly one of three forms, so resolution and aspect ratio can never be combined into a contradictory request.
      oneOf:
        - type: object
          title: Preset
          required:
            - preset_id
          additionalProperties: false
          properties:
            preset_id:
              type: string
              description: Platform size preset ID; see `/options/product-suite`
        - type: object
          title: Exact
          required:
            - width
            - height
          additionalProperties: false
          properties:
            width:
              type: integer
              minimum: 64
              maximum: 4096
              description: Aspect ratio must not exceed 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: Target marketplace; values from `/options/product-suite`
          examples:
            - amazon
            - taobao
            - pinduoduo
            - douyin
            - jd
            - temu
            - shopee
            - tiktok_shop
        language:
          type: string
          description: Language of text in the images (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
            - gpt-image-2
            - nano-banana-pro
        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: Festival theme ID from festival_themes in `/options/product-suite`; `none` or omitted means no festival mood
            custom:
              type: object
              description: Only allowed when theme=custom
              additionalProperties: false
              properties:
                name:
                  type: string
                  maxLength: 24
                prompt:
                  type: string
                  maxLength: 200
                palette_id:
                  type: string
                  description: See festival_palettes in `/options/product-suite`
    ImageGenerationInput:
      type: object
      required:
        - prompt
      additionalProperties: false
      properties:
        prompt:
          type: string
          minLength: 1
          maxLength: 4000
        images:
          type: array
          maxItems: 10
          description: Reference images
          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 mode: 0-9 images; image_to_video: exactly 1 (first frame); first_last_frame: exactly 2 (first frame, last frame)"
          items:
            $ref: "#/components/schemas/ImageInput"
        model:
          type: string
          description: Values from `/models?type=video`
        duration:
          type: integer
          description: Seconds; allowed values are listed in the model capabilities
        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: Automatic upscaling, billed extra; not available for 1080p / 2k; cannot be combined with watermark
    CreateTaskRequest:
      description: Task request discriminated by `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: No watermark by default; `true` adds the platform watermark at no extra cost. Video tasks reach a final status only after the watermark is burned in; video watermarks are not yet supported in the global region.
        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 actually pre-charged at creation
        points_refunded:
          type: integer
          description: Points refunded for failed outputs; net cost = 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 only
          $ref: "#/components/schemas/ProductSuiteModule"
        status:
          type: string
          enum:
            - pending
            - succeeded
            - failed
        url:
          type: string
          format: uri
          description: Signed URL, valid for 24 hours by default
        url_expires_at:
          type: string
          format: date-time
        cover_url:
          type: string
          format: uri
          description: "Video only: first-frame cover image"
        width:
          type: integer
        height:
          type: integer
        duration:
          type: number
          description: "Video only: seconds"
        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: Normalized echo of the input
        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: Whether this task requested a watermark
    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: Currently available points
        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: "Images: max_input_images / max_n / tiers / exact_size; videos: modes / durations / aspect_ratios / resolutions / enhance"
          additionalProperties: true
        pricing:
          type: object
          description: Images are billed per image (by tier), videos per second (by resolution)
          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: Grouped by platform 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: Personal keys only
          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: "Enterprise keys only: maximum number of tasks in progress at the same time"
            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: Points frozen after plan expiry; unfrozen on renewal (enterprise only)
        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: For task.* events this is the task object (same shape as GET /tasks/{task_id}); for webhook.test it is { 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: Full Markdown for AI coding tools (llms-full.txt)
  url: https://docs.pixgt.com/llms-full.txt
x-tagGroups:
  - name: API reference
    tags:
      - Tasks
      - Assets
      - Catalog
      - Account
