翻篇收录说明
翻篇网页快照

Video Generation API - Asynchronous Video Generation on OpenRouter

https://openrouter.ai/docs/api_reference/videos

最近抓取:2026-12-04 13:32:28(北京时间)

最近内容变化:2026-12-04 13:32:28(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Complete API reference for OpenRouter's dedicated asynchronous Video Generation API. Submit jobs, poll status, stream video content, discover models, and configure webhooks.

正文摘录

OpenRouter provides a dedicated asynchronous API for generating videos from text prompts, start and end frame images, and multimodal references. Because video generation takes significantly longer than text or image generation (typically 30 seconds to several minutes), requests follow an asynchronous submit-poll-download lifecycle. Endpoints The Video Generation API consists of four endpoints: MethodEndpointDescriptionResponsePOST/api/v1/videosSubmits a video generation job202 Accepted with job ID and polling URLGET/api/v1/videos/{jobId}Polls job status, progress, and download URLs200 OK with status and video URLsGET/api/v1/videos/{jobId}/contentStreams video binary bytes from the provider200 video/mp4 binary streamGET/api/v1/videos/modelsLists video generation models and capabilities200 OK with model parameter metadata End-to-end workflow Video generation follows three sequential steps: Submit: Send a generation request with a video model and prompt to POST /api/v1/videos. Receive a job ID (id) and an absolute polling URL (polling_url) on the job’s regional host; use it as returned. Poll: Send a GET to the returned polling_url every 10–30 seconds until the job is completed, failed, cancelled, or expired. Alternatively, supply a callback_url to receive a webhook notification. Download: When the job completes, use the returned unsigned_urls entry for the output you want, with your API key. If you use a signed link from urls instead, follow its redirect without sending your API key. Set OPENROUTER_API_ORIGIN to https://eu.openrouter.ai or https://us.openrouter.ai for regional routing, or leave it unset for https://openrouter.ai. Submit to that origin, then use the returned URLs without rebuilding them from the job ID. Before attaching your bearer token, verify that each polling or authenticated download URL matches your configured OpenRouter origin. The examples download the first output by default; set VIDEO_OUTPUT_INDEX to select a different zero-based entry. In a multi-user app, one API key can poll, download, and continue every job the app created. Record which end user owns each job ID, and check that ownership before you act on a job ID supplied by a client. cURL example Install jq before running this Bash example. set -euo pipefail command -v jq >/dev/null || { echo "Install jq before submitting a video job" >&2; exit 1; } API_ORIGIN="${OPENROUTER_API_ORIGIN:-https://openrouter.ai}" case "$API_ORIGIN" in https://openrouter.ai|https://eu.openrouter.ai|https://us.openrouter.ai) ;; *) echo "Invalid OpenRouter API origin" >&2; exit 1 ;; esac OUTPUT_INDEX="${VIDEO_OUTPUT_INDEX:-0}" [[ "$OUTPUT_INDEX" =~ ^(0|[1-9][0-9]*)$ ]] || exit 1 openrouter_get() { case "$1" in "$API_ORIGIN"/api/v1/videos/*) ;; *) echo "Expected a video URL on $API_ORIGIN" >&2; return 1 ;; esac local body status body=$(mktemp) || return 1 if ! status=$( curl -q -fgsS -H "Authorization: Bearer $OPENROUTER_API_KEY" \ --output "$body" --write-out '%{http_code}' "$1" ) || [[ "$status" != 2?? ]]; then rm -f -- "$body" echo "OpenRouter request failed (HTTP ${status:-unknown})" >&2 return 1 fi if [[ $# -eq 2 ]]; then mv -- "$body" "$2" else cat -- "$body" rm -f -- "$body" fi } # Step 1: Submit a video generation job (Veo 3.1 supports durations: 4, 6, 8) SUBMIT_RESPONSE=$(curl -q -fsS -X POST "$API_ORIGIN/api/v1/videos" \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "google/veo-3.1", "prompt": "A drone shot flying through a mist-shrouded redwood forest at sunrise, cinematic lighting, 4k", "duration": 6, "resolution": "720p", "aspect_ratio": "16:9" }') JOB_ID=$(jq -er '.id' <<< "$SUBMIT_RESPONSE") POLLING_URL=$(jq -er '.polling_url' <<< "$SUBMIT_RESPONSE") echo "Submitted job: $JOB_ID" # Step 2: Poll until completion (capped at 40 iterations = 10 minutes) POLL_COUNT=0 while [ "$POLL_COUNT" -lt 40 ]; do sleep 15 POLL_COUNT=$((POLL_COUNT + 1)) STATUS_RESPONSE=$(openrouter_get "$POLLING_URL") STATUS=$(jq -er '.status' <<< "$STATUS_RESPONSE") echo "Current status: $STATUS" if [ "$STATUS" = "completed" ]; then break elif [ "$STATUS" = "failed" ] || [ "$STATUS" = "cancelled" ] || [ "$STATUS" = "expired" ]; then echo "Job terminated with status $STATUS" >&2 exit 1 fi done if [ "$STATUS" != "completed" ]; then echo "Timed out waiting for video generation" >&2 exit 1 fi # Step 3: Download video using the authenticated content endpoint CONTENT_URL=$(jq -er --argjson index "$OUTPUT_INDEX" '.unsigned_urls[$index]' <<< "$STATUS_RESPONSE") openrouter_get "$CONTENT_URL" output.mp4 echo "Saved video to output.mp4" TypeScript example const apiKey = process.env.OPENROUTER_API_KEY; if (!apiKey) { throw new Error('OPENROUTER_API_KEY environment variable is required'); } const headers = { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', }; const apiOrigin = process.env.OPENROUTER_API_ORIGIN || 'https://openrouter.ai'; if (!['https://openrouter.ai', 'https://eu.openrouter.ai', 'https://us.openrouter.ai'].includes(apiOrigin)) { throw new Error('Invalid OpenRouter API origin'); } function openrouterGet(link: string | undefined): Promise<Response> { if (!link?.startsWith(`${apiOrigin}/api/v1/videos/`)) { throw new Error(`Expected a video URL on ${apiOrigin}`); } return fetch(link, { headers, redirect: 'error' }); } type VideoJobStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'cancelled' | 'expired'; interface VideoJobResponse { id: string; generation_id?: string; status: VideoJobStatus; polling_url: string; urls?: string[]; expires_at?: number; unsigned_urls?: string[]; error?: string; usage?: { cost: number | null; is_byok?: boolean; }; } // Step 1: Submit job (Veo 3.1 supports durations: 4, 6, 8) const submitRes = await fetch(`${apiOrigin}/api/v1/videos`, { method: 'POST', headers, redirect: 'error', body: JSON.stringify({ model: 'google/veo-3.1', prompt: 'A gentle ocean wave washing over golden sand in slow motion', duration: 6, resolution: '720p', aspect_ratio: '16:9', }), }); if (!submitRes.ok) { const errorText = await submitRes.text(); throw new Error(`Video submission failed (${submitRes.status}): ${errorText}`); } const job = (await submitRes.json()) as VideoJobResponse; console.log(`Job submitted: ${job.id}`); // Step 2: Poll status with a 10-minute deadline const deadline = Date.now() + 10 * 60_000; let completedJob: VideoJobResponse | null = null; while (!completedJob) { if (Date.now() > deadline) { throw new Error(`Timed out waiting for video job ${job.id} to complete`); } await new Promise((resolve) => setTimeout(resolve, 15000)); const pollRes = await openrouterGet(job.polling_url); if (!pollRes.ok) { const errorText = await pollRes.text(); throw new Error(`Polling failed with HTTP ${pollRes.status}: ${errorText}`); } const statusData = (await pollRes.json()) as VideoJobResponse; console.log(`Status: ${statusData.status}`); if (statusData.status === 'completed') { completedJob = statusData; } else if (['failed', 'cancelled', 'expired'].includes(statusData.status)) { throw new Error(`Job ended with status ${statusData.status}: ${statusData.error ?? 'Unknown error'}`); } } // Step 3: Stream video bytes to file or downstream response const outputIndex = Number(process.env.VIDEO_OUTPUT_INDEX || '0'); const videoRes = await openrouterGet(completedJob.unsigned_urls?.[outputIndex]); if (!videoRes.ok) { throw new Error(`Video download failed (${videoRes.status})`); } const videoBytes = await videoRes.arrayBuffer(); console.log(`Downloaded video (${videoBytes.byteLength} bytes)`); Python example import os import time import requests api_key = os.getenv("OPENROUTER_API_KEY") if not api_key: raise ValueError("OPENROUTER_API_KEY environment variable is required") headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", } api_origin = os.getenv("OPENROUTER_API_ORIGIN") or "https://openrouter.ai" if api_origin not in ("https://openrouter.ai", "https://eu.openrouter.ai", "https://us.openrouter.ai"): raise ValueError("Invalid OpenRouter API origin") def openrouter_get(link): if not link.startswith(f"{api_origin}/api/v1/videos/"): raise ValueError(f"Expected a video URL on {api_origin}") response = requests.get(link, headers=headers, allow_redirects=False) if response.is_redirect: raise RuntimeError("Unexpected redirect from the OpenRouter API") response.raise_for_status() return response # Step 1: Submit video job (Veo 3.1 supports durations: 4, 6, 8) submit_res = requests.post( f"{api_origin}/api/v1/videos", headers=headers, allow_redirects=False, json={ "model": "google/veo-3.1", "prompt": "An architect sketching a modern house on parchment, pencil strokes forming 3D walls", "duration": 6, "resolution": "720p", "aspect_ratio": "16:9", }, ) submit_res.raise_for_status() job = submit_res.json() job_id = job["id"] print(f"Submitted video job: {job_id}") # Step 2: Poll until finished (capped at 40 iterations = 10 minutes) max_polls = 40 polls = 0 while polls < max_polls: time.sleep(15) polls += 1 poll_res = openrouter_get(job["polling_url"]) poll_data = poll_res.json() status = poll_data["status"] print(f"Job status: {status}") if status == "completed": break if status in ("failed", "cancelled", "expired"): raise RuntimeError(f"Video job failed with status {status}: {poll_data.get('error')}") else: raise TimeoutError(f"Video job {job_id} did not finish within 10 minutes") # Step 3: Download video binary output_index = int(os.getenv("VIDEO_OUTPUT_INDEX") or "0") if output_index < 0: raise ValueError("VIDEO_OUTPUT_INDEX must be nonnegative") download_res = openrouter_get(poll_data["unsigned_urls"][output_index]) with open("output.mp4", "wb") as f: f.write(download_res.content) print("Saved output.mp4") Job lifecycle and statuses The status field on GET /api/v1/videos/{jobId} reflects the current state of generation: StatusTypeMeaningNext actionpendingIn-flightThe request was admitted and queued for processingContinue pollingin_progressIn-flightThe provider