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

# Image generation

> Generate images and decode inline base64 output.

Generate images from a text prompt through the attested TEE gateway. This endpoint returns a
buffered JSON response with inline base64 image data and an `x-receipt-id` header for verification.

```bash theme={null}
POST https://api.redpill.ai/v1/images/generations
```

## Request body

**model** `string` *required*

Image model id from `GET /v1/models`, for example `black-forest-labs/flux.2-klein-4b`.

**prompt** `string` *required*

Text describing the image. Maximum 32,000 Unicode characters.

**n** `integer`

Request up to `n` images, from `1` through `10` (default `1`). Providers may return fewer images;
image charges use the returned count. Non-integers, `null`, and integers outside this range return
`400` with `type: invalid_request_error`, `code: invalid_parameter`, and `param: n`.

**size** `string`

Image dimensions, for example `512x512`, or `auto` if the model supports it.

**quality** `string`

Model-specific quality setting.

**background** `string`

Model-specific background setting.

**output\_format** `string`

Image encoding option, for example `png`. For `black-forest-labs/flux.2-klein-4b`, the NEAR
provider does not honor this option; returned bytes may be JPEG. Inspect the decoded bytes
before choosing a file extension.

**output\_compression** `integer`

Compression setting from 0 through 100, if supported by the model and output format.

**moderation** `string`

Model-specific moderation setting.

**response\_format** `string`

Omit this field or set it to `b64_json`. The gateway always requests inline base64 output.
`url` is not supported.

**safety\_identifier** `string`

Accepted for SDK compatibility but removed before forwarding upstream.

**provider** `object`

The same routing constraints as [Chat completions](https://docs.redpill.ai/api-reference/chat-completions.md#body-provider),
including `zdr`, `aci_verified`, and `aci_session_ids`.

The gateway checks the types of the string options; supported values and defaults depend on the
model and are validated upstream. `user` and `style` are accepted as strings but removed before
forwarding. Other fields, including `seed`, return `400 unknown_parameter`. Omit `stream` and
`partial_images` entirely, including `stream: false`: streaming is not supported. ACI E2EE is not
supported on this endpoint.

## Example

Both examples save the first image as `image.bin` without assuming an encoding. The cURL example
also saves response headers to `image-headers.txt`, including the receipt id.

```bash cURL theme={null}
curl --fail-with-body --silent --show-error \
  https://api.redpill.ai/v1/images/generations \
  -H "Authorization: Bearer $REDPILL_AI_API_KEY" \
  -H "Content-Type: application/json" \
  -D image-headers.txt -o image-response.json \
  -d '{
    "model": "black-forest-labs/flux.2-klein-4b",
    "prompt": "A blue circle on a white background."
  }' && \
python3 - <<'PY'
import base64
import json
from pathlib import Path

response = json.loads(Path("image-response.json").read_text())
image = base64.b64decode(response["data"][0]["b64_json"], validate=True)
Path("image.bin").write_bytes(image)
PY
```

```python Python theme={null}
import base64
import os
from pathlib import Path
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["REDPILL_AI_API_KEY"],
    base_url="https://api.redpill.ai/v1",
)

response = client.images.generate(
    model="black-forest-labs/flux.2-klein-4b",
    prompt="A blue circle on a white background.",
)
if not response.data or not response.data[0].b64_json:
    raise ValueError("The response did not contain an inline image")
image = base64.b64decode(response.data[0].b64_json, validate=True)
Path("image.bin").write_bytes(image)
```

## Response

The image data below is shortened and the cost is illustrative, not a model price.

```json theme={null}
{
  "created": 1793059200,
  "data": [
    { "b64_json": "/9j/..." }
  ],
  "usage": {
    "input_tokens": 0,
    "output_tokens": 0,
    "total_tokens": 0,
    "input_tokens_details": { "text_tokens": 0, "image_tokens": 0 },
    "cost": 0.01
  }
}
```

`created` is a Unix timestamp in seconds, supplied by the upstream or filled in by the gateway.
`data` is a non-empty array of images. Each item contains `b64_json` and may contain
`revised_prompt` as a string or `null`. Image URLs are never returned. Optional top-level fields
are `size`, `quality`, `output_format`, and `background`; current
`black-forest-labs/flux.2-klein-4b` responses omit `size` and `output_format`.

When present, `usage` always includes integer `input_tokens`, `output_tokens`, `total_tokens`, and
`input_tokens_details.text_tokens` and `.image_tokens`. Missing token counts are filled with `0`,
including when the provider reports no token usage. `output_tokens_details` may also be present.
When pricing is available, the gateway adds `usage.cost` in USD: the returned image count times the
applicable per-image price, plus token charges when token usage and rates are available. Zero token
counts do not imply free image generation.

Read `x-receipt-id` from the response headers and fetch
`GET /v1/aci/receipts/{id}` using the same bearer token as the generation request. Image receipts
have `chat_id: null`, so use the receipt id rather than a chat id. See
[Get receipt](https://docs.redpill.ai/api-reference/receipts.md) for the response format and
[Verify a response](https://docs.redpill.ai/guides/verify-a-response.md) for verification.

## Errors

Errors use a JSON `error` object. Parameter validation errors have `error.type: invalid_request_error`
and include `error.code` and `error.param` where applicable.

| Status | Error field | Condition |
| - | - | - |
| 400 | `code: unknown_parameter` | Unrecognized field, such as `seed`; `param` names the field. |
| 400 | `code: invalid_parameter`, `param: n` | `n` is a non-integer, `null`, or an integer outside `1` through `10`. |
| 400 | `code: invalid_parameter` | `response_format: "url"`, any `stream` or `partial_images` field, missing required strings, invalid types for other parameters, prompt over 32,000 characters, or `output_compression` outside 0–100. |
| 400 | `type: invalid_request_error`, `code: null` | Invalid JSON or a malformed provider constraint. |
| 400 | `type: e2ee_unsupported_endpoint` | E2EE headers are present; refusal is decided before parsing or admission, and the gateway may then drain the remaining upload within bounded limits. |
| 404 | `type: model_not_found` | No eligible route supports image generation for the requested model. |
| 429 | `type: rate_limit_error`, `code: rate_limit_exceeded` | Image generation capacity is full, or a rate limit is reached. Capacity requests are rejected without queueing; respect `Retry-After` when present. |
| 502 | `type: upstream_error` | Upstream failure, buffered response over 64 MiB, or malformed success response, including empty `data`, more images than requested, or an item without a string `b64_json`. |

Authentication, budget, and routing constraint errors follow the shared
[error handling reference](https://docs.redpill.ai/guides/error-handling.md).

## Related

> [card] [Models](https://docs.redpill.ai/api-reference/models.md)
>
> Find available model ids and capabilities.

> [card] [Get receipt](https://docs.redpill.ai/api-reference/receipts.md)
>
> Retrieve the signed receipt using x-receipt-id.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.