
2025/12/24
3 分钟阅读
Ruxa AI API 集成最佳实践
集成 Ruxa AI API 的最佳实践 - 错误处理、任务轮询、回调配置和成本优化。
API 认证
安全存储 API Key
// ❌ 不要硬编码
const apiKey = "sk-xxxxx";
// ✅ 使用环境变量
const apiKey = process.env.RUXA_API_KEY;请求头格式
const headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
};任务状态处理
Ruxa AI 使用异步任务模式。创建任务后,需要查询状态获取结果。
任务状态
| 状态 | 描述 |
|---|---|
generating |
任务正在处理中 |
completed |
任务完成,结果可用 |
fail |
任务失败 |
轮询实现
async function pollTaskStatus(taskId, apiKey, maxAttempts = 60) {
const pollInterval = 5000; // 5秒
for (let i = 0; i < maxAttempts; i++) {
const response = await fetch(
`https://api.ruxa.ai/api/v1/tasks/query/${taskId}`,
{
headers: { 'Authorization': `Bearer ${apiKey}` }
}
);
const data = await response.json();
if (data.data.state === 'completed') {
return data.data;
}
if (data.data.state === 'fail') {
throw new Error(data.data.failMsg || '任务失败');
}
// 继续等待
await new Promise(r => setTimeout(r, pollInterval));
}
throw new Error('轮询超时');
}使用回调(推荐)
生产环境推荐使用回调而非轮询:
const response = await fetch('https://api.ruxa.ai/api/v1/tasks/create', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'google/nano-banana',
callBackUrl: 'https://your-app.com/api/webhook',
input: {
prompt: '您的提示词',
output_format: 'png'
}
})
});处理回调
// Next.js API Route 示例
export async function POST(request) {
const data = await request.json();
// 验证任务状态
if (data.state === 'completed') {
// 处理结果
const resultUrls = data.resultUrls;
// 保存或处理图像/视频
} else if (data.state === 'fail') {
// 处理失败
console.error('任务失败:', data.failMsg);
}
return Response.json({ received: true });
}错误处理
响应状态码
| 状态码 | 描述 | 处理方式 |
|---|---|---|
| 200 | 成功 | 正常处理 |
| 401 | 未授权 | 检查 API Key |
| 402 | 积分不足 | 充值账户 |
| 422 | 验证错误 | 检查请求参数 |
| 429 | 速率限制 | 实现退避重试 |
| 500 | 服务器错误 | 重试请求 |
重试逻辑
async function callAPIWithRetry(payload, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch('https://api.ruxa.ai/api/v1/tasks/create', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.RUXA_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
const data = await response.json();
if (data.code === 200) {
return data;
}
// 客户端错误不重试
if (response.status >= 400 && response.status < 500) {
throw new Error(`客户端错误: ${data.message}`);
}
} catch (error) {
if (attempt === maxRetries) throw error;
// 指数退避
await new Promise(r => setTimeout(r, Math.pow(2, attempt) * 1000));
}
}
}成本优化
选择合适的模型
| 用途 | 推荐模型 |
|---|---|
| 快速原型 | google/nano-banana |
| 高质量图像 | google/nano-banana-pro |
| 标清视频 | sora-2 |
| 高清视频 | sora-2-hd |
优化提示词
- 简洁明确的提示词通常效果更好
- 避免过长或冗余的描述
- 测试不同提示词找到最佳效果
安全建议
- 永远不要在客户端暴露 API Key
- 使用服务端代理 API 调用
- 定期轮换 API Key
- 监控异常使用情况
了解更多
作者

分类
更多文章
邮件列表
加入我们的社区
订阅邮件列表,及时获取最新消息和更新


