Use image endpoints
Generate and edit images with OpenAI-compatible endpoints.
Last updated on
Generate one image first
Choose an available image model from the current catalog. This minimal request asks for one base64-encoded result and saves the JSON response:
export PROVOD_API_KEY="sk_..."
curl --fail-with-body --silent --show-error https://api.provod.ai/v1/images/generations \
-H "Authorization: Bearer $PROVOD_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-image-2",
"prompt": "A clean product banner on a neutral background",
"response_format": "b64_json",
"n": 1
}' \
-o response.jsonA representative response has a data array. Each item contains either b64_json or url, according to the requested and supported response format:
{
"created": 1786651200,
"data": [
{
"b64_json": "iVBORw0KGgo..."
}
]
}For the b64_json request above, decode the first result into a file:
node -e 'const fs = require("node:fs"); const body = JSON.parse(fs.readFileSync("response.json", "utf8")); fs.writeFileSync("image.png", Buffer.from(body.data[0].b64_json, "base64"));'If you request url and the selected model supports it, read data[0].url instead. A successful response is never an empty generation: it contains at least one usable image item.
Start with generation, then add only options published by the selected model.
Discover capabilities before adding options
The image-specific catalog exposes current models, availability, operations, option constraints, reference limits, and streaming support, meaning whether partial results can arrive before the final images:
export PROVOD_API_KEY="sk_..."
curl --fail-with-body --silent --show-error https://api.provod.ai/v1/images/models \
-H "Authorization: Bearer $PROVOD_API_KEY"Check the selected record's available, capabilities, and supported_parameters. Options such as aspect_ratio, size, quality, resolution, background, output format, and compression are model-specific. For current Google image models, for example, aspect_ratio and resolution are separate controls whose allowed values come from that exact catalog record. Do not copy a combination from another model.
The field n controls the number of final output images, within the selected model's published range. It does not control edit references. Repeated image[] parts are ordered input images; their allowed count comes from capabilities.maxReferenceImages.
Stream through the unified endpoint
Streaming uses POST /v1/images, not /v1/images/generations. Select a currently available generation model whose catalog record permits at least one partial image, then make the request:
set -euo pipefail
export PROVOD_API_KEY="sk_..."
if ! IMAGE_MODELS_JSON="$(
curl --fail-with-body --silent --show-error https://api.provod.ai/v1/images/models \
-H "Authorization: Bearer $PROVOD_API_KEY"
)"; then
printf '%s\n' "$IMAGE_MODELS_JSON" >&2
exit 1
fi
if ! PROVOD_IMAGE_MODEL="$(
jq -er '
first(
.data[]
| select(
.available == true
and .capabilities.generation == true
and .supports_streaming == true
and ((.supported_parameters.partial_images.max // 0) >= 1)
)
| .id
)
' <<<"$IMAGE_MODELS_JSON"
)"; then
printf 'No available streaming image model found in /v1/images/models.\n' >&2
exit 1
fi
export PROVOD_IMAGE_MODEL
jq -n --arg model "$PROVOD_IMAGE_MODEL" '{
model: $model,
prompt: "A clean product banner on a neutral background",
stream: true,
partial_images: 1,
n: 1
}' | curl --no-buffer --fail-with-body --silent --show-error https://api.provod.ai/v1/images \
-H "Authorization: Bearer $PROVOD_API_KEY" \
-H "Content-Type: application/json" \
--data-binary @-Each SSE record uses a data: line. Read the JSON type field to distinguish partial, completed, and error records. A successful stream can contain partial and completed image records and ends with [DONE]:
data: {"type":"image_generation.partial_image","partial_image_index":0,"b64_json":"iVBORw0KGgo..."}
data: {"type":"image_generation.completed","b64_json":"iVBORw0KGgo..."}
data: [DONE]A failed stream can emit a data record with the public code and message:
data: {"type":"error","error":{"code":"IMAGE_UPSTREAM_FAILED","message":"Image generation failed"}}Treat type: error or a connection close before [DONE] as incomplete. Retry with a bounded backoff only if no partial or completed image has arrived. After output starts, preserve it and require an explicit decision before another request because an automatic retry can duplicate work and cost.
Edit with multipart form data
Use POST /v1/images/edits only for a model whose catalog record publishes edit support. curl -F creates the required multipart/form-data body and boundary:
export PROVOD_API_KEY="sk_..."
curl --fail-with-body --silent --show-error https://api.provod.ai/v1/images/edits \
-H "Authorization: Bearer $PROVOD_API_KEY" \
-F "model=google/gemini-3.1-flash-image" \
-F "prompt=Keep the subject and replace the background" \
-F "image[]=@reference.png" \
-F "aspect_ratio=16:9" \
-F "response_format=b64_json" \
-o response.jsonAdd more image[] parts in the intended order only while staying within the model's current reference limit. Add a mask part only when the model publishes mask support.
A public error code is the client-facing code in an API error response. MODEL_PARAMETER_COMBINATION_INVALID means the selected model cannot accept the requested option combination. MODEL_CAPABILITY_METADATA_UNAVAILABLE means the service cannot currently verify that combination against capability metadata. Use the exact returned code and current catalog values instead of guessing a replacement option.
Durable jobs and recovery
For large batches, use POST /v1/images/jobs. After validation and persistence it returns 202 with a job ID. The queue processes the accepted job independently of the submitting connection. Existing /generations and /edits keep their synchronous behavior.
Submit, poll and download
curl --fail-with-body --max-time 30 https://api.provod.ai/v1/images/jobs \
-H "Authorization: Bearer $PROVOD_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: post-123-image-v1" \
-d '{"model":"openai/gpt-image-2.5-flare","prompt":"A clean product banner on a neutral background","n":1}' \
-o job.json
JOB_ID=$(jq -r '.id' job.json)
curl --fail-with-body https://api.provod.ai/v1/images/jobs/$JOB_ID \
-H "Authorization: Bearer $PROVOD_API_KEY"
# After a saved output appears in data:
curl --fail-with-body --location "https://api.provod.ai/v1/images/jobs/$JOB_ID/content?index=0" \
-H "Authorization: Bearer $PROVOD_API_KEY" -o output.pngJob states are QUEUED, RUNNING, COMPLETED, PARTIALLY_COMPLETED, FAILED, and CANCELED. Persist id as soon as you receive it: this is the job ID for polling. request_id identifies the original HTTP admission request and does not replace the job ID. Saved files appear in data, with content_url, media_type and byte_size. On partial completion, download available outputs and inspect error_code. An empty data array is not a failure while the job remains nonterminal.
Status reads and saved-file downloads do not start generation or create another charge. Downloads redirect to a short-lived URL; request the protected /content route again if that URL expires. Use an active API key for the same workspace. Only successfully saved files are recoverable.
Optional Idempotency-Key
The header is optional. Use 1–200 printable ASCII characters without spaces. Without it, each POST creates an independent job that you can poll by its returned ID. If the POST response is lost before you receive the ID, repeating the request without an idempotency key cannot be promised safe from a second generation.
For reliable retries, persist the key with your business operation before the first submission. The same key and JSON payload return the existing queued, running or finished job, without another reservation or job. JSON field order does not matter. A changed payload with a reused key returns 409 IMAGE_IDEMPOTENCY_CONFLICT. Keys are scoped to the workspace and API key: keep the same API key when retrying the same operation. Use a new idempotency key for an intentionally new generation, never merely because the connection timed out.
Once 202 returned a valid job ID, repeat only GET requests. Idempotency protects job admission; it does not promise exactly one upstream request across every provider failure or worker restart.
The jobs API returns metadata and download links rather than the synchronous b64_json response, even when that format is requested.
Reuse references
Upload each source file once to POST /v1/images/input-assets, using multipart/form-data, a file field and the same API key. Save its returned id. Submit JSON jobs with operation: "edit" and inputImageIds: ["asset_..."]. ID order is reference order. The model must support editing and the requested reference count. Reusing IDs avoids uploading identical bytes again and consuming storage allowance with duplicates. Changing the ID array changes the idempotent request payload.
To upload a mask, send multipart field role=mask to /v1/images/input-assets, then submit its ID as maskImageId with operation=edit and inputImageIds. Omit role for ordinary references.
Python: submission retry, polling and download
This example uses httpx: these additional routes are not standard OpenAI SDK methods. Set API_KEY and persist operation_key in your own queue or database. The example retries POST only after a transport failure, always with the same key. Once it receives an ID, it retries only status reads.
import os
import time
from pathlib import Path
import httpx
# Persist this key with your business operation before the first POST.
# Reuse it, and the same payload, after a network failure.
API_KEY = os.environ["PROVOD_API_KEY"]
operation_key = "post-123-image-v1"
payload = {
"model": "openai/gpt-image-2.5-flare",
"prompt": "A clean product banner on a neutral background",
"n": 1,
"response_format": "b64_json",
}
with httpx.Client(
base_url="https://api.provod.ai",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=httpx.Timeout(connect=15, read=30, write=60, pool=15),
) as client:
for attempt in range(3):
try:
response = client.post(
"/v1/images/jobs",
headers={"Idempotency-Key": operation_key},
json=payload,
)
response.raise_for_status()
job = response.json()
break
except httpx.TransportError:
if attempt == 2:
raise # Keep operation_key; resume with it later.
time.sleep(2)
job_id = job["id"]
Path("image-job-id.txt").write_text(job_id)
terminal = {"COMPLETED", "PARTIALLY_COMPLETED", "FAILED", "CANCELED"}
for _ in range(360):
try:
response = client.get(f"/v1/images/jobs/{job_id}")
except httpx.TransportError:
time.sleep(5)
continue # Retry this GET, never create another job.
if response.status_code in {429, 500, 502, 503, 504}:
time.sleep(5)
continue
response.raise_for_status()
job = response.json()
if job["status"] in terminal:
break
time.sleep(5)
else:
raise TimeoutError(f"Keep polling job {job_id}; do not resubmit it")
for item in job["data"]:
result = client.get(item["content_url"], follow_redirects=True)
result.raise_for_status()
suffix = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
Path(f"{job_id}-{item['index']}{suffix.get(item['media_type'], '.bin')}").write_bytes(result.content)
if job["status"] != "COMPLETED":
raise RuntimeError(f"{job['status']}: {job['error_code']}; saved outputs were downloaded")Start with a 15-second connection timeout and 30-second read timeout for small JSON submissions and status reads. Configure reference uploads and large downloads for their size and connection speed. Poll about every five seconds. Your application's waiting deadline does not cancel an accepted job: keep its ID and resume polling later. Provider errors, storage failures and server reservation expiry still apply; read the actual job state. The API admits up to four active image jobs per workspace; do not generate new keys to bypass a 429 response.
Recover an older synchronous request
For /v1/images/generations, /v1/images/edits and unified /v1/images, save the response's x-request-id, including error responses. A connection timeout or HTTP 504 does not establish that processing stopped or no result exists. Raising the SDK read timeout does not disable proxy timeouts.
REQUEST_ID="saved-request-id"
curl --fail-with-body "https://api.provod.ai/v1/images/requests/$REQUEST_ID" \
-H "Authorization: Bearer $PROVOD_API_KEY" -o recovered.json
CONTENT_PATH=$(jq -er '.outputs[0].content_url' recovered.json)
curl --fail-with-body --location "https://api.provod.ai$CONTENT_PATH" \
-H "Authorization: Bearer $PROVOD_API_KEY" -o output.pngThis read-only view returns status, terminal, error_code and saved outputs. incomplete means the available records do not establish a complete result, not proof that a request is still running. 404 means no accessible record or file, not permission to safely create another generation. The endpoint cannot recover an image that the provider never returned or storage never saved.
Job idempotency does not apply retroactively to synchronous POSTs. For support, retain the time and timezone, model, endpoint, request ID, HTTP status, error text and client timeout settings. Do not send API keys, prompts or reference files.
Download using the content_url returned in outputs: it identifies a specific saved image and keeps pointing to that image when other outputs finish later.
Reconcile image charges
Read billing from GET /v1/images/requests/{request_id} or GET /v1/images/jobs/{job_id}. Monetary values are decimal strings with eight fractional digits in currency:
{
"billing": {
"currency": "RUB",
"settlement_status": "settled",
"charged_amount": "10.00000000",
"reserved_amount": "0.00000000",
"released_amount": "2.00000000",
"refund_coverage": "verified_links_only",
"refunded_amount": "1.00000000",
"net_amount": "9.00000000"
}
}charged_amount comes from posted usage debits. reserved_amount is the active hold; released_amount is released hold value, not a refund. settlement_status is pending, settled, or unknown for the initial usage settlement. It is independent of generation terminal, and later refunds may still appear after settled.
refunded_amount includes only positive refunds with a verified reference to this operation's debit, in the same workspace and currency. refund_coverage: "verified_links_only" excludes unlinked manual credits. net_amount subtracts those verified refunds only; it is not a guarantee that every manual credit can be attributed. Conflicting or over-limit refund records return refund_coverage: "unknown" and null refund/net amounts.
A null amount or unknown means the saved evidence is insufficient; do not turn it into zero or substitute an estimated price. Historical missing links and execution-unit requests whose hold belongs to a whole job may remain unknown; read the job by its own ID. A released hold with confirmed zero captured usage can report a settled zero debit. Status reads and downloads do not start generation or alter charges. Continue polling the same operation after a timeout; this view does not promise a fixed settlement deadline.