您將建置的內容
您將向 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");
同步產生
若要在建立回應中收到完成的影像,請在false async 中傳送 JSON 布林值。成功的回應會在 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 | 選填的 seed 值。結果可回報所使用的 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 模型: 模型.