快速比较
| 方面 | 轮询(异步) | Webhooks(回调) |
|---|---|---|
| 设置 | 简单的 | 需要公共端点 |
| 实时 | 近实时 | 立即的 |
| 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 公开访问
- 必须在 30 秒内返回 HTTP 200
- 应处理重复交付(使用
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。