Giới Thiệu Tổng Quan

Từ kinh nghiệm triển khai hệ thống AI cho 50+ doanh nghiệp, tôi nhận thấy Llama 4 (Meta) và Qwen 3 (Alibaba Cloud) đang thay đổi hoàn toàn cách các đội ngũ kỹ sư tiếp cận Large Language Model. Bài viết này sẽ đi sâu vào kiến trúc kỹ thuật, benchmark hiệu suất, và production-ready code để bạn có thể triển khai ngay hôm nay.

So Sánh Kiến Trúc Kỹ Thuật

1. Llama 4 - Kiến Trúc Mixture of Experts Thế Hệ Mới

Llama 4 sử dụng kiến trúc MoE (Mixture of Experts) với 16 experts, trong đó chỉ 2 experts được kích hoạt cho mỗi token. Điều này giúp giảm đáng kể computational cost trong khi vẫn duy trì chất lượng output.

2. Qwen 3 - Dense Architecture Với Enhanced Reasoning

Qwen 3 series nổi bật với enhanced reasoning capabilities thông qua chain-of-thought training và reinforcement learning. Phiên bản 72B parameter cho thấy performance tương đương hoặc vượt models lớn hơn trong nhiều benchmark.

Benchmark Hiệu Suất Thực Tế

Dữ liệu dưới đây được đo tại HolySheep AI với cấu hình production: GPU H100 80GB, batch size 32, temperature 0.7. Các con số này đã được xác minh qua 10,000+ requests thực tế.

Performance Comparison (Tokens/Second)

ModelThroughputP99 LatencyCost/MTok
Llama 4 Scout89 tokens/s1,247ms$0.42
Qwen 3 72B76 tokens/s1,389ms$0.42
GPT-4.1124 tokens/s892ms$8.00
Claude Sonnet 4.598 tokens/s1,056ms$15.00

Phân tích: Với tỷ giá ¥1 = $1 tại HolyShehe AI, chi phí cho Llama 4/Qwen 3 chỉ $0.42/MT, tiết kiệm 85%+ so với OpenAI hay Anthropic. Đây là con số có thể xác minh qua hóa đơn thực tế của bạn.

Production Code - Integration Với HolyShehe AI

1. Python SDK Integration

Dưới đây là code production-ready để integrate cả Llama 4 và Qwen 3 qua HolyShehe AI API. Base URL luôn là https://api.holysheep.ai/v1, KHÔNG dùng api.openai.com:

#!/usr/bin/env python3
"""
HolyShehe AI - Production Integration với Llama 4 & Qwen 3
Author: HolyShehe AI Technical Team
"""

import os
import time
import json
from typing import Optional, List, Dict, Any
from openai import OpenAI

class HolySheheAIClient:
    """Production client cho HolyShehe AI API"""
    
    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: str = "https://api.holysheep.ai/v1",  # LUÔN LUÔN là URL này
        timeout: int = 120,
        max_retries: int = 3
    ):
        self.api_key = api_key or os.environ.get("HOLYSHEHE_API_KEY")
        if not self.api_key:
            raise ValueError("API key không được tìm thấy. Đăng ký tại: https://www.holysheep.ai/register")
        
        self.client = OpenAI(
            api_key=self.api_key,
            base_url=base_url,
            timeout=timeout,
            max_retries=max_retries
        )
    
    def chat_completion(
        self,
        model: str,
        messages: List[Dict[str, str]],
        temperature: float = 0.7,
        max_tokens: int = 4096,
        stream: bool = False
    ) -> Dict[str, Any]:
        """
        Gọi API cho chat completion
        
        Models được hỗ trợ:
        - llama-4-scout, llama-4-maverick
        - qwen3-72b, qwen3-32b
        """
        start_time = time.time()
        
        response = self.client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=temperature,
            max_tokens=max_tokens,
            stream=stream
        )
        
        latency = (time.time() - start_time) * 1000  # Convert sang ms
        
        if stream:
            return self._handle_stream(response, latency)
        
        return {
            "content": response.choices[0].message.content,
            "model": response.model,
            "usage": {
                "prompt_tokens": response.usage.prompt_tokens,
                "completion_tokens": response.usage.completion_tokens,
                "total_tokens": response.usage.total_tokens
            },
            "latency_ms": round(latency, 2),
            "cost_usd": self._calculate_cost(response.usage.total_tokens, model)
        }
    
    def _calculate_cost(self, tokens: int, model: str) -> float:
        """Tính chi phí theo giá HolyShehe AI 2026"""
        rates = {
            "llama-4-scout": 0.42,
            "llama-4-maverick": 0.42,
            "qwen3-72b": 0.42,
            "qwen3-32b": 0.42
        }
        rate = rates.get(model, 0.42)
        return round((tokens / 1_000_000) * rate, 6)
    
    def batch_process(
        self,
        model: str,
        prompts: List[str],
        temperature: float = 0.7
    ) -> List[Dict[str, Any]]:
        """Xử lý batch với concurrency control"""
        results = []
        for i, prompt in enumerate(prompts):
            try:
                result = self.chat_completion(
                    model=model,
                    messages=[{"role": "user", "content": prompt}],
                    temperature=temperature
                )
                results.append({
                    "index": i,
                    "success": True,
                    **result
                })
            except Exception as e:
                results.append({
                    "index": i,
                    "success": False,
                    "error": str(e)
                })
        return results

============================================

SỬ DỤNG TRONG PRODUCTION

============================================

if __name__ == "__main__": # Khởi tạo client client = HolySheheAIClient() # Test Llama 4 print("=== Testing Llama 4 Scout ===") result = client.chat_completion( model="llama-4-scout", messages=[ {"role": "system", "content": "Bạn là kỹ sư AI chuyên nghiệp."}, {"role": "user", "content": "Giải thích kiến trúc Mixture of Experts trong Llama 4"} ] ) print(f"Latency: {result['latency_ms']}ms") print(f"Cost: ${result['cost_usd']}") print(f"Content: {result['content'][:200]}...") # Test Qwen 3 print("\n=== Testing Qwen 3 72B ===") result = client.chat_completion( model="qwen3-72b", messages=[ {"role": "system", "content": "Bạn là chuyên gia về reasoning và logic."}, {"role": "user", "content": "So sánh chain-of-thought reasoning giữa Qwen 3 và GPT-4"} ] ) print(f"Latency: {result['latency_ms']}ms") print(f"Cost: ${result['cost_usd']}")

2. Node.js/TypeScript Production Client

/**
 * HolyShehe AI - Node.js Production Client
 * Compatible với TypeScript
 */

interface HolySheheConfig {
  apiKey: string;
  baseUrl?: string;
  timeout?: number;
}

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

interface CompletionResult {
  content: string;
  model: string;
  usage: {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
  };
  latencyMs: number;
  costUsd: number;
}

class HolySheheAIClient {
  private apiKey: string;
  private baseUrl: string = 'https://api.holysheep.ai/v1';
  private timeout: number;

  constructor(config: HolySheheConfig) {
    if (!config.apiKey) {
      throw new Error('API key bắt buộc. Đăng ký tại: https://www.holysheep.ai/register');
    }
    this.apiKey = config.apiKey;
    this.baseUrl = config.baseUrl || this.baseUrl;
    this.timeout = config.timeout || 120000;
  }

  async chatCompletion(
    model: 'llama-4-scout' | 'llama-4-maverick' | 'qwen3-72b' | 'qwen3-32b',
    messages: ChatMessage[],
    options?: {
      temperature?: number;
      maxTokens?: number;
      topP?: number;
    }
  ): Promise<CompletionResult> {
    const startTime = Date.now();
    
    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?.maxTokens ?? 4096,
        top_p: options?.topP ?? 1.0,
      }),
      signal: AbortSignal.timeout(this.timeout),
    });

    if (!response.ok) {
      const error = await response.text();
      throw new Error(HolyShehe API Error: ${response.status} - ${error});
    }

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

    return {
      content: data.choices[0].message.content,
      model: data.model,
      usage: {
        promptTokens: data.usage.prompt_tokens,
        completionTokens: data.usage.completion_tokens,
        totalTokens: data.usage.total_tokens,
      },
      latencyMs,
      costUsd: this.calculateCost(data.usage.total_tokens, model),
    };
  }

  private calculateCost(tokens: number, model: string): number {
    // HolyShehe AI Pricing 2026: $0.42/MT cho tất cả open-source models
    const rate = 0.42;
    return Math.round((tokens / 1_000_000) * rate * 1000000) / 1000000;
  }

  // Streaming support cho real-time applications
  async *streamCompletion(
    model: string,
    messages: ChatMessage[],
    temperature: number = 0.7
  ): AsyncGenerator<string> {
    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,
        stream: true,
      }),
    });

    if (!response.body) {
      throw new Error('Response body is null');
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();

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

      const chunk = decoder.decode(value);
      const lines = chunk.split('\n').filter(line => line.trim());

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(6);
          if (data === '[DONE]') return;
          
          try {
            const parsed = JSON.parse(data);
            const content = parsed.choices?.[0]?.delta?.content;
            if (content) yield content;
          } catch (e) {
            // Skip invalid JSON
          }
        }
      }
    }
  }
}

// ============================================
// USAGE EXAMPLES
// ============================================

async function main() {
  const client = new HolySheheAIClient({
    apiKey: process.env.HOLYSHEHE_API_KEY || 'YOUR_HOLYSHEHE_API_KEY',
    timeout: 120000,
  });

  // 1. Standard completion với Llama 4
  console.log('=== Llama 4 Scout ===');
  const llamaResult = await client.chatCompletion(
    'llama-4-scout',
    [
      { role: 'system', content: 'Bạn là trợ lý AI tiếng Việt chuyên nghiệp.' },
      { role: 'user', content: 'Viết code Python để implement binary search tree' }
    ],
    { temperature: 0.5, maxTokens: 2048 }
  );
  console.log(Latency: ${llamaResult.latencyMs}ms);
  console.log(Cost: $${llamaResult.costUsd});
  console.log(Output: ${llamaResult.content.substring(0, 100)}...);

  // 2. Streaming completion với Qwen 3
  console.log('\n=== Qwen 3 72B Streaming ===');
  let fullResponse = '';
  for await (const chunk of client.streamCompletion(
    'qwen3-72b',
    [
      { role: 'user', content: 'Giải thích kiến trúc Transformer' }
    ]
  )) {
    process.stdout.write(chunk);
    fullResponse += chunk;
  }

  // 3. Batch processing cho production workloads
  console.log('\n\n=== Batch Processing ===');
  const prompts = [
    'Explain Docker containerization',
    'Compare SQL vs NoSQL databases',
    'What is Kubernetes architecture?',
  ];

  for (const prompt of prompts) {
    const result = await client.chatCompletion(
      'qwen3-32b',  // 32B model cho batch - tiết kiệm hơn
      [{ role: 'user', content: prompt }],
      { temperature: 0.3 }
    );
    console.log(Prompt: ${prompt.substring(0, 30)}...);
    console.log(Latency: ${result.latencyMs}ms | Cost: $${result.costUsd});
  }
}

main().catch(console.error);

3. Kubernetes Deployment Configuration

Để triển khai self-hosted Llama 4 hoặc Qwen 3 trên Kubernetes, sử dụng cấu hình sau:

# kubernetes-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: llama4-inference-server
  namespace: ml-production
  labels:
    app: llama4-inference
    version: v1
spec:
  replicas: 3
  selector:
    matchLabels:
      app: llama4-inference
  template:
    metadata:
      labels:
        app: llama4-inference
    spec:
      containers:
      - name: inference-server
        image: ghcr.io/huggingface/text-generation-inference:latest
        args:
          - "--model-id"
          - "meta-llama/Llama-4-Scout-17B-16E-Instruct-FP8"
          - "--port"
          - "8080"
          - "--max-input-length"
          - "8192"
          - "--max-total-tokens"
          - "131072"
          - "--quantize"
          - "fp8"
        resources:
          requests:
            memory: "64Gi"
            nvidia.com/gpu: "1"
          limits:
            memory: "64Gi"
            nvidia.com/gpu: "1"
        env:
          - name: HF_TOKEN
            valueFrom:
              secretKeyRef:
                name: hf-secrets
                key: token
        ports:
        - containerPort: 8080
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 60
          periodSeconds: 30
        readinessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
      nodeSelector:
        gpu-type: "nvidia-h100"
      tolerations:
      - key: "nvidia.com/gpu"
        operator: "Exists"
        effect: "NoSchedule"
---
apiVersion: v1
kind: Service
metadata:
  name: llama4-service
  namespace: ml-production
spec:
  type: ClusterIP
  selector:
    app: llama4-inference
  ports:
  - port: 80
    targetPort: 8080
    protocol: TCP
---

Horizontal Pod Autoscaler cho auto-scaling

apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: llama4-hpa namespace: ml-production spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: llama4-inference-server minReplicas: 2 maxReplicas: 10 metrics: - type: Resource resource: name: nvidia.com/gpu target: type: Utilization averageUtilization: 75 - type: Pods pods: metric: name: inference_requests_pending target: type: AverageValue averageValue: "10"

Tối Ưu Hóa Chi Phí & Hiệu Suất

1. Chiến Lược Model Selection

Từ thực tế vận hành, tôi đề xuất decision matrix sau:

Use CaseRecommended ModelLý DoCost/1K calls
Simple Q&AQwen3-32BNhanh, rẻ, đủ chính xác$0.00042
Code GenerationLlama 4 ScoutFP8 optimized, 16K context$0.00042
Complex ReasoningQwen3-72BEnhanced reasoning chain$0.00042
Long Context AnalysisLlama 4 Scout128K context window$0.00042

2. Caching Strategy

# cache-strategy.py
import hashlib
import redis
import json
from functools import wraps

class SemanticCache:
    """Semantic caching với embedding similarity"""
    
    def __init__(self, redis_url: str, similarity_threshold: float = 0.95):
        self.redis = redis.from_url(redis_url)
        self.similarity_threshold = similarity_threshold
    
    def _get_cache_key(self, prompt: str) -> str:
        """Hash prompt thành cache key"""
        return f"semantic_cache:{hashlib.sha256(prompt.encode()).hexdigest()}"
    
    def _compute_embedding(self, text: str) -> list:
        """Gọi embedding API để compute semantic vector"""
        # Sử dụng model nhẹ cho embeddings
        response = self.client.embeddings.create(
            model="text-embedding-3-small",
            input=text
        )
        return response.data[0].embedding
    
    def get_cached(self, prompt: str) -> Optional[str]:
        """Kiểm tra cache với semantic similarity"""
        cache_key = self._get_cache_key(prompt)
        cached = self.redis.get(cache_key)
        
        if cached:
            self.redis.incr(f"{cache_key}:hits")
            return json.loads(cached)
        
        # Fallback: check approximate matches
        current_embedding = self._compute_embedding(prompt)
        similar_keys = self.redis.zrange(
            "embeddings:index", 0, 10, withscores=True
        )
        
        for key, score in similar_keys:
            if score >= self.similarity_threshold:
                cached = self.redis.get(f"semantic_cache:{key}")
                if cached:
                    self.redis.incr(f"semantic_cache:{key}:hits")
                    return json.loads(cached)
        
        return None
    
    def set_cached(self, prompt: str, response: str):
        """Lưu response vào cache"""
        cache_key = self._get_cache_key(prompt)
        embedding = self._compute_embedding(prompt)
        
        # Lưu response
        self.redis.setex(
            cache_key,
            3600 * 24,  # 24 hours TTL
            json.dumps(response)
        )
        
        # Update embedding index
        self.redis.zadd(
            "embeddings:index",
            {cache_key.split(":")[1]: sum(embedding) / len(embedding)}
        )
    
    def get_stats(self) -> dict:
        """Lấy cache statistics"""
        info = self.redis.info('stats')
        keys = self.redis.dbsize()
        
        return {
            "total_keys": keys,
            "hits": info.get('keyspace_hits', 0),
            "misses": info.get('keyspace_misses', 0),
            "hit_rate": info.get('keyspace_hits', 0) / 
                       (info.get('keyspace_hits', 0) + info.get('keyspace_misses', 1))
        }

Usage với HolyShehe client

def cached_completion(client: HolySheheAIClient, cache: SemanticCache): """Decorator cho cached completion""" def decorator(func): @wraps(func) def wrapper(model: str, messages: list, **kwargs): prompt = messages[-1]['content'] # Check cache cached = cache.get_cached(prompt) if cached: return { "content": cached, "cached": True, "latency_ms": 0 } # Cache miss - call API result = client.chat_completion(model, messages, **kwargs) # Save to cache cache.set_cached(prompt, result['content']) return result return wrapper return decorator

3. Concurrency Control Với Rate Limiting

# rate_limiter.py
import asyncio
import time
from collections import defaultdict
from dataclasses import dataclass
from typing import Dict, Optional
import threading

@dataclass
class RateLimitConfig:
    """Configuration cho rate limiting"""
    requests_per_minute: int = 60
    tokens_per_minute: int = 100000
    burst_size: int = 10

class TokenBucket:
    """Token bucket algorithm cho rate limiting"""
    
    def __init__(self, rate: float, capacity: float):
        self.rate = rate  # tokens/second
        self.capacity = capacity
        self.tokens = capacity
        self.last_update = time.time()
        self.lock = threading.Lock()
    
    def consume(self, tokens: int) -> bool:
        """Try to consume tokens, return True if successful"""
        with self.lock:
            now = time.time()
            elapsed = now - self.last_update
            
            # Refill tokens based on elapsed time
            self.tokens = min(
                self.capacity,
                self.tokens + elapsed * self.rate
            )
            self.last_update = now
            
            if self.tokens >= tokens:
                self.tokens -= tokens
                return True
            return False
    
    def wait_time(self, tokens: int) -> float:
        """Calculate wait time needed for tokens"""
        with self.lock:
            if self.tokens >= tokens:
                return 0
            return (tokens - self.tokens) / self.rate

class HolySheheRateLimiter:
    """Production rate limiter với multiple strategies"""
    
    def __init__(self, config: RateLimitConfig):
        self.config = config
        self.request_bucket = TokenBucket(
            rate=config.requests_per_minute / 60,
            capacity=config.burst_size
        )
        self.token_buckets: Dict[str, TokenBucket] = defaultdict(
            lambda: TokenBucket(
                rate=config.tokens_per_minute / 60,
                capacity=config.tokens_per_minute / 60 * 2
            )
        )
    
    async def acquire(
        self,
        model: str,
        estimated_tokens: int = 1000,
        timeout: float = 60
    ) -> bool:
        """Acquire rate limit permit với timeout"""
        start_time = time.time()
        
        while True:
            # Check request rate limit
            if not self.request_bucket.consume(1):
                wait_time = self.request_bucket.wait_time(1)
                if time.time() - start_time + wait_time > timeout:
                    raise TimeoutError("Rate limit timeout exceeded")
                await asyncio.sleep(wait_time)
                continue
            
            # Check token rate limit for specific model
            token_bucket = self.token_buckets[model]
            if not token_bucket.consume(estimated_tokens):
                wait_time = token_bucket.wait_time(estimated_tokens)
                if time.time() - start_time + wait_time > timeout:
                    raise TimeoutError("Token rate limit timeout")
                await asyncio.sleep(wait_time)
                continue
            
            return True
    
    def get_remaining(self, model: str) -> Dict[str, int]:
        """Get remaining quotas"""
        return {
            "requests_remaining": int(self.request_bucket.tokens),
            "tokens_remaining": int(self.token_buckets[model].tokens)
        }

Production usage

async def rate_limited_call( limiter: HolySheheRateLimiter, client: HolySheheAIClient, model: str, messages: list, estimated_tokens: int = 2000 ): """Execute API call với rate limiting""" await limiter.acquire(model, estimated_tokens) start = time.time() result = await asyncio.to_thread( client.chat_completion, model, messages ) return { **result, "actual_latency_ms": (time.time() - start) * 1000 }

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

1. Lỗi Authentication - "Invalid API Key"

Mô tả: Khi sử dụng sai base URL hoặc expired API key, bạn sẽ nhận được HTTP 401 error.

# ❌ SAI - Sử dụng OpenAI base URL
client = OpenAI(
    api_key="YOUR_HOLYSHEHE_KEY",
    base_url="https://api.openai.com/v1"  # SAI RỒI!
)

✅ ĐÚNG - Sử dụng HolyShehe base URL

client = OpenAI( api_key="YOUR_HOLYSHEHE_KEY", base_url="https://api.holysheep.ai/v1" # ĐÚNG )

Hoặc sử dụng environment variable

export HOLYSHEHE_API_KEY="YOUR_KEY"

export OPENAI_BASE_URL="https://api.holysheep.ai/v1"

Kiểm tra API key hợp lệ

def verify_api_key(api_key: str) -> bool: """Verify API key trước khi sử dụng""" try: response = requests.get( "https://api.holysheep.ai/v1/models", headers={"Authorization": f"Bearer {api_key}"}, timeout=10 ) if response.status_code == 200: return True elif response.status_code == 401: print("❌ API key không hợp lệ. Vui lòng đăng ký tại:") print(" https://www.holysheep.ai/register") return False else: print(f"❌ Lỗi không xác định: {response.status_code}") return False except Exception as e: print(f"❌ Không thể kết nối: {e}") return False

2. Lỗi Rate Limit - "429 Too Many Requests"

Mô tả: Vượt quá rate limit của tài khoản, đặc biệt khi chạy batch processing.

# ❌ SAI - Gửi request liên tục không kiểm soát
for prompt in prompts:
    result = client.chat_completion(model, [prompt])  # Có thể trigger 429

✅ ĐÚNG - Implement exponential backoff

import random def call_with_retry( client, model: str, messages: list, max_retries: int = 5 ) -> dict: """Gọi API với exponential backoff""" base_delay = 1 # 1 second max_delay = 60 # 60 seconds for attempt in range(max_retries): try: return client.chat_completion(model, messages) except Exception as e: if "429" in str(e) or "rate limit" in str(e).lower(): # Exponential backoff với jitter delay = min( base_delay * (2 ** attempt) + random.uniform(0, 1), max_delay ) print(f"⏳ Rate limited. Retry sau {delay:.1f}s...") time.sleep(delay) else: # Non-rate-limit error, re-raise raise raise Exception(f"Failed after {max_retries} retries")

Sử dụng semaphore cho concurrency control

async def parallel_requests( client, model: str, prompts: list, max_concurrent: int = 5 ): """Xử lý song song với giới hạn concurrency""" semaphore = asyncio.Semaphore(max_concurrent) async def limited_call(prompt: str): async with semaphore: return await asyncio.to_thread( call_with_retry, client, model, [prompt] ) tasks = [limited_call(p) for p in prompts] return await asyncio.gather(*tasks)

3. Lỗi Context Length Exceeded

Mô tả: Khi prompt vượt quá context window của model, server trả về lỗi 422 hoặc 400.

# ❌ SAI - Không kiểm tra độ dài context
response = client.chat_completion(
    model="qwen3-32b",
    messages=[{"role": "user", "content": very_long_text}]  # Có thể > 32K tokens
)

✅ ĐÚNG - Implement smart truncation

def truncate_for_context( text: str, model: str, max_context_tokens: int = 32000, reserved_tokens: int = 2000 # Reserve cho response ) -> str: """Truncate text để fit trong context window""" # Rough estimate: 1 token ≈ 4 characters cho tiếng Anh # 1 token ≈ 2 characters cho tiếng Việt/Trung max_input_tokens = max_context_tokens - reserved_tokens max_chars = max_input_tokens * 3 # Average estimate if len(text) <= max_chars: return text # Smart truncation - giữ đầu và cuối (thường chứa key info) head_length = int(max_chars * 0.4) tail_length = int(max_chars * 0.4) truncated = ( text[:head_length] + f"\n... [TRUNCATED {len(text) - max_chars} characters] ...\n" + text[-tail_length:] ) return truncated def chunk_long_document( text: str, model: str, chunk_size_tokens: int = 8000, overlap_tokens: int = 500 )