Media generation
Upload references, generate images and video, and poll jobs through the ToyGate headless media API.
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.
At a glance
| Surface | Endpoint | Response shape |
|---|---|---|
| Upload | POST /v1/files (multipart) | one file object |
| Image | POST /v1/images/generations | synchronous image payload |
| Image status | GET /v1/images/generations/:job_id | job status envelope |
| Video submit | POST /v1/videos/generations | job id, status processing |
| Video status | GET /v1/videos/generations/:job_id | job 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:
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:
| Purpose | Accepted content | Max size | Retention |
|---|---|---|---|
reference_image | JPEG, PNG, WebP | 20 MiB | 7 days |
driving_audio | MPEG audio (MP3), WAV | 15 MiB | 7 days |
reference_video | MP4, MOV (1–15 s, 240–4096 px, ≤ 8:1 aspect) | 100 MiB | 7 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:
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:
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.
Reference rules:
imagesaccepts 1–16 entries (bounded by each route'smax_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_idorurl; aurlmust behttps:. - References cannot exceed the selected route's
max_reference_images; going over returnsreference_limit_exceededbefore any credits are reserved. - The route must accept references. A route that ignores images is rejected with the wire code
model_does_not_support_referencerather than silently producing an unconditioned image. ngreater than 1 is refused withunsupported_parameterunless the model explicitly supports multiple outputs.seedis accepted only where the model declares seed support, alsounsupported_parameterotherwise.
The older single-reference form stays available, and it accepts either a file_id or a url. Send
image or images, never both:
A successful call returns both the ToyGate job envelope and the OpenAI-compatible data[] array:
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:
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:
or, instead of frames:
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:
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:
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:
A safe polling loop — GET has no side effects and can be repeated freely:
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:
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:
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:
| Code | Meaning |
|---|---|
invalid_duration | wan-3.0 was called without an explicit duration |
unsupported_duration | Duration is outside the model's declared list |
unsupported_resolution | Resolution is outside the model's declared list |
unsupported_aspect_ratio | Aspect ratio is outside the model's declared list |
unsupported_audio | audio: true on a model without audio control |
model_not_found | Unknown slug, or the model does not support video generation |
model_does_not_support_reference | First 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.
| Field | Type | Notes |
|---|---|---|
id, job_id | string | Image status returns both; video status returns id |
status | string | queued, processing, succeeded, failed, cancelled |
model | string | The slug you requested |
result | object or null | Video only: duration_seconds |
media_status | string or null | pending, ready, failed, orphaned |
output_media_url | string or null | Durable URL, non-null only when media_status is ready |
credits_used | number or null | null while the job is in flight |
error_code | string or null | Canonical code from the table below |
error_message | string or null | Client-safe description |
created_at | string | ISO 8601 timestamp |
completed_at | string or null | ISO 8601 timestamp |
expires_at | string or null | Outputs are retained for 30 days |
error | string | Present 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:
| Code | HTTP | Meaning | Action |
|---|---|---|---|
file_not_found | 404 | Id is unknown, expired, or owned by another key | Re-upload |
file_in_use | 409 | An active generation still holds the file | Wait, then delete again |
invalid_image, invalid_audio | 400 | Bytes are not a valid image, or not MPEG/WAV audio | Convert or replace the file |
payload_too_large | 413 | File or request body exceeded its limit | Reduce the file size |
invalid_body | 400 | JSON, multipart, or parameter combination is invalid | Fix the request; see the message |
reference_not_found | 404 | Reference id is unknown, expired, or not owned by this key | Re-upload the reference |
reference_limit_exceeded | 400 | More references than the public or model limit allows | Remove references |
model_does_not_support_reference | 400 | The route does not accept a reference image | Drop the reference or change model |
unsupported_parameter | 400 | The model does not support a requested field | Remove or change the field |
model_not_found | 404 | Model slug is unknown, disabled, or lacks the capability | Check the slug |
job_not_found | 404 | Job id is unknown, expired, or owned by another key | Check the id and key |
concurrency_limit | 429 | Too many requests for this key are in flight | Retry after Retry-After: 1 |
rate_limit_exceeded | 429 | Request rate for the key was exceeded; error.code is null | Honour Retry-After: 60, then back off |
insufficient_quota | 429 | AI credit balance is exhausted; error.code is null | Top up; retries will not help |
ownerless_api_key | 403 | The API key is not linked to an account | Use a key bound to a user |
upstream_unavailable | 502 / 503 | No route, open breaker, or transport failure | Retry with backoff |
upstream_timeout | 504 | The upstream timed out | Poll video jobs; verify image outcome before resubmitting |
upstream_invalid_response, upstream_error | 502 | The upstream answer could not be used | Retry; report persistent failures |
media_storage_unavailable | 503 | Media storage is not available | Retry later |
internal_error | 500 | Unexpected gateway failure | Report 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:
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.
--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.
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.