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

# Image generation helpers

> Python reference for JSON and streamed image requests with automatic Aion authentication.

Import the helpers from `aion.api.images`, included in `aionto-sdk`. No OpenAI extra is required.
For setup and runnable file-saving examples, use the [Image models guide](https://docs.aion.to/docs/resources/model-service/images.md).

> [!WARNING]
>
> The Aion Images API is experimental. Model capabilities and response details can change.

## Methods

| Method | Use | Result |
| - | - | - |
| `generate_images(model, prompt, **options)` | Blocking JSON request. | Response dictionary. |
| `generate_images_async(model, prompt, **options)` | Await in an agent coroutine. | Response dictionary. |
| `stream_images(model, prompt, **options)` | Open with `with`, consume with `for`. | Iterator of event dictionaries. |
| `stream_images_async(model, prompt, **options)` | `async with`, then `async for`. | Async event iterator. |

All methods call `POST /v1/images` on the configured Aion API host.
The JSON methods set `stream: false`. The streaming methods set `stream: true` and handle JSON fallback.
Do not pass a `stream` option yourself.

## Parameters

| Parameter | Type | Required | Meaning |
| - | - | - | - |
| `model` | `str` | Yes | Exact model ID with the Images operation in the Aion catalog. |
| `prompt` | `str` | Yes | Nonempty image-generation instructions. |
| `client` | HTTPX client | No | Caller-owned `httpx.Client`, or `AsyncClient` for async helpers. Keyword-only. |
| `timeout` | `float` | No | Timeout per network operation in seconds; default `480.0`. Keyword-only. |
| `**options` | Image request fields | No | Controls supported by the selected model and route. |

Common controls include `n`, `size`, `quality`, `resolution`, and `output_format`.
The SDK forwards these fields to Aion for validation; accepted values depend on the selected route.
See [controls and limits](https://docs.aion.to/docs/resources/model-service/images.md#controls-and-limits) for the full field list and limits.

The timeout is not a whole-request deadline. Connection setup is limited to ten seconds or the supplied timeout,
whichever is shorter. For an additional deadline in async code, place the call inside `asyncio.timeout(...)`.
Allow at least eight minutes for normal requests unless you intentionally want an earlier cancellation.

## Authentication and attribution

Configure [deployment client credentials](https://docs.aion.to/docs/resources/model-service.md#deployment-client-credentials) once.
The helpers use the same token manager and request-local attribution rules as other Aion Model Service clients.
They resolve credentials and attribution when each request opens, including when you reuse an HTTPX client.

* A forwarded request uses its existing `Aion-Usage-Attribution` carrier.
* A supported direct-caller context uses the existing direct-caller attribution mechanism.
* Outside a request, neither attribution header is added; Aion resolves the deployment's current Daemon Identity.
* An active request without valid attribution fails. It does not fall back to the daemon.

Do not copy inbound bearer tokens or construct `Aion-Principal-Selector` headers.
A supplied HTTPX client is for transport reuse; the helper supplies Aion authentication for each call.

## JSON response

The JSON methods return the complete response object and preserve additional response fields.

| Field | Meaning |
| - | - |
| `created` | Generation timestamp, when supplied. |
| `data` | List of completed image dictionaries. |
| `data[].b64_json` | Base64-encoded image bytes. Decode before writing an image file. |
| `data[].media_type` | Image media type, when supplied. Do not assume PNG if absent. |
| `usage` | Usage metrics, when available. |
| `usage.cost` | Optional Aion credit quote. It can contain fractional credits. |

An absent quote does not mean a free request. Quotes are for the returned result and are not final settlement receipts.
The complete JSON response is buffered in client memory. No files are created by the SDK.

## Streaming response

Consume events inside the context block:

```python theme={null}
import os

from aion.api.images import stream_images

with stream_images(os.environ["AION_IMAGE_MODEL"], "A blue circle icon") as events:
    for event in events:
        print(event["type"])
```

For the async equivalent, use `async with stream_images_async(...)` and `async for event in events`.

| Event type | Meaning |
| - | - |
| `image_generation.partial_image` | Optional preview with `b64_json`; not a completed image. |
| `image_generation.completed` | Completed image with `b64_json` and optional media type and usage. |

The helper consumes `[DONE]` and ends the iterator. It raises `AionImageError` for a native error event or an
incomplete stream, rather than yielding either as a successful image result.
Unknown event types and malformed responses also raise `AionImageError`.

If a route returns JSON instead of SSE, the helper reads the JSON and yields one completed event per `data` item.
The fallback's whole-response usage appears **only on the last event**; it is not a separate charge for that image.
Native SSE usage is preserved as received. Do not assume that each event has usage or sum repeated cumulative values.

Each event is buffered in memory and can contain a complete base64 image. JSON fallback buffers the whole response.
These are parsed JSON iterators, not binary file streams. Save each completed image as it arrives when you do not
need to retain all output in memory; decoding still needs memory for the image bytes.
See [Save completed images](https://docs.aion.to/docs/resources/model-service/images.md#save-completed-images) for an example.

## Cleanup and client reuse

The context closes the HTTP response after completion, `break`, cancellation, or an error.
Read the iterator only inside its context. A client created by the helper is also closed.
A client passed by the caller remains open and must be closed by that caller:

```python theme={null}
import os

import httpx
from aion.api.images import generate_images

with httpx.Client() as client:
    result = generate_images(
        os.environ["AION_IMAGE_MODEL"], "A blue circle icon", client=client,
    )
    print(len(result["data"]))
```

Use `httpx.AsyncClient` with the async methods. Avoid sharing a client that stores credentials or attribution for
another request; the helpers reject conflicting attribution rather than selecting a different identity.

## Errors and retry behavior

| Exception | Meaning and action |
| - | - |
| `AionAuthenticationError` | Invalid credentials or attribution. Check configuration and request context. |
| `AionDaemonIdentityRequired` | Self-initiated work has no daemon. Configure the deployment's Daemon Identity. |
| `AionImageError` | Invalid image result, native error event, or incomplete stream. Preserve completed output. |
| `httpx.HTTPStatusError` | Aion rejected the HTTP request. Inspect `error.response.status_code` and its error body. |
| `httpx.RequestError` | Transport or timeout failure. Completion can be uncertain. |

The Aion exceptions are in `aion.core.exceptions`.
Async cancellation propagates to the caller after response cleanup.
The helpers make no automatic generation retries. A stream can deliver completed images before a later failure;
those images and their charges do not disappear. Do not blindly retry after an ambiguous result.


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