Tại sao đội ngũ của tôi quyết định chuyển đổi

Trong 18 tháng vận hành hệ thống email thông minh cho một startup thương mại điện tử quy mô vừa, đội ngũ kỹ thuật của tôi đã trải qua một hành trình đầy bài học. Chúng tôi bắt đầu với API chính thức từ một nhà cung cấp lớn, chi trả mức phí $15/MT cho Claude Sonnet, cộng thêm phí relay nội bộ $3/MT — tổng cộng $18 cho mỗi triệu token xử lý. Với khối lượng email 2 triệu email/tháng, hóa đơn hàng tháng lên đến $36,000 chỉ riêng chi phí AI. Điểm bùng phát là khi khách hàng phản hồi về độ trễ phản hồi. Hệ thống của chúng tôi đo được trung bình 340ms từ lúc nhận email đến lúc gửi gợi ý trả lời. Với một nền tảng thương mại điện tử, điều này tạo ra trải nghiệm chậm, và tỷ lệ khách hàng sử dụng tính năng smart reply giảm 40% sau tuần đầu tiên. Sau khi thử nghiệm HolySheep AI với gói dùng thử, kết quả vượt kỳ vọng: tiết kiệm 85%+ chi phí, độ trễ trung bình giảm còn 38ms, và hỗ trợ thanh toán qua WeChat/Alipay giúp đội ngũ kế toán không phải lo về thẻ quốc tế.

Kiến trúc hệ thống email thông minh hiện tại

Trước khi đi vào chi tiết migration, để tôi mô tả kiến trúc mà đội ngũ đã xây dựng. Hệ thống email thông minh của chúng tôi bao gồm ba thành phần chính: Kiến trúc này đòi hỏi API ổn định, chi phí thấp, và độ trễ thấp — ba yếu tố mà HolySheep AI đáp ứng xuất sắc với tỷ giá ¥1=$1 và thời gian phản hồi trung bình dưới 50ms.

Bước 1: Đánh giá hệ thống hiện tại và lập kế hoạch

Trước khi migration, đội ngũ cần thực hiện audit toàn diện. Tôi đã viết một script để đếm số lượng API call và phân tích chi phí hiện tại.
#!/usr/bin/env python3
"""
Audit script cho hệ thống email thông minh
Đếm số lượng request và ước tính chi phí trước khi migration
"""
import json
from datetime import datetime, timedelta
from collections import defaultdict

class EmailAPIAudit:
    def __init__(self):
        self.requests = []
        self.cost_breakdown = {
            'openai': {'gpt-4': 30.0, 'gpt-3.5-turbo': 2.0},  # $/MT input
            'anthropic': {'claude-3-sonnet': 15.0},  # $/MT
            'relay': 3.0  # chi phí relay trung bình
        }
    
    def load_logs(self, log_file):
        """Load API request logs từ hệ thống cũ"""
        with open(log_file, 'r') as f:
            for line in f:
                entry = json.loads(line)
                if entry.get('service') == 'smart_reply':
                    self.requests.append({
                        'timestamp': entry['timestamp'],
                        'model': entry['model'],
                        'input_tokens': entry['input_tokens'],
                        'output_tokens': entry['output_tokens'],
                        'service': entry['service']
                    })
    
    def calculate_current_cost(self):
        """Tính chi phí hiện tại với API và relay"""
        total_cost = 0.0
        model_usage = defaultdict(int)
        
        for req in self.requests:
            model = req['model']
            service = req['service']
            
            if 'gpt-4' in model:
                cost = self.cost_breakdown['openai']['gpt-4']
            elif 'claude' in model:
                cost = self.cost_breakdown['anthropic']['claude-3-sonnet']
            else:
                cost = self.cost_breakdown['openai']['gpt-3.5-turbo']
            
            tokens = req['input_tokens'] + req['output_tokens']
            total_cost += (tokens / 1_000_000) * (cost + self.cost_breakdown['relay'])
            model_usage[model] += tokens
        
        return {
            'total_monthly_cost_usd': total_cost,
            'model_usage_breakdown': dict(model_usage),
            'total_requests': len(self.requests)
        }
    
    def estimate_holy_sheep_cost(self):
        """Ước tính chi phí với HolySheep AI - giá rẻ hơn 85%"""
        holy_sheep_pricing = {
            'gpt-4.1': 8.0,
            'claude-sonnet-4.5': 15.0,
            'gemini-2.5-flash': 2.50,
            'deepseek-v3.2': 0.42
        }
        
        total_holy_sheep = 0.0
        for req in self.requests:
            model = req['model']
            tokens = req['input_tokens'] + req['output_tokens']
            
            # Map model cũ sang model tương đương trên HolySheep
            if 'gpt-4' in model:
                mapped_model = 'gpt-4.1'
            elif 'claude' in model:
                mapped_model = 'claude-sonnet-4.5'
            elif 'claude-sonnet-4.5' in model:
                mapped_model = 'claude-sonnet-4.5'
            else:
                mapped_model = 'deepseek-v3.2'  # fallback
            
            rate = holy_sheep_pricing.get(mapped_model, 8.0)
            total_holy_sheep += (tokens / 1_000_000) * rate
        
        return {
            'holy_sheep_monthly_usd': total_holy_sheep,
            'savings_percentage': ((self.calculate_current_cost()['total_monthly_cost_usd'] - total_holy_sheep) / 
                                   self.calculate_current_cost()['total_monthly_cost_usd'] * 100)
        }

Sử dụng

audit = EmailAPIAudit() audit.load_logs('/var/logs/email_api_30days.json') current = audit.calculate_current_cost() holy_sheep = audit.estimate_holy_sheep_cost() print(f"Chi phí hiện tại: ${current['total_monthly_cost_usd']:.2f}/tháng") print(f"Ước tính HolySheep: ${holy_sheep['holy_sheep_monthly_usd']:.2f}/tháng") print(f"Tiết kiệm: {holy_sheep['savings_percentage']:.1f}%")
Kết quả audit cho thấy đội ngũ đang chi $36,400/tháng và ước tính với HolySheep AI chỉ còn $4,850/tháng — tiết kiệm 86.7%. Con số này đã thuyết phục ban lãnh đạo phê duyệt dự án migration.

Bước 2: Thiết lập môi trường HolySheep AI

Sau khi đăng ký và nhận tín dụng miễn phí từ HolySheep AI, bước đầu tiên là cấu hình client và kiểm tra kết nối. Dưới đây là implementation hoàn chỉnh.
#!/usr/bin/env python3
"""
HolySheep AI Email Smart Reply Client
Migration từ API cũ sang HolySheep với chi phí thấp hơn 85%
"""
import httpx
import json
import asyncio
from typing import List, Dict, Optional
from dataclasses import dataclass
from datetime import datetime
import hashlib

@dataclass
class EmailContext:
    """Ngữ cảnh email để model xử lý"""
    sender: str
    subject: str
    body: str
    previous_conversation: List[Dict] = None
    tone: str = "professional"  # professional, casual, formal
    
    def to_prompt(self) -> str:
        conversation = ""
        if self.previous_conversation:
            for msg in self.previous_conversation[-3:]:
                role = "Người gửi" if msg['role'] == 'user' else "Bạn"
                conversation += f"{role}: {msg['content']}\n"
        
        return f"""Bạn là trợ lý viết email chuyên nghiệp. Dựa trên nội dung email sau:
        
Người gửi: {self.sender}
Chủ đề: {self.subject}
Nội dung: {self.body}

Lịch sử trò chuyện gần đất:
{conversation}

Hãy tạo 3 gợi ý trả lời ngắn gọn (dưới 50 từ mỗi gợi ý) với giọng điệu {self.tone}.
Trả lời dưới dạng JSON array với cấu trúc: [{{"text": "...", "sentiment": "positive/neutral/negative"}}]"""


class HolySheepEmailClient:
    """
    Client tương thích để gọi HolySheep AI cho email smart reply
    base_url: https://api.holysheep.ai/v1 (KHÔNG dùng api.openai.com)
    """
    
    BASE_URL = "https://api.holysheep.ai/v1"
    
    def __init__(self, api_key: str, organization_id: Optional[str] = None):
        self.api_key = api_key
        self.organization_id = organization_id
        self.client = httpx.AsyncClient(
            base_url=self.BASE_URL,
            timeout=30.0,
            headers=self._build_headers()
        )
        self.request_stats = {
            'total_requests': 0,
            'total_tokens': 0,
            'total_cost_usd': 0.0,
            'avg_latency_ms': 0.0
        }
    
    def _build_headers(self) -> Dict[str, str]:
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }
        if self.organization_id:
            headers["OpenAI-Organization"] = self.organization_id
        return headers
    
    async def generate_smart_replies(
        self, 
        email: EmailContext,
        model: str = "deepseek-v3.2",  # Model giá rẻ nhất, $0.42/MT
        temperature: float = 0.7
    ) -> List[Dict]:
        """
        Sinh các gợi ý trả lời email
        
        Args:
            email: EmailContext chứa thông tin email
            model: Model sử dụng (recommend deepseek-v3.2 cho cost-effective)
            temperature: Độ sáng tạo của response (0.0 - 2.0)
        
        Returns:
            List of smart reply suggestions
        """
        start_time = datetime.now()
        
        payload = {
            "model": model,
            "messages": [
                {"role": "system", "content": "Bạn là trợ lý viết email chuyên nghiệp. Trả lời ngắn gọn, lịch sự."},
                {"role": "user", "content": email.to_prompt()}
            ],
            "temperature": temperature,
            "max_tokens": 500,
            "stream": False
        }
        
        try:
            response = await self.client.post("/chat/completions", json=payload)
            response.raise_for_status()
            data = response.json()
            
            latency_ms = (datetime.now() - start_time).total_seconds() * 1000
            
            self._update_stats(data, latency_ms)
            
            content = data['choices'][0]['message']['content']
            
            # Parse JSON response
            if content.strip().startswith('['):
                return json.loads(content)
            else:
                # Fallback: tạo structure từ text
                return [
                    {"text": content, "sentiment": "neutral"}
                ]
                
        except httpx.HTTPStatusError as e:
            raise HolySheepAPIError(f"HTTP {e.response.status_code}: {e.response.text}")
        except Exception as e:
            raise HolySheepAPIError(f"Request failed: {str(e)}")
    
    def _update_stats(self, response_data: Dict, latency_ms: float):
        """Cập nhật thống kê sử dụng"""
        usage = response_data.get('usage', {})
        tokens = usage.get('total_tokens', 0)
        
        # Tính chi phí theo bảng giá HolySheep 2026
        pricing = {
            'gpt-4.1': 8.0,
            'claude-sonnet-4.5': 15.0,
            'gemini-2.5-flash': 2.50,
            'deepseek-v3.2': 0.42
        }
        
        model = response_data.get('model', 'deepseek-v3.2')
        rate = pricing.get(model, 8.0)
        cost = (tokens / 1_000_000) * rate
        
        self.request_stats['total_requests'] += 1
        self.request_stats['total_tokens'] += tokens
        self.request_stats['total_cost_usd'] += cost
        
        # EMA cho latency
        alpha = 0.1
        current_avg = self.request_stats['avg_latency_ms']
        self.request_stats['avg_latency_ms'] = alpha * latency_ms + (1 - alpha) * current_avg
    
    def get_stats(self) -> Dict:
        """Lấy thống kê sử dụng"""
        return {
            **self.request_stats,
            'cost_per_million_tokens_usd': (
                self.request_stats['total_cost_usd'] / 
                (self.request_stats['total_tokens'] / 1_000_000)
                if self.request_stats['total_tokens'] > 0 else 0
            )
        }
    
    async def close(self):
        await self.client.aclose()


class HolySheepAPIError(Exception):
    """Custom exception cho HolySheep API errors"""
    pass


Ví dụ sử dụng

async def main(): client = HolySheepEmailClient( api_key="YOUR_HOLYSHEEP_API_KEY" # Thay bằng API key thực ) email = EmailContext( sender="[email protected]", subject="Yêu cầu hoàn tiền đơn hàng #12345", body="Tôi đã đặt hàng 2 ngày trước nhưng chưa nhận được. " "Xin hoàn tiền cho đơn hàng này. Cảm ơn!", tone="professional" ) try: replies = await client.generate_smart_replies(email) print("Gợi ý trả lời:") for i, reply in enumerate(replies, 1): print(f"{i}. {reply['text']}") print(f"\nThống kê: {client.get_stats()}") finally: await client.close() if __name__ == "__main__": asyncio.run(main())
Điểm quan trọng cần lưu ý: base_url luôn là https://api.holysheep.ai/v1, không phải api.openai.com. API endpoint /chat/completions hoàn toàn tương thích với OpenAI SDK nhưng chạy trên hạ tầng HolySheep với chi phí thấp hơn đáng kể.

Bước 3: Chiến lược migration và zero-downtime deployment

Migration hệ thống production đòi hỏi chiến lược cẩn thận để tránh gián đoạn dịch vụ. Đội ngũ của tôi đã áp dụng blue-green deployment kết hợp feature flag.
#!/usr/bin/env python3
"""
Migration Manager - Zero-downtime migration từ API cũ sang HolySheep
Sử dụng feature flag để điều phối traffic
"""
import asyncio
import random
from enum import Enum
from typing import Callable, Dict, Any, Optional
from dataclasses import dataclass
from datetime import datetime
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class APIService(Enum):
    OLD_RELAY = "old_relay"
    HOLYSHEEP = "holy_sheep"


@dataclass
class MigrationConfig:
    """Cấu hình migration với các giai đoạn"""
    initial_holy_sheep_percentage: float = 0.05  # 5% ban đầu
    ramp_up_increment: float = 0.10  # Tăng 10% mỗi lần
    ramp_up_interval_hours: int = 4
    health_check_interval_seconds: int = 60
    error_threshold_percentage: float = 5.0  # Rollback nếu lỗi > 5%
    latency_threshold_ms: float = 200.0


class MigrationManager:
    """
    Quản lý quá trình migration với health checks và automatic rollback
    """
    
    def __init__(
        self,
        old_service: Callable,
        new_service: Callable,
        config: MigrationConfig = None
    ):
        self.config = config or MigrationConfig()
        self.old_service = old_service
        self.new_service = new_service
        self.holy_sheep_percentage = self.config.initial_holy_sheep_percentage
        
        self.metrics = {
            'total_requests': 0,
            'holy_sheep_requests': 0,
            'old_service_requests': 0,
            'holy_sheep_errors': 0,
            'old_service_errors': 0,
            'holy_sheep_latencies': [],
            'old_service_latencies': []
        }
        
        self.migration_state = {
            'is_migrating': False,
            'current_phase': 'idle',
            'started_at': None,
            'last_health_check': None
        }
    
    async def route_request(self, email_context: Any) -> Dict:
        """
        Route request tới service phù hợp dựa trên feature flag
        """
        self.metrics['total_requests'] += 1
        use_holy_sheep = random.random() < self.holy_sheep_percentage
        
        if use_holy_sheep:
            return await self._call_holy_sheep(email_context)
        else:
            return await self._call_old_service(email_context)
    
    async def _call_holy_sheep(self, email_context: Any) -> Dict:
        """Gọi HolySheep với error handling và latency tracking"""
        start_time = datetime.now()
        self.metrics['holy_sheep_requests'] += 1
        
        try:
            result = await self.new_service(email_context)
            latency_ms = (datetime.now() - start_time).total_seconds() * 1000
            self.metrics['holy_sheep_latencies'].append(latency_ms)
            
            return {
                'service': APIService.HOLYSHEEP,
                'result': result,
                'latency_ms': latency_ms,
                'success': True
            }
        except Exception as e:
            self.metrics['holy_sheep_errors'] += 1
            logger.error(f"HolySheep error: {e}")
            
            # Fallback về service cũ
            return await self._call_old_service(email_context, fallback=True)
    
    async def _call_old_service(self, email_context: Any, fallback: bool = False) -> Dict:
        """Gọi service cũ (fallback hoặc primary)"""
        start_time = datetime.now()
        self.metrics['old_service_requests'] += 1
        
        try:
            result = await self.old_service(email_context)
            latency_ms = (datetime.now() - start_time).total_seconds() * 1000
            self.metrics['old_service_latencies'].append(latency_ms)
            
            return {
                'service': APIService.OLD_RELAY,
                'result': result,
                'latency_ms': latency_ms,
                'success': True,
                'is_fallback': fallback
            }
        except Exception as e:
            self.metrics['old_service_errors'] += 1
            logger.error(f"Old service error: {e}")
            raise
    
    def _calculate_error_rate(self, service: APIService) -> float:
        """Tính tỷ lệ lỗi của service"""
        if service == APIService.HOLYSHEEP:
            total = self.metrics['holy_sheep_requests']
            errors = self.metrics['holy_sheep_errors']
        else:
            total = self.metrics['old_service_requests']
            errors = self.metrics['old_service_errors']
        
        return (errors / total * 100) if total > 0 else 0.0
    
    def _calculate_avg_latency(self, latencies: list) -> float:
        """Tính latency trung bình"""
        return sum(latencies) / len(latencies) if latencies else 0.0
    
    def health_check(self) -> Dict:
        """
        Kiểm tra sức khỏe của cả hai service
        Quyết định có tiếp tục migration hay rollback
        """
        holy_sheep_error_rate = self._calculate_error_rate(APIService.HOLYSHEEP)
        holy_sheep_latency = self._calculate_avg_latency(
            self.metrics['holy_sheep_latencies'][-100:]  # 100 request gần nhất
        )
        
        health = {
            'timestamp': datetime.now().isoformat(),
            'holy_sheep_percentage': f"{self.holy_sheep_percentage * 100:.1f}%",
            'holy_sheep_error_rate': f"{holy_sheep_error_rate:.2f}%",
            'holy_sheep_avg_latency_ms': f"{holy_sheep_latency:.1f}",
            'status': 'healthy',
            'recommendation': 'continue'
        }
        
        # Check nếu cần rollback
        if holy_sheep_error_rate > self.config.error_threshold_percentage:
            health['status'] = 'critical'
            health['recommendation'] = 'rollback'
            health['reason'] = f"Lỗi {holy_sheep_error_rate:.2f}% vượt ngưỡng {self.config.error_threshold_percentage}%"
        
        elif holy_sheep_latency > self.config.latency_threshold_ms:
            health['status'] = 'warning'
            health['recommendation'] = 'monitor'
            health['reason'] = f"Latency {holy_sheep_latency:.1f}ms cao hơn ngưỡng"
        
        self.migration_state['last_health_check'] = health
        return health
    
    def should_rollback(self) -> bool:
        """Kiểm tra điều kiện rollback tự động"""
        health = self.health_check()
        return health['recommendation'] == 'rollback'
    
    def should_continue(self) -> bool:
        """Kiểm tra điều kiện tiếp tục migration"""
        health = self.health_check()
        return health['recommendation'] == 'continue' and self.holy_sheep_percentage < 1.0
    
    def increase_traffic(self):
        """Tăng traffic sang HolySheep"""
        if self.holy_sheep_percentage < 1.0:
            self.holy_sheep_percentage = min(
                1.0,
                self.holy_sheep_percentage + self.config.ramp_up_increment
            )
            logger.info(f"Tăng HolySheep traffic lên {self.holy_sheep_percentage * 100:.0f}%")
    
    def get_migration_report(self) -> Dict:
        """Lấy báo cáo migration"""
        return {
            'current_traffic_split': {
                'holy_sheep': f"{self.holy_sheep_percentage * 100:.1f}%",
                'old_service': f"{(1 - self.holy_sheep_percentage) * 100:.1f}%"
            },
            'request_counts': self.metrics,
            'error_rates': {
                'holy_sheep': f"{self._calculate_error_rate(APIService.HOLYSHEEP):.2f}%",
                'old_service': f"{self._calculate_error_rate(APIService.OLD_RELAY):.2f}%"
            },
            'avg_latencies': {
                'holy_sheep_ms': self._calculate_avg_latency(self.metrics['holy_sheep_latencies']),
                'old_service_ms': self._calculate_avg_latency(self.metrics['old_service_latencies'])
            },
            'migration_state': self.migration_state
        }


Ví dụ sử dụng trong production

async def example_usage(): # Mock services async def old_email_service(ctx): await asyncio.sleep(0.3) # Latency cao return {"reply": "Cảm ơn bạn đã liên hệ!", "model": "old"} async def holy_sheep_email_service(ctx): from your_module import HolySheepEmailClient client = HolySheepEmailClient(api_key="YOUR_HOLYSHEEP_API_KEY") try: replies = await client.generate_smart_replies(ctx) return {"replies": replies, "model": "holy_sheep"} finally: await client.close() # Khởi tạo migration manager manager = MigrationManager( old_service=old_email_service, new_service=holy_sheep_email_service ) # Bắt đầu migration manager.migration_state['is_migrating'] = True # Simulation: xử lý 1000 requests for i in range(1000): email = {"subject": f"Test email {i}", "body": "Nội dung test"} result = await manager.route_request(email) # Health check mỗi 100 requests if i % 100 == 0: report = manager.get_migration_report() print(f"Request #{i}: {report['current_traffic_split']}") if manager.should_rollback(): print("⚠️ AUTOMATIC ROLLBACK TRIGGERED") break if manager.should_continue() and i > 200: manager.increase_traffic() print("\nMigration Report:") print(manager.get_migration_report()) if __name__ == "__main__": asyncio.run(example_usage())
Chiến lược này cho phép đội ngũ kiểm soát traffic một cách từ từ, monitor error rate và latency, đồng thời có cơ chế rollback tự động nếu HolySheep không hoạt động như kỳ vọng.

Bước 4: Rollback plan và kịch bản khắc phục

Một playbook migration không thể thiếu kế hoạch rollback chi tiết. Đội ngũ của tôi đã xây dựng circuit breaker pattern để tự động revert về service cũ khi phát hiện vấn đề.
#!/usr/bin/env python3
"""
Circuit Breaker cho HolySheep Migration
Tự động rollback khi HolySheep không khả dụng
"""
import asyncio
import time
from enum import Enum
from dataclasses import dataclass
from typing import Callable, Any
import logging

logger = logging.getLogger(__name__)


class CircuitState(Enum):
    CLOSED = "closed"      # Bình thường, tất cả requests đi HolySheep
    OPEN = "open"          # Mở, tất cả requests đi service cũ
    HALF_OPEN = "half_open"  # Thử lại HolySheep sau recovery


@dataclass
class CircuitBreakerConfig:
    failure_threshold: int = 5      # Số lỗi liên tiếp để open circuit
    recovery_timeout: int = 60       # Giây chờ trước khi thử lại
    success_threshold: int = 3       # Số thành công để close circuit
    half_open_requests: int = 10    # Số requests thử trong half-open


class HolySheepCircuitBreaker:
    """
    Circuit Breaker pattern cho HolySheep API
    Bảo vệ hệ thống khỏi cascade failures
    """
    
    def __init__(
        self,
        holy_sheep_func: Callable,
        fallback_func: Callable,
        config: CircuitBreakerConfig = None
    ):
        self.holy_sheep_func = holy_sheep_func
        self.fallback_func = fallback_func
        self.config = config or CircuitBreakerConfig()
        
        self.state = CircuitState.CLOSED
        self.failure_count = 0
        self.success_count = 0
        self.last_failure_time = None
        self.half_open_requests_made = 0
        
        # Metrics
        self.stats = {
            'total_requests': 0,
            'holy_sheep_success': 0,
            'holy_sheep_failures': 0,
            'fallback_calls': 0,
            'circuit_state_changes': []
        }
    
    def _record_success(self):
        """Ghi nhận thành công"""
        self.failure_count = 0
        self.success_count += 1
        
        if self.state == CircuitState.HALF_OPEN:
            if self.success_count >= self.config.success_threshold:
                self._transition_to(CircuitState.CLOSED)
    
    def _record_failure(self):
        """Ghi nhận lỗi"""
        self.failure_count += 1
        self.success_count = 0
        self.last_failure_time = time.time()
        
        if self.state == CircuitState.CLOSED:
            if self.failure_count >= self.config.failure_threshold:
                self._transition_to(CircuitState.OPEN)
        
        elif self.state == CircuitState.HALF_OPEN:
            self._transition_to(CircuitState.OPEN)
    
    def _transition_to(self, new_state: CircuitState):
        """Chuyển đổi trạng thái circuit"""
        old_state = self.state
        self.state = new_state
        
        if new_state == CircuitState.CLOSED:
            self.failure_count = 0
            self.success_count = 0
            logger.info("🔄 Circuit CLOSED - HolySheep hoạt động bình thường")
        
        elif new_state == CircuitState.OPEN:
            logger.warning("⚠️ Circuit OPEN - Fallback sang service cũ")
        
        elif new_state == CircuitState.HALF_OPEN:
            logger.info("🔄 Circuit HALF_OPEN - Đang thử khôi phục HolySheep")
            self.half_open_requests_made = 0
        
        self.stats['circuit_state_changes'].append({
            'from': old_state.value,
            'to': new_state.value,
            'timestamp': time.time()
        })
    
    def _should_allow_request(self) -> bool:
        """Kiểm tra có nên cho request đi HolySheep không"""
        if self.state == CircuitState.CLOSED:
            return True
        
        elif self.state == CircuitState.OPEN:
            # Kiểm tra recovery timeout
            if (time.time() - self.last_failure_time) >= self.config.re