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

# Sora 2 API 快速入门：使用 CometAPI 生成视频

> 使用 CometAPI 创建 Sora 2 视频任务、轮询状态，并通过 curl、Python 或 Node.js 下载已完成的视频内容。

## 你将构建的内容

你将提交一个 Sora 2 视频任务，存储返回的视频 ID，轮询直到任务完成，并下载最终的视频内容。

## 前提条件

* 存储在 `COMETAPI_KEY` 中的 CometAPI API key
* 安装了 `requests` 的 Python 3.10+，或 Node.js 18+
* 用于轮询的服务端 worker 或任务队列

## API key、基础 URL、身份验证

使用以下接口创建 Sora 任务：

```text theme={null}
POST https://api.cometapi.com/v1/videos
```

使用以下接口轮询状态：

```text theme={null}
GET https://api.cometapi.com/v1/videos/<video_id>
```

使用以下接口下载已完成的内容：

```text theme={null}
GET https://api.cometapi.com/v1/videos/<video_id>/content
```

使用 Bearer token 进行身份验证：

```text theme={null}
Authorization: Bearer $COMETAPI_KEY
```

## 代码示例

使用下方标签页查看可复制的 cURL、Python 和 Node.js 示例。

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.cometapi.com/v1/videos \
    -H "Authorization: Bearer $COMETAPI_KEY" \
    -F model=sora-2 \
    -F "prompt=A paper boat drifts across a calm pond at sunrise" \
    -F seconds=4 \
    -F size=1280x720

  curl "https://api.cometapi.com/v1/videos/<video_id>" \
    -H "Authorization: Bearer $COMETAPI_KEY"

  curl "https://api.cometapi.com/v1/videos/<video_id>/content" \
    -H "Authorization: Bearer $COMETAPI_KEY" \
    --output sora-result.mp4
  ```

  ```python Python theme={null}
  import os
  import time
  from pathlib import Path

  import requests

  api_key = os.environ["COMETAPI_KEY"]
  headers = {"Authorization": f"Bearer {api_key}"}

  create_response = requests.post(
      "https://api.cometapi.com/v1/videos",
      headers=headers,
      data={
          "model": "sora-2",
          "prompt": "A paper boat drifts across a calm pond at sunrise",
          "seconds": "4",
          "size": "1280x720",
      },
      timeout=60,
  )
  create_response.raise_for_status()
  video_id = create_response.json()["id"]

  for _ in range(60):
      status_response = requests.get(
          f"https://api.cometapi.com/v1/videos/{video_id}",
          headers=headers,
          timeout=30,
      )
      status_response.raise_for_status()
      status = status_response.json()
      if status["status"] == "completed":
          content_response = requests.get(
              f"https://api.cometapi.com/v1/videos/{video_id}/content",
              headers=headers,
              timeout=120,
          )
          content_response.raise_for_status()
          Path("sora-result.mp4").write_bytes(content_response.content)
          break
      if status["status"] == "failed":
          raise RuntimeError(status)
      time.sleep(5)
  else:
      raise TimeoutError("Sora job did not finish in time")
  ```

  ```javascript Node.js theme={null}
  import fs from "node:fs/promises";

  const form = new FormData();
  form.append("model", "sora-2");
  form.append("prompt", "A paper boat drifts across a calm pond at sunrise");
  form.append("seconds", "4");
  form.append("size", "1280x720");

  const createResponse = await fetch("https://api.cometapi.com/v1/videos", {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` },
    body: form,
  });

  if (!createResponse.ok) {
    throw new Error(await createResponse.text());
  }

  const { id } = await createResponse.json();

  for (let attempt = 0; attempt < 60; attempt += 1) {
    const statusResponse = await fetch(`https://api.cometapi.com/v1/videos/${id}`, {
      headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` },
    });

    if (!statusResponse.ok) {
      throw new Error(await statusResponse.text());
    }

    const status = await statusResponse.json();
    if (status.status === "completed") {
      const contentResponse = await fetch(
        `https://api.cometapi.com/v1/videos/${id}/content`,
        { headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` } },
      );
      const videoBuffer = Buffer.from(await contentResponse.arrayBuffer());
      await fs.writeFile("sora-result.mp4", videoBuffer);
      break;
    }
    if (status.status === "failed") {
      throw new Error(JSON.stringify(status));
    }
    await new Promise((resolve) => setTimeout(resolve, 5000));
  }
  ```
</CodeGroup>

## 流程说明

Sora 生成是异步的。创建端点会返回一个视频 ID 和初始状态。轮询 `GET /v1/videos/<video_id>`，直到 `status` 变为 `completed` 或 `failed`。当任务完成后，使用 `GET /v1/videos/<video_id>/content` 下载文件。

请使用精确的 `WxH` 尺寸。Sora API 参考文档列出了标准的横向和纵向尺寸，以及适用于 Pro model 工作流的更大 Pro 尺寸。

## 常用参数

| 参数                | 用途                                         |
| ----------------- | ------------------------------------------ |
| `model`           | Sora model ID。参考示例使用 `sora-2`。             |
| `prompt`          | 视频的文本 Prompt。                              |
| `seconds`         | 片段时长。API 参考文档列出了 `4`、`8`、`12`、`16` 和 `20`。 |
| `size`            | 精确的 `WxH` 输出尺寸，例如 `1280x720` 或 `720x1280`。 |
| `input_reference` | 可选的参考图片文件，用于首帧工作流。                         |

## 故障排查 / 常见问题

<AccordionGroup>
  <Accordion title="创建请求失败">
    请使用 multipart form data。参考中的 Sora 创建请求使用表单字段，而不是 JSON 请求体。
  </Accordion>

  <Accordion title="内容下载失败">
    仅在状态端点返回 `completed` 后再下载内容。请将完成后的文件存储到你自己的存储中。
  </Accordion>

  <Accordion title="Pro 尺寸不可用">
    仅在 Pro model 工作流中使用更大的 Pro 尺寸。首次请求请从 `1280x720` 开始。
  </Accordion>
</AccordionGroup>

## 后续步骤

* 阅读[创建 Sora 2 视频 API 参考](/api/video/sora-2/create)。
* 使用[获取 Sora 2 视频](/api/video/sora-2/retrieve)进行轮询。
* 使用[获取 Sora 2 视频内容](/api/video/sora-2/retrieve-content)进行下载。
* 在[模型](/zh-Hans/overview/models)中查找可用的视频模型。
* 查看[对视频生成使用轮询和 webhook](/zh-Hans/guides/webhook-and-polling-for-video-generation)。
* 通过[在调用模型前估算请求成本](/zh-Hans/guides/how-to-estimate-cost-before-calling-a-model)。
