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

# Serverless Inference エラー処理のベストプラクティスは何ですか？

W\&B Serverless Inference のエラーを適切に処理し、アプリケーションの信頼性を維持するには、以下のベストプラクティスに従ってください。

<div id="always-implement-error-handling">
  ## 常にエラー処理を実装してください
</div>

API呼び出しは `try-except` ブロックで囲んでください：

```python theme={null}
import openai

try:
    response = client.chat.completions.create(
        model="meta-llama/Llama-3.1-8B-Instruct",
        messages=messages
    )
except Exception as e:
    print(f"Error: {e}")
    # 適切にエラーを処理する
```

<div id="use-retry-logic-with-exponential-backoff">
  ## 指数バックオフによる再試行ロジックを使用する
</div>

試行の間隔を徐々に延ばしながら、一時的な障害を再試行します。

```python theme={null}
import time
from typing import Optional

def call_inference_with_retry(
    client, 
    messages, 
    model: str,
    max_retries: int = 3,
    base_delay: float = 1.0
) -> Optional[str]:
    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model=model,
                messages=messages
            )
            return response.choices[0].message.content
        except Exception as e:
            if attempt == max_retries - 1:
                raise
            
            # 指数バックオフで遅延を計算する
            delay = base_delay * (2 ** attempt)
            print(f"Attempt {attempt + 1} failed, retrying in {delay}s...")
            time.sleep(delay)
    
    return None
```

<div id="monitor-your-usage">
  ## 使用状況を監視する
</div>

* W\&B **Billing** ページでクレジットの使用状況をトラッキングする。
* 制限に達する前にアラートを設定する。
* アプリケーションで API の使用状況をログする。

<div id="handle-specific-error-codes">
  ## 特定のエラーコードに対応する
</div>

```python theme={null}
def handle_inference_error(error):
    error_str = str(error)
    
    if "401" in error_str:
        # 認証が無効です
        raise ValueError("Check your API key and project configuration")
    elif "402" in error_str:
        # クレジット不足
        raise ValueError("Insufficient credits")
    elif "429" in error_str:
        # レート制限中
        return "retry"
    elif "500" in error_str or "503" in error_str:
        # サーバーエラー
        return "retry"
    else:
        # 不明なエラー
        raise
```

<div id="set-appropriate-timeouts">
  ## 適切なタイムアウトを設定する
</div>

用途に応じて適切なタイムアウトを設定します。

```python theme={null}
# 長い応答の場合
client = openai.OpenAI(
    base_url='https://api.inference.wandb.ai/v1',
    api_key="your-api-key",
    timeout=60.0  # 60秒のタイムアウト
)
```

<div id="additional-tips">
  ## 追加のヒント
</div>

* デバッグしやすいよう、タイムスタンプ付きでエラーをログする
* 並行処理をより適切に扱うため、非同期処理を使用する
* 本番システムにはサーキットブレーカーを実装する
* 必要に応じて応答をキャッシュし、API呼び出しを減らす

***

<Badge stroke shape="pill" color="orange" size="md">[Inference](/ja/support/models/tags/inference)</Badge>
