> ## 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 密钥
* 安装了 `requests` 的 Python 3.10+，或 Node.js 18+
* 来自 Flux API 参考文档或 [Models](/zh-Hans/overview/models) 的 Flux 模型路径

## API 密钥、基础 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 具有时效限制。当你的应用需要持久访问时，请将已完成的图片复制到你自己的存储中。

## 常见参数

| Parameter            | 用途                                      |
| -------------------- | --------------------------------------- |
| `model` path segment | URL 路径中的 Flux 模型变体，例如参考示例中的 `flux-dev`。 |
| `prompt`             | 必填的文本 Prompt。                           |
| `width` / `height`   | 以像素为单位的输出尺寸。API 参考文档中注明了特定模型支持的范围。      |
| `seed`               | 可选的可复现性控制参数。                            |
| `output_format`      | 在所选 Flux 模型支持的情况下，请求的输出图像格式。            |
| `webhook_url`        | 适用于受支持 Flux 工作流的可选完成通知 URL。             |

## 故障排查 / 常见问题

<AccordionGroup>
  <Accordion title="任务一直处于 pending 状态">
    使用带有重试次数上限和超时设置的轮询循环持续查询。保存任务 ID，以便后续检查该任务。
  </Accordion>

  <Accordion title="图片 URL 已过期">
    在任务变为 `Ready` 后尽快下载 `result.sample`，然后将图片存储到你自己的存储系统中。
  </Accordion>

  <Accordion title="某个 Flux 参数调用失败">
    Flux 参数支持会因模型变体而异。先从 `prompt`、`width` 和 `height` 开始，然后在添加可选字段之前查看 Flux API 参考。
  </Accordion>
</AccordionGroup>

## 后续步骤

* 阅读 [Flux 生成图片 API 参考](/api/image/flux/flux-generate-image)。
* 使用 [获取 Flux 图片结果](/api/image/flux/flux-query) 轮询结果。
* 在 [Models](/zh-Hans/overview/models) 中查找 Flux 模型。
* 使用 [在调用模型前估算请求成本](/zh-Hans/guides/how-to-estimate-cost-before-calling-a-model)。
