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

# Kling API 快速入門：使用 CometAPI 產生影片

> 透過 CometAPI 建立 Kling 文生影片任務、輪詢任務狀態，並處理以回呼為基礎的完成通知。

## 你將建置的內容

你將提交一個 Kling 文生影片任務、儲存回傳的任務 ID、輪詢對應的 Kling 任務端點，並決定何時加入 `callback_url` 以接收推播通知。

## 先決條件

* 儲存在 `COMETAPI_KEY` 中的 CometAPI API key
* 安裝 `requests` 的 Python 3.10+，或 Node.js 18+
* 用於輪詢的伺服器端 worker，或用於 webhook 的 HTTPS 回呼端點

## API key、基礎 URL、驗證

使用以下端點建立 Kling 文生影片任務：

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

使用以下端點輪詢任務：

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

使用 Bearer token 進行驗證：

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

## 程式碼範例

使用下方分頁取得可直接複製的 cURL、Python 與 Node.js 範例。

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.cometapi.com/kling/v1/videos/text2video \
    -H "Authorization: Bearer $COMETAPI_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "prompt": "A small ceramic cup on a wooden table, steam rising in soft morning light",
      "model_name": "kling-v3",
      "mode": "std",
      "duration": "5",
      "sound": "off"
    }'

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

  ```python Python theme={null}
  import os
  import time

  import requests

  api_key = os.environ["COMETAPI_KEY"]
  headers = {
      "Authorization": f"Bearer {api_key}",
      "Content-Type": "application/json",
  }

  create_response = requests.post(
      "https://api.cometapi.com/kling/v1/videos/text2video",
      headers=headers,
      json={
          "prompt": "A small ceramic cup on a wooden table, steam rising in soft morning light",
          "model_name": "kling-v3",
          "mode": "std",
          "duration": "5",
          "sound": "off",
      },
      timeout=60,
  )
  create_response.raise_for_status()
  task_id = create_response.json()["data"]["task_id"]

  for _ in range(60):
      task_response = requests.get(
          f"https://api.cometapi.com/kling/v1/videos/text2video/{task_id}",
          headers={"Authorization": f"Bearer {api_key}"},
          timeout=30,
      )
      task_response.raise_for_status()
      task = task_response.json()["data"]
      if task["task_status"] in {"succeed", "failed"}:
          print(task)
          break
      time.sleep(5)
  else:
      raise TimeoutError("Kling task did not finish in time")
  ```

  ```javascript Node.js theme={null}
  const createResponse = await fetch(
    "https://api.cometapi.com/kling/v1/videos/text2video",
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        prompt: "A small ceramic cup on a wooden table, steam rising in soft morning light",
        model_name: "kling-v3",
        mode: "std",
        duration: "5",
        sound: "off",
      }),
    },
  );

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

  const created = await createResponse.json();
  const taskId = created.data.task_id;

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

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

    const task = (await taskResponse.json()).data;
    if (["succeed", "failed"].includes(task.task_status)) {
      console.log(task);
      break;
    }
    await new Promise((resolve) => setTimeout(resolve, 5000));
  }
  ```
</CodeGroup>

## 流程說明

Kling 影片生成是非同步的。建立端點會回傳 `data.task_id`。持續輪詢 `GET /kling/v1/videos/text2video/<task_id>`，直到 `data.task_status` 變成 `succeed` 或 `failed`。當任務成功時，如果你需要持久存取，請將 `data.task_result` 中已完成的資產 URL 複製到你自己的儲存空間。

當你希望將任務狀態更新推送到你所控制的 HTTPS 端點時，請加入 `callback_url`。同時保留輪詢機制，以便進行狀態校對與處理遺漏的 callback 傳送。

## 常見參數

| 參數             | 用途                                     |
| -------------- | -------------------------------------- |
| `prompt`       | 影片任務的文字 Prompt。                        |
| `model_name`   | Kling model ID。參考範例使用 `kling-v3`。      |
| `mode`         | 生成模式。測試更高成本模式之前，請先從 `std` 開始。          |
| `duration`     | 輸出長度。參考頁面在第一次請求中使用 `5`。                |
| `sound`        | 在支援的模型系列上，第一次請求請使用 `off`，以獲得可預期的無音訊結果。 |
| `callback_url` | 選填的 HTTPS URL，用於接收任務狀態 callback。       |

## 疑難排解 / 常見問題

<AccordionGroup>
  <Accordion title="回應格式與 OpenAI 影片路由不同">
    Kling 使用供應商特定的 JSON 欄位，例如 `data.task_id`、`data.task_status` 和 `data.task_result`。不要像解析 OpenAI 相容的 `/v1/videos` 路由那樣解析它。
  </Accordion>

  <Accordion title="任務始終沒有進入 succeed">
    請使用有界輪詢，並在任務失敗時檢查 `data.task_status_msg`。請儲存 task ID 以便後續診斷。
  </Accordion>

  <Accordion title="我應該使用 callback_url 還是輪詢">
    以輪詢作為基準做法。加入 `callback_url` 以進行推送傳送，然後再透過輪詢校對最終狀態。
  </Accordion>
</AccordionGroup>

## 後續步驟

* 閱讀 [Kling 文字轉影片 API 參考](/api/video/kling/text-to-video)。
* 使用 [取得 Kling 任務](/api/video/kling/individual-queries) 進行輪詢。
* 使用 [設定 Kling callback URL](/api/video/kling/callback_url) 來配置 callback。
* 在 [Models](/zh-Hant/overview/models) 中尋找 Kling 影片模型。
* 參閱 [在影片生成中使用輪詢與 webhook](/zh-Hant/guides/webhook-and-polling-for-video-generation)。
* 使用 [在呼叫模型前估算請求成本](/zh-Hant/guides/how-to-estimate-cost-before-calling-a-model) 來預估任務成本。
