- 提交后工作进程重启。 保存模型和任务 ID,让接手的进程可以继续轮询。
- 同一完成通知送达两次。 按任务 ID 去重,确保结果只处理一次。详见 Webhook 幂等处理。
- 任务到达
failed。 记录失败代码和消息,然后在重试前对错误进行分类。无效输入需通过修正请求处理。
请求模式选择
在实现以下重试逻辑前,使用 轮询和 Webhooks 比较 选择交付方式。| 模式 | 最适合 | 优点 | 缺点 |
|---|---|---|---|
| 异步(轮询) | 客户端应用程序,简单脚本 | 易于实现 | 需要轮询逻辑 |
| 回调(Webhook) | 生产服务器 | 实时,无轮询 | 需要公共端点 |
从
async模式开始进行开发,切换到callback进行生产。轮询策略
对于async模式,实施智能轮询以平衡响应能力和效率。
建议间隔时间
| 模型类型 | 初始等待 | 轮询间隔 | 最大等待时间 |
|---|---|---|---|
| 图像(快速) | 5s | 3s | 2 分钟 |
| 图像(质量) | 10s | 5s | 3 分钟 |
| 视频 | 60s | 15s | 10 分钟 |
| 音频 | 30s | 10s | 5 分钟 |
指数退避
async function pollWithBackoff(model, taskId, apiKey) {
let interval = 3000; // Start at 3s
const maxInterval = 30000; // Max 30s
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));
interval = Math.min(interval * 1.5, maxInterval);
}
throw new Error('Timeout');
}
错误处理
始终处理失败
const result = await pollForResult(taskId);
if (!result) {
// Handle null/undefined
}
// Check for specific error codes
if (result.state === 'failed') {
switch (result.failCode) {
case 'CONTENT_VIOLATION':
// Prompt needs modification
break;
case 'PROCESSING_TIMEOUT':
// Retry the request
break;
case 'INSUFFICIENT_CREDITS':
// Alert user to add credits
break;
}
}
实施重试
async function generateWithRetry(params, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await generateImage(params);
} catch (error) {
if (attempt === maxRetries - 1) throw error;
// Only retry on transient errors
if (error.failCode === 'PROCESSING_TIMEOUT') {
await new Promise(r => setTimeout(r, 5000));
continue;
}
throw error; // Don't retry content violations etc.
}
}
}
提示工程
图像生成技巧
| 做 | 不要 |
|---|---|
| 具体来说:“一只金毛小狗在秋叶中玩耍” | 含糊其辞:“一只狗” |
| 包含风格:“水彩画、柔和灯光” | 假设默认值 |
| 指定构图:“特写肖像,居中” | 让构图随机生成 |
| 使用积极的描述 | 使用“无背景”等否定词 |
有效的提示结构
[Subject] + [Action/Pose] + [Environment] + [Style] + [Technical details]
A young woman reading a book in a cozy cafe,
warm afternoon sunlight through windows,
impressionist oil painting style,
soft focus background, golden hour lighting
资源管理
及时下载结果
// Download results before the generated files expire.
const urls = await generateImage(prompt);
// Download immediately
for (const url of urls) {
const response = await fetch(url);
const buffer = await response.arrayBuffer();
// Save to your storage
}
存储任务 ID
// Log task IDs for debugging
console.log(`Task submitted: ${taskId}`);
// Store in database for reference
await db.tasks.create({
taskId,
userId: user.id,
model,
prompt,
status: 'pending',
createdAt: new Date(),
});
成本优化
选择合适的模型
| 使用场景 | 推荐型号 | 备注 |
|---|---|---|
| 原型制作 | Nano Banana | 快速迭代,实现快速反馈 |
| 生产级质量 | 通量-2 Pro | 平衡的保真度和控制 |
| 高端品质 | Midjourney | 强烈的艺术风格 |
| 视频(短) | Wan 2.5 | 高效的短形式生成 |
| 视频(电影) | Sora 2 | 最高端的视频质量 |
有关当前定价,请始终参阅 定价 页面。
批量相似请求
如果生成多个变体,请使用图生图模式,而不是每次都从头开始生成。监控使用情况
// Track costs per user/project
await db.usage.create({
userId: user.id,
model,
cost: MODEL_COSTS[model],
timestamp: new Date(),
});
// Set up alerts for unusual usage
if (dailyCost > threshold) {
sendAlert('High API usage detected');
}
安全
保护您的 API 密钥
// DO: Use environment variables
const apiKey = process.env.APIXO_API_KEY;
// DON'T: Hardcode in source
const apiKey = 'sk-abc123'; // Never do this!
// DON'T: Expose in client-side code
// API calls should go through your backend
验证用户输入
function validatePrompt(prompt) {
if (!prompt || typeof prompt !== 'string') {
throw new Error('Invalid prompt');
}
if (prompt.length > 5000) {
throw new Error('Prompt too long');
}
// Sanitize before sending to API
return prompt.trim();
}
表现
使用连接池
// Reuse HTTP connections
const agent = new https.Agent({ keepAlive: true });
const response = await fetch(url, {
agent,
// ...
});
尽可能并行化
// Generate multiple images in parallel
const prompts = ['prompt1', 'prompt2', 'prompt3'];
const tasks = await Promise.all(
prompts.map(prompt => submitTask(prompt))
);
const results = await Promise.all(
tasks.map(task => pollForResult(task.taskId))
);
监控
记录 API 调用
const startTime = Date.now();
try {
const result = await generateImage(prompt);
logger.info('Generation successful', {
taskId: result.taskId,
duration: Date.now() - startTime,
model,
});
} catch (error) {
logger.error('Generation failed', {
error: error.message,
duration: Date.now() - startTime,
model,
});
}
设置警报
监控:- 高错误率
- 异常延迟
- 成本飙升
- 达到速率限制