> ## 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 密钥
* 安装了 `requests` 的 Python 3.10+，或 Node.js 18+
* 一个用于轮询的服务端 worker，或一个用于 webhook 的 HTTPS 回调端点

## API 密钥、基础 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`。同时保留轮询机制，用于对账以及处理回调投递遗漏的情况。

## 常用参数

| Parameter      | Use                                  |
| -------------- | ------------------------------------ |
| `prompt`       | 视频任务的文本 Prompt。                      |
| `model_name`   | Kling model ID。参考示例使用 `kling-v3`。    |
| `mode`         | 生成模式。在测试更高成本模式之前，先从 `std` 开始。        |
| `duration`     | 输出时长。参考页面首次请求使用 `5`。                 |
| `sound`        | 在支持的模型版本上，首次请求使用 `off` 可获得确定性的无音频结果。 |
| `callback_url` | 可选的 HTTPS URL，用于接收任务状态回调。            |

## 故障排查 / 常见问题

<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 URLs](/api/video/kling/callback_url) 配置回调。
* 在 [Models](/zh-Hans/overview/models) 中查找 Kling 视频模型。
* 查看 [对视频生成使用轮询和 webhooks](/zh-Hans/guides/webhook-and-polling-for-video-generation)。
* 通过 [在调用模型前估算请求成本](/zh-Hans/guides/how-to-estimate-cost-before-calling-a-model)。
