Kling API Python Batch Pipeline + ffmpeg
A Kling API Python batch pipeline: CSV in, capped concurrency, retries keyed to error codes, a crash-safe manifest, immediate downloads and an ffmpeg stitch.
By OceanToken Team

Editor's note: Most broken video batches we hear about break in dull places: no cap on retries, no record of what was submitted, a temporary link that expired overnight. Our view is that a short Python script with a manifest file beats a clever workflow tool for anyone producing more than a handful of clips a day. The concurrency number gets the attention, but the manifest is what lets you rerun a batch without paying twice.
Short answer: For a Kling API Python batch, read prompts from a CSV, validate each row, submit with a semaphore that caps jobs in flight, poll with backoff and a deadline, download each finished clip at once, and write every state change to a manifest. Retry only error codes that can succeed on a second try. Then stitch clips with ffmpeg.
What actually limits a Kling batch
Two different limits apply, and they are easy to mix up. Kling's own concurrency rules count generation tasks running at once. A task holds a slot from the moment you submit it until it finishes, and it still holds the slot if it fails. The quota belongs to the account, so every API key on that account shares it, and query calls don't count against it. When you hit the ceiling, new creates fail with code 1303. Kling's error codes page lists that as HTTP 429, next to 1302 for plain request-rate limits.
The practical consequence: a semaphore around submit only is wrong. The slot is busy until the render ends, so the semaphore has to cover submit, poll and download together.
The examples here use OceanToken's endpoint, where the rules are expressed differently. Its limits page sets requests and tokens per minute per key, returns 429 rate_limited with a Retry-After header when you exceed them, and returns 429 provider_overloaded when every channel for a model is busy. It does not publish a cap on concurrent video jobs, so start low and raise the number only after a clean run.
| Kling's own API | OceanToken video API | |
|---|---|---|
| Statuses | submitted, processing, succeeded, failed |
queued, in_progress, completed, failed |
| Result lifetime | Kept 30 days | content_url valid 24 hours |
| Over the limit | 429, code 1303 (concurrency) or 1302 (rate) | 429 rate_limited or provider_overloaded |
| Duplicate protection | external_task_id, unique per account |
Idempotency-Key header |
Statuses differ, so a status check copied from a Kling-native example will loop forever against an OpenAI-style endpoint. Check for the strings your endpoint actually returns.
Design rules for a Kling API Python batch
Each rule below exists because of a specific way batches lose money.
Validate before you submit. On the endpoint used here, an unsupported value is refused with 400 invalid_request before anything runs, and the message lists the allowed values. That is cheap, but a CSV of 200 rows with a typo in the duration column still fails 200 times. The Kling 3.0 schemas take whole-second durations from 3 to 15 and aspect ratios of 16:9, 9:16 or 1:1. Kling's text-to-video reference also caps multi-shot prompts at six shots of at least one second each, 512 characters per shot. Check those in Python, and keep a comment with the date you read each limit.
These limits are for the kling-v3.0 ids only: kwaivgi/kling-video-o1 accepts 5 or 10 seconds, so for any other model read GET /oceantoken/video/model-spec?model=<id> instead of hard-coding.
Make submission idempotent. The video guide says a create retried with the same Idempotency-Key returns the existing job instead of starting, and charging, a second one. Derive the key from the row id and the attempt number, and save the attempt number before the call. A crash between "request sent" and "id saved" then resumes with the same key.
Download immediately. A completed job's content_url lasts 24 hours. A batch that finishes at 2 a.m. and gets collected on Monday has lost its files.
Retry by error code, not by status. The guide lists rate_limited, timeout, temporarily_unavailable and generation_failed as worth resubmitting. content_filtered and invalid_request will fail the same way again, so those rows go to a human.

The manifest
The manifest is one JSON file, keyed by row id. Each entry holds a short hash of the prompt, the attempt count, the job id, the status, timestamps, the local file path and the last error code. Write it after every state change, through a temporary file and a rename, so a crash can't leave half a file behind.
With that file you can answer the questions that come up the morning after a batch: which rows finished, which were refused and why, which are still rendering. Rerunning the script skips finished rows, resumes polling for rows that already have a job id, and leaves refused rows alone until someone edits the prompt.
The core loop
This uses httpx and the three documented endpoints: POST /v1/videos, GET /v1/videos/{id} and GET /v1/videos/{id}/content. It is a complete script, but we have not published a run of it; try it on three rows first.
import asyncio, csv, hashlib, json, os, random, sys, time
from pathlib import Path
import httpx
BASE = "https://api.oceantoken.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['OCEANTOKEN_API_KEY']}"}
MODEL = "kwaivgi/kling-v3.0-std"
CONCURRENCY = 3 # jobs in flight; raise only after a clean run
DEADLINE = 20 * 60 # seconds of polling per job, your own limit
MAX_ATTEMPTS = 3
RETRY_CODES = {"rate_limited", "timeout", "temporarily_unavailable", "generation_failed"}
MANIFEST, OUT = Path("manifest.json"), Path("out")
OUT.mkdir(exist_ok=True)
def save(m):
tmp = MANIFEST.with_suffix(".tmp")
tmp.write_text(json.dumps(m, indent=2))
tmp.replace(MANIFEST)
def validate(row):
# kling-v3.0 limits read 2026-11-10; other ids (e.g. kling-video-o1: 5 or 10 s)
# differ, so read the model-spec endpoint per model instead of hard-coding
d = int(row["duration"])
assert 3 <= d <= 15, "duration must be 3-15 s"
assert row.get("aspect_ratio", "16:9") in {"16:9", "9:16", "1:1"}, "bad aspect ratio"
assert row["prompt"].strip(), "empty prompt"
async def submit(client, row, attempt):
body = {"model": MODEL, "prompt": row["prompt"], "duration": int(row["duration"]),
"aspect_ratio": row.get("aspect_ratio", "16:9")}
for wait in (2, 4, 8, 16, 32):
r = await client.post(f"{BASE}/videos", json=body,
headers={"Idempotency-Key": f"{row['id']}-{attempt}"})
if r.status_code == 429 or r.status_code >= 500:
await asyncio.sleep(float(r.headers.get("Retry-After", wait)) + random.random())
continue
r.raise_for_status() # 400s raise and go to a human
return r.json()["id"]
raise RuntimeError("create kept failing")
async def wait_for(client, vid):
start, delay = time.monotonic(), 15
while time.monotonic() - start < DEADLINE:
await asyncio.sleep(delay)
r = await client.get(f"{BASE}/videos/{vid}")
if r.status_code == 429 or r.status_code >= 500:
delay = min(delay * 2, 60)
continue
r.raise_for_status()
job, delay = r.json(), 15
if job["status"] in ("completed", "failed"):
return job
return {"status": "deadline"}
async def download(client, vid, path):
async with client.stream("GET", f"{BASE}/videos/{vid}/content") as r:
r.raise_for_status()
with open(path, "wb") as f:
async for chunk in r.aiter_bytes():
f.write(chunk)
async def run_row(client, sem, row, m):
rec = m.setdefault(row["id"], {"attempts": 0,
"prompt_sha": hashlib.sha256(row["prompt"].encode()).hexdigest()[:12]})
if rec.get("status") in ("done", "rejected"):
return
try:
validate(row)
except (AssertionError, ValueError) as e:
rec.update(status="rejected", error=f"validation: {e}"); save(m); return
async with sem: # held until the render ends, like Kling's slots
while True:
if not rec.get("video_id"):
if rec.get("status") != "submitting": # after a crash, reuse the same key
if rec["attempts"] >= MAX_ATTEMPTS:
return
rec["attempts"] += 1
rec["status"] = "submitting"; save(m)
try:
rec["video_id"] = await submit(client, row, rec["attempts"])
except httpx.HTTPStatusError as e:
rec.update(status="rejected", error=e.response.text[:300]); save(m); return
except RuntimeError:
rec["error"] = "create_retries_exhausted"; save(m); return
rec.update(status="submitted", submitted_at=time.time()); save(m)
job = await wait_for(client, rec["video_id"])
if job["status"] == "deadline":
rec["status"] = "deadline"; save(m); return # rerun later to keep polling
if job["status"] == "completed":
path = OUT / f"{row['id']}.mp4"
await download(client, rec["video_id"], path)
rec.update(status="done", file=str(path), done_at=time.time()); save(m); return
code = (job.get("error") or {}).get("code", "unknown")
rec.update(status="failed", error=code, video_id=None); save(m)
if code not in RETRY_CODES:
return
async def main(csv_path):
rows = list(csv.DictReader(open(csv_path, newline="")))
m = json.loads(MANIFEST.read_text()) if MANIFEST.exists() else {}
sem = asyncio.Semaphore(CONCURRENCY)
async with httpx.AsyncClient(headers=HEADERS, timeout=60, follow_redirects=True) as client:
await asyncio.gather(*(run_row(client, sem, r, m) for r in rows))
save(m)
if __name__ == "__main__":
asyncio.run(main(sys.argv[1]))
The CSV needs id, prompt and duration columns, plus an optional aspect_ratio. Two choices are worth explaining. The poll interval starts at 15 seconds because the video guide recommends checking every 10 to 20 seconds; polling faster doesn't finish the render sooner. And a row that hits the deadline keeps its job id instead of resubmitting, since the job may still be running and a new create would be billed separately.
If you only need one job at a time with callbacks or a simpler poll, our Kling API async tasks tutorial covers that pattern.
Handling failures without paying twice
The decision is the same for every failed row: will a second try plausibly succeed? Rate limits, timeouts and temporary unavailability usually clear on their own, which is why the script resubmits them up to MAX_ATTEMPTS. A moderation refusal won't. Kling's error page describes its content-policy codes (1300 and 1301) as requests you need to change, and the video guide calls the equivalent failure content_filtered. The script marks those rows rejected and stops.

Budget errors deserve their own branch in larger setups. The limits page says the API returns 400 key_budget_exceeded when a key reaches its spending limit, even if the account still has credit. In this script that row lands as rejected with the error text, which is the right outcome: a person should decide whether to raise the limit.
Kling ffmpeg stitch: joining the clips
For a hard cut, the concat demuxer joins files without re-encoding, as long as every file has the same streams, codecs and time base, per the ffmpeg formats documentation . Clips from one model at one resolution normally qualify:
printf "file '%s'\n" out/shot1.mp4 out/shot2.mp4 out/shot3.mp4 > list.txt
ffmpeg -f concat -safe 0 -i list.txt -c copy cut.mp4
For a soft join, use the xfade filter. The filter documentation says both inputs need a constant frame rate and must match in resolution, pixel format, frame rate and timebase, and that offset is measured from the start of the first input. So normalize first, then fade:
ffmpeg -i a.mp4 -i b.mp4 -filter_complex \
"[0:v]fps=24,scale=1280:720,format=yuv420p,settb=AVTB[v0]; \
[1:v]fps=24,scale=1280:720,format=yuv420p,settb=AVTB[v1]; \
[v0][v1]xfade=transition=fade:duration=0.5:offset=4.5[v]" \
-map "[v]" -c:v libx264 -crf 18 cut.mp4
The offset is the first clip's length minus the fade: a 5-second clip with a half-second fade starts fading at 4.5. For a chain of clips, each offset is the running total of earlier clip lengths minus one fade per join so far; read real lengths with ffprobe rather than trusting the requested duration. If the clips carry sound, add an acrossfade with the same duration, or strip the audio and lay one music bed over the finished cut. Re-encode once, at the end.
How to test this on your workload
We haven't published timing or failure counts for this script. A safe order:
- Run three rows with
CONCURRENCY = 1and confirm the manifest records submit, done and the file path. - Kill the script mid-poll, rerun it, and confirm it resumes the same job ids instead of creating new ones.
- Add one row with an invalid duration and one prompt you expect to be refused, and confirm both end as
rejected. - Raise concurrency to 3, then 5, and note any 429 responses and the
x-oceantoken-key-rpm-limitheader. - Stitch three finished clips with both commands and check the joins frame by frame.
Our take: Spend your effort on the manifest and the retry rules, not the concurrency number. A batch you can stop, resume and audit from one file is a batch you can leave running overnight.
Running it on OceanToken
Point the script at https://api.oceantoken.ai/v1 and pick a Kling id from /kling-api: kwaivgi/kling-v3.0-std for drafts, kwaivgi/kling-v3.0-pro for 1080p finals (see the Kling v3.0 Pro model page), or kwaivgi/kling-v3.0-omni and kwaivgi/kling-video-o1 for reference-driven shots. The API is OpenAI-compatible, so the same key and client also run text models that can write the prompts in your CSV.
Three things matter for batches in particular. A failed video job is not charged and its balance hold is released. The Idempotency-Key header makes network retries safe. And each key can carry its own spending limit, so give the batch its own key. For the same flow without code, see our Kling n8n and Make workflow. See the current rate on /kling-api.
FAQ
How many Kling jobs should I run at once? Start with three. Kling counts concurrency per account until each task ends, and no video job cap is published for the endpoint used here, so raise the number only after a clean run.
Should I use asyncio or threads? Either works because the work is waiting on the network. asyncio keeps hundreds of polling jobs cheap in one process.
Why did my status loop never end? You are probably checking for succeeded on an endpoint that returns completed, or the reverse. The two APIs use different status strings.
How long do I have to download a clip? On the endpoint used here, content_url is valid for 24 hours. Kling's own API keeps results for 30 days.
Can I stitch without re-encoding? Yes, with the concat demuxer, if all clips share codecs and time base. Crossfades need xfade and a re-encode.
Sources
- Kling API: concurrency rules (checked 2026-11-10)
- Kling API: error codes (checked 2026-11-10)
- Kling API: Kling 3.0 text to video (checked 2026-11-10)
- OceanToken docs: video (checked 2026-11-10)
- OceanToken docs: limits (checked 2026-11-10)
- OceanToken docs: retries and failover (checked 2026-11-10)
- ffmpeg filters: xfade (checked 2026-11-10)
- ffmpeg formats: concat demuxer (checked 2026-11-10)
- OceanToken Kling API page (checked 2026-11-10)
Get your OceanToken API key
- Create an OceanToken account and an API key.
- Copy the snippet below, paste your key, and run it.
- Check the current rate on /kling-api.
curl https://api.oceantoken.ai/v1/videos \
-H "Authorization: Bearer $OCEANTOKEN_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: row-1-1" \
-d '{"model": "kwaivgi/kling-v3.0-std", "prompt": "A paper boat drifts down a rain gutter, close tracking, soft overcast light", "duration": 5, "aspect_ratio": "16:9"}'
More from the blog
A Unified API for Chat, Image and Video
Building on a unified API for chat, image and video: sync vs async calls, billing units, retries, timeouts and storage, with three calls and a launch checklist.
Kimi K3 API International Access Guide
Use the Kimi K3 API internationally: sign up with email, pay by card, create one key and call moonshotai/kimi-k3 with an OpenAI SDK. Steps, code and checks.
Call Tencent Hy3 With the OpenAI SDK
Call Tencent Hy3 with the OpenAI SDK outside China: base URL, model id, streaming, tool calls, reasoning_effort values, Hy3 vs Hy3 preview, and token billing.