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

1. 常にエラー処理を実装してください

API呼び出しは try-except ブロックで囲んでください:
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}")
    # 適切にエラーを処理する

2. 指数バックオフを使用したリトライロジックを使用する

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 + 1} 失敗、{delay}秒後に再試行します...")
            time.sleep(delay)
    
    return None

3. 使用状況を監視する

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

4. 特定のエラーコードを処理する

def handle_inference_error(error):
    error_str = str(error)
    
    if "401" in error_str:
        # 認証が無効です
        raise ValueError("APIキーとプロジェクトの設定を確認してください")
    elif "402" in error_str:
        # クレジット不足
        raise ValueError("クレジットが不足しています")
    elif "429" in error_str:
        # レート制限中
        return "retry"
    elif "500" in error_str or "503" in error_str:
        # サーバーエラー
        return "retry"
    else:
        # 不明なエラー
        raise

5. 適切なタイムアウトを設定する

用途に応じて適切なタイムアウトを設定します。
# 長いレスポンスの場合
client = openai.OpenAI(
    base_url='https://api.inference.wandb.ai/v1',
    api_key="your-api-key",
    timeout=60.0  # 60秒のタイムアウト
)

追加のヒント

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

Inference