> ## 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
* Python 3.10+ 與 `requests`，或 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` | 可選的參考圖片檔案，用於首幀工作流程。                        |

## 疑難排解 / FAQ

<AccordionGroup>
  <Accordion title="建立請求失敗">
    請使用 multipart form data。參考文件中的 Sora 建立請求使用表單欄位，而非 JSON request body。
  </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)下載。
* 在[Models](/zh-Hant/overview/models)中查看可用的影片模型。
* 參閱[對影片生成使用輪詢與 webhook](/zh-Hant/guides/webhook-and-polling-for-video-generation)。
* 透過[在呼叫模型前估算請求成本](/zh-Hant/guides/how-to-estimate-cost-before-calling-a-model)估算任務成本。
