> ## 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 の信頼性、コスト管理、エラー処理パターン。

非同期統合を運用環境に導入する前に、次の 3 つの結果をテストしてください。

1. **送信後にワーカーが再起動した場合**：モデルとタスク ID を永続化し、次のワーカーが[ポーリングを再開](https://apixo.ai/docs/ja/api-reference/status-task.md)できるようにします。
2. **完了通知が 2 回届いた場合**：タスク ID で重複を判定し、結果を 1 回だけ処理します。[Webhook の冪等処理](https://apixo.ai/docs/ja/api-reference/webhooks.md#implement-idempotency)を参照してください。
3. **タスクは `failed` に達します。** 失敗コードとメッセージをログに記録し、再試行する前に [エラーを分類します](https://apixo.ai/docs/ja/api-reference/errors.md)。無効な入力には修正リクエストが必要です。

## リクエストモードの選択

以下の再試行ロジックを実装する前に、[ポーリングと Webhook の比較](https://apixo.ai/docs/ja/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 | 素早いフィードバックのための素早い反復 |
| 生産品質 | Flux-2 プロ | バランスの取れた忠実度とコントロール |
| プレミアム品質 | 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.