模型能力

视频生成

查看 Markdown

使用 Grok 视频模型根据文本提示词生成视频。API 支持配置时长、宽高比和分辨率,SDK 会自动处理异步轮询。在 grok-imagine-video-1.5 上,文本转视频支持原生 1080p。


快速开始

通过一次 API 调用生成视频:

import os
import xai_sdk

client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))

response = client.video.generate(
    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",
    model="grok-imagine-video-1.5",
    duration=10,
    aspect_ratio="16:9",
    resolution="720p",
)

print(response.url)

视频生成是一个异步过程,通常最多需要几分钟才能完成。具体耗时取决于:

  • 提示词复杂度:场景越详细,需要的处理越多

  • 时长 — 视频越长,生成时间越长

  • 分辨率:分辨率越高(1080p 相比 480p),处理时间越长

  • 视频编辑:与图像转视频或文本转视频相比,编辑现有视频会增加额外开销


视频工作流

请根据希望创建的视频输出类型选择对应页面:


工作原理

视频生成在底层分为两个步骤:

  1. 启动 — 提交生成请求并接收 request_id

  2. 轮询 — 使用 request_id 反复检查状态,直到视频就绪

xAI SDK 的 generate()extend() 方法完全封装了这一过程;它们会提交请求、轮询结果并返回已完成的视频响应。你无需管理请求 ID 或实现轮询逻辑。对于长时间运行的生成任务,你可以 自定义轮询行为,设置超时和间隔参数;也可以 手动处理轮询,从而完全控制生成生命周期。

REST API 用户必须手动实现这一两步流程:

第 1 步:启动生成请求

Bash

curl -X POST https://api.x.ai/v1/videos/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-imagine-video-1.5",
    "prompt": "A glowing crystal-powered rocket launching from Mars"
  }'

响应:

JSON

{"request_id": "d97415a1-5796-b7ec-379f-4e6819e08fdf"}

第 2 步:轮询结果

使用 request_id 检查状态。每隔几秒继续轮询,直到视频就绪:

Bash

curl -X GET "https://api.x.ai/v1/videos/{request_id}" \
  -H "Authorization: Bearer $XAI_API_KEY"

响应包含一个 status 字段,其值为以下之一:

状态说明
pending视频仍在生成
done视频已就绪
expired请求已过期
failed视频生成失败

响应(完成时):

JSON

{
  "status": "done",
  "video": {
    "url": "https://vidgen.x.ai/.../video.mp4",
    "duration": 8,
    "respect_moderation": true
  },
  "model": "grok-imagine-video-1.5"
}

视频以临时 URL 形式返回。需要时可以直接访问 xAI 托管的 URL;如果需要保留副本,请及时下载或处理。


配置

视频生成 API 允许你控制生成视频的输出格式。你可以指定时长、宽高比、分辨率,以及(在参考图转视频中)预设语音,以满足具体用例。

时长

使用 duration 参数控制视频长度。允许范围为 1–15 秒。

视频编辑不支持自定义 duration。编辑后的视频会保留原视频时长,上限为 8.7 秒。

宽高比

比例用例
1:1社交媒体、缩略图
16:9 / 9:16宽屏、移动端、故事(默认:16:9
4:3 / 3:4演示文稿、人像
3:2 / 2:3摄影

对于图像转视频生成,输出默认采用输入图像的宽高比。如果指定 aspect_ratio 参数,则会覆盖默认值,并将图像拉伸到所需的宽高比。

视频编辑不支持自定义 aspect_ratio:输出会匹配输入视频的宽高比。

分辨率

分辨率说明
1080p全高清画质
720p高清画质
480p标准清晰度,处理更快(默认)

注意: 1080pgrok-imagine-video-1.5 上支持文本转视频和图像转视频。参考图转视频最高为 720p。

视频编辑不支持自定义 resolution。输出分辨率会匹配输入视频的分辨率,最高为 720p(例如,1080p 输入会缩小到 720p)。

音频

对于 grok-imagine-video-1.5参考图转视频 可以通过 reference_audios 携带语音。语音来自内置列表,并通过 voice_id 命名;使用自有音频文件的语音参考可按申请向受信任合作伙伴提供申请

属性说明
来源一个预设 voice_id(例如 {"voice_id": "eve"}),来自与 Text to Speech 相同的列表。标识符不区分大小写
限制每次请求最多 3 个语音
提示词按索引引用语音:<AUDIO_0><AUDIO_1><AUDIO_2>

生成的视频默认包含音轨。传入 generate_audio=False 可请求无声视频:

import os
import xai_sdk

client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))

response = client.video.generate(
    prompt="A paper boat drifting down a rain-soaked street",
    model="grok-imagine-video-1.5",
    generate_audio=False,
)

print(response.url)

示例

import os
import xai_sdk

client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))

response = client.video.generate(
    prompt="Timelapse of a flower blooming in a sunlit garden",
    model="grok-imagine-video-1.5",
    duration=10,
    aspect_ratio="16:9",
    resolution="720p",
)

print(f"Video URL: {response.url}")
print(f"Duration: {response.duration}s")

请求模式

视频生成端点支持多种模式,具体由设置的字段决定。编辑和扩展使用专用端点;生成模式共用 /v1/videos/generations

模式REST API 字段AI SDK 结构说明
文本转视频promptprompt: "..."仅根据文本 prompt 生成视频。
图像转视频prompt + imageprompt: { image, text }使用提供的图像作为起始帧生成视频。
参考图转视频prompt + reference_imagesreference_audiosprompt: "..." + providerOptions.xai.{ mode: "reference-to-video", referenceImageUrls }根据参考图像和/或预设语音引导视频生成,使用模型 grok-imagine-video-1.5
首帧与尾帧last_frame,可同时提供 image 和/或 promptREST 请求体中的 last_frame(AI SDK 暂无专用字段)对于 grok-imagine-video-1.5,可固定精确的尾帧。添加 image 还可固定首帧,并在两者之间插值。只要固定了帧,prompt 就是可选的。支持组合使用 reference_images / reference_audios
关键帧keyframes(最多 4 个 {image, timestamp_s} 条目),可选择配合 imagelast_frame 和/或 promptREST 请求体中的 keyframes(AI SDK 暂无专用字段)对于 grok-imagine-video-1.5,在片段内部的精确时间点固定图像,时间点按 1/3 秒网格对齐。可结合 image / last_frame 固定首尾帧,并结合 reference_images / reference_audios 提供引导。
Edit-video/v1/videos/edits + videoprompt: "..." + providerOptions.xai.{ mode: "edit-video", videoUrl }根据 prompt 修改现有视频。
Extend-video/v1/videos/extensions + videoprompt: "..." + providerOptions.xai.{ mode: "extend-video", videoUrl }从现有视频的最后一帧进行扩展。

对于 grok-imagine-video-1.5image 配合 reference_imagesreference_audioslast_framekeyframes 时,属于固定首帧的参考图生视频。视频以该图像开场,而非将其作为风格参考。仅提供 last_framekeyframes(不提供 image,也没有参考输入)也是有效的:模型会围绕固定帧生成片段的其余部分。prompt 在包含 imagereference_imageslast_framekeyframes 的请求中均为可选参数;只有文生视频必须提供。经典版 grok-imagine-video 仍会拒绝 last_framekeyframes,也不允许将 image 与参考输入组合使用。

不要混用 AI SDK 的 mode 值。每次请求只能选择 "edit-video""extend-video""reference-to-video" 中的一项。省略 mode 时,AI SDK 会使用标准生成模式。

请参阅 首帧与尾帧,查看 last_frame中的示例,以及关键帧中的片段内部固定帧用法。


自定义轮询行为

使用 SDK 的 generate()extend() 方法时,可以控制等待时长和结果检查频率:

Python SDKAI SDK(providerOptions.xai说明默认值
timeoutpollTimeoutMs等待视频完成的最长时间10 分钟
intervalpollIntervalMs状态检查间隔100 毫秒
import os
from datetime import timedelta
import xai_sdk

client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))

response = client.video.generate(
    prompt="Epic cinematic drone shot flying through mountain peaks",
    model="grok-imagine-video-1.5",
    duration=15,
    timeout=timedelta(minutes=15),  # Wait up to 15 minutes
    interval=timedelta(seconds=5),  # Check every 5 seconds
)

print(response.url)

如果视频在超时时限内仍未就绪,Python SDK 会抛出 TimeoutError,AI SDK 则会通过其 AbortSignal 中止。如需更精细的控制,请使用手动轮询方式;Python SDK 提供 start()get() 方法,AI SDK 则支持自定义 abortSignal 来取消操作。


手动处理轮询

如需精细控制生成生命周期,请分别使用 start()extend_start() 发起生成/扩展请求,并使用 get() 检查状态。

get() 方法会返回包含 status 字段的响应。请从 SDK 导入状态枚举:

import os
import time
import xai_sdk
from xai_sdk.proto import deferred_pb2

client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))

# Start the generation request
start_response = client.video.start(
    prompt="A cat lounging in a sunbeam, tail gently swishing",
    model="grok-imagine-video-1.5",
    duration=5,
)

print(f"Request ID: {start_response.request_id}")

# Poll for results
while True:
    result = client.video.get(start_response.request_id)
    
    if result.status == deferred_pb2.DeferredStatus.DONE:
        print(f"Video URL: {result.response.video.url}")
        break
    elif result.status == deferred_pb2.DeferredStatus.EXPIRED:
        print("Request expired")
        break
    elif result.status == deferred_pb2.DeferredStatus.FAILED:
        print("Video generation failed")
        break
    elif result.status == deferred_pb2.DeferredStatus.PENDING:
        print("Still processing...")
        time.sleep(5)

可用的状态值如下:

Proto 值说明
deferred_pb2.DeferredStatus.PENDING视频仍在生成
deferred_pb2.DeferredStatus.DONE视频已就绪
deferred_pb2.DeferredStatus.EXPIRED请求已过期
deferred_pb2.DeferredStatus.FAILED视频生成失败

错误处理

使用 SDK 的 generate()extend() 方法时,视频生成失败会以 VideoGenerationError 异常形式抛出。该异常包含 codemessage,用于说明错误原因。请从 xai_sdk.video

Python

import os
import xai_sdk
from xai_sdk.video import VideoGenerationError

client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))

try:
    response = client.video.generate(
        prompt="A cat lounging in a sunbeam, tail gently swishing",
        model="grok-imagine-video-1.5",
        duration=5,
    )
    print(response.url)
except VideoGenerationError as e:
    print(f"Error code: {e.code}")
    print(f"Error message: {e.message}")

VideoGenerationError 异常具有以下属性:

属性类型说明
codestr用于标识失败原因的错误代码
messagestr描述失败原因的可读消息

手动轮询时,生成失败会返回 status: "failed",其中包含 error 对象:

JSON

{
  "status": "failed",
  "error": {
    "code": "invalid_argument",
    "message": "Prompt cannot be empty. Please provide a prompt."
  }
}

可能的 error.code 值如下:

代码含义处理方式
invalid_argument请求输入无效,例如不支持的时长、无效的图像或视频输入、过长的 prompt、冲突的请求模式,或内容被审核拦截。修正请求参数或输入媒体,然后提交新请求。
permission_deniedAPI key 或团队没有执行所请求视频操作的权限。确认 API key 属于正确的团队,并且该团队有权访问所请求的能力。
failed_precondition所选模型或设置不支持请求的操作,例如视频编辑、视频扩展,或模型无法处理所请求的分辨率。更改模型、模式、分辨率或其他请求设置。
service_unavailable视频生成服务暂时过载。稍后重试请求。
internal_error服务因内部故障无法完成生成。重试请求。如果错误仍然存在,请携带 request_id

身份验证错误、模型不存在和速率限制会在创建视频任务之前作为标准 API 错误同步返回,因此不会出现在失败视频结果的 error.code 字段中。

你可以将其与 TimeoutError 处理结合使用,以全面覆盖错误:

Python

import os
import xai_sdk
from xai_sdk.video import VideoGenerationError

client = xai_sdk.Client(api_key=os.getenv("XAI_API_KEY"))

try:
    response = client.video.generate(
        prompt="A cat lounging in a sunbeam, tail gently swishing",
        model="grok-imagine-video-1.5",
        duration=5,
    )
    print(response.url)
except VideoGenerationError as e:
    print(f"Generation failed [{e.code}]: {e.message}")
except TimeoutError:
    print("Generation timed out — try increasing the timeout or simplifying the prompt")

响应详情

SDK 响应包含生成的视频和提供商特有的元数据。在 AI SDK 中,xAI 托管的输出 URL 位于 providerMetadata.xai.videoUrl

if response.respect_moderation:
    print(response.url)
else:
    print("Video filtered by moderation")

print(f"Duration: {response.duration} seconds")
print(f"Model: {response.model}")

并发请求

需要生成多个视频时,请并发运行请求。这对于比较 prompt 或创建多个变体尤其有用。

Python

import os
import asyncio
import xai_sdk

async def generate_concurrently():
    client = xai_sdk.AsyncClient(api_key=os.getenv("XAI_API_KEY"))

    prompts = [
        "A cat sitting on a sunlit windowsill, tail gently swishing.",
        "A dog sprinting through a field of tall grass at golden hour.",
        "A hummingbird hovering near a red flower in slow motion.",
    ]

    tasks = [
        client.video.generate(
            prompt=prompt,
            model="grok-imagine-video-1.5",
            duration=5,
        )
        for prompt in prompts
    ]

    results = await asyncio.gather(*tasks)

    for prompt, result in zip(prompts, results):
        print(f"{prompt}: {result.url}")

asyncio.run(generate_concurrently())


最后更新:2026 年 9 月 21 日