Mở Đầu: Câu Chuyện Đỉnh Dịch Vụ Thương Mại Điện Tử

Tôi vẫn nhớ rõ đêm mà hệ thống chatbot của một sàn thương mại điện tử lớn tại Việt Nam sụp đổ. Đó là Black Friday 2024, lượng truy cập tăng 800% so với ngày thường. Khách hàng chờ đợi phản hồi từ AI chatbot hơn 30 giây, tỷ lệ bỏ giỏ hàng tăng vọt. Đội kỹ thuật phải switch sang chế độ fallback, mất 3 tiếng đồng hồ để khắc phục. Sau sự cố đó, tôi được giao dẫn dắt dự án triển khai CDN edge AI inference — đưa model AI đến gần người dùng nhất có thể, giảm độ trễ từ hàng trăm mili-giây xuống dưới 50ms. Kết quả: đợt flash sale tiếp theo, hệ thống xử lý 50,000 request/giây với độ trễ trung bình 23ms. Bài viết này chia sẻ toàn bộ hành trình triển khai, từ lý thuyết đến code production-ready sử dụng HolySheep AI.

CDN Edge AI Inference Là Gì?

CDN (Content Delivery Network) edge inference là kiến trúc đưa các tác vụ suy luận AI (AI inference) đến các edge node — server vật lý đặt gần người dùng nhất. Thay vì request phải đi qua nhiều hop đến data center trung tâm, payload được xử lý tại CDN PoP (Point of Presence) gần nhất. Ưu điểm vượt trội:

Kiến Trúc Triển Khai

Kiến trúc tổng thể gồm 4 thành phần chính:
+-------------------+     +-------------------+     +-------------------+
|   Client App      |     |   CDN Edge Node   |     |   AI Model Cache  |
|   (Mobile/Web)    |---->|   (PoP Location)  |---->|   (KV Store)      |
+-------------------+     +-------------------+     +-------------------+
                                    |
                                    v
                          +-------------------+
                          |   HolySheep API   |
                          |   (api.holysheep  |
                          |    .ai/v1)        |
                          +-------------------+
Data flow:
  1. Request từ client đến CDN edge gần nhất
  2. Edge node kiểm tra cache cho prompt/response đã tồn tại
  3. Nếu cache miss, gọi HolyShehep AI API tại edge
  4. Response được cache lại tại edge và trả về client
  5. Subsequent request cùng prompt được serve từ cache

Triển Khai Chi Tiết Với HolySheep AI

HolyShehep AI cung cấp API tương thích OpenAI format, hỗ trợ nhiều model AI với pricing cực kỳ cạnh tranh. Đặc biệt, tỷ giá ¥1=$1 giúp tiết kiệm 85%+ so với các provider khác. Các model được hỗ trợ:

Code Implementation: Edge Worker (Cloudflare Workers)

Dưới đây là implementation production-ready cho Cloudflare Workers với caching layer:
// edge-ai-worker.js
// Triển khai CDN Edge AI Inference với HolySheep AI

const HOLYSHEEP_API_KEY = 'YOUR_HOLYSHEEP_API_KEY';
const HOLYSHEEP_BASE_URL = 'https://api.holysheep.ai/v1';
const CACHE_TTL = 3600; // 1 hour in seconds
const MODEL = 'deepseek-v3.2'; // $0.42/MTok - tiết kiệm nhất

export default {
  async fetch(request, env, ctx) {
    const corsHeaders = {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    };

    // Handle CORS preflight
    if (request.method === 'OPTIONS') {
      return new Response(null, { headers: corsHeaders });
    }

    try {
      const body = await request.json();
      const { prompt, conversation_id, temperature = 0.7, max_tokens = 1000 } = body;

      // Generate cache key từ prompt hash
      const cacheKey = await generateCacheKey(prompt, conversation_id);

      // Kiểm tra cache trước
      const cache = caches.default;
      const cachedResponse = await cache.match(cacheKey);

      if (cachedResponse) {
        console.log([EDGE-CACHE-HIT] ${cacheKey});
        const data = await cachedResponse.json();
        return new Response(JSON.stringify({
          ...data,
          cached: true,
          edge_location: request.cf?.colo || 'unknown'
        }), {
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }

      console.log([EDGE-CACHE-MISS] Calling HolySheep API);

      // Gọi HolySheep AI API
      const startTime = Date.now();
      const aiResponse = await callHolySheepAPI(prompt, {
        temperature,
        max_tokens,
        model: MODEL
      });
      const latency = Date.now() - startTime;

      console.log([HOLYSHEEP] Response time: ${latency}ms);

      const responseData = {
        id: aiResponse.id,
        model: aiResponse.model,
        content: aiResponse.choices[0].message.content,
        usage: aiResponse.usage,
        latency_ms: latency,
        timestamp: new Date().toISOString()
      };

      // Cache response
      const cacheResponse = new Response(JSON.stringify(responseData), {
        headers: {
          'Content-Type': 'application/json',
          'Cache-Control': public, max-age=${CACHE_TTL},
          'X-Edge-Latency': ${latency}ms
        }
      });

      ctx.waitUntil(cache.put(cacheKey, cacheResponse));

      return new Response(JSON.stringify({
        ...responseData,
        cached: false,
        edge_location: request.cf?.colo || 'unknown'
      }), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });

    } catch (error) {
      console.error('[EDGE-ERROR]', error);
      return new Response(JSON.stringify({
        error: error.message,
        code: error.code || 'INTERNAL_ERROR'
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  }
};

async function generateCacheKey(prompt, conversationId) {
  const data = JSON.stringify({ prompt, conversationId });
  const encoder = new TextEncoder();
  const dataBuffer = encoder.encode(data);
  const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
  return ai-inference:${hashHex};
}

async function callHolySheepAPI(prompt, options) {
  const response = await fetch(${HOLYSHEEP_BASE_URL}/chat/completions, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': Bearer ${HOLYSHEEP_API_KEY}
    },
    body: JSON.stringify({
      model: options.model,
      messages: [
        { role: 'user', content: prompt }
      ],
      temperature: options.temperature,
      max_tokens: options.max_tokens
    })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(HolySheep API Error: ${error.error?.message || response.statusText});
  }

  return await response.json();
}

Code Implementation: Node.js Backend Với Rate Limiting

Implementation cho Node.js backend với rate limiting và automatic retry:
// edge-ai-client.js
// Node.js client cho CDN Edge AI Inference với HolySheep

const HOLYSHEEP_BASE_URL = 'https://api.holysheep.ai/v1';
const HOLYSHEEP_API_KEY = 'YOUR_HOLYSHEEP_API_KEY';

class EdgeAIClient {
  constructor(options = {}) {
    this.baseURL = options.baseURL || HOLYSHEEP_BASE_URL;
    this.apiKey = options.apiKey || HOLYSHEEP_API_KEY;
    this.maxRetries = options.maxRetries || 3;
    this.retryDelay = options.retryDelay || 1000;
    this.defaultModel = options.model || 'gemini-2.5-flash';
    this.rateLimiter = new Map();
    this.rateLimitWindow = 60000; // 1 phút
    this.maxRequestsPerWindow = 100;
  }

  // Kiểm tra rate limit
  checkRateLimit(key) {
    const now = Date.now();
    const record = this.rateLimiter.get(key);

    if (!record) {
      this.rateLimiter.set(key, { count: 1, resetTime: now + this.rateLimitWindow });
      return true;
    }

    if (now > record.resetTime) {
      this.rateLimiter.set(key, { count: 1, resetTime: now + this.rateLimitWindow });
      return true;
    }

    if (record.count >= this.maxRequestsPerWindow) {
      return false;
    }

    record.count++;
    return true;
  }

  // Retry logic với exponential backoff
  async retryWithBackoff(fn, retries = 0) {
    try {
      return await fn();
    } catch (error) {
      if (retries < this.maxRetries && this.isRetryableError(error)) {
        const delay = this.retryDelay * Math.pow(2, retries);
        console.log([RETRY] Attempt ${retries + 1}/${this.maxRetries} after ${delay}ms);
        await this.sleep(delay);
        return this.retryWithBackoff(fn, retries + 1);
      }
      throw error;
    }
  }

  isRetryableError(error) {
    const retryableCodes = [408, 429, 500, 502, 503, 504];
    return retryableCodes.includes(error.status) || error.code === 'ECONNRESET';
  }

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

  // Chat completion - text generation
  async chatCompletion(messages, options = {}) {
    if (!this.checkRateLimit('global')) {
      throw new Error('RATE_LIMIT_EXCEEDED: Quá nhiều request. Vui lòng thử lại sau.');
    }

    const startTime = Date.now();
    const model = options.model || this.defaultModel;

    const requestBody = {
      model,
      messages,
      temperature: options.temperature ?? 0.7,
      max_tokens: options.max_tokens ?? 1000,
      top_p: options.top_p ?? 1,
    };

    if (options.stream) {
      return this.streamChatCompletion(requestBody, startTime);
    }

    return this.retryWithBackoff(async () => {
      const response = await fetch(${this.baseURL}/chat/completions, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': Bearer ${this.apiKey}
        },
        body: JSON.stringify(requestBody)
      });

      if (!response.ok) {
        const error = await response.json().catch(() => ({}));
        const err = new Error(error.error?.message || 'API Error');
        err.status = response.status;
        err.code = error.error?.code;
        throw err;
      }

      const data = await response.json();
      const latency = Date.now() - startTime;

      return {
        ...data,
        _meta: {
          latency_ms: latency,
          model,
          provider: 'holysheep',
          pricing: this.getPricing(model)
        }
      };
    });
  }

  // Streaming completion
  async *streamChatCompletion(requestBody, startTime) {
    const response = await fetch(${this.baseURL}/chat/completions, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': Bearer ${this.apiKey}
      },
      body: JSON.stringify({ ...requestBody, stream: true })
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error?.message || 'Stream Error');
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    let totalLatency = Date.now() - startTime;

    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6);
            if (data === '[DONE]') {
              yield { done: true, latency_ms: totalLatency };
            } else {
              try {
                const parsed = JSON.parse(data);
                yield parsed;
              } catch (e) {
                // Skip invalid JSON
              }
            }
          }
        }
      }
    } finally {
      reader.releaseLock();
    }
  }

  // Embeddings cho RAG system
  async embeddings(texts, model = 'embedding-v2') {
    const inputArray = Array.isArray(texts) ? texts : [texts];

    const response = await this.retryWithBackoff(async () => {
      const res = await fetch(${this.baseURL}/embeddings, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': Bearer ${this.apiKey}
        },
        body: JSON.stringify({ model, input: inputArray })
      });

      if (!res.ok) {
        const error = await res.json();
        throw new Error(error.error?.message || 'Embeddings Error');
      }

      return res.json();
    });

    return Array.isArray(texts) ? response.data : response.data[0];
  }

  getPricing(model) {
    const pricing = {
      'gpt-4.1': { input: 8, output: 8, unit: 'per million tokens' },
      'claude-sonnet-4.5': { input: 15, output: 15, unit: 'per million tokens' },
      'gemini-2.5-flash': { input: 2.5, output: 2.5, unit: 'per million tokens' },
      'deepseek-v3.2': { input: 0.42, output: 0.42, unit: 'per million tokens' }
    };
    return pricing[model] || pricing['deepseek-v3.2'];
  }
}

// Usage example
async function main() {
  const client = new EdgeAIClient({
    model: 'deepseek-v3.2', // $0.42/MTok - tiết kiệm cho RAG
    maxRetries: 3
  });

  try {
    // Chat completion
    const response = await client.chatCompletion([
      { role: 'system', content: 'Bạn là trợ lý AI cho hệ thống thương mại điện tử.' },
      { role: 'user', content: 'Tìm kiếm sản phẩm iPhone 15 Pro Max với giá dưới 30 triệu' }
    ], {
      temperature: 0.3,
      max_tokens: 500
    });

    console.log('Response:', response.choices[0].message.content);
    console.log('Latency:', response._meta.latency_ms, 'ms');
    console.log('Cost:', response._meta.pricing);

    // Embeddings cho semantic search
    const embedding = await client.embeddings('iPhone 15 Pro Max 256GB');
    console.log('Embedding dimensions:', embedding.embedding?.length);

  } catch (error) {
    console.error('Error:', error.message);
  }
}

module.exports = { EdgeAIClient };
// Run: node edge-ai-client.js

Code Implementation: Vercel Edge Function

Triển khai trên Vercel Edge Runtime với real-time streaming:
// app/api/ai-inference/route.ts
// Vercel Edge Function cho CDN Edge AI với HolySheep

import { NextRequest, NextResponse } from 'next/server';

const HOLYSHEEP_API_KEY = process.env.HOLYSHEEP_API_KEY;
const HOLYSHEEP_BASE_URL = 'https://api.holysheep.ai/v1';

export const runtime = 'edge';
export const dynamic = 'force-dynamic';

export async function POST(request: NextRequest) {
  const startTime = Date.now();

  try {
    const { prompt, model = 'gemini-2.5-flash', stream = true, ...options } = await request.json();

    // Validate input
    if (!prompt || typeof prompt !== 'string') {
      return NextResponse.json(
        { error: 'Invalid prompt: must be a non-empty string' },
        { status: 400 }
      );
    }

    // Build request to HolySheep
    const upstreamResponse = await fetch(${HOLYSHEEP_BASE_URL}/chat/completions, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': Bearer ${HOLYSHEEP_API_KEY},
      },
      body: JSON.stringify({
        model,
        messages: [{ role: 'user', content: prompt }],
        stream,
        temperature: options.temperature ?? 0.7,
        max_tokens: options.max_tokens ?? 2000,
      }),
    });

    if (!upstreamResponse.ok) {
      const error = await upstreamResponse.json().catch(() => ({}));
      return NextResponse.json(
        { error: error.error?.message || 'HolySheep API Error' },
        { status: upstreamResponse.status }
      );
    }

    // Stream response back to client
    if (stream) {
      const encoder = new TextEncoder();
      const stream = new ReadableStream({
        async start(controller) {
          const reader = upstreamResponse.body?.getReader();
          if (!reader) {
            controller.close();
            return;
          }

          try {
            while (true) {
              const { done, value } = await reader.read();
              if (done) {
                // Send metadata footer
                const latency = Date.now() - startTime;
                controller.enqueue(encoder.encode(
                  data: ${JSON.stringify({ _edge_latency_ms: latency })}\n\n
                ));
                controller.enqueue(encoder.encode('data: [DONE]\n\n'));
                break;
              }
              controller.enqueue(value);
            }
          } catch (error) {
            controller.error(error);
          } finally {
            reader.releaseLock();
          }
        },
      });

      return new Response(stream, {
        headers: {
          'Content-Type': 'text/event-stream',
          'Cache-Control': 'no-cache',
          'Connection': 'keep-alive',
          'X-Edge-Provider': 'vercel',
          'X-Response-Time': ${Date.now() - startTime}ms,
        },
      });
    }

    // Non-streaming response
    const data = await upstreamResponse.json();
    return NextResponse.json({
      ...data,
      _meta: {
        latency_ms: Date.now() - startTime,
        edge_region: request.geo?.region || 'unknown',
        provider: 'holysheep',
      }
    });

  } catch (error) {
    console.error('[Edge-AI Error]', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}

// GET endpoint for health check
export async function GET() {
  return NextResponse.json({
    status: 'ok',
    provider: 'HolySheep AI',
    base_url: HOLYSHEEP_BASE_URL,
    timestamp: new Date().toISOString(),
  });
}

Tối Ưu Hiệu Suất Và Chi Phí

Qua quá trình triển khai thực tế, tôi rút ra một số best practice quan trọng:

1. Chiến Lược Cache Thông Minh

// Cache strategy matrix
const CACHE_CONFIG = {
  // Prompt dạng câu hỏi - cache lâu vì content ổn định
  'question': { ttl: 3600, priority: 'high' },
  // Prompt có context thay đổi theo user - cache ngắn
  'personalized': { ttl: 300, priority: 'low' },
  // Product search - cache với key theo category
  'product_search': { ttl: 1800, scope: 'category' },
  // RAG queries - cache với vector similarity
  'rag_query': { ttl: 7200, strategy: 'semantic' }
};

// Semantic cache implementation
async function semanticCacheLookup(prompt, threshold = 0.95) {
  const queryEmbedding = await client.embeddings(prompt);
  const cacheEntries = await redis.zrange('semantic_cache', 0, -1, 'WITHSCORES');

  for (const entry of cacheEntries) {
    const similarity = cosineSimilarity(queryEmbedding, entry.embedding);
    if (similarity >= threshold) {
      return { hit: true, response: entry.response, similarity };
    }
  }
  return { hit: false };
}

2. Model Selection Strategy

| Use Case | Model | Giá | Lý do | |----------|-------|-----|-------| | Simple Q&A | DeepSeek V3.2 | $0.42 | Tiết kiệm, đủ chính xác | | Code generation | GPT-4.1 | $8 | Quality cao nhất | | Real-time chat | Gemini 2.5 Flash | $2.50 | Balance speed/cost | | Complex analysis | Claude Sonnet 4.5 | $15 | Reasoning xuất sắc |

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

1. Lỗi 401 Unauthorized - API Key Không Hợp Lệ

Mô tả lỗi: Khi gọi API, nhận được response với status 401 và message "Invalid API key". Nguyên nhân: Mã khắc phục:
// Kiểm tra và validate API key
async function validateHolySheepKey(apiKey) {
  try {
    const response = await fetch('https://api.holysheep.ai/v1/models', {
      headers: {
        'Authorization': Bearer ${apiKey}
      }
    });

    if (response.status === 401) {
      throw new Error('INVALID_API_KEY: API key không hợp lệ. Vui lòng kiểm tra tại https://www.holysheep.ai/register');
    }

    if (!response.ok) {
      throw new Error(API Error: ${response.status});
    }

    const data = await response.json();
    console.log('Available models:', data.data.map(m => m.id));
    return true;
  } catch (error) {
    console.error('Key validation failed:', error.message);
    return false;
  }
}

// Sử dụng
const isValid = await validateHolySheepKey('YOUR_HOLYSHEEP_API_KEY');
if (!isValid) {
  // Redirect user đến trang đăng ký
  window.location.href = 'https://www.holysheep.ai/register';
}

2. Lỗi 429 Rate Limit Exceeded

Mô tả lỗi: Request bị reject với "Rate limit exceeded" sau khi gửi nhiều request liên tiếp. Nguyên nhân: Mã khắc phục:
// Advanced rate limiter với queue system
class RateLimitedClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.requestQueue = [];
    this.processing = false;
    this.requestsPerSecond = 10;
    this.lastRequestTime = 0;
  }

  async request(endpoint, body) {
    return new Promise((resolve, reject) => {
      this.requestQueue.push({ endpoint, body, resolve, reject });
      this.processQueue();
    });
  }

  async processQueue() {
    if (this.processing || this.requestQueue.length === 0) return;

    this.processing = true;

    while (this.requestQueue.length > 0) {
      const now = Date.now();
      const timeSinceLastRequest = now - this.lastRequestTime;
      const delay = Math.max(0, 1000 / this.requestsPerSecond - timeSinceLastRequest);

      if (delay > 0) {
        await new Promise(r => setTimeout(r, delay));
      }

      const { endpoint, body, resolve, reject } = this.requestQueue.shift();

      try {
        const response = await this.executeRequest(endpoint, body);
        resolve(response);
      } catch (error) {
        if (error.status === 429) {
          // Re-add to queue với delay cao hơn
          this.requestQueue.unshift({ endpoint, body, resolve, reject });
          await new Promise(r => setTimeout(r, 5000)); // Chờ 5s
        } else {
          reject(error);
        }
      }

      this.lastRequestTime = Date.now();
    }

    this.processing = false;
  }

  async executeRequest(endpoint, body) {
    const response = await fetch(https://api.holysheep.ai/v1${endpoint}, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': Bearer ${this.apiKey}
      },
      body: JSON.stringify(body)
    });

    if (!response.ok) {
      const error = await response.json().catch(() => ({}));
      const err = new Error(error.error?.message);
      err.status = response.status;
      throw err;
    }

    return response.json();
  }
}

// Sử dụng
const client = new RateLimitedClient('YOUR_HOLYSHEEP_API_KEY');

// Queue 100 requests - sẽ tự động rate limit
for (let i = 0; i < 100; i++) {
  client.request('/chat/completions', {
    model: 'deepseek-v3.2',
    messages: [{ role: 'user', content: Query ${i} }]
  }).then(r => console.log(Completed ${i}));
}

3. Lỗi Connection Timeout / ECONNRESET

Mô tả lỗi: Request bị hủy giữa chừng với lỗi "Connection reset" hoặc "Timeout". Nguyên nhân: Mã khắc phục:
// Resilient HTTP client với timeout và circuit breaker
class ResilientHTTPClient {
  constructor() {
    this.failureCount = 0;
    this.failureThreshold = 5;
    this.circuitOpen = false;
    this.lastFailureTime = 0;
    this.cooldownPeriod = 60000; // 1 phút
  }

  async post(url, body, options = {}) {
    const timeout = options.timeout || 30000;
    const retries = options.retries || 3;

    // Circuit breaker check
    if (this.circuitOpen) {
      if (Date.now() - this.lastFailureTime > this.cooldownPeriod) {
        this.circuitOpen = false;
        this.failureCount = 0;
        console.log('[CIRCUIT] Connection restored');
      } else {
        throw new Error('CIRCUIT_OPEN: Service temporarily unavailable');
      }
    }

    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);

    for (let attempt = 1; attempt <= retries; attempt++) {
      try {
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': Bearer ${process.env.HOLYSHEEP_API_KEY}
          },
          body: JSON.stringify(body),
          signal: controller.signal
        });

        clearTimeout(timeoutId);
        this.recordSuccess();
        return response.json();

      } catch (error) {
        console.error([ATTEMPT ${attempt}/${retries}] Error:, error.message);

        if (attempt === retries) {
          this.recordFailure();
          throw error;
        }

        // Exponential backoff: 1s, 2s, 4s
        await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt - 1)));
      }
    }
  }

  recordSuccess() {
    this.failureCount = 0;
  }

  recordFailure() {
    this.failureCount++;
    this.lastFailureTime = Date.now();

    if (this.failureCount >= this.failureThreshold) {
      this.circuitOpen = true;
      console.error('[CIRCUIT] Opened due to consecutive failures');
    }
  }
}

// Sử dụng
const httpClient = new ResilientHTTPClient();

async function callWithFallback(prompt) {
  try {
    // Thử HolySheep trước
    return await httpClient.post('https://api.holysheep.ai/v1/chat/completions', {
      model: 'gemini-2.5-flash',
      messages: [{ role: 'user', content: prompt }],
      max_tokens: 1000
    });
  } catch (error) {
    // Fallback: Trả về cached response hoặc default message
    console.error('[FALLBACK] Primary API failed, using cached response');
    return {
      choices: [{
        message: {
          content: 'Xin lỗi, hệ thống đang bận. Vui lòng thử lại sau.'
        }
      }],
      cached: true
    };
  }
}

4. Lỗi Context Window Exceeded

Mô tả lỗi: Model từ chối request với "maximum context length exceeded". Nguyên nhân: Mã khắc phục:
// Smart context manager với automatic truncation
class ContextManager {
  constructor(maxTokens = 4096) {
    this.maxTokens = maxTokens;
    this.reservedTokens = 500; // Buffer cho response
    this.availableTokens = maxTokens - this.reservedTokens;
  }

  buildMessages(conversationHistory, newPrompt, systemPrompt = '') {
    const messages = [];
    let totalTokens = 0;

    // Estimate tokens (rough: 1 token ≈ 4 chars for Vietnamese)