---
agent:
  instructions: "Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://framesfield.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
title: "Video API Async Polling and Batch Render Skill"
description: "Production SKILL.md rulebook teaching Claude Code, Cursor, and Codex how to write safe batch render scripts for Google Gemini Omni 1.2 Flash, Kling 4.0, and Runway Gen-4 Turbo—enforcing mandatory `--dry-run` USD cost caps, exponential backoff polling, idempotent `manifest.json` resume, and automatic zero-billing error guards."
canonical: "https://framesfield.com/skills/veo-kling-api-batch-runner"
---

# Video API Async Polling and Batch Render Skill

> Production SKILL.md rulebook teaching Claude Code, Cursor, and Codex how to write safe batch render scripts for Google Gemini Omni 1.2 Flash, Kling 4.0, and Runway Gen-4 Turbo—enforcing mandatory `--dry-run` USD cost caps, exponential backoff polling, idempotent `manifest.json` resume, and automatic zero-billing error guards.

- **Canonical URL:** https://framesfield.com/skills/veo-kling-api-batch-runner
- **Raw Payload URL:** https://framesfield.com/raw/skills/veo-kling-api-batch-runner
- **Asset Type:** SKILL.md
- **Compatible Hosts:** Claude Code, Cursor, Codex
- **Target Creative Tool:** Gemini Omni Flash / Kling 4.0 / Runway APIs
- **License:** MIT
- **Last Verified:** 2026-11-29
- **Source Reference:** https://ai.google.dev/gemini-api/docs/video

## Setup & Install

```bash
mkdir -p .claude/skills/video-api-batch-runner
curl -fsSL https://framesfield.com/raw/skills/veo-kling-api-batch-runner -o .claude/skills/video-api-batch-runner/SKILL.md

```

## Copyable Asset (SKILL.md)

```markdown
---
name: video-api-batch-runner
description: Build safe, resumable, cost-capped video generation batch scripts for Google Gemini Omni 1.2 Flash, Kling 4.0, and Runway Gen-4 Turbo with mandatory dry-run USD previews, idempotent manifest logging, and exponential backoff polling.
---

# Safe Asynchronous Video API Batch Runner Protocol

Whenever asked to write or run code calling paid AI video APIs (Gemini Omni Flash, Kling 4.0, Runway, fal.ai), enforce ALL six engineering guardrails. The request shapes in section 2 were copied from the vendors' API docs on 2026-11-29 and have not been run against the paid APIs; re-read the current docs before the first paid run.

## 1. Mandatory `--dry-run` Default & Hard Cost Cap (`--max-usd`)
- Every generated script MUST default to `--dry-run` (or require explicit `--execute` + `--max-usd <limit>`).
- Before issuing a single HTTP POST, compute and print an exact line-item USD estimate (`shots × duration_s × unit_rate`). Abort immediately if projected spend exceeds `--max-usd`.
- Unit rates to price against, per generated second: Gemini Omni Flash `$0.07` (720p) / `$0.104` (1080p upscaled); Kling 4.0 `$0.157` (720p) / `$0.235` (1080p); Runway Gen-4 Turbo `$0.05` (silent, image-to-video only). Gemini Omni Flash and Kling 4.0 always include audio; there is no cheaper silent rate on either.
- Also print the request count: the Gemini API has no free tier and limits Tier 1 accounts to 40 requests a day.

## 2. Idempotent Manifest Persistence (`render-manifest.json`)
Never store job IDs only in RAM:
- Compute a deterministic `shot_hash` (`sha256(model + prompt + first_frame_sha + last_frame_sha + duration)`).
- Before submitting a shot, check `render-manifest.json`:
  - If status is `completed` and local MP4 exists: **skip cleanly** (zero double-billing).
  - If status is `submitted` with a saved `job_id`: **resume polling** that existing job instead of submitting a duplicate billable render.
- Write `render-manifest.json` atomically (`write temp -> rename`) immediately after receiving each `job_id`.

What counts as the `job_id` on each API:
- **Kling 4.0 on the Runway API (task-based):** `POST https://api.dev.runwayml.com/v1/image_to_video` with headers `Authorization: Bearer $RUNWAYML_API_SECRET` and `X-Runway-Version: 2024-11-06`, and a JSON body of `model: "kling_4"`, `promptImage` (required first frame, or an array with optional middle and last frames), `promptText`, `ratio` (`auto_720p` or `auto_1080p`) and `duration` (integer, 3–30). The response carries a task `id`: save it, then poll `GET /v1/tasks/{id}` until `status` is `SUCCEEDED` or `FAILED` (other values: `PENDING`, `THROTTLED`, `RUNNING`, `CANCELLED`). Result URLs are in `output[]`. Runway Gen-4 Turbo (`gen4_turbo`) uses the same task flow; copy its body fields from the Runway API reference.
- **Gemini Omni Flash in the Gemini API (response-based):** `POST https://generativelanguage.googleapis.com/v1beta/interactions` with header `x-goog-api-key: $GEMINI_API_KEY` and a JSON body of `model: "gemini-omni-1.2-flash"`, `input` (a prompt string, or an array of `{type: "image", data, mime_type}` and `{type: "text", text}` parts for a first frame) and `response_format: {type: "video", duration: "8s", resolution: "720p", aspect_ratio: "16:9", delivery: "uri"}`. The documented call returns the finished interaction in the POST response, so there is no job id to save while it renders. Write `status: "submitted"` to the manifest before the POST, then save the returned interaction `id` and the file URI found at `steps[] -> model_output -> content[] -> {type: "video", uri}` as soon as the response arrives. If a run finds `submitted` with no saved `id`, stop and ask the user before paying for that shot again.

## 3. Bounded Exponential Backoff Polling
Video renders take `30s – 240s`. Never poll in a 1-second tight loop:
- Start polling after `10s`, then back off (`10s -> 15s -> 20s -> 30s` cap) with jitter. The Runway API reference says not to expect task updates more often than once every five seconds.
- For Gemini Omni Flash with `delivery: "uri"`, the thing to poll is the file: `GET /v1beta/files/{FILE_ID}` until `state` is `ACTIVE` (`FAILED` means the generation failed). Set the HTTP client timeout on the POST itself to the same hard timeout.
- Stop cleanly after a hard timeout (`600s`) without deleting the saved `job_id` from the manifest.
- Honor `429 Retry-After` headers and cap concurrency (`MAX_CONCURRENT=2` default) so rate limits never trigger cascading retries.

## 4. Secret & Asset Hygiene
- Read API keys strictly from environment variables (`GEMINI_API_KEY`, `RUNWAYML_API_SECRET`, `FAL_KEY`)—never hardcode secrets or print them in logs. Send the Gemini key in the `x-goog-api-key` header, not in the URL query string, so it stays out of logged URLs.
- Validate every local `first_frame` / `last_frame` PNG exists and is non-empty BEFORE paying for API submission. Gemini Omni Flash renders `16:9` or `9:16` only, so reject frames in any other ratio for it; Kling 4.0 on the Runway API keeps the framing of the input image.

## 5. Immediate Local Download & Stream Verification
Download URLs returned by video APIs expire (the Runway API reference gives 24–48 hours for task output URLs). Download every completed MP4 immediately into `./renders/<shot_id>_<model>.mp4` (Gemini Omni Flash: `GET /v1beta/files/{FILE_ID}:download?alt=media`), verify `size > 50KB`, and run `ffprobe` to record real duration, resolution, frame rate, and audio presence inside `render-manifest.json`. Do not assume a frame rate for Kling 4.0; its resellers do not state one.

## 6. Clean Failure Classification
Distinguish non-retryable `400` / invalid-argument / safety-filter rejections (log verbatim error, do NOT auto-retry in a loop) from transient `502`/`503` transport hiccups (retry max 2 times with backoff). Gemini Omni Flash returns an invalid argument error for a `duration` over `15s`, and for first/last-frame interpolation over `10s`; catch both in the dry run instead.
```

## Example Input

```text
"Write a Node script to batch-render all 4 shots in shotlist.json using Google Gemini Omni Flash at 720p and Kling 4.0 at 720p with a $6.00 spend cap."
```

## Expected Output

```text
- Emits `scripts/render-batch.mjs` with `--dry-run` default, `--max-usd 6.00`, deterministic SHA-256 shot hashing, and atomic `render-manifest.json` persistence.
- Dry run prints two 8s Gemini Omni Flash shots (2 × $0.56 = $1.12) plus two 5s Kling 4.0 shots (2 × $0.79 = $1.58), $2.70 in total against the $6.00 cap.
- Validates all 4 opening PNGs exist before calling any endpoint.
- Polls Runway task IDs and Gemini file states with bounded 10s->30s backoff, downloads MP4s locally, and records `ffprobe` metadata.
```

## Requirements

- Node.js 20+ or Python 3.10+ with valid provider API keys in environment variables
- Claude Code, Cursor, or Codex with local file and shell execution

## Known Limits

- Request shapes come from the Gemini API and Runway API docs as read on 2026-11-29 and were not run against the paid APIs—confirm endpoints, fields, and model IDs against the current vendor docs before production runs
- Always keep `--max-usd` conservative on first execution until you inspect Take 1 quality

## Implementation Notes

## Combine with our Director & Budget Subagents

Use [Skill 11: AI Video Shot Director Subagent](/skills/shot-director-agent) to compile `shotlist.json`, audit spend with [Skill 13: AI Media Budget and Model Router Subagent](/skills/api-budget-estimator-agent), run renders safely with this skill, and verify exports with [Skill 12: Video QA and Broadcast Delivery Subagent](/skills/video-qc-delivery-agent).

Google shut down the Veo 3.1 preview models in the Gemini API on October 22, 2026, so this skill now targets [Google Gemini Omni 1.2 Flash](/specs/gemini-omni-flash) and [Kling 4.0](/specs/kling-4) through the Runway API, with [Runway Gen-4 Turbo](/specs/runway-gen-4) for silent image-to-video shots. The request shapes in the payload were taken from the vendors' API docs and have not been run against the paid APIs, so treat the first execution as a test.
