> ## 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 影片概覽 · 分組介紹](/zh-Hant/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]
>
> 模型價格與官網對齊，且可能隨官網調整；上表僅供參考，具體以頂部導航「模型價格」欄目為準：[模型價格](/zh-Hant/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 影片概覽](/zh-Hant/api-capabilities/grok-imagine-video/overview) - 定價、分組申請、引數詳解、常見問題
* [Grok Imagine 官轉生圖](/zh-Hant/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.