Mở Đầu: Câu Chuyện Thực Tế Từ Dự Án RAG Doanh Nghiệp

Tôi còn nhớ rõ ngày đầu triển khai hệ thống RAG (Retrieval-Augmented Generation) cho một doanh nghiệp thương mại điện tử lớn tại Việt Nam. Đội ngũ 50 nhân viên chăm sóc khách hàng đã quen với chatbot cũ, nhưng khi tích hợp AI API để trả lời tự động 80% câu hỏi, mọi thứ bắt đầu rối loạn. Buổi sáng thứ Hai, lưu lượng tăng đột biến gấp 10 lần do khuyến mãi cuối tuần — hệ thống AI mới không chịu nổi, khách hàng nhận được câu trả lời vô nghĩa, và đội ngũ kỹ thuật phải rollback lúc 2 giờ sáng.

Bài học đắt giá đó dẫn tôi đến khái niệm Gray Release (Phát hành có kiểm soát) — chiến lược triển khai AI API mà bất kỳ doanh nghiệp nào cũng cần nắm vững trước khi đưa sản phẩm AI đến tay người dùng thực.

Gray Release Là Gì? Tại Sao AI API Cần Chiến Lược Riêng?

Gray Release (hay Canary Deployment) là phương pháp triển khai phiên bản mới cho một phần nhỏ người dùng trước khi mở rộng toàn bộ. Khác với phần mềm truyền thống, AI API có đặc thù riêng:

Với HolySheep AI, bạn được hỗ trợ WeChat/Alipay thanh toán, độ trễ dưới 50ms, và tỷ giá chỉ ¥1=$1 (tiết kiệm 85%+ so với các provider phương Tây). Nhưng dù provider nào, chiến lược Gray Release vẫn là bắt buộc.

Các Mô Hình Gray Release Phổ Biến Cho AI API

1. Canary Release — Phân Chia Theo Tỷ Lệ Phần Trăm

Đây là mô hình kinh điển nhất. Ví dụ: 5% traffic đi qua API mới, 95% giữ nguyên.

// Canary Router - JavaScript/Node.js
// Tích hợp HolySheep AI với Canary Release

const express = require('express');
const Redis = require('ioredis');

const app = express();
const redis = new Redis(process.env.REDIS_URL);

// Cấu hình canary
const CANARY_PERCENT = parseInt(process.env.CANARY_PERCENT) || 5;
const HOLYSHEEP_BASE_URL = 'https://api.holysheep.ai/v1';

app.post('/api/chat', async (req, res) => {
    const userId = req.headers['x-user-id'] || req.ip;
    const canaryKey = canary:${userId};
    
    // Kiểm tra user đã được assign chưa
    let isCanary = await redis.get(canaryKey);
    
    if (isCanary === null) {
        // Random assign dựa trên percentage
        isCanary = Math.random() * 100 < CANARY_PERCENT;
        // Lưu assignment trong 24h
        await redis.setex(canaryKey, 86400, isCanary ? '1' : '0');
    }
    
    isCanary = isCanary === '1';
    
    // Log để theo dõi
    console.log([CANARY] user=${userId} isCanary=${isCanary});
    
    // Gọi API tương ứng
    if (isCanary) {
        // Canary: Dùng model mới (DeepSeek V3.2 - $0.42/MTok)
        const response = await callHolySheepAPI(req.body, 'deepseek-v3.2');
        await logMetrics('canary', response);
        res.json(response);
    } else {
        // Stable: Dùng model cũ đã validate (GPT-4.1 - $8/MTok)
        const response = await callHolySheepAPI(req.body, 'gpt-4.1');
        await logMetrics('stable', response);
        res.json(response);
    }
});

async function callHolySheepAPI(payload, model) {
    const response = await fetch(${HOLYSHEEP_BASE_URL}/chat/completions, {
        method: 'POST',
        headers: {
            'Authorization': Bearer ${process.env.HOLYSHEEP_API_KEY},
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            model: model,
            messages: payload.messages,
            temperature: payload.temperature || 0.7,
            max_tokens: payload.max_tokens || 2000
        })
    });
    
    if (!response.ok) {
        throw new Error(HolySheep API Error: ${response.status});
    }
    
    return response.json();
}

async function logMetrics(group, response) {
    const latency = Date.now() - startTime;
    const tokens = response.usage?.total_tokens || 0;
    
    await redis.lpush('metrics:latency', JSON.stringify({ group, latency, tokens, ts: Date.now() }));
    await redis.ltrim('metrics:latency', 0, 9999); // Giữ 10000 record gần nhất
}

app.listen(3000);

2. Feature Flag — Bật/Tắt Theo User Segment

Phân chia người dùng theo nhóm: VIP, Beta Tester, hay theo region.

# Feature Flag Implementation - Python

HolySheep AI Integration với User Segments

import os import hashlib import time from dataclasses import dataclass from typing import Optional import httpx HOLYSHEEP_API_KEY = os.getenv('HOLYSHEEP_API_KEY') HOLYSHEEP_BASE_URL = 'https://api.holysheep.ai/v1' @dataclass class UserContext: user_id: str plan: str # 'free', 'pro', 'enterprise' region: str is_beta_tester: bool class CanaryFeatureFlag: def __init__(self): # Cấu hình feature flags self.features = { 'new_rag_pipeline': { 'free_users': 0, # 0% free users 'pro_users': 10, # 10% pro users 'enterprise_users': 50, # 50% enterprise users 'beta_testers': 100 # 100% beta testers }, 'deepseek_model': { 'free_users': 0, 'pro_users': 5, 'enterprise_users': 30, 'beta_testers': 100 }, 'streaming_response': { 'free_users': 0, 'pro_users': 20, 'enterprise_users': 100, 'beta_testers': 100 } } def is_enabled(self, feature: str, user: UserContext) -> bool: """Kiểm tra feature có enabled cho user không""" if feature not in self.features: return False if user.is_beta_tester: return self.features[feature]['beta_testers'] >= 100 # Deterministic assignment dựa trên user_id + feature # Đảm bảo cùng user luôn nhận same result hash_input = f"{user.user_id}:{feature}" hash_value = int(hashlib.md5(hash_input.encode()).hexdigest(), 16) % 100 plan_key = f"{user.plan}_users" threshold = self.features[feature].get(plan_key, 0) return hash_value < threshold def get_model_for_user(self, user: UserContext, query_complexity: str) -> str: """Chọn model phù hợp dựa trên user segment và độ phức tạp query""" # Enterprise luôn dùng model tốt nhất cho complex queries if user.plan == 'enterprise' and query_complexity == 'high': return 'claude-sonnet-4.5' # $15/MTok # Pro users được thử nghiệm với model mới if self.is_enabled('deepseek_model', user): # DeepSeek V3.2: $0.42/MTok - tiết kiệm 95% return 'deepseek-v3.2' # Fallback sang GPT-4.1 đã validate return 'gpt-4.1' async def process_chat_request(user: UserContext, messages: list, query_complexity: str = 'medium'): flag_system = CanaryFeatureFlag() # Kiểm tra feature flags use_new_rag = flag_system.is_enabled('new_rag_pipeline', user) use_streaming = flag_system.is_enabled('streaming_response', user) # Chọn model model = flag_system.get_model_for_user(user, query_complexity) print(f"[DEBUG] user={user.user_id}, plan={user.plan}") print(f"[DEBUG] new_rag={use_new_rag}, streaming={use_streaming}, model={model}") # Gọi HolySheep API async with httpx.AsyncClient(timeout=30.0) as client: response = await client.post( f"{HOLYSHEEP_BASE_URL}/chat/completions", headers={ "Authorization": f"Bearer {HOLYSHEEP_API_KEY}", "Content-Type": "application/json" }, json={ "model": model, "messages": messages, "stream": use_streaming, "temperature": 0.7 } ) return response.json()

Sử dụng

if __name__ == '__main__': # Test các user segments khác nhau test_users = [ UserContext('user_001', 'free', 'VN', False), UserContext('user_002', 'pro', 'VN', False), UserContext('user_003', 'enterprise', 'VN', False), UserContext('beta_001', 'free', 'VN', True), # Beta tester ] import asyncio for user in test_users: result = asyncio.run(process_chat_request(user, [{"role": "user", "content": "Test"}])) print(f"Result for {user.user_id}: {result.get('model', 'error')}") print("---")

3. A/B Testing Cho AI Responses

So sánh chất lượng response giữa 2 model/prompt khác nhau trên cùng user.

// A/B Testing AI Responses - Go
// So sánh HolySheep models với traffic splitting

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "time"
)

const (
    HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
)

type ABTestConfig struct {
    ExperimentName string
    VariantA       string // Model A
    VariantB       string // Model B  
    TrafficSplit   float64 // % traffic cho Variant B (0.0 - 1.0)
}

type ChatRequest struct {
    Model    string      json:"model"
    Messages []Message   json:"messages"
}

type Message struct {
    Role    string json:"role"
    Content string json:"content"
}

type TestResult struct {
    Variant     string
    LatencyMs   int64
    Tokens      int
    Response    string
    Error       error
}

func main() {
    config := ABTestConfig{
        ExperimentName: "rag_quality_test",
        VariantA:        "gpt-4.1",
        VariantB:        "deepseek-v3.2",
        TrafficSplit:    0.2, // 20% traffic cho DeepSeek
    }
    
    // Tạo HTTP server với A/B testing
    http.HandleFunc("/api/query", func(w http.ResponseWriter, r *http.Request) {
        result := runABTest(r, config)
        
        // Trả về response
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(map[string]interface{}{
            "response":     result.Response,
            "variant":      result.Variant,
            "latency_ms":   result.LatencyMs,
            "tokens":       result.Tokens,
        })
    })
    
    http.ListenAndServe(":8080", nil)
}

func runABTest(r *http.Request, config ABTestConfig) TestResult {
    var req ChatRequest
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        return TestResult{Error: err}
    }
    
    // Deterministic assignment dựa trên user_id + timestamp hour
    userID := r.Header.Get("X-User-ID")
    hourKey := time.Now().Format("2006-01-02-15")
    hashInput := fmt.Sprintf("%s:%s:%s", userID, config.ExperimentName, hourKey)
    
    // Simple hash để split traffic
    variant := config.VariantA
    if hash([]byte(hashInput))%100 < int(config.TrafficSplit*100) {
        variant = config.VariantB
    }
    
    // Execute request
    startTime := time.Now()
    result := callHolySheep(req, variant)
    result.LatencyMs = time.Since(startTime).Milliseconds()
    
    // Log kết quả cho analysis
    logExperimentResult(config.ExperimentName, variant, result)
    
    return result
}

func callHolySheep(req ChatRequest, model string) TestResult {
    req.Model = model
    
    payload, _ := json.Marshal(req)
    
    httpReq, _ := http.NewRequest("POST", HOLYSHEEP_BASE_URL+"/chat/completions", bytes.NewBuffer(payload))
    httpReq.Header.Set("Authorization", "Bearer "+getEnv("HOLYSHEEP_API_KEY", ""))
    httpReq.Header.Set("Content-Type", "application/json")
    
    client := &http.Client{Timeout: 30 * time.Second}
    resp, err := client.Do(httpReq)
    
    if err != nil {
        return TestResult{Variant: model, Error: err}
    }
    defer resp.Body.Close()
    
    body, _ := io.ReadAll(resp.Body)
    
    var result map[string]interface{}
    json.Unmarshal(body, &result)
    
    return TestResult{
        Variant:   model,
        Tokens:    int(result["usage"].(map[string]interface{})["total_tokens"].(float64)),
        Response:  result["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string),
    }
}

// Hash function đơn giản
func hash(data []byte) int {
    h := 0
    for _, b := range data {
        h = h*31 + int(b)
    }
    return h
}

func logExperimentResult(expName, variant string, result TestResult) {
    // Log vào metrics system (Prometheus, Datadog, etc.)
    fmt.Printf("[AB_TEST] exp=%s variant=%s latency=%dms tokens=%d error=%v\n",
        expName, variant, result.LatencyMs, result.Tokens, result.Error)
}

func getEnv(key, fallback string) string {
    if value := os.Getenv(key); value != "" {
        return value
    }
    return fallback
}

Theo Dõi và Đo Lường Canary Release

Code chạy được rồi, nhưng quan trọng hơn là biết khi nào nên rollback hay scale up. Dưới đây là dashboard metrics cơ bản.

// Metrics Dashboard - TypeScript/React
// Theo dõi Canary performance real-time

interface CanaryMetrics {
    group: 'canary' | 'stable';
    timestamp: number;
    request_count: number;
    success_rate: number;
    avg_latency_ms: number;
    p95_latency_ms: number;
    p99_latency_ms: number;
    token_usage: number;
    error_count: number;
    error_types: Record;
}

class CanaryMonitor {
    private redis: any;
    private prometheus: any;
    
    constructor(redisUrl: string, prometheusUrl: string) {
        this.redis = new Redis(redisUrl);
        this.prometheus = new Prometheus.Client({ url: prometheusUrl });
    }
    
    async collectMetrics(group: 'canary' | 'stable', durationMinutes: number = 5): Promise {
        const now = Date.now();
        const startTime = now - durationMinutes * 60 * 1000;
        
        // Query Redis cho latency data
        const latencyData = await this.redis.lrange('metrics:latency', 0, -1);
        const relevantData = latencyData
            .map(JSON.parse)
            .filter(d => d.group === group && d.ts >= startTime);
        
        // Calculate metrics
        const latencies = relevantData.map(d => d.latency).sort((a, b) => a - b);
        const tokenUsages = relevantData.map(d => d.tokens);
        
        return {
            group,
            timestamp: now,
            request_count: relevantData.length,
            success_rate: this.calculateSuccessRate(relevantData),
            avg_latency_ms: this.average(latencies),
            p95_latency_ms: this.percentile(latencies, 95),
            p99_latency_ms: this.percentile(latencies, 99),
            token_usage: tokenUsages.reduce((a, b) => a + b, 0),
            error_count: relevantData.filter(d => d.error).length,
            error_types: this.aggregateErrors(relevantData)
        };
    }
    
    async shouldPromoteCanary(): Promise<{decision: 'promote' | 'rollback' | 'monitor', reason: string}> {
        const canary = await this.collectMetrics('canary', 10);
        const stable = await this.collectMetrics('stable', 10);
        
        // Criteria cho promotion
        const checks = {
            successRate: canary.success_rate >= stable.success_rate - 0.01, // Chênh lệch < 1%
            latencyP95: canary.p95_latency_ms <= stable.p95_latency_ms * 1.2, // Chênh lệch < 20%
            minRequests: canary.request_count >= 1000, // Đủ sample size
            errorRate: canary.error_count / canary.request_count < 0.01 // Error rate < 1%
        };
        
        if (checks.successRate && checks.latencyP95 && checks.minRequests && checks.errorRate) {
            return { decision: 'promote', reason: 'Canary đạt tất cả criteria' };
        }
        
        if (canary.success_rate < stable.success_rate - 0.05 || canary.error_count / canary.request_count > 0.05) {
            return { decision: 'rollback', reason: 'Canary performance giảm đáng kể' };
        }
        
        return { decision: 'monitor', reason: 'Cần thêm data để quyết định' };
    }
    
    private average(arr: number[]): number {
        return arr.reduce((a, b) => a + b, 0) / arr.length || 0;
    }
    
    private percentile(arr: number[], p: number): number {
        const index = Math.ceil((p / 100) * arr.length) - 1;
        return arr[Math.max(0, index)] || 0;
    }
    
    private calculateSuccessRate(data: any[]): number {
        const success = data.filter(d => !d.error).length;
        return success / data.length || 0;
    }
    
    private aggregateErrors(data: any[]): Record {
        return data.reduce((acc, d) => {
            if (d.error) {
                const errorType = d.error_type || 'unknown';
                acc[errorType] = (acc[errorType] || 0) + 1;
            }
            return acc;
        }, {});
    }
}

// Alerting khi Canary có vấn đề
async function setupAlerts(monitor: CanaryMonitor) {
    setInterval(async () => {
        const canary = await monitor.collectMetrics('canary', 5);
        
        // Alert nếu error rate tăng đột ngột
        if (canary.error_count / canary.request_count > 0.02) {
            await sendAlert({
                level: 'critical',
                message: Canary error rate cao: ${(canary.error_count / canary.request_count * 100).toFixed(2)}%,
                metrics: canary
            });
        }
        
        // Alert nếu latency tăng gấp đôi
        const stable = await monitor.collectMetrics('stable', 5);
        if (canary.avg_latency_ms > stable.avg_latency_ms * 2) {
            await sendAlert({
                level: 'warning',
                message: Canary latency cao hơn stable: ${canary.avg_latency_ms}ms vs ${stable.avg_latency_ms}ms,
                metrics: canary
            });
        }
    }, 60000); // Check every minute
}

async function sendAlert(alert: any) {
    // Gửi alert qua Slack, PagerDuty, etc.
    console.log('[ALERT]', JSON.stringify(alert));
}

Lỗi Thường Gặp và Cách Khắc Phục

Lỗi 1: "429 Too Many Requests" — Rate Limit Hit

Mô tả: Khi traffic tăng đột ngột (do flash sale hoặc canary promotion), HolySheep API trả về lỗi 429.

Mã khắc phục:

// Retry logic với exponential backoff
async function callWithRetry(payload, maxRetries = 3) {
    const HOLYSHEEP_BASE_URL = 'https://api.holysheep.ai/v1';
    
    for (let attempt = 0; attempt < maxRetries; attempt++) {
        try {
            const response = await fetch(${HOLYSHEEP_BASE_URL}/chat/completions, {
                method: 'POST',
                headers: {
                    'Authorization': Bearer ${process.env.HOLYSHEEP_API_KEY},
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            });
            
            if (response.status === 429) {
                // Rate limit - exponential backoff
                const retryAfter = parseInt(response.headers.get('Retry-After') || '1');
                const delay = Math.min(retryAfter * 1000 * Math.pow(2, attempt), 30000);
                console.log([RATE_LIMIT] Waiting ${delay}ms before retry ${attempt + 1});
                await sleep(delay);
                continue;
            }
            
            if (!response.ok) {
                throw new Error(API Error: ${response.status});
            }
            
            return await response.json();
            
        } catch (error) {
            if (attempt === maxRetries - 1) throw error;
            await sleep(1000 * Math.pow(2, attempt));
        }
    }
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// Circuit breaker pattern
class CircuitBreaker {
    constructor() {
        this.failureCount = 0;
        this.failureThreshold = 5;
        this.resetTimeout = 60000; // 1 phút
        this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
    }
    
    async execute(fn) {
        if (this.state === 'OPEN') {
            throw new Error('Circuit breaker is OPEN');
        }
        
        try {
            const result = await fn();
            this.onSuccess();
            return result;
        } catch (error) {
            this.onFailure();
            throw error;
        }
    }
    
    onSuccess() {
        this.failureCount = 0;
        if (this.state === 'HALF_OPEN') {
            this.state = 'CLOSED';
        }
    }
    
    onFailure() {
        this.failureCount++;
        if (this.failureCount >= this.failureThreshold) {
            this.state = 'OPEN';
            setTimeout(() => this.state = 'HALF_OPEN', this.resetTimeout);
        }
    }
}

Lỗi 2: Token Usage Vượt Ngân Sách

Mô tả: Canary release với model đắt hơn (GPT-4.1 $8/MTok) khiến chi phí tăng vượt dự kiến.

Mã khắc phục:

# Budget Alert và Auto-downgrade
import os
from datetime import datetime, timedelta
from dataclasses import dataclass

@dataclass
class BudgetConfig:
    daily_limit_usd: float = 100.0
    weekly_limit_usd: float = 500.0
    alert_threshold: float = 0.8  # Alert khi đạt 80%
    HOLYSHEEP_BASE_URL = 'https://api.holysheep.ai/v1'

class BudgetManager:
    def __init__(self, config: BudgetConfig):
        self.config = config
        self.redis = Redis(os.getenv('REDIS_URL'))
        
        # Model pricing (USD per 1M tokens) - theo bảng giá HolySheep 2026
        self.model_pricing = {
            'gpt-4.1': 8.0,
            'claude-sonnet-4.5': 15.0,
            'gemini-2.5-flash': 2.50,
            'deepseek-v3.2': 0.42,  # Tiết kiệm 95% so với GPT-4.1
        }
    
    async def check_and_log_usage(self, model: str, tokens: int, is_canary: bool):
        """Log usage và kiểm tra budget"""
        cost = (tokens / 1_000_000) * self.model_pricing.get(model, 8.0)
        
        today = datetime.now().strftime('%Y-%m-%d')
        usage_key = f"usage:{today}:{'canary' if is_canary else 'stable'}"
        
        # Cộng dồn usage
        await self.redis.incrbyfloat(usage_key, cost)
        await self.redis.expire(usage_key, 86400 * 2)  # 2 days TTL
        
        # Get current usage
        today_usage = await self.get_today_usage()
        weekly_usage = await self.get_weekly_usage()
        
        # Check thresholds
        if today_usage > self.config.daily_limit_usd * self.config.alert_threshold:
            await self.send_alert(f"Ngân sách hôm nay: ${today_usage:.2f} / ${self.config.daily_limit_usd}")
        
        if weekly_usage > self.config.weekly_limit_usd * self.config.alert_threshold:
            await self.send_alert(f"Ngân sách tuần: ${weekly_usage:.2f} / ${self.config.weekly_limit_usd}")
        
        return cost
    
    async def auto_downgrade_if_needed(self, current_model: str, is_canary: bool) -> str:
        """Tự động downgrade model nếu budget sắp hết"""
        if not is_canary:
            return current_model
        
        today_usage = await self.get_today_usage()
        
        if today_usage >= self.config.daily_limit_usd:
            print(f"[BUDGET] Daily budget exceeded (${today_usage:.2f}), downgrading canary to DeepSeek")
            return 'deepseek-v3.2'  # Model rẻ nhất
        
        remaining = self.config.daily_limit_usd - today_usage
        # Estimate remaining requests
        estimated_remaining_requests = remaining / (self.model_pricing.get(current_model, 8.0) * 0.001)  # ~1K tokens/request
        
        if estimated_remaining_requests < 100:
            print(f"[BUDGET] Low budget, downgrading to cost-effective model")
            return 'gemini-2.5-flash'  # $2.50/MTok - balance giữa cost và quality
        
        return current_model
    
    async def get_today_usage(self) -> float:
        today = datetime.now().strftime('%Y-%m-%d')
        canary_usage = float(await self.redis.get(f"usage:{today}:canary") or 0)
        stable_usage = float(await self.redis.get(f"usage:{today}:stable") or 0)
        return canary_usage + stable_usage
    
    async def get_weekly_usage(self) -> float:
        total = 0
        for i in range(7):
            day = (datetime.now() - timedelta(days=i)).strftime('%Y-%m-%d')
            total += float(await self.redis.get(f"usage:{day}:canary") or 0)
            total += float(await self.redis.get(f"usage:{day}:stable") or 0)
        return total
    
    async def send_alert(self, message: str):
        print(f"[ALERT] {message}")
        # Gửi notification: Slack, Email, SMS

Lỗi 3: Model Version Thay Đổi Không Báo Trước

Mô tả: HolySheep hoặc upstream provider thay đổi model version, gây ra response format khác hoặc quality drift.

Mã khắc phục:

// Model version pinning và fallback
interface ModelConfig {
    pinned_version?: string;
    fallback_versions: string[];
    health_check_prompts: string[];
}

class ModelVersionManager {
    private config: Map = new Map();
    private healthCache: Map = new Map();
    
    constructor() {
        // Pin specific versions để tránh surprise updates
        this.config.set('gpt-4.1', {
            pinned_version: 'gpt-4.1-2024-06', // Pin version cụ thể
            fallback_versions: ['gpt-4.1', 'gemini-2.5-flash'],
            health_check_prompts: [
                "What is 2+2? Answer with just the number.",
                "Is the sky blue? Answer yes or no."
            ]
        });
        
        this.config.set('deepseek-v3.2', {
            pinned_version: undefined, // Không pin, dùng latest
            fallback_versions: ['gemini-2.5-flash', 'gpt-4.1'],
            health_check_prompts: [
                "What is 2+2? Answer with just the number."
            ]
        });
    }
    
    async callWithVersionSafety(
        model: string, 
        messages: any[], 
        apiKey: string
    ): Promise {
        const config = this.config.get(model) || { fallback_versions: [model] };
        
        // Health check trước khi call
        const isHealthy = await this.checkModelHealth(model, apiKey);
        if (!isHealthy) {
            console.log([WARN] Model ${model} unhealthy, trying fallback);
            return this.tryFallbacks(config.fallback_versions, messages, apiKey);
        }
        
        try {
            const response = await this.callAPI(model, messages, apiKey);
            
            // Validate response format
            if (!this.validateResponse(response)) {
                throw new Error('Invalid response format');
            }
            
            return response;
            
        } catch (error: any) {
            console.log([ERROR] Model ${model} failed: ${error.message});
            return this.tryFallbacks(config.fallback_versions, messages, apiKey);
        }
    }
    
    async checkModelHealth(model: string, apiKey: string): Promise {
        const cacheKey = model;
        const cached = this.healthCache.get(cacheKey);
        
        // Cache valid trong 5 phút
        if (cached && Date.now() - cached.lastCheck < 5 * 60 * 1000) {
            return cached.healthy;
        }