Realtime TTS-2 is live. Built for realtime conversation that feels human. Read the Realtime TTS-2 announcement

Image generation

Generate and edit images with chat completions or the OpenAI-compatible Images API, save the result, and choose the right API for each model

Create images from a text prompt through Inworld Inference, and change existing images. Choose an image model, describe the result you want, and save the returned image in your application. To change an existing image, send it with instructions for what to preserve or change.

Inworld serves image models on two APIs. The model you choose decides which one you call:

  • Chat completions (POST https://api.inworld.ai/v1/chat/completions with modalities) serves most image models, such as google-ai-studio/gemini-nano-banana-2.1. Some of them also output text, and some output only images.
  • The Images API (POST https://api.inworld.ai/v1/images/generations and POST https://api.inworld.ai/v1/images/edits) serves the image models whose endpoints list /v1/images/generations, such as meta/muse-image-1.0. It follows OpenAI's Images API, so client.images.generate and client.images.edit in the OpenAI SDK work with it. See Generate and edit images with the Images API.

To ask a model to describe an image instead, see Image, audio and PDF inputs.

Choose a model

Browse inworld.ai/models and select Image. Copy the API model ID and check the model's supported inputs, output settings and pricing. A model that can read images does not necessarily generate them.

To list image models from code, call the List models API with ?output_modalities=image. Each model's endpoints names the API that serves it:

endpoints containsCallBilled
/v1/images/generationsThe Images API. The model also takes edits when endpoints contains /v1/images/edits.Per image returned
/v1/chat/completionsChat completions with modalities, as in the sections belowPer token

To find models that output only images, keep the models whose spec.outputModalities is exactly ["image"]; the output_modalities filter also returns models that output text as well. Outputting only images does not decide the API: some of those models are served on chat completions. A model is served on only one of the two APIs: an Images API model sent to chat completions returns 400, and a chat completions model sent to the Images API returns 404. To list only Images API models, add &endpoints=/v1/images/generations. Without output_modalities, the list leaves out Images API models. Check spec.inputModalities for image if you plan to send reference images, and pricing for the model's rates.

The chat completions examples use google-ai-studio/gemini-nano-banana-2.1. You can replace it with another chat completions image model. Start with the model's default output settings, then adjust them after your first image works.

Try a prompt in the Playground

Open Inworld Portal and choose Image generation in your workspace. Select a model, enter a prompt, and generate an image. Download the result you want to keep.

To compare models, use the same prompt and reference images for each. The Playground offers settings shared by the models you select. A setting that works for one model may need a different value when you switch models in your API request.

Generate and save your first image

This section and the ones up to Handle failures and costs use chat completions. Set modalities to ["text", "image"] to request image output; ["image"] alone also works. If you omit modalities, a model that generates images still returns images, and image_config still applies. If you set modalities, keep "image" in it: a request whose modalities leaves out "image" returns no images and ignores image_config. The examples below wait for the result in the same request and save every returned image to a file.

Create a Standard API key in Inworld Portal. Copy the complete Base64 credential and set it as-is; do not encode it again:

bash
export INWORLD_API_KEY="<your Base64 API key>"

Run the examples on your server. Keep a Standard API key out of browser and mobile code; use a server proxy or backend-minted token for those clients.

Save this as generate-image.py. It uses Python 3.10 or later and the standard library, with no packages to install.

python
import base64
import json
import os
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen

payload = {
    "model": "google-ai-studio/gemini-nano-banana-2.1",
    "messages": [{
        "role": "user",
        "content": "A ceramic teapot on a wooden table by a window, soft morning light, product photograph",
    }],
    "modalities": ["text", "image"],
    "stream": False,
}

request = Request(
    "https://api.inworld.ai/v1/chat/completions",
    data=json.dumps(payload).encode(),
    headers={
        "Authorization": f"Basic {os.environ['INWORLD_API_KEY']}",
        "Content-Type": "application/json",
    },
)
try:
    with urlopen(request, timeout=300) as response:
        result = json.load(response)
except HTTPError as error:
    raise RuntimeError(
        f"HTTP {error.code}: {error.read().decode(errors='replace')}"
    ) from error

images = [
    image
    for choice in result.get("choices", [])
    for image in choice.get("message", {}).get("images", [])
]
if not images:
    raise RuntimeError(f"No image returned. Inspect the response: {result}")

extensions = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
for index, image in enumerate(images, start=1):
    url = image["image_url"]["url"]
    if url.startswith("data:"):
        header, encoded = url.split(",", 1)
        media_type = header[5:].split(";", 1)[0]
        data = base64.b64decode(encoded, validate=True)
    elif url.startswith("https://"):
        with urlopen(url, timeout=60) as download:
            media_type = download.headers.get_content_type()
            data = download.read()
    else:
        raise RuntimeError("Expected an image data URL or HTTPS URL")
    if media_type not in extensions:
        raise RuntimeError(f"Handle this image format before saving: {media_type}")
    path = Path(f"image-{index}{extensions[media_type]}")
    path.write_bytes(data)
    print(f"Saved {path}")

Run it:

bash
python3 generate-image.py

Open the file printed by the script, such as image-1.png. Each run sends a new generation request and can incur a charge. A timeout does not prove that generation stopped, so consider the cost before resubmitting.

Read the response

Read generated images from choices[].message.images[].image_url.url. The value can be a base64 data URL or a download URL. When you request several images with image_config.n, a non-streaming response returns them all in the same choice's images array, not as separate choices. The scripts decode inline image bytes or download the file, and choose a file extension from its media type.

The image format is the one the model returns, usually PNG; a data URL names it in its media type, such as image/png or image/jpeg. No request field chooses the output format, so convert the file in your application if you need a different one.

This abbreviated example shows the shape, not a complete image or a captured response:

json
{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "",
      "images": [{
        "type": "image_url",
        "image_url": { "url": "data:image/png;base64,<image bytes>" }
      }]
    },
    "finish_reason": "stop"
  }]
}

An empty message.content does not mean the request failed: an image can arrive without accompanying text. Check for returned images before treating a response as text-only. Store image files you need in your own storage instead of relying on a returned download URL remaining available.

Change the output settings

Add image_config to the request body. For example, to request a landscape image from a model that supports this ratio:

json
"image_config": { "aspect_ratio": "16:9" }

Choose settings for the selected model:

What you wantHow to request it
A different shapeSet image_config.aspect_ratio to a ratio the model supports. Some models don't use it, and Inworld ignores it on them without an error. When the request includes a reference image, Inworld ignores this setting on every model.
A different sizeSet image_config.image_size to a size the model takes. The accepted values depend on the model: some take a size tier, such as 1K or 2K, and others take pixel dimensions, such as 1024x1024.
Cheaper, lower-detail imagesSet image_config.quality to a value the model takes, such as low, medium, high or auto; without it, the model uses its default. Lower quality returns fewer image tokens, which are billed as output tokens: compare usage.completion_tokens_details.image_tokens. It applies with or without a reference image. Inworld sends the value as given, and a model that takes quality rejects a value it does not accept with 400. Only some models take quality; the others never receive it, and Inworld ignores it without an error.
Several images from one requestSet image_config.n. Some models accept 1 to 10. Others return one image, and Inworld passes a larger value to them as sent, which they can reject. The top-level n field does not set the image count.

For every image option, including streaming previews, see image_config in the API reference. Use the model's defaults when you do not need a specific size. Unsupported values can cause a request to fail, and settings are not interchangeable across models.

Guide the result with an existing image

Use an image-capable generation model and send a reference as a base64 data URL in a user message. The prompt should say what to preserve and what to change. Encode the file itself instead of sending a remote image URL: some image models reject a remote URL with 400, and others ignore it and generate from the text alone.

Only user messages reach the image model. Inworld sends their text as the prompt and every inline image in them as a reference; system and assistant messages are not used. Inworld sets no limit on the number of references, but the selected model has its own limit and can reject a request that exceeds it.

For example, in the Python script above, insert this before request = Request(...). Replace image-1.png with the file you want to change:

python
import mimetypes

reference = Path("image-1.png")
media_type, _ = mimetypes.guess_type(reference.name)
if media_type not in {"image/png", "image/jpeg", "image/webp"}:
    raise ValueError("Use a PNG, JPEG or WebP reference with the matching file extension")
encoded = base64.b64encode(reference.read_bytes()).decode("ascii")
payload["messages"] = [{
    "role": "user",
    "content": [
        {"type": "text", "text": "Keep the teapot and composition. Change the background to a pale blue studio backdrop."},
        {"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{encoded}"}},
    ],
}]

Use a PNG, JPEG or WebP that the selected model accepts. Keep the file extension consistent with its actual format: the example uses the extension to choose the data URL's media type. Send the reference file again on each request that should use it. Describe a subtle or strong variation in the prompt; the Playground's variation actions also use reference images and prompt instructions.

Stream image output

Start with stream: false while you build and verify image saving. For a model that supports image streaming, set stream: true and read images from choices[].delta.images in the server-sent events. Process text and usage events separately from image events.

A model that can't stream image output fails with 400; send that request with stream: false. To receive progressive previews, set image_config.partial_images to a value from 1 to 3. When it is 0 or unset, the model sends no previews. Only some models send previews; the others ignore the setting and send only the final image. A preview is not an additional final image. See the API reference for the option.

Handle failures and costs

Check the HTTP status before reading the JSON response. Authentication and other errors can return a plain-text body. The scripts include the error body when a request fails.

What happenedWhat to check
401 or 403Check the credential and permissions; see API key authentication.
400Check the model ID, output modalities, image settings and reference format. Image output needs a billing method on your workspace. A safety block, or a prompt the model returns no image for, also returns 400.
429Wait before resubmitting; see Rate limits.
A response contains no imagesInspect choices, finish_reason, any text and any error before treating it as a generated image. The model may have refused the request.
A reference does not affect the resultSend its bytes as a base64 data URL in a user message and describe the intended change.

On chat completions, image models are priced per token, not per image. Inworld bills each request from its usage:

  • Generated images count as output tokens. They are included in usage.completion_tokens, which is billed at the model's output rate (pricing.completionToken in the List models API). usage.completion_tokens_details.image_tokens shows the image part when the provider reports it.
  • The prompt and reference images count as input tokens. They are included in usage.prompt_tokens, which is billed at the input rate (pricing.promptToken). usage.prompt_tokens_details.image_tokens shows the reference-image part when the provider reports it.

The token count of an image depends on the model and its output settings, such as size and image count, so compare models with the same prompt and settings. Use the models catalog for current rates and Inference billing for account billing.

Generate and edit images with the Images API

Use the Images API for a model whose endpoints in the List models API contain /v1/images/generations. The API follows OpenAI's Images API: a generation sends a JSON body, an edit sends the input images as a multipart form, and every image comes back in the response as base64 data. The request waits for the images; a single image usually takes a few seconds. The examples use meta/muse-image-1.0, an image-only model created by Meta.

The Images API needs a payment method on your account, and it is not available to workspaces with zero data retention.

Generate an image

Set INWORLD_API_KEY as in Generate and save your first image, and run the examples on your server.

Install the OpenAI Python SDK with pip install openai, then save this as generate_image.py. The default_headers line sends the key as Basic authentication; see OpenAI compatibility.

python
import base64
import os
from pathlib import Path

from openai import OpenAI

api_key = os.environ["INWORLD_API_KEY"]
client = OpenAI(
    base_url="https://api.inworld.ai/v1",
    api_key=api_key,
    default_headers={"Authorization": f"Basic {api_key}"},
)

result = client.images.generate(
    model="meta/muse-image-1.0",
    prompt="A ceramic teapot on a wooden table by a window, soft morning light, product photograph",
    output_format="png",
)

for index, image in enumerate(result.data or [], start=1):
    if not image.b64_json:
        raise RuntimeError("The response carried no image data")
    path = Path(f"image-{index}.png")
    path.write_bytes(base64.b64decode(image.b64_json))
    print(f"Saved {path}")

Run it:

bash
python3 generate_image.py

Open image-1.png. Each request can incur a charge, and a timeout does not prove that generation stopped, so consider the cost before resubmitting.

Edit an image

Send one or more input images to POST /v1/images/edits with a prompt that says what to keep and what to change. The model returns a new image; the input files are not changed. To make a variation of an image, send it here and describe the variation in the prompt. These examples edit the image-1.png saved above.

Save this as edit_image.py:

python
import base64
import os
from pathlib import Path

from openai import OpenAI

api_key = os.environ["INWORLD_API_KEY"]
client = OpenAI(
    base_url="https://api.inworld.ai/v1",
    api_key=api_key,
    default_headers={"Authorization": f"Basic {api_key}"},
)

result = client.images.edit(
    model="meta/muse-image-1.0",
    image=Path("image-1.png"),
    prompt="Keep the teapot and composition. Change the background to a pale blue studio backdrop.",
    output_format="png",
)

for index, image in enumerate(result.data or [], start=1):
    if not image.b64_json:
        raise RuntimeError("The response carried no image data")
    path = Path(f"edited-{index}.png")
    path.write_bytes(base64.b64decode(image.b64_json))
    print(f"Saved {path}")

To send several input images, pass a list, such as image=[Path("a.png"), Path("b.png")].

Input images must be PNG, JPEG or WebP, up to 20 MiB each and 64 MiB for the whole request. The API reads the format from the file's contents, not its name. A model takes up to its own number of input images: meta/muse-image-1.0 takes up to 10.

You can also send an edit as JSON instead of a form: put each image in images as {"image_url": "data:image/png;base64,<image bytes>"}. Send the bytes as a base64 data URL; a remote https:// URL returns 400, because the API does not download images.

A mask limits the edit to an area only on models that take one. meta/muse-image-1.0 does not: describe the area to change in the prompt instead.

Read the Images API response

A successful request returns 200 with the images in data, one entry per image, each as base64 in b64_json. The images are never returned as links, so save the bytes you need. A generation with meta/muse-image-1.0 and no output_format returned this (image data shortened):

json
{
  "created": 1794505773,
  "data": [
    { "b64_json": "UklGRq7DBABXRUJQ..." }
  ],
  "output_format": "webp",
  "size": "1920x1280",
  "background": "opaque",
  "usage": {
    "input_tokens": 9919,
    "output_tokens": 829,
    "total_tokens": 10748
  }
}
  • output_format is the file format of every image in data. Use it to choose the file extension.
  • size describes the returned image. A model can treat the requested size as a shape: a 1024x1024 request to meta/muse-image-1.0 returned 1600x1600 images. Read the dimensions from the image file if you depend on them.
  • usage holds the token counts the model reports, when it reports them. They are for information only; see Images API cost.
  • data[].revised_prompt appears when the model rewrote your prompt.

Streaming. With stream: true, the response is a stream of server-sent events. When the images are ready, it sends one image_generation.completed event per image (image_edit.completed for an edit), each with the image in b64_json; the last one carries usage. There are no partial previews. While the model works, the stream sends comment lines, which keep idle connections from timing out. If the request fails after the stream starts, the stream ends with one error event that carries the HTTP status the failure would have had.

Set the size, format and number of images

What you wantHow to request it
Several imagesSet n from 1 to the model's maximum. meta/muse-image-1.0 returns up to 10 images per request.
A different shapeSet size to WIDTHxHEIGHT, such as 1536x1024, or auto. The model chooses the exact pixel dimensions. Without size, meta/muse-image-1.0 returns a landscape image, such as 1920x1280.
A different file formatSet output_format. meta/muse-image-1.0 takes png, jpeg or webp, and returns webp when you leave it out.

Each model takes its own set of options. A request with an option the model does not take returns 400 with code: "unsupported_parameter", and a value the model does not allow returns 400 with code: "invalid_value". The message names the field and, for a value, the values the model allows. meta/muse-image-1.0 takes n, size and output_format; it does not take quality, background, moderation, input_fidelity or mask.

The prompt has no length limit of its own. A generation request body is limited to 512 KiB, and a model can reject a prompt longer than it accepts.

Handle Images API errors

Errors return JSON: {"error": {"message": "...", "type": "...", "code": "...", "param": "..."}}. param names the field at fault when there is one. The per-minute rate limit's 429 is the exception: its body is the plain text Rate limit exceeded. The edits 429 with code: "account_edits_at_capacity" is JSON like the other errors.

Status and codeWhat to check
400 missing_required_parameter, invalid_value, unsupported_parameter or unknown_parameterFix the field named in param. unknown_parameter means the API does not read that field; see OpenAI Images API compatibility.
400 payment_method_requiredAdd a payment method to your account.
400 zero_data_retention_unsupportedYour workspace has zero data retention, which the Images API does not offer.
401 or 403Check the credential and permissions; see API key authentication.
404 model_not_foundThe model does not exist or is not served on the Images API. Check its endpoints in the List models API.
413The request body is too large: over 512 KiB for a generation or 64 MiB for an edit.
415Send a generation as application/json, and an edit as multipart/form-data or application/json.
429 with the plain-text body Rate limit exceededYou reached the rate limit. The Images API has per-minute limits per account, with separate counters for generations and edits. Wait for the number of seconds in Retry-After when the response has it; see Rate limits.
429 account_edits_at_capacityYour account has too many edits running at the same time. This limit counts edits in progress, not requests per minute, and it covers all the workspaces of your billing account. Wait for the number of seconds in Retry-After, or for one of your running edits to finish, then send the edit again. To avoid it, send fewer edits at once. Generations do not have this limit.
502 no_image_returnedThe model returned no image. The request is not billed. Try again, or change the prompt if it keeps happening.
503 edits_at_capacityImage edits are temporarily at capacity. Retry after the number of seconds in the Retry-After header.
503 service_unavailableThe Images API is temporarily unavailable. Retry with backoff.
Other statuses with type: "upstream_error"The model rejected the request or failed. A 4xx, such as a safety refusal, needs a changed prompt or input image; retry a 5xx with backoff.

Images API cost

The Images API bills per image returned, for generations and edits alike. A request that returns three images is billed for three. The rate in USD is the model's pricing.image.outputImage in the List models API. Input images are not billed separately, and the token counts in usage are not billed.

A request that returns an error, including 502 no_image_returned, is not billed. If you disconnect while the model is working, the images it returns are still billed.

OpenAI Images API compatibility

Set the OpenAI SDK's base URL to https://api.inworld.ai/v1, as in the examples above. client.images.generate calls POST /v1/images/generations and client.images.edit calls POST /v1/images/edits. POST /v1/images/variations is not served: send the image to edits and describe the variation in the prompt.

The API reads each request field as follows. Supported means the field is passed to the model. Rejected means the request returns 400 and nothing is generated.

FieldInworld behavior
modelSupported. Use an Images API model ID, such as meta/muse-image-1.0.
promptSupported and required.
nSupported, from 1 to the model's maximum.
sizeSupported on models that take it, as auto or WIDTHxHEIGHT. The model can treat it as a shape.
output_formatSupported on models that take it, with the values each model allows.
quality, backgroundSupported on models that take them; rejected on others.
moderationGenerations only, on models that take it. Rejected on edits.
input_fidelityEdits only, on models that take it. Rejected on generations.
image, image[] (edit form)Supported. PNG, JPEG or WebP, up to 20 MiB each, up to the model's number of input images.
images[].image_url (JSON edit)Supported for base64 data URLs. A remote URL is rejected.
maskSupported on models that take one; rejected on others.
response_formatb64_json only, which is also what you get when you leave it out. url is rejected.
streamSupported. Sends one completed event per image when all images are ready; no partial images.
partial_images, output_compression, styleRejected (unknown_parameter).
user, safety_identifierIgnored: accepted but not sent to the model.
Any other fieldRejected (unknown_parameter).

In the response, data[].url is never set. usage.input_tokens_details and usage.output_tokens_details are present only when the model reports them, and usage is omitted when it reports no token counts.

Next steps