快速比較
| 項目 | 輪詢(非同步) | Webhook(回呼) |
|---|---|---|
| 設定 | 簡單的 | 需要公共端點 |
| 實時 | 近實時 | 即時 |
| API 呼叫 | 每個任務可有多個 | 每個任務一個 |
| 最佳適用情境 | 開發、用戶端應用程式 | 生產伺服器 |
| 基礎設施 | 無 | HTTPS 端點 |
何時使用輪詢
在下列情況下選擇輪詢:- 建立用戶端應用程式
- 原型設計或測試
- 您沒有公共伺服器
- 處理少量任務
基本輪詢實現
async function pollForResult(model, taskId, apiKey) {
const interval = 3000; // 3 seconds
const maxAttempts = 60;
for (let i = 0; i < maxAttempts; i++) {
const response = await fetch(
`https://api.apixo.ai/api/v1/statusTask/${model}?taskId=${taskId}`,
{ headers: { 'Authorization': `Bearer ${apiKey}` } }
);
const { data } = await response.json();
if (data.state === 'success') {
return JSON.parse(data.resultJson).resultUrls;
}
if (data.state === 'failed') {
throw new Error(data.failMsg);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('Timeout');
}
指數退避
為提升效率,建議使用指數退避:async function pollWithBackoff(model, taskId, apiKey) {
let interval = 3000; // Start at 3s
const maxInterval = 30000; // Max 30s
const maxTime = 300000; // 5 min timeout
let elapsed = 0;
while (elapsed < maxTime) {
const response = await fetch(
`https://api.apixo.ai/api/v1/statusTask/${model}?taskId=${taskId}`,
{ headers: { 'Authorization': `Bearer ${apiKey}` } }
);
const { data } = await response.json();
if (data.state === 'success') {
return JSON.parse(data.resultJson).resultUrls;
}
if (data.state === 'failed') {
throw new Error(data.failMsg);
}
await new Promise(r => setTimeout(r, interval));
elapsed += interval;
interval = Math.min(interval * 1.5, maxInterval);
}
throw new Error('Timeout');
}
依模型類型建議的間隔時間
| 型號類型 | 初始等待 | 輪詢間隔 | 最大等待時間 |
|---|---|---|---|
| 影像(快速) | 5s | 3s | 2 分鐘 |
| 影像(品質) | 10s | 5s | 3 分鐘 |
| 影片 | 60s | 15s | 10 分鐘 |
| 音訊 | 30s | 10s | 5 分鐘 |
何時使用 Webhook
在下列情況下選擇 Webhook:- 運行生產伺服器
- 處理大量任務
- 需要即時通知
- 想盡量減少 API 通話
Webhook 設定
1。建立端點:- Express.js
- FastAPI
- Next.js
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhook/apixo', (req, res) => {
const { taskId, state, resultJson, failCode, failMsg } = req.body.data;
if (state === 'success') {
const urls = JSON.parse(resultJson).resultUrls;
console.log('Generated:', urls);
// Process your images/videos
} else if (state === 'failed') {
console.error(`Task ${taskId} failed: ${failCode}`);
}
res.status(200).send('OK');
});
app.listen(3000);
from fastapi import FastAPI, Request
import json
app = FastAPI()
@app.post('/webhook/apixo')
async def handle_webhook(request: Request):
body = await request.json()
data = body['data']
if data['state'] == 'success':
urls = json.loads(data['resultJson'])['resultUrls']
print(f"Generated: {urls}")
elif data['state'] == 'failed':
print(f"Task {data['taskId']} failed: {data['failCode']}")
return {'status': 'ok'}
// app/api/webhook/apixo/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
const body = await request.json();
const { taskId, state, resultJson, failCode } = body.data;
if (state === 'success') {
const urls = JSON.parse(resultJson).resultUrls;
console.log('Generated:', urls);
} else if (state === 'failed') {
console.error(`Task ${taskId} failed: ${failCode}`);
}
return NextResponse.json({ status: 'ok' });
}
const response = await fetch('https://api.apixo.ai/api/v1/generateTask/nano-banana', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
request_type: 'callback',
callback_url: 'https://your-domain.com/webhook/apixo',
input: {
mode: 'text-to-image',
prompt: 'A beautiful landscape',
aspect_ratio: '16:9',
},
}),
});
Webhook 要求
- 必須可透過 HTTPS 公開存取
- 必須回應 HTTP 200 之內 30 秒
- 應處理重複交付(使用
taskId實現冪等性)
重試政策
如果您的 webhook 失敗:| 試圖 | 延遲 |
|---|---|
| 第一次重試 | 30秒 |
| 第二次重試 | 2 分鐘 |
| 第三次重試 | 10 分鐘 |
混合方法
為了獲得最大的可靠性,請結合這兩種方法:class TaskManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.pendingTasks = new Map();
}
async submit(model, input, callbackUrl = null) {
const response = await fetch(
`https://api.apixo.ai/api/v1/generateTask/${model}`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
request_type: callbackUrl ? 'callback' : 'async',
callback_url: callbackUrl,
input,
}),
}
);
const { data } = await response.json();
if (!callbackUrl) {
// Fallback to polling if no webhook
return this.poll(model, data.taskId);
}
// Track task for webhook
this.pendingTasks.set(data.taskId, { model, status: 'pending' });
return data.taskId;
}
handleWebhook(body) {
const { taskId, state, resultJson, failMsg } = body.data;
if (state === 'success') {
this.pendingTasks.delete(taskId);
return JSON.parse(resultJson).resultUrls;
}
if (state === 'failed') {
this.pendingTasks.delete(taskId);
throw new Error(failMsg);
}
}
async poll(model, taskId) {
// Fallback polling implementation
return pollWithBackoff(model, taskId, this.apiKey);
}
}
使用 ngrok 進行本地開發
對於本地測試 webhook:# Install ngrok
npm install -g ngrok
# Start your local server
node server.js # runs on port 3000
# Tunnel to local server
ngrok http 3000
# Returns: https://abc123.ngrok.io
# Use ngrok URL as callback_url
摘要
| 情境設定 | 建議 |
|---|---|
| 開發/測試 | 輪詢 |
| 用戶端應用程式 | 輪詢 |
| 生產後台 | Webhook |
| 高流量 | Webhook |
| 最高可靠性 | 混合(webhooks + 輪詢後備) |
為了簡單起見,從輪詢開始,然後隨著應用程式的擴展遷移到 Webhooks。