# Generation

> Start, wait for and manage AI Generator jobs: models, options, references, idempotency and refusals.

Generate only when a [search](https://imgsearch.com/developers/search-first.md) found nothing that fits. Generating spends AI balance, so it needs a key with `generate` (see [spending](https://imgsearch.com/developers/authentication.md#spending)) and an account that [can generate](https://imgsearch.com/developers/authentication.md#who-can-generate). Everything the website checks before a generation, the API checks too: the same models, prices, content checks and limits.


## Kinds

| `kind` | What it makes |
|---|---|
| `image` | Pictures, from a prompt and optionally one reference picture |
| `video` | Clips, from a prompt and optionally a first frame (or, on Kling, a reference) |
| `audio` | Voiceovers: the prompt is the script, spoken in `options.voice` |
| `meme` | A text-free scene; its captions come back for you to draw ([memes](https://imgsearch.com/developers/generation.md#memes)) |
| `music` | Tracks, instrumental or with lyrics |
| `sound` | Sound effects from a description, at the length in `options.duration` (2 to 30 s) |
| `3d` | A 3D model (GLB) from a picture, sent as the reference |
| `vector` | SVG illustrations |

## Models and options

Each kind has a default model, used when you leave `model` out. `GET /models?kind=` lists the models with their price range; `GET /models/{id}` gives a model’s options (values and defaults) and its price table per kind, in US dollars. The [models](https://imgsearch.com/developers/models.md) page shows the same, live. Options you leave out take the model’s defaults.

Paused models (`paused: true`) are failing at their provider right now; a request for one answers `503 model_paused` with `details.alternative`.

`POST /generations` and `/generations/estimate` refuse (`422 invalid_request`) a top-level field they don’t take, named in `details.fields` (`quote` points to `/generations/estimate`), a model not listed for the kind ("Send a model id from /v2/models?kind=image, or leave it out for the kind's default."), and an option key the model doesn’t take (`details.fields."options.<key>"`).

## Starting one

Check the price first with `POST /generations/estimate`: the same body without `max_usd`. Its `price_usd` is what `POST /generations` charges. It writes and charges nothing, and says whether this key could start it now (`can_generate`, `reason`).

`POST /generations` takes:

| Field | What it is |
|---|---|
| `kind` | One of the kinds above |
| `model` | A model id; the kind’s default when left out |
| `prompt` | What to make (for a voiceover, the script) |
| `options` | The model’s options, as `GET /models/{id}` lists them |
| `reference` | At most one picture to start from ([references](https://imgsearch.com/developers/generation.md#references)) |
| `max_usd` | Required: the most the user allows this to cost, in US dollars (at most three decimals) |

and the header `Idempotency-Key`: a value of your own, 1 to 255 printable ASCII characters, new for every new request. Keep it until you have the answer.

**curl**

```bash
# Starts a generation. max_usd is the most the user allows it to cost, in US dollars.
# Needs IMGSEARCH_API_KEY.
# To retry this same request without paying twice, run it again with the same IDEMPOTENCY_KEY.
IDEMPOTENCY_KEY="${IDEMPOTENCY_KEY:-$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)}"
echo "Idempotency-Key: $IDEMPOTENCY_KEY" >&2
curl -sS -X POST \
  "${IMGSEARCH_API_BASE:-https://imgsearch.com/api/v2}/generations" \
  -H "Authorization: Bearer $IMGSEARCH_API_KEY" \
  -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "kind": "image",
  "model": "openai/gpt-image-2.5-sunburst",
  "prompt": "A red fox standing in fresh snow at sunrise, wide shot, empty space on the left for a headline",
  "options": {
    "aspect_ratio": "16:9"
  },
  "max_usd": 0.02
}'
```

**Python**

```python
# Starts a generation. max_usd is the most the user allows it to cost, in US dollars.
# Needs IMGSEARCH_API_KEY.
import json
import os
import sys
import uuid

import httpx

base = os.environ.get("IMGSEARCH_API_BASE", "https://imgsearch.com/api/v2")
# To retry this same request without paying twice, run it again with the same IDEMPOTENCY_KEY.
idempotency_key = os.environ.get("IDEMPOTENCY_KEY") or str(uuid.uuid4())
print("Idempotency-Key:", idempotency_key, file=sys.stderr)
headers = {"Authorization": f"Bearer {os.environ['IMGSEARCH_API_KEY']}", "Idempotency-Key": idempotency_key}

r = httpx.post(
    f"{base}/generations",
    headers=headers,
    json={
        "kind": "image",
        "model": "openai/gpt-image-2.5-sunburst",
        "prompt": "A red fox standing in fresh snow at sunrise, wide shot, empty space on the left for a headline",
        "options": {"aspect_ratio": "16:9"},
        "max_usd": 0.02,
    },
    timeout=60,
)
print(r.status_code)
print(json.dumps(r.json(), indent=2))
```

**JavaScript**

```js
// Starts a generation. max_usd is the most the user allows it to cost, in US dollars.
// Needs IMGSEARCH_API_KEY.
const base = process.env.IMGSEARCH_API_BASE ?? "https://imgsearch.com/api/v2";
// To retry this same request without paying twice, run it again with the same IDEMPOTENCY_KEY.
const idempotencyKey = process.env.IDEMPOTENCY_KEY || crypto.randomUUID();
console.error("Idempotency-Key:", idempotencyKey);

const r = await fetch(`${base}/generations`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.IMGSEARCH_API_KEY}`,
    "Idempotency-Key": idempotencyKey,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    kind: "image",
    model: "openai/gpt-image-2.5-sunburst",
    prompt: "A red fox standing in fresh snow at sunrise, wide shot, empty space on the left for a headline",
    options: { aspect_ratio: "16:9" },
    max_usd: 0.02,
  }),
});
console.log(r.status);
console.log(JSON.stringify(await r.json(), null, 2));
```

**Response 201**

```json
{
    "object": "generation",
    "id": "01m8bky93c0jbbax10h5qnjj0m",
    "kind": "image",
    "model": "local/echo",
    "model_name": "Local echo (test)",
    "prompt": "A red fox standing in fresh snow at sunrise, wide shot, empty space on the left for a headline",
    "title": null,
    "starred": false,
    "options": {
        "count": 1,
        "style": "none",
        "aspect_ratio": "16:9"
    },
    "status": "queued",
    "created_at": "2026-11-26T09:45:43Z",
    "started_at": null,
    "finished_at": null,
    "estimate_seconds": 3,
    "poll_after_seconds": 2,
    "waiting": {
        "reason": "busy",
        "ahead": 0
    },
    "error": null,
    "notice": null,
    "quoted_usd": 0.01,
    "charged_usd": 0.01,
    "refunded_usd": 0,
    "reference": null,
    "outputs": [],
    "exports": null,
    "soundtrack": null,
    "voiceover_video": null
}
```

- **201** with `Location`: started, and the price is charged now. A failed generation is refunded in full.
- **200** with `Idempotent-Replayed: true`: the same key and the same body again. It answers the same generation as it is now and charges nothing. Retry a request that timed out or failed in transit with the same key.
- **409 `idempotency_conflict`**: the same key with a different body. `details.generation_id` is the generation the key belongs to. Use a new key for a new request.
- **409 `price_above_max`**: the price is above `max_usd` (`details.price_usd`). Nothing was charged. Ask the user before sending a higher `max_usd`.

Deleting a generation frees its key. Allow at least 30 seconds for the call: the content checks run before it answers.

> The example answers come from a local test server, where generation uses the test model `local/echo`. Ids, times, models and prices in your answers will differ.

## References

`reference` holds one of:

| Form | What it is |
|---|---|
| `{"generation": {"id": "…", "n": 0}}` | One of your own pictures (output `n` of a generation) |
| `{"photo": {"slug": "…"}}` | A catalogue photo, for a clip only. It counts as a photo download under fair use (checked first; an owned photo is free) |
| `{"upload_id": "upl_…"}` | A picture you uploaded with `POST /uploads`, within 60 minutes; an unknown or expired id answers 404 `not_found`, so upload it again |
| `{"url": "https://…"}` | A picture at an https address, fetched once by ImgSearch |

A clip’s picture is its first frame. On Kling 4.0 and 4.0 Flash, `options.picture_role` `reference` uses it as a reference instead: its subject (a character, a pet, a product) appears in a new scene the prompt describes, at the `aspect_ratio` you pick, so the prompt is required. `first_frame` is the default.

A clip from one of your pictures:

```json
{
  "kind": "video",
  "prompt": "The fox turns its head toward the camera as snow falls",
  "reference": {"generation": {"id": "01m6v1pm05dkbzdtxz90gjjr3h", "n": 0}},
  "options": {"duration": 5, "resolution": "480p"},
  "max_usd": 0.4
}
```

A picture edited from an upload:

```json
{
  "kind": "image",
  "prompt": "The same scene in a watercolor style",
  "reference": {"upload_id": "upl_01m6v1ph7vfsey82nrmr8xpp33"},
  "max_usd": 0.06
}
```

Uploads and addresses:

- `POST /uploads` takes a JPEG, PNG or WebP of 64 to 4,096 pixels a side and at most 10 MB, as the multipart field `file` ([reference](https://imgsearch.com/developers/reference/generations.md#uploads.store)). It needs a key that may spend.
- A `url` must be https on port 443 and resolve to public addresses only. No redirects are followed, and the file must arrive within 10 seconds and 10 MB. It passes the same checks as an upload, and a refusal answers `422 invalid_request` with `details.fields` naming `reference.url`.
- Before a URL is fetched, the request must fit `max_usd`, the account’s balance and the key’s limit at its lowest possible price, so a request that would be refused anyway never makes ImgSearch fetch anything.
- Uploads and URLs must be pictures the account holder has the rights to use, with everyone in them (or their parent or guardian) agreeing. The account holder confirms this once, on the website, when allowing a key to spend.

Each model takes references only where its kind does: see `accepts_reference` in `GET /models`.

## Waiting

A new generation is `queued`, then `running`, then `succeeded`, `failed` or `canceled`.

- Read it with `GET /generations/{id}` after `poll_after_seconds` (2 to 30 seconds) while it is queued or running. `waiting` says why it waits (`account`: your other generations run first; `slow` or `busy`: the Generator is full) and how many are `ahead`.
- Send the last `ETag` as `If-None-Match` to get `304` with no body while nothing changed.
- To poll several at once, `GET /generations?ids=a,b,c` (up to 20) answers them in that order.
- Or receive `generation.succeeded`, `generation.failed` and `generation.canceled` events by [webhook](https://imgsearch.com/developers/webhooks.md), or read them from the events feed.

**curl**

```bash
# One generation. Read it again after poll_after_seconds while it is queued or running.
# Needs IMGSEARCH_API_KEY and GENERATION_ID.
curl -sS \
  "${IMGSEARCH_API_BASE:-https://imgsearch.com/api/v2}/generations/$GENERATION_ID" \
  -H "Authorization: Bearer $IMGSEARCH_API_KEY"
```

**Python**

```python
# One generation. Read it again after poll_after_seconds while it is queued or running.
# Needs IMGSEARCH_API_KEY and GENERATION_ID.
import json
import os

import httpx

base = os.environ.get("IMGSEARCH_API_BASE", "https://imgsearch.com/api/v2")
headers = {"Authorization": f"Bearer {os.environ['IMGSEARCH_API_KEY']}"}

r = httpx.get(f"{base}/generations/{os.environ['GENERATION_ID']}", headers=headers, timeout=60)
print(r.status_code, r.headers.get("etag"))
print(json.dumps(r.json(), indent=2))
```

**JavaScript**

```js
// One generation. Read it again after poll_after_seconds while it is queued or running.
// Needs IMGSEARCH_API_KEY and GENERATION_ID.
const base = process.env.IMGSEARCH_API_BASE ?? "https://imgsearch.com/api/v2";

const r = await fetch(`${base}/generations/${process.env.GENERATION_ID}`, {
  headers: { Authorization: `Bearer ${process.env.IMGSEARCH_API_KEY}` },
});
console.log(r.status, r.headers.get("etag"));
console.log(JSON.stringify(await r.json(), null, 2));
```

**Response 200**

```json
{
    "object": "generation",
    "id": "01m8bky93c0jbbax10h5qnjj0m",
    "kind": "image",
    "model": "local/echo",
    "model_name": "Local echo (test)",
    "prompt": "A red fox standing in fresh snow at sunrise, wide shot, empty space on the left for a headline",
    "title": null,
    "starred": false,
    "options": {
        "count": 1,
        "style": "none",
        "aspect_ratio": "16:9"
    },
    "status": "succeeded",
    "created_at": "2026-11-26T09:45:43Z",
    "started_at": "2026-11-26T09:45:43Z",
    "finished_at": "2026-11-26T09:45:44Z",
    "estimate_seconds": 3,
    "poll_after_seconds": null,
    "waiting": null,
    "error": null,
    "notice": null,
    "quoted_usd": 0.01,
    "charged_usd": 0.01,
    "refunded_usd": 0,
    "reference": null,
    "outputs": [
        {
            "n": 0,
            "mime": "image/png",
            "width": 1344,
            "height": 768,
            "duration": null,
            "bytes": 6627,
            "triangles": null,
            "lyrics": null,
            "file_url": "https://imgsearch.com/api/v2/generation-files/EXAMPLE-SIGNED-LINK",
            "download_url": "https://imgsearch.com/api/v2/generation-files/EXAMPLE-SIGNED-LINK",
            "expires_at": "2026-11-26T09:55:44Z",
            "upscale": {
                "width": 2688,
                "height": 1536,
                "price_usd": 0.006
            },
            "upscaled": null
        }
    ],
    "exports": null,
    "soundtrack": null,
    "voiceover_video": null
}
```

A failed generation has `error.code`: `model_refused` or `output_blocked` (the model or our output check refused the content; do not retry it as it is), `canceled`, or `generation_failed` (the only one worth retrying, with `error.retryable: true`). `refunded_usd` shows what came back.

## Files

Each output has `file_url` and `download_url` (the same file as an attachment), valid for 10 minutes for this account and the key that read them (`expires_at`). Read the generation again for fresh links. They need no key, so you can hand one to a browser or another process.

With the key, `GET /generations/{id}/outputs/{n}` serves the same file. `n` is the output’s own `n`, counting from 0, so a generation’s only output is `outputs/0`:

- `download=1` sends it as an attachment.
- `format=png` gives an SVG as PNG; `format=wav` a track as WAV.
- A 3D model’s exports by `format` and `height`, once they are made.
- `n` can also be `soundtrack`, or `video-clip`, `video-loop`, `video-bounce` or `video-hold` for a voiceover laid on a clip.

## Side actions

Free, and run on ImgSearch’s workers. Each answers `202` while it is being made (call it again, or wait for its event) and `200` once ready, with `status` `running`, `succeeded` or `failed`.

| Call | What it does |
|---|---|
| `POST /generations/{id}/exports` | A 3D model as `fbx`, `obj`, `usdz`, `glb` or `glb-1k`, optionally at `height_m` (0.05 to 100). `GET /generations/{id}/exports/{key}` reads one (`fbx-asis`, `glb-1.80`) |
| `POST /generations/{id}/ar` | View in AR links for iOS Quick Look and Android Scene Viewer, valid 30 minutes |
| `POST /generations/{id}/soundtrack` | One of your tracks (`music_id`) on a clip, optionally with a voiceover (`voice_id`), volume, fades and ducking |
| `POST /generations/{id}/voiceover-video` | A finished voiceover laid on one of your clips (`video_id`) |

## Upscale

`POST /generations/{id}/upscale` makes a picture twice as large, as a new generation. Each picture output says what it would make and cost in `upscale` (`width`, `height`, `price_usd`); `upscale` is null when the picture is too large or not a picture. It spends AI balance, so it takes `max_usd` and an `Idempotency-Key` like `POST /generations`, plus `n`, the output to upscale. A picture already upscaled, or being upscaled, answers `200` with that generation and charges nothing.

## Memes

A meme comes back as a text-free scene: the model never draws the words. The captions are in `options.captions`, for you to draw on top. `PATCH /generations/{id}` changes a meme’s `captions` and `layout` (`classic`, `modern`, `subtitle` or `labels`), checked as the website checks them. The same call renames (`title`) or stars (`starred`) any generation.

## Cancel and delete

- `POST /generations/{id}/cancel` cancels a generation that is still `queued`. Its price comes back in full. Once it runs, it answers `409 not_cancelable`.
- `DELETE /generations/{id}` deletes a finished generation and its files, and frees its `Idempotency-Key`. While it is queued or running it answers `409 still_running`. Deleting gives nothing back and does not lower a key’s monthly spending count.

## Refusals

| Code | What to do |
|---|---|
| `content_refused` (422) | Tell the user what was refused (`details.field`). Never rephrase or retry it on your own. |
| `price_above_max` (409) | Ask the user before sending a higher `max_usd`. |
| `insufficient_balance` (402) | Tell the user; `details` says how much is needed and available, in US dollars. |
| `plan_required` (402) | Generating needs a paid plan or bought AI balance. Tell the user. |
| `spend_cap_reached` (402) | This key’s limit is used up until `details.resets_at`. |
| `storage_full` (403) | The account’s storage for its creations is full. Tell the user; deleting generations they no longer need makes room. |
| `spending_not_enabled` (403) | The account holder must allow spending for this key on the website (`details.settings_url`). |
| `insufficient_scope` (403) | The key has no `generate`: it was made without spending. The account holder makes a new key with spending allowed. |
| `daily_capacity` (503) | The Generator’s daily capacity for API and MCP generations is used up. Try after `details.retry_at`. |
| `model_paused` (503) | Use `details.alternative`, or this model later. |
| `too_many_active` (429) | Wait for your unfinished generations, then start the next. |

Every code, with its details, is on the [errors](https://imgsearch.com/developers/errors.md) page. The account’s generation limits are on [limits](https://imgsearch.com/developers/limits.md#generation).
