> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tokenflux.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Images API

> Async image generation on top of TokenFlux virtual LLM providers

# Images API

TokenFlux exposes a unified image generation surface that fronts multiple visual model providers. Every request uses a canonical model ID and a structured `input` payload that is validated against the model’s JSON schema before reaching the upstream provider. Responses share a consistent shape regardless of the backing service, making it easy to build tooling around job creation, polling, and history management.

## Available endpoints

| Method | Path                          | Auth? | Description                                                   |
| ------ | ----------------------------- | ----- | ------------------------------------------------------------- |
| `GET`  | `/v1/images/models`           | No    | List all enabled image models with pricing and JSON schemas.  |
| `POST` | `/v1/images/generations`      | Yes   | Start a new asynchronous image generation job.                |
| `GET`  | `/v1/images/generations`      | Yes   | Retrieve your most recent successful generations (up to 100). |
| `GET`  | `/v1/images/generations/{id}` | Yes   | Poll the status and outputs for a specific generation.        |

All authenticated endpoints accept API keys in `Authorization: Bearer` or `X-Api-Key` headers via the shared authentication middleware. Requests are rejected with `403 Forbidden` when the caller has less than `0.01` credits remaining.

## List image models

### Endpoint

```http theme={null}
GET /v1/images/models
```

### Response

The endpoint returns a `JSONResult` envelope with a `data` array of model descriptors. TokenFlux caches the list for 24 hours in memory so you can safely cache it in clients as well. Each entry includes:

| Field            | Type   | Description                                                    |
| ---------------- | ------ | -------------------------------------------------------------- |
| `id`             | string | Canonical model ID to use in generation requests.              |
| `name`           | string | Human-readable model name.                                     |
| `model_provider` | string | Upstream provider (for example `black-forest-labs`, `google`). |
| `description`    | string | Short description of the model’s strengths.                    |
| `tags`           | array  | Provider-defined tags such as `text-to-image`.                 |
| `pricing`        | object | Cost metadata with `price`, `currency`, and `unit` fields.     |
| `input_schema`   | object | JSON Schema describing the required `input` payload.           |

```json theme={null}
{
  "success": true,
  "code": 200,
  "data": [
    {
      "id": "black-forest-labs/flux-schnell",
      "name": "FLUX.1 [schnell]",
      "model_provider": "black-forest-labs",
      "description": "The fastest image generation model tailored for local development and personal use",
      "tags": ["text-to-image"],
      "pricing": { "price": 0.025, "currency": "USD", "unit": 1 },
      "input_schema": {
        "properties": {
          "prompt": { "type": "string", "description": "Prompt for generated image" },
          "aspect_ratio": { "type": "string", "enum": ["1:1", "16:9", "21:9", "3:2"] }
        }
      }
    }
  ]
}
```

## Create image generation

### Endpoint

```http theme={null}
POST /v1/images/generations
```

### Request body

| Field     | Type   | Required | Description                                                                                                                                                                    |
| --------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `model`   | string | **Yes**  | Canonical model ID from `/v1/images/models`.                                                                                                                                   |
| `input`   | object | **Yes**  | Provider-specific payload that must satisfy the model’s JSON schema. For example, `flux-schnell` expects `prompt`, `aspect_ratio`, `num_outputs`, and other tuning parameters. |
| `webhook` | string | No       | Optional URL to receive provider callbacks when supported. Currently stored for future use.                                                                                    |

Invalid payloads return `400 Bad Request` with a descriptive validation error message.

### Response

The endpoint returns the newly created job wrapped in a `JSONResult`. The `status` is usually `starting` immediately after creation. Use the job `id` to poll until the status becomes `succeeded` or `failed`.

```json theme={null}
{
  "success": true,
  "code": 200,
  "data": {
    "id": "0a4c1d62-2cd0-4cf1-9e0c-1b2f7f4f5678",
    "model": "black-forest-labs/flux-schnell",
    "status": "starting"
  }
}
```

## Get a generation

### Endpoint

```http theme={null}
GET /v1/images/generations/{id}
```

### Behavior

* Looks up the generation in the database and, if the job is still `starting` or `processing`, refreshes the status and image list by querying the upstream provider.
* Persists provider responses (including image URLs and costs) before returning the unified `data` payload.

### Response

```json theme={null}
{
  "success": true,
  "code": 200,
  "data": {
    "id": "0a4c1d62-2cd0-4cf1-9e0c-1b2f7f4f5678",
    "model": "black-forest-labs/flux-schnell",
    "status": "succeeded",
    "cost": 0.05,
    "images": [
      {
        "url": "https://replicate.delivery/pbxt/abc123.png"
      }
    ]
  }
}
```

### Status values

| Status       | Meaning                                                                        |
| ------------ | ------------------------------------------------------------------------------ |
| `starting`   | Job was accepted and queued with the provider.                                 |
| `processing` | Provider is still generating results. Poll again or wait for a webhook.        |
| `succeeded`  | Images are available in the `images` array.                                    |
| `failed`     | Provider reported an error; `error` contains details.                          |
| `canceled`   | Job was canceled (not currently issued by providers, reserved for future use). |

## List recent generations

### Endpoint

```http theme={null}
GET /v1/images/generations
```

### Response

Returns up to 100 successful generations for the authenticated user ordered by `created_at DESC`. In-progress or failed jobs are excluded from this list. Use the individual `GET /{id}` endpoint to inspect pending jobs.

```json theme={null}
{
  "success": true,
  "code": 200,
  "data": [
    {
      "id": "0a4c1d62-2cd0-4cf1-9e0c-1b2f7f4f5678",
      "model": "black-forest-labs/flux-schnell",
      "status": "succeeded",
      "cost": 0.05,
      "images": [
        { "url": "https://replicate.delivery/pbxt/abc123.png" },
        { "url": "https://replicate.delivery/pbxt/def456.png" }
      ]
    }
  ]
}
```

## Data model

Each response’s `data` field conforms to the following structure.

| Field    | Type   | Description                                                                                |
| -------- | ------ | ------------------------------------------------------------------------------------------ |
| `id`     | string | UUID of the generation.                                                                    |
| `model`  | string | Canonical model ID.                                                                        |
| `status` | string | One of the status values above.                                                            |
| `images` | array  | Zero or more `Image` objects. Present when the provider returns image URLs or base64 data. |
| `cost`   | number | Total credits consumed for the job. Set when images are available.                         |
| `error`  | string | Human-readable error message when `status` is `failed`.                                    |

`Image` objects provide:

| Field          | Type    | Description                                             |
| -------------- | ------- | ------------------------------------------------------- |
| `url`          | string  | Provider-hosted URL to download the image.              |
| `data`         | string  | Base64 data when the provider returns inline bytes.     |
| `context_type` | string  | MIME type of the inline data (for example `image/png`). |
| `width`        | integer | Image width in pixels, when reported.                   |
| `height`       | integer | Image height in pixels, when reported.                  |

## Error handling

| Status                      | When it occurs                                               | Body                                                                      |
| --------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------- |
| `400 Bad Request`           | Schema validation fails or required parameters are missing.  | `{ "success": false, "code": 400, "message": "input validation failed" }` |
| `403 Forbidden`             | Account quota below 0.01 credits.                            | `{ "success": false, "code": 403, "message": "insufficient quota" }`      |
| `404 Not Found`             | Generation ID does not exist for the current user.           | `{ "success": false, "code": 404, "message": "missing ID parameter" }`    |
| `500 Internal Server Error` | Provider call failed or TokenFlux could not persist results. | `{ "success": false, "code": 500, "message": "internal server error" }`   |

## Usage tips

* TokenFlux stores every request’s original input and provider response, so you can safely replay generations or audit output costs later.
* The optional `webhook` URL is persisted and ready for future asynchronous callback support. Until then, poll `GET /v1/images/generations/{id}` for job completion.
* Pair this API with the [Chat Completions API](./chat-completions) to build multimodal assistants that mix text and image generation.
