转载笔记:本文是对 Alex(alex_martllm)发表于 DEV Community 的文章《How to generate AI video from code: Veo 3.1, Kling and Seedance with one API》(2026 年 11 月 28 日)的总结笔记,不是原文转载。原文链接:https://dev.to/alex_martllm/how-to-generate-ai-video-from-code-veo-31-kling-and-seedance-with-one-api-3d9p

说明:核查时(11 月 29 日约 09:00)x.com 全站返回 HTTP 403,相关讨论帖未能打开;本文的细节、代码与价格以 DEV 原文为准,价格为作者 2026 年 11 月 28 日在公开目录上查到的数字,视频价格每周都在变,下单前请以实时报价为准。作者在文中披露:他经营 MartLLM,即示例中用的 API。原文配图未能取得可下载的地址,本文为纯文字版。

文本模型一两秒就能回答,视频模型不行。一条五秒的短片要花一分钟以上,所以每个正经的视频 API 都把它当作一项任务来处理:你启动它、查询它、完成后下载文件。如果你像写聊天代码那样写视频代码(一次阻塞请求、等字节回来),得到的是超时、重试造成的重复扣费,以及直到账单来了才知道一条短片花了多少钱。

这篇文章先搭了一个小而完整的 Python 客户端,走通这套流程,再用同一套代码跑三个模型家族:Google 的 Veo 3.1、快手的 Kling 和字节的 Seedance。价格是 2026 年 11 月 28 日公开目录上列出的数字。

四个步骤

  1. 先询价,不花一分钱。
  2. 启动任务,可以安全重试。
  3. 每 5–10 秒轮询一次,直到结束。
  4. 下载文件。

所有接口都在 https://api.martllm.com 下面,用 Authorization: Bearer <key> 认证:

步骤 调用
询价 POST /v1/video/generations,带 "validate": true
启动 POST /v1/video/generations(HTTP 202,返回任务 id)
轮询 GET /v1/video/generations/<job id>(进行中返回 202,结束返回 200)
下载 GET /v1/media/artifacts/<job id>/0
停止 DELETE /v1/video/generations/<job id>

第 1 步:生成之前先询价

在你真正要发的请求里加上 "validate": true。它会像真请求一样被检查(模型、时长、分辨率、源图片),但什么都不生成、什么都不扣费,返回的是标价和这项任务最多会被收多少钱:

curl https://api.martllm.com/v1/video/generations \
  -H "Authorization: Bearer $MARTLLM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "google/veo-3.1-lite",
       "prompt": "a paper boat drifting down a rain-soaked street at dusk, neon reflections",
       "duration_seconds": 8, "resolution": "720p", "aspect_ratio": "16:9", "audio": true,
       "validate": true}'
{ "object": "quote", "model": "google/veo-3.1-lite", "kind": "video",
  "valid": true, "cost_usd": 0.34, "unit": "second", "units": 8,
  "max_cost_usd": <the most this job can be billed> }

多这一步是值得的,因为无效请求会在花钱之前就失败。每个模型只支持特定的时长、分辨率和画面形状:让 Veo 3.1 Lite 生成 10 秒的短片,报错会列出它实际支持的时长(4、6 或 8 秒);给 Seedance 的图生视频模型不传图片,会得到 400 image_required。

第 2 步:启动任务

curl https://api.martllm.com/v1/video/generations \
  -H "Authorization: Bearer $MARTLLM_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"model": "google/veo-3.1-lite", "prompt": "...", "duration_seconds": 8,
       "resolution": "720p", "aspect_ratio": "16:9", "audio": true}'

返回 HTTP 202 和一个任务:

{ "id": "6f1c...", "object": "media.job", "kind": "video", "status": "queued",
  "estimated_cost_usd": 0.34, "max_cost_usd": <held while it runs>,
  "poll_url": "/v1/video/generations/6f1c...", "cancel_url": "/v1/video/generations/6f1c..." }

生产环境里有两个细节很重要:

  • Idempotency-Key:如果 HTTP 客户端在网络闪断后重试 POST,同一个键只会启动一个任务,而不是两个。没有它,一次连接不稳可能让你把同一条短片买两遍。
  • max_cost_usd:这笔钱会在任务运行期间从余额里冻结,也是这项任务最多会被收的钱。如果按用户统计开支,就把它和任务 id 存在一起。

第 3 步:轮询,直到结束

任务有六种状态:queued、running、succeeded、failed、canceled、expired。后四种是终态;failed、canceled 和 expired 不收费。每 5–10 秒查一次,查得再快也不会让视频来得更快。

curl -H "Authorization: Bearer $MARTLLM_API_KEY" \
  https://api.martllm.com/v1/video/generations/<job id>
{ "id": "6f1c...", "status": "succeeded",
  "results": [{ "artifact_index": 0, "url": "https://api.martllm.com/v1/media/artifacts/6f1c.../0",
                "content_type": "video/mp4", "duration_seconds": 8 }],
  "usage": { "cost_usd": 0.34 } }

一个容易踩的坑:确切的扣费会在文件就绪后晚一点才到账,通常在 30 秒以内。在那之前,一个已成功的任务会显示 "usage": {"cost_usd": null, "cost_pending": true}。别把 null 当成免费,晚点再读一次任务。

第 4 步:下载

curl -L -o veo.mp4 -H "Authorization: Bearer $MARTLLM_API_KEY" \
  https://api.martllm.com/v1/media/artifacts/<job id>/0

产物链接同样需要 Authorization 请求头。它不是公开链接,别把它贴进 <img> 或 <video> 标签里,下载下来、用自己的存储提供。

完整 Python 客户端

装好 requests、设好 MARTLLM_API_KEY,下面这段代码可以直接跑:

import os
import sys
import time
import uuid
import requests

API = "https://api.martllm.com"
HEADERS = {"Authorization": f"Bearer {os.environ['MARTLLM_API_KEY']}"}
DONE = {"succeeded", "failed", "canceled", "expired"}

def quote(body: dict) -> dict:
    """Same request with "validate": true: checked, priced, nothing made, nothing charged."""
    r = requests.post(f"{API}/v1/video/generations", headers=HEADERS,
                      json={**body, "validate": True}, timeout=60)
    r.raise_for_status()
    return r.json()

def start(body: dict) -> dict:
    """Start the job. The Idempotency-Key makes a retried POST start one job, not two."""
    r = requests.post(f"{API}/v1/video/generations",
                      headers={**HEADERS, "Idempotency-Key": str(uuid.uuid4())},
                      json=body, timeout=60)
    r.raise_for_status()
    return r.json()  # HTTP 202: {"id", "status": "queued", "max_cost_usd", "poll_url", ...}

def wait(job_id: str, every: float = 7, give_up_after: float = 20 * 60) -> dict:
    """Poll every 5-10 s until the job ends (202 while running, 200 once it ends)."""
    deadline = time.time() + give_up_after
    while time.time() < deadline:
        r = requests.get(f"{API}/v1/video/generations/{job_id}", headers=HEADERS, timeout=60)
        r.raise_for_status()
        job = r.json()
        if job["status"] in DONE:
            return job
        print(f"  {job['status']} {job.get('progress') or ''}", file=sys.stderr)
        time.sleep(every)
    raise TimeoutError(f"job {job_id} still running after {give_up_after}s")

def download(url: str, path: str) -> None:
    with requests.get(url, headers=HEADERS, stream=True, timeout=300) as r:
        r.raise_for_status()
        with open(path, "wb") as f:
            for chunk in r.iter_content(1 << 20):
                f.write(chunk)

def make_video(body: dict, path: str) -> dict:
    q = quote(body)
    print(f"{body['model']}: listed ${q['cost_usd']}, at most ${q['max_cost_usd']}")
    job = start(body)
    job = wait(job["id"])
    if job["status"] != "succeeded":
        err = job.get("error") or {}
        raise RuntimeError(f"{job['status']}: {err.get('message')} (retryable={err.get('retryable')})")
    download(job["results"][0]["url"], path)
    usage = job.get("usage") or {}
    if usage.get("cost_pending"):
        # The exact charge lands a little after the file is ready; GET the job again later.
        print("saved", path, "- charge still pending")
    else:
        print("saved", path, "- billed $", usage.get("cost_usd"))
    return job

if __name__ == "__main__":
    make_video({
        "model": "google/veo-3.1-lite",
        "prompt": "a paper boat drifting down a rain-soaked street at dusk, neon reflections",
        "duration_seconds": 8,
        "resolution": "720p",
        "aspect_ratio": "16:9",
        "audio": True,
    }, "veo.mp4")

任务失败时,error.retryable 会告诉你再发一次有没有用:内容被拒不会,服务繁忙通常会。

同一套代码,三个模型家族

只有请求体需要换。下面是目录里的真实模型 id,和各自在 2026 年 11 月 28 日列出的价格:

Veo 3.1 Lite,文生视频,8 秒,720p,带声音。 每秒 0.0425 美元,一条短片 0.34 美元。支持 4、6 或 8 秒,720p 或 1080p,16:9 或 9:16。

{"model": "google/veo-3.1-lite", "prompt": "...", "duration_seconds": 8,
 "resolution": "720p", "audio": true}

Kling V3 Standard,文生视频,5 秒。 每秒 0.0732 美元,5 秒约 0.37 美元。时长 3 到 15 秒。图生视频版 kling/kling-v3-standard-image-to-video 接受 image_url,每秒价格相同。

{"model": "kling/kling-v3-standard-text-to-video", "prompt": "...", "duration_seconds": 5}

Seedance 2.0 Mini,图生视频,5 秒,480p。 480p 每秒 0.0163 美元(720p 是 0.0351 美元),5 秒约 0.08 美元。传进去的图片会成为第一帧。时长 5 到 15 秒。

{"model": "bytedance/seedance-2-0-mini-image-to-video", "prompt": "slow push-in as the waves roll",
 "image_url": "https://example.com/first-frame.png", "duration_seconds": 5, "resolution": "480p"}

做图生视频时,先把图片裁成你想要的形状(竖屏短片就裁成 9:16)。大多数 Kling、Veo 和 Seedance 的图生视频模型会按源图片的形状出片,并且拒绝接受 aspect_ratio 参数。

上生产之前值得加的东西

  • 备用模型。 加上 "models": ["kling/kling-v3-standard-text-to-video"],只有当第一个模型暂时没有空闲服务方时才会试它;回复里的 model 字段会告诉你最终是哪个模型接了任务。
  • 同时跑很多任务时,用 webhook 代替轮询。 媒体文档里有回调的说明。
  • 单次请求的上限。 请求里的 max_cost 能限制一项任务最多花多少钱。
  • 价格跟踪。 视频价格每周都在变,视频 API 的定价页会实时列出每个模型每秒的价格。

同一套模式既可以跑成 Python 脚本,也可以跑成 n8n 工作流或队列 worker。任务就是基本单位:先询价、只启动一次、等它跑完、再把文件取回来。

执笔执笔人

请我喝杯咖啡吧~

Solana

Solana

Solana

Solana

Solana

Solana

背景音乐
直达评论
设置
回到顶部
直达底部
收起工具箱