> ## Documentation Index
> Fetch the complete documentation index at: https://apixo.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# APIXO API 正式環境使用指南

> 優化您的 APIXO 生產整合：重試、逾時、Webhook 可靠性、成本控制和錯誤處理模式。

在將非同步整合投入生產之前，請測試三種可能的結果：

1. **提交後工作程序重啟。** 儲存模型和任務 ID，讓接手的程序可以[繼續輪詢](https://apixo.ai/docs/zh-hant/api-reference/status-task.md)。
2. **同一完成通知送達兩次。** 按任務 ID 去重，確保結果只處理一次。詳見 [Webhook 冪等處理](https://apixo.ai/docs/zh-hant/api-reference/webhooks.md#implement-idempotency)。
3. **任務到達`failed`。** 記錄失敗代碼和訊息，然後[在重試前對錯誤進行分類](https://apixo.ai/docs/zh-hant/api-reference/errors.md)。無效的輸入需要更正的請求。

## 選擇請求模式

在實現以下重試邏輯之前，請使用 [輪詢和 Webhooks 比較](https://apixo.ai/docs/zh-hant/guides/polling-vs-webhooks.md) 來選擇交付方式。

| 模式 | 最適合 | 優點 | 缺點 |
| - | - | - | - |
| **異步（輪詢）** | 客戶端應用程式，簡單腳本 | 易於實作 | 需要輪詢邏輯 |
| **回呼（Webhook）** | 生產伺服器 | 即時，無輪詢 | 需要公共端點 |

> [!NOTE]
>
> 從`async`模式開始進行開發，切換到`callback`進行生產。

## 輪詢策略

對於`async`模式，實施智慧輪詢以平衡回應能力與效率。

### 建議間隔時間

| 型號類型 | 初始等待 | 輪詢間隔 | 最大等待時間 |
| - | - | - | - |
| 影像（快速） | 5s | 3s | 2 分鐘 |
| 影像（品質） | 10s | 5s | 3 分鐘 |
| 影片 | 60s | 15s | 10 分鐘 |
| 音訊 | 30s | 10s | 5 分鐘 |

### 指數退避

```javascript theme={null}
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');
}
```

## 錯誤處理

### 始終處理失敗

```javascript theme={null}
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;
  }
}
```

### 實施重試

```javascript theme={null}
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
```

## 資源管理

### 立即下載生成結果

```javascript theme={null}
// 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

```javascript theme={null}
// 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 | 最高畫質影片 |

> [!NOTE]
>
> 關於當前定價，請始終參閱 [定價](https://apixo.ai/pricing/api) 頁面。

### 批次類似請求

如果產生多個變體，請使用圖生圖模式，而不是每次從頭開始產生。

### 監控使用情況

```javascript theme={null}
// 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 金鑰

```javascript theme={null}
// 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
```

### 驗證使用者輸入

```javascript theme={null}
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();
}
```

## 表現

### 使用連線池

```javascript theme={null}
// Reuse HTTP connections
const agent = new https.Agent({ keepAlive: true });

const response = await fetch(url, {
  agent,
  // ...
});
```

### 儘可能並行化

```javascript theme={null}
// 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 呼叫

```javascript theme={null}
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,
  });
}
```

### 設定警報

監控：

* 高錯誤率
* 異常延遲
* 成本飆升
* 達到速率限制


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.