← Back to dashboard

AI Video Generation Integration Guide

What is AI video generation?

The real model

An async job pipeline: submit → webhook/poll → download → re-host. Priced per second.

AI SDK 7 wraps every provider. experimental_startVideo submits and returns a serializable operation (pass webhookUrl). experimental_getVideoStatus does one check. experimental_generateVideo submits and waits, for scripts and durable workflows only. Point them at AI Gateway ids ('google/veo-3.1-generate-001', 'klingai/kling-v3.0-t2v') or provider models (fal.video(...), xai.video('grok-imagine-video-1.5')), so changing model means changing a string. Never block a serverless handler. Prices run from $0.02/s (Grok Imagine 1.5 Lite, 480p) to $0.60/s (Veo 3.1 at 4K). Draft cheap, promote the keeper. For codeAmani, video is its own row in the AI routing policy. Re-host every clip to R2, and for Kenya-targeted projects default to short 9:16 clips.

Six things to know about generative video

It's an async render, not a request/response, and the clip URL is temporary.

Text
 █████╗ ██╗    ██╗   ██╗██╗██████╗ ███████╗ ██████╗
██╔══██╗██║    ██║   ██║██║██╔══██╗██╔════╝██╔═══██╗
███████║██║    ██║   ██║██║██║  ██║█████╗  ██║   ██║
██╔══██║██║    ╚██╗ ██╔╝██║██║  ██║██╔══╝  ██║   ██║
██║  ██║██║     ╚████╔╝ ██║██████╔╝███████╗╚██████╔╝
╚═╝  ╚═╝╚═╝      ╚═══╝  ╚═╝╚═════╝ ╚══════╝ ╚═════╝

AI Video Generation Integration Guide

Focus: generative video is an async job, not a request/response. You submit a prompt, get a job id, then either poll the status or let a webhook call you back, and finally download the rendered clip. It is the same reverse-API flow the repo already documents for webhooks, applied to a render that takes 30 seconds to several minutes.

Overview

Text-to-video and image-to-video models turn a prompt (and optionally a start image, reference images, or a source video) into a short MP4. Most current models generate native audio too. Unlike an LLM call that streams tokens back in seconds, a video render is long-running and expensive. An 8-second 1080p clip takes a minute or more of GPU time and costs anywhere from about $0.16 to several dollars. So no serious provider makes you hold an HTTP connection open for the render. They all use the same shape:

  1. Submit the prompt. You immediately get a job / prediction / operation id.
  2. Wait for completion, in one of two ways:
    • Poll: GET the job id every few seconds until status is terminal.
    • Webhook: register a callback URL and the provider POSTs to you when the clip is ready. This is the cheaper, more scalable path, and it is the same receiver pattern documented in webhooks/.
  3. Download the clip from the URL in the result. The URL expires, so re-host it to your own R2 or Supabase bucket.

This guide treats AI video as a separate modality in the codeAmani AI routing policy, alongside Claude (reasoning), OpenAI (structured output), and HuggingFace (open models). It covers three ways in:

  • AI SDK 7 (ai): one TypeScript API over AI Gateway, fal, xAI, Google, Vertex, Kling, Replicate and more. This is the default for Next.js projects.
  • Aggregators (fal.ai, Replicate, and now Runway Dev): dozens of models behind one async interface.
  • First-party APIs (Gemini API for Omni Flash and Veo, xAI, Runway, Luma Agents) when you need a feature the wrappers don't expose yet.

Models & providers

Prices are per second of output, checked against official pages on 2026-10-20. They move fast, so re-check before you commit a budget. Full table with sources: reference/pricing-snapshot.md.

ModelBest atNative audioDuration / res (API)$/sec (official)How to call
Google Gemini Omni Flash (gemini-omni-1.1-flash)Google's recommended default in the Gemini API: coherence, multi-input (text + image + audio + video), multi-turn editingYes3–10 s · 360p / 720p, with 1080p and 4K upscaled~$0.10 at 720p (token-billed)Gemini Interactions API (ai.interactions.create), fal google/gemini-omni-flash/v1.1/..., Runway
Google Veo 3.1 (Standard / Fast / Lite)Top realism and lip-sync; video extension, first/last frame, up to 3 reference imagesYes (default on)4 / 6 / 8 s · 720p / 1080p / 4K (no 4K on Lite)Std $0.40 (4K $0.60) · Fast $0.10 / $0.12 / $0.30 · Lite $0.05 / $0.08Gemini API generateVideos, Vertex, AI Gateway google/veo-3.1-generate-001, fal fal-ai/veo3.1, Replicate google/veo-3.1
xAI Grok Imagine Video 1.5 (+ Lite)Cheapest credible drafts; editing, extension, reference-to-video with reference audioYes1–15 s · 480p / 720p / 1080p1.5: $0.08 / $0.14 / $0.25 · Lite: $0.02 / $0.03 / $0.14xAI API, AI SDK @ai-sdk/xai (xai.video(...)), fal, Runway
Kling 3.0 (Standard / Pro / 4K) + Kling O3Physics, multi-shot consistency, voice controlYes (optional)3–15 s · up to 4Kfal Pro $0.112 (no audio) / $0.168 (audio) · Std $0.084 / $0.126AI SDK @ai-sdk/klingai, AI Gateway klingai/kling-v3.0-t2v, fal, Runway
Runway Gen-4.5Cinematic control, prompt adherenceNo (use Aleph 2.0 to edit with audio)2–10 s · 1280:720 / 720:1280$0.12 (12 credits/s) · Gen-4 Turbo $0.05Runway Dev API (@runwayml/sdk)
ByteDance Seedance 2.5 / 2.0Long clips (2.5: up to 30 s), strong image-to-videoYes4–30 s · 480p / 720p / 1080pfal 2.5 (US): ~$0.22 / $0.47 / $1.16 · 2.0 Fast ~$0.24 @720p · Runway 2.5: $0.20 / $0.30 / $0.68AI Gateway, fal bytedance/seedance-2.5/us/..., Runway
Alibaba Wan 3.0Low-cost generalist, smart durationYes2–30 s · 480p / 720p / 1080pfal $0.05 / $0.10 / $0.20fal alibaba/wan-3.0/..., AI Gateway (Wan 2.6), Runway
MiniMax Hailuo H3 / H3 MaxCheap, stylised presets, up to 4KYes5–15 s · 480p–4Kfal H3: $0.05 (480p) – $0.16 (4K) · H3 Max list $0.05–$0.16fal minimax/h3/..., Runway (hailuo3, h3_max)
Lightricks LTX 2.5Fast, long (up to 20 s at 24/25 fps), audio includedYes6–20 s · 720p–4Kfal Fast $0.09 (720p) – $0.30 (4K)fal lightricks/ltx-2.5/...
Luma Ray3.2HDR, keyframes, reframePartial5 / 10 s · 540p–1080pfal $0.10 (540p) / $0.20 (720p) / $0.40 (1080p)Luma Agents API (REST), fal luma/agent/ray/v3.2/...
Pika 2.2Stylised effects, socialPartial5 / 10 s · 720p / 1080pfal $0.04 (720p) / $0.09 (1080p)fal fal-ai/pika/v2.2/...
OpenAI Sora 2————Shut down 2026-09-24. Videos API and all sora-2* models removed, no replacement

⚠️ Sora is gone. OpenAI's deprecations page lists the Videos API, sora-2, sora-2-pro and their dated snapshots as removed on 2026-09-24, with no recommended replacement. Delete any remaining Sora code paths and route those jobs to Veo, Omni Flash, Kling or Grok Imagine.

Selection heuristic: draft on a cheap tier (Grok Imagine 1.5 Lite, Veo 3.1 Lite, Wan 3.0 or Hailuo H3 at 480p/720p). Then re-render only the chosen prompt on a hero tier (Veo 3.1 Standard, Omni Flash at 1080p, or Kling 3 Pro). In a Next.js app, go through AI SDK + AI Gateway or fal so changing models means changing a string.

Official Documentation

SourceURLWhat it covers
AI SDK video generationhttps://ai-sdk.dev/docs/ai-sdk-core/video-generationexperimental_generateVideo: settings, polling, webhook factory, NoVideoGeneratedError
AI SDK generateVideo referencehttps://ai-sdk.dev/docs/reference/ai-sdk-core/generate-videoFull parameter list
AI Gateway videohttps://vercel.com/docs/ai-gateway/modalities/video-generationGateway model ids (google/veo-3.1-generate-001, klingai/kling-v3.0-t2v, alibaba/wan-v2.6-r2v), async + webhook, 300 KiB start-request cap
Gemini video overviewhttps://ai.google.dev/gemini-api/docs/videoOmni Flash vs Veo 3.1: which to use when
Gemini Omni Flashhttps://ai.google.dev/gemini-api/docs/omniInteractions API, multi-turn editing, limits
Gemini Veo 3.1https://ai.google.dev/gemini-api/docs/veogenerateVideos, operation polling, extension, 2-day retention
Gemini pricinghttps://ai.google.dev/gemini-api/docs/pricingVeo 3.1 Standard / Fast / Lite and Omni per-second rates
xAI video generationhttps://docs.x.ai/developers/model-capabilities/video/generationGrok Imagine Video models, durations, editing/extension
xAI pricinghttps://docs.x.ai/developers/pricingPer-second rates by resolution
fal queue APIhttps://fal.ai/docs/model-apis/model-endpoints/queuefal.queue.submit/status/result, subscribe, webhookUrl
fal model schema (any model)https://fal.ai/models/<endpoint-id>/llms.txtCurrent input enums and pricing for one endpoint. Use this, not memory
Replicate Veo 3.1https://replicate.com/google/veo-3.1Inputs (image, last_frame, reference_images), pricing
Replicate JS clienthttps://github.com/replicate/replicate-javascriptpredictions.create + webhook, predictions.get
Runway Dev APIhttps://docs.dev.runwayml.com/Gen-4.5, Aleph 2.0, plus third-party models (Veo, Kling, Seedance, Wan, Grok, Hailuo, Omni)
Runway pricinghttps://docs.dev.runwayml.com/guides/pricing/Credits per second ($0.01 / credit)
Luma Agents APIhttps://docs.agents.lumalabs.ai/ray-3.2 video via https://agents.lumalabs.ai/v1/generations

The async lifecycle: submit → poll / webhook → download

Every provider is a variation on this. Submit returns an id, not the clip. You then wait by polling or by receiving a webhook, then download.

Two ways to wait, one rule: the clip URL the provider returns is temporary. Gemini deletes Veo files after 2 days, Luma Agents presigned URLs last 1 hour, and aggregator URLs are signed and expire. Download and re-host to your own bucket immediately. Never store the provider URL as your permanent asset link.

Provider selection flow


AI SDK 7: one API for every provider (default for Next.js)

AI SDK 7 (ai@7.0.146) ships video generation as an experimental API. There is no stable generateVideo export yet, so import the experimental_ names and alias them:

FunctionWhat it doesUse it in
experimental_generateVideoSubmit and wait. The SDK polls (default every 5 s, 10 min timeout) or waits on your webhook factory, then returns video.uint8Array / video.base64.Scripts, durable workflows (poll.delay), Workflow DevKit steps
experimental_startVideoSubmit and return immediately with a JSON-serializable operation. Accepts webhookUrl.Request handlers: submit, store operation, return 202
experimental_getVideoStatusOne status check: pending / completed (with videos) / error.Webhook receivers and scheduled pollers

startVideo and getVideoStatus are in the ai@7.0.146 type definitions and the fal, xAI, Google and Vertex providers implement doStart. They do not have reference pages on ai-sdk.dev yet, so re-check them whenever you bump ai.

TypeScript
// Script / durable workflow: submit + wait in one call.
import { experimental_generateVideo as generateVideo } from "ai";

const { video, warnings } = await generateVideo({
  model: "google/veo-3.1-generate-001", // AI Gateway id (needs AI_GATEWAY_API_KEY or Vercel OIDC)
  prompt: "Medium shot, a Nairobi street vendor arranging mangoes at dawn, slow dolly-in, warm light",
  aspectRatio: "9:16",
  duration: 8,
  generateAudio: true,
  poll: { intervalMs: 5_000, timeoutMs: 600_000 },
});
// video.uint8Array: upload straight to R2. warnings lists unsupported settings.
TypeScript
// Request handler: submit and return. The provider calls your webhook later.
import { experimental_startVideo as startVideo } from "ai";
import { fal } from "@ai-sdk/fal";

const { operation } = await startVideo({
  model: fal.video("fal-ai/kling-video/v3/pro/text-to-video"),
  prompt: "Product reel: a phone on a kitenge cloth, slow orbit, soft daylight",
  aspectRatio: "9:16",
  duration: 5,
  webhookUrl: "https://app.codeamanilabs.org/api/webhooks/video",
});
// Persist `operation` (JSON) on the job row now. It's your idempotency key.

Key settings (all optional, all model-dependent, and unsupported ones come back in warnings): aspectRatio ("16:9", "9:16", or "adaptive" for image-to-video), resolution ("1280x720"), duration (seconds), fps, seed, generateAudio, frameImages (first_frame / last_frame), inputReferences (images or videos), n, providerOptions. Failures throw NoVideoGeneratedError.

Provider packages (versions verified 2026-10-20):

PackageModel factoryExample ids
ai 7.0.146 (AI Gateway built in)model stringgoogle/veo-3.1-generate-001, klingai/kling-v3.0-t2v, alibaba/wan-v2.6-r2v
@ai-sdk/fal 3.0.65fal.video(id)any fal endpoint id, e.g. fal-ai/veo3.1, bytedance/seedance-2.5/us/text-to-video
@ai-sdk/xai 5.0.26xai.video(id)grok-imagine-video, grok-imagine-video-1.5
@ai-sdk/google 4.0.101google.video(id)veo-3.1-generate-preview, veo-3.1-fast-generate-preview, veo-3.1-lite-generate-preview
@ai-sdk/google-vertex 5.0.118vertex.video(id)veo-3.1-generate-001, veo-3.1-fast-generate-001
@ai-sdk/klingai 4.0.66klingai.video(id)kling-v3.0-t2v, kling-v3.0-i2v, kling-v3.0-motion-control
@ai-sdk/replicate 3.0.65 · @ai-sdk/black-forest-labs 2.0.66 · @ai-sdk/alibaba 2.0.72 · @ai-sdk/bytedance 2.0.67 · @ai-sdk/minimax 3.0.61per provider docssee ai-sdk.dev provider pages

The AI Gateway caps the async start request at 300 KiB, so pass hosted image URLs (R2 or Vercel Blob), not inline bytes, for image-to-video and references.

See examples/generate-video.ts for a type-checked submit / check / poll / download helper built on these calls.


fal.ai: the broadest aggregator (submit + webhook, or subscribe)

@fal-ai/client exposes the queue directly. For production, submit with a webhookUrl so you never block. For a quick script, fal.subscribe handles the polling. Always read the endpoint's current schema and price from https://fal.ai/models/<endpoint-id>/llms.txt.

TypeScript
// lib/video/fal.ts
import { fal } from "@fal-ai/client";

fal.config({ credentials: process.env.FAL_KEY! }); // server-side only

/** Production path: submit and let fal call your webhook when done. */
export async function submitVeoJob(prompt: string): Promise<string> {
  const { request_id } = await fal.queue.submit("fal-ai/veo3.1", {
    input: {
      prompt,
      aspect_ratio: "9:16", // "16:9" (default) | "9:16"
      duration: "8s",       // string enum: "4s" | "6s" | "8s" (default "8s")
      resolution: "720p",   // "720p" (default) | "1080p" | "4k"
      generate_audio: true, // default true; audio off halves the price ($0.20/s vs $0.40/s)
    },
    webhookUrl: "https://app.codeamanilabs.org/api/webhooks/fal",
  });
  return request_id; // store this: it's your idempotency key on the callback
}

/** Read the finished clip once the webhook says it's ready. */
export async function fetchVeoResult(requestId: string): Promise<string> {
  const result = await fal.queue.result("fal-ai/veo3.1", { requestId });
  return result.data.video.url; // re-host this immediately (it expires)
}

For a one-off with no webhook infrastructure, subscribe polls for you:

TypeScript
const result = await fal.subscribe("fal-ai/veo3.1", {
  input: { prompt, duration: "8s", resolution: "720p" },
  logs: true,
});
// result.data.video.url

Swap the endpoint id to change model. Current ids (from fal's catalog, 2026-10-20): fal-ai/kling-video/v3/pro/text-to-video, bytedance/seedance-2.5/us/text-to-video, alibaba/wan-3.0/text-to-video, minimax/h3/text-to-video, xai/grok-imagine-video/v1.5/text-to-video, google/gemini-omni-flash/v1.1/text-to-video, luma/agent/ray/v3.2/text-to-video, lightricks/ltx-2.5/text-to-video/fast. Most have an /image-to-video sibling.

The webhook receiver is exactly the pattern in webhooks/CLAUDE_CODE_INTEGRATION.md: verify, dedupe on request_id, ACK fast, then download and re-host out of band.


Replicate: one client, hundreds of models

replicate.predictions.create returns a prediction id and supports webhook + webhook_events_filter. Polling is predictions.get(id) with statuses starting → processing → succeeded | failed | canceled.

TypeScript
// lib/video/replicate.ts
import Replicate from "replicate";

const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN! });

/** Submit a Veo 3.1 render with a webhook callback. */
export async function submitReplicateVideo(prompt: string, imageUrl?: string) {
  const prediction = await replicate.predictions.create({
    model: "google/veo-3.1",
    input: {
      prompt,
      image: imageUrl,        // omit for text-to-video; `last_frame`, `reference_images` (1–3) also accepted
      duration: 8,            // 4 | 6 | 8 seconds
      resolution: "1080p",    // "720p" | "1080p"
      aspect_ratio: "9:16",
      generate_audio: true,   // $0.40/s with audio, $0.20/s without
    },
    webhook: "https://app.codeamanilabs.org/api/webhooks/replicate",
    webhook_events_filter: ["completed"], // fire once, when terminal
  });
  return prediction.id;
}

/** Polling fallback when you have no webhook endpoint. */
export async function pollReplicate(id: string): Promise<string> {
  let prediction = await replicate.predictions.get(id);
  while (!["succeeded", "failed", "canceled"].includes(prediction.status)) {
    await new Promise((r) => setTimeout(r, 3000));
    prediction = await replicate.predictions.get(id);
  }
  if (prediction.status !== "succeeded") throw new Error(String(prediction.error));
  return prediction.output as unknown as string; // signed MP4 url: re-host it
}

replicate.run(model, { input }) is the blocking convenience form. It's fine for scripts, but avoid it in request handlers: a render can outlast a serverless function's timeout.


Google first-party (@google/genai): Omni Flash and Veo 3.1

Google's video docs now say to use Gemini Omni Flash as the default video model, and Veo 3.1 for scene extension, last-frame control, or legacy pipelines. The two use different APIs.

Gemini Omni Flash: Interactions API

TypeScript
// lib/video/omni.ts
import { GoogleGenAI } from "@google/genai";
import { writeFileSync } from "node:fs";

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY! });

export async function generateOmniClip(prompt: string): Promise<string> {
  const interaction = await ai.interactions.create({
    model: "gemini-omni-1.1-flash",
    input: prompt,
  });
  if (!interaction.output_video?.data) throw new Error("No video returned");
  writeFileSync("omni.mp4", Buffer.from(interaction.output_video.data, "base64"));
  return "omni.mp4"; // upload to R2
}

By default this call is synchronous: base64 comes back inline. Google documents a URI-delivery mode for larger outputs. Omni limits: 3–10 s generation; 360p or 720p native with 1080p and 4K upscaled; 16:9 or 9:16; no negative_prompt (put "do not…" in the prompt); no audio-reference uploads; and uploaded-video editing is unavailable in the EEA, Switzerland and the UK. Multi-turn edits chain via previous_interaction_id.

Veo 3.1: long-running operation

generateVideos returns an operation that you poll with getVideosOperation until operation.done, then download with ai.files.download.

TypeScript
// lib/video/veo.ts
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY! });

export async function generateVeoClip(prompt: string): Promise<string> {
  let operation = await ai.models.generateVideos({
    // veo-3.1-generate-preview (Standard) · veo-3.1-fast-generate-preview (drafts)
    // · veo-3.1-lite-generate-preview (cheapest, no 4K)
    model: "veo-3.1-generate-preview",
    prompt,
  });

  // Poll the long-running operation (no webhook on this SDK path).
  while (!operation.done) {
    await new Promise((r) => setTimeout(r, 10_000));
    operation = await ai.operations.getVideosOperation({ operation });
  }

  const video = operation.response?.generatedVideos?.[0]?.video;
  if (!video) throw new Error("Veo returned no video (possibly filtered)");
  await ai.files.download({ file: video, downloadPath: "output.mp4" });
  return "output.mp4"; // upload to R2/Supabase: Gemini deletes it after 2 days
}

Veo 3.1 constraints (Gemini API): durations 4 / 6 / 8 s. Use 8 s for 1080p, 4K, reference images (up to 3), or extension. Extension only works on 720p clips, and Veo-generated input can be at most 141 s (148 s combined). Aspect ratio is 16:9 (default) or 9:16. Audio is native. Output carries a SynthID watermark. Veo 3.0 / 3.0 Fast are deprecated. All three 3.1 models are still -preview in the Gemini API. Vertex AI and AI Gateway expose GA ids (veo-3.1-generate-001, veo-3.1-fast-generate-001). For background jobs on Google at scale, prefer Vertex (or AI Gateway) over an inline polling loop.


xAI Grok Imagine Video: cheapest first-party drafts

xAI's video models are grok-imagine-video, grok-imagine-video-1.5, and grok-imagine-video-1.5-lite. They cover text-to-video, image-to-video, editing, extension and reference-to-video. Version 1.5 accepts reference audio and renders native 1080p. The simplest TypeScript path is the AI SDK provider:

TypeScript
import { experimental_generateVideo as generateVideo } from "ai";
import { xai } from "@ai-sdk/xai"; // reads XAI_API_KEY

const { video } = await generateVideo({
  model: xai.video("grok-imagine-video-1.5"),
  prompt: "Boda boda rider weaving through Nairobi traffic at golden hour, handheld",
  aspectRatio: "9:16",
  duration: 6,
});

The @ai-sdk/xai@5.0.26 typings list grok-imagine-video and grok-imagine-video-1.5. The -1.5-lite id is on xAI's pricing page and fal, and it passes through as a plain string.


Runway Dev: Gen-4.5 plus a model marketplace

Runway's API (Runway Dev, @runwayml/sdk 4.22.0, reads RUNWAYML_API_SECRET) now resells third-party models next to its own: Veo 3.1, Gemini Omni Flash, Kling 3 / O3, Seedance 2 / 2.5, Wan 3, Grok Imagine 1.5, and Hailuo 3. All are billed at $0.01 per credit. Gen-4.5 is 12 credits/s ($0.12/s), Gen-4 Turbo 5 credits/s, Aleph 2.0 (video-to-video editing) 28 credits/s.

TypeScript
import RunwayML from "@runwayml/sdk";

const client = new RunwayML(); // RUNWAYML_API_SECRET

const task = await client.textToVideo
  .create({
    model: "gen4.5",
    promptText: "Slow push-in on a Maasai beadwork stall at dusk, shallow depth of field",
    ratio: "720:1280", // gen4.5 text-to-video: "1280:720" | "720:1280"
    duration: 5,       // integer, 2–10 s
  })
  .waitForTaskOutput(); // polls for you; fine in a worker, not in a request handler

Luma: the Agents API replaced the Dream Machine API

Luma's old API docs (docs.lumalabs.ai, ray-2 / ray-flash-2, lumaai npm) now point to the Luma Agents API at https://agents.lumalabs.ai/v1/generations with model ray-3.2, auth LUMA_AGENTS_API_KEY, type: "video", video: { resolution, duration: "5s" }. Results come back as presigned URLs that expire after 1 hour, so re-host immediately. ⚠️ The luma-agents npm SDK (0.1.2) only types the image models (uni-1, uni-1-max) so far. For video, call the REST endpoint with fetch, or use fal's luma/agent/ray/v3.2/text-to-video.


Cost, limits & content moderation

  • Cost discipline. Price is per output-second, and failed or retried renders still cost money. Draft at 480p/720p on a cheap tier; deliver at 1080p on a hero tier. Turn audio off when you don't need it (it halves Veo's price on fal and Replicate). Cap duration: a 4 s clip costs half as much as 8 s. Show users the estimated cost before they hit generate.
  • Duration/resolution are per-model enums. Veo: 4/6/8 s. Kling 3: 3–15 s. Runway Gen-4.5: 2–10 s. Seedance 2.5: 4–30 s or auto. Luma: 5s/10s. Validate against the target model's enum at your adapter boundary. An invalid value is a wasted round-trip, and AI SDK may just drop it with a warning.
  • Prompt structure matters. Write the prompt as a shot list: subject + action + setting + camera move + lighting + style, e.g. "Medium shot, a Nairobi street vendor arranging mangoes at dawn, slow dolly-in, warm golden light, cinematic." Use negative_prompt where supported (not on Omni). Supply a start image or reference images for brand and character consistency.
  • Content moderation & safety. Every provider filters input and output: fal safety_tolerance "1"–"6" (Veo default "4") with optional auto_fix prompt rewriting; Luma failure code content_moderated; Runway moderation. Real-person likeness, public figures and minors are restricted. Omni blocks uploads of recognisable people, and of minors in the EEA, Switzerland and the UK. A job can come back failed or moderated, so handle that branch and don't bill the user for a rejected render. Veo and Omni output carries an invisible SynthID watermark.
  • Idempotency. Store the job_id / operation the instant submit returns. Dedupe webhook deliveries on it, since they are at-least-once (same rules as webhooks/).

codeAmani notes

  • AI routing policy: video row. Video is a separate modality alongside Claude (reasoning), OpenAI (structured) and HuggingFace (open models):

    Use caseProvider
    Client-deliverable / hero clip, lip-sync, 1080p+Veo 3.1 Standard (AI Gateway / Vertex) or Gemini Omni Flash at 1080p
    Draft / social / WhatsApp-status clips, cost-firstGrok Imagine 1.5 Lite, Veo 3.1 Lite, Wan 3.0 or Hailuo H3 at 480p/720p
    Social clip with audio, 5–15 sKling 3 (Standard/Pro) via fal or AI Gateway
    Swap-models-fast prototypingAI SDK (experimental_startVideo) over AI Gateway or fal: change the model string
    SoraRemoved 2026-09-24. Do not use
  • Default integration path. In Next.js apps use ai + AI Gateway (or @ai-sdk/fal). Submit with experimental_startVideo({ webhookUrl }) from the route handler, store operation, and finish in app/api/webhooks/video/route.ts with experimental_getVideoStatus. Use raw provider SDKs only for features the AI SDK doesn't expose yet (Omni multi-turn editing, Runway Aleph, Luma Ray3.2 keyframes).

  • Market defaults (US-first). Default to short clips (5–8 s) at 16:9 for web and 9:16 for social. Stripe-metered credits gate generation (see stripe/).

  • Kenya-targeted projects. For East African SME marketing (product reels, M-Pesa promo clips, WhatsApp-status ads), default to 9:16 vertical and 4–6 s clips at 720p. They stay cheap and still load on 2G/3G. Paywall generation with M-Pesa (Daraja) credits only when the project's primary users are in Kenya; otherwise use Stripe.

  • Swahili prompts. The strong models accept Swahili or Sheng prompts directly ("Muuzaji wa maembe sokoni Nairobi, mwanga wa asubuhi, cinematic"). For best results, write the visual description in English and keep on-screen text / dialogue in Swahili. Always check rendered captions and lip-synced speech, because loanword spelling and pronunciation drift.

  • Cost discipline on a budget. Never render inside a request handler and wait. Always submit + webhook, store the operation / job_id, and re-host the finished MP4 to R2 (no egress fees) instead of serving the provider's expiring URL. Draft cheap, deliver premium, cap duration, and show the per-clip cost estimate before generating.

  • Secrets. All keys are server-side only: .env.local locally, Vercel env vars in production, never NEXT_PUBLIC_*. Only set the keys for providers you actually use:

Bash
AI_GATEWAY_API_KEY=vck_...
FAL_KEY=fal_...
XAI_API_KEY=xai-...
GEMINI_API_KEY=AIza...
REPLICATE_API_TOKEN=r8_...
RUNWAYML_API_SECRET=key_...
LUMA_AGENTS_API_KEY=luma_...

On Vercel, AI Gateway can authenticate with the deployment's OIDC token instead of AI_GATEWAY_API_KEY. @ai-sdk/fal also accepts FAL_API_KEY. @ai-sdk/google reads GOOGLE_GENERATIVE_AI_API_KEY unless you pass apiKey explicitly. Verify each provider's webhook signature before trusting the callback (see webhooks/). AI Gateway's async start returns a webhookSigningSecret in providerMetadata.gateway.

Setting (not secret)Where
Model id per tier (e.g. google/veo-3.1-generate-001)lib/video/models.ts constant, not env
Webhook base URLNEXT_PUBLIC_APP_URL or route config
Max duration / resolution per planDB plan table
  • Route layout. app/api/webhooks/video/route.ts (AI SDK) or app/api/webhooks/<provider>/route.ts for raw fal/Replicate callbacks. Submit logic lives in lib/video/<provider>.ts behind the VideoJobState interface in examples/generate-video.ts.