DEVELOPERS / API v1
Developer integration guide
From your first request to recovery: fields, examples and handling rules in integration order.
Quick start
- Sign in, create an application API key and save its once-visible secret; ensure sufficient balance.
- Obtain the HTTPS gateway origin from your operator. GATEWAY_URL excludes /v1 and a trailing slash.
- Query models and prices, select a model with matching capabilities, then submit generation.
export GATEWAY_URL="https://<gateway-host>"
export GATEWAY_API_KEY="<your-api-key>"
curl "$GATEWAY_URL/v1/models" -H "Authorization: Bearer $GATEWAY_API_KEY"
curl "$GATEWAY_URL/v1/prices" -H "Authorization: Bearer $GATEWAY_API_KEY"Commands use Bash. Replace all angle-bracket placeholders; example sizes, durations, prices and dates are illustrative. Use a new idempotency key per new operation and preserve it for recovery. Discovery determines availability; contact the operator if the list is empty.
Authentication & conventions
| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
Authorization | headerRequired | Bearer <API Key> for all /v1 endpoints including queries and downloads. Console tokens are not interchangeable; keep API keys on your server. |
Content-Type | headerConditional | Use application/json for JSON bodies, encoded as UTF-8. |
Idempotency-Key | headerOptional | Strongly recommended for generation: 16–128 random characters from A–Z, a–z, 0–9, _, -. No personal data. Scoped by account and operation kind. |
X-Request-Id | response headerConditional | Platform operation ID, not your idempotency key; persist when provided. |
Location | response headerConditional | Operation lookup for chat, task lookup for accepted media. Authentication still required. |
Retry-After | response headerConditional | Suggested delay in seconds, possibly on 202, 429 or 503; combine with bounded backoff. |
Undeclared request fields are rejected. Only the documented Chat Completions subset is supported, excluding tools, audio, image messages, logprobs, Responses API and OpenAI image/video endpoints.
Models & prices
GET /v1/models
| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
object / data | string / arrayRequired | Model list envelope: object is list; data contains models. Empty means no callable models. |
id / kind | string / enumRequired | Model ID and kind: chat, image, video. |
input_modes | string[]Required | Supported input modes: text, reference_image. |
limits | objectRequired | Actual model limits apply in addition to the general request bounds. |
limits.max_input_tokens / max_output_tokens | integer | nullOptional | Input/output token caps; null does not mean unlimited. |
limits.max_count | integer | nullOptional | Maximum images per request. |
limits.sizes / durations / fps | arrayOptional | Allowed sizes, durations in seconds, and frame rates; choose supported values. |
cancellation_supported | booleanRequired | Whether cancellation can be requested; stopping is not immediate or guaranteed. |
execution_seconds | integerRequired | Fixed execution window in seconds from acceptance. |
reconciliation_window_seconds | integerRequired | Reconciliation window in seconds. |
result_retention_seconds | integer | nullRequired | Media retention in seconds; task result_expires_at gives the actual expiry. |
price_version | stringRequired | Published price version. |
validation_status | enumRequired | mock_only: simulation; capability_verified: verified capability declaration; production_verified: production validation. Capability verification alone is not GPU acceptance. |
GET /v1/prices
| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
currency / data | string / arrayRequired | Price envelope: currency is USDT, data contains published prices and may be empty. |
model / version / kind | stringRequired | Model ID, immutable price version, and kind (chat/image/video). |
input_per_million | decimal stringOptional | USDT per million input tokens (chat). |
output_per_million | decimal stringOptional | USDT per million output tokens (chat). |
per_image | decimal stringOptional | USDT per delivered image. |
per_second | decimal stringOptional | USDT per delivered video second. |
All amounts are USDT decimal strings with eight fractional digits. Use decimal arithmetic, not floating-point accumulation. Chat prices apply per million input/output tokens; media prices apply to delivered images/seconds.
Chat & SSE
POST /v1/chat/completions
| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
model | stringRequired | Model ID from GET /v1/models; up to 128 characters. |
messages | arrayRequired | 1–128 messages in conversation order. |
messages[].role | stringRequired | Message role: system instructions, user input, or assistant response. |
messages[].content | stringRequired | Message text, 1–65536 characters; strings only, no images or content arrays. |
max_tokens | integerRequired | Output token cap, 1–131072, also bounded by model max_output_tokens. |
stream | booleanRequired | Must be true; non-streaming responses are unsupported. |
prompt_optimization | stringOptional | Defaults to conservative-v1 (conservative prompt preparation); off disables it. |
curl -N "$GATEWAY_URL/v1/chat/completions" \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: example_chat_0001" \
-d '{"model":"<chat-model-id>","messages":[{"role":"user","content":"Hello"}],"max_tokens":256,"stream":true}'200 · text/event-stream response
Use a streaming HTTP client supporting POST and custom auth headers (e.g. fetch + ReadableStream). Split SSE events on blank lines; a network read is not necessarily one JSON event. Ignore colon-prefixed heartbeat comments and append delta.content in order.
data: {"id":"op_example","object":"chat.completion.chunk","model":"<chat-model-id>","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}
data: {"id":"op_example","object":"chat.completion.chunk","model":"<chat-model-id>","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: {"id":"op_example","object":"chat.completion.chunk","model":"<chat-model-id>","choices":[],"usage":{"prompt_tokens":8,"completion_tokens":1,"total_tokens":9}}
data: [DONE]| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
id / object / model | stringRequired | Operation ID, constant chat.completion.chunk, and model ID. |
choices | arrayRequired | Choices in delta/finish chunks; empty in the final usage chunk. |
choices[].index | integerRequired | Always 0 in this subset. |
choices[].delta.content | stringConditional | Append text in arrival order; finish chunk delta is empty. |
choices[].finish_reason | string | nullRequired | null for deltas; stop in the normal finish chunk. |
usage.prompt_tokens / completion_tokens / total_tokens | integerConditional | Final usage chunk: input, output, and total tokens; names differ from operation usage. |
Normal completion includes final usage and [DONE]. Pre-stream failures use HTTP JSON errors; failures after streaming starts send event: error with error JSON, then close without [DONE]. On disconnect/missing completion, preserve received text and query the original operation; never regenerate transparently.
event: error
data: {"error":{"code":"upstream_error","message":"Execution interrupted; query operation status.","request_id":"op_example","operation_url":"/v1/operations/op_example"}}Images & video
POST /v1/images/tasksPOST /v1/videos/tasks
Shared request fields
Images: text-to-image with text, image-to-image with reference_image. Videos: text-to-video with text, image-to-video with reference_image. First query /v1/models and use only published input_modes and limits.sizes. Video-to-video is not supported.
| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
model | stringRequired | Image or video model ID, 1–128 characters. |
prompt | stringRequired | Description of the content to generate, 1–16384 characters. |
input_mode | stringOptional | Defaults to text; reference_image requires model support. |
reference_image | string (HTTPS URI)Conditional | Required for reference_image only. HTTPS port 443, up to 4096 characters; ask the operator to allow your image host. Static PNG/JPEG/WebP, at most 16 MiB and 16,777,216 pixels. No redirects, Base64, uploads or private addresses. Center-cropped to the output aspect ratio; transparency becomes white. |
prompt_optimization | stringOptional | Defaults to conservative-v1; set off to disable. |
Image fields
| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
size | stringOptional | Width x height; default 1024x1024. Square, landscape and portrait profiles extend to 3840x2160 / 2160x3840 / 4096x4096; select only published limits.sizes. Usually PNG; oversized PNG is encoded as high-quality JPEG without resizing. Decode using content_type. |
n | integerOptional | Image count, default 1, range 1–16, bounded by model max_count. |
Image generation: 512x512, 1024x1024, 1536x1024 and 1024x1536 are native. 2048x2048, 3840x2160, 2160x3840 and 4096x4096 use Real-ESRGAN x4plus super-resolution from a base image, not native 4K. Check the model catalog for currently published profiles.
Video fields
| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
duration_seconds | integerRequired | Video duration, 1–300 seconds; must appear in limits.durations. |
size | stringOptional | Width x height; defaults to 1280x720 only if both size and resolution are absent; model limits apply. |
resolution | stringOptional | Landscape alias: 480P=832x480, 720P=1280x720, 1080P=1920x1080; P is case-insensitive. Must agree with size if both are supplied. |
fps | integerOptional | Frames per second, default 24, range 1–120; must appear in limits.fps. |
curl "$GATEWAY_URL/v1/images/tasks" \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: example_image_0001" \
-d '{"model":"<image-model-id>","prompt":"A mountain at sunrise","size":"1024x1024","n":1}'
curl "$GATEWAY_URL/v1/videos/tasks" \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: example_video_0001" \
-d '{"model":"<video-model-id>","prompt":"A slow camera pan over mountains","duration_seconds":5,"resolution":"720P","fps":24}'Reference-image request body example
{
"model": "<image-model-with-reference-support>",
"prompt": "Keep the subject, use a studio background",
"input_mode": "reference_image",
"reference_image": "https://<allowed-image-host>/reference.png",
"size": "1024x1024",
"n": 1
}Image-to-video request body
{
"model": "video-wan22",
"prompt": "Gentle movement and a slow camera pan",
"input_mode": "reference_image",
"reference_image": "https://<allowed-image-host>/reference.png",
"size": "832x480",
"duration_seconds": 5,
"fps": 24
}Initial acceptance returns 202: reservation and operation accepted, not proof of upstream execution or completion. Repeating identical media parameters with the same key returns 200 and the original task without another generation/reservation. Persist task_id and operation.operation_id.
FLUX image-to-image redraws the reference and does not guarantee exact identity, text or layout preservation. Wan image-to-video uses your reference as its starting frame; text-to-video generates that frame first. High-resolution images remain asynchronous. File dimensions alone do not establish native detail; see model release notes for native versus super-resolution generation. Video 1080P is upscaled from 720P.
Poll, cancel & download
curl "$GATEWAY_URL/v1/tasks/<task_id>" -H "Authorization: Bearer $GATEWAY_API_KEY"
curl "$GATEWAY_URL/v1/tasks/<task_id>/queue" -H "Authorization: Bearer $GATEWAY_API_KEY"
curl -X POST "$GATEWAY_URL/v1/tasks/<task_id>/cancel" -H "Authorization: Bearer $GATEWAY_API_KEY"
curl "$GATEWAY_URL/v1/tasks/<task_id>/results/<storage_id>" \
-H "Authorization: Bearer $GATEWAY_API_KEY" -o result.pngThe queue endpoint may return media_queue.stage: waiting_input waits for a first frame, prepare_frame prepares it, ready_video waits with a committed frame, and render_video generates the video. A finished frame neither completes the video nor adds an image charge. Show unavailable estimates when tasks_ahead or estimated_wait_seconds is null; image priority means arrival order is not a fixed queue rank.
Use the returned task_id (task_ prefix). storage_id is the 64-character lowercase hex identifier in the result URL; do not invent it. Polling returns 200 with a task. Cancellation has no body: 202 accepts intent, 200 returns an existing terminal task.
| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
task_id | stringRequired | Media task ID for polling, cancellation and downloads; distinct from operation_id. |
operation | objectRequired | Full operation object, documented below. |
result | arrayRequired | Delivered results; empty when unavailable. Failed tasks may have partial results. |
result[].url | string (URI)Required | Gateway download URL requiring the same account's API key; not a public permanent link. |
result[].content_type | stringRequired | Artifact MIME type, e.g. image/png, image/jpeg, video/mp4, video/webm. |
result[].size | stringRequired | Output width x height, e.g. 1024x1024; not file size in bytes. |
result_expires_at | date-time | nullRequired | Fixed result expiry, possibly null before delivery; polling/downloading never extends it. |
error | string | nullRequired | Task error: generation_failed may include partial delivery; result_unavailable means results are unavailable (e.g. expired or revoked); null if absent. Inspect results and operation state together. |
Complete successful task example (illustrative amounts and dates)
{
"task_id": "task_example",
"operation": {
"operation_id": "op_example",
"kind": "image",
"model": "<image-model-id>",
"execution_status": "succeeded",
"billing_status": "settled",
"cancellation_status": "none",
"verified_usage": {
"delivered_images": 1
},
"charged_amount": "0.02000000",
"reversed_amount": "0.00000000",
"net_charged_amount": "0.02000000",
"reserved_amount": "0.02000000",
"held_amount": "0.00000000",
"currency": "USDT",
"price_version": "example-price-v1",
"media_task_id": "task_example",
"execution_deadline": "2026-11-15T10:05:00Z",
"reconciliation_deadline": "2026-11-16T10:05:00Z",
"deadline": "2026-11-16T10:05:00Z",
"updated_at": "2026-11-15T10:01:00Z"
},
"result": [
{
"url": "https://<gateway-host>/v1/tasks/task_example/results/<storage_id>",
"content_type": "image/png",
"size": "1024x1024"
}
],
"result_expires_at": "2026-11-16T10:01:00Z",
"error": null
}- Suggested polling: honor Retry-After; otherwise start at 2 seconds, increase to 10 seconds with jitter. This is client guidance, not a server limit. For unknown/reconciling, continue low-frequency recovery without creating another task.
- requested is not confirmed cancellation. Unsupported cancellation returns 409 cancellation_unsupported. Delivered partial output may still be charged; cancellation does not guarantee a full refund.
- Download results from your server using the same account's API key; opening a URL in a browser does not attach credentials. A successful download returns the complete binary file (200); no Range/resume support or retention extension.
- Expired, revoked, missing or other-account results return 404; unavailable files return 503; busy downloads return 429 with Retry-After. Save results before expiry; links are not permanent storage.
Operations & recovery
curl "$GATEWAY_URL/v1/operations/<operation_id>" -H "Authorization: Bearer $GATEWAY_API_KEY"
curl "$GATEWAY_URL/v1/operations/by-key/example_chat_0001?kind=chat" -H "Authorization: Bearer $GATEWAY_API_KEY"operation_id is the returned op_ identifier. For by-key, use the original Idempotency-Key and required kind: chat, image or video. A 200 response returns operation metadata only, never prompts or generated text.
| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
operation_id | stringRequired | Platform operation ID starting with op_, for recovery and support. |
kind / model | stringRequired | Operation kind (chat/image/video) and model ID. |
execution_status | enumRequired | Execution state; see the state reference below. |
billing_status | enumRequired | Billing state, independent of execution and cancellation. |
cancellation_status | enumRequired | Cancellation state; requested only means intent accepted. |
verified_usage | object | nullRequired | Verified usage; null means unknown, not zero. |
verified_usage.input_tokens / output_tokens | integerOptional | Verified nonnegative input/output token counts. |
verified_usage.delivered_images | integerOptional | Verified delivered image count. |
verified_usage.delivered_video_seconds | integerOptional | Verified delivered video seconds. |
charged_amount | decimal stringRequired | Original settled charge, immutable after corrections. |
reversed_amount | decimal stringRequired | Posted cumulative reversals, excluding pending compensation. |
net_charged_amount | decimal stringRequired | Net charge = charged_amount minus reversed_amount. |
reserved_amount | decimal stringRequired | Original authorized reservation cap. |
held_amount | decimal stringRequired | Amount currently held. |
currency / price_version | stringRequired | Currency USDT and price version fixed at acceptance. |
media_task_id | string | nullRequired | Related media task ID; null for chat. |
execution_deadline | date-timeRequired | Fixed execution deadline; polling does not extend it. |
reconciliation_deadline | date-timeRequired | Reconciliation deadline; uncertainty may shorten it, never extend it. |
deadline | date-timeRequired | Compatibility alias for reconciliation_deadline. |
updated_at | date-timeRequired | Last operation update. All timestamps use UTC RFC3339. |
Three independent state dimensions
| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
accepted → submitting → queued → running | execution_statusRequired | Accepted → submitting → queued → running; intermediate states may be skipped. |
succeeded / failed / cancelled / unknown | execution_statusRequired | Success / failure (possibly partial delivery) / cancelled / unknown outcome. Unknown is not proof of failure; recover by querying. |
reserved / reconciling / settled / released | billing_statusRequired | Reserved / reconciling / settled / released. Failure/disconnection may still have verified charges; release does not prove upstream execution stopped. |
none / requested / confirmed / unsupported / unknown | cancellation_statusRequired | None / requested / confirmed / unsupported / unknown cancellation outcome. Only confirmed establishes cancellation. |
- On timeout, disconnect or 502/504, query the saved operation ID; if missing, query by original key and kind.
- If found, resume tracking the original operation; repeat chat submission returns 409 operation_already_exists without text replay.
- 404 only means currently unavailable, not never executed. Recovery submission must preserve the original key and parameters. Without a key and with all response data lost, do not retry automatically.
- Different parameters with the same key return 409 idempotency_conflict; change keys only for an intentional new operation. Terminal metadata defaults to 90-day retention (operator configuration applies); never retry old keys indefinitely.
Error handling
{
"error": {
"code": "insufficient_balance",
"message": "Insufficient available balance",
"request_id": null,
"operation_url": null
}
}| Field | Type / presence | Meaning, defaults and limits |
|---|---|---|
error.code | stringRequired | Stable machine error code for programmatic handling; see below. |
error.message | stringRequired | Human-readable, potentially localized message; do not branch on this text. |
error.request_id | string | nullRequired | Related operation ID, or null before an operation is associated. |
error.operation_url | string | nullRequired | Authenticated operation lookup URL, or null if unavailable. |
| HTTP | code | Handling |
|---|---|---|
| 400 | invalid_request | Correct invalid, missing or extra fields. |
| 401 | invalid_api_key | Check for an invalid/revoked API key; do not use a console token. |
| 402 | insufficient_balance | Not accepted due to insufficient balance; fund the account first. |
| 403 | account_disabled / permission_denied | Resolve account status or permissions before retrying. |
| 404 | not_found | Record unavailable, result expired, or not owned; never proof of non-execution. |
| 409 | idempotency_conflict | Key reused with different parameters; restore original parameters for recovery. |
| 409 | operation_already_exists | Chat operation exists; query it. Generated text is not replayed. |
| 409 | cancellation_unsupported | Cancellation unsupported; continue checking the original task. |
| 413 | request_too_large | Reduce request or message size. |
| 422 | unsupported_capability | Check model limits and correct mode, size, count, duration or fps; do not silently switch models. |
| 429 | rate_limit_exceeded / unresolved_limit | Honor Retry-After seconds and use bounded backoff; recover unresolved operations first. |
| 503 | service_unavailable | Model/dependency unavailable; honor Retry-After and query uncertain operations first. |
| 502 / 504 | upstream_error / upstream_timeout | May have executed; recover by original ID/key, never retry under a new key. |
Launch checklist
- Test parameters against discovered models; never assume example IDs/default sizes work for every model.
- Test normal SSE, in-stream errors, disconnects and missing usage; HTTP 200 alone is not generation success.
- Test media success, partial failure, unsupported cancellation, expiry and authenticated downloads.
- Persist request-to-key mappings; test identical retries, conflicting retries, timeout recovery and insufficient balance.
- Handle 401/403 and 429/503 backoff; record operation IDs for support without logging API keys.