Bối Cảnh Thực Tế: Khi Dịp Sale 11.11 Gần Như "Phá Sản" Hệ Thống

Tôi còn nhớ rõ cách đêm Sale 11.11 năm ngoái, team backend của một trung tâm thương mại điện tử lớn tại Việt Nam đã phải đối mặt với cơn ác mộng thực sự. Hệ thống chatbot AI hỗ trợ khách hàng 24/7 bắt đầu trả về timeout liên tục từ 23:00 — đúng thời điểm traffic đạt đỉnh. Đội ngũ kỹ sư đã thiết lập rate limit thủ công, restart server, thậm chí manually scale infrastructure lên 300% nhưng vẫn không thể xử lý kịp 15,000 requests/giây. Sáng hôm sau, sau 6 tiếng đồng hồ "chữa cháy", đội ngũ đã quyết định xây dựng một AI API Gateway tập trung — giải pháp giúp họ giảm 70% chi phí API và xử lý được 50,000 requests/giây mà không cần scale infrastructure thêm. Bài viết này sẽ hướng dẫn bạn xây dựng hệ thống tương tự từ con số 0.

Tại Sao Cần AI API Gateway?

Trước khi đi vào implementation, hãy phân tích tại sao gateway là thành phần không thể thiếu:

Kiến Trúc Tổng Quan

┌─────────────────────────────────────────────────────────────┐
│                      Client Applications                     │
│         (Web, Mobile, Chatbot, Internal Services)           │
└──────────────────────────┬──────────────────────────────────┘
                           │ HTTPS
                           ▼
┌─────────────────────────────────────────────────────────────┐
│                    AI API Gateway                            │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────┐   │
│  │ Rate Limiter │  │  Auth Layer  │  │  Load Balancer   │   │
│  └──────────────┘  └──────────────┘  └──────────────────┘   │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────┐   │
│  │  Cache Layer │  │ Proxy/Router │  │ Metrics & Logs   │   │
│  └──────────────┘  └──────────────┘  └──────────────────┘   │
└──────────────────────────┬──────────────────────────────────┘
                           │
            ┌──────────────┼──────────────┐
            ▼              ▼              ▼
     ┌──────────┐   ┌──────────┐   ┌──────────┐
     │DeepSeek  │   │  GPT-4.1 │   │ Claude   │
     │  V3.2    │   │          │   │ Sonnet 4.5│
     │$0.42/MTok│   │ $8/MTok  │   │ $15/MTok │
     └──────────┘   └──────────┘   └──────────┘

Implementation Chi Tiết Với Python

1. Cài Đặt Dependencies

pip install fastapi uvicorn redis aiohttp pydantic
pip install python-multipart httpx rate-limiter

2. Cấu Hình Base Configuration

# config.py
import os
from typing import Dict, Optional
from pydantic import BaseModel
from enum import Enum

class AIModel(str, Enum):
    DEEPSEEK_V32 = "deepseek/v3.2"
    GPT_41 = "gpt-4.1"
    CLAUDE_SONNET = "claude-sonnet-4.5"
    GEMINI_FLASH = "gemini-2.5-flash"

class GatewayConfig(BaseModel):
    # HolySheep AI Configuration
    base_url: str = "https://api.holysheep.ai/v1"
    api_key: str = os.getenv("HOLYSHEEP_API_KEY", "YOUR_HOLYSHEEP_API_KEY")
    
    # Model Pricing (2026 - USD per Million Tokens)
    model_pricing: Dict[str, float] = {
        "deepseek/v3.2": 0.42,
        "gpt-4.1": 8.00,
        "claude-sonnet-4.5": 15.00,
        "gemini-2.5-flash": 2.50,
    }
    
    # Rate Limiting
    rate_limit_requests: int = 100  # per minute
    rate_limit_tokens: int = 100000  # per minute
    
    # Cache Configuration
    cache_ttl: int = 3600  # seconds
    enable_semantic_cache: bool = True
    
    # Retry Configuration
    max_retries: int = 3
    retry_delay: float = 1.0  # seconds
    timeout: int = 30  # seconds

config = GatewayConfig()

3. Rate Limiter Implementation

# rate_limiter.py
import time
import hashlib
from typing import Dict, Tuple
from collections import defaultdict
import asyncio

class TokenBucketRateLimiter:
    """
    Token Bucket Algorithm cho rate limiting chính xác.
    Hỗ trợ cả rate limit theo requests và tokens.
    """
    
    def __init__(self, requests_per_minute: int = 100, tokens_per_minute: int = 100000):
        self.requests_per_minute = requests_per_minute
        self.tokens_per_minute = tokens_per_minute
        self.buckets: Dict[str, Dict] = defaultdict(self._create_bucket)
        self._lock = asyncio.Lock()
    
    def _create_bucket(self):
        return {
            "tokens": self.requests_per_minute,
            "token_tokens": self.tokens_per_minute,
            "last_update": time.time(),
            "request_count": 0,
        }
    
    def _hash_key(self, identifier: str, window: str = "minute") -> str:
        """Tạo key duy nhất cho mỗi user/endpoint"""
        timestamp = int(time.time() / 60) if window == "minute" else int(time.time() / 3600)
        return hashlib.sha256(f"{identifier}:{timestamp}:{window}".encode()).hexdigest()
    
    async def check_rate_limit(
        self, 
        user_id: str, 
        endpoint: str,
        tokens_estimate: int = 0
    ) -> Tuple[bool, Dict]:
        """
        Kiểm tra và cập nhật rate limit.
        Trả về (is_allowed, rate_limit_info)
        """
        async with self._lock:
            key = f"{user_id}:{endpoint}"
            bucket = self.buckets[key]
            
            current_time = time.time()
            time_passed = current_time - bucket["last_update"]
            
            # Refill tokens dựa trên thời gian đã trôi qua
            refill_rate = self.requests_per_minute / 60
            bucket["tokens"] = min(
                self.requests_per_minute,
                bucket["tokens"] + refill_rate * time_passed
            )
            
            token_refill_rate = self.tokens_per_minute / 60
            bucket["token_tokens"] = min(
                self.tokens_per_minute,
                bucket["token_tokens"] + token_refill_rate * time_passed
            )
            
            bucket["last_update"] = current_time
            
            # Kiểm tra limits
            can_proceed = (
                bucket["tokens"] >= 1 and 
                bucket["token_tokens"] >= tokens_estimate
            )
            
            if can_proceed:
                bucket["tokens"] -= 1
                bucket["token_tokens"] -= tokens_estimate
                bucket["request_count"] += 1
            
            return can_proceed, {
                "remaining_requests": int(bucket["tokens"]),
                "remaining_tokens": int(bucket["token_tokens"]),
                "reset_in_seconds": 60 - (current_time % 60),
                "request_count": bucket["request_count"]
            }

Singleton instance

rate_limiter = TokenBucketRateLimiter( requests_per_minute=100, tokens_per_minute=100000 )

4. AI Gateway Core Service

# gateway_service.py
import httpx
import hashlib
import json
import time
from typing import Optional, Dict, Any, List
from fastapi import HTTPException, Header, Request
from fastapi.responses import JSONResponse
import asyncio

class AIAuthMiddleware:
    """Layer xác thực và bảo mật API requests"""
    
    def __init__(self):
        self.valid_api_keys: Dict[str, Dict] = {}  # key -> user_info
        self._load_keys()
    
    def _load_keys(self):
        # Trong production, load từ database hoặc vault
        self.valid_api_keys = {
            "sk-user-001": {"user_id": "user_001", "tier": "premium", "quota": 1000000},
            "sk-user-002": {"user_id": "user_002", "tier": "standard", "quota": 100000},
        }
    
    async def verify_request(
        self, 
        authorization: Optional[str] = Header(None),
        x_api_key: Optional[str] = Header(None)
    ) -> Dict:
        api_key = None
        
        if authorization and authorization.startswith("Bearer "):
            api_key = authorization[7:]
        elif x_api_key:
            api_key = x_api_key
        
        if not api_key:
            raise HTTPException(status_code=401, detail="Missing API key")
        
        user_info = self.valid_api_keys.get(api_key)
        if not user_info:
            raise HTTPException(status_code=401, detail="Invalid API key")
        
        return user_info

class AICache:
    """Semantic cache để giảm chi phí và tăng tốc độ"""
    
    def __init__(self, ttl: int = 3600):
        self.cache: Dict[str, Dict] = {}
        self.ttl = ttl
        self._lock = asyncio.Lock()
    
    def _generate_cache_key(self, messages: List[Dict], model: str) -> str:
        """Tạo cache key từ messages và model"""
        content = json.dumps(messages, sort_keys=True) + model
        return hashlib.sha256(content.encode()).hexdigest()
    
    async def get(self, messages: List[Dict], model: str) -> Optional[str]:
        key = self._generate_cache_key(messages, model)
        async with self._lock:
            if key in self.cache:
                entry = self.cache[key]
                if time.time() - entry["timestamp"] < self.ttl:
                    return entry["response"]
                del self.cache[key]
        return None
    
    async def set(self, messages: List[Dict], model: str, response: str):
        key = self._generate_cache_key(messages, model)
        async with self._lock:
            self.cache[key] = {
                "response": response,
                "timestamp": time.time()
            }

class AIProxyService:
    """
    Core proxy service xử lý requests đến HolySheep AI.
    Implement retry logic, error handling, và response streaming.
    """
    
    def __init__(self, config):
        self.config = config
        self.auth = AIAuthMiddleware()
        self.cache = AICache(ttl=config.cache_ttl)
        self.rate_limiter = rate_limiter
    
    async def chat_completion(
        self,
        request: Request,
        messages: List[Dict[str, str]],
        model: str = "deepseek/v3.2",
        temperature: float = 0.7,
        max_tokens: int = 2048,
        stream: bool = False,
        user_id: Optional[str] = None,
        use_cache: bool = True,
    ) -> Dict[str, Any]:
        
        # 1. Xác thực
        user_info = await self.auth.verify_request(
            authorization=request.headers.get("Authorization"),
            x_api_key=request.headers.get("x-api-key")
        )
        
        actual_user_id = user_id or user_info["user_id"]
        
        # 2. Kiểm tra cache (chỉ cho non-streaming)
        if use_cache and not stream:
            cached_response = await self.cache.get(messages, model)
            if cached_response:
                return {
                    "cached": True,
                    "content": json.loads(cached_response),
                    "model": model,
                    "cost_savings": self._calculate_cost(model, max_tokens)
                }
        
        # 3. Rate limiting
        is_allowed, rate_info = await self.rate_limiter.check_rate_limit(
            user_id=actual_user_id,
            endpoint="chat/completions",
            tokens_estimate=max_tokens
        )
        
        if not is_allowed:
            raise HTTPException(
                status_code=429,
                detail={
                    "error": "Rate limit exceeded",
                    "retry_after": rate_info["reset_in_seconds"],
                    "limit_type": "requests" if rate_info["remaining_requests"] <= 0 else "tokens"
                }
            )
        
        # 4. Gọi HolySheep AI API với retry logic
        response = await self._make_request_with_retry(
            messages=messages,
            model=model,
            temperature=temperature,
            max_tokens=max_tokens,
            stream=stream
        )
        
        # 5. Cache response
        if use_cache and not stream and response.get("choices"):
            content = response["choices"][0]["message"]["content"]
            await self.cache.set(messages, model, json.dumps(response))
        
        # 6. Trả về response kèm metadata
        return {
            "cached": False,
            "content": response,
            "model": model,
            "rate_limit_info": rate_info,
            "cost": self._calculate_cost(model, response.get("usage", {}).get("total_tokens", max_tokens)),
            "latency_ms": response.get("latency_ms", 0)
        }
    
    async def _make_request_with_retry(
        self,
        messages: List[Dict],
        model: str,
        temperature: float,
        max_tokens: int,
        stream: bool,
        retry_count: int = 0
    ) -> Dict[str, Any]:
        
        url = f"{self.config.base_url}/chat/completions"
        headers = {
            "Authorization": f"Bearer {self.config.api_key}",
            "Content-Type": "application/json"
        }
        payload = {
            "model": model,
            "messages": messages,
            "temperature": temperature,
            "max_tokens": max_tokens,
            "stream": stream
        }
        
        start_time = time.time()
        
        try:
            async with httpx.AsyncClient(timeout=self.config.timeout) as client:
                response = await client.post(url, json=payload, headers=headers)
                latency_ms = (time.time() - start_time) * 1000
                
                if response.status_code == 200:
                    result = response.json()
                    result["latency_ms"] = round(latency_ms, 2)
                    return result
                
                # Xử lý specific error codes
                if response.status_code == 429:
                    raise HTTPException(status_code=429, detail="Upstream rate limit")
                elif response.status_code == 500 or response.status_code == 502:
                    # Retry cho server errors
                    if retry_count < self.config.max_retries:
                        await asyncio.sleep(self.config.retry_delay * (2 ** retry_count))
                        return await self._make_request_with_retry(
                            messages, model, temperature, max_tokens, stream, retry_count + 1
                        )
                
                raise HTTPException(
                    status_code=response.status_code,
                    detail=response.text
                )
                
        except httpx.TimeoutException:
            if retry_count < self.config.max_retries:
                await asyncio.sleep(self.config.retry_delay * (2 ** retry_count))
                return await self._make_request_with_retry(
                    messages, model, temperature, max_tokens, stream, retry_count + 1
                )
            raise HTTPException(status_code=504, detail="Request timeout after retries")
    
    def _calculate_cost(self, model: str, tokens: int) -> float:
        """Tính chi phí dựa trên model pricing"""
        price_per_million = self.config.model_pricing.get(model, 1.0)
        cost = (tokens / 1_000_000) * price_per_million
        return round(cost, 6)

Khởi tạo service

ai_gateway = AIProxyService(config)

5. FastAPI Application

# main.py
from fastapi import FastAPI, Request, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import List, Optional, Dict
import uvicorn
import logging

from gateway_service import ai_gateway
from config import config, AIModel

Logging setup

logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) app = FastAPI( title="HolySheep AI Gateway", description="AI API Gateway với Rate Limiting, Caching, và Multi-Model Support", version="1.0.0" )

CORS Configuration

app.add_middleware( CORSMiddleware, allow_origins=["*"], # Production: specify exact domains allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )

Request Models

class Message(BaseModel): role: str = Field(..., description="Role: system, user, assistant") content: str = Field(..., description="Nội dung message") class ChatCompletionRequest(BaseModel): model: str = Field(default="deepseek/v3.2", description="Model identifier") messages: List[Message] temperature: float = Field(default=0.7, ge=0, le=2) max_tokens: int = Field(default=2048, ge=1, le=128000) stream: bool = Field(default=False) user_id: Optional[str] = Field(default=None, description="Override user ID") use_cache: bool = Field(default=True, description="Sử dụng semantic cache") class ChatCompletionResponse(BaseModel): id: str model: str content: Dict cached: bool cost: float latency_ms: float rate_limit_info: Dict

API Endpoints

@app.post("/v1/chat/completions", response_model=ChatCompletionResponse) async def chat_completions( request: ChatCompletionRequest, http_request: Request ): """Endpoint chính cho chat completions""" logger.info(f"Received request for model: {request.model}") response = await ai_gateway.chat_completion( request=http_request, messages=[msg.dict() for msg in request.messages], model=request.model, temperature=request.temperature, max_tokens=request.max_tokens, stream=request.stream, user_id=request.user_id, use_cache=request.use_cache ) return ChatCompletionResponse( id=f"chatcmpl-{hash(str(request.messages)) % 1000000}", model=response["model"], content=response["content"], cached=response["cached"], cost=response["cost"], latency_ms=response.get("latency_ms", 0), rate_limit_info=response.get("rate_limit_info", {}) ) @app.get("/v1/models") async def list_models(): """Liệt kê các model có sẵn với pricing""" return { "models": [ { "id": "deepseek/v3.2", "name": "DeepSeek V3.2", "pricing_input": 0.42, "pricing_output": 2.80, "context_length": 128000, "latency_typical": "<50ms" }, { "id": "gpt-4.1", "name": "GPT-4.1", "pricing_input": 8.00, "pricing_output": 32.00, "context_length": 128000, "latency_typical": "<80ms" }, { "id": "claude-sonnet-4.5", "name": "Claude Sonnet 4.5", "pricing_input": 15.00, "pricing_output": 75.00, "context_length": 200000, "latency_typical": "<60ms" }, { "id": "gemini-2.5-flash", "name": "Gemini 2.5 Flash", "pricing_input": 2.50, "pricing_output": 10.00, "context_length": 1000000, "latency_typical": "<40ms" } ], "currency": "USD", "unit": "per million tokens", "savings_note": "Sử dụng HolySheep AI tiết kiệm 85%+ so với các nhà cung cấp khác" } @app.get("/v1/health") async def health_check(): """Health check endpoint""" return { "status": "healthy", "upstream": "HolySheep AI", "base_url": config.base_url, "version": "1.0.0" } @app.get("/v1/usage/{user_id}") async def get_usage(user_id: str): """Lấy thông tin sử dụng của user""" # Trong production, query từ database return { "user_id": user_id, "total_requests_today": 1542, "total_tokens_today": 2500000, "estimated_cost_today": 1.05, "cache_hit_rate": 0.32, "avg_latency_ms": 45.2 } if __name__ == "__main__": uvicorn.run( "main:app", host="0.0.0.0", port=8000, workers=4, reload=False )

6. Docker Deployment

# Dockerfile
FROM python:3.11-slim

WORKDIR /app

Install dependencies

COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt

Copy application code

COPY . .

Environment variables

ENV PYTHONUNBUFFERED=1 ENV HOLYSHEEP_API_KEY=${HOLYSHEEP_API_KEY}

Expose port

EXPOSE 8000

Run with uvicorn

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
# docker-compose.yml
version: '3.8'

services:
  ai-gateway:
    build: .
    ports:
      - "8000:8000"
    environment:
      - HOLYSHEEP_API_KEY=${HOLYSHEEP_API_KEY}
    deploy:
      replicas: 3
      resources:
        limits:
          cpus: '2'
          memory: 4G
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/v1/health"]
      interval: 30s
      timeout: 10s
      retries: 3

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    volumes:
      - redis-data:/data
    command: redis-server --appendonly yes

volumes:
  redis-data:

Hướng Dẫn Sử Dụng

Test Gateway Với Curl

# Health check
curl -X GET http://localhost:8000/v1/health

List models với pricing

curl -X GET http://localhost:8000/v1/models

Chat completion request

curl -X POST http://localhost:8000/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer sk-user-001" \ -d '{ "model": "deepseek/v3.2", "messages": [ {"role": "system", "content": "Bạn là trợ lý AI hỗ trợ khách hàng thương mại điện tử"}, {"role": "user", "content": "Tôi muốn đổi size áo từ M sang L, làm sao?"} ], "temperature": 0.7, "max_tokens": 500, "use_cache": true }'

Python Client Example

# client_example.py
import httpx
import asyncio
import time

class HolySheepAIClient:
    def __init__(self, api_key: str, base_url: str = "http://localhost:8000"):
        self.api_key = api_key
        self.base_url = base_url
    
    async def chat(self, messages, model="deepseek/v3.2", **kwargs):
        async with httpx.AsyncClient(timeout=60) as client:
            response = await client.post(
                f"{self.base_url}/v1/chat/completions",
                json={
                    "model": model,
                    "messages": messages,
                    **kwargs
                },
                headers={"Authorization": f"Bearer {self.api_key}"}
            )
            return response.json()
    
    async def batch_chat(self, requests, model="deepseek/v3.2"):
        """Xử lý nhiều requests song song với concurrency limit"""
        semaphore = asyncio.Semaphore(10)  # Max 10 concurrent requests
        
        async def limited_chat(req):
            async with semaphore:
                return await self.chat(req, model)
        
        start = time.time()
        results = await asyncio.gather(*[limited_chat(r) for r in requests])
        duration = time.time() - start
        
        return {
            "total_requests": len(requests),
            "successful": sum(1 for r in results if "error" not in r),
            "total_cost": sum(r.get("cost", 0) for r in results),
            "avg_latency_ms": sum(r.get("latency_ms", 0) for r in results) / len(results),
            "total_duration_s": round(duration, 2),
            "requests_per_second": round(len(requests) / duration, 2)
        }

Sử dụng client

async def main(): client = HolySheepAIClient(api_key="sk-user-001") # Single request result = await client.chat([ {"role": "user", "content": "Xin chào, tôi cần hỗ trợ về đơn hàng #12345"} ]) print(f"Response: {result['content']['choices'][0]['message']['content']}") print(f"Cost: ${result['cost']}, Latency: {result['latency_ms']}ms") # Batch processing batch_requests = [ [{"role": "user", "content": f"Tôi cần hỗ trợ về đơn hàng #{i}"}] for i in range(100) ] batch_result = await client.batch_chat(batch_requests) print(f"Batch processed: {batch_result['total_requests']} requests") print(f"Total cost: ${batch_result['total_cost']:.4f}") print(f"Throughput: {batch_result['requests_per_second']} req/s") asyncio.run(main())

So Sánh Chi Phí: HolySheep AI vs. Nhà Cung Cấp Khác

ModelNhà cung cấp khác ($/MTok)HolySheep AI ($/MTok)Tiết kiệm
DeepSeek V3.2$2.80$0.4285%
GPT-4.1$30.00$8.0073%
Claude Sonnet 4.5$45.00$15.0067%
Gemini 2.5 Flash$10.00$2.5075%

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ệ

# ❌ Sai cách - hardcode API key trong code
headers = {"Authorization": "Bearer sk-test-key-123"}

✅ Đúng cách - sử dụng environment variable

import os headers = {"Authorization": f"Bearer {os.getenv('HOLYSHEEP_API_KEY')}"}

Hoặc sử dụng Pydantic settings

from pydantic_settings import BaseSettings class Settings(BaseSettings): holysheep_api_key: str = "YOUR_HOLYSHEEP_API_KEY" settings = Settings()

Nguyên nhân: API key không được set đúng hoặc đã hết hạn. Cách khắc phục: Kiểm tra lại biến môi trường HOLYSHEEP_API_KEY và đảm bảo key còn hiệu lực tại dashboard HolySheep AI.

2. Lỗi 429 Rate Limit Exceeded

# ❌ Không handle rate limit - crash khi bị limit
response = await client.post(url, json=payload, headers=headers)

✅ Đúng cách - implement retry với exponential backoff

async def request_with_retry(client, url, payload, headers, max_retries=3): for attempt in range(max_retries): try: response = await client.post(url, json=payload, headers=headers) if response.status_code == 429: retry_after = int(response.headers.get("Retry-After", 60)) wait_time = retry_after if attempt == 0 else retry_after * (2 ** attempt) print(f"Rate limited. Waiting {wait_time}s...") await asyncio.sleep(wait_time) continue return response except httpx.TimeoutException: if attempt == max_retries - 1: raise await asyncio.sleep(2 ** attempt) raise Exception("Max retries exceeded")

Nguyên nhân: Số lượng requests vượt quá giới hạn cho phép. Cách khắc phục: Implement token bucket algorithm, theo dõi rate limit headers từ response, và sử dụng exponential backoff khi retry.

3. Lỗi Timeout Khi Xử Lý Request Lớn

# ❌ Default timeout quá ngắn cho request lớn
async with httpx.AsyncClient(timeout=10) as client:  # 10 seconds
    response = await client.post(url, json=payload)

✅ Config timeout thông minh dựa trên request size

def calculate_timeout(max_tokens: int, is_streaming: bool = False) -> float: """Tính timeout phù hợp với request size""" base_timeout = 30 # seconds # Timeout tăng theo max_tokens if max_tokens > 50000: base_timeout = 120 elif max_tokens > 10000: base_timeout = 60 # Streaming requests cần timeout dài hơn if is_streaming: base_timeout *= 2 return base_timeout

Sử dụng

timeout = calculate_timeout(request.max_tokens, request.stream) async with httpx.AsyncClient(timeout=timeout) as client: response = await client.post(url, json=payload, headers=headers)

Nguyên nhân: Request có max_tokens lớn hoặc upstream latency cao vượt quá timeout mặc định. Cách khắc phục: Config timeout động dựa trên request parameters, implement streaming cho response lớn, và sử dụng cache để giảm tải.

4. Lỗi Semantic Cache Miss Không Đáng Có

#