# Nano Banana (`nanobanana`)

> Image model `nanobanana` by Google on the Unitool API. Generations are asynchronous: `POST https://api.unitool.ai/v1/generations` creates one; then wait in the same request (`Prefer: wait`), poll `GET /v1/generations/{id}` or receive a webhook. This file is enough to write an integration.

The same model as JSON (modes, `input_schema`, prices): `GET /v1/models/nanobanana`. Docs index: https://unitool.ai/llms.txt.

## Facts

- id: `nanobanana`
- name: Nano Banana
- type: image
- vendor: Google
- price from: 6.25 balance tokens per generation
- modes: `v2-1`, `v2`, `v1`. Without a mode in the request the first one (`v2-1`) is used

## Calling the API

- Base URL `https://api.unitool.ai/v1`. Every request carries `Authorization: Bearer $UNITOOL_API_KEY` (`x-api-key: $UNITOOL_API_KEY` works too) and, with a body, `Content-Type: application/json`.
- Keys are created in the account (https://unitool.ai/settings?p=api), never through the API. `ut_live_...` spends the balance. `ut_test_...` runs the same checks and returns a fixed answer; nothing is charged.
- Prices and charges are in balance tokens (the account's currency), not model tokens. `GET /v1/balance` answers `{"object":"balance","unit":"tokens","available_tokens":1500,"held_tokens":40}`: `available_tokens` is free to spend, `held_tokens` is reserved by running requests.
- Every answer has an `x-request-id` header (`req_...`). The receipt of a charged request is `GET /v1/requests/{id}`.
- New fields may appear in answers: skip what you do not know.

## Create a generation

`POST https://api.unitool.ai/v1/generations` with a JSON body:

| Field | Type | Notes |
|---|---|---|
| `model` | string, required | `"nanobanana"`, or with the mode: `"nanobanana:v2-1"` |
| `mode` | string | One of `v2-1`, `v2`, `v1`, when not given in `model` |
| `input` | object, required | The fields of the mode, listed under "Modes" below. Enum values are accepted as strings and as numbers. A field the mode does not list is `400 invalid_parameter` |
| `max_cost_tokens` | number | Price ceiling. A higher price answers `402 price_exceeds_limit`; nothing is charged |
| `metadata` | object | Up to 16 string values of up to 500 characters; returned in the generation object and in webhook events |
| `webhook_url` | string | An https address that receives this generation's event, see "Webhook" |
| `webhook_events` | array | Which of `generation.succeeded`, `generation.failed` go to `webhook_url`; both by default. A 400 without `webhook_url` |

Any other top-level field is `400 invalid_parameter`. Headers:

- `Idempotency-Key`, 8 to 128 printable ASCII characters: a retry with the same key and the same body returns the same generation with `Idempotent-Replayed: true` and charges nothing again; the same key with another body is `422 idempotency_key_reused`. Keys never expire. Without the header every request is a new paid generation, so always send it and retry with the same key.
- `Prefer: wait=N` (or `?wait=N` in the URL), N up to 60: hold the answer until the generation ends or N seconds pass.

The answer is `202 Accepted` with `Location: /v1/generations/{id}` and `Retry-After: 5` while the generation has not ended, or `200 OK` with the finished object when it ended within the wait:

```json
{
  "id": "gen_6f1c0e9a2b7d4c3e8f5a1b2c3d4e5f60",
  "object": "generation",
  "model": "nanobanana",
  "mode": "v2-1",
  "status": "queued",
  "progress": 0,
  "cost": {
    "estimated_tokens": 12.5,
    "charged_tokens": 0,
    "refunded_tokens": 0,
    "settled": false
  },
  "outputs": [],
  "error": null,
  "metadata": {
    "order_id": "A-1042"
  },
  "created_at": "2026-11-29T12:00:00.000Z",
  "completed_at": null,
  "expires_at": null
}
```

## Result

`GET /v1/generations/{id}` answers `200` with the same object (with `Retry-After: 5` while it has not ended; `Prefer: wait=N` works here too). Statuses: `queued` → `running` → `succeeded`, `failed` or `canceled`; stop polling on the last three.

```json
{
  "id": "gen_6f1c0e9a2b7d4c3e8f5a1b2c3d4e5f60",
  "object": "generation",
  "model": "nanobanana",
  "mode": "v2-1",
  "status": "succeeded",
  "progress": 1,
  "cost": {
    "estimated_tokens": 12.5,
    "charged_tokens": 12.5,
    "refunded_tokens": 0,
    "settled": true
  },
  "outputs": [
    {
      "index": 0,
      "type": "image",
      "file_ref": "attachment:482913",
      "url": "https://api.unitool.ai/v1/files/q83vEjRkT1mXc0yLw2hN5aZp7dUoB9sGfI4tKeYxWrQ6/file.png",
      "content_type": "image/png",
      "width": 1024,
      "height": 1024,
      "size": 1843200,
      "expires_at": "2026-12-06T12:00:41.000Z"
    }
  ],
  "error": null,
  "metadata": {
    "order_id": "A-1042"
  },
  "created_at": "2026-11-29T12:00:00.000Z",
  "completed_at": "2026-11-29T12:00:41.000Z",
  "expires_at": "2026-12-06T12:00:41.000Z"
}
```

- `outputs[].url`: a signed link, valid for 1 hour, downloaded without a key (`GET`, `HEAD`, `Range`). Every `GET /v1/generations/{id}` issues fresh links; an expired one answers `404 file_link_expired`.
- The files are kept for 7 days, until `expires_at`. After that `outputs` is empty and `outputs_expired: true` is set. Download what you need.
- `outputs[].file_ref` passes this result to another generation as a file input; it does not expire with the link.
- `width` and `height` come with images and video, `duration_sec` with video and audio, `size` (bytes) when known.
- `outputs_filtered: N`: the model returned N variants fewer than ordered; the ordered price is charged.
- `cost.charged_tokens` minus `cost.refunded_tokens` is what the generation cost.

A failed generation is still a `200` on `GET`, with the reason in `error`:

```json
{
  "id": "gen_6f1c0e9a2b7d4c3e8f5a1b2c3d4e5f60",
  "object": "generation",
  "model": "nanobanana",
  "mode": "v2-1",
  "status": "failed",
  "progress": 0,
  "cost": {
    "estimated_tokens": 12.5,
    "charged_tokens": 12.5,
    "refunded_tokens": 12.5,
    "settled": true
  },
  "outputs": [],
  "error": {
    "code": "model_error",
    "message": "The model failed to produce a result.",
    "refund": "full"
  },
  "metadata": {
    "order_id": "A-1042"
  },
  "created_at": "2026-11-29T12:00:00.000Z",
  "completed_at": "2026-11-29T12:00:41.000Z",
  "expires_at": null
}
```

- `error.code`: `content_rejected` (moderation), `invalid_input` (the model refused the parameters or a file), `model_error`, `timeout`, `insufficient_balance` (the balance was short when the generation started), `internal_error` (the result was produced but could not be saved).
- `error.refund`: `full` (the tokens came back), `not_charged`, or `pending` (still charged, support decides; only with `internal_error`).

Also: `POST /v1/generations/{id}/cancel` (before the generation starts, else `409 not_cancellable`; answers the object), `DELETE /v1/generations/{id}` (removes the files of a finished generation; answers `{"id":"gen_...","object":"generation.deleted","deleted":true}`), `GET /v1/generations?limit=20&cursor=...&model=...&status=...` (newest first; answers `{"object":"list","data":[{"id","object","model","mode","status","metadata","created_at"}],"has_more":true,"next_cursor":"..."}`, pass `next_cursor` as `cursor`).

## Modes

The exact price of a request without running it: `POST /v1/quotes` with the same body answers `{"object":"quote","model","mode","price":{"tokens":60,...},"available_tokens":1500,"held_tokens":40,"can_afford":true,"normalized_input":{...}}`. Quotes are free. `available_tokens` is what can be spent now (as in `GET /v1/balance`), and `can_afford` compares it with the price.

How to read the "Rules" of a price: the first entry of `matrix` that matches sets the price (`when`: the request's values; `when_set` / `when_unset`: fields that are filled / empty). `price` is per generation; `rate` is multiplied by the value of the `per` parameter plus the `plus` fields (with `plus_mode: "max"` the `plus` part counts as at least the `per` value). A name ending in `_duration_sec` is the measured length in seconds of the file in the field without that ending, not a parameter to send. `addons` add `add` tokens or multiply by `multiply` when their `when` matches; `per_item` adds per list item, `per_text` per 1000 characters beyond `free_chars`. More: https://unitool.ai/en/developers/pricing.md#reading-the-price-rules

### Mode `v2-1` (Nano Banana 2.1)

- price: depends on parameters; 12.5 balance tokens for the example below, base 12.5. In short: 1K — 12.5 · 2K — 18.75 · 4K — 25 balance tokens per image, multiplied by num_images; +2.34 when search_mode is web, images, both. Rules (in order, the first match sets the price): {"matrix":[{"when":{"resolution":"1K","num_images":1,"search_mode":"off"},"price":12.5},{"when":{"resolution":"1K","num_images":1,"search_mode":"web"},"price":14.84},{"when":{"resolution":"1K","num_images":1,"search_mode":"images"},"price":14.84},{"when":{"resolution":"1K","num_images":1,"search_mode":"both"},"price":14.84},{"when":{"resolution":"1K","num_images":2,"search_mode":"off"},"price":25},{"when":{"resolution":"1K","num_images":2,"search_mode":"web"},"price":29.68},{"when":{"resolution":"1K","num_images":2,"search_mode":"images"},"price":29.68},{"when":{"resolution":"1K","num_images":2,"search_mode":"both"},"price":29.68},{"when":{"resolution":"1K","num_images":3,"search_mode":"off"},"price":37.5},{"when":{"resolution":"1K","num_images":3,"search_mode":"web"},"price":44.52},{"when":{"resolution":"1K","num_images":3,"search_mode":"images"},"price":44.52},{"when":{"resolution":"1K","num_images":3,"search_mode":"both"},"price":44.52},{"when":{"resolution":"1K","num_images":4,"search_mode":"off"},"price":50},{"when":{"resolution":"1K","num_images":4,"search_mode":"web"},"price":59.36},{"when":{"resolution":"1K","num_images":4,"search_mode":"images"},"price":59.36},{"when":{"resolution":"1K","num_images":4,"search_mode":"both"},"price":59.36},{"when":{"resolution":"2K","num_images":1,"search_mode":"off"},"price":18.75},{"when":{"resolution":"2K","num_images":1,"search_mode":"web"},"price":21.09},{"when":{"resolution":"2K","num_images":1,"search_mode":"images"},"price":21.09},{"when":{"resolution":"2K","num_images":1,"search_mode":"both"},"price":21.09},{"when":{"resolution":"2K","num_images":2,"search_mode":"off"},"price":37.5},{"when":{"resolution":"2K","num_images":2,"search_mode":"web"},"price":42.18},{"when":{"resolution":"2K","num_images":2,"search_mode":"images"},"price":42.18},{"when":{"resolution":"2K","num_images":2,"search_mode":"both"},"price":42.18},{"when":{"resolution":"2K","num_images":3,"search_mode":"off"},"price":56.25},{"when":{"resolution":"2K","num_images":3,"search_mode":"web"},"price":63.27},{"when":{"resolution":"2K","num_images":3,"search_mode":"images"},"price":63.27},{"when":{"resolution":"2K","num_images":3,"search_mode":"both"},"price":63.27},{"when":{"resolution":"2K","num_images":4,"search_mode":"off"},"price":75},{"when":{"resolution":"2K","num_images":4,"search_mode":"web"},"price":84.36},{"when":{"resolution":"2K","num_images":4,"search_mode":"images"},"price":84.36},{"when":{"resolution":"2K","num_images":4,"search_mode":"both"},"price":84.36},{"when":{"resolution":"4K","num_images":1,"search_mode":"off"},"price":25},{"when":{"resolution":"4K","num_images":1,"search_mode":"web"},"price":27.34},{"when":{"resolution":"4K","num_images":1,"search_mode":"images"},"price":27.34},{"when":{"resolution":"4K","num_images":1,"search_mode":"both"},"price":27.34},{"when":{"resolution":"4K","num_images":2,"search_mode":"off"},"price":50},{"when":{"resolution":"4K","num_images":2,"search_mode":"web"},"price":54.68},{"when":{"resolution":"4K","num_images":2,"search_mode":"images"},"price":54.68},{"when":{"resolution":"4K","num_images":2,"search_mode":"both"},"price":54.68},{"when":{"resolution":"4K","num_images":3,"search_mode":"off"},"price":75},{"when":{"resolution":"4K","num_images":3,"search_mode":"web"},"price":82.02},{"when":{"resolution":"4K","num_images":3,"search_mode":"images"},"price":82.02},{"when":{"resolution":"4K","num_images":3,"search_mode":"both"},"price":82.02},{"when":{"resolution":"4K","num_images":4,"search_mode":"off"},"price":100},{"when":{"resolution":"4K","num_images":4,"search_mode":"web"},"price":109.36},{"when":{"resolution":"4K","num_images":4,"search_mode":"images"},"price":109.36},{"when":{"resolution":"4K","num_images":4,"search_mode":"both"},"price":109.36}]}. Exact price of a request: POST /v1/quotes

```bash
curl https://api.unitool.ai/v1/generations \
  -H "Authorization: Bearer $UNITOOL_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Prefer: wait=60" \
  -d '{"model":"nanobanana","mode":"v2-1","input":{"prompt":"A red fox running through fresh snow at sunrise","aspect_ratio":"auto","resolution":"1K","num_images":1,"thinking_level":"minimal","search_mode":"off"}}'
```

| `input` field | Type | Required | Values | Default | Notes |
|---|---|---|---|---|---|
| `prompt` | string | yes |  |  |  |
| `aspect_ratio` | string | no | `auto`, `1:1`, `16:9`, `4:3`, `3:2`, `9:16`, `3:4`, `2:3`, `4:5`, `21:9`, `5:4`, `4:1`, `1:4`, `8:1`, `1:8` | `"auto"` |  |
| `resolution` | string | no | `1K`, `2K`, `4K` | `"1K"` |  |
| `num_images` | number 1–4 | no |  | `1` |  |
| `thinking_level` | string | no | `minimal`, `medium`, `high` | `"minimal"` |  |
| `search_mode` | string | no | `off`, `web`, `images`, `both` | `"off"` |  |
| `image_urls` | array of file (≤ 14) | no |  |  | A file_ref (asset:… or attachment:…), an https URL or a data: URL. |

### Mode `v2` (Nano Banana 2)

- price: depends on parameters; 12.5 balance tokens for the example below, base 12.5. In short: 0.5K — 9.375 · 1K — 12.5 · 2K — 18.75 · 4K — 25 balance tokens per image, multiplied by num_images. Rules (in order, the first match sets the price): {"matrix":[{"when":{"resolution":"0.5K","num_images":1},"price":9.38},{"when":{"resolution":"0.5K","num_images":2},"price":18.75},{"when":{"resolution":"0.5K","num_images":3},"price":28.13},{"when":{"resolution":"0.5K","num_images":4},"price":37.5},{"when":{"resolution":"1K","num_images":1},"price":12.5},{"when":{"resolution":"1K","num_images":2},"price":25},{"when":{"resolution":"1K","num_images":3},"price":37.5},{"when":{"resolution":"1K","num_images":4},"price":50},{"when":{"resolution":"2K","num_images":1},"price":18.75},{"when":{"resolution":"2K","num_images":2},"price":37.5},{"when":{"resolution":"2K","num_images":3},"price":56.25},{"when":{"resolution":"2K","num_images":4},"price":75},{"when":{"resolution":"4K","num_images":1},"price":25},{"when":{"resolution":"4K","num_images":2},"price":50},{"when":{"resolution":"4K","num_images":3},"price":75},{"when":{"resolution":"4K","num_images":4},"price":100}]}. Exact price of a request: POST /v1/quotes

```bash
curl https://api.unitool.ai/v1/generations \
  -H "Authorization: Bearer $UNITOOL_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Prefer: wait=60" \
  -d '{"model":"nanobanana","mode":"v2","input":{"prompt":"A red fox running through fresh snow at sunrise","aspect_ratio":"auto","resolution":"1K","num_images":1,"output_format":"jpeg"}}'
```

| `input` field | Type | Required | Values | Default | Notes |
|---|---|---|---|---|---|
| `prompt` | string | yes |  |  |  |
| `aspect_ratio` | string | no | `auto`, `1:1`, `16:9`, `4:3`, `3:2`, `9:16`, `3:4`, `2:3`, `4:5`, `21:9` | `"auto"` |  |
| `resolution` | string | no | `0.5K`, `1K`, `2K`, `4K` | `"1K"` |  |
| `num_images` | number 1–4 | no |  | `1` |  |
| `output_format` | string | no | `jpeg`, `png`, `webp` | `"jpeg"` |  |
| `image_urls` | array of file (≤ 9) | no |  |  | A file_ref (asset:… or attachment:…), an https URL or a data: URL. |

### Mode `v1` (Nano Banana 1)

- price: depends on parameters; 6.25 balance tokens for the example below, base 6.25. In short: without usePro — 6.25 · with usePro — 31.25 balance tokens per image, multiplied by num_images. Rules (in order, the first match sets the price): {"matrix":[{"when":{"num_images":1},"when_unset":["usePro"],"price":6.25},{"when":{"num_images":2},"when_unset":["usePro"],"price":12.5},{"when":{"num_images":3},"when_unset":["usePro"],"price":18.75},{"when":{"num_images":4},"when_unset":["usePro"],"price":25},{"when":{"usePro":true,"num_images":1},"price":31.25},{"when":{"usePro":true,"num_images":2},"price":62.5},{"when":{"usePro":true,"num_images":3},"price":93.75},{"when":{"usePro":true,"num_images":4},"price":125}]}. Exact price of a request: POST /v1/quotes

```bash
curl https://api.unitool.ai/v1/generations \
  -H "Authorization: Bearer $UNITOOL_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Prefer: wait=60" \
  -d '{"model":"nanobanana","mode":"v1","input":{"prompt":"A red fox running through fresh snow at sunrise","aspect_ratio":"1:1","resolution":"1K","num_images":1,"output_format":"jpeg"}}'
```

| `input` field | Type | Required | Values | Default | Notes |
|---|---|---|---|---|---|
| `prompt` | string | yes |  |  |  |
| `aspect_ratio` | string | no | `1:1`, `16:9`, `4:3`, `9:16`, `3:4` | `"1:1"` |  |
| `resolution` | string | no | `1K`, `2K`, `4K` | `"1K"` |  |
| `num_images` | number 1–4 | no |  | `1` |  |
| `usePro` | boolean | no |  | `false` |  |
| `output_format` | string | no | `jpeg`, `png`, `webp` | `"jpeg"` |  |
| `image_urls` | array of file (≤ 9) | no |  |  | A file_ref (asset:… or attachment:…), an https URL or a data: URL. |

## File inputs

A field of type `file` takes one of:

- an https link (public host, default port); the file is downloaded before the run: up to 100 MiB, 60 seconds, 3 redirects;
- a base64 `data:` URL;
- a `file_ref`: `attachment:...` from the `outputs` of an earlier generation, or `asset:...` of an upload.

At most 10 links and `data:` URLs per request. A local file: `POST /v1/uploads` with `{"name":"frame.png","mime_type":"image/png","size":482133}` answers `{"object":"upload","file_ref":"asset:...","upload_url":"https://...","method":"PUT","headers":{...},"upload_expires_at":"...","expires_at":"..."}`. `PUT` the bytes to `upload_url` with exactly the returned `headers` within 10 minutes (the size must equal the declared `size`), then pass `file_ref` in the field. Limits: images 20 MiB, audio and video 100 MiB.

File refusals, all `400`: `file_not_found` (the upload has no bytes yet), `file_unreadable`, `file_expired`, `file_too_large`, `unsupported_file_type`, `file_download_failed`.

## Client

Create, wait, poll and download in Python (`pip install requests`), mode `v2-1`:

```python
import json, mimetypes, os, time, uuid, requests

API = "https://api.unitool.ai/v1"
KEY = {"Authorization": f"Bearer {os.environ['UNITOOL_API_KEY']}"}

def call(method, path, headers=None, retries=3, **kwargs):
    for attempt in range(retries + 1):
        reply = requests.request(method, API + path, headers={**KEY, **(headers or {})}, timeout=90, **kwargs)
        if reply.status_code in (429, 500, 502, 503, 504) and attempt < retries:
            time.sleep(float(reply.headers.get("Retry-After", 2 ** attempt)))
            continue
        if reply.status_code >= 400:
            error = reply.json()["error"]
            raise RuntimeError(f"{reply.status_code} {error['code']}: {error['message']} ({error['request_id']})")
        return reply

body = json.loads(r'''{
  "model": "nanobanana",
  "mode": "v2-1",
  "input": {
    "prompt": "A red fox running through fresh snow at sunrise",
    "aspect_ratio": "auto",
    "resolution": "1K",
    "num_images": 1,
    "thinking_level": "minimal",
    "search_mode": "off"
  }
}''')
# One key per order: a retry with the same key and body returns the same generation and charges nothing again.
order = {"Idempotency-Key": str(uuid.uuid4()), "Prefer": "wait=60"}
generation = call("POST", "/generations", headers=order, json=body).json()
while generation["status"] in ("queued", "running"):
    time.sleep(5)
    generation = call("GET", f"/generations/{generation['id']}").json()

if generation["status"] == "succeeded":
    for output in generation["outputs"]:  # the links live 1 hour, the files 7 days: download now
        name = f"{generation['id']}-{output['index']}{mimetypes.guess_extension(output['content_type']) or ''}"
        open(name, "wb").write(requests.get(output["url"], timeout=300).content)
elif generation["status"] == "failed":
    print(generation["error"]["code"], generation["error"]["message"], "refund:", generation["error"]["refund"])
```

## Webhook

Instead of polling, pass `"webhook_url": "https://your.host/path"` in the create request (https, default port, a public host name, not an IP address; a bad address is `400 invalid_parameter` before anything is created or charged), or register an endpoint for all generations in the account (Settings → API → Webhooks). When the generation ends, this is POSTed to the address:

```json
{
  "type": "generation.succeeded",
  "timestamp": "2026-11-29T12:00:41.000Z",
  "data": {
    "id": "gen_6f1c0e9a2b7d4c3e8f5a1b2c3d4e5f60",
    "object": "generation",
    "model": "nanobanana",
    "mode": "v2-1",
    "status": "succeeded",
    "progress": 1,
    "cost": {
      "estimated_tokens": 12.5,
      "charged_tokens": 12.5,
      "refunded_tokens": 0,
      "settled": true
    },
    "outputs": [
      {
        "index": 0,
        "type": "image",
        "file_ref": "attachment:482913",
        "url": "https://api.unitool.ai/v1/files/q83vEjRkT1mXc0yLw2hN5aZp7dUoB9sGfI4tKeYxWrQ6/file.png",
        "content_type": "image/png",
        "width": 1024,
        "height": 1024,
        "size": 1843200,
        "expires_at": "2026-12-06T12:00:41.000Z"
      }
    ],
    "error": null,
    "metadata": {
      "order_id": "A-1042"
    },
    "created_at": "2026-11-29T12:00:00.000Z",
    "completed_at": "2026-11-29T12:00:41.000Z",
    "expires_at": "2026-12-06T12:00:41.000Z"
  }
}
```

- `type`: `generation.succeeded` or `generation.failed` (`generation.canceled` goes to registered endpoints only). `data` is the object `GET /v1/generations/{id}` returns; match it by `data.id` or `data.metadata`.
- Headers: `webhook-id` (`msg_...`, the same on every retry: drop duplicates by it), `webhook-timestamp` (Unix seconds), `webhook-signature` (`v1,<base64 HMAC-SHA256>`; two values separated by a space while a secret is rotated).
- Signature ([Standard Webhooks](https://www.standardwebhooks.com/)): HMAC-SHA256 of `{webhook-id}.{webhook-timestamp}.{raw body}`, the key being the base64-decoded part of the secret after `whsec_`. For `webhook_url` the secret is the account secret (Settings → API → Webhooks, "Show the account secret"); a registered endpoint has its own. The API never returns a secret.
- Answer 2xx within 10 seconds and do the work afterwards. A failed delivery to a `webhook_url` is retried in 5 s, 30 s, 2 min and 10 min (5 attempts). Delivery is at least once and unordered.
- Links in the event live 1 hour from the event. An event can be lost: for important orders also poll the generations whose event did not arrive.

```python
import base64, hashlib, hmac, time

def verify(raw_body: bytes, headers, secret: str) -> bool:
    """secret: whsec_... (the account secret for webhook_url, the endpoint's own for a registered endpoint)."""
    msg_id, ts = headers["webhook-id"], headers["webhook-timestamp"]
    if abs(time.time() - int(ts)) > 300:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    expected = hmac.new(key, f"{msg_id}.{ts}.".encode() + raw_body, hashlib.sha256).digest()
    return any(hmac.compare_digest(base64.b64decode(part.split(",", 1)[1]), expected)
               for part in headers["webhook-signature"].split(" ") if "," in part)
```

## Errors and retries

A refused request answers with a non-2xx status and one shape:

```json
{
  "error": {
    "type": "invalid_request_error",
    "code": "invalid_parameter",
    "message": "Text for a person; it may change.",
    "param": "max_tokens",
    "request_id": "req_01KB7Q3X9ZP4M6T2VHC8RN5WDE",
    "doc_url": "https://unitool.ai/en/developers/errors#invalid_parameter"
  }
}
```

Branch on `error.code`, it is stable. `error.param` names the field at fault or is `null`; some codes add `error.details`. Retry only 429, 500, 502, 503 and 504.

| HTTP | `error.code` | What to do |
|---|---|---|
| 400 | `invalid_parameter`, `missing_parameter` | Fix the field named in `error.param` (for example `input.duration`). Do not retry |
| 400 | `use_chat_endpoint` | The id is a text model: call `/v1/chat/completions` |
| 401 | `invalid_api_key`, `api_key_revoked` | Fix the key. Do not retry |
| 402 | `insufficient_balance`, `price_exceeds_limit`, `key_spend_limit_reached` | Top up, raise `max_cost_tokens`, or wait for the key's limit to reset. Nothing was charged |
| 403 | `insufficient_scope`, `payment_required`, `api_access_not_enabled`, `account_suspended`, `ip_not_allowed` | The key or the account may not do this. Do not retry |
| 404 | `model_not_found`, `generation_not_found` | No such model, mode or generation |
| 409 | `not_cancellable`, `generation_not_finished` | The generation has started (cancel) or has not ended (delete) |
| 410 | `model_retired` | The model left the API; `error.details.replacement` names the successor when there is one |
| 422 | `idempotency_key_reused` | The `Idempotency-Key` was used with another body: use a new key |
| 429 | `webhook_daily_limit` | Over 2000 per-request webhooks today: register an endpoint or poll. Do not retry today |
| 429 | `rate_limit_exceeded`, `concurrency_limit_exceeded`, `balance_held` | Wait `Retry-After` seconds, then retry |
| 500 | `internal_error` | Retry with backoff, 2 or 3 attempts |
| 503 | `overloaded`, `model_unavailable`, `service_paused` | Wait `Retry-After` seconds, then retry (or use another model) |

Retry creation only with the same `Idempotency-Key`. More generations than the account runs at once are not refused: they wait in `queued`.

Every code: https://unitool.ai/en/developers/errors.md. Limits and headers: https://unitool.ai/en/developers/rate-limits.md.

## More

- Generations (uploads, retention, delete, cancel): https://unitool.ai/en/developers/generations.md
- Webhooks (endpoints, retries, secret rotation): https://unitool.ai/en/developers/webhooks.md
- The same model in the OpenAI format (`/v1/images/generations`, `/v1/images/edits`, `/v1/audio/speech`): https://unitool.ai/en/developers/images-audio.md
- Prices: https://unitool.ai/en/developers/pricing.md
- Everything in one file: https://unitool.ai/llms-full.txt
