> ## 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.

# 文生视频 API 参考

> Sora 2 文生视频 API 参考与在线调试 — JSON 请求体、异步任务三步流程、4/8/12 秒灵活时长。

<Info>
  右侧的交互式 Playground 支持直接在线调试。请在 **Authorization** 中填入你的 API Key（格式：`Bearer sk-xxx`），输入 prompt、选择 model / size / seconds 后一键发送即可。
</Info>

<Tip>
  **场景说明**：本页用于「纯文本提示词生成视频」——不传 `input_reference`、走 `application/json` 请求体。如需基于一张参考图生成视频（图生视频），请使用 [图生视频接口](/api-capabilities/sora-2/image-to-video)（同一端点 + `input_reference` 文件上传）。
</Tip>

<Warning>
  **⚠️ 三步异步流程，本页只覆盖第一步（提交）**

  * **第 1 步（本页）**：`POST /v1/videos` → 返回 `video_id` + `status: "queued"`
  * **第 2 步**：`GET /v1/videos/{video_id}` 轮询，直到 `status: "completed"`
  * **第 3 步**：`GET /v1/videos/{video_id}/content` 下载 MP4 文件

  POST 提交本身耗时秒级，**不会**等到视频生成完成。完整流程见下方 Python 代码示例。
</Warning>

## 代码示例

### Python（OpenAI SDK 直连）

```python theme={null}
from openai import OpenAI
import time

client = OpenAI(
    api_key="sk-your-api-key",
    base_url="https://api.apiyi.com/v1"
)

# 第 1 步：提交生成任务
video = client.videos.create(
    model="sora-2",
    prompt="A golden retriever running on the beach at sunset, cinematic, golden hour, slow motion",
    seconds="8",
    size="1280x720"
)
print(f"Video ID: {video.id}, status: {video.status}")

# 第 2 步：轮询状态
while True:
    video = client.videos.retrieve(video.id)
    print(f"Status: {video.status}, progress: {getattr(video, 'progress', 0)}%")
    if video.status == "completed":
        break
    if video.status == "failed":
        raise RuntimeError(f"Generation failed: {video}")
    time.sleep(15)

# 第 3 步：下载视频
content = client.videos.download_content(video.id)
content.write_to_file("output.mp4")
print("Saved: output.mp4")
```

### Python（原生 requests）

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

API_KEY = "sk-your-api-key"
BASE_URL = "https://api.apiyi.com/v1"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

# 第 1 步：提交（JSON 请求体）
resp = requests.post(
    f"{BASE_URL}/videos",
    headers={**HEADERS, "Content-Type": "application/json"},
    json={
        "model": "sora-2",
        "prompt": "A serene Japanese garden with cherry blossoms, koi pond, traditional bridge, golden hour, ultra detailed",
        "seconds": "8",
        "size": "1280x720"
    },
    timeout=30  # POST 提交本身只是入队，30 秒足够
).json()
video_id = resp["id"]
print(f"Video ID: {video_id}, status: {resp['status']}")

# 第 2 步：轮询（最长等 15 分钟）
deadline = time.time() + 900
while time.time() < deadline:
    status_resp = requests.get(f"{BASE_URL}/videos/{video_id}", headers=HEADERS).json()
    print(f"Status: {status_resp['status']}, progress: {status_resp.get('progress', 0)}%")
    if status_resp["status"] == "completed":
        break
    if status_resp["status"] == "failed":
        raise RuntimeError(f"Generation failed: {status_resp}")
    time.sleep(15)

# 第 3 步：下载
with requests.get(f"{BASE_URL}/videos/{video_id}/content", headers=HEADERS, stream=True) as r:
    r.raise_for_status()
    with open("output.mp4", "wb") as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)
print("Saved: output.mp4")
```

### cURL

```bash theme={null}
{/* 第 1 步：提交任务 */}
curl -X POST "https://api.apiyi.com/v1/videos" \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "sora-2",
    "prompt": "A futuristic cityscape at night with neon lights and flying vehicles, cyberpunk style, cinematic",
    "seconds": "8",
    "size": "1280x720"
  }'

{/* 第 2 步：轮询状态（替换 video_id）*/}
curl -X GET "https://api.apiyi.com/v1/videos/video_abc123" \
  -H "Authorization: Bearer sk-your-api-key"

{/* 第 3 步：下载视频文件 */}
curl -X GET "https://api.apiyi.com/v1/videos/video_abc123/content" \
  -H "Authorization: Bearer sk-your-api-key" \
  -o output.mp4
```

### Node.js（原生 fetch）

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

const API_KEY = 'sk-your-api-key';
const BASE_URL = 'https://api.apiyi.com/v1';

// 第 1 步：提交
const submitResp = await fetch(`${BASE_URL}/videos`, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
    },
    body: JSON.stringify({
        model: 'sora-2',
        prompt: 'Aerial drone shot over snowy mountain range at sunrise, cinematic, ultra wide',
        seconds: '8',
        size: '1280x720'
    })
});
const { id: videoId } = await submitResp.json();
console.log(`Video ID: ${videoId}`);

// 第 2 步：轮询
let status = 'queued';
while (status !== 'completed' && status !== 'failed') {
    await new Promise(r => setTimeout(r, 15000));
    const statusResp = await fetch(`${BASE_URL}/videos/${videoId}`, {
        headers: { 'Authorization': `Bearer ${API_KEY}` }
    });
    const data = await statusResp.json();
    status = data.status;
    console.log(`Status: ${status}, progress: ${data.progress ?? 0}%`);
}

if (status === 'failed') throw new Error('Generation failed');

// 第 3 步：下载
const contentResp = await fetch(`${BASE_URL}/videos/${videoId}/content`, {
    headers: { 'Authorization': `Bearer ${API_KEY}` }
});
const buffer = Buffer.from(await contentResp.arrayBuffer());
fs.writeFileSync('output.mp4', buffer);
console.log('Saved: output.mp4');
```

### 浏览器 JavaScript

```javascript theme={null}
{/* 仅作演示，生产请走后端代理避免 Key 泄露；视频文件较大也不适合直接在浏览器下载 */}
const submitResp = await fetch('https://api.apiyi.com/v1/videos', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer sk-your-api-key'
    },
    body: JSON.stringify({
        model: 'sora-2',
        prompt: 'Watercolor northern lights over snowy mountains, gentle motion',
        seconds: '4',
        size: '720x1280'
    })
});
const { id } = await submitResp.json();
console.log('Video ID:', id);

{/* 轮询状态后，把视频 URL 交给后端代理下载，再回流给前端展示 */}
```

## 参数说明速查

| 参数        | 类型     | 必填 | 默认         | 说明                                                                   |
| --------- | ------ | -- | ---------- | -------------------------------------------------------------------- |
| `model`   | string | 是  | —          | `sora-2`（720p 标准）或 `sora-2-pro`（720p / 1024p / 1080p 多档）             |
| `prompt`  | string | 是  | —          | 视频描述提示词，建议详细描述场景、镜头运动、风格、光线                                          |
| `seconds` | string | 否  | `"4"`      | 视频时长，**字符串枚举**：`"4"` / `"8"` / `"12"`（**不是数字**）                      |
| `size`    | string | 否  | `720x1280` | 输出分辨率，需匹配模型支持档位（见 [概览页技术规格](/api-capabilities/sora-2/overview#技术规格)） |

<Tip>
  详细的参数约束、可选值、示例请查看右侧 Playground 中的字段说明，所有 enum 字段均支持下拉选择。**图生视频相关参数（`input_reference` 文件上传）见 [图生视频接口](/api-capabilities/sora-2/image-to-video)**。
</Tip>

## 响应格式

### 第 1 步 - 提交后立即返回

```json theme={null}
{
  "id": "video_abc123def456",
  "object": "video",
  "model": "sora-2",
  "status": "queued",
  "progress": 0,
  "created_at": 1712697600,
  "size": "1280x720",
  "seconds": "8",
  "quality": "standard"
}
```

### 第 2 步 - 轮询返回（生成中）

```json theme={null}
{
  "id": "video_abc123def456",
  "object": "video",
  "model": "sora-2",
  "status": "in_progress",
  "progress": 45,
  "created_at": 1712697600,
  "size": "1280x720",
  "seconds": "8"
}
```

### 第 2 步 - 轮询返回（完成）

```json theme={null}
{
  "id": "video_abc123def456",
  "object": "video",
  "model": "sora-2",
  "status": "completed",
  "progress": 100,
  "created_at": 1712697600,
  "completed_at": 1712697900,
  "size": "1280x720",
  "seconds": "8"
}
```

<Warning>
  **⚠️ 响应字段陷阱**

  * **没有直接的 `video_url` 字段** —— 视频文件需要通过 `GET /v1/videos/{id}/content` 端点单独下载（返回 `video/mp4` 二进制流），**不要**期待响应里直接出现一个 CDN 链接
  * `progress` 字段在不同生成阶段会跳变（如 0 → 45 → 80 → 100），不是严格线性的
  * `status: "failed"` 时不一定带详细 `error` 字段，多见于内容审核或服务过载，**直接重试或调整 prompt** 即可
  * 视频内容在 OpenAI 上**只保留 1 天**，过期后 `/content` 返回 404
</Warning>

<Info>
  本端点是异步任务式入口，**计费在生成完成时按 `seconds` 单价结算**（见 [概览页定价表](/api-capabilities/sora-2/overview#模型定价)）。POST 提交、轮询查询、视频下载本身**不计费**，失败任务也**不计费**。
</Info>


## OpenAPI

````yaml api-reference/sora-2-text-to-video-openapi.yaml POST /v1/videos
openapi: 3.1.0
info:
  title: Sora 2 文生视频 API
  description: >
    OpenAI Sora 2 / Sora 2 Pro 系列视频生成模型 — 文生视频接口（不传 `input_reference`，走
    `application/json`）。


    - 两个活跃模型：`sora-2`（720p，\$0.10/秒）与 `sora-2-pro`（720p / 1024p / 1080p 三档）

    - 时长支持 `"4"` / `"8"` / `"12"` 秒（**字符串枚举**）

    - 同步音轨视频输出（含环境音、对话、配乐）

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

    - 视频在 OpenAI 服务器仅保留 1 天，请生成完成后立即下载落地

    - 如需基于参考图生成视频，请使用 [图生视频接口](/api-capabilities/sora-2/image-to-video)（同端点 +
    multipart 上传 `input_reference`）


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


    **API Key 配置**：必须在 API易控制台把分组切到 **Sora2官转**、计费模式切到 **按量计费**，否则返回 403


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


        - 必填：`model`、`prompt`

        - 可选：`seconds`（默认 `"4"`）、`size`（默认 `"720x1280"`）

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

        - 典型生成耗时：sora-2 4 秒 ≈ 3 分钟；sora-2-pro 12 秒 1080p ≈ 8–10 分钟

        - 若使用参考图生成（图生视频），请改用 [图生视频接口](/api-capabilities/sora-2/image-to-video)
      operationId: generateSora2TextToVideo
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Sora2TextToVideoRequest'
            example:
              model: sora-2
              prompt: >-
                A golden retriever running on the beach at sunset, cinematic,
                golden hour, slow motion
              seconds: '8'
              size: 1280x720
      responses:
        '200':
          description: 任务已提交，返回 video_id 与 queued 状态
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Sora2VideoTask'
        '400':
          description: 参数非法（seconds 不在 4/8/12、size 不支持当前模型、prompt 缺失等）
        '401':
          description: 未授权 - API Key 无效
        '403':
          description: 内容审核拦截 / 计费模式不是按量计费 / 分组未选 Sora2官转
        '429':
          description: 请求频率超限或余额不足
        '500':
          description: 上游 OpenAI 网关错误，建议重试 1–2 次
      security:
        - bearerAuth: []
components:
  schemas:
    Sora2TextToVideoRequest:
      type: object
      required:
        - model
        - prompt
      properties:
        model:
          type: string
          description: 模型 ID。`sora-2` 仅支持 720p；`sora-2-pro` 支持 720p / 1024p / 1080p 三档分辨率
          enum:
            - sora-2
            - sora-2-pro
          default: sora-2
        prompt:
          type: string
          description: 视频生成提示词，建议详细描述场景、镜头运动、风格、光线、人物动作
          example: >-
            A serene Japanese garden with cherry blossoms, koi pond, traditional
            bridge, golden hour, ultra detailed
        seconds:
          type: string
          description: |
            视频时长，**字符串枚举**（不是数字）：
            - `"4"` —— 4 秒（默认），适合短演示、单镜头、快速试错
            - `"8"` —— 8 秒，标准短视频，最常用
            - `"12"` —— 12 秒，长镜头、连续动作

            传 `"10"` / `"15"` 或数字 `4` 会返回 400
          enum:
            - '4'
            - '8'
            - '12'
          default: '4'
        size:
          type: string
          description: |
            输出分辨率，**`sora-2` 与 `sora-2-pro` 支持档位不同**：

            - `sora-2`（仅 720p）：`720x1280`（竖屏，默认）/ `1280x720`（横屏）
            - `sora-2-pro` 额外支持：
              - `1024x1792` / `1792x1024`（1024p，\$0.50/秒）
              - `1080x1920` / `1920x1080`（1080p，\$0.70/秒）

            给 `sora-2` 传 1024p / 1080p 会返回 400
          enum:
            - 720x1280
            - 1280x720
            - 1024x1792
            - 1792x1024
            - 1080x1920
            - 1920x1080
          default: 720x1280
    Sora2VideoTask:
      type: object
      properties:
        id:
          type: string
          description: 任务 ID，用于后续轮询和下载
          example: video_abc123def456
        object:
          type: string
          description: 对象类型，固定 `video`
          example: video
        model:
          type: string
          description: 本次任务使用的模型 ID
          example: sora-2
        status:
          type: string
          description: |
            任务状态：
            - `queued` —— 已提交，排队等待
            - `in_progress` —— 正在生成
            - `completed` —— 完成，可下载（`/v1/videos/{id}/content`）
            - `failed` —— 失败（不计费），可重试
          enum:
            - queued
            - in_progress
            - completed
            - failed
          example: queued
        progress:
          type: integer
          description: 生成进度百分比（0–100），不严格线性
          example: 0
        created_at:
          type: integer
          description: 任务创建 Unix 时间戳（秒）
          example: 1712697600
        completed_at:
          type: integer
          description: 任务完成 Unix 时间戳（秒），仅 completed 状态返回
          example: 1712697900
        size:
          type: string
          description: 实际输出分辨率（与请求的 `size` 一致）
          example: 1280x720
        seconds:
          type: string
          description: 实际生成时长（与请求的 `seconds` 一致）
          example: '8'
        quality:
          type: string
          description: 画质档位（`standard` 对应 sora-2，`high` 对应 sora-2-pro）
          example: standard
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: 在 API易控制台获取的 API Key（必须配置 Sora2官转 分组 + 按量计费）

````