> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apiyi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Grok Imagine 视频生成 API 参考

> Grok Imagine 视频生成 API 参考与在线调试 — 文生视频 / 图生视频，异步任务三步流程，1–15 秒，480p / 720p / 1080p，与官网同价按秒计费

> [!WARNING]
>
> **🔒 需申请开通 `GrokOfficial` 分组**：Grok Imagine 视频不在 `Default` 默认分组，需申请开通后才能调用（含本页 Playground）。未开通、或令牌计费模式为「按次计费」时，调用固定返回 `503`。申请流程见 [Grok Imagine 视频概览 · 分组介绍](/api-capabilities/grok-imagine-video/overview#分组介绍)。

> [!NOTE]
>
> 右侧的交互式 Playground 支持直接在线调试。请在 **Authorization** 中填入你的 API Key（格式：`Bearer sk-xxx`），选择 `model`、填写 `prompt` / `seconds` / `size` 后发送；需要图生视频时再填 `input_reference`。**Playground 只完成第 1 步提交**，拿到任务 `id` 后按下方流程轮询与下载。

> [!WARNING]
>
> **⚠️ 三处最容易踩的坑**
>
> 1. **不传 `size` / `seconds` 默认 480p、8 秒**，并按此计费。
> 2. **`grok-imagine-video` 不支持 1080p**，传 `1920x1080` 返回 400；1080p 请用 `-1.5` 或 `-1.5-lite`。
> 3. **审核拦截照常计费**：被拦截的任务状态仍是 `completed`，但带 `error.code: "moderation_blocked"` 且没有成片。

> [!WARNING]
>
> **三步异步流程，本页只覆盖第一步（提交）**
>
> * **第 1 步（本页）**：`POST /v1/videos` → 返回任务 `id` + `status: "queued"`
> * **第 2 步**：`GET /v1/videos/{id}` 轮询，直到 `status: "completed"` 或 `"failed"`
> * **第 3 步**：`GET /v1/videos/{id}/content` 下载 MP4
>
> 提交本身秒级返回，**不会**等到视频生成完成。

## 代码示例

### Python（文生视频，完整三步）

```python theme={null}
import os, time, requests

BASE = "https://api.apiyi.com/v1"
H = {"Authorization": f"Bearer {os.environ['APIYI_API_KEY']}"}

# 第 1 步：提交
task = requests.post(f"{BASE}/videos", headers=H, json={
    "model": "grok-imagine-video-1.5",
    "prompt": "黄昏海边的灯塔，镜头缓慢推进，海浪轻拍礁石，海鸟叫声，电影级光影",
    "seconds": "5",
    "size": "1280x720",      # 720p 横屏；不传默认 480p
}, timeout=60).json()
vid = task["id"]

# 第 2 步：轮询
for _ in range(75):           # 最多约 10 分钟
    time.sleep(8)
    job = requests.get(f"{BASE}/videos/{vid}", headers=H, timeout=60).json()
    if job["status"] in ("completed", "failed"):
        break

if job["status"] != "completed" or job.get("error"):
    # moderation_blocked：被审核拦截，无成片但已计费
    raise RuntimeError(job.get("error"))

# 第 3 步：下载并立即转存
mp4 = requests.get(f"{BASE}/videos/{vid}/content", headers=H, timeout=300)
open("out.mp4", "wb").write(mp4.content)
```

### Python（图生视频，base64 输入图）

```python theme={null}
import base64, os, requests

H = {"Authorization": f"Bearer {os.environ['APIYI_API_KEY']}"}
img = base64.b64encode(open("first-frame.jpg", "rb").read()).decode()

task = requests.post("https://api.apiyi.com/v1/videos", headers=H, json={
    "model": "grok-imagine-video",
    "prompt": "the cat slowly turns its head and blinks",
    "seconds": "3",
    "input_reference": f"data:image/jpeg;base64,{img}",   # 也可直接传公网图片 URL
}, timeout=60).json()
print(task["id"])  # 之后同样轮询 + 下载；输出画幅跟随输入图
```

### cURL

```bash theme={null}
# 第 1 步：提交文生视频（1.5-lite，2 秒 480p）
curl -X POST "https://api.apiyi.com/v1/videos" \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-video-1.5-lite",
    "prompt": "a red paper boat drifting on a calm lake, gentle ripples",
    "seconds": "2",
    "size": "854x480"
  }'

# 图生视频也可以用 multipart 上传本地文件
curl -X POST "https://api.apiyi.com/v1/videos" \
  -H "Authorization: Bearer sk-your-api-key" \
  -F "model=grok-imagine-video" \
  -F "prompt=the cat slowly turns its head" \
  -F "seconds=2" \
  -F "input_reference=@first-frame.jpg"

# 第 2 步：查询状态
curl "https://api.apiyi.com/v1/videos/task_xxxxxxxx" \
  -H "Authorization: Bearer sk-your-api-key"

# 第 3 步：下载成片
curl -o out.mp4 "https://api.apiyi.com/v1/videos/task_xxxxxxxx/content" \
  -H "Authorization: Bearer sk-your-api-key"
```

### Node.js（原生 fetch）

```javascript theme={null}
import fs from 'node:fs';

const BASE = 'https://api.apiyi.com/v1';
const H = { 'Authorization': `Bearer ${process.env.APIYI_API_KEY}`, 'Content-Type': 'application/json' };

const task = await fetch(`${BASE}/videos`, {
    method: 'POST',
    headers: H,
    body: JSON.stringify({
        model: 'grok-imagine-video-1.5-lite',
        prompt: 'A serene Japanese garden with cherry blossoms drifting, koi pond, golden hour',
        seconds: '4',
        size: '720x1280'          // 720p 竖屏
    })
}).then(r => r.json());

let job;
for (let i = 0; i < 75; i++) {
    await new Promise(r => setTimeout(r, 8000));
    job = await fetch(`${BASE}/videos/${task.id}`, { headers: H }).then(r => r.json());
    if (['completed', 'failed'].includes(job.status)) break;
}
if (job.status !== 'completed' || job.error) throw new Error(JSON.stringify(job.error));

const mp4 = await fetch(`${BASE}/videos/${task.id}/content`, { headers: H });
fs.writeFileSync('out.mp4', Buffer.from(await mp4.arrayBuffer()));
```

## 参数说明速查

| 参数名 | 类型 | 必填 | 默认 | 说明 |
| - | - | - | - | - |
| `model` | string | ✅ | — | `grok-imagine-video` / `grok-imagine-video-1.5` / `grok-imagine-video-1.5-lite` |
| `prompt` | string | 文生必填 | — | 场景、主体、动作、镜头、光影；图生视频用来描述动作 |
| `seconds` | string / integer | ❌ | `8` | 1–15 秒，超出返回 400 |
| `size` | string | ❌ | 480p | `宽x高` 像素写法，短边定分辨率、宽高比取最近一档；也可传 `480p` / `720p` / `1080p` |
| `resolution` / `aspect_ratio` | string | ❌ | — | xAI 原生写法，与 `size` 同时传时以它们为准 |
| `input_reference` | string / file | ❌ | — | 图生视频输入图：公网 URL、Data URI，或 multipart 文件 |

**每秒单价**（与 xAI 官网一致）：

| 模型 | 480p | 720p | 1080p | 输入图 |
| - | - | - | - | - |
| `grok-imagine-video` | \$0.05 | \$0.07 | 不支持 | \$0.002 / 张 |
| `grok-imagine-video-1.5` | \$0.08 | \$0.14 | \$0.25 | \$0.01 / 张 |
| `grok-imagine-video-1.5-lite` | \$0.02 | \$0.03 | \$0.14 | \$0.01 / 张 |

> [!NOTE]
>
> 模型价格与官网对齐，且可能随官网调整；上表仅供参考，具体以顶部导航「模型价格」栏目为准：[模型价格](/models/index)。

## 响应示例

**提交（第 1 步）**：

```json theme={null}
{
  "id": "task_xxxxxxxxxxxxxxxx",
  "object": "video",
  "model": "grok-imagine-video-1.5-lite",
  "status": "queued",
  "progress": 0,
  "created_at": 1792320668
}
```

**完成（第 2 步轮询结果）**：

```json theme={null}
{
  "id": "task_xxxxxxxxxxxxxxxx",
  "object": "video",
  "model": "grok-imagine-video-1.5-lite",
  "status": "completed",
  "progress": 100,
  "seconds": "2",
  "created_at": 1792320668,
  "completed_at": 1792320715
}
```

**被审核拦截**：`status` 仍为 `completed`，但多一个 `error` 字段、没有可下载的成片：

```json theme={null}
{
  "id": "task_xxxxxxxxxxxxxxxx",
  "status": "completed",
  "error": { "code": "moderation_blocked", "message": "..." }
}
```

## 相关文档

* [Grok Imagine 视频概览](/api-capabilities/grok-imagine-video/overview) - 定价、分组申请、参数详解、常见问题
* [Grok Imagine 官转生图](/api-capabilities/grok-imagine-image-official/overview) - 同一分组的图片生成


## OpenAPI

````yaml api-reference/grok-imagine-video-openapi.yaml POST /v1/videos
openapi: 3.1.0
info:
  title: Grok Imagine 视频生成 API
  description: >
    xAI Grok Imagine 视频生成官方通道（官转）— OpenAI Videos 兼容的异步任务接口，支持文生视频与图生视频，与 xAI
    官网同价按秒计费。


    - 三个模型：`grok-imagine-video`（480p \$0.05/秒、720p
    \$0.07/秒）、`grok-imagine-video-1.5`（\$0.08 / \$0.14 / \$0.25
    每秒）、`grok-imagine-video-1.5-lite`（\$0.02 / \$0.03 / \$0.14 每秒）

    - `seconds` 1–15，**默认 8**；不传 `size` **默认 480p**

    - 图生视频：加 `input_reference`（图片 URL 或 base64 Data URI），每张输入图另收 \$0.002（video）/
    \$0.01（1.5 / lite）

    - **异步任务式端点**：本端点只提交任务，需配合 `GET /v1/videos/{id}` 轮询和 `GET
    /v1/videos/{id}/content` 下载

    - 被内容审核拦截的任务仍为 `completed`，带 `error.code: moderation_blocked`，无成片且照常计费


    **认证方式**：在请求头中添加 `Authorization: Bearer YOUR_API_KEY`


    **API Key 配置**：令牌分组需包含 **`GrokOfficial`**（需申请开通），计费模式选 **按量优先** 或
    **按量计费**；未开通或按次计费令牌会返回 503


    **获取 API Key**：访问 [API易控制台](https://api.apiyi.com/token) 创建令牌
  version: 1.0.0
servers:
  - url: https://api.apiyi.com
    description: 主要端点
security:
  - bearerAuth: []
paths:
  /v1/videos:
    post:
      tags:
        - 视频生成
      summary: 提交视频生成任务（文生视频 / 图生视频）
      description: >
        提交一个 Grok Imagine 视频生成任务（异步），返回任务 `id` 和 `status: "queued"`。


        - 必填：`model`；文生视频还需 `prompt`

        - 可选：`seconds`（默认 8）、`size`（默认 480p）、`input_reference`（传了即为图生视频）

        - **响应不包含视频**，需轮询 `GET /v1/videos/{id}` 直到 `status: "completed"`，再调 `GET
        /v1/videos/{id}/content` 下载 MP4

        - 典型耗时：2 秒 480p 约 20–25 秒，图生视频约 35–50 秒，1.5 的 1080p 约 110 秒
      operationId: generateGrokImagineVideo
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GrokImagineVideoRequest'
            example:
              model: grok-imagine-video-1.5-lite
              prompt: >-
                a red paper boat drifting on a calm lake, gentle ripples, soft
                morning light
              seconds: '2'
              size: 854x480
      responses:
        '200':
          description: 任务已提交，返回任务 id 与 queued 状态
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GrokImagineVideoTask'
        '400':
          description: 参数非法（分辨率不被该模型支持、seconds 超出 1–15、prompt 缺失等），`message` 写明原因
        '401':
          description: 未授权 - API Key 无效
        '429':
          description: 请求频率超限或余额不足
        '503':
          description: 令牌未开通 `GrokOfficial` 分组，或令牌计费模式为按次计费
      security:
        - bearerAuth: []
components:
  schemas:
    GrokImagineVideoRequest:
      type: object
      required:
        - model
      properties:
        model:
          type: string
          description: >
            模型 ID（按秒 × 分辨率单价计费）：

            - `grok-imagine-video` —— 480p \$0.05/秒、720p \$0.07/秒，**不支持 1080p**

            - `grok-imagine-video-1.5` —— 480p \$0.08、720p \$0.14、1080p \$0.25
            每秒

            - `grok-imagine-video-1.5-lite` —— 480p \$0.02、720p \$0.03、1080p
            \$0.14 每秒
          enum:
            - grok-imagine-video
            - grok-imagine-video-1.5
            - grok-imagine-video-1.5-lite
          default: grok-imagine-video-1.5-lite
        prompt:
          type: string
          description: 提示词：场景 + 主体 + 动作 + 镜头 + 光影。文生视频必填；图生视频用来描述动作与镜头
          example: >-
            a red paper boat drifting on a calm lake, gentle ripples, soft
            morning light
        seconds:
          type: string
          description: |
            视频时长 1–15 秒，字符串或数字均可，**默认 8**。超出范围返回 400。费用与秒数成正比，测试建议 1–2 秒。
          example: '2'
        size:
          type: string
          description: >
            输出尺寸，`宽x高` 像素写法：按**短边**换算分辨率（≥1080 为 1080p、≥720 为 720p、其余
            480p），宽高比取最接近的一档。

            也可直接传 `480p` / `720p` / `1080p`。**不传时默认 480p。**


            - `854x480` —— 480p 横屏（实测 848×480）

            - `1280x720` / `720x1280` —— 720p 横 / 竖屏

            - `1920x1080` / `1080x1920` —— 1080p（仅 1.5 / 1.5-lite）
          enum:
            - 854x480
            - 480x854
            - 1280x720
            - 720x1280
            - 1920x1080
            - 1080x1920
          default: 854x480
        input_reference:
          type: string
          description: >
            图生视频的输入图：公网图片 URL，或 `data:image/jpeg;base64,...` 形式的 Data
            URI。传了即为图生视频，输出画幅跟随输入图。

            每张输入图另收 \$0.002（`grok-imagine-video`）或 \$0.01（1.5 / 1.5-lite）。
          example: https://example.com/first-frame.jpg
    GrokImagineVideoTask:
      type: object
      properties:
        id:
          type: string
          description: 任务 ID，用于轮询和下载
          example: task_xxxxxxxxxxxxxxxx
        object:
          type: string
          description: 固定 `video`
          example: video
        model:
          type: string
          example: grok-imagine-video-1.5-lite
        status:
          type: string
          description: >
            任务状态：

            - `queued` —— 已提交，排队中

            - `in_progress` —— 生成中

            - `completed` —— 完成，可通过 `/v1/videos/{id}/content` 下载；若带 `error.code:
            moderation_blocked` 则为审核拦截、无成片

            - `failed` —— 失败
          enum:
            - queued
            - in_progress
            - completed
            - failed
          example: queued
        progress:
          type: integer
          description: 进度 0–100，粗粒度，不建议做精确进度条
          example: 0
        seconds:
          type: string
          description: 成片时长，完成后返回
        created_at:
          type: integer
          description: 任务创建 Unix 时间戳（秒）
        completed_at:
          type: integer
          description: 任务完成 Unix 时间戳（秒），完成后返回
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: 在 API易控制台获取的 API Key（令牌分组需包含 GrokOfficial）

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.