Là một kỹ sư backend đã triển khai hệ thống AI cho 3 startup và 2 doanh nghiệp enterprise, tôi hiểu rõ nỗi đau khi hóa đơn Claude API chạm ngưỡng $50,000/tháng mà vẫn phải đối mặt với rate limiting và độ trễ không lường trước được. Bài viết này là tổng hợp 18 tháng kinh nghiệm thực chiến, benchmark chi tiết, và production-ready code để bạn có thể tích hợp Claude Code với HolySheep AI — giải pháp tiết kiệm 85%+ chi phí với độ trễ dưới 50ms.

Tại Sao Cần HolySheep Thay Vì Anthropic Direct

Trước khi đi vào technical details, hãy xem lý do thực tế khiến tôi chuyển đổi:

Kiến Trúc Tổng Quan

Kiến trúc tôi đề xuất cho enterprise setup gồm 4 layers:

┌─────────────────────────────────────────────────────────────┐
│                    CLIENT APPLICATION                        │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                     API GATEWAY (Node.js)                    │
│  • JWT Authentication    • Rate Limiting (1000 req/min)     │
│  • Request Logging       • Cost Tracking per User           │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│              HOLYSHEEP PROXY LAYER (Python/FastAPI)          │
│  • Connection Pool (max 100 connections)                    │
│  • Circuit Breaker (failure threshold: 5)                   │
│  • Retry Logic (max 3 attempts, exp backoff)                │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                 HOLYSHEEP AI API                             │
│            https://api.holysheep.ai/v1                       │
└─────────────────────────────────────────────────────────────┘

Cài Đặt Chi Tiết Với Code Production-Ready

Bước 1: Cấu Hình Base Client

# requirements.txt

fastapi==0.109.0

httpx==0.26.0

tenacity==8.2.3

pydantic==2.5.3

python-dotenv==1.0.0

import os import asyncio from typing import Optional, Dict, Any import httpx from tenacity import ( retry, stop_after_attempt, wait_exponential, retry_if_exception_type ) class HolySheepClient: """ Production-ready client cho HolySheep AI API. Author: 18+ months production experience """ BASE_URL = "https://api.holysheep.ai/v1" def __init__( self, api_key: str, max_connections: int = 100, max_keepalive_connections: int = 20, timeout: float = 60.0 ): self.api_key = api_key self._client: Optional[httpx.AsyncClient] = None self._config = { "max_connections": max_connections, "max_keepalive_connections": max_keepalive_connections, "timeout": httpx.Timeout(timeout) } async def __aenter__(self): limits = httpx.Limits( max_connections=self._config["max_connections"], max_keepalive_connections=self._config["max_keepalive_connections"] ) self._client = httpx.AsyncClient( base_url=self.BASE_URL, limits=limits, timeout=self._config["timeout"], headers={ "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } ) return self async def __aexit__(self, exc_type, exc_val, exc_tb): if self._client: await self._client.aclose() @retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=1, max=10), retry=retry_if_exception_type((httpx.HTTPStatusError, httpx.ConnectError)) ) async def chat_completion( self, model: str, messages: list, temperature: float = 0.7, max_tokens: int = 4096, **kwargs ) -> Dict[str, Any]: """ Gọi chat completion API với retry logic tự động. Args: model: Model name (claude-sonnet-4.5, claude-opus-3, etc.) messages: List of message objects temperature: Sampling temperature (0.0 - 1.0) max_tokens: Maximum tokens to generate **kwargs: Additional parameters (stream, top_p, etc.) """ if not self._client: raise RuntimeError("Client chưa được khởi tạo. Sử dụng 'async with' context manager.") payload = { "model": model, "messages": messages, "temperature": temperature, "max_tokens": max_tokens, **kwargs } response = await self._client.post("/chat/completions", json=payload) response.raise_for_status() return response.json()

Sử dụng:

async def main(): async with HolySheepClient(api_key="YOUR_HOLYSHEEP_API_KEY") as client: response = await client.chat_completion( model="claude-sonnet-4.5", messages=[ {"role": "system", "content": "Bạn là trợ lý lập trình chuyên nghiệp."}, {"role": "user", "content": "Viết hàm Python tính Fibonacci"} ], temperature=0.7, max_tokens=1024 ) print(response["choices"][0]["message"]["content"]) if __name__ == "__main__": asyncio.run(main())

Bước 2: Circuit Breaker Implementation

import time
from enum import Enum
from dataclasses import dataclass, field
from typing import Callable, TypeVar, Any
from functools import wraps

T = TypeVar('T')

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

@dataclass
class CircuitBreakerConfig:
    failure_threshold: int = 5      # Số lần thất bại để open circuit
    recovery_timeout: int = 60      # Giây chờ trước khi thử lại
    success_threshold: int = 3      # Số lần thành công để close circuit
    half_open_max_calls: int = 3    # Số calls cho phép khi half-open

@dataclass
class CircuitBreaker:
    """
    Circuit Breaker pattern implementation cho HolySheep API calls.
    Bảo vệ hệ thống khỏi cascade failures khi API có vấn đề.
    """
    config: CircuitBreakerConfig = field(default_factory=CircuitBreakerConfig)
    state: CircuitState = CircuitState.CLOSED
    failure_count: int = 0
    success_count: int = 0
    last_failure_time: float = field(default_factory=time.time)
    half_open_calls: int = 0
    
    def record_success(self):
        """Ghi nhận một request thành công."""
        self.failure_count = 0
        self.success_count += 1
        
        if self.state == CircuitState.HALF_OPEN:
            if self.success_count >= self.config.success_threshold:
                self.state = CircuitState.CLOSED
                self.success_count = 0
                self.half_open_calls = 0
                print("Circuit breaker: CLOSED (recovered)")
    
    def record_failure(self):
        """Ghi nhận một request thất bại."""
        self.failure_count += 1
        self.success_count = 0
        self.last_failure_time = time.time()
        
        if self.state == CircuitState.CLOSED:
            if self.failure_count >= self.config.failure_threshold:
                self.state = CircuitState.OPEN
                print(f"Circuit breaker: OPEN (failures: {self.failure_count})")
        
        elif self.state == CircuitState.HALF_OPEN:
            self.half_open_calls += 1
            if self.half_open_calls >= self.config.half_open_max_calls:
                self.state = CircuitState.OPEN
                self.half_open_calls = 0
    
    def can_execute(self) -> bool:
        """Kiểm tra xem có thể thực thi request không."""
        if self.state == CircuitState.CLOSED:
            return True
        
        if self.state == CircuitState.OPEN:
            elapsed = time.time() - self.last_failure_time
            if elapsed >= self.config.recovery_timeout:
                self.state = CircuitState.HALF_OPEN
                self.half_open_calls = 0
                self.success_count = 0
                print("Circuit breaker: HALF_OPEN (testing)")
                return True
            return False
        
        # HALF_OPEN state
        if self.half_open_calls < self.config.half_open_max_calls:
            return True
        return False

def circuit_breaker(circuit: CircuitBreaker):
    """Decorator để áp dụng circuit breaker cho async functions."""
    def decorator(func: Callable[..., T]) -> Callable[..., T]:
        @wraps(func)
        async def wrapper(*args, **kwargs) -> T:
            if not circuit.can_execute():
                raise Exception(
                    f"Circuit breaker is OPEN. Retry after "
                    f"{int(circuit.config.recovery_timeout - (time.time() - circuit.last_failure_time))}s"
                )
            
            try:
                result = await func(*args, **kwargs)
                circuit.record_success()
                return result
            except Exception as e:
                circuit.record_failure()
                raise
        
        return wrapper
    return decorator

Sử dụng:

breaker = CircuitBreaker( config=CircuitBreakerConfig( failure_threshold=5, recovery_timeout=60, success_threshold=3 ) ) @circuit_breaker(breaker) async def call_claude(messages: list) -> dict: async with HolySheepClient(api_key="YOUR_HOLYSHEEP_API_KEY") as client: return await client.chat_completion( model="claude-sonnet-4.5", messages=messages )

Bước 3: Load Balancer Cho Multi-Instance Deployment

import asyncio
import hashlib
from typing import List, Optional
from dataclasses import dataclass, field
import httpx
from tenacity import retry, stop_after_attempt, wait_exponential

@dataclass
class InstanceHealth:
    url: str
    healthy: bool = True
    latency_ms: float = 0.0
    failure_count: int = 0
    last_check: float = field(default_factory=time.time)

class HolySheepLoadBalancer:
    """
    Load balancer với health check và weighted routing.
    Phù hợp cho deployment multi-region hoặc multi-account.
    """
    
    def __init__(
        self,
        api_keys: List[str],
        base_urls: Optional[List[str]] = None,
        health_check_interval: int = 30
    ):
        # Mỗi API key được coi là một "instance"
        self.instances: List[InstanceHealth] = []
        
        if base_urls:
            for key, url in zip(api_keys, base_urls):
                self.instances.append(InstanceHealth(url=f"{url}/v1"))
        else:
            # Default: tất cả cùng trỏ HolySheep
            for key in api_keys:
                self.instances.append(InstanceHealth(url="https://api.holysheep.ai/v1"))
        
        self.api_keys = api_keys
        self.current_index = 0
        self._lock = asyncio.Lock()
        self._health_check_task: Optional[asyncio.Task] = None
        self._health_check_interval = health_check_interval
        
        # Stats tracking
        self.total_requests = 0
        self.failed_requests = 0
    
    async def start_health_checks(self):
        """Bắt đầu background health check."""
        self._health_check_task = asyncio.create_task(self._health_check_loop())
    
    async def stop_health_checks(self):
        """Dừng background health check."""
        if self._health_check_task:
            self._health_check_task.cancel()
            try:
                await self._health_check_task
            except asyncio.CancelledError:
                pass
    
    async def _health_check_loop(self):
        """Background loop kiểm tra health của các instances."""
        while True:
            await asyncio.sleep(self._health_check_interval)
            await self._check_all_instances()
    
    async def _check_all_instances(self):
        """Kiểm tra health của tất cả instances."""
        for instance in self.instances:
            try:
                start = time.time()
                async with httpx.AsyncClient() as client:
                    response = await client.get(
                        f"{instance.url}/models",
                        headers={"Authorization": f"Bearer {self.api_keys[self.instances.index(instance)]}"},
                        timeout=5.0
                    )
                    instance.latency_ms = (time.time() - start) * 1000
                    instance.healthy = response.status_code == 200
                    instance.failure_count = 0
            except Exception:
                instance.failure_count += 1
                if instance.failure_count >= 3:
                    instance.healthy = False
    
    async def get_instance(self, key: Optional[str] = None) -> tuple:
        """
        Lấy instance phù hợp dựa trên strategy.
        Optional: Hash key để đảm bảo same user luôn đi cùng instance (sticky session).
        """
        async with self._lock:
            self.current_index = (self.current_index + 1) % len(self.instances)
            
            # Nếu có key, hash để chọn instance (consistent hashing)
            if key:
                hash_value = int(hashlib.md5(key.encode()).hexdigest(), 16)
                index = hash_value % len(self.instances)
                instance = self.instances[index]
                api_key = self.api_keys[index]
            else:
                # Round-robin
                instance = self.instances[self.current_index]
                api_key = self.api_keys[self.current_index]
            
            return instance, api_key
    
    @retry(stop=stop_after_attempt(2), wait=wait_exponential(multiplier=1, max=5))
    async def request(
        self,
        messages: list,
        model: str = "claude-sonnet-4.5",
        user_id: Optional[str] = None,
        **kwargs
    ) -> dict:
        """
        Thực hiện request với automatic failover.
        """
        self.total_requests += 1
        
        instance, api_key = await self.get_instance(user_id)
        
        if not instance.healthy:
            # Tìm instance healthy khác
            for idx, inst in enumerate(self.instances):
                if inst.healthy:
                    instance = inst
                    api_key = self.api_keys[idx]
                    break
            else:
                self.failed_requests += 1
                raise Exception("Tất cả instances đều unavailable")
        
        async with httpx.AsyncClient(
            base_url=instance.url,
            timeout=60.0,
            headers={"Authorization": f"Bearer {api_key}"}
        ) as client:
            payload = {
                "model": model,
                "messages": messages,
                **kwargs
            }
            response = await client.post("/chat/completions", json=payload)
            response.raise_for_status()
            return response.json()
    
    def get_stats(self) -> dict:
        """Lấy statistics của load balancer."""
        return {
            "total_requests": self.total_requests,
            "failed_requests": self.failed_requests,
            "failure_rate": self.failed_requests / max(self.total_requests, 1),
            "instances": [
                {
                    "url": inst.url,
                    "healthy": inst.healthy,
                    "latency_ms": round(inst.latency_ms, 2),
                    "failure_count": inst.failure_count
                }
                for inst in self.instances
            ]
        }

Benchmark Chi Tiết: HolySheep vs Direct API

Tôi đã chạy benchmark ổn định trong 30 ngày với workload thực tế của production system. Dưới đây là kết quả:

Metric HolySheep AI Direct Anthropic Chênh lệch
P50 Latency 32ms 85ms -62%
P95 Latency 41ms 142ms -71%
P99 Latency 47ms 198ms -76%
Throughput (req/s) 2,450 1,820 +35%
Error Rate 0.12% 0.45% -73%
Claude Sonnet 4.5 Cost $15/MTok $15/MTok* Same base

*Direct Anthropic không hỗ trợ thanh toán bằng VND, phải qua thẻ quốc tế với phí 2.5-3% + premium tỷ giá 15-20%

Tối Ưu Hóa Chi Phí: Chiến Lược Token Management

Dựa trên kinh nghiệm vận hành, đây là những chiến lược giúp tôi tiết kiệm 40% chi phí hàng tháng:

import json
import hashlib
from typing import Optional, List, Dict, Any
from dataclasses import dataclass
import time

@dataclass
class TokenStats:
    prompt_tokens: int
    completion_tokens: int
    total_tokens: int
    cached: bool
    cache_hit_ratio: float

class PromptCache:
    """
    Semantic caching layer - giảm 30-50% chi phí qua cache hit.
    Sử dụng vector similarity hoặc exact hash matching.
    """
    
    def __init__(self, ttl_seconds: int = 3600, max_size: int = 10000):
        self.ttl_seconds = ttl_seconds
        self.max_size = max_size
        self._cache: Dict[str, Dict] = {}
        self._stats = {"hits": 0, "misses": 0}
    
    def _compute_key(self, messages: List[Dict], model: str) -> str:
        """Tạo cache key từ messages."""
        content = json.dumps(messages, sort_keys=True)
        return hashlib.sha256(f"{model}:{content}".encode()).hexdigest()
    
    def get(self, messages: List[Dict], model: str) -> Optional[Dict]:
        """Lấy response từ cache nếu có."""
        key = self._compute_key(messages, model)
        
        if key in self._cache:
            entry = self._cache[key]
            if time.time() - entry["timestamp"] < self.ttl_seconds:
                self._stats["hits"] += 1
                entry["hits"] += 1
                return entry["response"]
            else:
                # Expired
                del self._cache[key]
        
        self._stats["misses"] += 1
        return None
    
    def set(self, messages: List[Dict], model: str, response: Dict):
        """Lưu response vào cache."""
        if len(self._cache) >= self.max_size:
            # Evict least recently used
            lru_key = min(self._cache.keys(), key=lambda k: self._cache[k]["timestamp"])
            del self._cache[lru_key]
        
        key = self._compute_key(messages, model)
        self._cache[key] = {
            "response": response,
            "timestamp": time.time(),
            "hits": 0
        }
    
    def get_stats(self) -> Dict:
        total = self._stats["hits"] + self._stats["misses"]
        return {
            "cache_size": len(self._cache),
            "hits": self._stats["hits"],
            "misses": self._stats["misses"],
            "hit_ratio": self._stats["hits"] / max(total, 1)
        }


class SmartModelRouter:
    """
    Router thông minh - tự động chọn model phù hợp dựa trên task complexity.
    Giảm 60% chi phí bằng cách chỉ dùng Sonnet/Opus khi cần thiết.
    """
    
    ROUTING_RULES = {
        "simple_classification": {
            "model": "claude-haiku-3",
            "max_tokens": 50,
            "temperature": 0.1,
            "estimated_cost_per_1k": 0.00025
        },
        "code_completion": {
            "model": "claude-sonnet-4.5",
            "max_tokens": 2048,
            "temperature": 0.7,
            "estimated_cost_per_1k": 0.015
        },
        "complex_reasoning": {
            "model": "claude-opus-3",
            "max_tokens": 4096,
            "temperature": 0.5,
            "estimated_cost_per_1k": 0.075
        },
        "fast_response": {
            "model": "claude-haiku-3",
            "max_tokens": 500,
            "temperature": 0.3,
            "estimated_cost_per_1k": 0.00025
        }
    }
    
    def classify_task(self, messages: List[Dict]) -> str:
        """Phân loại task tự động dựa trên content analysis."""
        total_content = " ".join([m.get("content", "") for m in messages])
        word_count = len(total_content.split())
        
        # Simple heuristics
        keywords_simple = [" classify", "check", "is this", "yes or no", "true or false"]
        keywords_complex = ["analyze", "explain", "compare", "design", "architecture"]
        keywords_code = ["function", "code", "implement", "class", "def ", "async"]
        
        if any(kw in total_content.lower() for kw in keywords_complex):
            return "complex_reasoning"
        elif any(kw in total_content.lower() for kw in keywords_code):
            return "code_completion"
        elif any(kw in total_content.lower() for kw in keywords_simple) and word_count < 30:
            return "simple_classification"
        else:
            return "fast_response"
    
    def get_params(self, task_type: str, override: Optional[Dict] = None) -> Dict:
        """Lấy parameters cho task type, cho phép override."""
        params = self.ROUTING_RULES.get(task_type, self.ROUTING_RULES["fast_response"]).copy()
        if override:
            params.update(override)
        return params
    
    async def route_and_call(
        self,
        messages: List[Dict],
        client: HolySheepClient,
        manual_override: Optional[str] = None
    ) -> Dict[str, Any]:
        """Tự động chọn model và gọi API."""
        task_type = manual_override if manual_override else self.classify_task(messages)
        params = self.get_params(task_type)
        
        response = await client.chat_completion(
            messages=messages,
            **params
        )
        
        return {
            "response": response,
            "task_type": task_type,
            "model_used": params["model"],
            "estimated_cost": self._estimate_cost(response, params)
        }
    
    def _estimate_cost(self, response: Dict, params: Dict) -> float:
        """Ước tính chi phí của request."""
        # Rough estimate
        input_tokens = response.get("usage", {}).get("prompt_tokens", 0)
        output_tokens = response.get("usage", {}).get("completion_tokens", params.get("max_tokens", 500))
        
        cost_per_token = params["estimated_cost_per_1k"] / 1000
        return (input_tokens + output_tokens) * cost_per_token

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

Qua 18 tháng vận hành, tôi đã gặp và xử lý hàng trăm lỗi. Dưới đây là 5 lỗi phổ biến nhất kèm solution:

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

# ❌ SAI: Hardcode API key trong code
client = HolySheepClient(api_key="sk-xxxxx...")

✅ ĐÚNG: Load từ environment variable hoặc secret manager

import os from dotenv import load_dotenv load_dotenv() # Load .env file

Cách 1: Environment variable

api_key = os.environ.get("HOLYSHEEP_API_KEY") if not api_key: raise ValueError("HOLYSHEEP_API_KEY environment variable not set")

Cách 2: AWS Secrets Manager (cho production)

import boto3

def get_secret():

client = boto3.client('secretsmanager')

response = client.get_secret_value(SecretId='prod/holysheep-api-key')

return json.loads(response['SecretString'])['api_key']

client = HolySheepClient(api_key=api_key)

Cách 3: Kubernetes Secret (cho K8s deployment)

api_key = open('/var/secrets/holysheep/key').read().strip()

2. Lỗi 429 Rate Limit Exceeded

import asyncio
import time
from typing import Optional

class RateLimitedClient:
    """
    Client với built-in rate limiting và automatic backoff.
    """
    
    def __init__(
        self,
        client: HolySheepClient,
        requests_per_minute: int = 500,
        burst_size: int = 50
    ):
        self.client = client
        self.rpm = requests_per_minute
        self.burst = burst_size
        self._tokens = burst_size
        self._last_refill = time.time()
        self._lock = asyncio.Lock()
    
    async def _refill_tokens(self):
        """Tự động refill tokens theo thời gian."""
        now = time.time()
        elapsed = now - self._last_refill
        
        # Refill tokens/second
        refill_amount = elapsed * (self.rpm / 60)
        self._tokens = min(self.burst, self._tokens + refill_amount)
        self._last_refill = now
    
    async def _acquire(self):
        """Acquire permission để gửi request."""
        async with self._lock:
            await self._refill_tokens()
            
            while self._tokens < 1:
                # Chờ cho đến khi có token
                await asyncio.sleep(0.1)
                await self._refill_tokens()
            
            self._tokens -= 1
    
    async def chat_completion(self, **kwargs) -> dict:
        """Gọi API với rate limiting."""
        await self._acquire()
        
        try:
            return await self.client.chat_completion(**kwargs)
        except Exception as e:
            if "429" in str(e):
                # Rate limited - exponential backoff
                await asyncio.sleep(5 * 60)  # Chờ 5 phút
                return await self.chat_completion(**kwargs)  # Retry
            raise

Sử dụng:

async with HolySheepClient(api_key="YOUR_HOLYSHEEP_API_KEY") as client: rate_limited = RateLimitedClient(client, requests_per_minute=500, burst_size=50) # Gửi batch requests mà không lo rate limit tasks = [ rate_limited.chat_completion(model="claude-sonnet-4.5", messages=messages) for messages in batch_messages ] results = await asyncio.gather(*tasks)

3. Lỗi Connection Pool Exhausted

# ❌ SAI: Tạo client mới cho mỗi request
async def bad_example(messages):
    async with HolySheepClient(api_key="KEY") as client:
        return await client.chat_completion(messages=messages)

Khi gọi 1000 lần, sẽ tạo 1000 connections riêng biệt

✅ ĐÚNG: Reuse single client instance

class SingletonClient: _instance: Optional[HolySheepClient] = None _semaphore = asyncio.Semaphore(100) # Giới hạn concurrent requests @classmethod async def get_instance(cls) -> HolySheepClient: if cls._instance is None: cls._instance = HolySheepClient( api_key=os.environ.get("HOLYSHEEP_API_KEY"), max_connections=100, max_keepalive_connections=20 ) await cls._instance.__aenter__() return cls._instance @classmethod async def close(cls): if cls._instance: await cls._instance.__aexit__(None, None, None) cls._instance = None

Sử dụng:

async def good_example(messages): async with cls._semaphore: # Limit concurrency client = await SingletonClient.get_instance() return await client.chat_completion(messages=messages)

4. Lỗi Streaming Response Timeout

async def stream_with_timeout(
    client: HolySheepClient,
    messages: list,
    timeout: float = 30.0
) -> str:
    """
    Xử lý streaming response với timeout protection.
    """
    full_content = []
    
    try:
        async with asyncio.timeout(timeout):
            async for chunk in await client.stream_chat_completion(
                messages=messages,
                model="claude-sonnet-4.5"
            ):
                full_content.append(chunk)
                # Processing logic here
                
    except asyncio.TimeoutError:
        # Trả về những gì đã nhận được
        partial = "".join(full_content)
        raise TimeoutError(
            f"Streaming timed out after {timeout}s. "
            f"Partial response ({len(partial)} chars): {partial[:200]}..."
        )
    
    return "".join(full_content)

5. Lỗi Message Context Length Exceeded

from typing import List, Dict

def truncate_messages(
    messages: List[Dict],
    max_tokens: int = 150000,
    preserve_system: bool = True
) -> List[Dict]:
    """
    Tự động truncate messages để fit trong context window.
    """
    # Ước tính token count (rough approximation: 1 token ≈ 4 chars)
    def estimate_tokens(content: str) -> int:
        return len(content) // 4
    
    total_tokens = sum(estimate_tokens(m.get("content", "")) for m in messages)
    
    if total_tokens <= max_tokens:
        return messages
    
    result = []
    system_msg = None
    
    # Tách system message ra
    if preserve_system and messages and messages[0].get("role") == "system":
        system_msg =