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

# Hướng dẫn nhanh Kling API: Tạo video với CometAPI

> Tạo một tác vụ Kling text-to-video thông qua CometAPI, thăm dò trạng thái tác vụ và xử lý hoàn tất dựa trên callback.

## Những gì bạn sẽ xây dựng

Bạn sẽ gửi một tác vụ Kling text-to-video, lưu task ID được trả về, thăm dò endpoint tác vụ Kling tương ứng và quyết định khi nào cần thêm `callback_url` để nhận thông báo đẩy.

## Điều kiện tiên quyết

* Một API key CometAPI được lưu trong `COMETAPI_KEY`
* Python 3.10+ với `requests`, hoặc Node.js 18+
* Một worker phía máy chủ để thăm dò hoặc một endpoint callback HTTPS cho webhook

## API key, base URL, xác thực

Tạo một tác vụ Kling text-to-video bằng:

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

Thăm dò tác vụ bằng:

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

Xác thực bằng Bearer token:

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

## Ví dụ mã

Sử dụng các tab bên dưới để xem các ví dụ có thể sao chép trong cURL, Python và 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>

## Giải thích luồng

Quá trình tạo video Kling là bất đồng bộ. Endpoint tạo sẽ trả về `data.task_id`. Hãy poll `GET /kling/v1/videos/text2video/<task_id>` cho đến khi `data.task_status` đạt `succeed` hoặc `failed`. Khi tác vụ thành công, hãy sao chép URL asset đã hoàn tất từ `data.task_result` vào bộ lưu trữ của riêng bạn nếu bạn cần quyền truy cập bền vững.

Thêm `callback_url` khi bạn muốn các bản cập nhật trạng thái tác vụ được đẩy đến một endpoint HTTPS do bạn kiểm soát. Vẫn giữ cơ chế polling để đối soát và xử lý các trường hợp callback bị bỏ lỡ.

## Các tham số phổ biến

| Parameter      | Cách dùng                                                                                              |
| -------------- | ------------------------------------------------------------------------------------------------------ |
| `prompt`       | Prompt văn bản cho tác vụ video.                                                                       |
| `model_name`   | model ID của Kling. Ví dụ tham chiếu sử dụng `kling-v3`.                                               |
| `mode`         | Chế độ tạo. Hãy bắt đầu với `std` trước khi thử các chế độ có chi phí cao hơn.                         |
| `duration`     | Độ dài đầu ra. Trang tham chiếu sử dụng `5` cho yêu cầu đầu tiên.                                      |
| `sound`        | Dùng `off` cho yêu cầu đầu tiên không có âm thanh và có tính xác định trên các dòng model được hỗ trợ. |
| `callback_url` | URL HTTPS tùy chọn cho callback trạng thái tác vụ.                                                     |

## Khắc phục sự cố / FAQ

<AccordionGroup>
  <Accordion title="Cấu trúc phản hồi khác với các route video của OpenAI">
    Kling sử dụng các trường JSON đặc thù của nhà cung cấp như `data.task_id`, `data.task_status`, và `data.task_result`. Đừng parse nó như các route `/v1/videos` tương thích OpenAI.
  </Accordion>

  <Accordion title="Tác vụ không bao giờ đạt trạng thái succeed">
    Sử dụng polling có giới hạn và kiểm tra `data.task_status_msg` khi tác vụ thất bại. Lưu task ID để chẩn đoán sau này.
  </Accordion>

  <Accordion title="Tôi nên dùng callback_url hay polling">
    Dùng polling làm phương án cơ bản. Thêm `callback_url` để nhận cập nhật theo cơ chế đẩy, sau đó đối soát trạng thái cuối cùng bằng polling.
  </Accordion>
</AccordionGroup>

## Các bước tiếp theo

* Đọc [tài liệu tham chiếu API Kling text-to-video](/api/video/kling/text-to-video).
* Poll với [Lấy một tác vụ Kling](/api/video/kling/individual-queries).
* Cấu hình callback với [Sử dụng URL callback của Kling](/api/video/kling/callback_url).
* Tìm các model video Kling trong [Models](/vi/overview/models).
* Xem lại [Sử dụng polling và webhook cho việc tạo video](/vi/guides/webhook-and-polling-for-video-generation).
* Ước tính chi phí tác vụ với [Ước tính chi phí yêu cầu trước khi gọi một model](/vi/guides/how-to-estimate-cost-before-calling-a-model).
