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

# Flux API 快速入門：使用 CometAPI 產生圖片

> 透過 CometAPI 建立 Flux 圖片任務、輪詢產生出的圖片，並在 URL 過期前下載結果。

## 你將建立的內容

你將使用 `POST /flux/v1/flux-dev` 建立一個 Flux 圖片生成任務，輪詢 `GET /flux/v1/get_result`，並在任務就緒時下載產生出的圖片 URL。

## 先決條件

* 儲存在 `COMETAPI_KEY` 中的 CometAPI API key
* Python 3.10+ 與 `requests`，或 Node.js 18+
* 來自 Flux API 參考文件或 [Models](/zh-Hant/overview/models) 的 Flux 模型路徑

## API key、基礎 URL、驗證

Flux 生成會在 URL 路徑中使用模型名稱：

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

使用任務 ID 輪詢結果端點：

```text theme={null}
https://api.cometapi.com/flux/v1/get_result?id=<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/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>

## 流程說明

Flux 生成是非同步的。建立端點會回傳任務 `id`。持續輪詢 `/flux/v1/get_result?id=<task_id>`，直到 `status` 為 `Ready`，接著下載 `result.sample`。

Flux 結果 URL 具有時間限制。當你的應用程式需要持久存取時，請將已完成的圖片複製到你自己的儲存空間中。

## 常見參數

| 參數                   | 用途                                      |
| -------------------- | --------------------------------------- |
| `model` path segment | URL 路徑中的 Flux 模型變體，例如參考範例中的 `flux-dev`。 |
| `prompt`             | 必填的文字 Prompt。                           |
| `width` / `height`   | 輸出尺寸（以像素為單位）。API 參考文件中有註明各模型特定的範圍。      |
| `seed`               | 用於控制可重現性的選用參數。                          |
| `output_format`      | 當所選 Flux 模型支援時，請求的輸出圖片格式。               |
| `webhook_url`        | 適用於支援的 Flux 工作流程的選用完成通知 URL。            |

## 疑難排解 / 常見問題

<AccordionGroup>
  <Accordion title="任務一直處於 pending">
    持續使用具有限制重試次數與逾時設定的輪詢迴圈。請儲存 task ID，以便稍後檢查該工作。
  </Accordion>

  <Accordion title="圖片 URL 已過期">
    在任務變為 `Ready` 後，盡快下載 `result.sample`，然後將圖片儲存到你自己的儲存空間。
  </Accordion>

  <Accordion title="Flux 參數失敗">
    Flux 參數支援會因 model variant 而異。請先使用 `prompt`、`width` 和 `height`，再於加入選用欄位前查閱 Flux API 參考文件。
  </Accordion>
</AccordionGroup>

## 後續步驟

* 閱讀 [Flux generate image API reference](/api/image/flux/flux-generate-image)。
* 使用 [Get Flux image result](/api/image/flux/flux-query) 輪詢結果。
* 在 [Models](/zh-Hant/overview/models) 中查找 Flux 模型。
* 使用 [Estimate request cost before calling a model](/zh-Hant/guides/how-to-estimate-cost-before-calling-a-model) 估算成本。
