API 教程

图生视频 API 接入指南:首帧、尾帧与回调

图生视频 API 怎么调:传入首帧或首尾帧,创建异步任务,再用轮询或回调拿到成品视频。

一幅装裱的帆船画,海水从画框中涌出,化作流动的波浪
文档目录

图生视频的调用分三步:传入一两张图片和提示词,API 创建一个异步任务,你再通过轮询或回调拿到生成好的视频。这套流程在各个模型上都一样,不一样的是字段名、状态字符串,以及结果链接的有效期。

本文以 Seedance 2.5 为主线走完整个流程,再说明 Kling 4.0 和 Wan 3.0 的不同之处。下文的接口、参数和限制全部来自 DreamTo 的 API 文档。Seedance API 的其他部分,请看 Seedance 2.5 API 接入指南。

三个模型,三种请求格式#

这三个模型都支持只传首帧,或同时传首帧和尾帧,但请求格式各不相同。

模型创建接口首帧尾帧时长分辨率
seedance-2.5POST /api/v3/contents/generations/tasksimage_url 项,带 role: first_framerole: last_frame4 到 30 秒,或 -1480p、720p、1080p、4k
kling-4.0POST /v1/videosinput.image_urlinput.last_frame_url3 到 30 秒720P、1080P、2K、4K
wan3.0-videoPOST /api/v1/services/aigc/video-generation/video-synthesisinput.media 中 type: first_frame 的项type: last_frame2 到 30 秒,或 -1480P、720P、1080P

三者的鉴权头相同:Authorization: Bearer $DREAMTO_API_KEY。Key 在控制台的 API Key 页面创建,只放在你自己的服务端,详见鉴权文档。

建议显式指定 duration 和 resolution,因为各模型的默认值不同:Seedance 2.5 默认 duration: -1(由模型在 4 到 30 秒内自行决定)、720p;Kling 4.0 默认 5 秒、720P;Wan 3.0 默认 5 秒、1080P。

给 Seedance 2.5 传入首帧#

首帧就是视频开始的那张图。提示词里只需要写画面要怎么动,不必再复述图里有什么。

Seedance 把提示词和图片放在同一个 content 数组里,图片项带上 role: first_frame。输出视频沿用图片的宽高比,ratio 不起作用。

bash
curl -X POST "https://api.dreamto.ai/api/v3/contents/generations/tasks" \  -H "Authorization: Bearer $DREAMTO_API_KEY" \  -H "Content-Type: application/json" \  -d '{    "model": "seedance-2.5",    "content": [      {        "type": "text",        "text": "Slow push-in, the person smiles, hair gently moving in the breeze, cinematic lighting"      },      {        "type": "image_url",        "image_url": { "url": "https://example.com/portrait.jpg" },        "role": "first_frame"      }    ],    "duration": 5,    "resolution": "720p"  }'

响应里返回的是任务 id,不是视频:

json
{  "id": "task_8c1d2e3f4a5b6c7d8e9f0a1b",  "request_id": "req_3f9a1c2b7d4e5f60718293a4"}

轮询时用 id 查询。request_id 与响应头 X-Request-Id 相同,联系技术支持时请附上它。

图片 URL、Base64 和素材引用#

Seedance 的图片有三种传法:公开的 http(s) URL、指向素材库文件的 asset://<asset Id>,或内联 Base64(格式为 data:image/png;base64,...)。Base64 解码后单项不能超过 45 MB,整个请求体不能超过 64 MB;Base64 无效或超限会返回 HTTP 400。

图片格式须为 jpeg、png、webp、bmp、tiff 或 gif,宽高比在 0.4 到 2.5 之间,边长 300 到 6000 px,大小不超过 30 MB。这些限制由模型端校验,所以图片不合规时创建请求照样成功,任务最后以 failed 结束,并给出原因。

Kling 的 image_url 和 last_frame_url 要求是公开 URL,指向不超过 10 MB 的 jpeg、jpg 或 png。Wan 支持公开的 http(s) URL,图片也可以用 Base64,格式为 data:{MIME};base64,{data};不支持 oss:// 这类临时存储 URL。

如果 Kling 拉取不到图片 URL,任务会以 failed 结束,错误信息类似:InvalidParameterValue: Please input the ImageURL that can be retrieved from the external network.

加上尾帧,做转场#

加上尾帧,生成的就是一段转场:视频从一张图开始,到另一张图结束,提示词描述中间的运动。两张图在构图和主体上越接近,转场越自然。输出视频仍然沿用输入图片的宽高比。

在 Seedance 上,再加一个带 role: last_frame 的图片项:

json
{  "model": "seedance-2.5",  "content": [    {      "type": "text",      "text": "Smoothly transition from the first image to the second, steady push-in, soft light, cinematic transition"    },    {      "type": "image_url",      "image_url": { "url": "https://example.com/frame_start.jpg" },      "role": "first_frame"    },    {      "type": "image_url",      "image_url": { "url": "https://example.com/frame_end.jpg" },      "role": "last_frame"    }  ],  "duration": 5,  "resolution": "720p"}

Kling 把两个 URL 都放在 input 里,与提示词和生成设置并列。last_frame_url 必须和 image_url 一起传:

json
{  "model": "kling-4.0",  "input": {    "prompt": "The camera pushes in slowly as day turns to night and the city lights come on",    "image_url": "https://your-cdn.example.com/first-frame.png",    "last_frame_url": "https://your-cdn.example.com/last-frame.png",    "resolution": "1080P",    "duration": 8  }}

Wan 的请求遵循 DashScope 协议:首帧和尾帧作为 input.media 里的项传入,生成设置放在 parameters 中,创建请求还要多带一个请求头 X-DashScope-Async: enable:

json
{  "model": "wan3.0-video",  "input": {    "prompt": "The character walks from the window to the door; the camera follows.",    "media": [      { "type": "first_frame", "url": "https://your-cdn.example.com/first-frame.jpg" },      { "type": "last_frame", "url": "https://your-cdn.example.com/last-frame.jpg" }    ]  },  "parameters": { "resolution": "720P", "duration": 6 }}

Wan 用首帧、尾帧生成时不支持音频输入,首帧、尾帧也不能和参考图、参考视频或音频一起用。

创建任务并轮询结果#

创建请求返回的是任务 id 而不是视频,所以客户端需要一个循环来等结果。下面的脚本会创建一个 Seedance 首帧任务、轮询状态并下载成品。运行前请设置 DREAMTO_API_KEY,并换成你自己的图片 URL。

python
import osimport timeimport requestsURL = "https://api.dreamto.ai/api/v3/contents/generations/tasks"HEADERS = {"Authorization": f"Bearer {os.environ['DREAMTO_API_KEY'].strip()}"}payload = {    "model": "seedance-2.5",    "content": [        {"type": "text", "text": "Slow push-in, the person smiles, hair gently moving in the breeze"},        {            "type": "image_url",            "image_url": {"url": "https://example.com/portrait.jpg"},            "role": "first_frame",        },    ],    "duration": 5,    "resolution": "720p",}resp = requests.post(URL, headers=HEADERS, json=payload, timeout=60)if not resp.ok:    err = resp.json()["error"]    raise RuntimeError(f"{resp.status_code} {err['code']}: {err['message']} (param={err.get('param')})")task_id = resp.json()["id"]started = time.time()while True:    task = requests.get(f"{URL}/{task_id}", headers=HEADERS, timeout=30).json()    if task["status"] == "succeeded":        video_url = task["content"]["video_url"]        break    if task["status"] == "failed":        raise RuntimeError(task["error"]["message"])    elapsed = time.time() - started    if elapsed > 30 * 60:        raise TimeoutError(f"task {task_id} not finished after 30 minutes")    time.sleep(3 if elapsed < 30 else 5 if elapsed < 120 else 10)# The video URL is a direct link: do not send the Authorization header.with requests.get(video_url, stream=True, timeout=300) as r:    r.raise_for_status()    with open(f"{task_id}.mp4", "wb") as f:        for chunk in r.iter_content(chunk_size=1 << 20):            f.write(chunk)print("saved", f"{task_id}.mp4")

轮询间隔沿用 Seedance 文档里的建议:前 30 秒每 3 秒一次,30 秒到 2 分钟之间每 5 秒一次,再往后每 10 秒一次。查询任务必须用创建它的那个 API Key,换成别的 Key 会返回 404。

各模型的状态值和结果字段#

各模型对状态和结果字段的命名都不一样:

模型查询接口状态字段进行中成功失败视频 URL
seedance-2.5GET /api/v3/contents/generations/tasks/{id}statusrunningsucceededfailedcontent.video_url
kling-4.0GET /v1/videos/{task_id}statusqueued、in_progresscompletedfailedvideo_url
wan3.0-videoGET /api/v1/tasks/{task_id}output.task_statusPENDING、RUNNINGSUCCEEDEDFAILED、CANCELED、UNKNOWNoutput.video_url

创建响应里的任务 id,Seedance 是 id,Kling 是 task_id,Wan 是 output.task_id。

Kling 文档说一条视频需要几分钟,要求每 10 到 15 秒轮询一次,不要更频繁。Wan 文档建议大约每 15 秒一次。Wan 的任务 id 可查询 24 小时;超过 24 小时,或任务不存在、属于其他账号时,查询会返回 task_status: UNKNOWN,所以请把 UNKNOWN 当作终态处理。

用回调接收结果#

在 Seedance 上,创建请求里加上 callback_url,任务进入终态(成功或失败)时,平台会向该地址发送一次 POST:

json
{  "model": "seedance-2.5",  "content": [    { "type": "text", "text": "Slow push-in, steam rising from the cup" },    {      "type": "image_url",      "image_url": { "url": "https://example.com/cup.jpg" },      "role": "first_frame"    }  ],  "duration": 5,  "resolution": "720p",  "callback_url": "https://your-server.example.com/dreamto/callback"}

回调的请求体和查询响应不一样,需要单独解析。它的 status 取值是 success 或 failed,而查询接口返回的是 succeeded:

json
{  "event": "task.completed",  "taskId": "task_8c1d2e3f4a5b6c7d8e9f0a1b",  "status": "success",  "result": ["https://example-cdn.com/videos/2026/11/11/output.mp4"],  "errorMsg": "",  "timestamp": "2026-11-11T08:03:16Z",  "signature": "5d0c1b7e9a..."}

任务失败时 result 为 [],原因在 errorMsg 里。任务回调文档对接收端有以下要求:

  • callback_url 必须是 http 或 https,否则创建时返回 HTTP 400。
  • 如果 URL 解析到内网、回环或链路本地地址,平台会拒绝投递,所以 localhost 不能用。
  • 超时时间为 10 秒,任何 2xx 都算成功。首次投递失败后,会在 1、5、30 分钟后重试,最多投递 4 次。
  • 同一个任务可能被重复投递,请按 taskId 去重。
  • 最后一次重试也失败后就不再发送,此时请通过 Get task 或 List tasks 取回结果。

校验回调签名#

如果你的账号配置了 Webhook 签名密钥,每次回调都会带一个 X-DreamTo-Signature 请求头。密钥在控制台的 API Key 页面生成,格式是 whsec_ 后接 48 位小写十六进制字符。签名的算法是:用完整的密钥(含 whsec_ 前缀)对 timestamp.taskId.status 做 HMAC-SHA256,结果取小写十六进制。请求头 X-DreamTo-Timestamp 与请求体里的 timestamp 一致。

没有配置密钥时,不会发送签名请求头,请求体里的 signature 是空字符串,所以文档建议在生产环境生成一个密钥。下面这个接收端会拒绝未签名的回调,用恒定时间比较签名,并把下载交给后台任务:

python
import hashlibimport hmacimport jsonimport osfrom flask import Flask, abort, requestapp = Flask(__name__)WEBHOOK_SECRET = os.environ["DREAMTO_WEBHOOK_SECRET"]  # whsec_...def expected_signature(secret: str, timestamp: str, task_id: str, status: str) -> str:    message = f"{timestamp}.{task_id}.{status}".encode("utf-8")    return hmac.new(secret.encode("utf-8"), message, hashlib.sha256).hexdigest()@app.post("/dreamto/callback")def dreamto_callback():    payload = json.loads(request.get_data())    signature = request.headers.get("X-DreamTo-Signature", "")    timestamp = request.headers.get("X-DreamTo-Timestamp", "")    if not signature or timestamp != payload.get("timestamp"):        abort(401)    expected = expected_signature(        WEBHOOK_SECRET, payload["timestamp"], payload["taskId"], payload["status"]    )    if not hmac.compare_digest(expected, signature):        abort(401)    # Be idempotent on taskId: retries can deliver the same task more than once.    if payload["status"] == "success":        video_url = payload["result"][0]        # enqueue a download of video_url    else:        print("task failed:", payload["taskId"], payload["errorMsg"])    return "", 204

签名覆盖的是 timestamp、taskId 和 status,不包含结果 URL。如果还想校验 URL,请在收到回调后用 taskId 调一次 Get task。同时也要保留一个低频轮询:按文档的说法,回调只是让你更快收到通知,结果以查询接口为准。

Kling 4.0 和 Wan 3.0:只能轮询#

Kling 4.0 和 Wan 3.0 的文档只讲了轮询,没有列出回调参数,所以这两个模型请按轮询来接。

处理被拒绝的请求和失败的任务#

创建请求被拒绝。这时不会产生任务,也不会计费。Seedance 任务接口会返回 HTTP 状态码和一个响应体,里面有 error.code、error.message,校验类错误还有 error.param:

HTTPerror.code常见原因
400invalid_parametercontent 为空、没有文本提示词、duration 超出范围、使用了不支持的参数
400invalid_request请求格式错误,或不符合业务规则
401unauthorizedAPI Key 缺失或无效
402insufficient_balance余额不足
403forbidden无权访问该资源或模型
404not_found任务不存在或由其他 API Key 创建;模型未知或未开通
429rate_limit_exceeded超出频率限制
500api_error内部错误
502、503、504service_unavailable服务暂时不可用或超时

错误码页面给出了处理原则:除 429 外的 4xx 错误通常要先修正请求;429 和 5xx 可以用指数退避重试。请根据 HTTP 状态码和 error.code 判断,不要去匹配错误信息的文字。

在 Kling 上,duration 超出范围时,错误信息会指出字段名和允许的范围;但 resolution 这类枚举值填错时,只返回一条不带字段名的通用提示,这时请对照参数表检查请求。Wan 对无效参数返回 400 InvalidParameter。

任务在生成过程中失败。创建请求已经成功,所以失败要到轮询时才能看到。Seedance 会返回 HTTP 200 和 status: failed,并带一个 error 对象,其中 code 一律是 task_failed:

json
{  "id": "task_8c1d2e3f4a5b6c7d8e9f0a1b",  "model": "seedance-2.5",  "status": "failed",  "error": {    "code": "task_failed",    "message": "Video generation failed, please retry"  },  "created_at": 1794384000,  "updated_at": 1794384120,  "request_id": "req_b2c4d6e8f0a1b3c5d7e9f1a2"}

Kling 任务失败时是 status: failed,原因在 error.message 里。Wan 任务失败时是 task_status: FAILED,原因在 output.code 和 output.message 里。重试之前,请先读一下错误信息。

无论成功还是失败,每个响应都带有 X-Request-Id 响应头,请把它和任务 id 一起记进日志。

在链接过期前下载视频#

三个模型的结果链接都不是永久有效的,有效期也各不相同:

模型文档对结果 URL 的说明
seedance-2.5直接下载链接,不需要 Authorization 头;请尽快转存到你自己的存储,链接不是永久有效的
kling-4.0video_url 在任务完成后 7 天内有效
wan3.0-videooutput.video_url 是 DreamTo 的链接,自任务创建起 24 小时内有效

哪个作业检测到任务成功,就在那个作业里把视频下载下来。

价格与模型选择#

三个模型都按输出视频的秒数计费,单价由分辨率决定。下表是 DreamTo 截至 2026 年 12 月的价格,单位是美元/秒,对应不带参考视频的请求,首帧和首尾帧请求都属于这一类。价格已算上当前的优惠:Seedance 2.5 和 Wan 3.0 优惠 30%,Kling 4.0 优惠 10%。价格会变动,最新数字请看价格页。

分辨率seedance-2.5kling-4.0wan3.0-video
480p$0.10794不提供$0.035
720p$0.242676$0.1413$0.07
1080p$0.597051$0.2115$0.14
2K不提供$0.25434不提供
4K$0.959364$0.4941不提供

在 720p 下生成一段 5 秒的视频,Seedance 2.5 约 $1.21,Kling 4.0 约 $0.71,Wan 3.0 约 $0.35。想事先算准成本,就显式指定 duration:设为 -1 时,Seedance 和 Wan 会自己决定时长,按实际生成的时长计费。Kling 的 2K 和 4K 是放大出来的,按对应分辨率的价格计费。

从文档能看出的选型依据:

  • 三个模型中,只有 Seedance 2.5 在文档里写明了回调,而且同一个接口还能接着做参考生成、视频编辑和视频延长。详见 Seedance 2.5 长视频。
  • Kling 4.0 的参数都放在一个扁平的 input 对象里。每条视频都带音频,没有关闭音频的参数。详见 Kling 4.0 API 接入指南。
  • Wan 3.0 遵循 DashScope 协议,已有的 DashScope 代码只需改一下 base URL 和 API Key 就能用。详见 Wan 3.0 API 接入指南。

想看逐项对比,请读 Kling 4.0 与 Seedance 2.5 对比。想在写代码之前先试试模型,可以打开对应的在线体验:Seedance 2.5、Kling 4.0 或 Wan 3.0。完整的模型目录见模型列表。

请求格式的参考文档:Seedance 2.5 的图生视频和首尾帧,Kling 4.0,以及 Wan 3.0 的图生视频和首尾帧。

FAQ#

图生视频里的首帧和尾帧有什么区别?#

首帧是视频开始的那张图,提示词描述接下来的运动。尾帧是可选的第二张图,视频以这张图收尾,由模型生成两张图之间的过渡。Seedance 2.5、Kling 4.0 和 Wan 3.0 都支持只传首帧,也支持首尾帧一起传。

输出视频会保持我这张图的宽高比吗?#

会。在 Seedance 2.5 上,输出沿用图片的宽高比,ratio 不起作用。在 Kling 4.0 上,设置了首帧之后 aspect_ratio 不起作用。在 Wan 3.0 上,宽高比同样沿用图片的,按文档的说法,ratio 保持默认值 adaptive 即可。

该用轮询还是回调?#

在 Seedance 2.5 上两者都用:传 callback_url 及时收到通知,同时保留低频轮询做兜底,因为回调最多投递 4 次,之后就不会再发。Kling 4.0 和 Wan 3.0 的文档只讲了轮询。

生成的视频能保留多久?#

Kling 4.0 的 video_url 在任务完成后 7 天内有效,Wan 3.0 的链接自任务创建起 24 小时内有效。Seedance 2.5 返回的是直接下载链接,没有写明有效期;文档要求尽快把文件转存到你自己的存储,不要把链接当作永久地址。

任务失败会计费吗?#

Kling 4.0 和 Wan 3.0 的文档都说明,失败的任务和无效的请求不计费。在 Seedance 2.5 上,被校验拒绝的请求不会创建任务,也不会计费。

  • Image to Video
  • Video API
  • Webhooks