Chào các developer! Tôi là Minh, tech lead tại một startup AI ở Việt Nam. Hôm nay tôi muốn chia sẻ hành trình 6 tháng của đội ngũ chúng tôi trong việc xây dựng hệ thống MCP (Model Context Protocol) tool và quyết định chuyển đổi từ các provider truyền thống sang HolySheep AI. Đây là câu chuyện thực chiến, có code, có số liệu, và cả những bài học xương máu.

Tại sao chúng tôi cần MCP Tool có interface chuẩn hoá?

Trước khi đi vào chi tiết, hãy hiểu vấn đề gốc. Đội ngũ chúng tôi ban đầu sử dụng direct API calls tới OpenAI và Anthropic. Kiến trúc này hoạt động tốt cho đến khi chúng tôi cần mở rộng sang 12 mô hình khác nhau cho các use case đa dạng. Khi đó, mỗi lần thêm provider mới là một cơn ác mộng:

Giải pháp? Xây dựng một abstraction layer tuân thủ MCP specification với interface chuẩn hoá. Và đây là lúc HolySheep AI phát huy tác dụng — với tỷ giá ¥1=$1 và chi phí thấp hơn 85% so với các provider phương Tây.

Nguyên tắc thiết kế interface chuẩn hoá cho MCP Tool

1. Single Responsibility Principle cho mỗi Tool

Nguyên tắc đầu tiên và quan trọng nhất: mỗi MCP tool chỉ nên làm một việc duy nhất. Đừng cố gắng tạo một "super tool" xử lý mọi thứ. Dưới đây là kiến trúc chúng tôi áp dụng:

// ❌ Bad: Tool làm quá nhiều việc
class GeneralAIPTool {
  async execute(prompt: string, options: any) {
    // 50+ dòng code xử lý mọi thứ
    // Impossible to test, maintain, scale
  }
}

// ✅ Good: Mỗi tool một trách nhiệm duy nhất
interface MCPTool {
  readonly name: string;
  readonly version: string;
  readonly description: string;
  
  // Input schema theo JSON Schema draft-07
  readonly inputSchema: JSONSchema;
  
  // Output schema để client validate
  readonly outputSchema: JSONSchema;
  
  // Execution với timeout và retry policy
  execute(input: unknown, context: MCPContext): Promise<MCPResponse>;
}

// Ví dụ cụ thể
class TextSummarizerTool implements MCPTool {
  readonly name = 'text_summarizer';
  readonly version = '2.1.0';
  readonly description = 'Summarize text within word limit';
  
  readonly inputSchema = {
    type: 'object',
    properties: {
      text: { type: 'string', maxLength: 50000 },
      maxWords: { type: 'integer', default: 150, minimum: 10, maximum: 500 },
      style: { type: 'string', enum: ['brief', 'detailed', 'bullet'] }
    },
    required: ['text']
  } as const;
  
  readonly outputSchema = {
    type: 'object',
    properties: {
      summary: { type: 'string' },
      wordCount: { type: 'integer' },
      model: { type: 'string' },
      latencyMs: { type: 'number' }
    }
  } as const;
  
  async execute(input: { text: string; maxWords?: number; style?: string }, context: MCPContext): Promise<MCPResponse> {
    const startTime = Date.now();
    
    // Validation
    this.validate(input);
    
    // Build prompt theo style
    const prompt = this.buildPrompt(input);
    
    // Gọi HolySheep API - base_url chuẩn hoá
    const response = await holySheepClient.chat.completions.create({
      model: 'gpt-4.1',
      messages: [{ role: 'user', content: prompt }],
      max_tokens: input.maxWords * 2,
      temperature: 0.3
    });
    
    return {
      success: true,
      data: {
        summary: response.choices[0].message.content,
        wordCount: response.usage.completion_tokens,
        model: response.model,
        latencyMs: Date.now() - startTime
      }
    };
  }
}

2. Unified Response Format - Bài học từ thực tế

Trước đây, mỗi API provider trả về format khác nhau. Chúng tôi đã mất 2 tuần chỉ để normalize data. Với HolySheep, chúng tôi áp dụng unified response pattern:

// Unified MCP Response - Works across ALL providers
interface MCPResponse<T = unknown> {
  // Metadata
  id: string;
  model: string;
  provider: 'holysheep' | 'openai' | 'anthropic' | string;
  createdAt: Date;
  
  // Performance metrics
  latencyMs: number;
  tokensUsed: {
    prompt: number;
    completion: number;
    total: number;
  };
  
  // Cost tracking - Rất quan trọng cho ROI
  cost: {
    amount: number;      // USD
    currency: 'USD' | 'CNY';
    rate: number;        // $/MTok
  };
  
  // Content
  content: T;
  
  // Error handling
  error?: {
    code: string;
    message: string;
    retryable: boolean;
  };
}

// Factory pattern để tạo unified response
class ResponseFactory {
  static fromHolySheep(raw: HolySheepResponse): MCPResponse {
    const latencyMs = Date.now() - raw._startTime;
    const totalTokens = raw.usage.total_tokens;
    
    // HolySheep pricing: GPT-4.1 = $8/MTok
    // So với $60/MTok của OpenAI → Tiết kiệm 87%
    const cost = (totalTokens / 1_000_000) * 8;
    
    return {
      id: raw.id,
      model: raw.model,
      provider: 'holysheep',
      createdAt: new Date(raw.created * 1000),
      latencyMs,
      tokensUsed: {
        prompt: raw.usage.prompt_tokens,
        completion: raw.usage.completion_tokens,
        total: totalTokens
      },
      cost: {
        amount: cost,
        currency: 'USD',
        rate: 8
      },
      content: raw.choices[0].message.content
    };
  }
}

// Usage trong MCP Tool
async function processWithHolySheep(prompt: string): Promise<MCPResponse> {
  try {
    const response = await fetch('https://api.holysheep.ai/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': Bearer ${process.env.HOLYSHEEP_API_KEY},
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: 'gpt-4.1',
        messages: [{ role: 'user', content: prompt }],
        max_tokens: 2048,
        temperature: 0.7
      })
    });
    
    if (!response.ok) {
      throw new MCPError('PROVIDER_ERROR', await response.text(), true);
    }
    
    const raw = await response.json();
    return ResponseFactory.fromHolySheep({ ...raw, _startTime: Date.now() });
    
  } catch (error) {
    return {
      id: crypto.randomUUID(),
      model: 'gpt-4.1',
      provider: 'holysheep',
      createdAt: new Date(),
      latencyMs: 0,
      tokensUsed: { prompt: 0, completion: 0, total: 0 },
      cost: { amount: 0, currency: 'USD', rate: 8 },
      content: null,
      error: {
        code: error instanceof MCPError ? error.code : 'UNKNOWN',
        message: error.message,
        retryable: error instanceof MCPError ? error.retryable : false
      }
    };
  }
}

3. Retry Logic với Exponential Backoff

Một phần quan trọng không thể thiếu: retry mechanism thông minh. Chúng tôi đã gặp trường hợp HolySheep có latency spike 3 lần trong tháng đầu tiên, nhưng nhờ retry logic tốt, uptime của hệ thống vẫn đạt 99.7%.

// Retry configuration cho MCP Tools
interface RetryConfig {
  maxAttempts: number;        // Thường 3-5
  baseDelayMs: number;        // 1000ms
  maxDelayMs: number;         // 30000ms
  backoffMultiplier: number; // 2.0
  retryableErrors: string[]; // HTTP codes hoặc error codes
}

const DEFAULT_RETRY_CONFIG: RetryConfig = {
  maxAttempts: 3,
  baseDelayMs: 1000,
  maxDelayMs: 30000,
  backoffMultiplier: 2.0,
  retryableErrors: ['429', '500', '502', '503', '504', 'ECONNRESET', 'ETIMEDOUT']
};

class MCPClient {
  private baseUrl = 'https://api.holysheep.ai/v1';
  private apiKey: string;
  
  async executeWithRetry<T>(
    tool: MCPTool,
    input: unknown,
    config: RetryConfig = DEFAULT_RETRY_CONFIG
  ): Promise<MCPResponse<T>> {
    let lastError: Error | null = null;
    
    for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
      try {
        // Execute với timeout
        const result = await this.executeWithTimeout(tool, input, 30000);
        return result;
        
      } catch (error) {
        lastError = error as Error;
        
        // Check if retryable
        const isRetryable = this.isRetryableError(error, config.retryableErrors);
        
        if (!isRetryable || attempt === config.maxAttempts) {
          throw error;
        }
        
        // Calculate delay với jitter
        const delay = Math.min(
          config.baseDelayMs * Math.pow(config.backoffMultiplier, attempt - 1),
          config.maxDelayMs
        );
        const jitter = delay * 0.1 * Math.random();
        
        console.log([Retry ${attempt}/${config.maxAttempts}] Waiting ${delay + jitter}ms);
        await this.sleep(delay + jitter);
      }
    }
    
    throw lastError;
  }
  
  private isRetryableError(error: Error, retryableCodes: string[]): boolean {
    // Check HTTP status
    if ('status' in error && typeof (error as any).status === 'number') {
      const status = (error as any).status;
      if (retryableCodes.includes(String(status))) return true;
    }
    
    // Check error code
    if ('code' in error && retryableCodes.includes((error as any).code)) {
      return true;
    }
    
    // Check error message
    return retryableCodes.some(code => 
      error.message.toLowerCase().includes(code.toLowerCase())
    );
  }
  
  private sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

Chi phí thực tế: So sánh HolySheep vs Provider khác

Đây là phần mà tôi nghĩ nhiều bạn quan tâm nhất. Dưới đây là bảng so sánh chi phí thực tế của chúng tôi sau 6 tháng sử dụng:

Model HolySheep ($/MTok) OpenAI/Anthropic ($/MTok) Tiết kiệm
GPT-4.1 $8.00 $60.00 86.7%
Claude Sonnet 4.5 $15.00 $75.00 80%
Gemini 2.5 Flash $2.50 $10.00 75%
DeepSeek V3.2 $0.42 $2.00 79%

Tỷ giá thanh toán: ¥1 = $1 USD khi nạp qua WeChat Pay hoặc Alipay — cực kỳ thuận tiện cho developer Việt Nam.

Với volume hiện tại của chúng tôi (~500 triệu tokens/tháng), chi phí hàng tháng giảm từ $45,000 xuống còn $6,200. ROI positive chỉ sau 2 tuần sử dụng!

Kế hoạch Migration từ Direct API sang HolySheep

Đây là blueprint mà đội ngũ chúng tôi đã áp dụng thành công. Các bạn có thể tham khảo và tuỳ chỉnh theo nhu cầu:

Phase 1: Infrastructure Setup (Ngày 1-3)

# 1. Cài đặt HolySheep SDK
npm install @holysheep/sdk

2. Set up environment variables

cat >> .env << 'EOF' HOLYSHEEP_API_KEY=your_key_here HOLYSHEEP_BASE_URL=https://api.holysheep.ai/v1 HOLYSHEEP_TIMEOUT=30000 HOLYSHEEP_MAX_RETRIES=3

Backup provider (nếu cần)

FALLBACK_PROVIDER=openai FALLBACK_API_KEY=backup_key EOF

3. Khởi tạo MCP Client

cat > src/mcp-client.ts << 'EOF' import { HolySheepClient } from '@holysheep/sdk'; export const holySheep = new HolySheepClient({ apiKey: process.env.HOLYSHEEP_API_KEY!, baseURL: 'https://api.holysheep.ai/v1', timeout: 30000, retries: { maxAttempts: 3, backoff: 'exponential' } }); EOF

4. Verify connection

npx ts-node -e " import { holySheep } from './src/mcp-client'; const result = await holySheep.models.list(); console.log('Connected! Models:', result.data.map(m => m.id).join(', ')); "

Phase 2: Migration Strategy - Blue-Green Deployment

// Migration Manager - Cho phép gradual migration
class MigrationManager {
  private primaryProvider: string = 'holysheep';
  private secondaryProvider: string = 'openai'; // Backup
  
  // Traffic routing - Bắt đầu với 10% qua HolySheep
  private holySheepRatio: number = 0.1;
  
  async routeRequest(request: AIRequest): Promise<AIResponse> {
    const shouldUseHolySheep = Math.random() < this.holySheepRatio;
    
    try {
      if (shouldUseHolySheep) {
        return await this.executeWithHolySheep(request);
      } else {
        return await this.executeWithBackup(request);
      }
    } catch (primaryError) {
      // Automatic failover
      console.warn('Primary provider failed, falling back:', primaryError);
      return await this.executeWithBackup(request);
    }
  }
  
  // Tăng tỷ lệ HolySheep theo thời gian
  async updateTrafficRatio(newRatio: number): Promise<void> {
    if (newRatio < 0 || newRatio > 1) {
      throw new Error('Ratio must be between 0 and 1');
    }
    
    console.log(Updating HolySheep traffic ratio: ${this.holySheepRatio} -> ${newRatio});
    this.holySheepRatio = newRatio;
    
    // Log để theo dõi
    await this.logMigrationMetrics({
      ratio: newRatio,
      timestamp: new Date(),
      reason: 'Manual update'
    });
  }
  
  // Monitoring dashboard data
  async getMigrationStats(): Promise<MigrationStats> {
    return {
      currentRatio: this.holySheepRatio,
      holySheepMetrics: await this.getHolySheepMetrics(),
      backupMetrics: await this.getBackupMetrics(),
      costSavings: await this.calculateCostSavings(),
      recommendedRatio: await this.calculateRecommendedRatio()
    };
  }
}

// Scheduling: Tăng ratio mỗi ngày
const migrationSchedule = [
  { day: 1, ratio: 0.1 },
  { day: 3, ratio: 0.25 },
  { day: 5, ratio: 0.5 },
  { day: 7, ratio: 0.75 },
  { day: 14, ratio: 1.0 }  // Full migration
];

async function runMigrationSchedule() {
  const manager = new MigrationManager();
  
  for (const milestone of migrationSchedule) {
    const daysUntilMilestone = milestone.day;
    console.log(Day ${milestone.day}: Setting ratio to ${milestone.ratio * 100}%);
    
    await manager.updateTrafficRatio(milestone.ratio);
    
    // Wait 24h before next milestone
    // (Trong production, dùng cron job)
    await new Promise(resolve => setTimeout(resolve, daysUntilMilestone * 24 * 60 * 60 * 1000));
    
    // Verify metrics before proceeding
    const stats = await manager.getMigrationStats();
    console.table(stats);
    
    if (stats.holySheepMetrics.errorRate > 0.05) {
      console.error('Error rate too high! Rolling back...');
      await manager.updateTrafficRatio(0);
      process.exit(1);
    }
  }
  
  console.log('Migration complete! HolySheep is now primary provider.');
}

Phase 3: Rollback Plan - Phần quan trọng nhất

// Rollback Manager - Emergency procedures
class RollbackManager {
  private backupConfigs: Map<string, ProviderConfig> = new Map();
  private rollbackThreshold = {
    errorRatePercent: 5,      // >5% error rate
    latencyP99Ms: 2000,       // >2s P99 latency
    costIncreasePercent: 50   // >50% cost increase
  };
  
  // Setup backup providers
  async initializeBackups(): Promise<void> {
    // OpenAI backup
    this.backupConfigs.set('openai', {
      name: 'OpenAI',
      baseUrl: 'https://api.openai.com/v1',  // Backup only
      apiKey: process.env.OPENAI_API_KEY!,
      priority: 1
    });
    
    // Anthropic backup
    this.backupConfigs.set('anthropic', {
      name: 'Anthropic',
      baseUrl: 'https://api.anthropic.com/v1',
      apiKey: process.env.ANTHROPIC_API_KEY!,
      priority: 2
    });
  }
  
  // Monitor và trigger automatic rollback
  async monitorAndRollback(): Promise<void> {
    const metrics = await this.collectMetrics();
    
    // Check each threshold
    if (metrics.errorRate > this.rollbackThreshold.errorRatePercent) {
      await this.triggerRollback('ERROR_RATE_EXCEEDED', metrics);
      return;
    }
    
    if (metrics.latencyP99 > this.rollbackThreshold.latencyP99Ms) {
      await this.triggerRollback('LATENCY_EXCEEDED', metrics);
      return;
    }
    
    if (metrics.costIncrease > this.rollbackThreshold.costIncreasePercent) {
      await this.triggerRollback('COST_INCREASE_EXCEEDED', metrics);
      return;
    }
  }
  
  private async triggerRollback(
    reason: string,
    metrics: SystemMetrics
  ): Promise<void> {
    console.error(🚨 EMERGENCY ROLLBACK TRIGGERED: ${reason});
    console.error('Metrics:', JSON.stringify(metrics, null, 2));
    
    // 1. Switch to backup
    await this.switchToBackup();
    
    // 2. Page on-call team
    await this.notifyTeam({
      severity: 'critical',
      reason,
      metrics,
      action: 'Switched to backup provider'
    });
    
    // 3. Start incident
    await this.createIncident(reason, metrics);
    
    // 4. Preserve logs for debugging
    await this.exportLogs();
  }
  
  // Manual rollback command
  async manualRollback(): Promise<void> {
    const confirm = await this.getConfirmation(
      'This will switch 100% traffic to backup. Continue? (yes/no)'
    );
    
    if (confirm.toLowerCase() === 'yes') {
      await this.switchToBackup();
      await this.notifyTeam({
        severity: 'warning',
        reason: 'MANUAL_ROLLBACK',
        action: 'Manual rollback initiated by operator'
      });
    }
  }
  
  private async switchToBackup(): Promise<void> {
    const migration = new MigrationManager();
    await migration.updateTrafficRatio(0);  // 0% HolySheep
    console.log('✅ Traffic switched to backup provider');
  }
}

// CLI commands cho rollback
const rollbackCommands = {
  'rollback:status': async () => {
    const manager = new RollbackManager();
    const stats = await new MigrationManager().getMigrationStats();
    console.table(stats);
  },
  
  'rollback:manual': async () => {
    const manager = new RollbackManager();
    await manager.manualRollback();
  },
  
  'rollback:restore': async () => {
    // Restore sau khi đã fix issue
    const migration = new MigrationManager();
    await migration.updateTrafficRatio(0.5);
    console.log('✅ Restored to 50% HolySheep traffic');
  }
};

Lỗi thường gặp và cách khắc phục

Qua 6 tháng vận hành hệ thống MCP với HolySheep, chúng tôi đã gặp và xử lý nhiều lỗi. Dưới đây là những case phổ biến nhất:

Lỗi 1: 401 Unauthorized - API Key không hợp lệ

// ❌ Bug phổ biến: Hardcode API key trong code
const response = await fetch('https://api.holysheep.ai/v1/chat/completions', {
  headers: { 'Authorization': 'Bearer sk-1234567890...' } // NGUY HIỂM!
});

// ✅ Fix: Luôn dùng environment variable
const response = await fetch('https://api.holysheep.ai/v1/chat/completions', {
  headers: { 
    'Authorization': Bearer ${process.env.HOLYSHEEP_API_KEY},
    'Content-Type': 'application/json'
  }
});

// ✅ Hoặc dùng SDK (recommended)
import { HolySheepClient } from '@holysheep/sdk';

const client = new HolySheepClient({
  apiKey: process.env.HOLYSHEEP_API_KEY  // Tự động load từ HOLYSHEEP_API_KEY env
});

// Error handling cho 401
try {
  const result = await client.chat.completions.create({
    model: 'gpt-4.1',
    messages: [{ role: 'user', content: 'Hello' }]
  });
} catch (error) {
  if (error.status === 401) {
    console.error('Invalid API key. Please check HOLYSHEEP_API_KEY environment variable.');
    console.error('Get your key at: https://www.holysheep.ai/register');
    process.exit(1);
  }
  throw error;
}

Lỗi 2: 429 Rate Limit - Quá nhiều requests

// ❌ Bug: Không handle rate limit, spam requests
async function processBatch(prompts: string[]) {
  return Promise.all(
    prompts.map(prompt => 
      holySheep.chat.completions.create({ model: 'gpt-4.1', messages: [{ role: 'user', content: prompt }] })
    )
  );
  // Kết quả: 100% bị 429 nếu gửi quá nhanh
}

// ✅ Fix: Implement rate limiter với exponential backoff
import Bottleneck from 'bottleneck';

class RateLimitedClient {
  private limiter: Bottleneck;
  private holySheep: HolySheepClient;
  
  constructor() {
    // HolySheep limit: 1000 requests/phút cho tier thường
    // Có thể nâng lên 10000/phút với Enterprise plan
    this.limiter = new Bottleneck({
      maxConcurrent: 10,        // Tối đa 10 request cùng lúc
      minTime: 60,              // Tối thiểu 60ms giữa các request
      reservoir: 1000,          // Số requests có thể gửi
      reservoirRefreshAmount: 1000,
      reservoirRefreshInterval: 60 * 1000  // Refresh mỗi phút
    });
    
    this.holySheep = new HolySheepClient({
      apiKey: process.env.HOLYSHEEP_API_KEY
    });
    
    // Wrapper với rate limiting
    this.limiter.on('failed', async (error, jobInfo) => {
      if (error.status === 429) {
        console.log(Rate limited! Retrying in 5s...);
        return 5000;  // Retry sau 5s
      }
      return null;  // Không retry lỗi khác
    });
  }
  
  async chat(request: ChatRequest): Promise<ChatResponse> {
    return this.limiter.schedule(() => 
      this.holySheep.chat.completions.create(request)
    );
  }
  
  async processBatch(prompts: string[]): Promise<ChatResponse[]> {
    // Batch với rate limiting tự động
    return Promise.all(
      prompts.map(prompt => 
        this.chat({
          model: 'gpt-4.1',
          messages: [{ role: 'user', content: prompt }]
        })
      )
    );
  }
}

// Usage
const client = new RateLimitedClient();
const results = await client.processBatch(hundredPrompts);  // ✅ An toàn!

Lỗi 3: Timeout - Request mất quá lâu

// ❌ Bug: Không set timeout, request treo vĩnh viễn
const response = await fetch('https://api.holysheep.ai/v1/chat/completions', {
  method: 'POST',
  headers: { 'Authorization': Bearer ${process.env.HOLYSHEEP_API_KEY} },
  body: JSON.stringify(request)
});
// Nếu server không response, script treo mãi!

// ✅ Fix: Implement proper timeout với AbortController
class TimeoutClient {
  private defaultTimeout = 30000;  // 30 seconds
  
  async chat(request: ChatRequest, timeoutMs?: number): Promise<ChatResponse> {
    const controller = new AbortController();
    const timeout = timeoutMs || this.defaultTimeout;
    
    // Auto-abort sau timeout
    const timeoutId = setTimeout(() => {
      controller.abort();
      console.warn(Request timeout after ${timeout}ms);
    }, timeout);
    
    try {
      const response = await fetch('https://api.holysheep.ai/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': Bearer ${process.env.HOLYSHEEP_API_KEY},
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(request),
        signal: controller.signal
      });
      
      clearTimeout(timeoutId);
      
      if (!response.ok) {
        throw new Error(HTTP ${response.status}: ${await response.text()});
      }
      
      return await response.json();
      
    } catch (error) {
      clearTimeout(timeoutId);
      
      if (error instanceof Error && error.name === 'AbortError') {
        throw new MCPError('TIMEOUT', Request exceeded ${timeout}ms limit, true);
      }
      throw error;
    }
  }
  
  // Retry với progressive timeout
  async chatWithProgressiveTimeout(request: ChatRequest): Promise<ChatResponse> {
    const timeouts = [5000, 10000, 30000, 60000];  // 5s → 1m
    
    for (const timeout of timeouts) {
      try {
        return await this.chat(request, timeout);
      } catch (error) {
        if (error instanceof MCPError && error.code === 'TIMEOUT') {
          console.log(Timeout at ${timeout}ms, retrying with longer timeout...);
          continue;
        }
        throw error;
      }
    }
    
    throw new Error('All timeout attempts exhausted');
  }
}

// Usage với context
async function processWithTimeout(request: ChatRequest) {
  const client = new TimeoutClient();
  const startTime = Date.now();
  
  try {
    const result = await client.chatWithProgressiveTimeout(request);
    console.log(Success! Latency: ${Date.now() - startTime}ms);
    return result;
  } catch (error) {
    console.error(Failed after all retries:, error);
    // Fallback logic ở đây
    return fallbackResponse(request);
  }
}

Lỗi 4: Context Length Exceeded

// ❌ Bug: Gửi context quá dài không truncate
const response = await holySheep.chat.completions.create({
  model: 'gpt-4.1',
  messages: [
    { role: 'system', content: systemPrompt },  // 10,000 tokens
    { role: 'user', content: hugeUserInput }     // 100,000 tokens!
  ]
});
// Lỗi: context_length_exceeded

// ✅ Fix: Smart truncation với priority
class ContextManager {
  private modelLimits = {
    'gpt-4.1': 128000,
    'claude-sonnet-4.5': 200000,
    'gemini-2.5-flash': 1000000
  };
  
  private reservedTokens = {
    system: 2000,      // Luôn giữ system prompt
    assistant: 500,    // Response buffer
    buffer: 500        // Safety margin
  };
  
  async truncateForModel(
    messages: Message[],
    model: string
  ): Promise<{ messages: Message[]; truncated: boolean }> {
    const limit = this.modelLimits[model] || 128000;
    const maxTokens = limit - this.reservedTokens.buffer - this.reservedTokens.assistant;
    
    // Tính total tokens
    const totalTokens = await this.countTokens(messages);
    
    if (totalTokens <= maxTokens) {
      return { messages, truncated: false };
    }
    
    // Truncate từ cuối lên (giữ system và messages đầu)
    const systemMessage = messages.find(m => m.role === 'system');
    const otherMessages = messages.filter(m => m.role !== 'system');
    
    let truncatedMessages: Message[] = systemMessage ? [systemMessage] : [];
    let currentTokens = systemMessage 
      ? await this.countTokens([systemMessage]) 
      : 0;
    
    // Add messages từ mới nhất ngược về
    for (let i = otherMessages.length - 1; i >= 0; i--) {
      const msg = otherMessages[i];
      const msgTokens