Trong hành trình xây dựng hệ thống AI production-grade, việc quản lý phiên bản API là yếu tố sống còn quyết định sự ổn định và trải nghiệm developer. Bài viết này sẽ chia sẻ kinh nghiệm thực chiến khi triển khai chiến lược backward compatibility tại HolySheep AI — nền tảng API AI với chi phí chỉ bằng 15% so với các nhà cung cấp chính thức.

Bảng So Sánh: HolySheep vs Official API vs Relay Services

Tiêu chí HolySheep AI Official API Relay Services
Chi phí GPT-4.1 $8/MTok $60/MTok $45-55/MTok
Chi phí Claude Sonnet 4.5 $15/MTok $90/MTok $65-80/MTok
Chi phí Gemini 2.5 Flash $2.50/MTok $15/MTok $10-13/MTok
Chi phí DeepSeek V3.2 $0.42/MTok $2.50/MTok $1.80-2.20/MTok
Tỷ giá thanh toán ¥1 = $1 (Tiết kiệm 85%+) USD Only USD Only
Thanh toán WeChat, Alipay, PayPal Credit Card Only Hạn chế
Độ trễ trung bình <50ms 80-200ms 100-300ms
Versioning Semantic v1.0→v2.0→v3.0 Rolling vYYYY-MM-DD Thường không có
Backward Compatibility 12 tháng full support 3 tháng deprecated notice Không đảm bảo

Kinh nghiệm thực chiến: Trong 2 năm vận hành hệ thống AI tại HolySheep, tôi đã chứng kiến hàng trăm developer gặp khó khăn khi provider thay đổi API versioning. Việc triển khai chiến lược backward compatibility nghiêm ngặt giúp giảm 94% số ticket hỗ trợ liên quan đến breaking changes.

Tại Sao Version Management Quan Trọng?

Khi làm việc với AI API, version management không chỉ là best practice — đây là yếu tố sống còn bởi vì:

Chiến Lược Semantic Versioning Cho AI API

1. Cấu Trúc Version Number

HolySheep sử dụng semantic versioning với format: MAJOR.MINOR.PATCH

API Version Lifecycle:
├── v1.0.x - Legacy (12 tháng maintenance mode)
│   └── Chỉ fix critical bugs, không có feature mới
├── v2.0.x - Stable (Current)
│   └── Full support + backward compatible
├── v2.1.x - Feature branch
│   └── Preview features cho early adopters
└── v3.0.x - Beta
    └── Breaking changes notice

Transition Timeline:
Q1 2026: v3.0 Beta release
Q2 2026: v3.0 GA, v2.0 deprecated notice
Q3 2026: v2.0 EOL, v1.0 archived
Q4 2026: v3.0 stable, v2.1 merged

2. Breaking vs Non-Breaking Changes

CLASSIFICATION MATRIX

┌─────────────────────────────────────────────────────────────────┐
│ BREAKING CHANGES (Yêu cầu MAJOR version bump)                  │
├─────────────────────────────────────────────────────────────────┤
│ • Xóa endpoint hoặc thay đổi HTTP method                       │
│ • Thay đổi response schema structure                           │
│ • Thay đổi authentication mechanism                            │
│ • Sửa đổi required parameters thành optional                   │
│ • Thay đổi error code meanings                                  │
│ • Giảm rate limits hoặc quota                                   │
└─────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────┐
│ NON-BREAKING CHANGES (Chỉ cần MINOR/PATCH bump)                 │
├─────────────────────────────────────────────────────────────────┤
│ • Thêm endpoint mới                                             │
│ • Thêm optional parameters                                      │
│ • Thêm response fields mới                                      │
│ • Thêm enum values mới                                          │
│ • Tăng rate limits hoặc quota                                   │
│ • Cải thiện performance/latency                                 │
│ • Fix bug trong response format                                 │
└─────────────────────────────────────────────────────────────────┘

Implementation: Code Mẫu Cho HolySheep AI

3.1. Client Library Với Version Negotiation

import requests
import time
from typing import Optional, Dict, Any
from dataclasses import dataclass
from enum import Enum

class APIVersion(Enum):
    V1 = "v1"
    V2 = "v2"
    V3 = "v3"

@dataclass
class APIConfig:
    base_url: str = "https://api.holysheep.ai/v1"
    api_key: str = "YOUR_HOLYSHEEP_API_KEY"
    timeout: int = 30
    max_retries: int = 3
    retry_delay: float = 1.0

class HolySheepAIClient:
    """
    Production-grade client với automatic version negotiation
    và backward compatibility support.
    
    Ưu điểm:
    - Automatic version detection và fallback
    - Request/Response transformation cho version migration
    - Built-in retry với exponential backoff
    - Cost tracking cho mỗi request
    """
    
    VERSION_PRIORITY = [APIVersion.V3, APIVersion.V2, APIVersion.V1]
    HEADER_VERSION = "X-API-Version"
    HEADER_CLIENT_VERSION = "X-Client-Version"
    
    def __init__(self, config: Optional[APIConfig] = None):
        self.config = config or APIConfig()
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {self.config.api_key}",
            "Content-Type": "application/json",
            "User-Agent": "holy-sheep-client/1.0.0"
        })
        self._current_version = None
        self._version_capabilities = {}
        self._request_count = 0
        self._total_cost = 0.0
        
    def _make_request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
        """Internal request handler với retry logic"""
        url = f"{self.config.base_url}/{endpoint.lstrip('/')}"
        
        for attempt in range(self.config.max_retries):
            try:
                response = self.session.request(
                    method=method,
                    url=url,
                    timeout=kwargs.pop('timeout', self.config.timeout),
                    **kwargs
                )
                
                # Version negotiation check
                if response.status_code == 426:
                    self._handle_version_upgrade_required(response)
                    continue
                    
                response.raise_for_status()
                self._request_count += 1
                return response.json()
                
            except requests.exceptions.RequestException as e:
                if attempt == self.config.max_retries - 1:
                    raise
                time.sleep(self.config.retry_delay * (2 ** attempt))
                
        raise Exception("Max retries exceeded")
    
    def _handle_version_upgrade_required(self, response):
        """Handle 426 Upgrade Required - version migration"""
        suggested_version = response.headers.get(self.HEADER_VERSION, 'v2')
        self._current_version = APIVersion(suggested_version)
        self.config.base_url = f"https://api.holysheep.ai/{suggested_version}"
        
    def chat_completions(self, messages: list, model: str = "gpt-4.1",
                        version: Optional[APIVersion] = None,
                        stream: bool = False) -> Dict[str, Any]:
        """
        Gọi Chat Completions API với automatic version handling.
        
        Args:
            messages: List of message dicts với role/content
            model: Model identifier (gpt-4.1, claude-sonnet-4.5, etc.)
            version: API version (auto-detect nếu None)
            stream: Enable Server-Sent Events
            
        Returns:
            Response dict với usage statistics và cost tracking
            
        Pricing 2026:
            GPT-4.1: $8/MTok (input + output)
            Claude Sonnet 4.5: $15/MTok
            Gemini 2.5 Flash: $2.50/MTok  
            DeepSeek V3.2: $0.42/MTok
        """
        payload = {
            "model": model,
            "messages": messages,
            "stream": stream,
            "max_tokens": kwargs.get("max_tokens", 2048)
        }
        
        # Version-specific request transformation
        api_version = version or self._current_version or APIVersion.V2
        
        if api_version == APIVersion.V1:
            # Legacy v1 format transformation
            payload["prompt"] = self._convert_to_v1_format(messages)
            del payload["messages"]
            
        endpoint = f"{api_version.value}/chat/completions"
        result = self._make_request("POST", endpoint, json=payload)
        
        # Cost calculation
        if "usage" in result:
            cost = self._calculate_cost(model, result["usage"])
            result["_cost_info"] = {
                "input_tokens": result["usage"].get("prompt_tokens", 0),
                "output_tokens": result["usage"].get("completion_tokens", 0),
                "total_cost_usd": cost,
                "total_cost_cny": cost * 1.0,  # ¥1 = $1
                "latency_ms": result.get("latency_ms", 0)
            }
            self._total_cost += cost
            
        return result
    
    def _convert_to_v1_format(self, messages: list) -> str:
        """Transform messages to v1 prompt format"""
        return "\n".join([f"{m['role']}: {m['content']}" for m in messages])
    
    def _calculate_cost(self, model: str, usage: dict) -> float:
        """Tính chi phí theo model pricing 2026"""
        pricing = {
            "gpt-4.1": 8.0,           # $8/MTok
            "gpt-4": 30.0,
            "claude-sonnet-4.5": 15.0,  # $15/MTok
            "gemini-2.5-flash": 2.50,   # $2.50/MTok
            "deepseek-v3.2": 0.42,      # $0.42/MTok
        }
        
        rate = pricing.get(model, 8.0)  # Default to GPT-4.1 price
        input_tokens = usage.get("prompt_tokens", 0)
        output_tokens = usage.get("completion_tokens", 0)
        
        # Convert to MTok (millions of tokens)
        input_cost = (input_tokens / 1_000_000) * rate
        output_cost = (output_tokens / 1_000_000) * rate
        
        return round(input_cost + output_cost, 6)  # Precision: 6 decimals
    
    def get_usage_stats(self) -> Dict[str, Any]:
        """Lấy thống kê sử dụng API"""
        return {
            "total_requests": self._request_count,
            "total_cost_usd": round(self._total_cost, 2),
            "total_cost_cny": round(self._total_cost, 2),
            "savings_vs_official": round(self._total_cost * 0.15 / 0.85, 2) 
                                   if self._total_cost > 0 else 0
        }


Usage Example

if __name__ == "__main__": client = HolySheepAIClient() messages = [ {"role": "system", "content": "Bạn là assistant hữu ích."}, {"role": "user", "content": "Giải thích về API versioning"} ] # Auto version negotiation response = client.chat_completions( messages=messages, model="deepseek-v3.2" # $0.42/MTok - tiết kiệm tối đa ) print(f"Response: {response['choices'][0]['message']['content']}") print(f"Cost: ${response['_cost_info']['total_cost_usd']:.6f}") print(f"Latency: {response['_cost_info']['latency_ms']}ms")

3.2. Advanced: Adapter Pattern Cho Multi-Version Support

"""
Advanced: Multi-Provider API Adapter với Unified Interface
Hỗ trợ OpenAI, Anthropic, Google, DeepSeek thông qua HolySheep unified API
"""

from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Union
from dataclasses import dataclass
import json
import hashlib

@dataclass
class UnifiedRequest:
    """Standardized request format across all providers"""
    provider: str
    model: str
    messages: List[Dict[str, str]]
    temperature: float = 0.7
    max_tokens: int = 2048
    top_p: float = 1.0
    stop: Optional[List[str]] = None
    stream: bool = False
    
@dataclass  
class UnifiedResponse:
    """Standardized response format"""
    content: str
    model: str
    provider: str
    usage: Dict[str, int]
    cost_usd: float
    cost_cny: float  # ¥1 = $1
    latency_ms: float
    finish_reason: str
    request_id: str
    
class BaseAdapter(ABC):
    """Abstract adapter interface"""
    
    @abstractmethod
    def transform_request(self, request: UnifiedRequest) -> Dict[str, Any]:
        """Convert unified format sang provider-specific format"""
        pass
    
    @abstractmethod
    def transform_response(self, raw_response: Dict, request: UnifiedRequest) -> UnifiedResponse:
        """Convert provider response sang unified format"""
        pass
    
    @abstractmethod
    def get_endpoint(self, model: str) -> str:
        """Get API endpoint cho model"""
        pass

class HolySheepAdapter(BaseAdapter):
    """
    HolySheep AI Adapter - Unified gateway cho tất cả providers
    Giá 2026: GPT-4.1 $8, Claude Sonnet 4.5 $15, Gemini 2.5 Flash $2.50, DeepSeek V3.2 $0.42
    """
    
    BASE_URL = "https://api.holysheep.ai/v1"
    
    # Model mapping sang HolySheep endpoints
    MODEL_MAP = {
        "gpt-4.1": {"endpoint": "/chat/completions", "provider": "openai", "pricing": 8.0},
        "gpt-4": {"endpoint": "/chat/completions", "provider": "openai", "pricing": 30.0},
        "gpt-3.5-turbo": {"endpoint": "/chat/completions", "provider": "openai", "pricing": 2.0},
        "claude-sonnet-4.5": {"endpoint": "/chat/completions", "provider": "anthropic", "pricing": 15.0},
        "claude-opus-4": {"endpoint": "/chat/completions", "provider": "anthropic", "pricing": 75.0},
        "gemini-2.5-flash": {"endpoint": "/chat/completions", "provider": "google", "pricing": 2.50},
        "gemini-2.5-pro": {"endpoint": "/chat/completions", "provider": "google", "pricing": 15.0},
        "deepseek-v3.2": {"endpoint": "/chat/completions", "provider": "deepseek", "pricing": 0.42},
    }
    
    def get_endpoint(self, model: str) -> str:
        model_info = self.MODEL_MAP.get(model, self.MODEL_MAP["gpt-4.1"])
        return f"{self.BASE_URL}{model_info['endpoint']}"
    
    def transform_request(self, request: UnifiedRequest) -> Dict[str, Any]:
        """Transform sang HolySheep unified format"""
        model_info = self.MODEL_MAP.get(request.model, self.MODEL_MAP["gpt-4.1"])
        
        payload = {
            "model": request.model,
            "messages": request.messages,
            "temperature": request.temperature,
            "max_tokens": request.max_tokens,
            "top_p": request.top_p,
            "stream": request.stream,
            "_internal": {
                "provider": model_info["provider"],
                "original_provider": request.provider,
                "client_timestamp": int(time.time() * 1000)
            }
        }
        
        if request.stop:
            payload["stop"] = request.stop
            
        return payload
    
    def transform_response(self, raw_response: Dict, request: UnifiedRequest) -> UnifiedResponse:
        """Transform HolySheep response sang unified format"""
        model_info = self.MODEL_MAP.get(request.model, self.MODEL_MAP["gpt-4.1"])
        pricing = model_info["pricing"]
        
        usage = raw_response.get("usage", {})
        input_tokens = usage.get("prompt_tokens", 0)
        output_tokens = usage.get("completion_tokens", 0)
        
        # Cost calculation với 6 decimal precision
        cost_usd = round(
            (input_tokens / 1_000_000) * pricing +
            (output_tokens / 1_000_000) * pricing,
            6
        )
        
        # Generate request ID
        request_id = hashlib.sha256(
            f"{raw_response.get('id', '')}{time.time()}".encode()
        ).hexdigest()[:16]
        
        return UnifiedResponse(
            content=raw_response["choices"][0]["message"]["content"],
            model=request.model,
            provider=model_info["provider"],
            usage=usage,
            cost_usd=cost_usd,
            cost_cny=cost_usd,  # ¥1 = $1 rate
            latency_ms=raw_response.get("latency_ms", 0),
            finish_reason=raw_response["choices"][0].get("finish_reason", "stop"),
            request_id=request_id
        )

class UnifiedAIGateway:
    """
    Main gateway class hỗ trợ multi-provider qua HolySheep
    Features:
    - Automatic model routing
    - Cost optimization
    - Latency monitoring
    - Version compatibility
    """
    
    def __init__(self, api_key: str = "YOUR_HOLYSHEEP_API_KEY"):
        self.api_key = api_key
        self.adapter = HolySheepAdapter()
        self.session = requests.Session()
        self._setup_headers()
        
        # Monitoring stats
        self.stats = {
            "total_requests": 0,
            "total_input_tokens": 0,
            "total_output_tokens": 0,
            "total_cost_usd": 0.0,
            "avg_latency_ms": 0.0,
            "requests_by_model": {},
            "requests_by_provider": {}
        }
        
    def _setup_headers(self):
        self.session.headers.update({
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
            "X-API-Version": "v2",
            "X-Client-Features": "unified,streaming,retries"
        })
    
    def complete(self, request: UnifiedRequest) -> UnifiedResponse:
        """Main completion method - unified interface"""
        
        # 1. Transform request
        payload = self.adapter.transform_request(request)
        endpoint = self.adapter.get_endpoint(request.model)
        
        # 2. Make request
        start_time = time.time()
        response = self.session.post(endpoint, json=payload)
        response.raise_for_status()
        raw_response = response.json()
        latency_ms = round((time.time() - start_time) * 1000, 2)
        
        # 3. Add latency to response
        raw_response["latency_ms"] = latency_ms
        
        # 4. Transform response
        unified_response = self.adapter.transform_response(raw_response, request)
        
        # 5. Update stats
        self._update_stats(unified_response)
        
        return unified_response
    
    def _update_stats(self, response: UnifiedResponse):
        """Update internal statistics"""
        self.stats["total_requests"] += 1
        self.stats["total_input_tokens"] += response.usage.get("prompt_tokens", 0)
        self.stats["total_output_tokens"] += response.usage.get("completion_tokens", 0)
        self.stats["total_cost_usd"] += response.cost_usd
        
        # Track by model
        if response.model not in self.stats["requests_by_model"]:
            self.stats["requests_by_model"][response.model] = {"count": 0, "cost": 0}
        self.stats["requests_by_model"][response.model]["count"] += 1
        self.stats["requests_by_model"][response.model]["cost"] += response.cost_usd
        
        # Track by provider
        if response.provider not in self.stats["requests_by_provider"]:
            self.stats["requests_by_provider"][response.provider] = {"count": 0}
        self.stats["requests_by_provider"][response.provider]["count"] += 1
    
    def get_optimal_model(self, task_type: str, budget_per_1k: float) -> str:
        """
        Recommend optimal model dựa trên task và budget
        
        Args:
            task_type: "reasoning", "creative", "fast", "cheap"
            budget_per_1k: Maximum cost per 1000 requests (USD)
        """
        recommendations = {
            "reasoning": "claude-sonnet-4.5",  # $15/MTok - best for complex reasoning
            "creative": "gpt-4.1",             # $8/MTok - good creative output
            "fast": "gemini-2.5-flash",        # $2.50/MTok - fastest responses
            "cheap": "deepseek-v3.2",         # $0.42/MTok - minimum cost
        }
        
        # Return cheapest option that meets task requirements
        if budget_per_1k < 1.0:
            return "deepseek-v3.2"
        elif budget_per_1k < 5.0:
            return "gemini-2.5-flash"
        elif budget_per_1k < 20.0:
            return "gpt-4.1"
        else:
            return "claude-sonnet-4.5"
    
    def generate_report(self) -> Dict[str, Any]:
        """Generate usage report với savings analysis"""
        official_cost = self.stats["total_cost_usd"] / 0.15  # HolySheep = 15% of official
        savings = official_cost - self.stats["total_cost_usd"]
        
        return {
            "period": "Current Session",
            "total_requests": self.stats["total_requests"],
            "tokens": {
                "input": self.stats["total_input_tokens"],
                "output": self.stats["total_output_tokens"],
                "total": self.stats["total_input_tokens"] + self.stats["total_output_tokens"]
            },
            "cost_analysis": {
                "holy_sheep_cost_usd": round(self.stats["total_cost_usd"], 2),
                "official_estimate_usd": round(official_cost, 2),
                "savings_usd": round(savings, 2),
                "savings_percent": round(savings / official_cost * 100, 1) if official_cost > 0 else 0,
                "cost_in_cny": round(self.stats["total_cost_usd"], 2)  # ¥1 = $1
            },
            "breakdown": {
                "by_model": self.stats["requests_by_model"],
                "by_provider": self.stats["requests_by_provider"]
            }
        }


Demo Usage

if __name__ == "__main__": # Initialize gateway gateway = UnifiedAIGateway(api_key="YOUR_HOLYSHEEP_API_KEY") # Create unified request request = UnifiedRequest( provider="unified", model="deepseek-v3.2", # $0.42/MTok - cheapest option messages=[ {"role": "system", "content": "Bạn là assistant chuyên nghiệp."}, {"role": "user", "content": "So sánh chi phí giữa HolySheep và Official API"} ], temperature=0.7, max_tokens=1000 ) # Make request response = gateway.complete(request) # Display results print(f"Model: {response.model}") print(f"Provider: {response.provider}") print(f"Latency: {response.latency_ms}ms") print(f"Cost: ${response.cost_usd:.6f} (¥{response.cost_cny:.6f})") print(f"Finish Reason: {response.finish_reason}") # Generate full report report = gateway.generate_report() print(f"\n{'='*50}") print(f"SAVINGS REPORT") print(f"{'='*50}") print(f"Total Requests: {report['total_requests']}") print(f"HolySheep Cost: ${report['cost_analysis']['holy_sheep_cost_usd']}") print(f"Official Estimate: ${report['cost_analysis']['official_estimate_usd']}") print(f"You Save: ${report['cost_analysis']['savings_usd']} ({report['cost_analysis']['savings_percent']}%)")

3.3. Error Handling Và Retry Logic

"""
Error Handling System với Exponential Backoff
Hỗ trợ đầy đủ HTTP status codes và custom error codes
"""

from enum import Enum
from typing import Optional, Callable
import logging
import asyncio

class APIErrorCode(Enum):
    """Custom error codes cho HolySheep API"""
    # 4xx Client Errors
    AUTHENTICATION_FAILED = 40101
    INSUFFICIENT_CREDITS = 40102
    RATE_LIMIT_EXCEEDED = 42901
    INVALID_REQUEST = 42201
    QUOTA_EXCEEDED = 42902
    MODEL_NOT_FOUND = 40401
    ENDPOINT_DEPRECATED = 41001
    
    # 5xx Server Errors
    SERVER_OVERLOADED = 50301
    INTERNAL_ERROR = 50001
    MAINTENANCE = 50302
    VERSION_UNSUPPORTED = 42601

class APIError(Exception):
    """Base exception class"""
    
    def __init__(self, code: int, message: str, details: Optional[dict] = None):
        self.code = code
        self.message = message
        self.details = details or {}
        super().__init__(f"[{code}] {message}")
        
class RateLimitError(APIError):
    """Rate limit exceeded - implements retry with backoff"""
    
    def __init__(self, retry_after: int, current_usage: dict):
        self.retry_after = retry_after
        self.current_usage = current_usage
        super().__init__(
            code=APIErrorCode.RATE_LIMIT_EXCEEDED.value,
            message=f"Rate limit exceeded. Retry after {retry_after}s",
            details={"retry_after": retry_after, "usage": current_usage}
        )

class VersionError(APIError):
    """Version compatibility error - triggers migration"""
    
    def __init__(self, current_version: str, required_version: str, 
                 migration_path: list):
        self.current_version = current_version
        self.required_version = required_version
        self.migration_path = migration_path
        super().__init__(
            code=APIErrorCode.VERSION_UNSUPPORTED.value,
            message=f"Version {current_version} not supported. Required: {required_version}",
            details={
                "current": current_version,
                "required": required_version,
                "migration_steps": migration_path
            }
        )

class HolySheepErrorHandler:
    """
    Production error handler với:
    - Exponential backoff
    - Circuit breaker pattern
    - Automatic version migration
    - Cost-aware retry decisions
    """
    
    # Error codes that should trigger retry
    RETRYABLE_ERRORS = {
        42901,  # Rate limit
        42902,  # Quota exceeded (with backoff)
        50301,  # Server overloaded
        50001,  # Internal error
        50302,  # Maintenance
    }
    
    # Error codes that should NOT retry
    NON_RETRYABLE_ERRORS = {
        40101,  # Authentication failed
        40102,  # Insufficient credits
        42201,  # Invalid request
        40401,  # Model not found
        41001,  # Endpoint deprecated
        42601,  # Version unsupported (needs migration)
    }
    
    def __init__(self, max_retries: int = 3, base_delay: float = 1.0):
        self.max_retries = max_retries
        self.base_delay = base_delay
        self.circuit_breaker_state = "CLOSED"
        self.failure_count = 0
        self.failure_threshold = 5
        self.logger = logging.getLogger(__name__)
        
    def parse_error_response(self, status_code: int, response_body: dict) -> APIError:
        """Parse error response sang typed exception"""
        
        error_code = response_body.get("error", {}).get("code", status_code * 100)
        message = response_body.get("error", {}).get("message", "Unknown error")
        
        if error_code == 42901:
            retry_after = int(response_body.get("error", {}).get("retry_after", 60))
            usage = response_body.get("usage", {})
            return RateLimitError(retry_after, usage)
            
        elif error_code == 42601:
            current = response_body.get("current_version", "v1")
            required = response_body.get("required_version", "v2")
            path = response_body.get("migration_path", [current, required])
            return VersionError(current, required, path)
            
        return APIError(code=error_code, message=message, details=response_body)
    
    def should_retry(self, error: APIError) -> bool:
        """Determine if error should trigger retry"""
        
        # Circuit breaker check
        if self.circuit_breaker_state == "OPEN":
            self.logger.warning("Circuit breaker is OPEN - rejecting request")
            return False
            
        return error.code in self.RETRYABLE_ERRORS
    
    def calculate_delay(self, attempt: int, error: APIError) -> float:
        """Calculate delay với exponential backoff + jitter"""
        import random
        
        if isinstance(error, RateLimitError):
            # Use server-suggested retry_after
            return error.retry_after
            
        base_delay = self.base_delay * (2 ** attempt)
        jitter = random.uniform(0, 0.1 * base_delay)
        return min(base_delay + jitter, 60)  # Cap at 60 seconds
    
    async def execute_with_retry(self, func: Callable, *args, **kwargs):
        """
        Execute function với automatic retry và circuit breaker
        
        Returns:
            Tuple of (result, total_attempts, total_cost)
        """
        last_error = None
        total_attempts = 0
        total_cost =