您将构建的内容
您将向 FLUX.2 Pro 提交一个1280x768 PNG 任务,存储返回的任务 id,轮询 GET /flux/v1/get_result,并在任务变为 result.sample 时下载 Ready。
前提条件
- 存储在
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");
流程说明
创建端点会返回一个顶层任务id;它也可能返回 status: "processing"。使用该 id 轮询 CometAPI 结果端点。Ready 表示成功的终止状态。将已知的错误和审核状态视为失败;对于其他状态,仅在客户端超时之前继续轮询。
仅使用 result.sample 下载已完成的图像。它是临时 URL,不应作为应用程序的持久存储。
常用参数
| 参数 | 用途 |
|---|---|
model 路径片段 | URL 路径中的 FLUX.2 模型 ID。本快速入门使用 flux-2-pro;请查看 模型 以确认账户是否可用。 |
prompt | 必填的图像描述或编辑指令。 |
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,然后将图像存入由应用程序控制的存储中。请求字段不起作用
请求字段不起作用
从 API 参考中的字段开始。在确认所选 CometAPI 路由会保留并应用其他模型特定控件之前,应将其视为未经验证。
后续步骤
- 阅读 生成 FLUX 图像 API 参考.
- 使用以下项轮询结果: 获取 FLUX 图像结果.
- 在以下位置查找可用的 FLUX 模型: 模型.