Images
Create Image
Creates an image given a prompt
Overview
Use GET /v1/models?recommended_for=image to get current image models, then send the selected model explicitly.
Each model accepts its own operations and fields. GET /v1/models/{model} (Get Model) gives the endpoint for each operation in tokenlab.request_format_summary.request_endpoint_by_operation, and the accepted fields, values, and limits for each operation in tokenlab.request_format_details.operation_constraints. A field the model does not list can return 400 unsupported_parameter. An operation sent to the wrong endpoint returns 400 unsupported_endpoint.
Image tasks and results:
- Models that list
asyncamong their supported parameters can create a task first: sendasync: true, then pollGET /v1/tasks/{id}. - Image links are saved for 30 days; see Data retention.
- Send an
Idempotency-Keyheader to retry a create request safely after a timeout; see Retry safely with an idempotency key.
gpt-image-2 is a token-priced GPT Image model. TokenLab follows OpenAI's official usage breakdown for text input, image input, reported cached input, and image output tokens; it is not billed as a fixed per-image model.
For gpt-image-2 image generation, supported public parameters are prompt, n, size, quality, response_format, async, background, output_format, output_compression or compression, moderation, and user. background accepts auto or opaque; transparent is not supported. Omit size or quality to let TokenLab use auto; custom size values must use the flexible WIDTHxHEIGHT contract documented below.
input_fidelity is not part of the current TokenLab supported fields for gpt-image-2; omit it or the request returns 400 unsupported_parameter.
SVG and GIF output
gpt-image-2.6-flare and gpt-image-2.6-sunburst can return an SVG or an animated GIF instead of a raster image. Other models reject these formats.
- SVG: send
output_format: "svg"andsvg: {"model": "..."}. The image model first draws a reference image, then the author model writes the SVG from it.svg.modelis required; the model details list its accepted values underparameter_options(svg.model). You can also sendsvg.reasoning.effort. SVG works only on this endpoint, withn: 1, and withoutpartial_imagesoroutput_compression. - GIF: send
output_format: "gif".frame_count(2 to 16, default 9) sets the number of frames, andframe_duration_ms(20 to 2000, default 200) sets the time of each frame.sizeis the size of one frame. GIF does not acceptpartial_imagesoroutput_compression.
The result is in data[].b64_json or data[].url, the same as other images. Decode an SVG as UTF-8 XML text and save it as .svg; save a GIF as .gif.
Billing: image tokens are billed at the model's token prices, and the GIF frames are image output tokens. An SVG request also bills the author model's tokens, which the response reports in svg_usage, at the SVG authoring prices shown on the model page.
Model behavior notes
Google Gemini image-family models do not share the same selector contract:
gemini-3.1-flash-image,gemini-nano-banana-2.1,gemini-3-pro-image,nano-banana-2.1, andnano-banana-prosupportaspect_ratioplusresolution(1k,2k,4k) for their public text-to-image, image-to-image, and image-edit operations.nano-banana-2supportsaspect_ratioandresolution(1k,2k,4k) for both text-to-image and image-to-image generation.gemini-3.1-flash-lite-imageandnano-banana-2-litesupport text-to-image, image-to-image, and image-edit at1kresolution only.nano-bananasupportsaspect_ratiobut does not expose publicresolutionselection.- For image-to-image with
gemini-3.1-flash-image,gemini-nano-banana-2.1,gemini-3.1-flash-lite-image, orgemini-3-pro-image, use this endpoint withoperation: "image-to-image"and reference images. Send image-edit requests for these models to/v1/images/edits. - For Nano Banana reference-image requests, use
nano-banana-2,nano-banana-2.1,nano-banana-2-lite, ornano-banana-proon this endpoint (/v1/images/generations) withoperation: "image-to-image"andimage_urls. Image-edit requests fornano-banana-2,nano-banana-2.1,nano-banana-2-lite, andnano-banana-proalso use this endpoint, withoperation: "image-edit". Do not send Nano Banana reference-image requests to/v1/images/edits. - Reference images on this endpoint can be supplied as JSON
image_url/image_urls, or as a multipartimagefile.images[]andfile_idare not accepted on/v1/images/generations; create/v1/filesreferences only for/v1/images/editsmodels that documentimages[].file_id.
For Google image families, prefer aspect_ratio and only send resolution when the model explicitly supports it.
xAI Grok Imagine image models (grok-imagine-image and grok-imagine-image-2.0) support aspect_ratio plus resolution (1k, 2k). Text-to-image uses this endpoint. Their image-to-image and image-edit requests use /v1/images/edits.
hy-image-v3.5-preview creates one 1024x1024 image per request from text on this endpoint and supports only response_format: "url". It edits reference images on /v1/images/edits.
Request Body
Synchronous request timeout: Some image requests return the final image inline and wait for generation to finish. High-resolution or high-quality requests can take close to a minute or longer, so set your HTTP client timeout to at least 120s. If the create response includes status: "pending", task_id, or poll_url, poll GET /v1/tasks/{task_id} instead.
Model to use (for example, gpt-image-2, flux-pro-1.1, or nano-banana-pro). Query GET /v1/models?recommended_for=image for the current recommended list.
Text description of the desired image, up to 32,000 characters. Required for every model whose details list prompt.
text-to-image, image-to-image, or image-edit. When omitted, it is image-to-image if the request has a reference image, otherwise text-to-image. Set image-edit for models whose edit operation is on this endpoint, such as nano-banana-pro. text-to-image with a reference image returns 400 invalid_parameter.
Public image URL for image-to-image generation. For Nano Banana reference-image requests, set operation to image-to-image; nano-banana-pro may include resolution.
Public reference image URLs, up to 16. Use this for one or more reference images in JSON requests. file_id and images[] are not supported on this endpoint.
Additional reference image URLs, up to 16, for models that distinguish primary inputs from references.
Multipart reference image file for image-to-image generation. Use this when the source image is private or header-protected. This is different from a /v1/files file_id, which is not accepted on this endpoint.
1Number of images to generate (1-10, model dependent).
Image size. Use this for OpenAI-style image families and other models that accept exact pixel sizes.
For gpt-image-2, size accepts auto or WIDTHxHEIGHT. Custom dimensions must both be multiples of 16, the longest edge must be at most 3840px, the long/short ratio must be at most 3:1, and total pixels must be between 655,360 and 8,294,400. aspect_ratio and resolution are not part of the current TokenLab model details for gpt-image-2.
For Google image models with resolution tiers (gemini-3.1-flash-image, gemini-nano-banana-2.1, gemini-3-pro-image, gemini-3.1-flash-lite-image, nano-banana-2, nano-banana-2.1, and nano-banana-pro), size accepts an output size from the model's size table, such as 1376x768 (16:9 at 1K), or a resolution tier: 1K, 2K, or 4K. TokenLab sends a tier as resolution, so the request and its price are the same as with resolution. A tier that the model does not support (for example 2K on gemini-3.1-flash-lite-image), or a tier that is different from resolution, returns 400 with code invalid_image_size_contract and the model's allowed_resolutions. For these models, the recommended form is aspect_ratio with resolution.
Model-dependent aspect ratio selector.
Common Google image-family values include 1:1, 16:9, 9:16, 3:2, and 2:3.
Model-dependent output resolution. gemini-3.1-flash-image, gemini-nano-banana-2.1, gemini-3-pro-image, nano-banana-2, nano-banana-2.1, and nano-banana-pro support 1k, 2k, and 4k; Grok Imagine image models support 1k and 2k. Omit this field unless the selected model and operation explicitly support it.
Image quality. GPT Image models such as gpt-image-2 use auto, low, medium, or high. Other models may use different values; check the model details before sending a non-default value.
File format of the image: png, jpeg, or webp. gpt-image-2.6-flare and gpt-image-2.6-sunburst also accept svg and gif; see SVG and GIF output.
SVG settings, only with output_format: "svg". model (required) selects the author model that writes the SVG. reasoning.effort optionally sets its reasoning effort.
9Number of GIF frames, from 2 to 16. Only with output_format: "gif".
200Time of each GIF frame in milliseconds, from 20 to 2000. Only with output_format: "gif".
How the images are returned: url or b64_json.
- Omitted: when the model returns image bytes, each image is in
data[].b64_json, and also indata[].urlwhen TokenLab stored it. When the model returns a link, each image is indata[].url. url: each image is only indata[].url.b64_json: each image is only indata[].b64_jsonas Base64 data.
Links are TokenLab media-result URLs. They stay valid for 30 days. See Data retention.
falseSet to true to create a task first. Only models that list async among their supported parameters accept it, for example gpt-image-2, flux-pro-1.1, nano-banana-pro, and seedream-5.0-lite; for any other model the request returns 400 unsupported_async_mode. Completed async image tasks return URLs regardless of the requested response_format; use synchronous requests when you need b64_json.
Optional style selector. Only send this when the selected model explicitly documents it; omit it for gpt-image-2 unless the model metadata says otherwise.
A unique identifier for the end-user.
Some models also accept fields such as negative_prompt, seed, width, height, steps, guidance_scale, or mask_url. Send them only when the model's details list them. stream: true is not supported and returns 400 unsupported_parameter.
Response
Inline Response
Unix timestamp of creation.
Array of generated images.
Each object contains:
url(string): TokenLab media-result URL of the image, valid for 30 days. Not present whenresponse_formatisb64_json. Whenresponse_formatis omitted, it is missing if TokenLab could not store the image.b64_json(string): Base64 image data. Present whenresponse_formatisb64_json, or when it is omitted and the model returns image bytes.revised_prompt(string): Optional prompt revision, when the selected model returns one
Token counts (input_tokens, output_tokens, total_tokens, and their details) for token-priced models such as gpt-image-2, when available.
Token counts of the SVG author model (model, input_tokens, output_tokens, reasoning_tokens, total_tokens). Present only for SVG output. These tokens are not in usage and are billed at the SVG authoring prices.
Async Task Response
Set async: true on a model that supports it to create a task instead of waiting for the final image in the create request. The response includes status: "pending", task_id, and poll_url. Poll /v1/tasks/{task_id} until the task reaches completed or failed.
Async image tasks return final image URLs only. If you need raw b64_json image data, use a synchronous request.
Billing may reserve the estimated amount when the task is created. Completed tasks are billed by actual usage, and failed or timed-out tasks are released or refunded.
Unix timestamp of creation.
Unique task identifier for polling.
Initial status: pending.
Relative URL to poll for results, for example /v1/tasks/{id}.
Empty while the task is pending. Completed image tasks return generated image URLs in data[].url.
When you receive status: "pending", call GET /v1/tasks/{task_id} to retrieve the result.
Request
curl -X POST "https://api.tokenlab.sh/v1/images/generations" \
-H "Authorization: Bearer sk-your-api-key" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3-pro-image",
"prompt": "A cinematic portrait of a white cat sitting on a rainy windowsill",
"aspect_ratio": "16:9",
"resolution": "2k"
}'from openai import OpenAI
client = OpenAI(
api_key="sk-your-api-key",
base_url="https://api.tokenlab.sh/v1"
)
response = client.images.generate(
model="gemini-3-pro-image",
prompt="A cinematic portrait of a white cat sitting on a rainy windowsill",
extra_body={"aspect_ratio": "16:9", "resolution": "2k"}
)
print(response.data[0].url)import OpenAI from 'openai';
const client = new OpenAI({
apiKey: 'sk-your-api-key',
baseURL: 'https://api.tokenlab.sh/v1'
});
const response = await client.images.generate({
model: 'gemini-3-pro-image',
prompt: 'A cinematic portrait of a white cat sitting on a rainy windowsill',
aspect_ratio: '16:9',
resolution: '2k'
});
console.log(response.data[0].url);<?php
$ch = curl_init('https://api.tokenlab.sh/v1/images/generations');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer sk-your-api-key'
],
CURLOPT_POSTFIELDS => json_encode([
'model' => 'gemini-3-pro-image',
'prompt' => 'A cinematic portrait of a white cat sitting on a rainy windowsill',
'aspect_ratio' => '16:9',
'resolution' => '2k'
])
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
echo $data['data'][0]['url'];Ratio-only image-family example: for nano-banana, send aspect_ratio but omit resolution:
{
"model": "nano-banana",
"prompt": "A clean editorial product shot of a citrus soda can",
"aspect_ratio": "16:9"
}Nano Banana Pro reference-image example: send the request to /v1/images/generations, not /v1/images/edits. resolution is optional and may be set to 1k, 2k, or 4k:
{
"model": "nano-banana-pro",
"prompt": "Create a clean cinematic character image based on the reference images",
"operation": "image-to-image",
"image_urls": ["https://example.com/reference-1.png"],
"aspect_ratio": "1:1",
"resolution": "2k"
}Direct multipart upload example for private or local source images. Do not pass a file_id to /v1/images/generations:
curl -X POST "https://api.tokenlab.sh/v1/images/generations" \
-H "Authorization: Bearer sk-your-api-key" \
-F "model=nano-banana-pro" \
-F "prompt=Create a clean cinematic character image based on this reference" \
-F "operation=image-to-image" \
-F "image=@reference.png" \
-F "aspect_ratio=1:1" \
-F "resolution=2k"Response
{
"created": 1706000000,
"data": [
{
"url": "https://...",
"revised_prompt": "A fluffy white cat with bright eyes sitting peacefully on a wooden windowsill, watching raindrops stream down the glass window..."
}
]
}Errors
Request errors return 400 (413 for oversized uploads) with an error.code. Common codes for image requests:
| Code | Cause |
|---|---|
unsupported_parameter | The model does not list the field, or stream is true |
unsupported_operation | The model has no such operation |
unsupported_endpoint | The operation for this model is on another endpoint, such as /v1/images/edits |
unsupported_async_mode | The model does not support async: true |
invalid_resolution, invalid_aspect_ratio, invalid_parameter_value, too_many_items | A value is outside what the model accepts. The error names the accepted values |
invalid_image_size_contract | A size or tier the model does not support, or one that conflicts with resolution |
prompt_too_long | The prompt is longer than the model accepts |
request_too_large, file_too_large | An upload is over the size limit (50 MiB per file, 200 MiB for all inputs) |
For balance (402), rate limit (429), and retry rules, see Error handling.
Choose a Model
Query GET /v1/models?recommended_for=image or use the Models page for current availability, capabilities, and prices.
Do not hard-code a model as always synchronous or always asynchronous. A request without async: true can still return status: "pending"; whenever the create response carries status: "pending" or status: "processing", poll GET /v1/tasks/{task_id} until completion.
Handling Task-Based Responses
For image models, always check whether the response contains status: "pending" / status: "processing":
import requests
import time
def generate_image(prompt, model="gpt-image-2"):
# Create image request
response = requests.post(
"https://api.tokenlab.sh/v1/images/generations",
headers={"Authorization": "Bearer sk-your-api-key"},
json={"model": model, "prompt": prompt, "async": True},
timeout=120
)
response.raise_for_status()
data = response.json()
# Check if task-based
if data.get("status") in ("pending", "processing"):
task_id = data["task_id"]
print(f"Image task started: {task_id}")
# Poll for result
deadline = time.time() + 600
while time.time() < deadline:
status_resp = requests.get(
f"https://api.tokenlab.sh/v1/tasks/{task_id}",
headers={"Authorization": "Bearer sk-your-api-key"},
timeout=30
)
status_resp.raise_for_status()
status_data = status_resp.json()
if status_data["status"] == "completed":
return status_data["data"][0]["url"]
elif status_data["status"] == "failed":
raise Exception(status_data.get("error", "Generation failed"))
time.sleep(3)
raise TimeoutError(f"Image task {task_id} did not finish in time")
else:
# Inline response
return data["data"][0]["url"]
# Usage
url = generate_image("a beautiful sunset over mountains", model="gpt-image-2")
print(f"Generated image: {url}")Hy Image 3.5 Preview example. It takes size 1024x1024 and n 1 only:
{
"model": "hy-image-v3.5-preview",
"prompt": "A yellow lemon on a white table",
"size": "1024x1024",
"n": 1,
"response_format": "url"
}Authorization
BearerAuth API Key authentication. Create or manage API keys in Dashboard > API > API Keys.
In: header
Headers
Per-request Delivery policy. Overrides the API key and Workspace defaults. Auto tries TokenLab Verified first and may switch once to Official only before output, request acceptance, or persistent resource creation.
Value in
- "auto"
- "verified"
- "official"
Optional key that makes an image request safe to retry if the request created a task. Send a new unique value, such as a UUID, for each request. A retry with the same key and the same body then returns that task and does not create, dispatch, or charge a second task. For a request that returns the image directly, a retry with the same key can return a task status instead of the image, or 409 with idempotent_response_not_replayable. A different body with a key that was already accepted is rejected; the status code and error code for that case are not guaranteed. A key longer than 255 characters is ignored, and the request then has no idempotency protection. See Retry safely with an idempotency key.
1 <= length <= 255Response
application/json
application/json
application/json
application/json
application/json
application/json
application/json