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

# Bắt đầu nhanh với Flux API: Tạo ảnh bằng CometAPI

> Tạo một tác vụ ảnh Flux thông qua CometAPI, thăm dò ảnh được tạo ra, và tải kết quả xuống trước khi URL hết hạn.

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

Bạn sẽ tạo một tác vụ tạo ảnh Flux với `POST /flux/v1/flux-dev`, thăm dò `GET /flux/v1/get_result`, và tải URL ảnh được tạo xuống khi tác vụ đã sẵn sàng.

## Đ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 đường dẫn model Flux từ tài liệu tham chiếu Flux API hoặc [Models](/vi/overview/models)

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

Việc tạo ảnh Flux sử dụng tên model trong đường dẫn URL:

```text theme={null}
https://api.cometapi.com/flux/v1/flux-dev
```

Thăm dò endpoint kết quả bằng task ID:

```text theme={null}
https://api.cometapi.com/flux/v1/get_result?id=<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 bằng cURL, Python và Node.js.

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.cometapi.com/flux/v1/flux-dev \
    -H "Authorization: Bearer $COMETAPI_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "prompt": "A paper boat floating on calm water at sunrise.",
      "width": 512,
      "height": 512
    }'

  curl "https://api.cometapi.com/flux/v1/get_result?id=<task_id>" \
    -H "Authorization: Bearer $COMETAPI_KEY"
  ```

  ```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/flux/v1/flux-dev",
      headers={**headers, "Content-Type": "application/json"},
      json={
          "prompt": "A paper boat floating on calm water at sunrise.",
          "width": 512,
          "height": 512,
      },
      timeout=60,
  )
  create_response.raise_for_status()
  task_id = create_response.json()["id"]

  for _ in range(30):
      result_response = requests.get(
          "https://api.cometapi.com/flux/v1/get_result",
          headers=headers,
          params={"id": task_id},
          timeout=30,
      )
      result_response.raise_for_status()
      result = result_response.json()
      if result.get("status") == "Ready":
          image_url = result["result"]["sample"]
          image_bytes = requests.get(image_url, timeout=60).content
          Path("flux-result.jpeg").write_bytes(image_bytes)
          break
      if result.get("status") == "Task not found":
          raise RuntimeError("Flux task was not found")
      time.sleep(2)
  else:
      raise TimeoutError("Flux task did not finish in time")
  ```

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

  const headers = {
    Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
    "Content-Type": "application/json",
  };

  const createResponse = await fetch("https://api.cometapi.com/flux/v1/flux-dev", {
    method: "POST",
    headers,
    body: JSON.stringify({
      prompt: "A paper boat floating on calm water at sunrise.",
      width: 512,
      height: 512,
    }),
  });

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

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

  for (let attempt = 0; attempt < 30; attempt += 1) {
    const resultResponse = await fetch(
      `https://api.cometapi.com/flux/v1/get_result?id=${encodeURIComponent(id)}`,
      { headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` } },
    );

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

    const result = await resultResponse.json();
    if (result.status === "Ready") {
      const imageResponse = await fetch(result.result.sample);
      const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
      await fs.writeFile("flux-result.jpeg", imageBuffer);
      break;
    }
    if (result.status === "Task not found") {
      throw new Error("Flux task was not found");
    }
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }
  ```
</CodeGroup>

## Giải thích luồng

Việc tạo bằng Flux là bất đồng bộ. Endpoint tạo sẽ trả về một `id` tác vụ. Poll `/flux/v1/get_result?id=<task_id>` cho đến khi `status` là `Ready`, sau đó tải xuống `result.sample`.

Các URL kết quả của Flux có thời hạn. Hãy sao chép các hình ảnh đã hoàn tất vào hệ thống lưu trữ của riêng bạn khi ứng dụng cần quyền truy cập lâu dài.

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

| Tham số              | Mục đích sử dụng                                                                                          |
| -------------------- | --------------------------------------------------------------------------------------------------------- |
| `model` path segment | Biến thể model Flux trong đường dẫn URL, chẳng hạn như ví dụ tham chiếu `flux-dev`.                       |
| `prompt`             | Prompt văn bản bắt buộc.                                                                                  |
| `width` / `height`   | Kích thước đầu ra tính bằng pixel. Tài liệu tham chiếu API có ghi chú các phạm vi theo từng model cụ thể. |
| `seed`               | Điều khiển khả năng tái lập, không bắt buộc.                                                              |
| `output_format`      | Định dạng hình ảnh đầu ra được yêu cầu khi được model Flux đã chọn hỗ trợ.                                |
| `webhook_url`        | URL thông báo hoàn tất không bắt buộc cho các quy trình Flux được hỗ trợ.                                 |

## Khắc phục sự cố / Câu hỏi thường gặp

<AccordionGroup>
  <Accordion title="Tác vụ vẫn ở trạng thái chờ">
    Tiếp tục polling bằng một vòng lặp retry có giới hạn và timeout. Lưu task ID để có thể kiểm tra job sau.
  </Accordion>

  <Accordion title="URL hình ảnh đã hết hạn">
    Tải xuống `result.sample` ngay sau khi tác vụ chuyển sang `Ready`, rồi lưu hình ảnh vào bộ nhớ lưu trữ của riêng bạn.
  </Accordion>

  <Accordion title="Một tham số Flux bị lỗi">
    Mức độ hỗ trợ tham số Flux khác nhau tùy theo biến thể model. Hãy bắt đầu với `prompt`, `width` và `height`, sau đó kiểm tra tài liệu tham chiếu Flux API trước khi thêm các trường tùy chọn.
  </Accordion>
</AccordionGroup>

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

* Đọc [tài liệu tham chiếu Flux generate image API](/api/image/flux/flux-generate-image).
* Poll kết quả bằng [Get Flux image result](/api/image/flux/flux-query).
* Tìm các model Flux trong [Models](/vi/overview/models).
* Ước tính chi phí bằng [Estimate request cost before calling a model](/vi/guides/how-to-estimate-cost-before-calling-a-model).
