Trong bài viết này, tôi sẽ chia sẻ những kinh nghiệm thực chiến khi thiết kế và đóng gói SDK cho API AI, dựa trên quá trình làm việc với hàng chục dự án tích hợp HolySheep AI. Bạn sẽ học cách tránh những bẫy phổ biến nhất khi làm việc với timeout, retry logic, và error handling.

Kịch bản lỗi thực tế: Khi mọi thứ sụp đổ vào 3 giờ sáng

Tôi vẫn nhớ rõ đêm định mệnh đó. Sản phẩm AI của khách hàng báo lỗi liên tục: ConnectionError: timeout after 30000ms. Người dùng không thể chat, doanh thu chảy ào ạt qua từng giây. Sau 4 tiếng debug căng thẳng, tôi phát hiện vấn đề nằm ở cách SDK xử lý retry — không có exponential backoff, không có circuit breaker, và quan trọng nhất: không có graceful degradation.

Bài học đắt giá đó đã thay đổi hoàn toàn cách tôi thiết kế SDK. Hãy cùng tôi đi sâu vào những best practice đã được kiểm chứng qua thực chiến.

1. Thiết kế TypeScript Client với Error Handling chặt chẽ

Khi làm việc với HolySheep AI, điều quan trọng nhất là xử lý lỗi một cách có hệ thống. Dưới đây là kiến trúc SDK production-ready mà tôi đã sử dụng cho 15+ dự án:

// holysheep-sdk.ts
interface HolySheepConfig {
  apiKey: string;
  baseUrl?: string;
  timeout?: number; // milliseconds
  maxRetries?: number;
  retryDelay?: number;
}

interface ChatMessage {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

interface ChatCompletionResponse {
  id: string;
  object: string;
  created: number;
  model: string;
  choices: Array<{
    index: number;
    message: ChatMessage;
    finish_reason: string;
  }>;
  usage: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  };
}

class HolySheepError extends Error {
  constructor(
    message: string,
    public statusCode?: number,
    public code?: string,
    public isRetryable: boolean = false
  ) {
    super(message);
    this.name = 'HolySheepError';
  }
}

class HolySheepClient {
  private baseUrl: string;
  private timeout: number;
  private maxRetries: number;
  private retryDelay: number;
  private apiKey: string;

  constructor(config: HolySheepConfig) {
    if (!config.apiKey) {
      throw new HolySheepError('API key is required', undefined, 'MISSING_API_KEY');
    }
    
    this.apiKey = config.apiKey;
    this.baseUrl = config.baseUrl || 'https://api.holysheep.ai/v1';
    this.timeout = config.timeout || 60000; // 60 seconds default
    this.maxRetries = config.maxRetries || 3;
    this.retryDelay = config.retryDelay || 1000;
  }

  private async sleep(ms: number): Promise {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  private calculateRetryDelay(attempt: number): number {
    // Exponential backoff với jitter
    const baseDelay = this.retryDelay * Math.pow(2, attempt);
    const jitter = Math.random() * 0.3 * baseDelay;
    return Math.min(baseDelay + jitter, 30000); // Max 30 giây
  }

  private isRetryableError(statusCode: number | undefined): boolean {
    if (!statusCode) return true; // Network error - retry
    return [408, 429, 500, 502, 503, 504].includes(statusCode);
  }

  async chatCompletion(
    messages: ChatMessage[],
    options: {
      model?: string;
      temperature?: number;
      max_tokens?: number;
    } = {}
  ): Promise<ChatCompletionResponse> {
    const model = options.model || 'gpt-4.1';
    let lastError: Error | undefined;

    for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
      try {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), this.timeout);

        const response = await fetch(${this.baseUrl}/chat/completions, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': Bearer ${this.apiKey},
          },
          body: JSON.stringify({
            model,
            messages,
            temperature: options.temperature ?? 0.7,
            max_tokens: options.max_tokens ?? 2048,
          }),
          signal: controller.signal,
        });

        clearTimeout(timeoutId);

        if (!response.ok) {
          const errorBody = await response.json().catch(() => ({}));
          const isRetryable = this.isRetryableError(response.status);
          
          throw new HolySheepError(
            errorBody.error?.message || HTTP ${response.status}: ${response.statusText},
            response.status,
            errorBody.error?.type || 'API_ERROR',
            isRetryable
          );
        }

        return await response.json();
      } catch (error) {
        lastError = error as Error;

        if (error instanceof HolySheepError && !error.isRetryable) {
          throw error; // Không retry lỗi không thể khôi phục
        }

        if (attempt < this.maxRetries) {
          const delay = this.calculateRetryDelay(attempt);
          console.warn(Retry attempt ${attempt + 1}/${this.maxRetries} sau ${delay}ms);
          await this.sleep(delay);
        }
      }
    }

    throw new HolySheepError(
      Failed sau ${this.maxRetries + 1} attempts: ${lastError?.message},
      undefined,
      'MAX_RETRIES_EXCEEDED',
      false
    );
  }
}

// Export singleton instance
export const createHolySheepClient = (config: HolySheepConfig) => new HolySheepClient(config);
export { HolySheepError, HolySheepConfig, ChatMessage, ChatCompletionResponse };

2. Python SDK với Retry Logic và Circuit Breaker

Đối với Python, tôi khuyến nghị sử dụng tenacity cho retry logic và tự implement circuit breaker đơn giản. Dưới đây là implementation hoàn chỉnh:

# holysheep_python_sdk.py
import time
import logging
from typing import Optional, Any, Callable
from dataclasses import dataclass
from enum import Enum
from collections import defaultdict
import httpx
import asyncio

logger = logging.getLogger(__name__)

class CircuitState(Enum):
    CLOSED = "closed"      # Hoạt động bình thường
    OPEN = "open"          # Không cho phép request
    HALF_OPEN = "half_open"  # Thử nghiệm

@dataclass
class CircuitBreakerConfig:
    failure_threshold: int = 5      # Số lỗi để mở circuit
    recovery_timeout: float = 60.0 # Giây trước khi thử lại
    expected_exception: type = Exception

class CircuitBreaker:
    def __init__(self, config: Optional[CircuitBreakerConfig] = None):
        self.config = config or CircuitBreakerConfig()
        self.state = CircuitState.CLOSED
        self.failure_count = 0
        self.last_failure_time: Optional[float] = None
        self.opening_time: Optional[float] = None

    def record_success(self):
        self.failure_count = 0
        self.state = CircuitState.CLOSED

    def record_failure(self):
        self.failure_count += 1
        self.last_failure_time = time.time()
        
        if self.failure_count >= self.config.failure_threshold:
            self.state = CircuitState.OPEN
            self.opening_time = time.time()
            logger.warning(f"Circuit breaker OPENED sau {self.failure_count} failures")

    def can_attempt(self) -> bool:
        if self.state == CircuitState.CLOSED:
            return True
        
        if self.state == CircuitState.OPEN:
            if self.opening_time:
                elapsed = time.time() - self.opening_time
                if elapsed >= self.config.recovery_timeout:
                    self.state = CircuitState.HALF_OPEN
                    logger.info("Circuit breaker chuyển sang HALF_OPEN")
                    return True
            return False
        
        # HALF_OPEN - cho phép 1 request thử nghiệm
        return True

class HolySheepError(Exception):
    def __init__(self, message: str, status_code: Optional[int] = None, 
                 error_code: Optional[str] = None, is_retryable: bool = False):
        super().__init__(message)
        self.status_code = status_code
        self.error_code = error_code
        self.is_retryable = is_retryable

class HolySheepPythonSDK:
    BASE_URL = "https://api.holysheep.ai/v1"
    
    # Giá thực tế từ HolySheep AI (cập nhật 2026)
    PRICING = {
        'gpt-4.1': {'input': 8.00, 'output': 8.00},           # $8/MTok
        'claude-sonnet-4.5': {'input': 15.00, 'output': 15.00}, # $15/MTok
        'gemini-2.5-flash': {'input': 2.50, 'output': 2.50},   # $2.50/MTok
        'deepseek-v3.2': {'input': 0.42, 'output': 0.42},      # $0.42/MTok
    }
    
    def __init__(
        self,
        api_key: str,
        base_url: Optional[str] = None,
        timeout: float = 60.0,
        max_retries: int = 3,
        circuit_breaker: Optional[CircuitBreaker] = None
    ):
        if not api_key:
            raise HolySheepError("API key là bắt buộc", error_code="MISSING_API_KEY")
        
        self.api_key = api_key
        self.base_url = base_url or self.BASE_URL
        self.timeout = timeout
        self.max_retries = max_retries
        self.circuit_breaker = circuit_breaker or CircuitBreaker()
        self._client = httpx.AsyncClient(timeout=self.timeout)

    async def _request_with_retry(
        self,
        method: str,
        endpoint: str,
        **kwargs
    ) -> dict:
        """Internal request với exponential backoff retry"""
        
        async def _make_request() -> httpx.Response:
            headers = kwargs.pop('headers', {})
            headers['Authorization'] = f'Bearer {self.api_key}'
            headers['Content-Type'] = 'application/json'
            
            url = f"{self.base_url}{endpoint}"
            return await self._client.request(method, url, headers=headers, **kwargs)

        last_error = None
        
        for attempt in range(self.max_retries + 1):
            if not self.circuit_breaker.can_attempt():
                raise HolySheepError(
                    "Circuit breaker đang OPEN - service tạm thời không khả dụng",
                    error_code="CIRCUIT_OPEN"
                )
            
            try:
                response = await _make_request()
                
                if response.status_code == 200:
                    self.circuit_breaker.record_success()
                    return response.json()
                
                # Xử lý lỗi HTTP
                error_data = response.json() if response.text else {}
                is_retryable = response.status_code in [408, 429, 500, 502, 503, 504]
                
                if not is_retryable or attempt == self.max_retries:
                    self.circuit_breaker.record_failure()
                    raise HolySheepError(
                        error_data.get('error', {}).get('message', f"HTTP {response.status_code}"),
                        status_code=response.status_code,
                        error_code=error_data.get('error', {}).get('type', 'API_ERROR'),
                        is_retryable=is_retryable
                    )
                
                last_error = HolySheepError(
                    error_data.get('error', {}).get('message', f"HTTP {response.status_code}"),
                    status_code=response.status_code,
                    is_retryable=True
                )
                
            except httpx.TimeoutException as e:
                last_error = HolySheepError(str(e), error_code="TIMEOUT", is_retryable=True)
                self.circuit_breaker.record_failure()
            except httpx.ConnectError as e:
                last_error = HolySheepError(str(e), error_code="CONNECTION_ERROR", is_retryable=True)
                self.circuit_breaker.record_failure()
            except HolySheepError:
                raise
            except Exception as e:
                last_error = HolySheepError(str(e), error_code="UNKNOWN", is_retryable=False)
                break
            
            # Exponential backoff
            if attempt < self.max_retries:
                delay = min(2 ** attempt * 1.0 + random.uniform(0, 0.5), 30.0)
                logger.info(f"Retry {attempt + 1}/{self.max_retries} sau {delay:.1f}s")
                await asyncio.sleep(delay)
        
        raise last_error or HolySheepError("Max retries exceeded", error_code="MAX_RETRIES")

    async def chat_completion(
        self,
        messages: list[dict],
        model: str = 'gpt-4.1',
        temperature: float = 0.7,
        max_tokens: int = 2048,
        **kwargs
    ) -> dict:
        """
        Gọi Chat Completions API
        
        Pricing reference (HolySheep AI 2026):
        - gpt-4.1: $8/MTok (tiết kiệm 85%+ so với OpenAI)
        - deepseek-v3.2: $0.42/MTok (rẻ nhất thị trường)
        """
        payload = {
            'model': model,
            'messages': messages,
            'temperature': temperature,
            'max_tokens': max_tokens,
            **kwargs
        }
        
        return await self._request_with_retry('POST', '/chat/completions', json=payload)

    def calculate_cost(self, usage: dict, model: str) -> float:
        """Tính chi phí dựa trên token usage thực tế"""
        pricing = self.PRICING.get(model, self.PRICING['gpt-4.1'])
        input_cost = (usage.get('prompt_tokens', 0) / 1_000_000) * pricing['input']
        output_cost = (usage.get('completion_tokens', 0) / 1_000_000) * pricing['output']
        return round(input_cost + output_cost, 6)  # Chính xác đến 6 chữ số thập phân

    async def close(self):
        await self._client.aclose()

Usage example

async def main(): client = HolySheepPythonSDK( api_key="YOUR_HOLYSHEEP_API_KEY", max_retries=3 ) try: response = await client.chat_completion( messages=[ {"role": "system", "content": "Bạn là trợ lý AI hữu ích"}, {"role": "user", "content": "Xin chào, giới thiệu về HolySheep AI"} ], model='deepseek-v3.2', # $0.42/MTok - tiết kiệm tối đa max_tokens=500 ) # Tính chi phí thực tế cost = client.calculate_cost(response['usage'], 'deepseek-v3.2') print(f"Chi phí: ${cost:.6f}") print(f"Response: {response['choices'][0]['message']['content']}") finally: await client.close() if __name__ == "__main__": asyncio.run(main())

3. Ví dụ thực chiến: Tích hợp vào dự án Production

Dưới đây là ví dụ hoàn chỉnh về cách tích hợp SDK vào một ứng dụng thực tế với streaming response và cost tracking:

// production-integration.ts
import { createHolySheepClient, HolySheepError } from './holysheep-sdk';

interface CostMetrics {
  totalInputTokens: number;
  totalOutputTokens: number;
  totalCostUSD: number;
  requestCount: number;
}

class AIContentService {
  private client: ReturnType<typeof createHolySheepClient>;
  private metrics: CostMetrics;

  // Pricing từ HolySheep AI (2026)
  private readonly PRICING = {
    'gpt-4.1': { input: 8.00, output: 8.00 },
    'claude-sonnet-4.5': { input: 15.00, output: 15.00 },
    'gemini-2.5-flash': { input: 2.50, output: 2.50 },
    'deepseek-v3.2': { input: 0.42, output: 0.42 },
  };

  constructor(apiKey: string) {
    this.client = createHolySheepClient({
      apiKey,
      baseUrl: 'https://api.holysheep.ai/v1', // LUÔN LUÔN dùng HolySheep
      timeout: 90000,
      maxRetries: 3,
    });
    
    this.metrics = {
      totalInputTokens: 0,
      totalOutputTokens: 0,
      totalCostUSD: 0,
      requestCount: 0,
    };
  }

  private calculateCost(
    promptTokens: number, 
    completionTokens: number, 
    model: string
  ): number {
    const pricing = this.PRICING[model] || this.PRICING['gpt-4.1'];
    const inputCost = (promptTokens / 1_000_000) * pricing.input;
    const outputCost = (completionTokens / 1_000_000) * pricing.output;
    return inputCost + outputCost;
  }

  async generateContent(
    prompt: string,
    options: {
      model?: string;
      maxTokens?: number;
      temperature?: number;
    } = {}
  ): Promise<{ content: string; cost: number; latencyMs: number }> {
    const startTime = performance.now();
    const model = options.model || 'deepseek-v3.2'; // Mặc định dùng model rẻ nhất

    try {
      const response = await this.client.chatCompletion(
        [
          { role: 'system', content: 'Bạn là chuyên gia viết content SEO...' },
          { role: 'user', content: prompt },
        ],
        {
          model,
          max_tokens: options.maxTokens || 2000,
          temperature: options.temperature ?? 0.7,
        }
      );

      const latencyMs = Math.round(performance.now() - startTime);
      const content = response.choices[0]?.message?.content || '';
      const { prompt_tokens, completion_tokens } = response.usage;
      
      // Cập nhật metrics
      const cost = this.calculateCost(prompt_tokens, completion_tokens, model);
      this.updateMetrics(prompt_tokens, completion_tokens, cost);

      console.log([${model}] Latency: ${latencyMs}ms | Cost: $${cost.toFixed(6)} | Tokens: ${prompt_tokens + completion_tokens});
      
      return { content, cost, latencyMs };
      
    } catch (error) {
      if (error instanceof HolySheepError) {
        console.error(HolySheep Error [${error.code}]:, error.message);
        
        // Fallback strategy: thử model rẻ hơn
        if (error.statusCode === 429 || error.statusCode === 503) {
          console.warn('Rate limited - implementing fallback...');
          await this.sleep(2000);
          return this.generateContent(prompt, { ...options, model: 'gemini-2.5-flash' });
        }
        
        // Fallback to cache hoặc default response
        if (error.statusCode === 401) {
          throw new Error('API key không hợp lệ. Vui lòng kiểm tra YOUR_HOLYSHEEP_API_KEY');
        }
      }
      throw error;
    }
  }

  private updateMetrics(
    inputTokens: number, 
    outputTokens: number, 
    cost: number
  ): void {
    this.metrics.totalInputTokens += inputTokens;
    this.metrics.totalOutputTokens += outputTokens;
    this.metrics.totalCostUSD += cost;
    this.metrics.requestCount++;
  }

  getMetrics(): CostMetrics & { avgLatencyMs: number } {
    return {
      ...this.metrics,
      get avgLatencyMs() {
        return this.requestCount > 0 
          ? this.totalCostUSD / this.requestCount 
          : 0;
      },
    };
  }

  private sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

// Khởi tạo với API key từ environment
const contentService = new AIContentService(
  process.env.YOUR_HOLYSHEEP_API_KEY || ''
);

// Batch processing với concurrency control
async function processBatch(
  prompts: string[], 
  concurrency: number = 5
): Promise<any[]> {
  const results: any[] = [];
  
  for (let i = 0; i < prompts.length; i += concurrency) {
    const batch = prompts.slice(i, i + concurrency);
    const batchResults = await Promise.all(
      batch.map(prompt => contentService.generateContent(prompt))
    );
    results.push(...batchResults);
    
    // Rate limiting - tránh quá tải API
    if (i + concurrency < prompts.length) {
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }
  
  return results;
}

// Test với dữ liệu thực
(async () => {
  const testPrompts = [
    'Viết bài giới thiệu về AI API integration',
    'Hướng dẫn tối ưu chi phí khi sử dụng LLM',
    'So sánh các mô hình AI hiện nay',
  ];

  console.log('Starting batch processing với HolySheep AI...');
  const results = await processBatch(testPrompts);
  
  console.log('\n=== COST REPORT ===');
  const metrics = contentService.getMetrics();
  console.log(Total Requests: ${metrics.requestCount});
  console.log(Total Input Tokens: ${metrics.totalInputTokens.toLocaleString()});
  console.log(Total Output Tokens: ${metrics.totalOutputTokens.toLocaleString()});
  console.log(Tổng chi phí: $${metrics.totalCostUSD.toFixed(6)});
  
  // So sánh với OpenAI原生
  const openaiCost = (metrics.totalInputTokens + metrics.totalOutputTokens) / 1_000_000 * 15;
  const savings = openaiCost - metrics.totalCostUSD;
  const savingsPercent = ((openaiCost - metrics.totalCostUSD) / openaiCost * 100).toFixed(1);
  console.log(\nSo với OpenAI: Tiết kiệm $${savings.toFixed(6)} (${savingsPercent}%));
})();

4. Streaming Response với Real-time Progress

Streaming là tính năng quan trọng cho UX. Dưới đây là implementation với progress indicator:

// streaming-client.ts
import { createHolySheepClient } from './holysheep-sdk';

interface StreamChunk {
  delta: string;
  done: boolean;
  tokensReceived: number;
}

class StreamingAIClient {
  private client = createHolySheepClient({
    apiKey: process.env.YOUR_HOLYSHEEP_API_KEY!,
    baseUrl: 'https://api.holysheep.ai/v1',
  });

  async *streamChat(
    messages: { role: string; content: string }[],
    model: string = 'deepseek-v3.2'
  ): AsyncGenerator<StreamChunk> {
    let tokensReceived = 0;
    let fullResponse = '';

    try {
      const response = await fetch(${this.client.baseUrl}/chat/completions, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': Bearer ${process.env.YOUR_HOLYSHEEP_API_KEY},
        },
        body: JSON.stringify({
          model,
          messages,
          stream: true,
          max_tokens: 2048,
        }),
      });

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

      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let buffer = '';

      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 { delta: '', done: true, tokensReceived };
              return;
            }

            try {
              const parsed = JSON.parse(data);
              const content = parsed.choices?.[0]?.delta?.content || '';
              
              if (content) {
                tokensReceived++;
                fullResponse += content;
                yield { delta: content, done: false, tokensReceived };
              }
            } catch (e) {
              // Skip invalid JSON chunks
            }
          }
        }
      }
    } catch (error) {
      console.error('Stream error:', error);
      throw error;
    }
  }

  async chatWithProgress(
    messages: { role: string; content: string }[],
    onProgress?: (chunk: StreamChunk) => void
  ): Promise<string> {
    let fullResponse = '';
    const startTime = Date.now();
    
    console.log('🎯 Bắt đầu streaming với HolySheep AI...');
    
    for await (const chunk of this.streamChat(messages)) {
      if (chunk.done) {
        const duration = ((Date.now() - startTime) / 1000).toFixed(2);
        console.log(\n✅ Hoàn thành trong ${duration}s | ${chunk.tokensReceived} tokens);
        break;
      }
      
      fullResponse += chunk.delta;
      
      if (onProgress) {
        onProgress(chunk);
      } else {
        // Progress indicator mặc định
        process.stdout.write(chunk.delta);
      }
    }
    
    return fullResponse;
  }
}

// Sử dụng
const streamingClient = new StreamingAIClient();

(async () => {
  const response = await streamingClient.chatWithProgress([
    { role: 'user', content: 'Giải thích về cách HolySheep AI giúp tiết kiệm chi phí AI' }
  ]);
  
  console.log('\n\n--- Full Response ---');
  console.log(response);
})();

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, bạn nhận được response với status: 401 và message "Invalid authentication credentials".

// ❌ SAI: Hardcode API key trong code
const client = new HolySheepClient({
  apiKey: 'sk-xxx-actual-key', // KHÔNG BAO GIỜ làm thế này!
});

// ✅ ĐÚNG: Sử dụng environment variable
const client = new HolySheepClient({
  apiKey: process.env.YOUR_HOLYSHEEP_API_KEY,
});

// ✅ TỐT NHẤT: Validation với clear error message
if (!process.env.YOUR_HOLYSHEEP_API_KEY) {
  throw new Error(`
    ⚠️ HolySheep API Key không được tìm thấy!
    
    Vui lòng thiết lập biến môi trường:
    export YOUR_HOLYSHEEP_API_KEY="your-key-here"
    
    Đăng ký tại: https://www.holysheep.ai/register
  `);
}

2. Lỗi "ConnectionError: timeout after 30000ms"

Mô tả lỗi: Request bị timeout sau 30 giây, thường xảy ra khi server HolySheep đang bận hoặc network không ổn định.

// ❌ SAI: Không có retry, timeout quá ngắn
const response = await fetch(url, {
  method: 'POST',
  signal: AbortSignal.timeout(5000), // Chỉ 5 giây - quá ngắn!
});
// Không retry = 100% fail khi timeout

// ✅ ĐÚNG: Exponential backoff với retry
const client = new HolySheepClient({
  apiKey: process.env.YOUR_HOLYSHEEP_API_KEY,
  timeout: 90000,        // 90 giây cho complex requests
  maxRetries: 3,         // Retry 3 lần
  retryDelay: 1000,      // Bắt đầu từ 1 giây
});

// Custom timeout handler cho từng request
async function requestWithCustomTimeout<T>(
  fn: () => Promise<T>,
  timeoutMs: number = 60000
): Promise<T> {
  return Promise.race([
    fn(),
    new Promise<T>((_, reject) => 
      setTimeout(() => reject(new Error(Timeout sau ${timeoutMs}ms)), timeoutMs)
    )
  ]);
}

3. Lỗi "429 Too Many Requests" - Rate Limiting

Mô tả lỗi: Bạn gửi quá nhiều request trong thời gian ngắn, API trả về 429 với thông báo rate limit exceeded.

// ❌ SAI: Gửi request liên tục không kiểm soát
const results = await Promise.all(
  prompts.map(prompt => api.chat(prompt)) // 100 requests cùng lúc!
);

// ✅ ĐÚNG: Rate limiter với queue
class RateLimiter {
  private queue: Array<() => void> = [];
  private processing = 0;
  
  constructor(
    private maxConcurrent: number = 5,
    private minInterval: number = 100 // ms giữa các request
  ) {}
  
  async execute<T>(fn: () => Promise<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      this.queue.push(async () => {
        try {
          const result = await fn();
          resolve(result);
        } catch (e) {
          reject(e);
        } finally {
          this.processing--;
          this.processNext();
        }
      });
      
      this.processNext();
    });
  }
  
  private processNext() {
    if (this.processing < this.maxConcurrent && this.queue.length > 0) {
      this.processing++;
      const next = this.queue.shift()!;
      setTimeout(next, this.minInterval);
    }
  }
}

// Sử dụng rate limiter
const limiter = new RateLimiter(maxConcurrent: 5, minInterval: 200);

const results = await Promise.all(
  prompts.map(prompt => limiter.execute(() => api.chat(prompt)))
);

// ✅ XỬ LÝ KHI GẶP 429 - Backoff thông minh
async function handleRateLimit(error: HolySheepError, attempt: number) {
  if (error.statusCode === 429) {
    // HolySheep trả về header Retry-After
    const retryAfter = error.headers?.['retry-after'] || Math.pow(2, attempt);
    console.warn(Rate limited! Chờ ${retryAfter}s trước khi retry...);
    await sleep(retryAfter * 1000);
  }
}

4. Lỗi "500 Internal Server Error" - Server-side Issues

Mô tả lỗi: HolySheep API gặp sự cố nội bộ, trả về 500 hoặc 503.

// ✅ ĐÚNG: Graceful degradation với fallback
class ResilientAIClient {
  private primaryModels = ['deepseek-v3.2', 'gemini-2.5-flash'];
  private fallbackResponse = 'Xin lỗi, hệ thống AI tạm thời bận. Vui lòng thử lại sau.';

  async chat(message: string): Promise<string> {
    const errors: Error[] = [];
    
    // Thử lần lượt các model
    for (const model of this.primaryModels) {
      try {
        return await this.callAPI