
Byted Seedance Video Generate
- 3 installs
- 408 repo stars
- Updated August 3, 2026
- volcengine/agentkit-samples
Helps with ai & agent building tasks.
About
byted-seedance-video-generate is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- byted-seedance-video-generate
- AI & Agent Building
- AI-coding skill
Byted Seedance Video Generate by the numbers
- 3 all-time installs (skills.sh)
- Ranked #13,655 of 16,556 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/volcengine/agentkit-samples --skill byted-seedance-video-generateAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 3 |
|---|---|
| repo stars | ★ 408 |
| Last updated | August 3, 2026 |
| Repository | volcengine/agentkit-samples ↗ |
What it does
Helps with ai & agent building tasks.
Files
Video Generate Skill
This skill generates videos using Doubao Seedance 1.0/1.5 models.
Trigger Conditions
1. User wants to generate videos from text descriptions 2. User wants to create videos based on images (first/last frame) 3. User wants to create videos with reference materials (images, videos, audio) 4. User asks for video generation capabilities
Usage
Environment Variables
Before using this skill, ensure the following environment variables are set:
ARK_API_KEYorMODEL_VIDEO_API_KEYorMODEL_AGENT_API_KEY: API key for the video generation serviceMODEL_VIDEO_API_BASE: API base URL (optional, has default)MODEL_VIDEO_NAME: Model name (optional, has default)
Function Signature
async def video_generate(
params: list,
batch_size: int = 10,
max_wait_seconds: int = 1200,
model_name: str = None,
) -> Dict:Parameters
params (list[dict])
A list of video generation requests. Each item is a dict with the following fields:
Required per item:
video_name(str): Name/identifier of the output video fileprompt(str): Text describing the video to generate. Supports Chinese and English.
Optional per item - Input Materials:
first_frame(str): URL for the first frame imagelast_frame(str): URL for the last frame imagereference_images(list[str]): 1-4 reference image URLs for style/content guidancereference_videos(list[str]): 0-3 reference video URLs (mp4/mov, 2-15s each, total ≤15s)reference_audios(list[str]): 0-3 reference audio URLs (mp3/wav, 2-15s each, total ≤15s)
Optional per item - Video Output Parameters:
ratio(str): Aspect ratio. Options: "16:9" (default), "9:16", "4:3", "3:4", "1:1", "2:1", "21:9", "adaptive"duration(int): Video length in seconds. Range: 2-12s depending on modelresolution(str): Video resolution. Options: "480p", "720p", "1080p"frames(int): Total frame count. Must be in [29, 289] and follow format 25 + 4ncamera_fixed(bool): Lock camera movement. Default: falseseed(int): Random seed for reproducibility. Range: [-1, 2^32-1]watermark(bool): Whether to add watermark. Default: falsegenerate_audio(bool): Whether to generate audio. Only Seedance 1.5 supports thistools(list[dict]): Tool configuration, e.g.,[{"type": "web_search"}]
Input Modes
1. Text-to-Video: Only provide prompt, no images/videos 2. First Frame Guidance: Provide first_frame for starting image 3. First + Last Frame Guidance: Provide both for transition video 4. Reference Images: Provide reference_images for style/content guidance 5. Multimodal Reference: Combine reference_images, reference_videos, reference_audios
Return Value
Script Return Info
The video_generate.py script will return these info:
{
"status": "success" | "partial_success" | "error",
"success_list": [{"video_name": "video_url"}],
"error_list": ["video_name"],
"error_details": [{"video_name": "...", "error": {...}}],
"pending_list": [{"video_name": "...", "task_id": "cgt-xxx", ...}]
}Based on the script return info, the final response returned to the user consists of a description of the video generation task and the video URL(s). You may download the video from the URL, but the video URL should still be provided to the user for viewing and downloading.
Note: the URL is the 'url' in the success_list of script return info. The URL must return in two ways:
Final Return Info
For OpenClaw
1. First, save/download the generated video to an allowed directory:
- Recommended:
~/.openclaw/workspace/
2. Use the `message tool` to send the video with these parameters:
{
"action": "send",
"message": "Optional text description",
"media": "/root/.openclaw/workspace/generated-video.mp4"
}- The tool will automatically: read the local file, upload to the channel server as a web URL, and send as a video message
3. Verify success: Check that the tool returns {"ok": true} to confirm the video was sent successfully
4. Normal Text not message tool: After generation, show list of videos with Markdown format, for example:
<video src="https://example.com/video1.mp4" width="640" controls>video-1</video>Very important: The video URL must be an original online resource link starting with https://, not a local video address you have downloaded.
For Normal
You should return three types of information: 1. File format, return the video file (if you have some other methods to send the video file) and the local path of the video, for example: local_path: /root/.openclaw/workspace/skills/video-generate/xxx.mp4 2. After generation, show list of videos with Markdown format, for example:
<video src="https://example.com/video1.mp4" width="640" controls>video-1</video>
<video src="https://example.com/video2.mp4" width="640" controls>video-2</video>Code Implementation
See scripts/video_generate.py for the full implementation.
Example Usage
# Text-to-Video
python scripts/video_generate.py -p "小猫骑着滑板穿过公园" -n cat_park -r 16:9 -d 5 --resolution 720p
# First Frame Guidance
python scripts/video_generate.py -p "小猫跳起来" -n cat_jump -f "https://example.com/cat.png" -r adaptive -d 5
# First + Last Frame Guidance
python scripts/video_generate.py -p "平滑过渡动画" -n transition \
-f "https://example.com/start.png" \
-l "https://example.com/end.png" \
-d 6
# Reference Images (style/content guidance)
python scripts/video_generate.py -p "[图1]戴着眼镜的男生和[图2]柯基小狗坐在草坪上" -n styled \
--ref-images "https://example.com/boy.png" "https://example.com/dog.png" \
-r 16:9 -d 5
# Multimodal Reference (video + audio)
python scripts/video_generate.py -p "将视频中的人物换成[图1]中的男孩" -n multimodal \
--ref-images "https://example.com/boy.png" \
--ref-videos "https://example.com/source.mp4" \
--ref-audios "https://example.com/voice.wav" \
-d 5
# With Audio Generation (Seedance 1.5 only)
python scripts/video_generate.py -p "女孩抱着狐狸,可以听到风声和树叶沙沙声" -n with_audio \
-f "https://example.com/girl_fox.png" \
--generate-audio \
-m doubao-seedance-1-5-pro-251215 \
-d 6 --resolution 1080p
# Query task status
python scripts/video_generate.py -q "cgt-20260222165751-wsnw8"
# Use specific model
python scripts/video_generate.py -p "A futuristic city" -m doubao-seedance-1-5-pro-251215
# No watermark
python scripts/video_generate.py -p "A beautiful landscape" --no-watermarkCommand Line Options
| Option | Short | Description |
|---|---|---|
--prompt | -p | Text description of the video (required) |
--name | -n | Video name identifier (default: video) |
--model | -m | Model name (default: doubao-seedance-1-0-pro-250528) |
--ratio | -r | Aspect ratio (default: 16:9) |
--duration | -d | Video duration in seconds (2-12) |
--resolution | Video resolution: 480p, 720p, 1080p | |
--first-frame | -f | First frame image URL |
--last-frame | -l | Last frame image URL |
--ref-images | Reference image URLs (space-separated, 1-4 images) | |
--ref-videos | Reference video URLs (space-separated, 0-3 videos) | |
--ref-audios | Reference audio URLs (space-separated, 0-3 audios) | |
--generate-audio | Generate audio (Seedance 1.5 only) | |
--seed | Random seed for reproducibility | |
--no-watermark | Disable watermark | |
--timeout | -t | Max wait time in seconds (default: 1200) |
--query-task | -q | Query task status by task_id |
Model Fallback
If you encounter a model-related error (like ModelNotOpen), you can downgrade to these models:
doubao-seedance-1-5-pro-251215doubao-seedance-1-0-pro-250528
Error Handling
- IF the script raises the error "PermissionError: ARK_API_KEY or MODEL_VIDEO_API_KEY or MODEL_AGENT_API_KEY not found in environment variables", inform the user that they need to provide the
ARK_API_KEYorMODEL_VIDEO_API_KEYorMODEL_AGENT_API_KEYenvironment variable. Write it to the environment variable file in the workspace. If the file already exists, append it to the end. Ensure the environment variable format is correct, make the environment variable effective, and retry the video generation task that just failed.
Notes
- Keep prompt concise (recommended ≤ 500 characters)
- For first/last frame, ensure aspect ratios match your chosen ratio
- Reference images: 1-4 images, formats: jpeg/png/webp/bmp/tiff/gif
- Reference videos: 0-3 videos, formats: mp4/mov, total duration ≤ 15s
- Reference audios: 0-3 audios, formats: mp3/wav, total duration ≤ 15s
- Multimodal requires at least one image or video (audio-only not supported)
- Audio generation is only supported by Seedance 1.5 pro
- If polling times out, use
--query-taskwith the returned task_id
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.import argparse
import asyncio
import json
import os
import sys
from dataclasses import dataclass, field
from typing import Dict, List, Optional
import httpx
API_KEY = (
os.getenv("ARK_API_KEY")
or os.getenv("MODEL_VIDEO_API_KEY")
or os.getenv("MODEL_AGENT_API_KEY")
)
API_BASE = (
os.getenv("ARK_BASE_URL")
or os.getenv("MODEL_VIDEO_API_BASE")
or "https://ark.cn-beijing.volces.com/api/v3"
).rstrip("/")
API_BASE = API_BASE.replace("/api/coding/v3", "/api/v3")
# DEFAULT_MODEL = "doubao-seedance-2-0-260128"
DEFAULT_MODEL = "doubao-seedance-1-5-pro-251215"
@dataclass
class VideoTaskResult:
video_name: str
task_id: Optional[str] = None
video_url: Optional[str] = None
error: Optional[str] = None
error_detail: Optional[dict] = None
status: str = "pending"
execution_expires_after: Optional[int] = None
@dataclass
class VideoGenerationConfig:
first_frame: Optional[str] = None
last_frame: Optional[str] = None
reference_images: List[str] = field(default_factory=list)
reference_videos: List[str] = field(default_factory=list)
reference_audios: List[str] = field(default_factory=list)
generate_audio: Optional[bool] = None
ratio: Optional[str] = None
duration: Optional[int] = None
resolution: Optional[str] = None
frames: Optional[int] = None
camera_fixed: Optional[bool] = None
seed: Optional[int] = None
watermark: Optional[bool] = None
tools: Optional[List[Dict]] = None
def _get_headers() -> dict:
return {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}",
}
def _build_content(prompt: str, config: VideoGenerationConfig) -> list:
content = [{"type": "text", "text": prompt}]
if config.first_frame:
content.append(
{
"type": "image_url",
"image_url": {"url": config.first_frame},
"role": "first_frame",
}
)
if config.last_frame:
content.append(
{
"type": "image_url",
"image_url": {"url": config.last_frame},
"role": "last_frame",
}
)
for ref_image in config.reference_images:
content.append(
{
"type": "image_url",
"image_url": {"url": ref_image},
"role": "reference_image",
}
)
for ref_video in config.reference_videos:
content.append(
{
"type": "video_url",
"video_url": {"url": ref_video},
"role": "reference_video",
}
)
for ref_audio in config.reference_audios:
content.append(
{
"type": "audio_url",
"audio_url": {"url": ref_audio},
"role": "reference_audio",
}
)
return content
def _should_disable_audio(
model_name: str, generate_audio: Optional[bool]
) -> Optional[bool]:
if generate_audio is False:
return None
if model_name.startswith("doubao-seedance-1-0") and generate_audio:
print(
"Warning: doubao-seedance-1-0 series do not support audio generation. Use doubao-seedance-1-5 for audio."
)
return None
return generate_audio
def _is_text_to_video(config: VideoGenerationConfig) -> bool:
return not (
config.first_frame
or config.last_frame
or config.reference_images
or config.reference_videos
or config.reference_audios
)
def _build_request_body(
prompt: str, config: VideoGenerationConfig, model_name: str
) -> dict:
body = {
"model": model_name,
"content": _build_content(prompt, config),
}
if config.tools is not None and _is_text_to_video(config):
body["tools"] = config.tools
generate_audio = _should_disable_audio(model_name, config.generate_audio)
if generate_audio is not None:
body["generate_audio"] = generate_audio
optional_fields = [
"ratio",
"duration",
"resolution",
"frames",
"camera_fixed",
"seed",
"watermark",
]
for field_name in optional_fields:
value = getattr(config, field_name, None)
if value is not None:
body[field_name] = value
return body
async def _create_video_task(
prompt: str, config: VideoGenerationConfig, model_name: str
) -> dict:
url = f"{API_BASE}/contents/generations/tasks"
body = _build_request_body(prompt, config, model_name)
async with httpx.AsyncClient(timeout=60.0) as client:
response = await client.post(url, headers=_get_headers(), json=body)
response.raise_for_status()
return response.json()
async def _get_task_status(task_id: str) -> dict:
url = f"{API_BASE}/contents/generations/tasks/{task_id}"
async with httpx.AsyncClient(timeout=60.0) as client:
response = await client.get(url, headers=_get_headers())
response.raise_for_status()
return response.json()
def _parse_item_to_config(item: dict) -> VideoGenerationConfig:
return VideoGenerationConfig(
first_frame=item.get("first_frame"),
last_frame=item.get("last_frame"),
reference_images=item.get("reference_images", []),
reference_videos=item.get("reference_videos", []),
reference_audios=item.get("reference_audios", []),
generate_audio=item.get("generate_audio"),
ratio=item.get("ratio"),
duration=item.get("duration"),
resolution=item.get("resolution"),
frames=item.get("frames"),
camera_fixed=item.get("camera_fixed"),
seed=item.get("seed"),
watermark=item.get("watermark"),
tools=item.get("tools"),
)
async def _process_single_item(item: dict, model_name: str) -> VideoTaskResult:
video_name = item["video_name"]
prompt = item["prompt"]
config = _parse_item_to_config(item)
try:
task_data = await _create_video_task(prompt, config, model_name)
task_id = task_data.get("id")
return VideoTaskResult(
video_name=video_name,
task_id=task_id,
status="created",
execution_expires_after=task_data.get("execution_expires_after"),
)
except httpx.HTTPStatusError as e:
error_text = e.response.text if e.response else str(e)
error_detail = None
try:
error_detail = json.loads(error_text)
except Exception:
error_detail = {"raw_error": error_text}
return VideoTaskResult(
video_name=video_name,
error=error_text,
error_detail=error_detail,
status="failed",
)
except Exception as e:
return VideoTaskResult(
video_name=video_name,
error=str(e),
error_detail={"raw_error": str(e)},
status="failed",
)
async def _poll_task_status(
task_id: str,
video_name: str,
max_wait_seconds: int = 1200,
poll_interval: int = 10,
) -> VideoTaskResult:
max_polls = max_wait_seconds // poll_interval
polls = 0
while polls < max_polls:
result = await _get_task_status(task_id)
status = result.get("status")
if status == "succeeded":
video_url = result.get("content", {}).get("video_url")
return VideoTaskResult(
video_name=video_name,
task_id=task_id,
video_url=video_url,
status="succeeded",
execution_expires_after=result.get("execution_expires_after"),
)
if status == "failed":
error = result.get("error", {})
return VideoTaskResult(
video_name=video_name,
task_id=task_id,
error=str(error),
error_detail=error,
status="failed",
execution_expires_after=result.get("execution_expires_after"),
)
print(f"Video {video_name} status: {status}, waiting...")
await asyncio.sleep(poll_interval)
polls += 1
result = await _get_task_status(task_id)
return VideoTaskResult(
video_name=video_name,
task_id=task_id,
error="polling_timeout",
status="pending",
execution_expires_after=result.get("execution_expires_after"),
)
async def video_task_query(task_id: str) -> Dict:
result = await _get_task_status(task_id)
status = result.get("status")
response = {
"task_id": task_id,
"status": status,
"video_url": None,
"error": None,
"model": result.get("model"),
"created_at": result.get("created_at"),
"updated_at": result.get("updated_at"),
"execution_expires_after": result.get("execution_expires_after"),
}
if status == "succeeded":
response["video_url"] = result.get("content", {}).get("video_url")
elif status == "failed":
response["error"] = result.get("error")
return response
async def video_generate(
params: list,
batch_size: int = 10,
max_wait_seconds: int = 1200,
model_name: str = None,
) -> Dict:
model = model_name or os.getenv("MODEL_VIDEO_NAME", DEFAULT_MODEL)
success_list = []
error_list = []
error_details = []
pending_list = []
for start_idx in range(0, len(params), batch_size):
batch = params[start_idx : start_idx + batch_size]
task_results = await asyncio.gather(
*[_process_single_item(item, model) for item in batch]
)
created_tasks = []
for r in task_results:
if r.status == "created" and r.task_id:
created_tasks.append(r)
elif r.status == "failed":
error_list.append(r.video_name)
if r.error_detail:
error_details.append(
{
"video_name": r.video_name,
"error": r.error_detail,
}
)
poll_results = await asyncio.gather(
*[
_poll_task_status(r.task_id, r.video_name, max_wait_seconds)
for r in created_tasks
]
)
for result in poll_results:
if result.status == "succeeded":
success_list.append({result.video_name: result.video_url})
print(f"Video {result.video_name} completed: {result.video_url}")
elif result.status == "failed":
error_list.append(result.video_name)
error_details.append(
{
"video_name": result.video_name,
"error": result.error_detail,
}
)
print(f"Video {result.video_name} failed: {result.error}")
elif result.status == "pending":
pending_list.append(
{
"video_name": result.video_name,
"task_id": result.task_id,
"execution_expires_after": result.execution_expires_after,
"message": f"Task still running. Use video_task_query('{result.task_id}') to check status later.",
}
)
if success_list and not error_list and not pending_list:
status = "success"
elif success_list:
status = "partial_success"
else:
status = "error"
return {
"status": status,
"success_list": success_list,
"error_list": error_list,
"error_details": error_details,
"pending_list": pending_list,
}
def main():
parser = argparse.ArgumentParser(
description="Generate videos using Seedance models"
)
parser.add_argument("--prompt", "-p", help="Text description of the video")
parser.add_argument("--name", "-n", default="video", help="Video name identifier")
parser.add_argument(
"--model",
"-m",
default=None,
help="Model name (default: doubao-seedance-2-0-260128)",
)
parser.add_argument(
"--ratio",
"-r",
choices=["16:9", "9:16", "4:3", "3:4", "1:1", "2:1", "21:9", "adaptive"],
default="16:9",
help="Aspect ratio (default: 16:9)",
)
parser.add_argument(
"--duration",
"-d",
type=int,
default=None,
help="Video duration in seconds (2-12)",
)
parser.add_argument(
"--resolution",
choices=["480p", "720p", "1080p"],
default=None,
help="Video resolution",
)
parser.add_argument(
"--first-frame", "-f", default=None, help="First frame image URL"
)
parser.add_argument("--last-frame", "-l", default=None, help="Last frame image URL")
parser.add_argument(
"--ref-images",
nargs="+",
default=None,
help="Reference image URLs (1-4 images)",
)
parser.add_argument(
"--ref-videos",
nargs="+",
default=None,
help="Reference video URLs (0-3 videos)",
)
parser.add_argument(
"--ref-audios",
nargs="+",
default=None,
help="Reference audio URLs (0-3 audios)",
)
parser.add_argument(
"--generate-audio",
action="store_true",
help="Generate audio (Seedance 1.5 only)",
)
parser.add_argument(
"--seed", type=int, default=None, help="Random seed for reproducibility"
)
parser.add_argument("--no-watermark", action="store_true", help="Disable watermark")
parser.add_argument(
"--timeout",
"-t",
type=int,
default=1200,
help="Max wait time in seconds (default: 1200)",
)
parser.add_argument(
"--query-task", "-q", default=None, help="Query task status by task_id"
)
args = parser.parse_args()
if not API_KEY:
raise PermissionError(
"ARK_API_KEY or MODEL_VIDEO_API_KEY or MODEL_AGENT_API_KEY not found in environment variables."
)
if args.query_task:
result = asyncio.run(video_task_query(args.query_task))
print(json.dumps(result, indent=2, ensure_ascii=False))
return
if not args.prompt:
print("Error: --prompt is required when not using --query-task")
sys.exit(1)
item = {
"video_name": args.name,
"prompt": args.prompt,
"ratio": args.ratio,
"watermark": not args.no_watermark,
}
if args.first_frame:
item["first_frame"] = args.first_frame
if args.last_frame:
item["last_frame"] = args.last_frame
if args.ref_images:
item["reference_images"] = args.ref_images
if args.ref_videos:
item["reference_videos"] = args.ref_videos
if args.ref_audios:
item["reference_audios"] = args.ref_audios
if args.generate_audio:
item["generate_audio"] = True
if args.duration:
item["duration"] = args.duration
if args.resolution:
item["resolution"] = args.resolution
if args.seed is not None:
item["seed"] = args.seed
result = asyncio.run(
video_generate([item], max_wait_seconds=args.timeout, model_name=args.model)
)
print(json.dumps(result, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()