DEVELOPER REFERENCE / IMAGE

Image API

Generate images with Kling and Seedream. Check model-specific fields, save outputs, and recover async tasks.

Updated November 8, 2026Sync + async
POST/v1/images/generations
Replace placeholders and check model access before running requests. Live requests may incur usage charges.

1. Getting started

This reference applies only to https://api.sinorouter.ai. The image API uses OpenAI-style JSON, with different extensions for Kling and Seedream. Do not interchange their model-specific fields.

BASH
read -r -s -p "SinoRouter API_KEY (hidden): " API_KEY; printf '\n'
export API_KEY
export BASE_URL="https://api.sinorouter.ai"

Examples use Bash, curl and jq. The result-saving helper in §4 also requires Python 3. Curl examples using --fail-with-body require a curl version that supports that option. Keep API keys on your server and out of public code.

BASE_URL above is the site root; request paths below already include /v1. For an SDK's OpenAI Base URL setting, use https://api.sinorouter.ai/v1. Do not add /v1 twice. Site-specific tokens, model access and groups must match this domain.

1.1 Available image models

Exact request modelSite statusToken group
kling-image-v3EnabledImage All in One
kling-image-v3-omniEnabledImage All in One
doubao-seedream-5-0-pro-260628EnabledImage All in One
doubao-seedream-5-0-lite-260128EnabledImage All in One
doubao-seedream-5-0-flash-260915EnabledImage All in One

Both synchronous generation and asynchronous image tasks are enabled. Async requests apply only to enabled image models routable through your token group. Check current console availability if a route is unavailable.

2. Kling image generation

Synchronous endpoint: POST /v1/images/generations. A synchronous success response contains the final image data; no task polling is required.

FieldContract
modelkling-image-v3 or kling-image-v3-omni
promptRequired, non-empty text
resolutionExplicit lowercase 1k / 2k recommended; 4k is omni-only. size can also specify resolution, but pixel dimensions are mapped to a tier, not guaranteed exactly
aspect_ratio16:9, 9:16, 1:1, 4:3, 3:4, 3:2, 2:3, 21:9; default 16:9. auto applies only to omni
nInteger 1–9, default 1; different from Seedream's sequential-generation mechanism
image / image_listFor v3, use image as one URL string. For omni, use image_list as an array of URL strings
negative_promptAvailable for v3; not forwarded for omni

2.1 Text-to-image example

BASH
curl --fail-with-body --silent --show-error --max-time 300 \
  -X POST "$BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  --data-raw '{
  "model": "kling-image-v3",
  "prompt": "An orange cat on a windowsill watching the rain",
  "aspect_ratio": "1:1",
  "resolution": "1k",
  "n": 1
}' \
  -o kling.json

2.2 Reference-image example

Reference images must have publicly downloadable HTTP(S) URLs that require no login, cookies or authorization headers. Prefer stable HTTPS image hosting. Do not use private-network addresses or expired links. Some hosts restrict downloads; past Kling calls recorded blocked overseas image hosts and failures with signed links. Prefer stable direct links that do not require signatures where available.

BASH
read -r -p "Publicly downloadable reference-image URL: " REF_IMAGE_URL
jq -n --arg image "$REF_IMAGE_URL" '{model:"kling-image-v3",prompt:"Keep the subject and change the background to a blue photography studio",image:$image,resolution:"1k",aspect_ratio:"1:1",n:1}' > kling-reference.json
curl --fail-with-body --silent --show-error --max-time 300 \
  -X POST "$BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @kling-reference.json -o kling.json

For multiple references with omni, change model to kling-image-v3-omni and replace image with image_list: ["https://example.com/first.png", "https://example.com/second.png"]. Replace the example URLs with real accessible images. This reference does not specify a verified Kling reference-count or upload-size limit; do not infer one from Seedream's limits.

3. Seedream image generation

3.1 Models and limits

Exact model IDRecommended sizeReference-image limitSequential output
doubao-seedream-5-0-pro-2606281K / 1.5K / 2K10 imagesNot supported; do not send auto
doubao-seedream-5-0-lite-2601282K / 3K / 4K14 imagesSupports auto
doubao-seedream-5-0-flash-2609151K / 1.5K / 2K10 imagesNot supported; do not send auto

model and prompt are required. Use synchronous POST /v1/images/generations; explicitly setting size: "2K" and response_format: "url" is recommended.

You may supply size: "WIDTHxHEIGHT" within the selected model's total pixel range: Pro / Flash: 921600–4624220; Lite: 3686400–16777216. The total pixel count is width multiplied by height, not a limit on either dimension alone. The width-to-height ratio must also be within 1:16–16:1; both limits must be satisfied. Do not use Kling's resolution, aspect_ratio or image_list as Seedream parameters.

3.2 Synchronous text-to-image example

BASH
curl --fail-with-body --silent --show-error --max-time 300 \
  -X POST "$BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  --data-raw '{
  "model": "doubao-seedream-5-0-lite-260128",
  "prompt": "An orange cat on a windowsill watching the rain, soft natural light",
  "size": "2K",
  "response_format": "url"
}' \
  -o seedream.json

3.3 Reference-image field and formats

Use image: a string for one image or an array of strings for several, for example image: ["https://example.com/first.png", "https://example.com/second.png"]. Replace these URLs with your own images. URLs must be publicly downloadable without custom authorization headers.

Complete data URIs are also accepted, for example data:image/png;base64,ACTUAL_BASE64_DATA, with a lowercase media type. Raw Base64 strings and {url: ...} objects are not accepted.

BASH
read -r -p "Publicly downloadable reference-image URL: " REF_IMAGE_URL
jq -n --arg image "$REF_IMAGE_URL" '{model:"doubao-seedream-5-0-lite-260128",prompt:"Keep the subject and change the background to a blue photography studio",image:$image,size:"2K",response_format:"url"}' > seedream-reference.json
curl --fail-with-body --silent --show-error --max-time 300 \
  -X POST "$BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @seedream-reference.json -o seedream.json

3.4 Sequential output and model differences

For Lite only, set sequential_image_generation: "auto" and use sequential_image_generation_options: {"max_images": 4} to cap output count.

  • max_images must be an integer from 1 to 15.
  • Reference images plus output images must total no more than 15.
  • The cap is not a guaranteed output count. Process the actual data array.
  • For one image, omit the sequential fields or use "disabled".
  • Do not request Seedream sequential output with n: 4; omit n or use only 1.
  • Pro and Flash do not support sequential output. Omit both sequential_image_generation and sequential_image_generation_options for these models.
BASH
curl --fail-with-body --silent --show-error --max-time 300 \
  -X POST "$BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  --data-raw '{
  "model": "doubao-seedream-5-0-lite-260128",
  "prompt": "Create four coordinated illustrations of the same orange cat in spring, summer, autumn and winter",
  "size": "2K",
  "response_format": "url",
  "sequential_image_generation": "auto",
  "sequential_image_generation_options": {
    "max_images": 4
  }
}' \
  -o seedream-group.json

4. Responses and image downloads

For a synchronous success response, data is an array of image entries:

Response fieldMeaning
data[i].urlDownload URL in URL mode
data[i].b64_jsonEncoded image in Base64 mode
data[i].sizeImage size, when included by Seedream
data[i].errorPer-image error; an entry containing only an error is not a successful image

Do not treat the synchronous response as a task_id. response_format: "url" is the documented request mode used in these examples. A b64_json response may be handled by the helper below; the complete model-specific request-format enum still requires backend confirmation.

4.1 Save every returned image

Save the following helper as save_images.py beside your scripts. Requires Python 3 only. It supports synchronous responses and completed asynchronous task objects, processes all returned items, reports per-item failures and decodes b64_json where present. It checks common file signatures to choose an extension; unrecognized binary formats are saved as .bin. Signature detection does not replace image decoding or visual inspection.

PYTHON
#!/usr/bin/env python3
"""Save synchronous image results or a completed async task. No API key needed."""
import base64
import json
from pathlib import Path
import sys
import urllib.error
import urllib.parse
import urllib.request


def extension(data):
    if data.startswith(b"\x89PNG\r\n\x1a\n"):
        return ".png"
    if data.startswith(b"\xff\xd8\xff"):
        return ".jpg"
    if data[:6] in (b"GIF87a", b"GIF89a"):
        return ".gif"
    if data.startswith(b"RIFF") and data[8:12] == b"WEBP":
        return ".webp"
    if data.startswith(b"BM"):
        return ".bmp"
    if data[:4] in (b"II*\x00", b"MM\x00*"):
        return ".tiff"
    if data[4:8] == b"ftyp":
        if data[8:12] in (b"avif", b"avis"):
            return ".avif"
        if data[8:12] in (b"heic", b"heix", b"mif1"):
            return ".heif"
    return ".bin"


def main():
    if len(sys.argv) != 3:
        raise ValueError("Usage: python3 save_images.py RESPONSE.json OUTPUT_DIR")
    document = json.loads(Path(sys.argv[1]).read_text())
    if not isinstance(document, dict):
        raise ValueError("Expected a JSON object")
    if "status" in document:
        if document["status"] != "completed":
            raise ValueError("Async task is not completed; inspect status/error")
        result = document.get("result")
    else:
        result = document
    entries = result.get("data") if isinstance(result, dict) else None
    if not isinstance(entries, list) or not entries:
        raise ValueError("No image entries; inspect the original response")
    output = Path(sys.argv[2])
    output.mkdir(parents=True, exist_ok=True)
    failures = 0
    for index, item in enumerate(entries, 1):
        temp = output / f"image-{index}.part"
        try:
            if not isinstance(item, dict):
                raise ValueError("Invalid image entry")
            if item.get("error"):
                raise ValueError("Per-image error: " + json.dumps(item["error"]))
            if item.get("url"):
                url = item["url"]
                if not isinstance(url, str) or urllib.parse.urlsplit(url).scheme not in ("http", "https"):
                    raise ValueError("Expected an HTTP(S) image URL")
                # Preserve the full URL. Never add the API Authorization header.
                with urllib.request.urlopen(url, timeout=120) as response:
                    if urllib.parse.urlsplit(response.url).scheme not in ("http", "https"):
                        raise ValueError("Unsupported redirect scheme")
                    content_type = response.headers.get_content_type()
                    data = response.read()
                if content_type.startswith("text/") or "json" in content_type:
                    raise ValueError("Image host returned text/JSON")
            elif item.get("b64_json"):
                data = base64.b64decode(item["b64_json"], validate=True)
            else:
                raise ValueError("No URL or Base64 image in this entry")
            if not data or data.lstrip().startswith((b"{", b"[", b"<")):
                raise ValueError("Empty image or text-like error response")
            target = output / f"image-{index}{extension(data)}"
            if target.exists():
                # Re-running a task can re-use an identical result without overwriting it.
                if target.read_bytes() == data:
                    print(f"Already saved: {target}")
                    continue
                raise ValueError("Existing output differs; choose a new output directory")
            with temp.open("xb") as stream:
                stream.write(data)
            temp.rename(target)
            print(f"Saved: {target}; verify image decoding before use")
        except Exception as error:
            failures += 1
            # Do not print full signed URLs from HTTP/URL exceptions.
            if isinstance(error, urllib.error.HTTPError):
                message = f"Image download HTTP {error.code}"
            elif isinstance(error, urllib.error.URLError):
                message = "Image download network error"
            else:
                message = str(error)
            print(f"Image {index} failed: {message}", file=sys.stderr)
    return 1 if failures else 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (ValueError, OSError) as error:
        print(f"Cannot save images: {error}", file=sys.stderr)
        sys.exit(1)

Run this after the relevant synchronous generation example. For the sequential example, change RESPONSE_FILE to seedream-group.json; for Kling, use kling.json.

BASH
RESPONSE_FILE="seedream.json"
python3 save_images.py "$RESPONSE_FILE" ./saved-images

4.2 Storage and URL handling

Download promptly to storage you control. Result links may expire and are not permanent asset addresses. Preserve the complete URL, including every signature query parameter. Image downloads do not need the SinoRouter API key; never attach the API authorization header to the image host.

The helper writes a temporary file before finalizing each download and reports partial failures. A .png filename does not convert JPEG or WebP data into PNG. Verify the actual downloaded image before using it downstream.

5. Asynchronous image tasks

Async image tasks use the same model-specific request body as the corresponding synchronous endpoint.

5.1 Submit and query

OperationEndpointResponse
SubmitPOST /v1/images/generations/asyncHTTP 202; top-level task object
QueryGET /v1/images/tasks/{task_id}Top-level task object; not wrapped in data

Submission returns top-level id, task_id, object, status, created_at, expires_at and poll_url. The initial status is processing. The Location header and poll_url identify the same relative path; the documented Retry-After value is 3 seconds. HTTP 202 means accepted, not generated successfully.

Submit and query with the same API token belonging to the same user, on the same site. Treat task IDs as opaque strings; URL-encode them when building a path instead of relying on a fixed prefix or length.

5.2 Task fields and terminal outcomes

FieldDescription
statusprocessing, completed or failed
http_status / completed_atMay be present at a terminal state
result.data[i].urlImage URL in a completed task; process all items
image_urlShortcut to the first image
errorFailure details when status is failed
expires_atTask-record expiry; not the image URL's expiry

A query can return HTTP 200 while the task is failed. Read status before processing images.

5.3 Submit, poll and download

This example uses Kling v3, 1k, one image. Keep save_images.py from §4.1 in the current directory. It will also save multiple output entries if present. Changing models requires changing the request body's model-specific fields, not just MODEL.

Submission is attempted once. A persistent task directory supports recovery without blindly resending the POST. Do not enable set -x. Keep the directory private because it contains temporary access-bearing download links.

BASH
#!/usr/bin/env bash
set -euo pipefail
umask 077
BASE_URL="https://api.sinorouter.ai"
# Do not enable set -x. Submit and query with the same SinoRouter token.
read -r -s -p "SinoRouter API_KEY (hidden): " API_KEY; printf '\n'
: "${API_KEY:?API_KEY must not be empty}"
[[ -f save_images.py ]] || { printf 'Save save_images.py from section 4 first.\n' >&2; exit 1; }
MODEL="kling-image-v3"
PROMPT="An orange on a tabletop with a pure white background, minimal product photography"
# First run creates a task directory. Resume with export RUN_DIR=ORIGINAL_DIRECTORY.
RUN_DIR="${RUN_DIR:-$(mktemp -d ./image-task.XXXXXX)}"
mkdir -p "$RUN_DIR"
printf 'Task directory: %s\n' "$RUN_DIR"
if [[ -f "$RUN_DIR/base-url.txt" ]]; then
  [[ "$(cat "$RUN_DIR/base-url.txt")" == "$BASE_URL" ]] || { printf 'Resume the task on the original site.\n' >&2; exit 1; }
else
  printf '%s\n' "$BASE_URL" > "$RUN_DIR/base-url.txt"
fi
if [[ ! -s "$RUN_DIR/task-id.txt" ]]; then
  [[ ! -e "$RUN_DIR/submit-started" ]] || { printf 'Previous submission outcome is uncertain. Inspect submit.json and contact support; do not automatically resend.\n' >&2; exit 1; }
  jq -n --arg model "$MODEL" --arg prompt "$PROMPT" \
    '{model:$model,prompt:$prompt,resolution:"1k",aspect_ratio:"1:1",n:1}' > "$RUN_DIR/request.json"
  touch "$RUN_DIR/submit-started"
  # POST once only; do not automatically retry even after a network failure.
  HTTP=$(curl --silent --show-error --max-time 60 --proto '=https' \
    "$BASE_URL/v1/images/generations/async" \
    -H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" \
    --data-binary @"$RUN_DIR/request.json" -o "$RUN_DIR/submit.json" -w '%{http_code}') || {
      printf 'Submission transfer failed; preserve the directory and do not resubmit.\n' >&2; exit 1;
    }
  [[ "$HTTP" == 202 ]] || { printf 'Submission HTTP %s; inspect submit.json and do not blindly retry.\n' "$HTTP" >&2; exit 1; }
  TASK_ID=$(jq -er '(.task_id // .id) | select(type == "string" and length > 0)' "$RUN_DIR/submit.json")
  printf '%s\n' "$TASK_ID" > "$RUN_DIR/task-id.txt"
fi
TASK_ID=$(cat "$RUN_DIR/task-id.txt")
: "${TASK_ID:?Empty task_id}"
TASK_PATH=$(jq -rn --arg id "$TASK_ID" '$id | @uri')
printf 'TASK_ID=%s\n' "$TASK_ID"
for ((attempt=1; attempt<=600; attempt++)); do
  HTTP=$(curl --silent --show-error --max-time 60 --proto '=https' \
    "$BASE_URL/v1/images/tasks/$TASK_PATH" -H "Authorization: Bearer $API_KEY" \
    -o "$RUN_DIR/task.json" -w '%{http_code}') || {
      printf 'Query transfer failed. Resume with the same directory, site and token; do not resend POST.\n' >&2; exit 1;
    }
  [[ "$HTTP" == 200 ]] || { printf 'Query HTTP %s; inspect task.json.\n' "$HTTP" >&2; exit 1; }
  STATUS=$(jq -er '.status | select(type == "string")' "$RUN_DIR/task.json")
  case "$STATUS" in
    completed) break ;;
    processing) sleep 3 ;;
    failed) jq '.error' "$RUN_DIR/task.json" >&2; exit 1 ;;
    *) printf 'Unknown status: %s\n' "$STATUS" >&2; exit 1 ;;
  esac
done
jq -e '.status == "completed"' "$RUN_DIR/task.json" >/dev/null || {
  printf 'Client wait ended; this is not task failure. Preserve the directory and resume queries; do not submit again.\n' >&2; exit 1;
}
# The helper reads result.data for async tasks, not top-level data.
# It handles every output entry and never sends the API key to image hosts.
python3 save_images.py "$RUN_DIR/task.json" "$RUN_DIR/images"
unset API_KEY

5.4 Expiry and recovery

The source specifies image download links valid for 24 hours; that is not a guarantee of image-object retention. Save results to your own storage promptly.

Task records are documented as expiring 24 hours after creation or a status change, using the latest expires_at. Queries do not extend retention, and long-term retention is not guaranteed.

To resume, set RUN_DIR to the original directory and rerun the script with the same site and API token. A client waiting limit does not mean the task failed. If the POST outcome is uncertain and no task ID was saved, inspect submit.json and contact support rather than automatically submitting again. Do not publish API keys or full temporary result URLs.

6. Troubleshooting

SymptomCheck / action
401 / authentication failureVerify the key belongs to this site, is active, and uses Authorization: Bearer followed by one space and the key
No available channelUse an enabled model from §1.1 and an Image All in One token group. Do not rely on group conventions in older documentation
404 / HTML responseCheck the site and /v1 path, duplicate /v1 and invisible characters. Async is enabled on this site; verify its exact task path and token permissions
Reference-image download failureCheck expiry, public access and login requirements; use a stable accessible host. Seedream data URIs must include a media type
Size or sequential parameters rejectedKling uses lowercase resolution; Seedream uses uppercase size presets. Pro and Flash do not support sequential output. Omit both sequential_image_generation and sequential_image_generation_options for these models. Do not use n for Seedream groups
Async query returns 404Check task ID, submitting token and expires_at. Do not query with a different token
Async query returns 200 but no imageRead status: continue waiting for processing; inspect error for failed; read result.data for completed
model_price_errorServer-side model configuration issue. Preserve the request identifier and contact the administrator

When requesting support, provide the site, model ID, request time with timezone, HTTP status, error body and task ID if any. Do not send your API key. A synchronous client timeout may be set to 300 seconds, but a timeout does not prove generation has stopped on the server; avoid blind resubmission.

Use current console notices for model or feature changes.