預測
了解非同步生成任務——提交、輪詢和取得結果
什麼是預測?
當您向 Atlas Cloud 提交圖片或影片生成請求時,任務不會立即完成。相反,您會收到一個 prediction ID,可用於追蹤任務進度並在完成後取得結果。
這種非同步模式用於所有非 LLM 的生成任務(圖片、影片等),因為這些任務可能需要數秒到數分鐘不等的時間才能完成。
預測生命週期
┌─────────┐ ┌────────────┐ ┌───────────┐
│ 提交 │ ──→ │ 處理中 │ ──→ │ 已完成 │
│ 任務 │ │ │ │ │
└─────────┘ └────────────┘ └───────────┘
│
▼
┌───────────┐
│ 已失敗 │
└───────────┘狀態值:
processing——模型正在處理任務completed——生成完成,輸出結果可用failed——生成失敗,可查看錯誤詳情
提交任務
圖片生成
import requests
response = requests.post(
"https://api.atlascloud.ai/api/v1/model/generateImage",
headers={
"Authorization": "Bearer your-api-key",
"Content-Type": "application/json"
},
json={
"model": "seedream-3.0",
"prompt": "A beautiful mountain landscape at golden hour"
}
)
data = response.json()
prediction_id = data["data"]["id"]
print(f"Task submitted: {prediction_id}")影片生成
response = requests.post(
"https://api.atlascloud.ai/api/v1/model/generateVideo",
headers={
"Authorization": "Bearer your-api-key",
"Content-Type": "application/json"
},
json={
"model": "kling-v2.0",
"prompt": "Ocean waves crashing on a rocky shore at sunset"
}
)
data = response.json()
prediction_id = data["data"]["id"]輪詢取得結果
使用 prediction ID 查看任務狀態並取得輸出:
import requests
import time
def wait_for_result(prediction_id, api_key, interval=5, timeout=300):
"""輪詢生成結果,含逾時處理。"""
elapsed = 0
while elapsed < timeout:
response = requests.get(
f"https://api.atlascloud.ai/api/v1/model/prediction/{prediction_id}",
headers={"Authorization": f"Bearer {api_key}"}
)
result = response.json()
status = result["data"]["status"]
if status == "completed":
return result["data"]["outputs"][0]
elif status == "failed":
raise Exception(f"Generation failed: {result['data'].get('error')}")
print(f"Status: {status} ({elapsed}s elapsed)")
time.sleep(interval)
elapsed += interval
raise TimeoutError(f"Task did not complete within {timeout}s")
# 使用範例
output = wait_for_result("your-prediction-id", "your-api-key")
print(f"Result: {output}")Node.js 範例
async function waitForResult(predictionId, apiKey, interval = 5000, timeout = 300000) {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const response = await fetch(
`https://api.atlascloud.ai/api/v1/model/prediction/${predictionId}`,
{ headers: { Authorization: `Bearer ${apiKey}` } }
);
const result = await response.json();
const status = result.data.status;
if (status === "completed") return result.data.outputs[0];
if (status === "failed") throw new Error(`Failed: ${result.data.error}`);
console.log(`Status: ${status}`);
await new Promise((r) => setTimeout(r, interval));
}
throw new Error("Timeout");
}
const output = await waitForResult("your-prediction-id", "your-api-key");
console.log(`Result: ${output}`);cURL 範例
curl "https://api.atlascloud.ai/api/v1/model/prediction/your-prediction-id" \
-H "Authorization: Bearer your-api-key"輪詢最佳實踐
- 從較長的間隔開始:影片生成使用 5 秒間隔,圖片生成使用 2 秒間隔
- 設定逾時:務必設定最大等待時間以避免無限輪詢
- 優雅處理失敗:檢查
failed狀態並適當處理錯誤 - 記錄進度:列印狀態更新,讓使用者知道任務仍在執行中
典型生成時間
| 任務類型 | 典型時間 |
|---|---|
| 圖片生成 | 2–10 秒 |
| 影片生成 | 30 秒 – 3 分鐘 |
| 圖片轉影片 | 30 秒 – 3 分鐘 |
| 圖片工具(放大等) | 5–15 秒 |
實際時間會因模型、參數(解析度、時長)和當前負載而異。
錯誤處理
當預測失敗時,結果會包含錯誤訊息:
{
"data": {
"id": "prediction-id",
"status": "failed",
"error": "Invalid parameter: resolution not supported by this model",
"outputs": []
}
}常見失敗原因:
- 無效的模型參數
- 輸入圖片 URL 無法存取
- 提示詞包含不允許的內容
- 帳戶餘額不足
完整的錯誤碼文件請參閱 API 參考。