Wan 3.0 Video Generation API Developer Guide
Supported models: wan3.0-video-prime, wan3.0-video
API Base URL: https://openapi.yhsapi.com
Document version: 1.0 · Updated: 2026-11-07
This guide covers the full workflow for calling Wan 3.0 through this platform: preparing an API key, submitting a generation task, querying its status, retrieving the video, and handling rate limits, failures, and retries. Both models use the same endpoints and parameter schema; change only the request's model value to select one.
1. Models and Capabilities
| Model ID | Edition | Description |
|---|---|---|
wan3.0-video-prime | Prime | The provider describes it as matching Standard's capabilities with faster generation; actual latency depends on queueing, media, and output specifications |
wan3.0-video | Standard | Uses the same request format, task queries, and result schema |
Both models use asynchronous tasks and support the input scenarios below. See the official Wan 3.0 guide for model capabilities.
| Scenario | Input | Description |
|---|---|---|
| Text-to-video | input.prompt | Describe the video in text and omit media |
| First-frame generation | first_frame | Use an image as the starting frame |
| First-and-last-frame generation | first_frame + last_frame | Specify the starting and ending frames |
| Reference-based generation | reference_image / reference_video / reference_audio | Combine images, video, audio, and a prompt |
| File- or webpage-based generation | file or link | Generate from a public document or webpage, optionally with reference media |
| Video editing | reference_video + editing instructions | Describe changes to the style, visual content, or other aspects in the prompt |
| Video extension | reference_video + extension instructions | Explicitly specify the final output duration; adaptive aspect ratio is recommended |
The platform accepts 480P, 720P, and 1080P output resolutions and integer durations from 2 to 30 seconds. Requests must also meet the combined input/output duration limit and the specifications and capabilities currently enabled for the model. Output is MP4, with a standard model output frame rate of 30 fps. See the official output specifications.
2. Before You Begin
2.1 Access and Authentication
Create an active platform API key and confirm that the account balance, key quota, model permissions, and IP allowlist permit the call.
All submission and query requests use:
Authorization: Bearer <PLATFORM_API_KEY>Platform keys consist of LT- followed by 32 English letters or digits. Use the complete key issued by this platform. Bailian keys, website login JWTs, and keys from other platforms cannot authenticate these endpoints.
Call the API from your server and store the key in environment variables or a secret management service. Do not place it in frontend pages, mobile app packages, public repositories, or URL query parameters.
2.2 Endpoints
| Operation | Method | Full URL |
|---|---|---|
| Create a video task | POST | https://openapi.yhsapi.com/api/v1/services/aigc/video-generation/video-synthesis |
| Query a video task | GET | https://openapi.yhsapi.com/api/v1/tasks/{task_id} |
The base URL excludes /api/v1; do not add the path prefix twice. These endpoints use the Bailian-native schema. Use the exact paths above.
2.3 Protocol Conventions
- Submit UTF-8 JSON with
Content-Type: application/json. - Task submission requires
X-DashScope-Async: enable. Queries do not require this header. - Success and failure responses are JSON. HTTP request failures use standard HTTP status codes; task execution failures are reported through
output.task_statusin the query response. - The response body's
request_idand theX-Request-IDresponse header identify the current request for troubleshooting.request_idis not the task ID; each query has its own request identifier. - Use
Accept-Language: zh-CN,zh-Hant, orento select the error message language. The default is Simplified Chinese; theContent-Languageresponse header identifies the response language. Do not add a JSONlanguagefield.
3. Quickstart
The cURL examples use Bash / zsh syntax. On Windows PowerShell, use curl.exe and adapt environment variable and line continuation syntax, or use the Python example later in this guide.
Step 1: Set Environment Variables
export API_BASE_URL="https://openapi.yhsapi.com"
export PLATFORM_API_KEY="REPLACE_WITH_YOUR_COMPLETE_PLATFORM_API_KEY"Step 2: Submit a Task
curl --request POST \
"$API_BASE_URL/api/v1/services/aigc/video-generation/video-synthesis" \
--header "Authorization: Bearer $PLATFORM_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-Async: enable' \
--header 'Accept-Language: en' \
--data-raw '{
"model": "wan3.0-video-prime",
"input": {
"prompt": "At the seaside in the morning, a golden retriever runs along the beach. A steady tracking shot follows it in warm sunlight, with natural ocean sounds."
},
"parameters": {
"resolution": "720P",
"ratio": "16:9",
"duration": 5,
"audio": true
}
}'An accepted request returns HTTP 200:
{
"output": {
"task_id": "b5836ed1-f195-441d-990b-0eaec3b9f349",
"task_status": "PENDING"
},
"request_id": "33c511a7-d546-49dd-bb06-6405b5c51873"
}Save output.task_id immediately. This response means the platform has accepted the task; query it to obtain the final result.
Step 3: Query the Status
Replace the task ID with the actual returned value and use the same API key that created the task:
export TASK_ID="b5836ed1-f195-441d-990b-0eaec3b9f349"
curl --request GET \
"$API_BASE_URL/api/v1/tasks/$TASK_ID" \
--header "Authorization: Bearer $PLATFORM_API_KEY" \
--header 'Accept-Language: en'For PENDING or RUNNING, wait 10–15 seconds before querying again. For SUCCEEDED, read output.video_url and download the result. See task statuses for FAILED, CANCELED, and UNKNOWN. This polling interval is client guidance, not a generation time commitment.
4. Create a Video Generation Task
POST /api/v1/services/aigc/video-generation/video-synthesis4.1 Request Headers
| Header | Required | Value and description |
|---|---|---|
Authorization | Yes | Bearer <PLATFORM_API_KEY> |
Content-Type | Yes | application/json |
X-DashScope-Async | Yes | The lowercase string enable |
Accept-Language | No | zh-CN, zh-Hant, or en; defaults to Simplified Chinese |
4.2 Top-Level Request Body
| Field | Type | Required | Description |
|---|---|---|---|
model | string | Yes | wan3.0-video-prime or wan3.0-video; case-sensitive |
input | object | Yes | Prompt and input media |
parameters | object | No | Generation settings; omitting it selects a 5-second output at 1080P |
4.3 The input Object
| Field | Type | Required | Description |
|---|---|---|---|
prompt | string | Conditional | Describe subjects, actions, scenes, camera movement, and sound; provide at least one of prompt and media |
media | array of object | Conditional | 1–20 ordered media items; omit for text-only generation and provide at least one of prompt and media |
Keep prompts within 20,000 characters where possible, and shorten longer content yourself instead of relying on upstream truncation. Model configuration may impose an additional length limit, and the entire JSON body is always limited to 65,535 bytes. See the official prompt parameters.
Each item in media has this structure:
| Field | Type | Required | Description |
|---|---|---|---|
type | string | Yes | One of the media types below |
url | string | Yes | Publicly readable HTTP(S) media URL; preserve signed URLs exactly |
4.4 The parameters Object
| Field | Type | Default behavior | Allowed values and description |
|---|---|---|---|
resolution | string | The platform inserts 1080P | 480P, 720P, or 1080P; uppercase required |
ratio | string | The model defaults to adaptive when omitted | adaptive, 21:9, 16:9, 4:3, 1:1, 3:4, or 9:16 |
duration | integer | The platform inserts 5 | Output duration in seconds, an integer from 2 to 30; reference video also imposes a combined duration limit |
audio | boolean | The model defaults to true when omitted | true generates sound; false produces no audio track |
seed | integer | The model selects a random seed when omitted | -1 or 0–2147483647; -1 means random, and matching seeds do not guarantee identical results |
prompt_extend | boolean | The model defaults to true when omitted | Enable intelligent prompt rewriting; must not be false with file or link, and explicitly setting true is recommended |
watermark | boolean | The model defaults to false when omitted | Whether to add a watermark |
Omitted ratio, audio, seed, prompt_extend, and watermark remain unspecified and use the model's default behavior. Set them explicitly when fixed behavior is required. See the official parameter defaults.
The platform does not currently support duration: -1 for intelligent duration selection. It returns HTTP 403 with code: "UnsupportedOperation". Video editing and extension also require a fixed integer duration, or the default of 5 seconds when omitted.
4.5 Validation and Empty Values
- The request's top-level and all nested objects accept only fields declared in this guide. Unknown fields are rejected. Do not add
stream,n,negative_prompt,callback_url, or parameters for other models. - Use strict JSON types for integers and booleans, such as
duration: 5andaudio: false. Do not send"5",5.0, or"false". - Declared fields containing
null, empty strings, whitespace-only strings, or the string"null"after case-insensitive comparison and trimming are treated as omitted. Required fields fail validation; optional fields use their omission behavior. 0,false,[], and{}are not treated as empty and must satisfy field constraints. For example,media: []is invalid; omitmediafor text-only generation.parameters: {}uses default parameters.- JSON must be valid and must not contain duplicate object keys,
NaN, orInfinity. - The body limit is 65,535 bytes, including field names, prompts, URLs, and JSON structure. This is a byte limit, not a character limit. Exceeding it returns HTTP
413.
4.6 Acceptance Response
| Field | Type | Description |
|---|---|---|
output.task_id | string | Platform task ID as a canonical lowercase UUID, used for subsequent queries |
output.task_status | string | Successful submission always returns PENDING. Use the query endpoint for the current execution status |
request_id | string | Trace ID for this submission request |
5. Media Requirements and Combination Rules
5.1 Media Types and Counts
type | Meaning | Maximum count | Requirements |
|---|---|---|---|
first_frame | First-frame image | 1 image | Use alone or only with last_frame |
last_frame | Last-frame image | 1 image | Requires first_frame |
reference_image | Reference image | 10 images | May be combined with other reference types, a file, or a webpage |
reference_video | Reference video | 5 clips | Each clip is 1–15 seconds; total input video duration must not exceed 15 seconds |
reference_audio | Reference audio | 5 clips | Each clip is 1–15 seconds; total input audio duration must not exceed 15 seconds |
file | Reference document | 1 file | Mutually exclusive with link; may be combined with reference images, video, and audio |
link | Public webpage | 1 link | Mutually exclusive with file; may be combined with reference images, video, and audio |
Meet both the per-type limits and the 20-item total limit for media. The maximum counts for all categories cannot simply be added together. Available combinations also depend on the capabilities currently enabled for the model.
5.2 File Specifications
| Media | Formats | Constraints |
|---|---|---|
| Image | JPEG / JPG / PNG / BMP / WEBP | At most 20 MB each; each side 240–8000 pixels; long-to-short-side ratio at most 8; PNG must not use an alpha channel |
| Video | MP4 / MOV | At most 100 MB each; each side 240–4096 pixels; long-to-short-side ratio at most 8; frame rate at least 16 fps; duration must also meet the preceding table |
| Audio | WAV / MP3 | At most 15 MB each; duration must also meet the preceding table |
| Document | DOCX / DOC / XLSX / XLS / PPTX / PPT / PDF / TXT / KEY / PAGES / NUMBERS / MD | At most 100 MB each; PDF, Word, PowerPoint, KEY, and PAGES documents must not exceed 50 pages |
| Webpage | HTTP(S) URL | Publicly readable without login |
These are model-side media specifications. Passing JSON validation does not guarantee valid media content. The platform reads the actual duration of reference videos before acceptance; other media properties or content may also be rejected by the model during asynchronous execution. See the official media specifications.
5.3 URL Requirements
- Only public
http://orhttps://URLs are accepted. HTTPS is recommended. - Base64 /
data:,oss://, local paths,file://,localhost, private IP addresses, and URLs containing usernames or passwords are not accepted. - URLs must directly return the actual media without browser cookies, a login session, or additional custom authentication headers. These endpoints do not upload local files.
- Valid signed URLs are supported. Their validity must cover media checks at submission, queueing, and generation retrieval. Do not delete or overwrite the media or change the URL content after submission.
- Reference videos must be readable and parseable. HTTP Range support helps duration probing. Inaccessible, expired, or unparseable resources may cause
400 InvalidParameterduring task creation.
5.4 Combinations and Reference Order
First-frame and first-and-last-frame modes allow only first_frame and last_frame. Do not mix them with reference images, video, audio, files, or webpages. To combine images with audio, use reference_image + reference_audio.
In reference mode, images, video, and audio may be combined, with at most one of file and link. The platform preserves media array order. References such as "image 1" and "image 2" are numbered by the order of reference images, while videos and audio clips each use their own numbering. These numbers are not absolute array indexes. See the official media usage guide.
5.5 Duration Constraints
Without reference video input:
2 <= parameters.duration <= 30, integer onlyWith reference video input, all of the following must hold:
Each input video duration is in [1, 15] seconds
Total input video duration <= 15 seconds
Total input video duration + parameters.duration <= 30 secondsReference audio duration is calculated separately and does not count toward the total input video duration above. Do not add input video duration fields to the request; the platform reads the actual media duration.
For video extension, duration is the total duration of the final generated video. To extend a 5-second source by 2 seconds, set duration: 7; input plus output totals 12 seconds. See the official extension duration guide.
6. Common Request Examples
Each example below is a complete JSON body for the creation endpoint, using the same headers as the quickstart. Replace https://media.example.com/... placeholders with your own publicly accessible media URLs.
6.1 Text-to-Video: Portrait Video with Sound
{
"model": "wan3.0-video-prime",
"input": {
"prompt": "Portrait short film: a street-corner cafe after the rain. An employee opens the wooden door as the camera slowly moves forward, with soft jazz and raindrop sounds."
},
"parameters": {
"resolution": "720P",
"ratio": "9:16",
"duration": 8,
"audio": true,
"prompt_extend": true,
"watermark": false
}
}6.2 First-Frame Generation
{
"model": "wan3.0-video",
"input": {
"prompt": "Start from the first frame: a small boat slowly heads toward the center of the lake. The camera pulls back slightly, preserving natural lighting and character appearance.",
"media": [
{"type": "first_frame", "url": "https://media.example.com/first_frame.jpg"}
]
},
"parameters": {
"resolution": "1080P",
"ratio": "adaptive",
"duration": 5
}
}6.3 First-and-Last-Frame Generation
{
"model": "wan3.0-video-prime",
"input": {
"prompt": "Move smoothly from a closed flower bud to a fully open flower, showing a continuous, natural blooming process.",
"media": [
{"type": "first_frame", "url": "https://media.example.com/flower_start.jpg"},
{"type": "last_frame", "url": "https://media.example.com/flower_end.jpg"}
]
},
"parameters": {
"resolution": "720P",
"ratio": "adaptive",
"duration": 6
}
}6.4 Multimodal References
{
"model": "wan3.0-video",
"input": {
"prompt": "The character in image 1 enters the room in image 2. Follow video 1 for movement pacing and audio 1 for the soundtrack atmosphere.",
"media": [
{"type": "reference_image", "url": "https://media.example.com/character.jpg"},
{"type": "reference_video", "url": "https://media.example.com/motion.mp4"},
{"type": "reference_image", "url": "https://media.example.com/room.jpg"},
{"type": "reference_audio", "url": "https://media.example.com/music.mp3"}
]
},
"parameters": {
"resolution": "720P",
"ratio": "16:9",
"duration": 8,
"audio": true
}
}Here, character.jpg is "image 1", room.jpg is "image 2", and motion.mp4 is "video 1". Reference video and audio must each meet their duration limits, and total input video duration plus 8 seconds must not exceed 30 seconds.
6.5 Document- or Webpage-Based Generation
{
"model": "wan3.0-video-prime",
"input": {
"prompt": "Create a product introduction video from the product document, showing its core features, usage scenarios, and appearance in sequence.",
"media": [
{"type": "file", "url": "https://media.example.com/product.pdf"}
]
},
"parameters": {
"resolution": "720P",
"ratio": "16:9",
"duration": 10,
"prompt_extend": true
}
}For a webpage, replace the media item with {"type": "link", "url": "https://www.example.com/product"} and keep the remaining structure. The webpage URL is also a placeholder and must be replaced. Do not submit both file and link.
6.6 Video Editing
{
"model": "wan3.0-video",
"input": {
"prompt": "Change video 1 to a warm, hand-drawn animation style while preserving its composition, subjects, and actions.",
"media": [
{"type": "reference_video", "url": "https://media.example.com/source_5s.mp4"}
]
},
"parameters": {
"resolution": "720P",
"ratio": "adaptive",
"duration": 5
}
}To match the input duration, determine it first and supply an integer duration that meets the constraints. The platform does not support -1 to match the source duration automatically.
6.7 Video Extension
{
"model": "wan3.0-video-prime",
"input": {
"prompt": "Extend video 1 by 2 seconds at the end. The character keeps walking forward, with a steady tracking shot and consistent scenery and lighting.",
"media": [
{"type": "reference_video", "url": "https://media.example.com/source_5s.mp4"}
]
},
"parameters": {
"resolution": "720P",
"ratio": "adaptive",
"duration": 7
}
}This example assumes an actual 5-second input and a 7-second target output, giving 5 + 7 = 12 billable seconds. State clearly in the prompt whether to extend forward or backward.
7. Query Tasks and Retrieve Results
GET /api/v1/tasks/{task_id}
Authorization: Bearer <THE_SAME_PLATFORM_API_KEY_USED_FOR_CREATION>7.1 Request Parameters and Query Scope
| Parameter | Location | Type | Required | Description |
|---|---|---|---|---|
task_id | Path | string | Yes | Platform task ID returned by creation, a canonical lowercase UUID with hyphens |
Authorization | Header | string | Yes | The same API key that created the task |
Accept-Language | Header | string | No | Error message language |
Queries require neither a body nor X-DashScope-Async. Tasks are isolated by user, creating API key, and endpoint protocol. A different API key cannot read the original task, even under the same account, and receives HTTP 404. A malformed task ID returns HTTP 400.
Queries return the task status recorded by the platform. More frequent queries do not speed up generation. Task processing, result confirmation, and file delivery take time; keep polling at a reasonable interval.
7.2 Task Statuses
output.task_status | Meaning | Client action |
|---|---|---|
PENDING | Accepted by the platform, awaiting submission or queued upstream | Wait, then query again |
RUNNING | Generating, or delivery / terminal-state processing is incomplete | Wait, then query again; do not create a duplicate task |
SUCCEEDED | Generation succeeded and the result is ready for delivery | Read video_url, save the result, and stop polling |
FAILED | Confirmed task failure | Read output.code / output.message, stop polling, and handle the cause |
CANCELED | Task canceled | Stop polling; this status does not imply an active cancellation endpoint is available |
UNKNOWN | Result or delivery requires review | Stop frequent polling, retain the task and request IDs, and contact the platform; do not automatically resubmit |
Statuses may be skipped; the first query might already return SUCCEEDED. Clients must not require seeing RUNNING first.
When the query request itself succeeds, all these statuses return HTTP 200. Check both the HTTP status and output.task_status; HTTP 200 alone does not mean video generation has completed.
7.3 Successful Response Example
This structural example uses illustrative task IDs, timestamps, URLs, and usage. Actual fields depend on the response:
{
"output": {
"task_id": "b5836ed1-f195-441d-990b-0eaec3b9f349",
"task_status": "SUCCEEDED",
"submit_time": "2026-11-07 10:00:00.000",
"scheduled_time": "2026-11-07 10:00:02.000",
"end_time": "2026-11-07 10:03:10.000",
"orig_prompt": "At the seaside in the morning, a golden retriever runs along the beach. A steady tracking shot follows it in warm sunlight, with natural ocean sounds.",
"video_url": "https://media.example.com/generated/video.mp4"
},
"usage": {
"video_count": 1,
"duration": 5.0,
"input_video_duration": 0.0,
"output_video_duration": 5.0,
"fps": 30,
"SR": 720,
"ratio": "16:9"
},
"request_id": "91472d54-521d-4473-8e1a-97a612609928"
}7.4 Response Fields
| Field | Type | Availability and meaning |
|---|---|---|
output | object | Present on a successful query |
output.task_id | string | Platform task UUID, matching the ID returned at submission |
output.task_status | string | Current task status |
output.submit_time | string | Optional upstream submission time in YYYY-MM-DD HH:mm:ss.SSS format |
output.scheduled_time | string | Optional upstream execution time in the same format |
output.end_time | string | Optional upstream completion time in the same format |
output.orig_prompt | string | Original prompt when available on success; may be omitted for media-only input |
output.video_url | string | Delivered video URL when SUCCEEDED |
output.code | string | Error / review code for FAILED or UNKNOWN |
output.message | string | Corresponding safe, localized message |
usage | object | Present on success when valid usage is available; individual fields may also be omitted |
usage.video_count | integer | Output count; 1 when returned |
usage.duration | number | Sum of actual input and output video durations in seconds |
usage.input_video_duration | number | Actual total input video duration in seconds; may be 0 without input video |
usage.output_video_duration | number | Actual output video duration in seconds |
usage.fps | integer | Actual output frame rate |
usage.SR | integer | Output resolution tier as a number, such as 720; the field name is uppercase SR |
usage.ratio | string | Actual output aspect ratio, such as 16:9 |
request_id | string | Request ID of this query |
Timestamps have no time-zone offset and must not be assumed to be UTC. For cross-time-zone ordering, also record your own request and receipt timestamps. Usage fields are JSON numbers that may include fractional values; do not force them to integers. Handle missing optional fields normally.
7.5 Failure and Review Responses
Confirmed content moderation failure, HTTP 200:
{
"output": {
"task_id": "b5836ed1-f195-441d-990b-0eaec3b9f349",
"task_status": "FAILED",
"code": "DataInspectionFailed",
"message": "Content failed moderation. Adjust the input and try again."
},
"request_id": "91472d54-521d-4473-8e1a-97a612609928"
}Result awaiting review, HTTP 200:
{
"output": {
"task_id": "b5836ed1-f195-441d-990b-0eaec3b9f349",
"task_status": "UNKNOWN",
"code": "TaskStatusUnknown",
"message": "The task result cannot currently be confirmed. Keep the task ID for review."
},
"request_id": "91472d54-521d-4473-8e1a-97a612609928"
}7.6 Download and Save the Video
Use output.video_url only after SUCCEEDED. The platform publishes success after file delivery is complete; the status may remain RUNNING during delivery.
curl --location --fail \
'REPLACE_WITH_THE_COMPLETE_VIDEO_URL_FROM_THE_RESPONSE' \
--output generated_video.mp4Do not include the platform API key in download requests. File URLs may use a different hostname from the API. Do not construct storage paths, append extensions, or rewrite URL query parameters yourself.
Download the result promptly and save it in your own storage. Platform delivery URLs do not directly reuse Bailian's temporary artifact URLs. The provider's rule that video URLs and task IDs expire after 24 hours does not apply automatically, and platform URLs are not a promise of permanent storage. Follow platform announcements or service agreements for retention policies.
8. Submission Errors and Query Retries
- After successful submission, save
task_idand use it to query the task. - If creation times out, disconnects, or returns an unclear result, confirm whether the platform accepted the task before deciding whether to resubmit. Record the request time and any available
request_idfor troubleshooting. Automatic resubmission can create another task and incur a charge. - For queries that encounter
429,500,502,503, or a temporary network error, retry the sametask_ida limited number of times. For example, wait 2, 4, and 8 seconds with random jitter. Keeptask_idfor later queries when the client waiting limit is reached. - If the task status is
UNKNOWN, keep the task and request IDs and contact the platform to check the execution and delivery outcome.
9. Error Handling
9.1 HTTP Request Errors
Unsuccessful HTTP requests use this top-level error schema:
{
"code": "InvalidApiKey",
"message": "The API key is invalid or expired",
"request_id": "33c511a7-d546-49dd-bb06-6405b5c51873"
}The example message is illustrative and changes with the error and language. Branch on HTTP status and code, not exact message text.
| HTTP | code | Common cause | Recommended action |
|---|---|---|---|
400 | InvalidParameter | Invalid JSON / parameter types, missing fields, invalid enums, media combinations or durations, unreadable media, unavailable model, etc. | Check the request and media; submit corrections as a new business request |
401 | InvalidApiKey | Missing, malformed, disabled, or expired platform key | Check the key; do not retry blindly |
403 | AccessDenied | Disabled user, disallowed IP, unauthorized model, insufficient balance or key quota | Adjust account settings, authorization, or quota |
403 | UnsupportedOperation | duration: -1 | Use an integer from 2 to 30 and check combined duration |
404 | NotFound | Missing task, cross-user / cross-key query, or task from another protocol | Use the original key and a task ID returned by this protocol |
405 | UnsupportedOperation | Incorrect HTTP method | Use POST or GET as documented |
413 | RequestEntityTooLarge | JSON body exceeds 65,535 bytes | Shorten the body or URLs; use public media URLs |
429 | Throttling | Request rate, RPM, or concurrency limit exceeded | Reduce request frequency and the number of parallel tasks |
500 | InternalError | Internal platform error | Retry queries a limited number of times. Provide request IDs if it persists |
503 | ServiceUnavailable | Unavailable dependencies, model maintenance, no available channel, etc. | Use backoff for query retries. Contact the platform if it persists |
Upstream generation happens asynchronously after platform acceptance, so generation problems are normally reported through task status rather than necessarily as synchronous HTTP errors from creation. Localized task messages appear in output.message; HTTP request errors use the top-level message.
9.2 Task Error and Review Codes
| Task status | output.code | Meaning and action |
|---|---|---|
FAILED | DataInspectionFailed | Content failed moderation; adjust the prompt or media before creating a new task |
FAILED | ServiceUnavailable | Confirmed generation failure; create a new task if needed after checking the outcome and account records |
UNKNOWN | TaskStatusUnknown | Execution outcome cannot be confirmed; keep the task ID for review and do not automatically resubmit |
UNKNOWN | DeliveryNeedsReview | Video generated but delivery requires review; do not create the same task again |
CANCELED may have no code or message; handle the status directly. The platform returns sanitized public errors rather than raw upstream error bodies. For troubleshooting, provide the model, task ID, request ID, time, and HTTP status. Do not provide the complete API key.
10. Billing and Call Limits
10.1 Billing Basis
At task acceptance, the endpoint calculates the cost from the fixed requested output specifications and charges once:
Billable seconds = actual total reference video duration + requested output duration
Base cost = billable seconds * per-second rate for the model and output resolution
Credits charged use the platform's prices and credit conversion rules at acceptance| Scenario | Total input video duration | Requested output duration | Billable seconds |
|---|---|---|---|
| Text-only / image references | 0 seconds | 5 seconds | 5 seconds |
| Video reference | 10.32 seconds | 7 seconds | 17.32 seconds |
| Extend a 5-second source to 7 seconds | 5 seconds | 7 seconds | 12 seconds |
Fractional input video durations are used as measured, without first rounding up to whole seconds. Prompts, images, audio, files, and webpages do not add input video seconds. The current unit price is selected by model and output resolution; the audio switch does not change that unit price.
Refer to the platform's model pricing. The two models and different resolutions may have different rates. Successful tasks keep the quote recorded at acceptance. Query usage reports actual usage and does not trigger an additional charge or refund for a duration difference.
For confirmed failures or cancellations, the platform refunds the original charge. Queries may remain RUNNING until refund processing completes. Request timeouts, client exits, UNKNOWN, and delivery issues must not be treated directly as confirmed failure or a refund; follow review outcomes and account records.
10.2 Limit Summary
| Item | Current constraint |
|---|---|
| Request body | UTF-8 JSON, at most 65,535 bytes |
| Outputs per request | 1 video; no n parameter |
| Output resolution | 480P / 720P / 1080P, subject to current model configuration |
| Output duration | Integer from 2 to 30 seconds; defaults to 5; -1 is not accepted |
| Media items | At most 20 total, within per-type limits |
| Input video | At most 5 clips, each 1–15 seconds, at most 15 seconds total |
| Input video + output | At most 30 seconds combined |
| Input audio | At most 5 clips, each 1–15 seconds, at most 15 seconds total |
| Request rate / RPM / concurrency | Determined by account entitlements, API key permissions, and actual model limits; follow the platform display or service agreement |
| Suggested query interval | 10–15 seconds, with backoff when rate-limited |
Multiple API keys under one account may share account-level rate and concurrency limits. Do not switch keys to bypass them. Bailian's default RPS or free quota is not a platform commitment.
11. Complete Python Example
Use Python 3.11+. This client uses requests. Install the dependency and set environment variables:
python -m pip install requests
export API_BASE_URL="https://openapi.yhsapi.com"
export PLATFORM_API_KEY="REPLACE_WITH_YOUR_COMPLETE_PLATFORM_API_KEY"The example sends one creation request, then polls the task status and streams the video download. It limits retries for temporary query failures and sets a 30-minute polling limit.
import json
import os
import random
import time
import requests
BASE_URL = os.getenv("API_BASE_URL", "https://openapi.yhsapi.com").rstrip("/")
API_KEY = os.environ["PLATFORM_API_KEY"]
RETRYABLE = {429, 500, 502, 503}
session = requests.Session()
def request_json(method, path, *, body=None):
submitting = method == "POST"
attempts = 1 if submitting else 4
headers = {
"Authorization": f"Bearer {API_KEY}",
"Accept-Language": "en",
}
if submitting:
headers.update({
"Content-Type": "application/json",
"X-DashScope-Async": "enable",
})
for attempt in range(attempts):
can_retry = attempt + 1 < attempts
try:
response = session.request(
method, BASE_URL + path, headers=headers, data=body,
timeout=(10, 360 if submitting else 30),
allow_redirects=False,
)
except (requests.Timeout, requests.ConnectionError):
if submitting:
raise RuntimeError("Submission outcome is uncertain. Confirm whether the task was accepted") from None
if not can_retry:
raise RuntimeError("Query failed. Keep the task ID and try again later") from None
else:
if can_retry and response.status_code in RETRYABLE:
response.close()
else:
try:
data = response.json()
except ValueError:
raise RuntimeError(
f"Response is not JSON; HTTP {response.status_code}; "
f"request_id={response.headers.get('X-Request-ID', '')}"
) from None
finally:
response.close()
if response.status_code != 200:
raise RuntimeError(
f"HTTP {response.status_code}: {data.get('code')} / "
f"{data.get('message')}; request_id={data.get('request_id')}"
)
return data
time.sleep(2 ** (attempt + 1) + random.random())
payload = {
"model": "wan3.0-video-prime",
"input": {"prompt": "A mountain lake at dusk. The camera slowly glides over the water, with natural wind sounds."},
"parameters": {"resolution": "720P", "ratio": "16:9", "duration": 5},
}
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
try:
submitted = request_json(
"POST", "/api/v1/services/aigc/video-generation/video-synthesis",
body=body,
)
task_id = submitted["output"]["task_id"]
print("Task ID (save this):", task_id)
# Production: associate task_id with the original business reference.
deadline = time.monotonic() + 30 * 60
while True:
result = request_json("GET", f"/api/v1/tasks/{task_id}")
output = result["output"]
status = output["task_status"]
if status == "SUCCEEDED":
# Use an independent download request without platform Authorization.
with requests.get(
output["video_url"], stream=True, timeout=(10, 120)
) as video:
video.raise_for_status()
with open("generated_video.mp4", "wb") as target:
for chunk in video.iter_content(chunk_size=1024 * 1024):
if chunk:
target.write(chunk)
print("Saved generated_video.mp4; usage:", result.get("usage", {}))
break
if status in {"FAILED", "CANCELED", "UNKNOWN"}:
raise RuntimeError(
f"Task status {status}: {output.get('code', '')} / "
f"{output.get('message', '')}; task_id={task_id}; "
f"request_id={result['request_id']}"
)
if status not in {"PENDING", "RUNNING"}:
raise RuntimeError(f"Unrecognized status {status}; keep task_id={task_id}")
if time.monotonic() >= deadline:
raise TimeoutError(f"Client wait ended; the task may still be running: {task_id}")
time.sleep(12 + random.random() * 3)
finally:
session.close()If the submission outcome is unclear, confirm whether the task was accepted. Once task_id is available, use it to resume queries. If downloading fails, retry the download or query the video URL again.
12. Complete Node.js Example
Use Node.js 20+ with built-in fetch; no additional package is required. Set API_BASE_URL and PLATFORM_API_KEY as in the quickstart, save the code as .mjs, and run it.
import { createWriteStream } from "node:fs";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { setTimeout as sleep } from "node:timers/promises";
const baseURL = (process.env.API_BASE_URL ?? "https://openapi.yhsapi.com")
.replace(/\/+$/, "");
const apiKey = process.env.PLATFORM_API_KEY;
if (!apiKey) throw new Error("Set PLATFORM_API_KEY");
const retryable = new Set([429, 500, 502, 503]);
async function requestJSON(method, path, body) {
const submitting = method === "POST";
const attempts = submitting ? 1 : 4;
const headers = {
Authorization: `Bearer ${apiKey}`,
"Accept-Language": "en",
};
if (submitting) {
Object.assign(headers, {
"Content-Type": "application/json",
"X-DashScope-Async": "enable",
});
}
for (let attempt = 0; attempt < attempts; attempt++) {
const canRetry = attempt + 1 < attempts;
let response;
try {
response = await fetch(baseURL + path, {
method, headers, body, redirect: "error",
signal: AbortSignal.timeout(submitting ? 360_000 : 30_000),
});
} catch {
if (submitting) {
throw new Error("Submission outcome is uncertain. Confirm whether the task was accepted");
}
if (!canRetry) {
throw new Error("Query failed. Keep the task ID and try again later");
}
}
if (response) {
if (!canRetry || !retryable.has(response.status)) {
const data = await response.json().catch(() => {
throw new Error(
`Response is not JSON; HTTP ${response.status}; ` +
`request_id=${response.headers.get("X-Request-ID") ?? ""}`
);
});
if (response.status !== 200) {
throw new Error(
`HTTP ${response.status}: ${data.code} / ${data.message}; ` +
`request_id=${data.request_id}`
);
}
return data;
}
await response.body?.cancel();
}
await sleep(2 ** (attempt + 1) * 1000 + Math.random() * 1000);
}
}
const body = JSON.stringify({
model: "wan3.0-video-prime",
input: { prompt: "A forest in the morning, sunlight filtering through the leaves. The camera moves slowly forward, with birdsong." },
parameters: { resolution: "720P", ratio: "16:9", duration: 5 },
});
const submitted = await requestJSON(
"POST", "/api/v1/services/aigc/video-generation/video-synthesis",
body
);
const taskId = submitted.output.task_id;
console.log("Task ID (save this):", taskId);
const deadline = Date.now() + 30 * 60 * 1000;
while (true) {
const result = await requestJSON("GET", `/api/v1/tasks/${taskId}`);
const output = result.output;
if (output.task_status === "SUCCEEDED") {
// Do not send platform Authorization to the video download host.
const video = await fetch(output.video_url, {
signal: AbortSignal.timeout(120_000),
});
if (!video.ok || !video.body) throw new Error("Download failed; keep the task ID and retry the download");
await pipeline(
Readable.fromWeb(video.body), createWriteStream("generated_video.mp4")
);
console.log("Saved generated_video.mp4; usage:", result.usage ?? {});
break;
}
if (["FAILED", "CANCELED", "UNKNOWN"].includes(output.task_status)) {
throw new Error(
`Task status ${output.task_status}: ${output.code ?? ""} / ` +
`${output.message ?? ""}; task_id=${taskId}; request_id=${result.request_id}`
);
}
if (!["PENDING", "RUNNING"].includes(output.task_status)) {
throw new Error(`Unrecognized status; keep task_id=${taskId}`);
}
if (Date.now() >= deadline) {
throw new Error(`Client wait ended; the task may still be running: ${taskId}`);
}
await sleep(12_000 + Math.random() * 3000);
}Adjust client waiting limits and network timeouts to your application. After an error, resume querying with the task ID if you have it. If the submission outcome is unclear, confirm whether the task was accepted first.
13. Migrating from Bailian
The platform uses Bailian's model / input / parameters request structure and output / usage / request_id response structure, with public fields validated and sanitized by the platform. When migrating using the Bailian-native API reference, observe these differences:
| Item | Platform convention |
|---|---|
| API address | Use https://openapi.yhsapi.com with the full native endpoint paths in this guide |
| API key | Use a platform-issued LT-... key |
| Workspace / region | Callers do not supply a Workspace ID or region; the platform handles channel configuration |
X-DashScope-Async | Still requires enable for creation |
| Task ID | Use the returned platform UUID, not an Alibaba Cloud console task ID |
| Query identity | Must use the same platform key that created the task |
| Intelligent duration | duration: -1 is unsupported; omitted duration defaults to 5 seconds |
| Media URLs | Public HTTP(S) only; no Base64 or oss:// |
| Billing | Platform prices, credits, and the billing basis in this guide |
| Result URLs | Platform video URLs are returned after delivery; do not assume upstream URLs or their validity periods |
UNKNOWN | Result / delivery requires review; missing or inaccessible local tasks return HTTP 404 |
| HTTP error envelope | Top-level code, message, and request_id; neither the Web API's code / msg / data nor an OpenAI error object |
| SDK | This guide provides native HTTP examples; changing an OpenAI SDK base URL and calling a chat endpoint does not generate video |
| Other task management | Only creation and single-task queries are available here; no cancellation, batch queries, task lists, callbacks, or SSE video streaming |
Do not assume every provider-side optional field, SDK method, or other model's parameters are supported. Confirm platform endpoint availability before integrating additional capabilities.
14. Frequently Asked Questions
Why Does Creation Return Only a Task ID?
Creation only accepts the task. Query the returned task_id until SUCCEEDED, then read video_url.
Why Can Another API Key under the Same Account Not Read the Task?
Query access is bound to the creating key. Restore that key. If it is unavailable, retain the task ID and contact the platform.
How Do I Generate a Silent Video?
Set "audio": false in parameters using a JSON boolean, not the string "false".
Can I Submit Local Files or Base64 Directly?
No. Store media in publicly accessible storage first, then place its HTTP(S) URL in input.media. Signed URLs must stay valid until media retrieval completes.
Can I Use -1 to Match the Input Duration Automatically?
No. Supply a fixed integer output duration. Omission uses 5 seconds and does not automatically match the input video.
Why Are 10.32 Seconds of Input and 7 Seconds of Output Not Billed as 7 Seconds?
This endpoint bills input reference video and output video together, giving 17.32 billable seconds. The unit rate depends on the selected model and output resolution.
Can I Immediately Resubmit or Assume a Refund after UNKNOWN?
No. The execution outcome or file delivery still requires review. Retain task_id and request_id and contact the platform to avoid duplicate tasks and charges.
Does Canceling a Request or Stopping Queries Cancel Generation?
No. Closing a connection or stopping polling does not cancel an accepted platform task. This guide provides no active cancellation endpoint.
Must I Regenerate if Downloading the Video Fails?
Retry the download or query again using the original task ID, and check network access and URL validity. Do not directly resubmit generation. Contact the platform with the task ID if the failure persists.

