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

# Image generation and editing

> Generate, edit, decode, and save images.

Image generation and [image understanding](/en/guides/vision.md) are different capabilities. Confirm that your deployment exposes a model through the Images endpoints. Appearing in the model list does not prove support for generation, editing, or every parameter.

## Choose an endpoint

| Operation | Request | Result |
| - | - | - |
| [Generate images](/en/api-reference/images-generations.md) | `POST /v1/images/generations`, JSON | Images in `data[]` |
| [Edit images](/en/api-reference/images-edits.md) | `POST /v1/images/edits`, multipart or model-supported JSON | Images in `data[]` |

Start with `model`, `prompt`, and `n: 1`. Select `size`, `quality`, `background`, and `output_format` according to the model. Do not apply one model's size, count, or format limits to all channels. `response_format` selects the result representation (URL / Base64); `output_format` selects the image encoding (PNG / JPEG / WebP).

## Python: generate and edit

Prepare the [Python SDK environment](/en/guides/python.md). Set `API_BASE_URL` (including `/v1`), `API_KEY`, and an image model's `API_MODEL`. Save as `images.py`. Run `python images.py generate` for generation. For editing, also set `API_IMAGE_PATH` to a local image and run `python images.py edit`. Editing uploads the file to the configured gateway and its upstream.

The example leaves the response format at the model default: it prefers `b64_json`, otherwise prints `url`. It chooses PNG/JPEG/WebP extensions from file signatures, which is not full image validation. It writes to the current directory without overwriting files.

```python theme={null}
import base64
import binascii
import os
import sys
from pathlib import Path
from openai import OpenAI, APIConnectionError, APIStatusError

mode = sys.argv[1] if len(sys.argv) == 2 else ""
if mode not in ("generate", "edit"):
    raise SystemExit("Usage: python images.py generate|edit")

with OpenAI(base_url=os.environ["API_BASE_URL"].rstrip("/"),
            api_key=os.environ["API_KEY"], timeout=180.0, max_retries=0) as client:
    try:
        if mode == "generate":
            result = client.images.generate(
                model=os.environ["API_MODEL"], n=1,
                prompt="A small blue ceramic cup on a plain white background.",
            )
        else:
            with Path(os.environ["API_IMAGE_PATH"]).open("rb") as source:
                result = client.images.edit(
                    model=os.environ["API_MODEL"], image=source, n=1,
                    prompt="Change the cup to green, preserving the composition.",
                )
        if not result.data:
            raise ValueError("No image payload.")
        for index, item in enumerate(result.data, start=1):
            if item.b64_json:
                data = base64.b64decode(item.b64_json, validate=True)
                if data.startswith(b"\x89PNG\r\n\x1a\n"):
                    extension = "png"
                elif data.startswith(b"\xff\xd8\xff"):
                    extension = "jpg"
                elif data.startswith(b"RIFF") and data[8:12] == b"WEBP":
                    extension = "webp"
                else:
                    raise ValueError("Unsupported image bytes.")
                output = Path(f"image-{index}.{extension}")
                with output.open("xb") as target:
                    target.write(data)
                print(f"Saved {output}")
            elif item.url:
                # Do not send the gateway API key to this URL.
                print(item.url)
            else:
                raise ValueError("Image entry has no payload.")
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). Check the request logs.")
    except APIConnectionError:
        raise SystemExit("Connection failed; do not automatically resubmit generation.")
    except (ValueError, binascii.Error, OSError):
        raise SystemExit("Cannot save image. Check the response format and output files.")
```

## Edit inputs and save results

Use the `image` multipart file field. Channels supporting multiple images may require repeated `image[]` fields. Let the SDK create the boundary; do not label an upload as `application/json`. Masks commonly use a `mask` file, but transparent-area semantics, dimensions, and formats depend on the model.

JSON editing formats differ. This reference describes the common `images: [{"image_url": "https://..."}]` shape when supported; some plugins use other fields. Remote URLs must be reachable by the service processing the request. A local path is not a remote URL. The gateway's generic Files API is unimplemented, so do not copy an upstream upload-to-Files and `file_id` workflow unchanged.

URLs may expire: save results promptly without forwarding the gateway Bearer key to a third-party image URL. Decode Base64 to binary bytes. Check HTTP errors and then image payload fields; `revised_prompt` alone is not an image. When saving multiple images, earlier files may already exist if a later save fails.

## Waiting, streaming, and retries

This example uses synchronous results. The task-plugin Images protocol also waits within the request. It can return `504 task_timeout`, and work can continue after a client disconnects. A timeout does not prove submission failed: inspect request/task logs before generating again.

Direct relay channels may support image SSE, but the plugin Images protocol has no universal streaming mode. Do not assume `stream: true` works for all image models or parse image events with a Chat text-stream parser.

Reference: [OpenAI image generation](https://developers.openai.com/api/docs/guides/image-generation). This describes the upstream protocol; actual availability depends on the gateway.

[简体中文](/zh/guides/image-generation.md)


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