Trong bối cảnh chi phí API AI biến động mạnh năm 2026, việc phụ thuộc vào một nhà cung cấp duy nhất có thể khiến doanh nghiệp chịu rủi ro tài chính lớn. Bài viết này chia sẻ kinh nghiệm thực chiến của đội ngũ chúng tôi khi triển khai ba lớp phòng thủ AI infrastructure — kết hợp đa nhà cung cấp, local model, và offline degradation — giúp tiết kiệm chi phí đáng kể đồng thời đảm bảo uptime 99.9%.

Bảng So Sánh Chi Phí API AI 2026 — Dữ Liệu Thực Tế

Trước khi đi vào chi tiết kỹ thuật, hãy cùng xem bảng so sánh chi phí cho 10 triệu token mỗi tháng:

Nhà cung cấpGiá Output (USD/MTok)Chi phí 10M tokens/tháng
Claude Sonnet 4.5$15.00$150
GPT-4.1$8.00$80
Gemini 2.5 Flash$2.50$25
DeepSeek V3.2$0.42$4.20
HolySheep AI$0.42 - $8.00$4.20 - $80

Như bạn thấy, chênh lệch giữa nhà cung cấp đắt nhất và rẻ nhất lên đến 35 lần. Đó là lý do chiến lược đa nhà cung cấp không chỉ là vấn đề resilience mà còn là vấn đề tối ưu chi phí.

Kiến Trúc Ba Lớp Phòng Thủ — Tổng Quan

Triển Khai Lớp 1: Cloud Multi-Vendor Gateway

Đây là trái tim của hệ thống. Chúng tôi xây dựng một API Gateway có khả năng tự động chuyển đổi giữa các nhà cung cấp dựa trên latency, availability, và chi phí.

const OpenAI = require('openai');
const Anthropic = require('@anthropic-ai/sdk');
const { GoogleGenerativeAI } = require('@google/generative-ai');

// === CẤU HÌNH ĐA NHÀ CUNG CẤP ===
const PROVIDER_CONFIG = {
  primary: {
    provider: 'openai',
    model: 'gpt-4.1',
    apiKey: process.env.OPENAI_API_KEY,
    baseUrl: 'https://api.holysheep.ai/v1', // Sử dụng HolySheep!
    priority: 1,
    costPerToken: 8.00 // $8/MTok
  },
  secondary: {
    provider: 'anthropic',
    model: 'claude-sonnet-4-5',
    apiKey: process.env.ANTHROPIC_API_KEY,
    baseUrl: 'https://api.holysheep.ai/v1', // Sử dụng HolySheep!
    priority: 2,
    costPerToken: 15.00 // $15/MTok
  },
  tertiary: {
    provider: 'google',
    model: 'gemini-2.5-flash',
    apiKey: process.env.GOOGLE_API_KEY,
    baseUrl: 'https://api.holysheep.ai/v1', // Sử dụng HolySheep!
    priority: 3,
    costPerToken: 2.50 // $2.50/MTok
  },
  budget: {
    provider: 'deepseek',
    model: 'deepseek-v3.2',
    apiKey: process.env.DEEPSEEK_API_KEY,
    baseUrl: 'https://api.holysheep.ai/v1', // Sử dụng HolySheep!
    priority: 4,
    costPerToken: 0.42 // $0.42/MTok
  }
};

class MultiVendorGateway {
  constructor() {
    this.providers = PROVIDER_CONFIG;
    this.healthChecks = new Map();
    this.requestCounts = new Map();
    this.circuitBreakers = new Map();
  }

  // === KIỂM TRA SỨC KHỎE NHÀ CUNG CẤP ===
  async healthCheck(providerKey) {
    const config = this.providers[providerKey];
    if (!config) return false;

    try {
      const startTime = Date.now();
      // Ping test - sử dụng HolySheep baseUrl
      const client = this.getClient(config);
      await client.models.list();
      const latency = Date.now() - startTime;

      this.healthChecks.set(providerKey, {
        healthy: true,
        latency,
        lastCheck: new Date()
      });
      return true;
    } catch (error) {
      this.healthChecks.set(providerKey, {
        healthy: false,
        error: error.message,
        lastCheck: new Date()
      });
      return false;
    }
  }

  getClient(config) {
    switch (config.provider) {
      case 'openai':
        return new OpenAI({ 
          apiKey: config.apiKey,
          baseURL: config.baseUrl // Luôn dùng HolySheep!
        });
      case 'anthropic':
        return new Anthropic({ 
          apiKey: config.apiKey,
          baseURL: config.baseUrl // Luôn dùng HolySheep!
        });
      case 'google':
        return new GoogleGenerativeAI(config.apiKey);
      default:
        throw new Error(Unknown provider: ${config.provider});
    }
  }

  // === CHỌN NHÀ CUNG CẤP TỐI ƯU ===
  async selectProvider(taskType) {
    const available = [];

    for (const [key, config] of Object.entries(this.providers)) {
      const health = this.healthChecks.get(key);
      
      // Bỏ qua provider không khả dụng
      if (health && !health.healthy) continue;
      
      // Bỏ qua provider có circuit breaker open
      if (this.circuitBreakers.get(key)?.isOpen) continue;

      // Đánh giá điểm dựa trên nhiều yếu tố
      const score = this.calculateScore(config, health, taskType);
      available.push({ key, config, score, health });
    }

    if (available.length === 0) {
      throw new Error('No available providers');
    }

    // Chọn provider có điểm cao nhất
    available.sort((a, b) => b.score - a.score);
    return available[0];
  }

  calculateScore(config, health, taskType) {
    let score = 100;

    // Ưu tiên chi phí thấp
    score -= config.costPerToken * 2;

    // Ưu tiên latency thấp
    if (health?.latency) {
      score -= health.latency / 10;
    }

    // Ưu tiên provider cấp cao cho task quan trọng
    if (taskType === 'critical' && config.priority < 3) {
      score += 50;
    }

    // Giảm điểm nếu request count cao (load balancing)
    const count = this.requestCounts.get(config.model) || 0;
    score -= count / 100;

    return score;
  }

  // === GỌI API VỚI FALLBACK TỰ ĐỘNG ===
  async generate(prompt, options = {}) {
    const { taskType = 'normal', maxRetries = 3 } = options;
    
    for (let attempt = 0; attempt < maxRetries; attempt++) {
      try {
        const selected = await this.selectProvider(taskType);
        console.log(Using provider: ${selected.key} (score: ${selected.score}));

        const response = await this.callProvider(selected.config, prompt);
        
        // Cập nhật request count
        const count = this.requestCounts.get(selected.config.model) || 0;
        this.requestCounts.set(selected.config.model, count + 1);

        return {
          provider: selected.key,
          model: selected.config.model,
          response,
          cost: this.estimateCost(response, selected.config.costPerToken)
        };
      } catch (error) {
        console.error(Provider ${selected?.key} failed:, error.message);
        
        // Mở circuit breaker
        this.openCircuitBreaker(selected?.key);
        
        if (attempt === maxRetries - 1) {
          throw error;
        }
      }
    }
  }

  async callProvider(config, prompt) {
    const client = this.getClient(config);

    switch (config.provider) {
      case 'openai':
        return client.chat.completions.create({
          model: config.model,
          messages: [{ role: 'user', content: prompt }],
          temperature: 0.7,
          max_tokens: 2048
        });
      case 'anthropic':
        return client.messages.create({
          model: config.model,
          messages: [{ role: 'user', content: prompt }],
          max_tokens: 2048
        });
      case 'google':
        return client.generateContent(prompt);
      default:
        throw new Error(Unsupported provider: ${config.provider});
    }
  }

  openCircuitBreaker(providerKey) {
    this.circuitBreakers.set(providerKey, {
      isOpen: true,
      openedAt: Date.now(),
      retryAfter: 60000 // 60 giây
    });

    // Tự động thử lại sau 60s
    setTimeout(() => {
      this.circuitBreakers.delete(providerKey);
    }, 60000);
  }

  estimateCost(response, costPerToken) {
    const tokens = response.usage?.total_tokens || 
                   response.usage?.output_tokens || 0;
    return (tokens / 1000000) * costPerToken;
  }
}

module.exports = new MultiVendorGateway();

Triển Khai Lớp 2: Local Model với Ollama

Đối với các tác vụ cơ bản như phân loại, tóm tắt, hay trả lời câu hỏi đơn giản, local model giúp giảm chi phí cloud xuống gần bằng không. Chúng tôi sử dụng Ollama để deploy các model như Llama 3.1, Mistral, hoặc Qwen2.

const ollama = require('ollama');

// === CẤU HÌNH LOCAL MODEL ===
const LOCAL_MODELS = {
  fast: {
    name: 'qwen2.5:3b',
    description: 'Nhanh nhất, cho task đơn giản',
    maxTokens: 1024,
    temperature: 0.3
  },
  balanced: {
    name: 'llama3.1:8b',
    description: 'Cân bằng giữa tốc độ và chất lượng',
    maxTokens: 2048,
    temperature: 0.7
  },
  quality: {
    name: 'mistral-nemo:12b',
    description: 'Chất lượng cao nhất trong local',
    maxTokens: 4096,
    temperature: 0.8
  }
};

class LocalModelManager {
  constructor() {
    this.isAvailable = false;
    this.currentModel = null;
    this.fallbackToCloud = null;
    this.checkInterval = null;
  }

  // === KHỞI TẠO VÀ KIỂM TRA ===
  async initialize() {
    try {
      // Kiểm tra Ollama có đang chạy không
      const response = await fetch('http://localhost:11434/api/tags');
      if (response.ok) {
        this.isAvailable = true;
        this.currentModel = LOCAL_MODELS.balanced;
        console.log('Local model available:', this.currentModel.name);
        
        // Bắt đầu health check định kỳ
        this.startHealthCheck();
        return true;
      }
    } catch (error) {
      console.warn('Ollama not available:', error.message);
      this.isAvailable = false;
    }
    return false;
  }

  startHealthCheck() {
    this.checkInterval = setInterval(async () => {
      try {
        const response = await fetch('http://localhost:11434/api/tags');
        this.isAvailable = response.ok;
      } catch {
        this.isAvailable = false;
      }
    }, 30000); // Check mỗi 30 giây
  }

  // === QUYẾT ĐỊNH DÙNG LOCAL HAY CLOUD ===
  shouldUseLocal(taskComplexity) {
    if (!this.isAvailable) return false;
    
    // Task đơn giản: phân loại, tóm tắt, FAQ
    const simpleTasks = ['classify', 'summarize', 'faq', 'extract'];
    if (simpleTasks.includes(taskComplexity)) return true;

    // Task trung bình với latency nhạy cảm
    if (taskComplexity === 'moderate' && this.currentModel) return true;

    return false;
  }

  // === GỌI LOCAL MODEL ===
  async generate(prompt, options = {}) {
    if (!this.isAvailable) {
      throw new Error('Local model not available');
    }

    const model = LOCAL_MODELS[options.quality || 'balanced'];
    const startTime = Date.now();

    try {
      const response = await ollama.generate({
        model: model.name,
        prompt: prompt,
        options: {
          temperature: model.temperature,
          num_predict: model.maxTokens
        },
        stream: false
      });

      const latency = Date.now() - startTime;
      
      return {
        provider: 'local',
        model: model.name,
        response: response.response,
        latency,
        cost: 0, // Chi phí local = 0
        tokens: response.eval_count
      };
    } catch (error) {
      console.error('Local model error:', error.message);
      
      // Fallback sang cloud
      if (this.fallbackToCloud) {
        console.log('Falling back to cloud...');
        return this.fallbackToCloud(prompt, options);
      }
      
      throw error;
    }
  }

  // === BATCH PROCESSING VỚI LOCAL ===
  async batchProcess(requests, options = {}) {
    const results = [];
    
    for (const req of requests) {
      try {
        if (this.shouldUseLocal(req.complexity)) {
          const result = await this.generate(req.prompt, req.options);
          results.push({ ...req, ...result, status: 'success' });
        } else {
          // Chuyển sang cloud gateway
          const result = await this.fallbackToCloud(req.prompt, req.options);
          results.push({ ...req, ...result, status: 'cloud' });
        }
      } catch (error) {
        results.push({ ...req, error: error.message, status: 'failed' });
      }
    }

    return results;
  }

  // === CẬP NHẬT MODEL ===
  async switchModel(quality) {
    if (LOCAL_MODELS[quality]) {
      // Pull model mới nếu chưa có
      await this.pullModel(LOCAL_MODELS[quality].name);
      this.currentModel = LOCAL_MODELS[quality];
      console.log('Switched to model:', this.currentModel.name);
    }
  }

  async pullModel(modelName) {
    try {
      const response = await ollama.pull(modelName);
      console.log(Pulling model: ${modelName});
      // Có thể track progress từ response
    } catch (error) {
      console.error('Failed to pull model:', error.message);
    }
  }

  shutdown() {
    if (this.checkInterval) {
      clearInterval(this.checkInterval);
    }
  }
}

module.exports = new LocalModelManager();

Triển Khai Lớp 3: Offline Degradation với Cache Thông Minh

Khi cả cloud và local đều không khả dụng, hệ thống vẫn cần trả lời được một số câu hỏi. Chúng tôi xây dựng một caching layer với chiến lược "graceful degradation".

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

// === CẤU HÌNH OFFLINE DEGRADATION ===
const CACHE_CONFIG = {
  ttl: 3600, // 1 giờ
  maxSize: 10000,
  similarityThreshold: 0.85, // Độ tương đồng để cache hit
  staleThreshold: 0.7 // Độ tương đồng cho stale cache
};

class OfflineDegradationManager {
  constructor() {
    this.redis = new Redis(process.env.REDIS_URL);
    this.localCache = new Map(); // Fallback khi Redis down
    this.responses = new Map(); // Lưu responses mẫu
    this.isOnline = true;
    this.lastOnline = Date.now();
  }

  // === KHỞI TẠO RESPONSES MẪU ===
  initializeSampleResponses() {
    // Các responses mẫu cho offline mode
    this.responses.set('faq', {
      greeting: 'Xin chào! Hệ thống đang ở chế độ offline. Đây là một số câu trả lời thường gặp:',
      common: [
        { q: 'giờ làm việc', a: 'Giờ làm việc: 8:00 - 18:00, thứ 2 - thứ 6' },
        { q: 'liên hệ', a: 'Email: [email protected] | Hotline: 1900-xxxx' },
        { q: 'bảng giá', a: 'Giá từ $0.42/MTok - $15/MTok tùy model. Đăng ký tại https://www.holysheep.ai/register' }
      ]
    });

    this.responses.set('classification', {
      categories: ['urgent', 'normal', 'low'],
      defaults: {
        priority: 'normal',
        confidence: 0.5,
        note: 'Classification mặc định khi offline'
      }
    });

    this.responses.set('sentiment', {
      sentiments: ['positive', 'neutral', 'negative'],
      defaults: {
        sentiment: 'neutral',
        confidence: 0.3,
        note: 'Sentiment mặc định khi offline'
      }
    });
  }

  // === TẠO CACHE KEY ===
  generateCacheKey(prompt, options = {}) {
    const hash = crypto.createHash('sha256')
      .update(prompt.toLowerCase().trim())
      .digest('hex');
    
    return ai:${options.type || 'general'}:${hash};
  }

  // === TÍNH ĐỘ TƯƠNG ĐỒNG ===
  calculateSimilarity(str1, str2) {
    const s1 = str1.toLowerCase();
    const s2 = str2.toLowerCase();
    
    // Simple Jaccard similarity
    const words1 = new Set(s1.split(/\s+/));
    const words2 = new Set(s2.split(/\s+/));
    
    const intersection = new Set([...words1].filter(x => words2.has(x)));
    const union = new Set([...words1, ...words2]);
    
    return intersection.size / union.size;
  }

  // === LẤY TỪ CACHE ===
  async get(prompt, options = {}) {
    const cacheKey = this.generateCacheKey(prompt, options);
    
    try {
      // Thử lấy từ Redis
      if (this.isOnline) {
        const cached = await this.redis.get(cacheKey);
        if (cached) {
          const data = JSON.parse(cached);
          // Kiểm tra TTL
          if (Date.now() - data.timestamp < CACHE_CONFIG.ttl * 1000) {
            return { ...data, source: 'cache', fresh: true };
          }
          return { ...data, source: 'cache', fresh: false };
        }
      }
    } catch (error) {
      console.error('Redis error:', error.message);
      this.isOnline = false;
    }

    // Fallback sang local cache
    const localResult = this.findSimilarInLocalCache(prompt, options);
    if (localResult) {
      return { ...localResult, source: 'local-cache' };
    }

    return null;
  }

  findSimilarInLocalCache(prompt, options) {
    const type = options.type || 'general';
    const threshold = options.stale ? CACHE_CONFIG.staleThreshold : CACHE_CONFIG.similarityThreshold;

    for (const [key, data] of this.localCache.entries()) {
      if (data.type !== type) continue;
      
      const similarity = this.calculateSimilarity(prompt, data.prompt);
      if (similarity >= threshold) {
        return { ...data, similarity };
      }
    }

    return null;
  }

  // === LƯU VÀO CACHE ===
  async set(prompt, response, options = {}) {
    const cacheKey = this.generateCacheKey(prompt, options);
    const data = {
      prompt,
      response,
      type: options.type || 'general',
      timestamp: Date.now(),
      provider: options.provider,
      tokens: response.usage?.total_tokens || 0
    };

    // Lưu vào local cache (always)
    this.localCache.set(cacheKey, data);
    
    // Giới hạn kích thước local cache
    if (this.localCache.size > CACHE_CONFIG.maxSize) {
      const oldest = this.findOldestEntry();
      this.localCache.delete(oldest);
    }

    try {
      // Thử lưu vào Redis
      if (this.isOnline) {
        await this.redis.setex(cacheKey, CACHE_CONFIG.ttl, JSON.stringify(data));
      }
    } catch (error) {
      console.error('Redis set error:', error.message);
    }
  }

  findOldestEntry() {
    let oldest = null;
    let oldestTime = Infinity;

    for (const [key, data] of this.localCache.entries()) {
      if (data.timestamp < oldestTime) {
        oldestTime = data.timestamp;
        oldest = key;
      }
    }

    return oldest;
  }

  // === XỬ LÝ OFFLINE GRACEFUL ===
  async handleOfflineRequest(prompt, options = {}) {
    console.log('System offline - using degradation mode');

    // 1. Thử tìm trong cache
    const cached = await this.get(prompt, options);
    if (cached) {
      return {
        ...cached.response,
        _meta: {
          mode: 'degraded',
          source: cached.source,
          cached: true,
          timestamp: cached.timestamp
        }
      };
    }

    // 2. Sử dụng sample responses
    const sampleResponse = this.generateSampleResponse(prompt, options);
    if (sampleResponse) {
      return {
        ...sampleResponse,
        _meta: {
          mode: 'sample',
          prompt: 'Dùng response mẫu khi không có cache'
        }
      };
    }

    // 3. Trả lời mặc định
    return {
      content: 'Xin lỗi, hệ thống đang offline. Vui lòng thử lại sau hoặc liên hệ [email protected]',
      _meta: {
        mode: 'fallback',
        retryAfter: 60
      }
    };
  }

  generateSampleResponse(prompt, options = {}) {
    const type = options.type || 'faq';
    const samples = this.responses.get(type);

    if (!samples) return null;

    if (type === 'faq' && samples.common) {
      // Tìm FAQ gần nhất
      let bestMatch = null;
      let bestScore = 0;

      for (const item of samples.common) {
        const score = this.calculateSimilarity(prompt, item.q);
        if (score > bestScore && score > 0.3) {
          bestScore = score;
          bestMatch = item;
        }
      }

      if (bestMatch) {
        return {
          content: ${samples.greeting}\n\nQ: ${bestMatch.q}\nA: ${bestMatch.a},
          matched: true,
          confidence: bestScore
        };
      }
    }

    if (samples.defaults) {
      return {
        content: samples.defaults.note,
        ...samples.defaults
      };
    }

    return null;
  }

  // === KIỂM TRA TRẠNG THÁI ONLINE/OFFLINE ===
  async checkOnlineStatus() {
    try {
      await this.redis.ping();
      this.isOnline = true;
      this.lastOnline = Date.now();
      return true;
    } catch {
      this.isOnline = false;
      return false;
    }
  }

  getStatus() {
    return {
      isOnline: this.isOnline,
      lastOnline: this.lastOnline,
      localCacheSize: this.localCache.size,
      uptimePercentage: this.calculateUptime()
    };
  }

  calculateUptime() {
    const totalTime = Date.now() - this.lastOnline;
    const offlineTime = 0; // Cần track offline periods
    return ((totalTime - offlineTime) / totalTime) * 100;
  }
}

module.exports = new OfflineDegradationManager();

Tích Hợp Hoàn Chỉnh — Hệ Thống Resilience

Đây là code tích hợp cuối cùng, kết hợp cả ba lớp phòng thủ:

const MultiVendorGateway = require('./multi-vendor-gateway');
const LocalModelManager = require('./local-model-manager');
const OfflineManager = require('./offline-degradation');

// === AI RESILIENCE SYSTEM ===
class AIResilienceSystem {
  constructor() {
    this.gateway = MultiVendorGateway;
    this.local = LocalModelManager;
    this.offline = OfflineManager;
    this.metrics = {
      totalRequests: 0,
      cloudRequests: 0,
      localRequests: 0,
      cacheHits: 0,
      offlineHits: 0,
      costs: { cloud: 0, local: 0 }
    };
  }

  async initialize() {
    console.log('🚀 Initializing AI Resilience System...');
    
    // Khởi tạo local model
    await this.local.initialize();
    
    // Set fallback function
    this.local.fallbackToCloud = (prompt, options) => this.callCloud(prompt, options);
    
    // Khởi tạo offline manager
    this.offline.initializeSampleResponses();
    
    // Health check định kỳ
    this.startHealthChecks();
    
    console.log('✅ System initialized successfully');
  }

  async callCloud(prompt, options = {}) {
    return this.gateway.generate(prompt, {
      ...options,
      taskType: options.critical ? 'critical' : 'normal'
    });
  }

  // === XỬ LÝ REQUEST CHÍNH ===
  async processRequest(prompt, options = {}) {
    this.metrics.totalRequests++;
    const startTime = Date.now();

    try {
      // Bước 1: Kiểm tra cache trước
      const cached = await this.offline.get(prompt, options);
      if (cached && cached.fresh) {
        this.metrics.cacheHits++;
        return {
          ...cached.response,
          _meta: {
            source: 'cache',
            latency: Date.now() - startTime
          }
        };
      }

      // Bước 2: Thử local model cho task phù hợp
      if (this.local.shouldUseLocal(options.complexity)) {
        try {
          const localResult = await this.local.generate(prompt, options);
          this.metrics.localRequests++;
          this.metrics.costs.local += localResult.cost;
          
          // Cache kết quả
          await this.offline.set(prompt, localResult, options);
          
          return {
            ...localResult.response,
            _meta: {
              source: 'local',
              model: localResult.model,
              latency: localResult.latency,
              cost: localResult.cost
            }
          };
        } catch (localError) {
          console.warn('Local model failed:', localError.message);
        }
      }

      // Bước 3: Gọi cloud với fallback
      const cloudResult = await this.callCloudWithFallback(prompt, options);
      this.metrics.cloudRequests++;
      this.metrics.costs.cloud += cloudResult.cost;

      // Cache kết quả
      await this.offline.set(prompt, cloudResult, options);

      return {
        ...cloudResult.response,
        _meta: {
          source: 'cloud',
          provider: cloudResult.provider,
          model: cloudResult.model,
          latency: Date.now() - startTime,
          cost: cloudResult.cost
        }
      };

    } catch (error) {
      console.error('All providers failed:', error.message);
      
      // Bước 4: Graceful degradation
      const offlineResult = await this.offline.handleOfflineRequest(prompt, options);
      this.metrics.offlineHits++;
      
      return offlineResult;
    }
  }

  async callCloudWithFallback(prompt, options = {}) {
    // Ưu tiên budget provider cho task thông thường
    if (!options.critical) {
      try {
        const budgetResult = await this.gateway.generate(prompt, {
          ...options,
          taskType: 'budget'
        });
        return budgetResult;
      } catch {
        console.warn('Budget provider failed, trying primary...');
      }
    }

    // Fallback sang primary provider
    return this.gateway.generate(prompt, {
      ...options,
      taskType: 'critical'
    });
  }

  // === HEALTH CHECKS ===
  startHealthChecks() {
    // Check local model
    setInterval(async () => {
      await this.local.initialize();
    }, 30000);

    // Check offline system
    setInterval(async () => {
      await this.offline.checkOnlineStatus();
    }, 10000);

    // Log metrics
    setInterval(() => {
      this.logMetrics();
    }, 60000);
  }

  logMetrics() {
    const total = this.metrics.totalRequests;
    if (total === 0) return;

    console.log('\n📊 === AI RESILIENCE METRICS ===');
    console.log(Total Requests: ${total});
    console.log(Cloud: ${this.metrics.cloudRequests} (${(this.metrics.cloudRequests/total*100).toFixed(1)}%));
    console.log(Local: ${this.metrics.localRequests} (${(this.metrics.localRequests/total*100).toFixed(1)}%));
    console.log(Cache Hits: ${this.metrics.cacheHits} (${(this.metrics.cacheHits/total*100).toFixed(1)}%));
    console.log(Offline Hits: ${this.metrics.offlineHits} (${(this.metrics.offlineHits/total*100).toFixed(1)}%));
    console.log(Cloud Cost: $${this.metrics.costs.cloud.toFixed(4)});
    console.log(Local Cost: $${this.metrics.costs.local.toFixed(4)});
    console.log(Total Cost: $${(this.metrics.costs.cloud + this.metrics.costs.local).toFixed(4)});
    
    // So sánh với single provider
    const singleProviderCost = total * 0.001 * 15; // Giả định dùng Claude hết
    console.log(\n💰 Savings vs Single Provider: $${(singleProviderCost - this.metrics.costs.cloud).toFixed(4)});
    console.log('================================\n');
  }

  // === STATS ===
  getStats() {
    return {
      ...this.metrics,
      localAvailable: this.local.isAvailable,
      offlineAvailable: this.offline.isOnline,
      cacheStatus: this.offline.getStatus()
    };
  }
}

// === SỬ DỤNG ===
async function main() {
  const system = new AIResilienceSystem();
  await system.initialize();

  // Ví dụ request
  const testPrompts = [
    { prompt: 'Tóm tắt bài viết này', options: { complexity: 'simple', type: 'summarize' } },
    { prompt: 'Phân loại email này là urgent hay normal', options: { complexity: 'simple', type: 'classify' } },
    { prompt: 'Viết code Python để sort array', options: { critical: true } }
  ];

  for (const { prompt, options } of testPrompts) {
    const result = await system.processRequest(prompt, options);
    console.log('Result:', result._meta);
  }
}

// Chạy với HolySheep API
// Đăng ký tại: https://www.holysheep.ai/register
const HOLYSHEEP_CONFIG = {
  baseUrl: 'https://api.holysheep.ai/v1',
  apiKey: process.env.HOLYSHEEP_API_KEY || 'YOUR_HOLYS