SPB Git

Repository Public

generation.md 27.2 KB 764 lines markdown

1<!-- source: https://docs.x.ai/developers/model-capabilities/video/generation (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Model Capabilities34# Video Generation56Generate videos from text prompts with Grok video models. The API supports configurable duration, aspect ratio, and resolution, and the SDK handles asynchronous polling automatically. On `grok-imagine-video-1.5`, text-to-video supports native 1080p.78> [!NOTE]9>10> On , text-to-video uses text-to-image then image-to-video under the hood: the model generates a first frame from your prompt, then animates it. You still make a single text-to-video request; the intermediate image is not returned.1112## Quick Start1314Generate a video with a single API call:1516```python customLanguage="pythonXAI"17import os18import xai_sdk1920client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))2122response = client.video.generate(23    prompt="A glowing crystal-powered rocket launching from the red dunes of Mars, ancient alien ruins lighting up in the background as it soars into a sky full of unfamiliar constellations",24    model="grok-imagine-video-1.5",25    duration=10,26    aspect_ratio="16:9",27    resolution="720p",28)2930print(response.url)31```3233```python customLanguage="pythonRequests"34import os35import time36import requests3738headers = {39    "Content-Type": "application/json",40    "Authorization": f"Bearer {os.environ['XAI_API_KEY']}",41}4243response = requests.post(44    "https://api.x.ai/v1/videos/generations",45    headers=headers,46    json={47        "model": "grok-imagine-video-1.5",48        "prompt": "A glowing crystal-powered rocket launching from the red dunes of Mars, ancient alien ruins lighting up in the background as it soars into a sky full of unfamiliar constellations",49        "duration": 10,50        "aspect_ratio": "16:9",51        "resolution": "720p",52    },53)5455request_id = response.json()["request_id"]5657# Poll until the video is ready58while True:59    result = requests.get(60        f"https://api.x.ai/v1/videos/{request_id}",61        headers={"Authorization": headers["Authorization"]},62    )63    data = result.json()64    if data["status"] == "done":65        print(data["video"]["url"])66        break67    elif data["status"] == "expired":68        print("Request expired")69        break70    time.sleep(5)71```7273```javascript customLanguage="javascriptAISDK"74import { xai } from "@ai-sdk/xai";75import { experimental_generateVideo as generateVideo } from "ai";7677const result = await generateVideo({78    model: xai.video("grok-imagine-video-1.5"),79    prompt: "A glowing crystal-powered rocket launching from the red dunes of Mars, ancient alien ruins lighting up in the background as it soars into a sky full of unfamiliar constellations",80    duration: 10,81    aspectRatio: "16:9",82    providerOptions: {83        xai: { resolution: "720p" },84    },85});8687const videoUrl = result.providerMetadata?.xai?.videoUrl;88console.log(videoUrl);89```9091```bash92# Start the video generation request93REQUEST_ID=$(curl -s -X POST https://api.x.ai/v1/videos/generations \94  -H "Content-Type: application/json" \95  -H "Authorization: Bearer $XAI_API_KEY" \96  -d '{97    "model": "grok-imagine-video-1.5",98    "prompt": "A glowing crystal-powered rocket launching from the red dunes of Mars, ancient alien ruins lighting up in the background as it soars into a sky full of unfamiliar constellations",99    "duration": 10,100    "aspect_ratio": "16:9",101    "resolution": "720p"102  }' | jq -r '.request_id')103104# Poll until the video is ready105while true; do106  RESULT=$(curl -s https://api.x.ai/v1/videos/$REQUEST_ID \107    -H "Authorization: Bearer $XAI_API_KEY")108  STATUS=$(echo "$RESULT" | jq -r '.status')109  if [ "$STATUS" = "done" ]; then110    echo "$RESULT" | jq -r '.video.url'111    break112  elif [ "$STATUS" = "failed" ] || [ "$STATUS" = "expired" ]; then113    echo "Request $STATUS"; echo "$RESULT" | jq .114    break115  fi116  sleep 5117done118```119120Video generation is an **asynchronous process** that typically takes up to several minutes to complete. The exact time varies based on:121122* **Prompt complexity** — More detailed scenes require additional processing123* **Duration** — Longer videos take more time to generate124* **Resolution** — Higher resolutions (1080p vs 480p) increase processing time125* **Video editing** — Editing existing videos adds overhead compared to image-to-video or text-to-video126127## Video workflows128129Use the page that matches the kind of video output you want to create:130131* [Image-to-Video](/developers/model-capabilities/video/image-to-video) — Animate a still image.132* [Video Editing](/developers/model-capabilities/video/editing) — Modify an existing video.133* [Reference-to-Video](/developers/model-capabilities/video/reference-to-video) — Guide a generated video with reference images, and on `grok-imagine-video-1.5` pin exact first or last frames.134* [Video Extension](/developers/model-capabilities/video/extension) — Continue an existing video from its last frame.135136## How it works137138Under the hood, video generation is a two-step process:1391401. **Start** — Submit a generation request and receive a `request_id`1412. **Poll** — Repeatedly check the status using the `request_id` until the video is ready142143The xAI SDK's `generate()` and `extend()` methods abstract this entirely; they submit your request, poll for the result, and return the completed video response. You don't need to manage request IDs or implement polling logic. For long-running generations, you can [customize the polling behavior](#customize-polling-behavior) with timeout and interval parameters, or [handle polling manually](#handle-polling-manually) for full control over the generation lifecycle.144145**REST API users** must implement this two-step flow manually:146147**Step 1: Start the generation request**148149```bash150curl -X POST https://api.x.ai/v1/videos/generations \151  -H "Content-Type: application/json" \152  -H "Authorization: Bearer $XAI_API_KEY" \153  -d '{154    "model": "grok-imagine-video-1.5",155    "prompt": "A glowing crystal-powered rocket launching from Mars"156  }'157```158159Response:160161```json162{"request_id": "d97415a1-5796-b7ec-379f-4e6819e08fdf"}163```164165**Step 2: Poll for the result**166167Use the `request_id` to check the status. Keep polling every few seconds until the video is ready:168169```bash170curl -X GET "https://api.x.ai/v1/videos/{request_id}" \171  -H "Authorization: Bearer $XAI_API_KEY"172```173174The response includes a `status` field with one of these values:175176| Status | Description |177|--------|-------------|178| `pending` | Video is still being generated |179| `done` | Video is ready |180| `expired` | Request has expired |181| `failed` | Video generation failed |182183Response (when complete):184185```json186{187  "status": "done",188  "video": {189    "url": "https://vidgen.x.ai/.../video.mp4",190    "duration": 8,191    "respect_moderation": true192  },193  "model": "grok-imagine-video-1.5"194}195```196197Videos are returned as temporary URLs. Access the xAI-hosted URL directly when you need it, or download/process it promptly if you need to keep a copy.198199## Configuration200201The video generation API lets you control the output format of your generated videos. You can specify the duration, aspect ratio, resolution, and (on reference-to-video) a preset voice to match your specific use case.202203### Duration204205Control video length with the `duration` parameter. The allowed range is 1–15 seconds.206207Video editing does not support custom `duration`. The edited video retains the duration of the original, which is capped at 8.7 seconds.208209### Aspect Ratio210211| Ratio | Use case |212|-------|----------|213| `1:1` | Social media, thumbnails |214| `16:9` / `9:16` | Widescreen, mobile, stories (default: `16:9`) |215| `4:3` / `3:4` | Presentations, portraits |216| `3:2` / `2:3` | Photography |217218For image-to-video generation, the output defaults to the input image's aspect ratio. If you specify the `aspect_ratio` parameter, it will override this and stretch the image to the desired aspect ratio.219220Video editing does not support custom `aspect_ratio` — the output matches the input video's aspect ratio.221222### Resolution223224| Resolution | Description |225|------------|-------------|226| `1080p` | Full HD quality |227| `720p` | HD quality |228| `480p` | Standard definition, faster processing (default) |229230**Note:** `1080p` is supported on `grok-imagine-video-1.5` for text-to-video and image-to-video. Reference-to-video is capped at 720p.231232Video editing does not support custom `resolution`. The output resolution matches the input video's resolution, capped at 720p (e.g., a 1080p input will be downsized to 720p).233234### Audio235236> [!WARNING]237>238> Preset voices are generally available. Voice references with your own audio files are available to trusted partners, on request. .239240On `grok-imagine-video-1.5`, [reference-to-video](/developers/model-capabilities/video/reference-to-video#reference-audio) can carry a voice via `reference_audios`. Voices come from the built-in roster and are named by `voice_id`; voice references with your own audio files are available to trusted partners [on request](https://x.ai/contact-sales?interest=imagine):241242| Property | Description |243|----------|-------------|244| Source | A preset `voice_id` (e.g. `{"voice_id": "eve"}`), from the same roster as [Text to Speech](/developers/model-capabilities/audio/text-to-speech#voices). Identifiers are case-insensitive |245| Limit | Max **3** voices per request |246| Prompt | Reference voices by index: `<AUDIO_0>`, `<AUDIO_1>`, `<AUDIO_2>` |247248Generated videos include an audio track by default. Pass `generate_audio=False` to request a silent video:249250```python customLanguage="pythonXAI"251import os252import xai_sdk253254client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))255256response = client.video.generate(257    prompt="A paper boat drifting down a rain-soaked street",258    model="grok-imagine-video-1.5",259    generate_audio=False,260)261262print(response.url)263```264265```bash266curl -X POST https://api.x.ai/v1/videos/generations \267  -H "Content-Type: application/json" \268  -H "Authorization: Bearer $XAI_API_KEY" \269  -d '{270    "model": "grok-imagine-video-1.5",271    "prompt": "A paper boat drifting down a rain-soaked street",272    "generate_audio": false273  }'274```275276### Example277278```python customLanguage="pythonXAI"279import os280import xai_sdk281282client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))283284response = client.video.generate(285    prompt="Timelapse of a flower blooming in a sunlit garden",286    model="grok-imagine-video-1.5",287    duration=10,288    aspect_ratio="16:9",289    resolution="720p",290)291292print(f"Video URL: {response.url}")293print(f"Duration: {response.duration}s")294```295296```python customLanguage="pythonRequests"297import os298import time299import requests300301headers = {302    "Content-Type": "application/json",303    "Authorization": f"Bearer {os.environ['XAI_API_KEY']}",304}305306response = requests.post(307    "https://api.x.ai/v1/videos/generations",308    headers=headers,309    json={310        "model": "grok-imagine-video-1.5",311        "prompt": "Timelapse of a flower blooming in a sunlit garden",312        "duration": 10,313        "aspect_ratio": "16:9",314        "resolution": "720p",315    },316)317318request_id = response.json()["request_id"]319320while True:321    result = requests.get(322        f"https://api.x.ai/v1/videos/{request_id}",323        headers={"Authorization": headers["Authorization"]},324    )325    data = result.json()326    if data["status"] == "done":327        print(f"Video URL: {data['video']['url']}")328        print(f"Duration: {data['video']['duration']}s")329        break330    elif data["status"] == "expired":331        print("Request expired")332        break333    time.sleep(5)334```335336```javascript customLanguage="javascriptAISDK"337import { xai } from "@ai-sdk/xai";338import { experimental_generateVideo as generateVideo } from "ai";339340const result = await generateVideo({341    model: xai.video("grok-imagine-video-1.5"),342    prompt: "Timelapse of a flower blooming in a sunlit garden",343    duration: 10,344    aspectRatio: "16:9",345    providerOptions: {346        xai: { resolution: "720p" },347    },348});349350const videoUrl = result.providerMetadata?.xai?.videoUrl;351console.log(videoUrl);352```353354```bash355# Start the video generation request356REQUEST_ID=$(curl -s -X POST https://api.x.ai/v1/videos/generations \357  -H "Content-Type: application/json" \358  -H "Authorization: Bearer $XAI_API_KEY" \359  -d '{360    "model": "grok-imagine-video-1.5",361    "prompt": "Timelapse of a flower blooming in a sunlit garden",362    "duration": 10,363    "aspect_ratio": "16:9",364    "resolution": "720p"365  }' | jq -r '.request_id')366367# Poll until the video is ready368while true; do369  RESULT=$(curl -s https://api.x.ai/v1/videos/$REQUEST_ID \370    -H "Authorization: Bearer $XAI_API_KEY")371  STATUS=$(echo "$RESULT" | jq -r '.status')372  if [ "$STATUS" = "done" ]; then373    echo "$RESULT" | jq -r '.video.url'374    break375  elif [ "$STATUS" = "failed" ] || [ "$STATUS" = "expired" ]; then376    echo "Request $STATUS"; echo "$RESULT" | jq .377    break378  fi379  sleep 5380done381```382383### Request Modes384385The video generation endpoint supports multiple modes, determined by which fields are set. Edit and extend use dedicated endpoints; generation modes share `/v1/videos/generations`:386387| Mode | REST API fields | AI SDK shape | Description |388|------|-----------------|--------------|-------------|389| Text-to-video | `prompt` only | `prompt: "..."` | Generates video from a text prompt alone. |390| Image-to-video | `prompt` + `image` | `prompt: { image, text }` | Generates video with the provided image as the starting frame. |391| Reference-to-video | `prompt` + `reference_images` or `reference_audios` | `prompt: "..."` + `providerOptions.xai.{ mode: "reference-to-video", referenceImageUrls }` | Generates video guided by reference images and/or a preset voice on `grok-imagine-video-1.5`. |392| First & Last frame | `last_frame`, optionally with `image` and/or `prompt` | REST body `last_frame` (no dedicated AI SDK field) | On `grok-imagine-video-1.5`, pins the exact last frame. Add `image` to also pin the first frame and interpolate between the two. `prompt` is optional whenever a frame is pinned. Can be combined with `reference_images` / `reference_audios`. |393| Edit-video | `/v1/videos/edits` + `video` | `prompt: "..."` + `providerOptions.xai.{ mode: "edit-video", videoUrl }` | Modifies an existing video based on the prompt. |394| Extend-video | `/v1/videos/extensions` + `video` | `prompt: "..."` + `providerOptions.xai.{ mode: "extend-video", videoUrl }` | Extends an existing video from its last frame. |395396On `grok-imagine-video-1.5`, `image` combined with `reference_images`, `reference_audios`, or `last_frame` is reference-to-video with a pinned first frame. The clip starts on that image rather than treating it as a style reference. `last_frame` on its own (no `image`, no references) is valid: the model generates the opening and lands on the pinned frame. `prompt` is optional for any request that includes `image`, `reference_images`, or `last_frame`; it is required only for text-to-video. Classic `grok-imagine-video` still rejects `last_frame` and rejects combining `image` with reference inputs.397398Do not mix AI SDK `mode` values. Each request supports exactly one of `"edit-video"`, `"extend-video"`, or `"reference-to-video"`. When you omit `mode`, the AI SDK uses standard generation.399400See [First & Last frame](/developers/model-capabilities/video/reference-to-video#first--last-frame) for `last_frame` examples.401402## Customize Polling Behavior403404When using the SDK's `generate()` or `extend()` methods, you can control how long to wait and how frequently to check for results:405406| Python SDK | AI SDK (`providerOptions.xai`) | Description | Default |407|-----------|-------------|-------------|---------|408| `timeout` | `pollTimeoutMs` | Maximum time to wait for the video to complete | 10 minutes |409| `interval` | `pollIntervalMs` | Time between status checks | 100 milliseconds |410411```python customLanguage="pythonXAI"412import os413from datetime import timedelta414import xai_sdk415416client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))417418response = client.video.generate(419    prompt="Epic cinematic drone shot flying through mountain peaks",420    model="grok-imagine-video-1.5",421    duration=15,422    timeout=timedelta(minutes=15),  # Wait up to 15 minutes423    interval=timedelta(seconds=5),  # Check every 5 seconds424)425426print(response.url)427```428429```javascript customLanguage="javascriptAISDK"430import { xai } from "@ai-sdk/xai";431import { experimental_generateVideo as generateVideo } from "ai";432433const result = await generateVideo({434    model: xai.video("grok-imagine-video-1.5"),435    prompt: "Epic cinematic drone shot flying through mountain peaks",436    duration: 15,437    providerOptions: {438        xai: {439            pollTimeoutMs: 15 * 60 * 1000,  // Wait up to 15 minutes440            pollIntervalMs: 5 * 1000,        // Check every 5 seconds441        },442    },443});444445const videoUrl = result.providerMetadata?.xai?.videoUrl;446console.log(videoUrl);447```448449If the video isn't ready within the timeout period, the Python SDK raises a `TimeoutError` and the AI SDK aborts via its `AbortSignal`. For even finer control, use the [manual polling approach](#handle-polling-manually); the Python SDK provides `start()` and `get()` methods, while the AI SDK supports a custom `abortSignal` for cancellation.450451## Handle Polling Manually452453For fine-grained control over the generation lifecycle, use `start()` or `extend_start()` to initiate generation/extension requests respectively and `get()` to check status.454455The `get()` method returns a response with a `status` field. Import the status enum from the SDK:456457```python customLanguage="pythonXAI"458import os459import time460import xai_sdk461from xai_sdk.proto import deferred_pb2462463client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))464465# Start the generation request466start_response = client.video.start(467    prompt="A cat lounging in a sunbeam, tail gently swishing",468    model="grok-imagine-video-1.5",469    duration=5,470)471472print(f"Request ID: {start_response.request_id}")473474# Poll for results475while True:476    result = client.video.get(start_response.request_id)477    478    if result.status == deferred_pb2.DeferredStatus.DONE:479        print(f"Video URL: {result.response.video.url}")480        break481    elif result.status == deferred_pb2.DeferredStatus.EXPIRED:482        print("Request expired")483        break484    elif result.status == deferred_pb2.DeferredStatus.FAILED:485        print("Video generation failed")486        break487    elif result.status == deferred_pb2.DeferredStatus.PENDING:488        print("Still processing...")489        time.sleep(5)490```491492```python customLanguage="pythonRequests"493import os494import time495import requests496497headers = {498    "Content-Type": "application/json",499    "Authorization": f"Bearer {os.environ['XAI_API_KEY']}",500}501502# Step 1: Start generation503response = requests.post(504    "https://api.x.ai/v1/videos/generations",505    headers=headers,506    json={507        "model": "grok-imagine-video-1.5",508        "prompt": "A cat lounging in a sunbeam, tail gently swishing",509        "duration": 5,510    },511)512513request_id = response.json()["request_id"]514print(f"Request ID: {request_id}")515516# Step 2: Poll for results517while True:518    result = requests.get(519        f"https://api.x.ai/v1/videos/{request_id}",520        headers={"Authorization": headers["Authorization"]},521    )522    data = result.json()523524    if data["status"] == "done":525        print(f"Video URL: {data['video']['url']}")526        break527    elif data["status"] == "expired":528        print("Request expired")529        break530    elif data["status"] == "failed":531        print("Video generation failed")532        break533    else:534        print("Still processing...")535        time.sleep(5)536```537538```javascript customLanguage="javascriptWithoutSDK"539// Step 1: Start generation540const response = await fetch("https://api.x.ai/v1/videos/generations", {541    method: "POST",542    headers: {543        "Content-Type": "application/json",544        "Authorization": `Bearer ${process.env.XAI_API_KEY}`,545    },546    body: JSON.stringify({547        model: "grok-imagine-video-1.5",548        prompt: "A cat lounging in a sunbeam, tail gently swishing",549        duration: 5,550    }),551});552553const { request_id } = await response.json();554console.log(`Request ID: ${request_id}`);555556// Step 2: Poll for results557while (true) {558    const result = await fetch(`https://api.x.ai/v1/videos/${request_id}`, {559        headers: { "Authorization": `Bearer ${process.env.XAI_API_KEY}` },560    });561562    const data = await result.json();563564    if (data.status === "done") {565        console.log(`Video URL: ${data.video.url}`);566        break;567    } else if (data.status === "expired") {568        console.log("Request expired");569        break;570    } else if (data.status === "failed") {571        console.log("Video generation failed");572        break;573    } else {574        console.log("Still processing...");575        await new Promise(resolve => setTimeout(resolve, 5000));576    }577}578```579580```bash581# Step 1: Start generation582REQUEST_ID=$(curl -s -X POST https://api.x.ai/v1/videos/generations \583  -H "Content-Type: application/json" \584  -H "Authorization: Bearer $XAI_API_KEY" \585  -d '{586    "model": "grok-imagine-video-1.5",587    "prompt": "A cat lounging in a sunbeam, tail gently swishing",588    "duration": 5589  }' | jq -r '.request_id')590591echo "Request ID: $REQUEST_ID"592593# Step 2: Poll for results594while true; do595  RESULT=$(curl -s https://api.x.ai/v1/videos/$REQUEST_ID \596    -H "Authorization: Bearer $XAI_API_KEY")597  STATUS=$(echo "$RESULT" | jq -r '.status')598  if [ "$STATUS" = "done" ]; then599    echo "$RESULT" | jq -r '.video.url'600    break601  elif [ "$STATUS" = "failed" ] || [ "$STATUS" = "expired" ]; then602    echo "Request $STATUS"; echo "$RESULT" | jq .603    break604  fi605  echo "Still processing..."606  sleep 5607done608```609610The available status values are:611612| Proto Value | Description |613|-------------|-------------|614| `deferred_pb2.DeferredStatus.PENDING` | Video is still being generated |615| `deferred_pb2.DeferredStatus.DONE` | Video is ready |616| `deferred_pb2.DeferredStatus.EXPIRED` | Request has expired |617| `deferred_pb2.DeferredStatus.FAILED` | Video generation failed |618619## Error Handling620621When using the SDK's `generate()` or `extend()` methods, video generation failures are raised as a `VideoGenerationError` exception. This exception includes a `code` and `message` describing what went wrong. Import it from `xai_sdk.video`:622623```python customLanguage="pythonXAI"624import os625import xai_sdk626from xai_sdk.video import VideoGenerationError627628client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))629630try:631    response = client.video.generate(632        prompt="A cat lounging in a sunbeam, tail gently swishing",633        model="grok-imagine-video-1.5",634        duration=5,635    )636    print(response.url)637except VideoGenerationError as e:638    print(f"Error code: {e.code}")639    print(f"Error message: {e.message}")640```641642The `VideoGenerationError` exception has the following attributes:643644| Attribute | Type | Description |645|-----------|------|-------------|646| `code` | `str` | An error code identifying the failure reason |647| `message` | `str` | A human-readable message describing the failure |648649When polling manually, a failed generation returns `status: "failed"` with an `error` object:650651```json652{653  "status": "failed",654  "error": {655    "code": "invalid_argument",656    "message": "Prompt cannot be empty. Please provide a prompt."657  }658}659```660661The possible `error.code` values are:662663| Code | Meaning | What to do |664|------|---------|------------|665| `invalid_argument` | The request input is invalid, such as an unsupported duration, an invalid image or video input, a prompt that is too long, conflicting request modes, or content blocked by moderation. | Fix the request parameters or input media, then submit a new request. |666| `permission_denied` | The API key or team does not have permission for the requested video operation. | Confirm the API key belongs to the right team and that the team has access to the requested capability. |667| `failed_precondition` | The requested operation is not available for the selected model or settings, such as video editing, video extension, or a requested resolution that the model cannot process. | Change the model, mode, resolution, or other request settings. |668| `service_unavailable` | Video generation is temporarily overloaded. | Retry the request later. |669| `internal_error` | The service could not complete the generation because of an internal failure. | Retry the request. If the error persists, contact xAI support with the `request_id`. |670671Authentication errors, missing models, and rate limits are returned synchronously as standard API errors before a video job is created, so they do not appear in the `error.code` field of a failed video result.672673You can combine this with `TimeoutError` handling for comprehensive error coverage:674675```python customLanguage="pythonXAI"676import os677import xai_sdk678from xai_sdk.video import VideoGenerationError679680client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))681682try:683    response = client.video.generate(684        prompt="A cat lounging in a sunbeam, tail gently swishing",685        model="grok-imagine-video-1.5",686        duration=5,687    )688    print(response.url)689except VideoGenerationError as e:690    print(f"Generation failed [{e.code}]: {e.message}")691except TimeoutError:692    print("Generation timed out — try increasing the timeout or simplifying the prompt")693```694695## Response Details696697The SDK response includes the generated video and provider-specific metadata. In the AI SDK, the xAI-hosted output URL is available at `providerMetadata.xai.videoUrl`.698699```python customLanguage="pythonXAI"700if response.respect_moderation:701    print(response.url)702else:703    print("Video filtered by moderation")704705print(f"Duration: {response.duration} seconds")706print(f"Model: {response.model}")707```708709```javascript customLanguage="javascriptAISDK"710const result = await generateVideo({711    model: xai.video("grok-imagine-video-1.5"),712    prompt: "A futuristic city skyline at dusk",713    duration: 5,714});715716console.log(result.providerMetadata?.xai?.videoUrl);717```718719## Concurrent Requests720721When you need to generate multiple videos, run requests concurrently. This is especially useful for comparing prompts or creating multiple variations.722723```python customLanguage="pythonXAI"724import os725import asyncio726import xai_sdk727728async def generate_concurrently():729    client = xai_sdk.AsyncClient(api_key=os.getenv("XAI_API_KEY"))730731    prompts = [732        "A cat sitting on a sunlit windowsill, tail gently swishing.",733        "A dog sprinting through a field of tall grass at golden hour.",734        "A hummingbird hovering near a red flower in slow motion.",735    ]736737    tasks = [738        client.video.generate(739            prompt=prompt,740            model="grok-imagine-video-1.5",741            duration=5,742        )743        for prompt in prompts744    ]745746    results = await asyncio.gather(*tasks)747748    for prompt, result in zip(prompts, results):749        print(f"{prompt}: {result.url}")750751asyncio.run(generate_concurrently())752```753754## Related755756* [Models](/developers/models) — Available video models and pricing757* [Image-to-Video](/developers/model-capabilities/video/image-to-video) — Animate a still image758* [Reference-to-Video](/developers/model-capabilities/video/reference-to-video) — Guide a video with reference images, or pin the first & last frame759* [Video Editing](/developers/model-capabilities/video/editing) — Edit existing videos760* [Video Extension](/developers/model-capabilities/video/extension) — Extend existing videos761* [Image Generation](/developers/model-capabilities/images/generation) — Generate still images from text762* [API Reference](/developers/rest-api-reference) — Full endpoint documentation763* [Imagine API Landing Page](https://x.ai/api/imagine) — Showcase of the Imagine API in action764
Files main
Menu

Theme