Phần 11 · LLM Engineering · Bài 11

Caching, Rate Limiting & Tối ưu chi phí

23:02

Phần lớn startup AI không thất bại vì model kém. Họ thất bại vì chi phí trên mỗi đơn vị sản phẩm quá cao. Một lần gọi GPT-4o chỉ tốn một phần nhỏ của một cent. Nhưng 10.000 người dùng, mỗi người gọi mười lần mỗi ngày, sẽ tốn $250 chỉ riêng input token -- trước khi bạn thu được một đô la nào. Những công ty tồn tại là những công ty xem mỗi lần gọi API như một giao dịch tài chính, chứ không chỉ là một lần gọi hàm.

Loại bài: Build
Ngôn ngữ: Python
Cần biết trước: Phase 11 Bài 09 (Function Calling)
Thời gian: ~45 phút
Liên quan: Phase 11 · 15 (Prompt Caching) — bài này nói về caching ở tầng ứng dụng (semantic cache, exact hash cache, model routing). Bài 15 nói về prompt caching ở tầng nhà cung cấp (Anthropic cache_control, OpenAI tự động, Gemini CachedContent). Kết hợp cả hai để giảm 50-95% chi phí.

Mục tiêu bài học

  • Triển khai semantic caching để trả lời các truy vấn lặp lại hoặc tương tự từ cache thay vì gọi API lần nữa
  • Tính chi phí cho từng request trên các nhà cung cấp, đồng thời triển khai rate limiting theo token và cảnh báo ngân sách
  • Xây dựng một tầng tối ưu chi phí gồm prompt compression, model routing (model đắt và model rẻ), và response caching
  • Thiết kế chiến lược caching nhiều tầng, dùng exact match, semantic similarity và prefix caching cho các loại truy vấn khác nhau

Vấn đề

Bạn xây dựng một chatbot RAG. Nó hoạt động rất tốt. Người dùng thích nó.

Rồi hóa đơn tới.

GPT-5 có giá $1.25 cho mỗi triệu input token và $10 cho mỗi triệu output token. Claude Opus 4.7 có giá $5 cho input / $25 cho output. Gemini 3.1 Pro có giá $2 cho input / $12 cho output (với prompt tối đa 200K token). GPT-5-mini có giá $0.25/$2. GPT-4o, model dùng trong phép tính dưới đây, có giá $2.50/$10. Các mức giá này chỉ để minh họa; hãy luôn kiểm tra trang giá hiện tại của nhà cung cấp.

Đây là phép tính có thể giết chết startup:

  • 10.000 người dùng hoạt động mỗi ngày
  • 10 truy vấn cho mỗi người dùng mỗi ngày
  • 1.000 input token cho mỗi truy vấn (system prompt + context + tin nhắn của người dùng)
  • 500 output token cho mỗi câu trả lời

Chi phí input mỗi ngày: 10.000 x 10 x 1.000 / 1.000.000 x $2.50 = $250/ngày
Chi phí output mỗi ngày: 10.000 x 10 x 500 / 1.000.000 x $10.00 = $500/ngày
Tổng mỗi tháng: $22.500/tháng

Đó mới chỉ là LLM. Cộng thêm embedding, phí lưu trữ vector database và hạ tầng. Bạn sẽ phải trả khoảng $30.000/tháng cho một chatbot.

Điều nghiệt ngã là: 40-60% số truy vấn đó gần như trùng nhau. Người dùng hỏi cùng một câu bằng những cách diễn đạt hơi khác. System prompt của bạn -- giống hệt nhau ở mọi request -- vẫn bị tính phí mỗi lần. Các tài liệu context do RAG truy xuất cũng lặp lại giữa những người dùng hỏi cùng một chủ đề.

Bạn đang trả đủ tiền cho những phép tính dư thừa.

Khái niệm

Các khoản chi phí của một lần gọi LLM

Mỗi lần gọi API có năm khoản chi phí.

Sơ đồ

System prompt âm thầm ngốn tiền. Một system prompt dài 1.500 token được gửi trong mọi request tốn $3.75 cho mỗi triệu request chỉ riêng phần prefix đó. Với 100K request mỗi ngày, con số là $375/ngày -- $11.250/tháng -- cho đoạn văn bản không bao giờ thay đổi.

Provider Caching: Giảm giá có sẵn

Cả ba nhà cung cấp lớn đều có prompt caching ở phía nhà cung cấp vào năm 2026, nhưng cách hoạt động khác nhau. Xem Phase 11 · 15 để tìm hiểu kỹ hơn.

Nhà cung cấpCách hoạt độngMức giảm giáĐộ dài tối thiểuThời gian lưu cache
AnthropicĐánh dấu cache_control tường minh90% khi cache hit (trả thêm 25% khi ghi)1.024 token (Sonnet/Opus), 2.048 (Haiku)Mặc định 5 phút; có thể kéo dài đến 1 giờ (phí ghi gấp 2 lần)
OpenAITự động khớp prefix50% khi cache hit1.024 tokenTối đa 1 giờ, tùy khả năng đáp ứng
Google GeminiCachedContent API tường minhGiảm ~75% (cộng thêm phí lưu trữ)4.096 (Flash) / 32.768 (Pro)TTL do người dùng cấu hình

Cách của Anthropic là tường minh. Bạn đánh dấu các phần trong prompt bằng cache_control: {"type": "ephemeral"}. Request đầu tiên trả thêm 25% phí ghi. Các request tiếp theo có cùng prefix được giảm 90%. Một system prompt dài 2.000 token bình thường tốn $0.005 sẽ chỉ tốn $0.000625 khi cache hit. Trên 100K request, bạn tiết kiệm được $437.50/ngày.

Cách của OpenAI là tự động. Bất kỳ prompt prefix nào khớp với một request trước đó đều được giảm 50%. Không cần đánh dấu. Đổi lại, mức giảm ít hơn và bạn ít kiểm soát hơn, nhưng không tốn công triển khai.

Semantic Caching: Tầng riêng của bạn

Provider caching chỉ hoạt động với những prefix giống hệt nhau. Semantic caching xử lý trường hợp khó hơn: các truy vấn khác nhau nhưng cùng ý nghĩa.

"What is the return policy?" và "How do I return an item?" là hai chuỗi khác nhau nhưng cùng ý định. Semantic cache tạo embedding cho cả hai truy vấn, tính cosine similarity và trả về câu trả lời trong cache nếu độ tương đồng vượt ngưỡng (thường là 0.92-0.95).

Sơ đồ

Chi phí embedding không đáng kể. text-embedding-3-small của OpenAI có giá $0.02 cho mỗi triệu token. Kiểm tra cache gần như chẳng tốn gì so với một lần gọi LLM đầy đủ.

Exact Caching: Hash rồi đối chiếu

Với những lần gọi deterministic (temperature=0, cùng model, cùng prompt), exact caching đơn giản và nhanh hơn. Hash toàn bộ prompt, kiểm tra cache và trả về kết quả nếu tìm thấy.

Cách này rất hợp với:

  • System prompt + context cố định + truy vấn người dùng giống hệt nhau
  • Function calling với các định nghĩa tool giống hệt nhau
  • Batch processing khi cùng một tài liệu được xử lý nhiều lần

Rate Limiting: Bảo vệ ngân sách của bạn

Rate limiting không chỉ để đảm bảo công bằng. Nó còn giúp bạn sống sót.

Thuật toán token bucket: mỗi người dùng có một bucket chứa N token, được nạp lại với tốc độ R token mỗi giây. Một request tiêu thụ token trong bucket. Nếu bucket rỗng, request bị từ chối. Cách này cho phép gửi dồn request (dùng hết bucket cùng lúc), đồng thời vẫn giới hạn tốc độ trung bình.

Quota theo người dùng: đặt giới hạn token theo ngày/tháng cho từng tier người dùng.

TierGiới hạn token mỗi ngàyRequest tối đa/phútModel được dùng
Free50.00010Chỉ GPT-4o-mini
Pro500.00060GPT-4o, Claude Sonnet
Enterprise5.000.000300Tất cả model

Model Routing: Chọn đúng model cho đúng việc

Không phải truy vấn nào cũng cần GPT-4o.

"Cửa hàng đóng cửa lúc mấy giờ?" không cần một model có giá $10 cho mỗi triệu output token. GPT-4o-mini, với giá $0.60 cho mỗi triệu output token, xử lý được câu này rất tốt. Claude Haiku với giá $1.25 cho mỗi triệu output token cũng vậy. Một classifier đơn giản chuyển truy vấn dễ sang model rẻ và truy vấn phức tạp sang model đắt.

Sơ đồ

Một router được tinh chỉnh tốt có thể tiết kiệm 40-70% chỉ riêng chi phí model.

Cost Tracking: Biết tiền đi đâu

Bạn không thể tối ưu thứ mình không đo. Hãy log mọi lần gọi API cùng với:

  • Timestamp
  • Tên model
  • Số input token
  • Số output token
  • Latency (ms)
  • Chi phí tính được ($)
  • User ID
  • Cache hit/miss
  • Loại request

Dữ liệu này cho thấy tính năng nào tốn kém, người dùng nào tiêu thụ nhiều và caching tạo ra tác động lớn nhất ở đâu.

Batching: Giảm giá khi xử lý hàng loạt

Batch API của OpenAI xử lý request bất đồng bộ với mức giảm giá 50%. Bạn gửi một batch gồm tối đa 50.000 request và nhận kết quả trong vòng 24 giờ.

Dùng batching cho:

  • Xử lý tài liệu hằng đêm
  • Phân loại hàng loạt
  • Các lượt evaluation
  • Pipeline bổ sung dữ liệu

Đừng dùng cho: truy vấn phục vụ người dùng theo thời gian thực (latency rất quan trọng).

Cảnh báo ngân sách và Circuit Breaker

Circuit breaker ngừng chi tiêu khi bạn chạm giới hạn. Nếu thiếu nó, một bug hoặc hành vi lạm dụng có thể đốt sạch ngân sách cả tháng chỉ trong vài giờ.

Đặt ba ngưỡng:

  1. Cảnh báo (70% ngân sách): gửi cảnh báo
  2. Giới hạn (85% ngân sách): chỉ chuyển sang model rẻ hơn
  3. Dừng (95% ngân sách): từ chối request mới, chỉ trả về câu trả lời trong cache

Stack tối ưu chi phí

Áp dụng các kỹ thuật này theo thứ tự. Mỗi tầng bổ sung hiệu quả cho những tầng trước đó.

TầngKỹ thuậtMức tiết kiệm thường thấyCông sức triển khai
1Provider prompt caching30-50%Thấp (thêm dấu đánh dấu cache)
2Exact caching10-20%Thấp (hash + dict)
3Semantic caching15-30%Trung bình (embedding + similarity)
4Model routing40-70%Trung bình (classifier)
5Rate limitingBảo vệ ngân sáchThấp (token bucket)
6Prompt compression10-30%Trung bình (viết lại prompt)
7Batching50% với request phù hợpThấp (batch API)

Một ứng dụng RAG áp dụng các tầng 1-5 thường giảm chi phí từ $22.500/tháng xuống còn $4.000-6.000/tháng. Đó là khác biệt giữa đốt hết vốn dự phòng và xây dựng được một doanh nghiệp.

Tiết kiệm thực tế: Trước và sau

Đây là bảng chi tiết cho một chatbot RAG phục vụ 10.000 người dùng hoạt động mỗi ngày.

Chỉ sốTrước khi tối ưuSau khi tối ưuMức tiết kiệm
Chi phí LLM mỗi tháng$22.500$5.20077%
Chi phí trung bình mỗi truy vấn$0.0075$0.001777%
Tỷ lệ cache hit0%52%--
Truy vấn được chuyển sang mini0%65%--
P95 latency2.800ms900ms (cache hit: 50ms)68%
Chi phí embedding mỗi tháng$0$180(chi phí mới)
Tổng chi phí mỗi tháng$22.500$5.38076%

Chi phí embedding cho semantic caching ($180/tháng) được bù lại ngay trong giờ đầu tiên có cache hit.

Tự xây dựng

Bước 1: Công cụ tính chi phí

Xây dựng một công cụ tính chi phí token, có thông tin giá hiện tại của các model lớn.

python
import hashlib
import time
import json
import math
from dataclasses import dataclass, field


MODEL_PRICING = {
    "gpt-4o": {"input": 2.50, "output": 10.00, "cached_input": 1.25},
    "gpt-4o-mini": {"input": 0.15, "output": 0.60, "cached_input": 0.075},
    "gpt-4.1": {"input": 2.00, "output": 8.00, "cached_input": 0.50},
    "gpt-4.1-mini": {"input": 0.40, "output": 1.60, "cached_input": 0.10},
    "gpt-4.1-nano": {"input": 0.10, "output": 0.40, "cached_input": 0.025},
    "o3": {"input": 2.00, "output": 8.00, "cached_input": 0.50},
    "o3-mini": {"input": 1.10, "output": 4.40, "cached_input": 0.55},
    "o4-mini": {"input": 1.10, "output": 4.40, "cached_input": 0.275},
    "claude-opus-4": {"input": 15.00, "output": 75.00, "cached_input": 1.50},
    "claude-sonnet-4": {"input": 3.00, "output": 15.00, "cached_input": 0.30},
    "claude-haiku-3.5": {"input": 0.80, "output": 4.00, "cached_input": 0.08},
    "gemini-2.5-pro": {"input": 1.25, "output": 10.00, "cached_input": 0.3125},
    "gemini-2.5-flash": {"input": 0.15, "output": 0.60, "cached_input": 0.0375},
}


def calculate_cost(model, input_tokens, output_tokens, cached_input_tokens=0):
    if model not in MODEL_PRICING:
        return {"error": f"Unknown model: {model}"}
    pricing = MODEL_PRICING[model]
    non_cached = input_tokens - cached_input_tokens
    input_cost = (non_cached / 1_000_000) * pricing["input"]
    cached_cost = (cached_input_tokens / 1_000_000) * pricing["cached_input"]
    output_cost = (output_tokens / 1_000_000) * pricing["output"]
    total = input_cost + cached_cost + output_cost
    return {
        "model": model,
        "input_tokens": input_tokens,
        "output_tokens": output_tokens,
        "cached_input_tokens": cached_input_tokens,
        "input_cost": round(input_cost, 6),
        "cached_input_cost": round(cached_cost, 6),
        "output_cost": round(output_cost, 6),
        "total_cost": round(total, 6),
    }

Bước 2: Exact Cache

Hash toàn bộ prompt và trả về câu trả lời trong cache cho những request giống hệt nhau.

python
class ExactCache:
    def __init__(self, max_size=1000, ttl_seconds=3600):
        self.cache = {}
        self.max_size = max_size
        self.ttl = ttl_seconds
        self.hits = 0
        self.misses = 0

    def _hash(self, model, messages, temperature):
        key_data = json.dumps({"model": model, "messages": messages, "temperature": temperature}, sort_keys=True)
        return hashlib.sha256(key_data.encode()).hexdigest()

    def get(self, model, messages, temperature=0.0):
        if temperature > 0:
            self.misses += 1
            return None
        key = self._hash(model, messages, temperature)
        if key in self.cache:
            entry = self.cache[key]
            if time.time() - entry["timestamp"] < self.ttl:
                self.hits += 1
                entry["access_count"] += 1
                return entry["response"]
            del self.cache[key]
        self.misses += 1
        return None

    def put(self, model, messages, temperature, response):
        if temperature > 0:
            return
        if len(self.cache) >= self.max_size:
            oldest_key = min(self.cache, key=lambda k: self.cache[k]["timestamp"])
            del self.cache[oldest_key]
        key = self._hash(model, messages, temperature)
        self.cache[key] = {
            "response": response,
            "timestamp": time.time(),
            "access_count": 1,
        }

    def stats(self):
        total = self.hits + self.misses
        return {
            "hits": self.hits,
            "misses": self.misses,
            "hit_rate": round(self.hits / total, 4) if total > 0 else 0,
            "cache_size": len(self.cache),
        }

Bước 3: Semantic Cache

Tạo embedding cho truy vấn và trả về câu trả lời trong cache khi độ tương đồng vượt ngưỡng.

python
def simple_embed(text):
    words = text.lower().split()
    vocab = {}
    for w in words:
        vocab[w] = vocab.get(w, 0) + 1
    norm = math.sqrt(sum(v * v for v in vocab.values()))
    if norm == 0:
        return {}
    return {k: v / norm for k, v in vocab.items()}


def cosine_similarity(a, b):
    if not a or not b:
        return 0.0
    all_keys = set(a) | set(b)
    dot = sum(a.get(k, 0) * b.get(k, 0) for k in all_keys)
    return dot


class SemanticCache:
    def __init__(self, similarity_threshold=0.85, max_size=500, ttl_seconds=3600):
        self.entries = []
        self.threshold = similarity_threshold
        self.max_size = max_size
        self.ttl = ttl_seconds
        self.hits = 0
        self.misses = 0

    def get(self, query):
        query_embedding = simple_embed(query)
        now = time.time()
        best_match = None
        best_sim = 0.0
        for entry in self.entries:
            if now - entry["timestamp"] > self.ttl:
                continue
            sim = cosine_similarity(query_embedding, entry["embedding"])
            if sim > best_sim:
                best_sim = sim
                best_match = entry
        if best_match and best_sim >= self.threshold:
            self.hits += 1
            best_match["access_count"] += 1
            return {"response": best_match["response"], "similarity": round(best_sim, 4), "original_query": best_match["query"]}
        self.misses += 1
        return None

    def put(self, query, response):
        if len(self.entries) >= self.max_size:
            self.entries.sort(key=lambda e: e["timestamp"])
            self.entries.pop(0)
        self.entries.append({
            "query": query,
            "embedding": simple_embed(query),
            "response": response,
            "timestamp": time.time(),
            "access_count": 1,
        })

    def stats(self):
        total = self.hits + self.misses
        return {
            "hits": self.hits,
            "misses": self.misses,
            "hit_rate": round(self.hits / total, 4) if total > 0 else 0,
            "cache_size": len(self.entries),
        }

Bước 4: Rate Limiter

Rate limiter dùng token bucket với quota theo người dùng.

python
class TokenBucketRateLimiter:
    def __init__(self):
        self.buckets = {}
        self.tiers = {
            "free": {"capacity": 50_000, "refill_rate": 500, "max_requests_per_min": 10},
            "pro": {"capacity": 500_000, "refill_rate": 5_000, "max_requests_per_min": 60},
            "enterprise": {"capacity": 5_000_000, "refill_rate": 50_000, "max_requests_per_min": 300},
        }

    def _get_bucket(self, user_id, tier="free"):
        if user_id not in self.buckets:
            tier_config = self.tiers.get(tier, self.tiers["free"])
            self.buckets[user_id] = {
                "tokens": tier_config["capacity"],
                "capacity": tier_config["capacity"],
                "refill_rate": tier_config["refill_rate"],
                "last_refill": time.time(),
                "request_timestamps": [],
                "max_rpm": tier_config["max_requests_per_min"],
                "tier": tier,
                "total_tokens_used": 0,
            }
        return self.buckets[user_id]

    def _refill(self, bucket):
        now = time.time()
        elapsed = now - bucket["last_refill"]
        refill = int(elapsed * bucket["refill_rate"])
        if refill > 0:
            bucket["tokens"] = min(bucket["capacity"], bucket["tokens"] + refill)
            bucket["last_refill"] = now

    def check(self, user_id, tokens_needed, tier="free"):
        bucket = self._get_bucket(user_id, tier)
        self._refill(bucket)
        now = time.time()
        bucket["request_timestamps"] = [t for t in bucket["request_timestamps"] if now - t < 60]
        if len(bucket["request_timestamps"]) >= bucket["max_rpm"]:
            return {"allowed": False, "reason": "rate_limit", "retry_after_seconds": 60 - (now - bucket["request_timestamps"][0])}
        if bucket["tokens"] < tokens_needed:
            deficit = tokens_needed - bucket["tokens"]
            wait = deficit / bucket["refill_rate"]
            return {"allowed": False, "reason": "token_limit", "tokens_available": bucket["tokens"], "retry_after_seconds": round(wait, 1)}
        return {"allowed": True, "tokens_available": bucket["tokens"]}

    def consume(self, user_id, tokens_used, tier="free"):
        bucket = self._get_bucket(user_id, tier)
        bucket["tokens"] -= tokens_used
        bucket["request_timestamps"].append(time.time())
        bucket["total_tokens_used"] += tokens_used

    def get_usage(self, user_id):
        if user_id not in self.buckets:
            return {"error": "User not found"}
        b = self.buckets[user_id]
        return {
            "user_id": user_id,
            "tier": b["tier"],
            "tokens_remaining": b["tokens"],
            "capacity": b["capacity"],
            "total_tokens_used": b["total_tokens_used"],
            "utilization": round(b["total_tokens_used"] / b["capacity"], 4) if b["capacity"] else 0,
        }

Bước 5: Cost Tracker

Log mọi lần gọi và tính tổng chi phí liên tục.

python
class CostTracker:
    def __init__(self, monthly_budget=1000.0):
        self.logs = []
        self.monthly_budget = monthly_budget
        self.alerts = []

    def log_call(self, model, input_tokens, output_tokens, cached_input_tokens=0, latency_ms=0, user_id="anonymous", cache_status="miss"):
        cost = calculate_cost(model, input_tokens, output_tokens, cached_input_tokens)
        entry = {
            "timestamp": time.time(),
            "model": model,
            "input_tokens": input_tokens,
            "output_tokens": output_tokens,
            "cached_input_tokens": cached_input_tokens,
            "latency_ms": latency_ms,
            "cost": cost["total_cost"],
            "user_id": user_id,
            "cache_status": cache_status,
        }
        self.logs.append(entry)
        self._check_budget()
        return entry

    def _check_budget(self):
        total = self.total_cost()
        pct = total / self.monthly_budget if self.monthly_budget > 0 else 0
        if pct >= 0.95 and not any(a["level"] == "stop" for a in self.alerts):
            self.alerts.append({"level": "stop", "message": f"Budget 95% consumed: ${total:.2f}/${self.monthly_budget:.2f}", "timestamp": time.time()})
        elif pct >= 0.85 and not any(a["level"] == "throttle" for a in self.alerts):
            self.alerts.append({"level": "throttle", "message": f"Budget 85% consumed: ${total:.2f}/${self.monthly_budget:.2f}", "timestamp": time.time()})
        elif pct >= 0.70 and not any(a["level"] == "warning" for a in self.alerts):
            self.alerts.append({"level": "warning", "message": f"Budget 70% consumed: ${total:.2f}/${self.monthly_budget:.2f}", "timestamp": time.time()})

    def total_cost(self):
        return round(sum(e["cost"] for e in self.logs), 6)

    def cost_by_model(self):
        by_model = {}
        for e in self.logs:
            m = e["model"]
            if m not in by_model:
                by_model[m] = {"calls": 0, "cost": 0, "input_tokens": 0, "output_tokens": 0}
            by_model[m]["calls"] += 1
            by_model[m]["cost"] = round(by_model[m]["cost"] + e["cost"], 6)
            by_model[m]["input_tokens"] += e["input_tokens"]
            by_model[m]["output_tokens"] += e["output_tokens"]
        return by_model

    def cache_savings(self):
        cache_hits = [e for e in self.logs if e["cache_status"] == "hit"]
        if not cache_hits:
            return {"saved": 0, "cache_hits": 0}
        saved = 0
        for e in cache_hits:
            full_cost = calculate_cost(e["model"], e["input_tokens"], e["output_tokens"])
            saved += full_cost["total_cost"]
        return {"saved": round(saved, 4), "cache_hits": len(cache_hits)}

    def summary(self):
        if not self.logs:
            return {"total_calls": 0, "total_cost": 0}
        total_latency = sum(e["latency_ms"] for e in self.logs)
        cache_hits = sum(1 for e in self.logs if e["cache_status"] == "hit")
        return {
            "total_calls": len(self.logs),
            "total_cost": self.total_cost(),
            "avg_cost_per_call": round(self.total_cost() / len(self.logs), 6),
            "avg_latency_ms": round(total_latency / len(self.logs), 1),
            "cache_hit_rate": round(cache_hits / len(self.logs), 4),
            "cost_by_model": self.cost_by_model(),
            "cache_savings": self.cache_savings(),
            "budget_remaining": round(self.monthly_budget - self.total_cost(), 2),
            "budget_utilization": round(self.total_cost() / self.monthly_budget, 4) if self.monthly_budget > 0 else 0,
            "alerts": self.alerts,
        }

Bước 6: Model Router

Chuyển truy vấn đến model rẻ nhất có thể xử lý được.

python
SIMPLE_KEYWORDS = ["what time", "hours", "address", "phone", "price", "return policy", "hello", "hi", "thanks", "yes", "no"]
COMPLEX_KEYWORDS = ["analyze", "compare", "explain why", "write code", "debug", "architect", "design", "trade-off", "evaluate"]


def classify_complexity(query):
    q = query.lower()
    if len(q.split()) <= 5 or any(kw in q for kw in SIMPLE_KEYWORDS):
        return "simple"
    if any(kw in q for kw in COMPLEX_KEYWORDS):
        return "complex"
    return "medium"


def route_model(query, tier="pro"):
    complexity = classify_complexity(query)
    routing_table = {
        "simple": {"free": "gpt-4.1-nano", "pro": "gpt-4o-mini", "enterprise": "gpt-4o-mini"},
        "medium": {"free": "gpt-4o-mini", "pro": "claude-sonnet-4", "enterprise": "claude-sonnet-4"},
        "complex": {"free": "gpt-4o-mini", "pro": "gpt-4o", "enterprise": "claude-opus-4"},
    }
    model = routing_table[complexity].get(tier, "gpt-4o-mini")
    return {"query": query, "complexity": complexity, "model": model, "tier": tier}

Bước 7: Chạy bản demo

python
def simulate_llm_call(model, query):
    input_tokens = len(query.split()) * 4 + 500
    output_tokens = 150 + (len(query.split()) * 2)
    latency = 200 + (output_tokens * 2)
    return {
        "model": model,
        "response": f"[Simulated {model} response to: {query[:50]}...]",
        "input_tokens": input_tokens,
        "output_tokens": output_tokens,
        "latency_ms": latency,
    }


def run_demo():
    print("=" * 60)
    print("  Caching, Rate Limiting & Cost Optimization Demo")
    print("=" * 60)

    print("\n--- Model Pricing ---")
    for model, pricing in list(MODEL_PRICING.items())[:6]:
        cost_1k = calculate_cost(model, 1000, 500)
        print(f"  {model}: ${cost_1k['total_cost']:.6f} per 1K in + 500 out")

    print("\n--- Cost Comparison: 100K Requests ---")
    for model in ["gpt-4o", "gpt-4o-mini", "claude-sonnet-4", "claude-haiku-3.5"]:
        cost = calculate_cost(model, 1000 * 100_000, 500 * 100_000)
        print(f"  {model}: ${cost['total_cost']:.2f}")

    print("\n--- Anthropic Cache Savings ---")
    no_cache = calculate_cost("claude-sonnet-4", 2000, 500, 0)
    with_cache = calculate_cost("claude-sonnet-4", 2000, 500, 1500)
    saving = no_cache["total_cost"] - with_cache["total_cost"]
    print(f"  Without cache: ${no_cache['total_cost']:.6f}")
    print(f"  With 1500 cached tokens: ${with_cache['total_cost']:.6f}")
    print(f"  Savings per call: ${saving:.6f} ({saving/no_cache['total_cost']*100:.1f}%)")

    exact_cache = ExactCache(max_size=100, ttl_seconds=300)
    semantic_cache = SemanticCache(similarity_threshold=0.75, max_size=100)
    rate_limiter = TokenBucketRateLimiter()
    tracker = CostTracker(monthly_budget=100.0)

    print("\n--- Exact Cache ---")
    messages_1 = [{"role": "user", "content": "What is the return policy?"}]
    result = exact_cache.get("gpt-4o-mini", messages_1, 0.0)
    print(f"  First lookup: {'HIT' if result else 'MISS'}")
    exact_cache.put("gpt-4o-mini", messages_1, 0.0, "You can return items within 30 days.")
    result = exact_cache.get("gpt-4o-mini", messages_1, 0.0)
    print(f"  Second lookup: {'HIT' if result else 'MISS'} -> {result}")
    result = exact_cache.get("gpt-4o-mini", messages_1, 0.7)
    print(f"  With temp=0.7: {'HIT' if result else 'MISS (non-deterministic, skip cache)'}")
    print(f"  Stats: {exact_cache.stats()}")

    print("\n--- Semantic Cache ---")
    test_queries = [
        ("What is the return policy?", "Items can be returned within 30 days with receipt."),
        ("How do I return an item?", None),
        ("What are your store hours?", "We are open 9am-9pm Monday through Saturday."),
        ("When does the store open?", None),
        ("Tell me about quantum computing", "Quantum computers use qubits..."),
        ("Explain quantum mechanics", None),
    ]
    for query, response in test_queries:
        cached = semantic_cache.get(query)
        if cached:
            print(f"  '{query[:40]}' -> CACHE HIT (sim={cached['similarity']}, original='{cached['original_query'][:40]}')")
        elif response:
            semantic_cache.put(query, response)
            print(f"  '{query[:40]}' -> MISS (stored)")
        else:
            print(f"  '{query[:40]}' -> MISS (no match)")
    print(f"  Stats: {semantic_cache.stats()}")

    print("\n--- Rate Limiting ---")
    for i in range(12):
        check = rate_limiter.check("user_1", 1000, "free")
        if check["allowed"]:
            rate_limiter.consume("user_1", 1000, "free")
        status = "OK" if check["allowed"] else f"BLOCKED ({check['reason']})"
        if i < 5 or not check["allowed"]:
            print(f"  Request {i+1}: {status}")
    print(f"  Usage: {rate_limiter.get_usage('user_1')}")

    print("\n--- Model Routing ---")
    routing_queries = [
        "What time do you close?",
        "Summarize this quarterly earnings report",
        "Analyze the trade-offs between microservices and monoliths",
        "Hello",
        "Write code for a binary search tree with deletion",
    ]
    for q in routing_queries:
        route = route_model(q, "pro")
        print(f"  '{q[:50]}' -> {route['model']} ({route['complexity']})")

    print("\n--- Full Pipeline: Before vs After Optimization ---")
    queries = [
        "What is the return policy?",
        "How do I return something?",
        "What are your hours?",
        "When do you open?",
        "Explain the difference between TCP and UDP",
        "Compare TCP vs UDP protocols",
        "Hello",
        "What is your phone number?",
        "Write a Python function to sort a list",
        "Analyze the pros and cons of serverless architecture",
    ]

    print("\n  [Before: no caching, single model (gpt-4o)]")
    tracker_before = CostTracker(monthly_budget=1000.0)
    for q in queries:
        result = simulate_llm_call("gpt-4o", q)
        tracker_before.log_call("gpt-4o", result["input_tokens"], result["output_tokens"], latency_ms=result["latency_ms"], cache_status="miss")
    before = tracker_before.summary()
    print(f"  Total cost: ${before['total_cost']:.6f}")
    print(f"  Avg cost/call: ${before['avg_cost_per_call']:.6f}")
    print(f"  Avg latency: {before['avg_latency_ms']}ms")

    print("\n  [After: caching + routing + rate limiting]")
    exact_c = ExactCache()
    semantic_c = SemanticCache(similarity_threshold=0.75)
    tracker_after = CostTracker(monthly_budget=1000.0)

    for q in queries:
        messages = [{"role": "user", "content": q}]
        cached = exact_c.get("gpt-4o", messages, 0.0)
        if cached:
            tracker_after.log_call("gpt-4o-mini", 0, 0, latency_ms=5, cache_status="hit")
            continue
        sem_cached = semantic_c.get(q)
        if sem_cached:
            tracker_after.log_call("gpt-4o-mini", 0, 0, latency_ms=15, cache_status="hit")
            continue
        route = route_model(q)
        result = simulate_llm_call(route["model"], q)
        tracker_after.log_call(route["model"], result["input_tokens"], result["output_tokens"], latency_ms=result["latency_ms"], cache_status="miss")
        exact_c.put(route["model"], messages, 0.0, result["response"])
        semantic_c.put(q, result["response"])

    after = tracker_after.summary()
    print(f"  Total cost: ${after['total_cost']:.6f}")
    print(f"  Avg cost/call: ${after['avg_cost_per_call']:.6f}")
    print(f"  Avg latency: {after['avg_latency_ms']}ms")
    print(f"  Cache hit rate: {after['cache_hit_rate']:.0%}")

    if before["total_cost"] > 0:
        savings_pct = (1 - after["total_cost"] / before["total_cost"]) * 100
        print(f"\n  SAVINGS: {savings_pct:.1f}% cost reduction")
        print(f"  Latency improvement: {(1 - after['avg_latency_ms'] / before['avg_latency_ms']) * 100:.1f}% faster")

    print("\n--- Budget Alerts Demo ---")
    alert_tracker = CostTracker(monthly_budget=0.01)
    for i in range(5):
        alert_tracker.log_call("gpt-4o", 5000, 2000, latency_ms=500)
    print(f"  Total spent: ${alert_tracker.total_cost():.6f} / ${alert_tracker.monthly_budget}")
    for alert in alert_tracker.alerts:
        print(f"  ALERT [{alert['level'].upper()}]: {alert['message']}")

    print("\n--- Cost Breakdown by Model ---")
    multi_tracker = CostTracker(monthly_budget=500.0)
    for _ in range(50):
        multi_tracker.log_call("gpt-4o-mini", 800, 200, latency_ms=150)
    for _ in range(30):
        multi_tracker.log_call("claude-sonnet-4", 1500, 500, latency_ms=400)
    for _ in range(10):
        multi_tracker.log_call("gpt-4o", 2000, 800, latency_ms=600)
    for _ in range(10):
        multi_tracker.log_call("claude-opus-4", 3000, 1000, latency_ms=1200)
    breakdown = multi_tracker.cost_by_model()
    for model, data in sorted(breakdown.items(), key=lambda x: x[1]["cost"], reverse=True):
        print(f"  {model}: {data['calls']} calls, ${data['cost']:.6f}, {data['input_tokens']:,} in / {data['output_tokens']:,} out")
    print(f"  Total: ${multi_tracker.total_cost():.6f}")

    print("\n" + "=" * 60)
    print("  Demo complete.")
    print("=" * 60)


if __name__ == "__main__":
    run_demo()

Dùng thực tế

Anthropic Prompt Caching

python
# import anthropic
#
# client = anthropic.Anthropic()
#
# response = client.messages.create(
#     model="claude-sonnet-5",
#     max_tokens=1024,
#     system=[
#         {
#             "type": "text",
#             "text": "You are a helpful customer support agent for Acme Corp...",
#             "cache_control": {"type": "ephemeral"},
#         }
#     ],
#     messages=[{"role": "user", "content": "What is the return policy?"}],
# )
#
# print(f"Input tokens: {response.usage.input_tokens}")
# print(f"Cache creation tokens: {response.usage.cache_creation_input_tokens}")
# print(f"Cache read tokens: {response.usage.cache_read_input_tokens}")

Lần gọi đầu tiên ghi vào cache (phí cao hơn 25%). Mọi lần gọi tiếp theo có cùng system prompt prefix đều đọc từ cache (giảm giá 90%). Cache tồn tại trong 5 phút và thời gian này được tính lại sau mỗi lần cache hit.

OpenAI Automatic Caching

python
# from openai import OpenAI
#
# client = OpenAI()
#
# response = client.chat.completions.create(
#     model="gpt-4o",
#     messages=[
#         {"role": "system", "content": "You are a helpful customer support agent..."},
#         {"role": "user", "content": "What is the return policy?"},
#     ],
# )
#
# print(f"Prompt tokens: {response.usage.prompt_tokens}")
# print(f"Cached tokens: {response.usage.prompt_tokens_details.cached_tokens}")
# print(f"Completion tokens: {response.usage.completion_tokens}")

OpenAI tự động caching. Bất kỳ prompt prefix dài từ 1.024 token trở lên khớp với một request gần đây đều được giảm giá 50%. Không cần sửa code -- chỉ cần kiểm tra prompt_tokens_details.cached_tokens trong response để xác nhận nó đang hoạt động.

OpenAI Batch API

python
# import json
# from openai import OpenAI
#
# client = OpenAI()
#
# requests = []
# for i, query in enumerate(queries):
#     requests.append({
#         "custom_id": f"request-{i}",
#         "method": "POST",
#         "url": "/v1/chat/completions",
#         "body": {
#             "model": "gpt-4o-mini",
#             "messages": [{"role": "user", "content": query}],
#         },
#     })
#
# with open("batch_input.jsonl", "w") as f:
#     for r in requests:
#         f.write(json.dumps(r) + "\n")
#
# batch_file = client.files.create(file=open("batch_input.jsonl", "rb"), purpose="batch")
# batch = client.batches.create(input_file_id=batch_file.id, endpoint="/v1/chat/completions", completion_window="24h")
# print(f"Batch ID: {batch.id}, Status: {batch.status}")

Batch API giảm giá cố định 50% cho mọi token. Kết quả có trong vòng 24 giờ. Rất hợp với các tác vụ không cần xử lý theo thời gian thực: evaluation, gán nhãn dữ liệu, tóm tắt hàng loạt.

Production Semantic Cache với Redis

python
# import redis
# import numpy as np
# from openai import OpenAI
#
# r = redis.Redis()
# client = OpenAI()
#
# def get_embedding(text):
#     response = client.embeddings.create(model="text-embedding-3-small", input=text)
#     return response.data[0].embedding
#
# def semantic_cache_lookup(query, threshold=0.95):
#     query_emb = np.array(get_embedding(query))
#     keys = r.keys("cache:emb:*")
#     best_sim, best_key = 0, None
#     for key in keys:
#         stored_emb = np.frombuffer(r.get(key), dtype=np.float32)
#         sim = np.dot(query_emb, stored_emb) / (np.linalg.norm(query_emb) * np.linalg.norm(stored_emb))
#         if sim > best_sim:
#             best_sim, best_key = sim, key
#     if best_sim >= threshold and best_key:
#         response_key = best_key.decode().replace("cache:emb:", "cache:resp:")
#         return r.get(response_key).decode()
#     return None

Trong production, hãy thay cách quét tuần tự bằng một vector index (Redis Vector Search, Pinecone hoặc pgvector). Quét tuần tự phù hợp khi có dưới 1.000 mục. Khi vượt mức đó, dùng ANN (approximate nearest neighbor) để tra cứu với độ phức tạp O(log⁡n)O(\log n).

Đưa vào sản phẩm

Bài này tạo ra outputs/prompt-cost-optimizer.md -- một prompt có thể tái sử dụng để phân tích ứng dụng LLM của bạn và đề xuất những cách tối ưu chi phí cụ thể cùng mức tiết kiệm dự kiến.

Bài này cũng tạo ra outputs/skill-cost-patterns.md -- một khung ra quyết định để chọn chiến lược caching, cấu hình rate limiting và quy tắc model routing phù hợp với trường hợp của bạn.

Bài tập

  1. Triển khai LRU eviction cho semantic cache. Thay cách loại bỏ mục cũ nhất bằng cách loại bỏ mục ít được dùng gần đây nhất. Theo dõi thời điểm truy cập cuối của từng mục và loại bỏ mục có thời điểm truy cập xa nhất khi cache đầy. So sánh tỷ lệ cache hit giữa hai chiến lược trên 100 truy vấn.
  2. Xây dựng công cụ dự báo chi phí. Từ log các lần gọi API (log của CostTracker), dự báo chi phí mỗi tháng dựa trên mức trung bình của 7 ngày gần nhất. Tính đến sự khác biệt giữa ngày trong tuần và cuối tuần. Gửi cảnh báo nếu chi phí dự báo cho tháng vượt ngân sách hơn 20%.
  3. Triển khai semantic caching nhiều tầng. Dùng hai ngưỡng similarity: 0.98 cho cache hit có độ tin cậy cao (trả về ngay) và 0.90 cho cache hit có độ tin cậy trung bình (trả về kèm lời lưu ý: "Dựa trên một câu hỏi tương tự trước đây..."). Theo dõi mỗi cache hit đến từ tầng nào và đo sự khác biệt về mức độ hài lòng của người dùng.
  4. Xây dựng classifier cho model routing. Thay classifier dựa trên keyword bằng classifier dựa trên embedding. Tạo embedding cho 50 truy vấn đã gán nhãn (đơn giản/trung bình/phức tạp), rồi phân loại truy vấn mới bằng cách tìm ví dụ đã gán nhãn gần nhất. Đo độ chính xác phân loại trên một test set gồm 20 truy vấn.
  5. Triển khai circuit breaker với nhiều mức giảm chất lượng dịch vụ. Khi dùng hết 70% ngân sách, log cảnh báo. Ở mức 85%, tự động chuyển toàn bộ routing sang model rẻ nhất (gpt-4o-mini). Ở mức 95%, chỉ phục vụ câu trả lời trong cache và từ chối truy vấn mới. Kiểm tra bằng cách mô phỏng 1.000 request với ngân sách $1.00 và xác nhận từng ngưỡng được kích hoạt đúng.

Thuật ngữ chính

Thuật ngữNgười ta hay nóiNghĩa thật sự
Prompt caching"Cache system prompt"Caching ở tầng nhà cung cấp, trong đó những prompt prefix lặp lại được giảm giá (Anthropic 90%, OpenAI 50%) -- OpenAI không cần sửa code, Anthropic cần đánh dấu tường minh
Semantic caching"Caching thông minh"Tạo embedding cho truy vấn, tính độ tương đồng với các truy vấn trước và trả về câu trả lời trong cache nếu độ tương đồng vượt ngưỡng -- bắt được những cách diễn đạt lại mà exact matching bỏ sót
Exact caching"Hash caching"Hash toàn bộ prompt (model + messages + temperature) và trả về câu trả lời trong cache cho input giống hệt nhau -- chỉ hoạt động với những lần gọi deterministic có temperature=0
Token bucket"Rate limiter"Một thuật toán trong đó mỗi người dùng có một bucket chứa N token, được nạp lại với tốc độ R token mỗi giây -- cho phép gửi dồn tối đa N token nhưng vẫn giữ tốc độ trung bình là R
Model routing"Routing kiểu tiết kiệm"Dùng classifier để gửi truy vấn đơn giản đến model rẻ (GPT-4o-mini, Haiku) và truy vấn phức tạp đến model đắt (GPT-4o, Opus) -- tiết kiệm 40-70% chi phí model
Cost tracking"Đo mức sử dụng"Log mọi lần gọi API cùng với model, số token, latency, chi phí và user ID để bạn biết chính xác tiền đi đâu và tính năng nào tốn kém
Circuit breaker"Công tắc ngắt"Tự động giảm chất lượng dịch vụ (dùng model rẻ hơn, chỉ dùng cache) hoặc dừng hẳn request khi chi tiêu tiến gần giới hạn ngân sách
Batch API"Giảm giá khi xử lý hàng loạt"Cách xử lý bất đồng bộ của OpenAI với mức giảm giá 50% -- gửi tối đa 50.000 request và nhận kết quả trong vòng 24 giờ
Prompt compression"Ăn kiêng token"Viết lại system prompt và context để dùng ít token hơn mà vẫn giữ nguyên ý nghĩa -- prompt ngắn hơn tốn ít tiền hơn và thường cho kết quả tốt hơn
Cache hit rate"Hiệu quả cache"Tỷ lệ phần trăm request được phục vụ từ cache thay vì gọi LLM -- mức 40-60% thường gặp ở chatbot production và giúp tiết kiệm chi phí tương ứng

Đọc thêm