您将构建的内容
您将向 FLUX.2 Pro 提交一个1280x768 PNG 任务,保存返回的任务 id,轮询 GET /flux/v1/get_result,并在任务变为 result.sample 时下载 Ready。
对于同步请求,请发送 "async": false,并从创建响应中读取 result.sample。请参阅 同步生成 以获取完整示例。
前提条件
- 存储在
COMETAPI_KEY中的 CometAPI API 密钥 curl以及jq、安装了requests的 Python 3.10+,或 Node.js 18+- 您的 CometAPI 账户拥有
flux-2-pro的访问权限
端点和身份验证
提交任务:POST https://api.cometapi.com/flux/v1/flux-2-pro
id 进行轮询:
GET https://api.cometapi.com/flux/v1/get_result?id=<task_id>
Authorization: Bearer $COMETAPI_KEY
代码示例
set -e
CREATE_RESPONSE=$(curl --max-time 60 -fSs https://api.cometapi.com/flux/v1/flux-2-pro \
-H "Authorization: Bearer $COMETAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A clean editorial photograph of a red ceramic teapot on a pale blue table, a small yellow lemon on the right, soft window light, no text.",
"width": 1280,
"height": 768,
"output_format": "png",
"seed": 424242
}')
TASK_ID=$(printf "%s" "$CREATE_RESPONSE" | jq -r '.id')
for ATTEMPT in $(seq 1 60); do
RESULT=$(curl --max-time 30 -fSs "https://api.cometapi.com/flux/v1/get_result?id=$TASK_ID" \
-H "Authorization: Bearer $COMETAPI_KEY")
STATUS=$(printf "%s" "$RESULT" | jq -r '.status')
echo "status: $STATUS"
case "$STATUS" in
Ready)
IMAGE_URL=$(printf "%s" "$RESULT" | jq -r '.result.sample')
curl --max-time 60 -fL "$IMAGE_URL" -o flux-result.png
exit 0
;;
Error|Failed|Failure|"Task not found"|"Request Moderated"|"Content Moderated"|failed|failure)
echo "FLUX task failed: $STATUS" >&2
exit 1
;;
esac
sleep 5
done
echo "FLUX task did not finish in time" >&2
exit 1
import os
import time
from pathlib import Path
import requests
headers = {"Authorization": "Bearer " + os.environ["COMETAPI_KEY"]}
payload = {
"prompt": (
"A clean editorial photograph of a red ceramic teapot on a pale blue "
"table, a small yellow lemon on the right, soft window light, no text."
),
"width": 1280,
"height": 768,
"output_format": "png",
"seed": 424242,
}
create_response = requests.post(
"https://api.cometapi.com/flux/v1/flux-2-pro",
headers={**headers, "Content-Type": "application/json"},
json=payload,
timeout=60,
)
create_response.raise_for_status()
task_id = create_response.json()["id"]
failure_statuses = {
"Error",
"Failed",
"Failure",
"Task not found",
"Request Moderated",
"Content Moderated",
"failed",
"failure",
}
for _ in range(60):
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()
status = result.get("status")
print(status)
if status == "Ready":
image_response = requests.get(result["result"]["sample"], timeout=60)
image_response.raise_for_status()
Path("flux-result.png").write_bytes(image_response.content)
break
if status in failure_statuses:
raise RuntimeError(f"FLUX task failed: {status}")
time.sleep(5)
else:
raise TimeoutError("FLUX task did not finish in time")
import fs from "node:fs/promises";
const authHeaders = {
Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
};
const createResponse = await fetch(
"https://api.cometapi.com/flux/v1/flux-2-pro",
{
method: "POST",
headers: { ...authHeaders, "Content-Type": "application/json" },
signal: AbortSignal.timeout(60_000),
body: JSON.stringify({
prompt:
"A clean editorial photograph of a red ceramic teapot on a pale blue table, a small yellow lemon on the right, soft window light, no text.",
width: 1280,
height: 768,
output_format: "png",
seed: 424242,
}),
},
);
if (!createResponse.ok) throw new Error(await createResponse.text());
const { id } = await createResponse.json();
const failureStatuses = new Set([
"Error",
"Failed",
"Failure",
"Task not found",
"Request Moderated",
"Content Moderated",
"failed",
"failure",
]);
let completed = false;
for (let attempt = 0; attempt < 60; attempt += 1) {
const resultResponse = await fetch(
`https://api.cometapi.com/flux/v1/get_result?id=${encodeURIComponent(id)}`,
{ headers: authHeaders, signal: AbortSignal.timeout(30_000) },
);
if (!resultResponse.ok) throw new Error(await resultResponse.text());
const result = await resultResponse.json();
console.log(result.status);
if (result.status === "Ready") {
const imageResponse = await fetch(result.result.sample, {
signal: AbortSignal.timeout(60_000),
});
if (!imageResponse.ok) throw new Error(await imageResponse.text());
await fs.writeFile(
"flux-result.png",
Buffer.from(await imageResponse.arrayBuffer()),
);
completed = true;
break;
}
if (failureStatuses.has(result.status)) {
throw new Error(`FLUX task failed: ${result.status}`);
}
await new Promise((resolve) => setTimeout(resolve, 5000));
}
if (!completed) throw new Error("FLUX task did not finish in time");
同步生成
要在创建响应中接收完成的图像,请在 JSON 布尔值false 中发送 async。成功响应包含 status: "Ready" 和图像 URL
,位于 result.sample 中。使用 true 或省略 async 以采用上述异步工作流
。不要将 "false" 作为字符串发送,也不要将 async: false 与
webhook_url 或 webhook_secret 结合使用。
这些示例最多等待 300 秒以获取创建响应,然后下载
图像。超时由客户端设置,而非完成期限:
set -e
RESULT=$(curl \
https://api.cometapi.com/flux/v1/flux-2-pro \
--max-time 300 \
--fail-with-body \
--silent \
--show-error \
-H "Authorization: Bearer $COMETAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A red ceramic teapot on a pale blue table, soft window light.",
"width": 1280,
"height": 768,
"output_format": "png",
"seed": 424242,
"async": false
}')
if [ "$(printf '%s' "$RESULT" | jq -r '.status')" != "Ready" ]; then
echo "FLUX generation did not return a Ready result" >&2
exit 1
fi
IMAGE_URL=$(printf '%s' "$RESULT" | jq -er '.result.sample')
curl \
"$IMAGE_URL" \
--max-time 60 \
--fail \
--location \
--output flux-result.png
import os
from pathlib import Path
import requests
response = requests.post(
"https://api.cometapi.com/flux/v1/flux-2-pro",
headers={
"Authorization": "Bearer " + os.environ["COMETAPI_KEY"],
"Content-Type": "application/json",
},
json={
"prompt": "A red ceramic teapot on a pale blue table, soft window light.",
"width": 1280,
"height": 768,
"output_format": "png",
"seed": 424242,
"async": False,
},
timeout=300,
)
response.raise_for_status()
task = response.json()
if task.get("status") != "Ready":
raise RuntimeError("FLUX generation did not return a Ready result")
image_response = requests.get(task["result"]["sample"], timeout=60)
image_response.raise_for_status()
Path("flux-result.png").write_bytes(image_response.content)
import fs from "node:fs/promises";
const response = await fetch(
"https://api.cometapi.com/flux/v1/flux-2-pro",
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
"Content-Type": "application/json",
},
signal: AbortSignal.timeout(300_000),
body: JSON.stringify({
prompt: "A red ceramic teapot on a pale blue table, soft window light.",
width: 1280,
height: 768,
output_format: "png",
seed: 424242,
async: false,
}),
},
);
if (!response.ok) throw new Error(await response.text());
const task = await response.json();
if (task.status !== "Ready") {
throw new Error("FLUX generation did not return a Ready result");
}
const imageResponse = await fetch(task.result.sample, {
signal: AbortSignal.timeout(60_000),
});
if (!imageResponse.ok) throw new Error(await imageResponse.text());
await fs.writeFile(
"flux-result.png",
Buffer.from(await imageResponse.arrayBuffer()),
);
工作流程
使用async: true 或不提供 async 字段时,创建端点会在生成继续进行期间返回顶层任务 id。使用该 id 轮询 CometAPI 结果端点。Ready 是成功的终止状态。将已知的错误和审核状态视为失败,其他状态仅在客户端超时前继续轮询。
使用 async: false 时,成功的创建响应包含 status: "Ready" 和 result.sample。直接读取图像 URL,无需轮询。
仅使用 result.sample 下载完成的图像。它是临时 URL,不应用作持久的应用程序存储。
通用参数
| 参数 | 用途 |
|---|---|
model 路径段 | URL 路径中的 FLUX.2 模型 ID。本快速入门使用 flux-2-pro;请查看 模型 了解账户可用性。 |
prompt | 必填的图像描述或编辑指令。 |
async | 可选的 JSON 布尔值。false 会在创建响应中等待图像;true 或省略该参数会提交异步任务。请勿将 false 与 webhook_url 或 webhook_secret. |
width / height | 请求的输出尺寸,单位为像素。 |
output_format | 所选模型支持的格式。本快速入门使用 png. |
seed | 可选的种子值。结果可能会报告所用的种子;仅凭该字段无法确保输出可重复。 |
input_image | 用于编辑的公开 HTTPS 参考图像 URL。 |
input_image_2 | 适用于 FLUX.2 Pro 的第二个公开 HTTPS 参考图像 URL;还需发送 input_image. |
故障排除
任务一直处于处理中状态
任务一直处于处理中状态
在有限次数的重试循环中继续轮询。如果达到客户端超时限制,请保留任务 ID 以便后续检查,并将请求报告为已超时,而非成功。
图像 URL 不再可用
图像 URL 不再可用
任务变为
result.sample 后,立即下载 Ready,然后将图像存放在由您的应用程序控制的存储中。请求字段未生效
请求字段未生效
使用 生成 FLUX 图像 API 参考 为您的模型选择请求字段。请根据请求示例检查字段名称和 JSON 类型。
后续步骤
- 阅读 生成 FLUX 图像 API 参考.
- 使用以下方式轮询结果: 获取 FLUX 图像结果.
- 在以下位置查找可用的 FLUX 模型: 模型.