cd /news/generative-ai/how-to-generate-ai-video-from-code-v… · home › topics › generative-ai › article
[ARTICLE · art-177592] src=dev.to ↗ pub= topic=generative-ai verified=true sentiment=· neutral

How to generate AI video from code: Veo 3.1, Kling and Seedance with one API

Alex, who runs the MartLLM API, published a complete Python client pattern for generating AI video from code, covering a price/start/poll/download job flow and demonstrating the same code against Google's Veo 3.1, Kuaishou's Kling and ByteDance's Seedance. The writeup emphasizes a validate step that quotes cost before any charge, idempotency keys to prevent double billing on retries, and polling every 5-10 seconds until a job reaches a final status.

recommendation

Quote every video request with validate:true before starting it and attach an Idempotency-Key, so invalid parameters and retries never trigger charges.

more in playbook: Controlling LLM cost
by read6 min views6 publishedNov 28, 2026

Disclosure: I'm Alex, and I run MartLLM, the API used in the examples. The job pattern (price, start, poll, download) is the same on most video APIs; swap the URLs and field names for your provider's.

Text models answer in a second or two. Video models don't. A five-second clip takes a minute or more, so every serious video API treats it as a job: you start it, you check on it, and you download the file when it's done. If you write video code like chat code (one blocking request, wait for the bytes), you get timeouts, double charges on retries, and no idea what a clip will cost until the bill arrives.

This post builds a small, complete Python client for that flow, then runs the same code against three model families: Google's Veo 3.1, Kuaishou's Kling and ByteDance's Seedance. Prices are what the public catalog listed on 2026-11-28.

The endpoints, all under https://api.martllm.com with Authorization: Bearer <key>:

Step Call
Price POST /v1/video/generations with"validate": true
Start POST /v1/video/generations (HTTP 202, returns a job id)
Poll GET /v1/video/generations/<job id> (202 while running, 200 when it ends)
Download GET /v1/media/artifacts/<job id>/0
Stop DELETE /v1/video/generations/<job id>

The full reference, with every field, is in the video section of the media docs.

Add "validate": true to the exact request you're about to send. It's checked as if it were real (model, length, resolution, source picture), nothing is made, nothing is charged, and you get back the listed cost and the most the job can be billed:

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> }

The extra step is worth it because an invalid request fails here, before money moves. Each model only makes certain lengths, resolutions and shapes. Ask Veo 3.1 Lite for a 10-second clip and the error lists the lengths it does make (4, 6 or 8). A Seedance image-to-video model sent no picture gets 400 image_required.

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}'

You get HTTP 202 with a job:

{ "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..." }

Two details matter in production:

Idempotency-Key`` max_cost_usd A job has six statuses: queued, running, succeeded, failed, canceled, expired. The last four are final. failed, canceled and expired cost nothing. Poll every 5-10 seconds. Faster doesn't make the video arrive sooner.

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 } }

One edge case catches people out. The exact charge comes in a little after the file is ready, usually within 30 seconds. Until then a succeeded job shows "usage": {"cost_usd": null, "cost_pending": true}. Don't treat null as free. Read the job again later.

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

The artifact URL needs the same Authorization header. It isn't a public link, so don't paste it into an <img> or <video> tag. Download it and serve it from your own storage.

pip install requests, set MARTLLM_API_KEY, and this runs as is:

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"):
        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")

On a failed job, error.retryable tells you whether sending it again can work. A content refusal won't. A busy moment usually will.

Only the body changes. These are real model ids from the catalog, with the price each listed on 2026-11-28:

Veo 3.1 Lite, text to video, 8 s, 720p with sound. $0.0425 per second, so $0.34 a clip. It makes 4, 6 or 8 second clips at 720p or 1080p, 16:9 or 9:16. (model page)

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

Kling V3 Standard, text to video, 5 s. $0.0732 per second, about $0.37 for 5 seconds. Lengths 3 to 15 s. The image-to-video version, kling/kling-v3-standard-image-to-video, takes image_url and the same per-second price.

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

Seedance 2.0 Mini, image to video, 5 s at 480p. $0.0163 per second at 480p ($0.0351 at 720p), about $0.08 for 5 seconds. The picture becomes the first frame. Lengths 5 to 15 s. (model page)

{"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"}

For image-to-video, send a picture that already has the shape you want (crop it to 9:16 for a vertical clip). Most Kling, Veo and Seedance image-to-video models make the clip in the shape of the source picture and refuse an aspect_ratio.

"models": ["kling/kling-v3-standard-text-to-video"] and that model is tried only if the first has no free provider right now. The reply's model field says which one took the job.max_cost on the request caps what one job can cost. The same pattern runs as a Python script, an n8n workflow or a queue worker. The job is the unit: price it, start it once, wait, fetch it.

Alex, CEO, MartLLM

── more in #generative-ai 4 stories · sorted by recency
── more on @martllm 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/how-to-generate-ai-v…] indexed:0 read:6min 2026-11-28 · —