Media generation

Upload references, generate images and video, and poll jobs through the ToyGate headless media API.

Reference

The headless media API covers the three calls a batch pipeline needs: upload local media, generate an image synchronously, and generate video as a pollable job. Every /v1 media endpoint authenticates with a bearer API key and scopes ownership to that key.

export TOYGATE_API_URL="https://api.toygate.store"
export TOYGATE_API_KEY="gw_<your-key>"

At a glance

SurfaceEndpointResponse shape
UploadPOST /v1/files (multipart)one file object
ImagePOST /v1/images/generationssynchronous image payload
Image statusGET /v1/images/generations/:job_idjob status envelope
Video submitPOST /v1/videos/generationsjob id, status processing
Video statusGET /v1/videos/generations/:job_idjob status envelope

Files and jobs are owned by the API key that created them. A different key — even one on the same account — receives 404 file_not_found or 404 job_not_found for a foreign id and for an unknown id alike. /client/files is a separate browser surface that authenticates with session cookies; it is not part of the /v1 media contract.

1. Upload a reference

A successful upload returns 201 with the file record:

{
  "id": "file_0f1e2d3c4b5a69788796a5b4",
  "object": "file",
  "purpose": "reference_image",
  "mime_type": "image/png",
  "size": 842173,
  "width": 1024,
  "height": 1536,
  "duration_ms": null,
  "created_at": "2026-10-23T09:15:04.000Z",
  "expires_at": "2026-10-30T09:15:04.000Z"
}

Audio uses the same route with the driving_audio purpose. Its dimensions are null and duration_ms is populated when the container carries duration metadata:

curl -sS "$TOYGATE_API_URL/v1/files" \
  -H "Authorization: Bearer $TOYGATE_API_KEY" \
  -F "file=@./dialogue.wav" \
  -F "purpose=driving_audio"
{
  "id": "file_7a6b5c4d3e2f1a0b9c8d7e6f",
  "object": "file",
  "purpose": "driving_audio",
  "mime_type": "audio/wav",
  "size": 1310720,
  "width": null,
  "height": null,
  "duration_ms": 8400,
  "created_at": "2026-10-23T09:16:11.000Z",
  "expires_at": "2026-10-30T09:16:11.000Z"
}
PurposeAccepted contentMax sizeRetention
reference_imageJPEG, PNG, WebP20 MiB7 days
driving_audioMPEG audio (MP3), WAV15 MiB7 days
reference_videoMP4, MOV (1–15 s, 240–4096 px, ≤ 8:1 aspect)100 MiB7 days

You can also import media from a public https: URL by posting Content-Type: application/json ({ "url": "https://...", "purpose": "reference_video" }). Redirects, private-network hosts, and spoofed MIME headers are rejected.

The gateway sniffs the MIME type from the bytes instead of trusting headers. purpose is optional; without it the gateway infers the purpose from the sniffed content. The whole multipart body is capped at 105 MiB. Expired ids behave exactly like unknown ids. Read or release a file with its id:

curl -sS "$TOYGATE_API_URL/v1/files/$FILE_ID" \
  -H "Authorization: Bearer $TOYGATE_API_KEY"

curl -sS -X DELETE "$TOYGATE_API_URL/v1/files/$FILE_ID" \
  -H "Authorization: Bearer $TOYGATE_API_KEY" \
  -o /dev/null -w '%{http_code}\n'

DELETE answers 204 with an empty body. While an active generation still holds the file it answers 409 with file_in_use; wait for that job to finish, then delete again.

Rejected uploads use the standard error envelope:

{
  "error": {
    "message": "Uploaded file is not a valid image",
    "type": "invalid_request_error",
    "code": "invalid_image"
  }
}

The audio equivalent is invalid_audio. A file above its size limit returns 413 with payload_too_large, and a multipart body without exactly one file part returns 400 with invalid_body.

2. Generate an image

Image generation is synchronous: the request returns once the upstream has produced the image, so there is no submit-then-poll cycle for the image itself.

curl -sS "$TOYGATE_API_URL/v1/images/generations" \
  -H "Authorization: Bearer $TOYGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "seedream-5.0-pro",
    "prompt": "the same character at dusk, cinematic key light",
    "images": [
      { "file_id": "file_front" },
      { "file_id": "file_side" },
      { "file_id": "file_back" }
    ],
    "aspect_ratio": "16:9",
    "resolution": "1K",
    "response_format": "b64_json"
  }'

Reference rules:

  • images accepts 1–16 entries (bounded by each route's max_reference_images, e.g. 5 for Grok, 10 for Seedream/Nano Banana, 16 for GPT Image 2.5/2.6), and the array order is the order the model receives.
  • Every entry carries exactly one of file_id or url; a url must be https:.
  • References cannot exceed the selected route's max_reference_images; going over returns reference_limit_exceeded before any credits are reserved.
  • The route must accept references. A route that ignores images is rejected with the wire code model_does_not_support_reference rather than silently producing an unconditioned image.
  • n greater than 1 is refused with unsupported_parameter unless the model explicitly supports multiple outputs. seed is accepted only where the model declares seed support, also unsupported_parameter otherwise.

The older single-reference form stays available, and it accepts either a file_id or a url. Send image or images, never both:

{
  "model": "seedream-5.0-pro",
  "prompt": "same character, plain backdrop",
  "image": { "url": "https://media.example/reference.png" }
}

A successful call returns both the ToyGate job envelope and the OpenAI-compatible data[] array:

{
  "job_id": "8f14e45f-ea0b-4f2a-9d3b-2c1f0a6b7c11",
  "status": "succeeded",
  "media_status": "ready",
  "output_media_url": "https://media.toygate.store/gen/out-0001.png",
  "created": 1731500000,
  "model": "seedream-5.0-pro",
  "data": [
    { "url": "https://media.toygate.store/gen/out-0001.png" }
  ]
}

When response_format is "b64_json", data[] returns verified base64 bytes immediately ({ "b64_json": "..." }). For "url" (or when omitted), ToyGate waits up to 10 seconds to publish the durable copy to ToyGate media storage so data[0].url and output_media_url point to ToyGate media rather than a temporary provider host. If storage publication takes longer than 10 seconds, the response returns media_status: "pending", output_media_url: null, and data: [] — poll the job endpoint until media_status becomes "ready". The submit response carries no credit figure.

Reading the image job is optional for "b64_json" or when media_status is already "ready". It never re-runs generation and is useful to wait for a pending output_media_url or to read the settled credit figure:

curl -sS "$TOYGATE_API_URL/v1/images/generations/$JOB_ID" \
  -H "Authorization: Bearer $TOYGATE_API_KEY"
{
  "id": "8f14e45f-ea0b-4f2a-9d3b-2c1f0a6b7c11",
  "job_id": "8f14e45f-ea0b-4f2a-9d3b-2c1f0a6b7c11",
  "status": "succeeded",
  "model": "seedream-5.0-pro",
  "media_status": "ready",
  "output_media_url": "https://media.example/gen/out-0001.png",
  "credits_used": 77000,
  "error_code": null,
  "error_message": null,
  "created_at": "2026-10-23T09:20:04.000Z",
  "completed_at": "2026-10-23T09:20:31.000Z",
  "expires_at": "2026-11-22T09:20:04.000Z"
}

3. Generate a video

Video submission is asynchronous. The call validates the request, reserves credits, creates the job, and returns immediately; the clip is produced behind the job id.

First frame is the only Wan video reference mode enabled by the current ToyGate production capability flags. The provider schema also documents last-frame, reference-image, reference-audio and seed inputs, but those ToyGate modes remain owner-gated. Until they are explicitly enabled, they return 400 unsupported_parameter before credits are reserved. Do not use the following examples against production until that separate owner approval has landed.

Owner-gated upstream modes (not enabled by default)

The provider schema documents these request shapes:

{"image":{"file_id":"file_first"},"last_frame":{"file_id":"file_last"}}

or, instead of frames:

{"references":[{"file_id":"file_character"},{"file_id":"file_location"}],"reference_videos":[{"file_id":"file_clip"}],"reference_audios":[{"file_id":"file_dialogue"}],"seed":7}

Do not mix image/last_frame with references/reference_videos/driving_audio/reference_audios: the upstream modes are mutually exclusive. Reference video clips (reference_videos, up to 5 clips, each 1–15 s, total ≤ 15 s, ≤ 100 MiB) can be passed by file_id or https: url (imported once into ToyGate storage before credit reservation) and bill input_video_seconds + output_duration at the model's per-second rate (input_video_seconds + duration ≤ 30). Audio inputs (driving_audio or up to 5 reference_audios, 1–15 s, total ≤ 15 s, ≤ 15 MiB) are reference tracks, not a promised lip-sync driver. When enabled, duration: -1 lets the model choose duration and reserves the upper bound (30 total seconds including input video), then reconciles to the confirmed duration. last_frame, references, reference_videos, driving_audio, reference_audios, and seed remain refused until the corresponding route capability is enabled by an owner-approved configuration change. negative_prompt, prompt_extend and shot_type are not documented by the upstream and always return 400 unsupported_parameter.

To generate a first-frame clip today, use only image:

{"model":"wan-3.0","prompt":"the character walks across the room","image":{"file_id":"file_first"},"duration":5,"resolution":"720p","aspect_ratio":"16:9","audio":true}
{
  "id": "2b6d1f0a-3c4e-4a5b-8c9d-0e1f2a3b4c5d",
  "status": "processing",
  "model": "wan-3.0"
}

The submit call answers 200, or 202 when the upstream acknowledged the job asynchronously.

Reference mode uses ordered reference images and an optional driving-audio track instead of frames:

curl -sS "$TOYGATE_API_URL/v1/videos/generations" \
  -H "Authorization: Bearer $TOYGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "wan-3.0",
    "prompt": "the two characters walk through the market",
    "references": [
      { "file_id": "file_character" },
      { "file_id": "file_location" }
    ],
    "driving_audio": { "file_id": "file_dialogue" },
    "duration": 5,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }'

image is the first frame, last_frame is the final frame, references is an ordered array of up to 10 entries, driving_audio is an uploaded audio track, and seed is an integer. Which of them a model accepts is gated by the route: last_frame, references, driving_audio, audio and seed each answer unsupported_parameter (or unsupported_audio for audio) when the selected model does not declare that capability. wan-3.0 also requires an explicit duration.

Poll the job with its id:

curl -sS "$TOYGATE_API_URL/v1/videos/generations/$JOB_ID" \
  -H "Authorization: Bearer $TOYGATE_API_KEY"
{
  "id": "2b6d1f0a-3c4e-4a5b-8c9d-0e1f2a3b4c5d",
  "status": "succeeded",
  "model": "wan-3.0",
  "result": { "duration_seconds": 5 },
  "media_status": "ready",
  "output_media_url": "https://media.example/gen/clip-0001.mp4",
  "error_code": null,
  "error_message": null,
  "credits_used": 210000,
  "created_at": "2026-10-23T09:24:02.000Z",
  "completed_at": "2026-10-23T09:26:40.000Z",
  "expires_at": "2026-11-22T09:24:02.000Z"
}

A safe polling loop — GET has no side effects and can be repeated freely:

delay=2
while :; do
  body=$(curl -sS "$TOYGATE_API_URL/v1/videos/generations/$JOB_ID" \
    -H "Authorization: Bearer $TOYGATE_API_KEY")
  status=$(printf '%s' "$body" | jq -r '.status')
  case "$status" in
    succeeded|failed)
      printf '%s\n' "$body"
      break
      ;;
  esac
  sleep "$delay"
  delay=$(( delay < 30 ? delay * 2 : 30 ))
done

4. Unsupported parameters and incompatible combinations

negative_prompt, prompt_extend and shot_type are not accepted by any video model. Sending one returns 400 and names the field:

curl -sS "$TOYGATE_API_URL/v1/videos/generations" \
  -H "Authorization: Bearer $TOYGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "wan-3.0", "prompt": "a quiet street", "duration": 5, "negative_prompt": "blur"}'
{
  "error": {
    "message": "negative_prompt is not supported by any video model",
    "type": "invalid_request_error",
    "code": "unsupported_parameter"
  }
}

The request is rejected rather than accepted and ignored, so a pipeline never pays for a parameter it did not get.

Frame mode and reference mode cannot be mixed. A first frame or last frame alongside a reference array is rejected as a body-level conflict:

{
  "error": {
    "message": "references cannot be combined with image or last_frame",
    "type": "invalid_request_error",
    "code": "invalid_body"
  }
}

The same rule covers driving audio with frames: the upstream schema treats the ordered reference set (and the audio that accompanies it) as one mode, and the first/last frame pair as another. Pick one mode per job, and send a single job for each half of a scene that needs both.

Other gate errors on this route:

CodeMeaning
invalid_durationwan-3.0 was called without an explicit duration
unsupported_durationDuration is outside the model's declared list
unsupported_resolutionResolution is outside the model's declared list
unsupported_aspect_ratioAspect ratio is outside the model's declared list
unsupported_audioaudio: true on a model without audio control
model_not_foundUnknown slug, or the model does not support video generation
model_does_not_support_referenceFirst frame requested on a route that does not accept one

5. Status schema, credits, and errors

Both status endpoints use one envelope. It is also the payload style the media pipeline should store next to the job id.

FieldTypeNotes
id, job_idstringImage status returns both; video status returns id
statusstringqueued, processing, succeeded, failed, cancelled
modelstringThe slug you requested
resultobject or nullVideo only: duration_seconds
media_statusstring or nullpending, ready, failed, orphaned
output_media_urlstring or nullDurable URL, non-null only when media_status is ready
credits_usednumber or nullnull while the job is in flight
error_codestring or nullCanonical code from the table below
error_messagestring or nullClient-safe description
created_atstringISO 8601 timestamp
completed_atstring or nullISO 8601 timestamp
expires_atstring or nullOutputs are retained for 30 days
errorstringPresent on failed jobs, equal to error_message

status reports job progress, and media_status reports whether the durable copy exists. A job can be succeeded with media_status: "pending"; keep polling until media_status becomes ready, because output_media_url stays null before that point.

Credits settle at the end of the job. credits_used is a number once the job succeeds, 0 after a failure or cancellation, and null while it is still running. A failed or cancelled job does not expose a successful generation result; keep the status envelope with its error_code and error_message.

Media error codes:

CodeHTTPMeaningAction
file_not_found404Id is unknown, expired, or owned by another keyRe-upload
file_in_use409An active generation still holds the fileWait, then delete again
invalid_image, invalid_audio400Bytes are not a valid image, or not MPEG/WAV audioConvert or replace the file
payload_too_large413File or request body exceeded its limitReduce the file size
invalid_body400JSON, multipart, or parameter combination is invalidFix the request; see the message
reference_not_found404Reference id is unknown, expired, or not owned by this keyRe-upload the reference
reference_limit_exceeded400More references than the public or model limit allowsRemove references
model_does_not_support_reference400The route does not accept a reference imageDrop the reference or change model
unsupported_parameter400The model does not support a requested fieldRemove or change the field
model_not_found404Model slug is unknown, disabled, or lacks the capabilityCheck the slug
job_not_found404Job id is unknown, expired, or owned by another keyCheck the id and key
concurrency_limit429Too many requests for this key are in flightRetry after Retry-After: 1
rate_limit_exceeded429Request rate for the key was exceeded; error.code is nullHonour Retry-After: 60, then back off
insufficient_quota429AI credit balance is exhausted; error.code is nullTop up; retries will not help
ownerless_api_key403The API key is not linked to an accountUse a key bound to a user
upstream_unavailable502 / 503No route, open breaker, or transport failureRetry with backoff
upstream_timeout504The upstream timed outPoll video jobs; verify image outcome before resubmitting
upstream_invalid_response, upstream_error502The upstream answer could not be usedRetry; report persistent failures
media_storage_unavailable503Media storage is not availableRetry later
internal_error500Unexpected gateway failureReport timestamp, endpoint, and envelope

Status responses canonicalize the stored failure. Expect insufficient_credits, invalid_request, model_not_reference_capable, rate_limit_exceeded, provider_error, provider_timeout, reference_not_found, job_not_found, and internal_error in error_code. Wire codes such as insufficient_quota, concurrency_limit, model_does_not_support_reference, invalid_body, the upstream_* family, and media_storage_unavailable are mapped onto those canonical values, so store error_code rather than reconstructing it from the submit response.

6. Retries, backoff, and concurrency

Keep 2–3 generations in flight per API key. The gateway also enforces its own in-flight cap for the process handling the request (MAX_STREAMS_PER_KEY, default 20); exceeding it returns 429 concurrency_limit with Retry-After: 1. There is no hard cap on queued jobs, so a producer that submits faster than it polls will accumulate unfinished jobs rather than fail fast — pace the batch.

Honour a numeric Retry-After when the response carries one. Otherwise back off exponentially at 1, 2, 4, 8, 16, then 30 seconds capped at 30:

retry_media_request() {
  for delay in 1 2 4 8 16 30 30; do
    code=$(curl -sS -o body.json -w '%{http_code}' "$@") || code=000
    case "$code" in
      2??)
        cat body.json
        return 0
        ;;
      429|5??)
        sleep "$delay"
        ;;
      *)
        cat body.json >&2
        return 1
        ;;
    esac
  done
  return 1
}

Only an idempotent GET — a status poll or a file lookup — is unconditionally safe to repeat after a timeout or a 5xx.

A POST submit is not unconditionally safe to repeat. Treat its outcome as ambiguous unless that specific response path is known to reject before credit reservation. Correct validation errors before trying again; a concurrency/admission denial can be retried after its delay when it is confirmed to be pre-reservation. An upstream 429, 502, or 504 can happen after reservation, and a network timeout may hide a created job. Check the generation history in the ToyGate studio or reconcile against the response before submitting again. A 429 with insufficient_quota requires an account change.

7. Hermès batch scripts

The repository ships two Bun commands for a headless episode pipeline. Both read TOYGATE_API_URL and TOYGATE_API_KEY from the environment only, and both upload local inputs to /v1/files with the reference_image or driving_audio purpose.

TOYGATE_API_URL=https://api.example TOYGATE_API_KEY=gw_example bun scripts/generate-shot.ts \
  --model seedream-5.0-pro --reference ./character-front.png \
  --reference ./character-side.png --prompt "..." --aspect-ratio 16:9 \
  --resolution 1K --seed 42 --output ./out

--reference is repeatable 1–9 times. The image script makes exactly one synchronous request, saves the image as shot-<created>.png, and writes shot-<created>.json beside it with the request, the file ids, and timings. It records that image generation returns no credit figure rather than inventing one.

TOYGATE_API_URL=https://api.example TOYGATE_API_KEY=gw_example bun scripts/generate-video-shot.ts \
  --model wan-3.0 --image ./first-frame.png --audio ./dialogue.wav \
  --duration 5 --resolution 720p --aspect-ratio 16:9 \
  --reference ./character.png --seed 7 --output ./out

The video script requires --model, --image, --audio, --duration, --resolution, --aspect-ratio, and --output; --prompt, --last-frame, and --seed are optional, and --reference is repeatable up to 10 times. It writes <job-id>.json before polling, saves the clip as <job-id>.mp4, and resumes an interrupted run with --job-id <id> --output <dir>. Failed jobs keep their job id and failure detail in the metadata file.

Both scripts retry 429 up to five attempts and 5xx up to three, honouring a numeric Retry-After and otherwise backing off 1, 2, 4, 8 seconds up to 30. Other 4xx responses fail immediately. Video submission is never retried automatically after a network error; the script asks you to check the generation list instead.

8. Voice and text-to-speech

Text-to-speech, voice enrollment, and voice cloning are not implemented in this API, and this guide does not promise them. A driving_audio upload is input media for a video job; it is not a voice model, and no endpoint returns synthesized speech. Adding such a surface would require a verified provider contract, recorded consent from the speaker, and owner approval before any public contract is documented.

See Errors for the shared error envelope and Error codes for the chat-side catalogue.