跳转到主要内容
遵循以下建议,构建稳健、高效的集成。

选择请求模式

ModeBest ForProsCons
Async (Polling)客户端应用、简单脚本易于实现需要轮询逻辑
Callback (Webhooks)生产服务器实时、无需轮询需要公网 endpoint
开发阶段建议使用 async 模式,生产环境可切换到 callback

轮询策略

使用 async 模式时,建议实现智能轮询,兼顾响应速度与效率。

推荐间隔

Model TypeInitial WaitPoll IntervalMax Wait
图像(快速)5s3s2 min
图像(高质量)10s5s3 min
视频60s15s10 min
音频30s10s5 min

指数退避

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.
    }
  }
}

提示词工程

图像生成建议

DoDon’t
具体描述:“金色寻回犬幼犬在秋叶中玩耍”模糊:“一只狗”
注明风格:“水彩画,柔和光线”依赖默认
说明构图:“特写人像,居中”交给随机
使用肯定描述使用否定如”无背景”

有效提示词结构

[主体] + [动作/姿态] + [环境] + [风格] + [技术细节]
示例:
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

资源管理

及时下载结果

// Result URLs expire after 24 hours
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
}

记录 Task 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(),
});

成本优化

选择合适模型

Use CaseRecommended ModelNotes
原型开发Nano Banana快速反馈、迭代
生产级质量Flux-2 Pro平衡质量与控制
高端质量Midjourney强艺术风格
短视频Wan 2.5高效短视频生成
电影级视频Sora 2顶级视频质量
当前定价请参考 Pricing 页面。

批量相似请求

若需生成多种变体,可优先使用 image-to-image 模式,而非每次都从头生成。

监控用量

// 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,
  });
}

设置告警

关注以下指标:
  • 高错误率
  • 异常延迟
  • 成本突增
  • 速率限制触发