Image Generation API in Python Tutorial
An image generation API in Python with one code path for GPT Image 2, Seedream, Qwen Image and Riverflow: model-spec, sizes, URL output and safe retries.
By OceanToken Team

Editor's note: The first image call is easy. The second model is where code breaks: one takes quality as low, medium or high, the next as 1K or 2K, one makes eight images per call and another makes one. Hard-coding those values per model works until the catalog changes. Asking the API what each model takes, and retrying without paying twice, keeps the code short and the bill honest.
Short answer: For an image generation API in Python, use the OpenAI SDK's client.images.generate() with the base URL changed, read each model's options from the model-spec endpoint before you send a size or count, download data[].url within 24 hours, and send an Idempotency-Key on every request so a retry never bills a second image.
We use OceanToken for the examples because one key reaches image models from OpenAI, ByteDance Seed, Qwen and Sourceful through the same OpenAI-style Images endpoint, so switching models is a change of the model string. Every fact below comes from our docs and model pages, read November 28, 2026. We have not run your prompts through these models, so the article ends with a checklist for testing them yourself. For prices, see /gpt-image-api, /seedream-api and each model's page.
01 · The image generation API in Python: one call, any model
Our image endpoints follow OpenAI's Images API, so the Python code is the OpenAI SDK with two values changed: the base URL and the key. POST /v1/images/generations creates an image from a prompt, and POST /v1/images/edits starts from one or more images you send.
# pip install openai httpx
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.oceantoken.ai/v1",
api_key=os.environ["OCEANTOKEN_API_KEY"])
result = client.images.generate(
model="openai/gpt-image-2",
prompt="A small lighthouse on a calm sea at dawn, watercolor",
size="1:1",
quality="low",
)
print(result.data[0].url) # download within 24 hours
The request fields are the familiar ones:
| Field | What it does | Watch out for |
|---|---|---|
model |
An image model id | Changes which values the other fields accept |
prompt |
What to draw | |
size |
Aspect ratio such as 16:9, or width x height such as 1536x1024 |
Width x height is mapped to a ratio on these four models |
quality |
low/medium/high, or a resolution tier such as 1K/2K |
Only on models that have quality levels |
n |
How many images | Only on models that make more than one per request |
images |
Reference images, as URLs or data URLs | Makes the request an edit |
The last column is where a single code path gets into trouble, and the rest of this guide is about handling it.
02 · OpenAI Images API with a custom base URL
Using the OpenAI Images API with a custom base URL takes one argument: pass base_url="https://api.oceantoken.ai/v1" to the client, and use your OceanToken key as api_key. Our docs say client.images.generate() and client.images.edit() work with the base URL changed.
Three differences from calling OpenAI directly are worth knowing before you port existing code.
Model ids carry a publisher prefix. You write openai/gpt-image-2, bytedance-seed/seedream-5-5, qwen/qwen-image-3 or sourceful/riverflow-v2.5-fast. The prefix is part of the id, not a path.
size accepts ratios. Each of the four model specs lists size as an aspect ratio, and says width x height such as 1024x1024 "is accepted too and mapped to its ratio." Code that sends 1536x1024 still works, but you are asking for 3:2, not for exactly those pixels. If exact dimensions matter, check what comes back (section 10 has the test).
Your type checker may complain. The SDK's type hints list OpenAI's own size and quality values. Sending "16:9" or "2K" works at runtime, because the SDK passes the string through, but a strict type checker will flag it. A # type: ignore on that line, or a small wrapper that takes str, keeps the noise down.
03 · Image model-spec: sizes, quality and counts per model
The image model-spec endpoint tells you what a model takes before you send anything. It lives outside /v1, so call it with a plain HTTP client:
import httpx
def model_spec(model):
r = httpx.get("https://api.oceantoken.ai/oceantoken/image/model-spec",
params={"model": model},
headers={"Authorization": f"Bearer {os.environ['OCEANTOKEN_API_KEY']}"},
timeout=15)
r.raise_for_status()
return r.json()["spec"] # aspectRatios, resolutions, qualities, maxImages, maxReferences
The answer's spec has aspectRatios, resolutions, qualities, maxImages (the most n can be) and maxReferences (the most reference images). Why call it instead of reading the docs once? Because a value the model does not take is refused with 400 invalid_request. Our docs say the error message lists the values it does take, which is helpful while debugging and unhelpful in production, where it means a failed request and a user waiting.
Here is what each model's docs entry listed on November 28, 2026. Treat it as a snapshot; the model-spec endpoint is the source to code against.
| Model | Publisher | Sizes (aspect ratios) | Quality | Max n |
Max reference images |
|---|---|---|---|---|---|
openai/gpt-image-2 |
OpenAI | 1:1, 3:2, 2:3, 4:3, 3:4, 16:9, 9:16, 21:9 | low, medium, high | 8 | 16 |
bytedance-seed/seedream-5-5 |
ByteDance Seed | 17 ratios, from 1:1 to 21:9 and 9:21 | 1K, 1.5K, 2K | not listed | 10 |
qwen/qwen-image-3 |
Qwen | 13 ratios, including 1:4 and 4:1 | 1K, 2K | 6 | 3 |
sourceful/riverflow-v2.5-fast |
Sourceful | 1:1, 4:3, 3:4, 3:2, 2:3, 16:9, 9:16, 21:9 | 1K, 2K | not listed | 4 |
The table changes two things in your code. GPT Image 2 uses named quality levels, while the other three use resolution tiers, and their specs say low, medium and high are accepted as tiers too. And only GPT Image 2 and Qwen Image 3 list n; on the other two, plan for one image per request and loop if you need more. Qwen Image 3 also lists a seed, so the same seed and prompt give the same image, which is handy for regression tests.

04 · Turning the spec into per-model config
The stance we would take: never hard-code a size, quality or count in the code that calls the model. Read the spec, pick the closest allowed value, and cache the spec for a while so you are not making two calls per image.
from functools import lru_cache
@lru_cache(maxsize=64)
def cached_spec(model):
return model_spec(model)
def pick(wanted, allowed, default=None):
allowed = list(allowed or [])
if not allowed:
return default
return wanted if wanted in allowed else allowed[0]
def build_request(model, prompt, ratio="1:1", quality=None, n=1):
spec = cached_spec(model)
req = {"model": model, "prompt": prompt,
"size": pick(ratio, spec.get("aspectRatios"), ratio)}
q = pick(quality, spec.get("qualities"))
if q:
req["quality"] = q
max_n = spec.get("maxImages") or 1
if max_n > 1:
req["n"] = min(n, max_n)
return req
Falling back to the first allowed value is a choice, not a rule. For a product where the aspect ratio is part of the design, raising an error is better than silently changing 21:9 to 1:1. We have also not seen a live spec response, so check the exact format of each field (for example, whether qualities comes back as "2K" or another spelling) with one call before you rely on pick.
05 · b64_json vs URL image response
On our API, the image response is always a URL: each image comes back in data[].url, also when you ask for b64_json. Code ported from a setup that returned base64 will find data[0].b64_json empty, so read the URL and download the bytes yourself.
def download(url, path):
with httpx.stream("GET", url, timeout=60) as r:
r.raise_for_status()
with open(path, "wb") as f:
for chunk in r.iter_bytes():
f.write(chunk)
Download within 24 hours. Our docs say the URL stops working after that. If you store image links in a database and render them later, you will have broken images the next day. Copy the file to your own storage as part of the same job that made it. The images also appear in the console under Media, which is useful for checking a result by hand, but it is not a substitute for your own copy.
Why a URL instead of inline base64? For you, the practical upside is smaller responses and no large JSON strings in memory. The downside is the extra download step, which is why the end-to-end example in section 08 treats download as part of generation, not an afterthought.
06 · Edits and reference images
Editing uses /v1/images/edits. Send the starting image as a URL or data URL in images, or upload a file as a multipart image field, which is what the OpenAI SDK's client.images.edit() does. Reference images also work on /v1/images/generations, where our docs say the request is treated as an edit.
The limits are where cross-model code needs care:
- Reference count. Each model takes up to a set number, listed in its spec as
maxReferences. More is refused with400, never silently cut. From the table above, the range runs from 3 on Qwen Image 3 to 16 on GPT Image 2. - Masks. A mask is one PNG whose transparent area marks what to change. It works on models that support masks. On a model that does not, the request is refused rather than run without it. For mask technique, see our guide to GPT Image editing with masks.
- Size. URLs must be public. Each image may be up to 25 MB, and our docs suggest keeping the whole request under 10 MB, so send large images as URLs rather than data URLs.
For model-specific editing workflows, see the Qwen Image API guide and the one-change-at-a-time workflow for Nano Banana edits. Our docs also note that a Gemini image model sometimes stops at its drafts without finishing a picture; the request then answers 400 saying you were not charged, and you can send it again. Rates for those models are on /nano-banana-api.
07 · Image API retry without paying twice
An image API retry without paying twice needs an Idempotency-Key header. Our docs say an image is charged when it is made, so a retry after a network timeout would otherwise make, and bill, a second image. With the header, a retry with the same key and the same body gets the first result back.
The rules from our errors page:
| Situation | What you get |
|---|---|
| First request | Runs normally; the response is kept for 24 hours |
| Retry, same key and same body | The kept response, with Idempotency-Replayed: true; nothing runs or is charged |
| Same key, different body | 409 idempotency_key_reused |
| Retry while the first is still running | 409 idempotency_key_in_progress with Retry-After |
| First succeeded but its response could not be kept | 409 idempotency_result_unavailable; not run or charged again |
A 5xx, or a refusal for key, rate limit or balance |
Not kept, so a retry runs again |
The key can be any unique string up to 255 characters; a UUID is the usual choice. Keys are scoped to your API key. Generate the key once per logical image, not once per HTTP attempt, or the protection does nothing.
There is a second reason to retry: concurrency. Image calls count toward the same limit as your video and 3D jobs. When every slot is taken, an image call waits up to 20 seconds, then answers 429 concurrency_limited with a Retry-After header. Nothing ran and nothing was charged, so waiting and sending it again is safe. If your app also generates video, a burst of image requests and a queue of video jobs compete for the same slots; our text-to-image-to-video pipeline guide shows that flow end to end.
08 · End-to-end Python: spec, generate, download, retry
This puts the pieces together. It reuses build_request and download from above.
import time, uuid
from openai import OpenAI, APIStatusError
client = OpenAI(base_url="https://api.oceantoken.ai/v1",
api_key=os.environ["OCEANTOKEN_API_KEY"],
max_retries=0) # we retry ourselves, with one idempotency key
def generate_image(model, prompt, out_prefix, ratio="1:1", quality=None, n=1, tries=4):
req = build_request(model, prompt, ratio, quality, n)
key = str(uuid.uuid4()) # one key per logical request, reused on every retry
for attempt in range(tries):
try:
raw = client.images.with_raw_response.generate(
**req, extra_headers={"Idempotency-Key": key})
result = raw.parse()
cost = raw.headers.get("x-oceantoken-cost")
replayed = raw.headers.get("Idempotency-Replayed")
paths = []
for i, img in enumerate(result.data):
path = f"{out_prefix}-{i}.png"
download(img.url, path)
paths.append(path)
return {"paths": paths, "cost": cost, "replayed": replayed}
except APIStatusError as e:
body = e.body if isinstance(e.body, dict) else {}
code = getattr(e, "code", None) or body.get("code") or (body.get("error") or {}).get("code")
if e.status_code == 429 or e.status_code >= 500 or (e.status_code == 409 and code == "idempotency_key_in_progress"):
wait = float(e.response.headers.get("Retry-After", 2 ** attempt))
time.sleep(wait)
continue
raise # 400, other 409s: fix the request or check Logs, do not retry
raise RuntimeError(f"{model}: gave up after {tries} attempts")
for m in ["openai/gpt-image-2", "bytedance-seed/seedream-5-5",
"qwen/qwen-image-3", "sourceful/riverflow-v2.5-fast"]:
print(m, generate_image(m, "A paper boat on a puddle, overhead shot", m.split("/")[1], ratio="16:9"))
A few lines deserve explanation. Setting max_retries=0 on the client hands retries to our loop, so every attempt carries the same key and we can honour Retry-After. Only 409 idempotency_key_in_progress is retried; idempotency_key_reused means the body changed (a bug), and idempotency_result_unavailable means the image was made and charged, so look it up in Logs instead of retrying. We do not retry 400, because a value the model does not take will be refused the same way every time. The file extension is a guess; check the content type of the download if format matters to you.
09 · What each image costs, and where to read it
Our docs say image models are charged per image, per megapixel or per token, depending on the model. That is why a single "price per image" figure across models is misleading: a per-megapixel model costs more at a higher resolution tier, and a per-token model depends on what it generates.
Each response carries what it cost in the x-oceantoken-cost header, which the end-to-end code above reads, and Logs in the console lists every request. For the rates themselves, see each model's page and the series pages: /gpt-image-api, /seedream-api and /qwen-image-api.

How to test this on your workload
We have not generated images with your prompts, so this is the checklist we would run before shipping:
- Call model-spec for all four models and save the raw JSON, so you know the exact field formats.
- Send one value outside the spec on purpose and read the
400 invalid_requestmessage, so your logs know what it looks like. - Send
size: "1536x1024"to each model and record the dimensions of the file you get back. - Ask for
b64_jsononce and confirm the response still carriesdata[].url. - Retry a request with the same
Idempotency-Keyand body and confirmIdempotency-Replayed: trueand a single charge in Logs. - Send more reference images than
maxReferencesto one model and confirm the400. - Send a mask to a model and record whether it is accepted or refused.
- Run several image calls at once alongside a video job, and record whether you see
429 concurrency_limitedand whatRetry-Aftersays. - Compare
x-oceantoken-costacross quality tiers on one model to see how its billing unit behaves.
Our take: Treat every image model as a set of allowed values you look up, not constants you remember. Read model-spec, keep sizes and counts as per-model config, download the URL as part of the same job, and put an Idempotency-Key on every paid request. Those four habits remove most of the surprises when you add a model.
Running it on OceanToken
From our docs, as of November 28, 2026:
- One key, one SDK, many image models. GPT Image 2, Seedream 5.5, Qwen Image 3 and Riverflow V2.5 Fast all answer on
https://api.oceantoken.ai/v1/images/generations; switching is a change ofmodelid. - Options you can query. The model-spec endpoint returns sizes, quality levels and limits per model.
- Retries that do not bill twice.
Idempotency-Keyreplays the first result for 24 hours, and a429 concurrency_limitedis never charged. - Cost per request. The
x-oceantoken-costheader and console Logs show what each image cost.
Price: see the current rate on /gpt-image-api, /seedream-api, /qwen-image-api, and on the Riverflow V2.5 Fast model page.
FAQ
Can I use the OpenAI Python SDK for non-OpenAI image models? Yes. Our Images endpoints follow OpenAI's Images API, so client.images.generate() works with the base URL changed and a model id such as qwen/qwen-image-3.
Why did my image request return 400? Usually a size, quality, count or reference number the model does not take. The error message lists the allowed values; read them first from model-spec.
Why is b64_json empty? Images always come back as a URL in data[].url, even when you ask for b64_json. Download it within 24 hours.
How do I avoid paying twice when I retry? Send the same Idempotency-Key and the same body on every attempt. A replay is marked Idempotency-Replayed: true and is not charged.
What does 429 concurrency_limited mean? All your slots, shared with video and 3D jobs, were busy for 20 seconds. Nothing was charged; retry after Retry-After.
Sources
- OceanToken docs: Images (checked 2026-11-28)
- OceanToken docs: Errors, retrying a request that costs money (checked 2026-11-28)
- OceanToken docs: GPT Image 2 model spec (checked 2026-11-28)
- OceanToken docs: Seedream 5.5 model spec (checked 2026-11-28)
- OceanToken docs: Qwen Image 3 model spec (checked 2026-11-28)
- OceanToken docs: Riverflow V2.5 Fast model spec (checked 2026-11-28)
Get your OceanToken API key
- Create an OceanToken account and an API key.
- Copy the snippet below, paste your key, and run it.
- Check the current rate on /gpt-image-api.
curl https://api.oceantoken.ai/v1/images/generations \
-H "Authorization: Bearer $OCEANTOKEN_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $(uuidgen)" \
-d '{"model": "openai/gpt-image-2", "prompt": "A small lighthouse on a calm sea at dawn, watercolor", "size": "1:1", "quality": "low"}'
More from the blog
Veo 3.1 Reference Images API Guide
How to send reference images to Veo 3.1 through the API: input_references vs first frame, which tiers take them, two-shot Python script and a consistency test.
LLM Function Calling API Across Models
Write one LLM function calling API loop that works across GPT, Claude, Gemini, Qwen, GLM and DeepSeek: tool_choice, streaming and the silent no-call trap.
LLM Image Input API: Screenshots and Scans
Send screenshots, photos and scans to a chat model with one LLM image input API: URL vs base64 data URL, per-model image limits, the 400 error and token costs.