AI API を本番環境に統合する際、最大の問題の一つが「依存サービスの障害による連鎖的故障」です。Netflix が提唱した Hystrix パターンは、この問題に対する効果的な解決策ですが、Python 环境下でどのように実装すればよいでしょうか。本稿では、HolySheep AI をバックエンドにした熔断器パターンの実践的実装方法を詳しく解説します。

熔断器パターンとは?

熔断器(Circuit Breaker)パターンは、分散システムにおける障害伝播を防ぐ設計パターンです。電気のブレーカーと同様に、異常検出時に「回路を遮断」し、障害回復後は自動的に「回路を再開」します。

熔断器の3つの状態

HolySheep AI の料金体系とコスト優位性

実装の詳細説明に入る前に、HolySheep AI の料金体系を確認しましょう。2026年現在の市场价格数据显示、HolySheep は显著なコスト優位性を持っています。

主要 AI API 提供者の料金比較(Output 価格)

モデル 提供者 Output 価格 ($/MTok) 月間1000万トークン時のコスト
GPT-4.1 OpenAI $8.00 $80
Claude Sonnet 4.5 Anthropic $15.00 $150
Gemini 2.5 Flash Google $2.50 $25
DeepSeek V3.2 DeepSeek $0.42 $4.20
HolySheep Unified API HolySheep AI ¥1/$1(公式¥7.3比85%節約) 最安値保証

HolySheep AI は ¥1=$1 の為替レートで提供されており、DeepSeek よりも低コストで同一のモデルにアクセスできます。さらに、登録すると無料クレジットがもらえるため、試用段階でのコストリスクがありません。

Python による熔断器の実装

ここからは、Python で熔断器パターンを実装し、HolySheep AI と統合する具体的な方法を説明します。

プロジェクト構成

ai-circuit-breaker/
├── circuit_breaker.py      # 熔断器クラス
├── holysheep_client.py     # HolySheep API クライアント
├── config.py               # 設定ファイル
├── main.py                 # メインアプリケーション
└── requirements.txt        # 依存ライブラリ

熔断器クラスの実装

"""
circuit_breaker.py
熔断器パターンの実装
"""

import time
import threading
from enum import Enum
from typing import Callable, Any, Optional
from dataclasses import dataclass
from functools import wraps


class CircuitState(Enum):
    CLOSED = "closed"        # 正常動作
    OPEN = "open"            # 遮断状態
    HALF_OPEN = "half_open"  # 試験再開状態


@dataclass
class CircuitBreakerConfig:
    failure_threshold: int = 5       # OPEN に遷移する失敗回数
    success_threshold: int = 3        # CLOSED に遷移する成功回数
    timeout: float = 30.0             # OPEN → HALF_OPEN への移行秒数
    expected_exception: type = Exception


class CircuitBreaker:
    """
    熔断器の実装
    障害発生時にサーキットブレーカー一样にリクエストを遮断
    """
    
    def __init__(self, name: str, config: Optional[CircuitBreakerConfig] = None):
        self.name = name
        self.config = config or CircuitBreakerConfig()
        self._state = CircuitState.CLOSED
        self._failure_count = 0
        self._success_count = 0
        self._last_failure_time: Optional[float] = None
        self._lock = threading.RLock()
        
        # 統計情報
        self.total_calls = 0
        self.successful_calls = 0
        self.failed_calls = 0
        self.rejected_calls = 0
    
    @property
    def state(self) -> CircuitState:
        with self._lock:
            if self._state == CircuitState.OPEN:
                # タイムアウト確認
                if self._last_failure_time and \
                   time.time() - self._last_failure_time >= self.config.timeout:
                    self._state = CircuitState.HALF_OPEN
                    self._success_count = 0
            return self._state
    
    def call(self, func: Callable, *args, **kwargs) -> Any:
        """熔断器経由で関数を実行"""
        self.total_calls += 1
        
        if self.state == CircuitState.OPEN:
            self.rejected_calls += 1
            raise CircuitOpenError(
                f"Circuit '{self.name}' is OPEN. Request rejected."
            )
        
        try:
            result = func(*args, **kwargs)
            self._on_success()
            self.successful_calls += 1
            return result
        except self.config.expected_exception as e:
            self._on_failure()
            self.failed_calls += 1
            raise
    
    def _on_success(self):
        """成功時の処理"""
        with self._lock:
            if self._state == CircuitState.HALF_OPEN:
                self._success_count += 1
                if self._success_count >= self.config.success_threshold:
                    self._transition_to_closed()
            elif self._state == CircuitState.CLOSED:
                self._failure_count = 0  # 成功でカウントリセット
    
    def _on_failure(self):
        """失敗時の処理"""
        with self._lock:
            self._failure_count += 1
            self._last_failure_time = time.time()
            
            if self._state == CircuitState.HALF_OPEN:
                self._transition_to_open()
            elif self._state == CircuitState.CLOSED:
                if self._failure_count >= self.config.failure_threshold:
                    self._transition_to_open()
    
    def _transition_to_open(self):
        """OPEN 状態への遷移"""
        self._state = CircuitState.OPEN
        print(f"[CircuitBreaker] '{self.name}' OPEN (failures: {self._failure_count})")
    
    def _transition_to_closed(self):
        """CLOSED 状態への遷移"""
        self._state = CircuitState.CLOSED
        self._failure_count = 0
        self._success_count = 0
        print(f"[CircuitBreaker] '{self.name}' CLOSED (circuit reset)")
    
    def get_stats(self) -> dict:
        """統計情報を取得"""
        return {
            "name": self.name,
            "state": self.state.value,
            "total_calls": self.total_calls,
            "successful_calls": self.successful_calls,
            "failed_calls": self.failed_calls,
            "rejected_calls": self.rejected_calls,
            "success_rate": f"{(self.successful_calls / self.total_calls * 100):.1f}%" if self.total_calls > 0 else "N/A"
        }
    
    def reset(self):
        """熔断器をリセット"""
        with self._lock:
            self._transition_to_closed()
            self.total_calls = 0
            self.successful_calls = 0
            self.failed_calls = 0
            self.rejected_calls = 0


class CircuitOpenError(Exception):
    """熔断器が開いているときに 발생하는エラー"""
    pass


def circuit_breaker(breaker: CircuitBreaker):
    """デコレータ形式で熔断器を適用"""
    def decorator(func: Callable):
        @wraps(func)
        def wrapper(*args, **kwargs):
            return breaker.call(func, *args, **kwargs)
        return wrapper
    return decorator

HolySheep AI クライアントの実装

"""
holysheep_client.py
HolySheep AI API クライアント(熔断器統合版)
"""

import os
import time
import json
from typing import Optional, Dict, Any, List
from circuit_breaker import CircuitBreaker, CircuitBreakerConfig, CircuitOpenError

import requests


class HolySheepAIClient:
    """
    HolySheep AI API クライアント
    熔断器パターンを統合した高可用性設計
    """
    
    BASE_URL = "https://api.holysheep.ai/v1"
    
    def __init__(self, api_key: str, circuit_breaker: Optional[CircuitBreaker] = None):
        self.api_key = api_key
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        })
        
        # 熔断器の初期化
        if circuit_breaker is None:
            circuit_breaker = CircuitBreaker(
                name="holysheep_api",
                config=CircuitBreakerConfig(
                    failure_threshold=5,
                    success_threshold=3,
                    timeout=30.0,
                    expected_exception=Exception
                )
            )
        self.circuit_breaker = circuit_breaker
        
        # レイテンシ追跡
        self.latencies: List[float] = []
        self.max_latency_samples = 1000
    
    def _make_request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
        """
        HTTP リクエストの内部処理
        熔断器経由で実行
        """
        def _request():
            url = f"{self.BASE_URL}{endpoint}"
            response = self.session.request(method, url, **kwargs)
            
            # レイテンシ記録
            latency = response.elapsed.total_seconds() * 1000  # ms
            self.latencies.append(latency)
            if len(self.latencies) > self.max_latency_samples:
                self.latencies.pop(0)
            
            # エラーステータスコードのチェック
            if response.status_code >= 500:
                raise APIError(
                    f"Server Error: {response.status_code}",
                    status_code=response.status_code,
                    response=response.text
                )
            
            if response.status_code >= 400:
                raise APIError(
                    f"Client Error: {response.status_code}",
                    status_code=response.status_code,
                    response=response.text
                )
            
            return response.json()
        
        # 熔断器経由でリクエスト実行
        return self.circuit_breaker.call(_request)
    
    def chat_completions(
        self,
        model: str,
        messages: List[Dict[str, str]],
        temperature: float = 0.7,
        max_tokens: int = 2048,
        **kwargs
    ) -> Dict[str, Any]:
        """
        チャット補完リクエスト
        
        Args:
            model: モデル名(gpt-4.1, claude-sonnet-4.5, gemini-2.5-flash, deepseek-v3.2)
            messages: メッセージリスト
            temperature: 生成温度
            max_tokens: 最大トークン数
        
        Returns:
            API レスポンス
        """
        payload = {
            "model": model,
            "messages": messages,
            "temperature": temperature,
            "max_tokens": max_tokens,
            **kwargs
        }
        
        return self._make_request(
            "POST",
            "/chat/completions",
            json=payload,
            timeout=60.0
        )
    
    def get_average_latency(self) -> float:
        """平均レイテンシを取得(ms)"""
        if not self.latencies:
            return 0.0
        return sum(self.latencies) / len(self.latencies)
    
    def get_p95_latency(self) -> float:
        """P95 レイテンシを取得(ms)"""
        if not self.latencies:
            return 0.0
        sorted_latencies = sorted(self.latencies)
        index = int(len(sorted_latencies) * 0.95)
        return sorted_latencies[index]
    
    def get_circuit_status(self) -> dict:
        """熔断器の状態を取得"""
        return self.circuit_breaker.get_stats()


class APIError(Exception):
    """API エラーを表す例外"""
    def __init__(self, message: str, status_code: int = None, response: str = None):
        super().__init__(message)
        self.status_code = status_code
        self.response = response


使用例

if __name__ == "__main__": # 熔断器のカスタム設定 config = CircuitBreakerConfig( failure_threshold=3, # 3回失敗で OPEN success_threshold=2, # 2回成功で CLOSED timeout=15.0, # 15秒後に HALF_OPEN ) breaker = CircuitBreaker(name="holy_sheep_primary", config=config) client = HolySheepAIClient( api_key="YOUR_HOLYSHEEP_API_KEY", circuit_breaker=breaker ) # 簡単なテスト try: response = client.chat_completions( model="deepseek-v3.2", messages=[{"role": "user", "content": "Hello!"}] ) print(f"Response: {response['choices'][0]['message']['content']}") except CircuitOpenError as e: print(f"Circuit is open: {e}") except APIError as e: print(f"API Error: {e}")

フォールバック机制の実装

"""
fallback_strategy.py
フォールバック戦略の実装
"""

from typing import Callable, Any, Optional, List
from enum import Enum
from dataclasses import dataclass
import logging

logger = logging.getLogger(__name__)


class FallbackStrategy(Enum):
    CASCADE = "cascade"           # 優先度順に試行
    CHEAP_FIRST = "cheap_first"   # 安いモデルから試行
    FAST_FIRST = "fast_first"     # 速いモデルから試行


@dataclass
class ModelConfig:
    name: str
    provider: str
    cost_per_mtok: float          # $/MTok
    typical_latency_ms: float      # 典型的なレイテンシ
    priority: int = 0             # 優先度(高いほど先)


class FallbackManager:
    """
    フォールバック戦略を管理するクラス
    プライマリが失敗した場合に代替モデルにフォールバック
    """
    
    def __init__(
        self,
        client,  # HolySheepAIClient
        strategy: FallbackStrategy = FallbackStrategy.CASCADE
    ):
        self.client = client
        self.strategy = strategy
        self.models: List[ModelConfig] = []
    
    def add_model(self, config: ModelConfig):
        """モデルを追加"""
        self.models.append(config)
        self._sort_models()
    
    def _sort_models(self):
        """戦略に基づいてモデルをソート"""
        if self.strategy == FallbackStrategy.CASCADE:
            self.models.sort(key=lambda x: x.priority, reverse=True)
        elif self.strategy == FallbackStrategy.CHEAP_FIRST:
            self.models.sort(key=lambda x: x.cost_per_mtok)
        elif self.strategy == FallbackStrategy.FAST_FIRST:
            self.models.sort(key=lambda x: x.typical_latency_ms)
    
    def execute_with_fallback(
        self,
        messages: List[Dict[str, str]],
        fallback_handler: Optional[Callable] = None
    ) -> Any:
        """
        フォールバック付きでリクエストを実行
        
        Args:
            messages: チャットメッセージ
            fallback_handler: すべてのモデルが失敗した場合のハンドラ
        
        Returns:
            成功したレスポンス
        """
        errors = []
        
        for model in self.models:
            try:
                logger.info(f"Trying model: {model.name}")
                
                # 熔断器の状態を確認
                circuit_status = self.client.get_circuit_status()
                if circuit_status["state"] == "open":
                    logger.warning(f"Circuit is open for {model.name}")
                    errors.append(f"Circuit open: {model.name}")
                    continue
                
                response = self.client.chat_completions(
                    model=model.name,
                    messages=messages
                )
                
                logger.info(f"Success with {model.name}")
                return {
                    "response": response,
                    "model_used": model.name,
                    "cost_per_mtok": model.cost_per_mtok
                }
                
            except Exception as e:
                logger.warning(f"Failed with {model.name}: {e}")
                errors.append(f"{model.name}: {str(e)}")
                continue
        
        # すべてのモデルが失敗した場合
        if fallback_handler:
            logger.info("All models failed, using fallback handler")
            return fallback_handler(messages)
        
        raise AllModelsFailedError(
            f"All models failed. Errors: {errors}"
        )


class AllModelsFailedError(Exception):
    """すべてのモデルが失敗した場合のエラー"""
    pass


使用例

if __name__ == "__main__": from holysheep_client import HolySheepAIClient from circuit_breaker import CircuitBreaker, CircuitBreakerConfig # HolySheep クライアントの初期化 breaker = CircuitBreaker( name="holysheep_fallback", config=CircuitBreakerConfig(failure_threshold=3, success_threshold=2) ) client = HolySheepAIClient( api_key="YOUR_HOLYSHEEP_API_KEY", circuit_breaker=breaker ) # フォールバックマネージャの設定 manager = FallbackManager( client=client, strategy=FallbackStrategy.CHEAP_FIRST # 安いモデル優先 ) # モデルの追加(HolySheep が提供するモデル) manager.add_model(ModelConfig( name="deepseek-v3.2", provider="DeepSeek", cost_per_mtok=0.42, # $0.42/MTok typical_latency_ms=800, priority=1 )) manager.add_model(ModelConfig( name="gemini-2.5-flash", provider="Google", cost_per_mtok=2.50, # $2.50/MTok typical_latency_ms=400, priority=2 )) # フォールバック付きで実行 try: result = manager.execute_with_fallback([ {"role": "user", "content": "Explain quantum computing in simple terms"} ]) print(f"Used model: {result['model_used']}") print(f"Cost: ${result['cost_per_mtok']}/MTok") print(f"Response: {result['response']['choices'][0]['message']['content'][:100]}...") except AllModelsFailedError as e: print(f"All models failed: {e}")

HolySheep AI の統合ポイント

HolySheep AI を熔断器システムに統合する理由は以下の通りです:

機能 HolySheep の魅力 競合比較
為替レート ¥1=$1(公式¥7.3比85%節約) 他社は¥7.3=$1
レイテンシ <50ms(アジアリージョン最適化) 海外APIは150-300ms
決済方法 WeChat Pay / Alipay対応 多くはクレジットカードのみ
モデル統一 1つのAPIで複数モデルにアクセス 提供者ごとに個別API
初期コスト 登録で無料クレジット付与 有料のみ

向いている人・向いていない人

向いている人

向いていない人

価格とROI

月間1000万トークンを使用するシナリオで、HolySheep AI のコスト優位性を検証しましょう。

提供者のAPI DeepSeek V3.2 コスト HolySheep での同等コスト 月間節約額 年間節約額
DeepSeek 直契約 $4,200($0.42 × 10M) $4,200 $0 $0
OpenAI GPT-4.1 $80,000 $4,200 $75,800 $909,600
Anthropic Claude 4.5 $150,000 $4,200 $145,800 $1,749,600

注目すべき点は、DeepSeek V3.2 モデルを HolySheep 経由で呼び出すことで、DeepSeek 直契約と同等の价格在りながら、アジアリージョンの<50msレイテンシとWeChat Pay/Alipay決済という附加価値をを得られることです。

HolySheep を選ぶ理由

熔断器パターンと HolySheep AI を組み合わせる理由は以下の3点です:

  1. コスト効率:¥1=$1 の為替レートは業界最安水準。DeepSeek V3.2 ($0.42/MTok) が最安値。
  2. 可用性の担保:熔断器パターンで障害時も代替モデルに自動フォールバック。Asia-Pacific リージョンで <50ms 応答。
  3. 運用の簡素化:1つのAPIキーで複数モデル(GPT-4.1, Claude Sonnet 4.5, Gemini 2.5 Flash, DeepSeek V3.2)を統一管理。

実践的な実装例

"""
main.py
実践的な熔断器 + HolySheep 統合のデモ
"""

import time
import logging
from holysheep_client import HolySheepAIClient, APIError
from circuit_breaker import CircuitBreaker, CircuitBreakerConfig, CircuitOpenError
from fallback_strategy import FallbackManager, FallbackStrategy, ModelConfig

ロギングの設定

logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) class AIServiceWithCircuitBreaker: """ 熔断器パターンを統合した AI サービス HolySheep AI をバックエンドに使用 """ def __init__(self, api_key: str): # 熔断器の初期化 self.circuit_breaker = CircuitBreaker( name="holysheep_main", config=CircuitBreakerConfig( failure_threshold=5, # 5回失敗で OPEN success_threshold=2, # 2回成功で CLOSED timeout=30.0, # 30秒後に HALF_OPEN ) ) # HolySheep クライアント self.client = HolySheepAIClient( api_key=api_key, circuit_breaker=self.circuit_breaker ) # フォールバック戦略 self.fallback_manager = FallbackManager( client=self.client, strategy=FallbackStrategy.CHEAP_FIRST ) # 利用可能なモデル(HolySheep が提供するモデル) self.fallback_manager.add_model(ModelConfig( name="deepseek-v3.2", provider="DeepSeek", cost_per_mtok=0.42, typical_latency_ms=800, priority=1 )) self.fallback_manager.add_model(ModelConfig( name="gemini-2.5-flash", provider="Google", cost_per_mtok=2.50, typical_latency_ms=400, priority=2 )) def ask(self, question: str, model: str = "deepseek-v3.2") -> dict: """ AI に質問する Args: question: 質問内容 model: 使用するモデル Returns: 回答とメタデータ """ start_time = time.time() try: response = self.client.chat_completions( model=model, messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": question} ], temperature=0.7, max_tokens=1000 ) latency = (time.time() - start_time) * 1000 return { "success": True, "answer": response['choices'][0]['message']['content'], "model": model, "latency_ms": round(latency, 2), "usage": response.get('usage', {}), "circuit_state": self.client.get_circuit_status()["state"] } except CircuitOpenError as e: logger.error(f"Circuit breaker is OPEN: {e}") # フォールバックを試行 try: fallback_result = self.fallback_manager.execute_with_fallback([ {"role": "user", "content": question} ]) return { "success": True, "answer": fallback_result["response"]['choices'][0]['message']['content'], "model": fallback_result["model_used"], "latency_ms": round((time.time() - start_time) * 1000, 2), "fallback_used": True } except Exception as fallback_error: return { "success": False, "error": str(fallback_error), "fallback_failed": True } except APIError as e: logger.error(f"API Error: {e}") return { "success": False, "error": str(e), "api_error": True } def get_health_report(self) -> dict: """健全性レポートを取得""" circuit_stats = self.client.get_circuit_status() return { "circuit_breaker": circuit_stats, "latency": { "average_ms": round(self.client.get_average_latency(), 2), "p95_ms": round(self.client.get_p95_latency(), 2) }, "recommendation": self._get_recommendation(circuit_stats) } def _get_recommendation(self, stats: dict) -> str: """統計に基づく推奨事項""" if stats["state"] == "open": return "⚠️ 熔断器が開いています。しばらくしてから再試行してください。" success_rate = float(stats["success_rate"].replace("%", "")) if success_rate < 90: return "🔧 成功率低下を検出。モデルの安定性を確認してください。" if stats["rejected_calls"] > 0: return "📊 熔断器による拒否が発生しました。容量规划を確認してください。" return "✅ システム正常に動作中" def demo(): """デモ実行""" print("=" * 60) print("HolySheep AI - 熔断器パターン デモ") print("=" * 60) # 初期化(実際のAPIキーに置き換えてください) api_key = "YOUR_HOLYSHEEP_API_KEY" service = AIServiceWithCircuitBreaker(api_key) # 正常系リクエスト print("\n📝 リクエスト 1: 正常系クエリ") result = service.ask("What is the capital of Japan?") print(f"結果: {result}") print("\n📝 リクエスト 2: 正常系クエリ") result = service.ask("Explain AI circuit breakers in one sentence.") print(f"結果: {result}") # 健全性レポート print("\n📊 システム健全性レポート:") health = service.get_health_report() print(f" - 熔断器状態: {health['circuit_breaker']['state']}") print(f" - 成功率: {health['circuit_breaker']['success_rate']}") print(f" - 平均レイテンシ: {health['latency']['average_ms']}ms") print(f" - P95レイテンシ: {health['latency']['p95_ms']}ms") print(f" - 推奨: {health['recommendation']}") print("\n" + "=" * 60) if __name__ == "__main__": demo()

よくあるエラーと対処法

エラー1:CircuitOpenError - 熔断器が開いている

# 症状
CircuitOpenError: Circuit 'holysheep_main' is OPEN. Request rejected.

原因

- 短期間に連続して API 要求が失敗した - failure_threshold(デフォルト: 5回)を超えた

解決方法

1. 一時的に待機(自動回復を待つ)

import time time.sleep(35) # timeout 設定値 + 5秒

2. 手動で熔断器をリセット(注意:原因調査後に)

circuit_breaker.reset() print("熔断器を手動リセットしました")

3. 熔断器設定の調整(しきい値の緩和)

from circuit_breaker import CircuitBreakerConfig config = CircuitBreakerConfig( failure_threshold=10, # 10回失敗で OPEN(増加) success_threshold=3, # 3回成功で CLOSED timeout=60.0, # 60秒後に HALF_OPEN(長期化) ) breaker = CircuitBreaker(name="holysheep_safe", config=config)

4. フォールバックモデルへの切り替え(推奨)

fallback_result = fallback_manager.execute_with_fallback(messages)

エラー2:AuthenticationError - API キーが無効

# 症状
APIError: Client Error: 401 - {"error": {"message": "Invalid API key", ...}}

原因

- API キーが正しく設定されていない - キーが期限切れまたは無効

解決方法

1. 環境変数としての正しい設定

import os os.environ["HOLYSHEEP_API_KEY"] = "YOUR_HOLYSHEEP_API_KEY"

正しい初期化

client = HolySheepAIClient( api_key=os.environ.get("HOLYSHEEP_API_KEY") )

2. API キーの確認(HolySheep ダッシュボード)

https://www.holysheep.ai/register

から API Keys セクションでキーを確認

3. プレフィックスの確認

HolySheep のキーは "hs-" プレフィックスが必要な場合がある

api_key = "hs-YOUR_HOLYSHEEP_API_KEY"

4. テスト用の簡単な検証

def validate_api_key(api_key: str) -> bool: try: client = HolySheepAIClient(api_key=api_key) response = client.chat_completions( model="deepseek-v3.2", messages=[{"role": "user", "content": "test"}], max_tokens=10 ) return True except Exception as e: print(f"Validation failed: {e}") return False

エラー3:RateLimitError - レート制限を超過

# 症状
APIError: Client Error: 429 - {"error": {"message": "Rate limit exceeded", ...}}

原因

- 分間または日次のリクエスト上限を超えた - アカウントのクォータを使い切った

解決方法

1. リトライロジック(指数バックオフ付き)

import time import random def retry_with_backoff(func, max_retries=3, base_delay=1): for attempt in range(max_retries): try: return func() except APIError as e: if e.status_code == 429 and attempt < max_retries - 1: delay = base_delay * (2 ** attempt) + random.uniform(0, 1) print(f"Rate limited. Retrying in {delay:.1f}s...") time.sleep(delay) else: raise

使用例

result = retry_with_backoff( lambda: client.chat_completions(model="deepseek-v3.2", messages=messages) )

2. レート制限の監視

class RateLimitMonitor: def __init