Image
GPT Image 2
Generate images, edit references, and apply masks through one asynchronous image endpoint.
GPT Image 2 accepts a text prompt and optional reference images. Submit once, keep the returned task ID, and check that task for the finished images. It is sold on two channels, each with its own model ID; both read the same parameters.
Model IDs
| Model ID | Channel | Billing |
|---|---|---|
gpt-image-2 | Standard | One flat price per delivered image, at any size or quality |
gpt-image-2-official | Official | The tokens each render reports (text input and image output) |
Both IDs accept the same parameters and support every mode; only billing differs. See the pricing page for current prices. The examples below use gpt-image-2; replace it with gpt-image-2-official to bill by tokens.
Quick example
curl https://api.toklab.ai/v1/images/generations \
-H "Authorization: Bearer $TOKLAB_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "An amber glass bottle on a cream background, studio lighting",
"size": "1024x1024",
"quality": "low"
}'Endpoint
POST https://api.toklab.ai/v1/images/generations| Header | Value |
|---|---|
| Authorization | Bearer YOUR_API_KEY |
| Content-Type | application/json |
The same endpoint handles generation, reference edits, and masked edits. The response contains a task ID, not the finished image. Keep API keys in server-side code.
Parameters
| Name | Type | Required | Default | Notes |
|---|---|---|---|---|
model | string | Yes | — | gpt-image-2 or gpt-image-2-official |
prompt | string | Yes | — | Nonblank; up to 32,000 characters. |
images | object[] | No | — | 1–16 objects shaped as {"image_url":"https://..."}; adding images selects editing. |
mask | object | No | — | {"image_url":"https://..."}; requires images. |
size | string | No | auto | auto or WIDTHxHEIGHT, subject to the rules below. |
quality | enum | No | auto | auto, low, medium, high. |
background | enum | No | auto | auto, opaque, transparent. |
output_format | enum | No | png | png, jpeg. |
output_compression | integer | No | 100 for JPEG | 0–100; send only with jpeg. Zero is valid. |
n | integer | No | 1 | 1–10 images. |
moderation | enum | No | auto | auto, low. |
user | string | No | — | Optional application end-user identifier. Avoid personal information. |
Size rules
Common choices are 1024x1024, 1536x1024, and 1024x1536. Custom dimensions must satisfy every rule:
- Width and height are multiples of 16.
- Neither edge exceeds 3840 pixels.
- The aspect ratio is between 1:3 and 3:1.
- Total area is between 655,360 and 8,294,400 pixels, inclusive.
auto leaves the output dimensions to the model. Do not send aspect ratios such as 16:9 as size.
Send the final dimensions as size; there are no separate resolution or aspect_ratio parameters. For example, a 16:9 image at 4K is size: "3840x2160", 9:16 at 4K is "2160x3840", and 1:1 at 2K is "2048x2048".
OpenAI describes resolutions above 2560×1440 as experimental. They are accepted within the limits above; higher resolution is not a guarantee of better detail.
Quality tiers
Use low for drafts and compare results before choosing a higher tier. auto lets the model choose; it does not guarantee a particular tier or cost.
Transparent backgrounds
Transparency is in preview for GPT Image 2. For a transparent background, set background: "transparent" and use PNG. JPEG does not support transparency. Compression applies only to JPEG.
Optional scalar settings (n, size, quality, background, output_format, output_compression, moderation) accept null as omission. Unknown fields are rejected. input_fidelity is not configurable for GPT Image 2; reference inputs always use high fidelity. style and response_format belong to other image models and are not accepted here.
Modes
There is no separate mode parameter or editing endpoint to choose.
| Operation | Parameters |
|---|---|
| Text to image | prompt |
| Reference edit | prompt + images |
| Masked edit | prompt + images + mask |
Edit reference images
curl https://api.toklab.ai/v1/images/generations \
-H "Authorization: Bearer $TOKLAB_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "Make the bottle blue. Preserve the composition and lighting.",
"images": [{"image_url": "https://example.com/reference.png"}],
"mask": {"image_url": "https://example.com/mask.png"},
"output_format": "jpeg",
"output_compression": 90
}'Replace both example URLs with your own accessible images. Omit mask for a reference edit without a selected region.
Media inputs
This API accepts URL references only. OpenAI Files IDs, base64 data URLs, and multipart uploads are not accepted.
Reference images must be public HTTP(S) URLs pointing to PNG, JPEG, or WebP files smaller than 50 MB each. A mask must be a PNG smaller than 4 MB, with the same dimensions as the first reference image; its transparent area marks what to edit. A mask guides the model and does not guarantee pixel-perfect boundaries. For multiple references, the mask applies to the first image. URL media is validated during processing; invalid or inaccessible media can produce a failed task.
API requests use JSON URL objects: do not send file bytes, base64, data: URLs, blob: URLs, or multipart form data.
Pricing dimensions
Check the pricing page for current rates. gpt-image-2 (Standard) charges one flat price per delivered image, whatever the quality, size, or prompt. On gpt-image-2-official (Official), the final cost depends on input and output usage: quality, output dimensions, reference images, prompt length, and image count can all affect it.
View final charges in your account usage history. Failed tasks are not charged.
Output schema
Submission returns a task reference:
{
"id": "task_...",
"model": "gpt-image-2",
"status": "processing",
"created_at": 1789970508
}Poll the task
curl https://api.toklab.ai/v1/tasks/YOUR_TASK_ID \
-H "Authorization: Bearer $TOKLAB_API_KEY"Poll at a modest interval, such as every three seconds, until status is completed or failed. A network timeout while polling does not mean generation failed: keep the task ID and resume checking it. Do not create another task to check progress.
Complete polling example
Run this after the Python submission example above. It uses the returned task_id and waits up to ten minutes. Reaching this local deadline stops polling only; retain the ID and resume querying the same task.
import time
print(f"Task ID: {task_id}")
deadline = time.monotonic() + 600
while time.monotonic() < deadline:
result = requests.get(
f"https://api.toklab.ai/v1/tasks/{task_id}",
headers={"Authorization": f"Bearer {os.environ['TOKLAB_API_KEY']}"},
timeout=30,
)
result.raise_for_status()
task = result.json()
if task["status"] == "completed":
for image in task["output"]["data"]:
print(image["url"])
break
if task["status"] == "failed":
raise RuntimeError(task["error"]["message"])
time.sleep(3)
else:
raise TimeoutError(f"Still waiting. Resume polling task {task_id}.")Completed task
A completed task returns hosted image URLs and usage:
{
"id": "task_...",
"model": "gpt-image-2",
"status": "completed",
"created_at": 1789970508,
"finished_at": 1789970538,
"output": {
"created": 1789970532,
"data": [{"url": "https://cdn.example.com/media/tasks/task_example/0.png"}],
"usage": {
"input_tokens": 29,
"output_tokens": 196,
"total_tokens": 225
}
}
}| Field | Meaning |
|---|---|
id | Keep this ID for subsequent queries. |
status | processing, completed, or failed. |
created_at, finished_at | Unix timestamps in seconds; completion time is unset or zero while processing. |
output.data[].url | Generated image URLs, available on completion. |
output.size | Actual output dimensions, when reported. |
output.quality | Actual quality tier, when reported. |
output.background | Actual background, when reported. |
output.output_format | Actual image format, when reported. |
output.usage | Reported token usage, when available. Detail objects may contain text and image token counts. |
error | Structured error on a failed task. |
This API uses asynchronous task delivery. It is not a synchronous Images SDK replacement; stream and partial_images are not supported.
Errors
Requests rejected before a task is created return an HTTP error with an error object. A task that fails after acceptance returns HTTP 200 when queried, with status: "failed" and an error object.
See the shared error catalog for codes, HTTP statuses, and retry guidance. All model APIs use the same error envelope.
{
"id": "task_...",
"status": "failed",
"error": {
"code": 60002,
"message": "Generation could not be completed. Please try again."
}
}If submission itself times out, check your task history before submitting again: the first request may have been accepted.
Tips
- Describe materials, composition, and lighting in the prompt.
- For an edit, specify both the change and what should remain unchanged.
- Use a mask when only a selected area should change.
- Save returned images to your own storage when you need a durable copy.
Pricing
Every rate this model is billed at, read live from the price list billing uses. A tier applies when its condition matches, checked top to bottom.
gpt-image-2
per request| Request | $0.01875 |
|---|
gpt-image-2-official
per 1M tokens| Input | $3.75 |
|---|---|
| Output | $22.50 |
| Cache read | $0.9375 |
| Image input | $6.00 |
| Image cache read | $1.50 |