# GPT-Image 2.5 (`gpt-image`)

> Image model `gpt-image` by OpenAI 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/gpt-image`. Docs index: https://unitool.ai/llms.txt.

## Facts

- id: `gpt-image`
- name: GPT-Image 2.5
- type: image
- vendor: OpenAI
- price from: 8 balance tokens per generation
- modes: `generate`. Without a mode in the request the first one (`generate`) 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 | `"gpt-image"`, or with the mode: `"gpt-image:generate"` |
| `mode` | string | One of `generate`, 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": "gpt-image",
  "mode": "generate",
  "status": "queued",
  "progress": 0,
  "cost": {
    "estimated_tokens": 8,
    "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": "gpt-image",
  "mode": "generate",
  "status": "succeeded",
  "progress": 1,
  "cost": {
    "estimated_tokens": 8,
    "charged_tokens": 8,
    "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": 576,
      "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": "gpt-image",
  "mode": "generate",
  "status": "failed",
  "progress": 0,
  "cost": {
    "estimated_tokens": 8,
    "charged_tokens": 8,
    "refunded_tokens": 8,
    "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 `generate` (GPT Image)

- price: depends on parameters; 8 balance tokens for the example below, base 8. In short: 1K — 8 · 2K — 11 · 4K — 14 balance tokens per image. Rules (in order, the first match sets the price): {"matrix":[{"when":{"resolution":"1K"},"price":8},{"when":{"resolution":"2K"},"price":11},{"when":{"resolution":"4K"},"price":14}]}. 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":"gpt-image","mode":"generate","input":{"prompt":"A red fox running through fresh snow at sunrise","variant":"flare","aspect_ratio":"16:9","resolution":"1K","background":"auto"}}'
```

| `input` field | Type | Required | Values | Default | Notes |
|---|---|---|---|---|---|
| `prompt` | string | yes |  |  |  |
| `variant` | string | no | `flare`, `sunburst` | `"flare"` |  |
| `aspect_ratio` | string | no | `auto`, `1:1`, `4:3`, `16:9`, `3:4`, `9:16` | `"16:9"` |  |
| `resolution` | string | no | `1K`, `2K`, `4K` | `"1K"` |  |
| `background` | string | no | `auto`, `transparent`, `opaque` | `"auto"` |  |
| `input_urls` | array of file (≤ 6) | 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 `generate`:

```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": "gpt-image",
  "mode": "generate",
  "input": {
    "prompt": "A red fox running through fresh snow at sunrise",
    "variant": "flare",
    "aspect_ratio": "16:9",
    "resolution": "1K",
    "background": "auto"
  }
}''')
# 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": "gpt-image",
    "mode": "generate",
    "status": "succeeded",
    "progress": 1,
    "cost": {
      "estimated_tokens": 8,
      "charged_tokens": 8,
      "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": 576,
        "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
