Là một kỹ sư đã triển khai hàng chục hệ thống AI production trong 5 năm qua, tôi đã chứng kiến vô số teams đối mặt với cùng một vấn đề: model đưa ra dự đoán nhưng không biết độ tin cậy của dự đoán đó. Bài viết này sẽ chia sẻ kinh nghiệm thực chiến của tôi, bắt đầu từ một case study điển hình mà tôi đã tư vấn gần đây.

Case Study: Startup AI Tại TP.HCM Giải Quyết Bài Toán Uncertainty

Một startup AI ở TP.HCM chuyên cung cấp dịch vụ credit scoring cho các nền tảng tài chính đã gặp nghiêm trọng vấn đề khi model của họ đưa ra xác suất duyệt tín dụng 85% nhưng thực tế chỉ đúng 60%. Khách hàng doanh nghiệp mất niềm tin, team phải thường xuyên can thiệp thủ công, và chi phí vận hành tăng 300% chỉ trong 3 tháng.

Sau khi đánh giá, tôi phát hiện nguyên nhân gốc: model hoàn toàn không được calibrate. Họ sử dụng raw output của model như confidence score mà không hiểu rằng output đó chỉ phản ánh likelihood theo training distribution, không phải true probability.

Đội ngũ đã quyết định Đăng ký tại đây với HolySheep AI để tận dụng infrastructure có độ trễ thấp và chi phí tiết kiệm 85% so với giải pháp cũ. Sau 30 ngày triển khai, kết quả nói lên tất cả: độ trễ trung bình giảm từ 420ms xuống 180ms, và hóa đơn hàng tháng giảm từ $4,200 xuống $680.

Model Calibration Là Gì Và Tại Sao Nó Quan Trọng?

Model calibration là quá trình điều chỉnh output của model để xác suất dự đoán phản ánh đúng tần suất xảy ra thực tế. Nếu model calibrated hoàn hảo, khi nó dự đoán xác suất 80% cho 100 trường hợp, đúng 80 trường hợp sẽ xảy ra.

Expected Calibration Error (ECE)

ECE là metric chuẩn để đo độ calibration của model:

import numpy as np
from sklearn.metrics import accuracy_score

def expected_calibration_error(y_true, y_prob, n_bins=10):
    """
    Tính Expected Calibration Error (ECE)
    
    Args:
        y_true: Ground truth labels (0 hoặc 1)
        y_prob: Predicted probabilities
        n_bins: Số lượng bins để phân nhóm
    
    Returns:
        ECE score (càng thấp càng tốt)
    """
    bin_edges = np.linspace(0, 1, n_bins + 1)
    ece = 0.0
    
    for i in range(n_bins):
        # Lấy samples trong bin i
        bin_lower = bin_edges[i]
        bin_upper = bin_edges[i + 1]
        
        if i == n_bins - 1:
            in_bin = (y_prob >= bin_lower) & (y_prob <= bin_upper)
        else:
            in_bin = (y_prob >= bin_lower) & (y_prob < bin_upper)
        
        bin_count = np.sum(in_bin)
        
        if bin_count > 0:
            # Accuracy trong bin
            bin_accuracy = accuracy_score(y_true[in_bin], (y_prob[in_bin] >= 0.5).astype(int))
            # Confidence trung bình trong bin
            bin_confidence = np.mean(y_prob[in_bin])
            # Trọng số của bin
            weight = bin_count / len(y_prob)
            
            ece += weight * np.abs(bin_accuracy - bin_confidence)
    
    return ece

Ví dụ sử dụng

y_true = np.array([1, 1, 0, 0, 1, 0, 1, 0, 1, 1]) y_prob = np.array([0.9, 0.85, 0.2, 0.15, 0.8, 0.3, 0.75, 0.25, 0.7, 0.65]) ece_score = expected_calibration_error(y_true, y_prob, n_bins=5) print(f"ECE Score: {ece_score:.4f}") # Giá trị càng gần 0 càng tốt

Platt Scaling: Phương Pháp Calibration Cổ Điển

Platt Scaling (hay còn gọi là Logistic Regression Calibration) là phương pháp đơn giản nhất nhưng hiệu quả cao. Nó fit một logistic regression model lên raw model outputs.

import requests
import json

class HolySheepCalibratedModel:
    """
    Sử dụng HolySheep AI API cho inference với calibration layer
    """
    
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.holysheep.ai/v1"
        self.calibration_params = None
    
    def train_platt_scaling(self, train_probs, train_labels, model_name="gpt-4.1"):
        """
        Train Platt Scaling parameters sử dụng HolySheep API
        
        Args:
            train_probs: Raw probabilities từ model
            train_labels: True labels
            model_name: Model sử dụng (gpt-4.1, claude-sonnet-4.5, deepseek-v3.2)
        """
        # Tính Platt Scaling parameters
        from sklearn.linear_model import LogisticRegression
        
        # Reshape để fit logistic regression
        X = train_probs.reshape(-1, 1)
        y = train_labels
        
        lr = LogisticRegression()
        lr.fit(X, y)
        
        self.calibration_params = {
            'a': lr.coef_[0][0],
            'b': lr.intercept_[0]
        }
        
        return self.calibration_params
    
    def calibrate_probability(self, raw_prob):
        """
        Apply Platt Scaling calibration
        P_calibrated = 1 / (1 + exp(a * logit(raw_prob) + b))
        """
        import math
        
        if self.calibration_params is None:
            raise ValueError("Chưa train calibration parameters")
        
        a = self.calibration_params['a']
        b = self.calibration_params['b']
        
        # Tránh log(0)
        raw_prob = max(min(raw_prob, 0.9999), 0.0001)
        
        # Tính calibrated probability
        logit = math.log(raw_prob / (1 - raw_prob))
        calibrated = 1 / (1 + math.exp(a * logit + b))
        
        return calibrated
    
    def predict_with_uncertainty(self, prompt, return_raw=False):
        """
        Dự đoán với uncertainty estimation qua HolySheep API
        """
        response = requests.post(
            f"{self.base_url}/chat/completions",
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            },
            json={
                "model": "gpt-4.1",  # $8/MTok
                "messages": [{"role": "user", "content": prompt}],
                "temperature": 0.7
            }
        )
        
        result = response.json()
        raw_prob = result.get('choices', [{}])[0].get('raw_confidence', 0.5)
        
        if return_raw:
            return {'raw': raw_prob}
        
        calibrated_prob = self.calibrate_probability(raw_prob)
        
        return {
            'raw_confidence': raw_prob,
            'calibrated_confidence': calibrated_prob,
            'uncertainty': abs(calibrated_prob - 0.5) * 2  # 0-1 scale
        }

Khởi tạo với API key

model = HolySheepCalibratedModel(api_key="YOUR_HOLYSHEEP_API_KEY")

Train với historical data

train_probs = np.array([0.85, 0.72, 0.45, 0.91, 0.33, 0.68, 0.55, 0.79]) train_labels = np.array([1, 1, 0, 1, 0, 1, 0, 1]) params = model.train_platt_scaling(train_probs, train_labels) print(f"Platt Scaling Parameters: a={params['a']:.4f}, b={params['b']:.4f}")

Predict với calibration

result = model.predict_with_uncertainty("Xác định rủi ro tín dụng cho khách hàng này") print(f"Calibrated Confidence: {result['calibrated_confidence']:.4f}") print(f"Uncertainty: {result['uncertainty']:.4f}")

Isotonic Regression: Calibration Phi Tuyến Tính

Khi relationship giữa predicted probability và actual frequency không tuyến tính, Isotonic Regression là lựa chọn tốt hơn. Nó fit một monotonic function không tham số.

import numpy as np
from sklearn.isotonic import IsotonicRegression
from sklearn.calibration import CalibratedClassifierCV
import requests

class IsotonicCalibratedPredictor:
    """
    Isotonic Regression Calibration với HolySheep AI backend
    Hỗ trợ multi-class classification với uncertainty estimation
    """
    
    def __init__(self, api_key, model_name="deepseek-v3.2"):
        self.api_key = api_key
        self.base_url = "https://api.holysheep.ai/v1"
        self.model_name = model_name
        self.calibrators = {}
        
    def _get_calibration_pricing(self):
        """
        HolySheep AI Pricing 2026 (per million tokens):
        - DeepSeek V3.2: $0.42 (tiết kiệm 85%+)
        - Gemini 2.5 Flash: $2.50
        - Claude Sonnet 4.5: $15
        - GPT-4.1: $8
        """
        pricing = {
            'deepseek-v3.2': 0.42,
            'gemini-2.5-flash': 2.50,
            'claude-sonnet-4.5': 15,
            'gpt-4.1': 8
        }
        return pricing
    
    def train_calibration(self, raw_probs, true_labels, n_classes=3):
        """
        Train Isotonic Regression cho multi-class
        
        Args:
            raw_probs: Dict với keys là class names, values là arrays
            true_labels: True class indices
            n_classes: Số lượng classes
        """
        for class_idx in range(n_classes):
            class_probs = raw_probs.get(f'class_{class_idx}', np.array([]))
            
            if len(class_probs) == 0:
                continue
            
            # Isotonic Regression cho từng class
            ir = IsotonicRegression(y_min=0, y_max=1, out_of_bounds='clip')
            
            # Tạo binary labels cho class này
            binary_labels = (true_labels == class_idx).astype(int)
            
            ir.fit(class_probs, binary_labels)
            self.calibrators[class_idx] = ir
        
        return self.calibrators
    
    def predict_multi_class(self, prompts_batch, class_names):
        """
        Batch prediction với calibration
        Độ trễ <50ms với HolySheep infrastructure
        """
        # Gọi batch API
        response = requests.post(
            f"{self.base_url}/chat/completions",
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            },
            json={
                "model": self.model_name,
                "messages": [{"role": "user", "content": p} for p in prompts_batch],
                "temperature": 0.3
            },
            timeout=5  # HolySheep đảm bảo <50ms latency
        )
        
        results = []
        for item in response.json():
            raw_probs = item.get('class_probabilities', {})
            calibrated_probs = {}
            
            for class_idx, class_name in enumerate(class_names):
                if class_idx in self.calibrators:
                    raw_prob = raw_probs.get(class_name, 0.33)
                    calibrated_probs[class_name] = self.calibrators[class_idx].predict([raw_prob])[0]
                else:
                    calibrated_probs[class_name] = raw_probs.get(class_name, 0.33)
            
            # Tính uncertainty (entropy-based)
            probs = np.array(list(calibrated_probs.values()))
            probs = probs / probs.sum()  # Normalize
            entropy = -np.sum(probs * np.log(probs + 1e-10))
            max_uncertainty = np.log(len(class_names))
            normalized_uncertainty = entropy / max_uncertainty
            
            results.append({
                'predictions': calibrated_probs,
                'uncertainty': normalized_uncertainty,
                'confidence': 1 - normalized_uncertainty
            })
        
        return results

Ví dụ sử dụng

predictor = IsotonicCalibratedPredictor( api_key="YOUR_HOLYSHEEP_API_KEY", model_name="deepseek-v3.2" )

Training data

raw_probs = { 'class_0': np.array([0.7, 0.8, 0.6, 0.75, 0.85]), 'class_1': np.array([0.2, 0.15, 0.3, 0.15, 0.1]), 'class_2': np.array([0.1, 0.05, 0.1, 0.1, 0.05]) } true_labels = np.array([0, 0, 1, 0, 0]) predictor.train_calibration(raw_probs, true_labels, n_classes=3)

Batch prediction

prompts = [ "Phân loại: rủi ro cao", "Phân loại: rủi ro trung bình", "Phân loại: rủi ro thấp" ] class_names = ['high_risk', 'medium_risk', 'low_risk'] predictions = predictor.predict_multi_class(prompts, class_names) for i, pred in enumerate(predictions): print(f"Prompt {i+1}:") print(f" Predictions: {pred['predictions']}") print(f" Confidence: {pred['confidence']:.2%}") print(f" Uncertainty: {pred['uncertainty']:.2%}")

Temperature Scaling Cho Large Language Models

Với LLMs, temperature scaling là phương pháp phổ biến nhất vì nó chỉ có một parameter duy nhất và không thay đổi prediction ordering.

import torch
import torch.nn.functional as F
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import requests
import json

class LLMTemperatureScaling:
    """
    Temperature Scaling cho LLM calibration
    Tích hợp HolySheep AI với độ trễ tối ưu
    """
    
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.holysheep.ai/v1"
        self.temperature = 1.0
        self.calibration_logits = []
        self.calibration_labels = []
    
    def collect_calibration_data(self, prompts, labels):
        """
        Collect logits từ model cho calibration
        
        Args:
            prompts: List of prompts
            labels: True labels (0 hoặc 1)
        """
        for prompt, label in zip(prompts, labels):
            response = requests.post(
                f"{self.base_url}/chat/completions",
                headers={
                    "Authorization": f"Bearer {self.api_key}",
                    "Content-Type": "application/json"
                },
                json={
                    "model": "gpt-4.1",
                    "messages": [{"role": "user", "content": prompt}],
                    "temperature": 0,
                    "logprobs": True
                }
            )
            
            result = response.json()
            logit = result.get('logit', 0.0)  # Log probability
            
            self.calibration_logits.append(logit)
            self.calibration_labels.append(label)
    
    def find_optimal_temperature(self):
        """
        Tìm temperature tối ưu bằng grid search
        """
        best_temp = 1.0
        best_ece = float('inf')
        
        calibration_logits = torch.tensor(self.calibration_logits)
        calibration_labels = torch.tensor(self.calibration_labels)
        
        for temp in torch.linspace(0.5, 3.0, 50):
            # Scale logits
            scaled_logits = calibration_logits / temp
            
            # Convert to probabilities
            probs = torch.sigmoid(scaled_logits)
            
            # Tính ECE
            ece = self._compute_ece(probs, calibration_labels)
            
            if ece < best_ece:
                best_ece = ece
                best_temp = temp.item()
        
        self.temperature = best_temp
        return best_temp, best_ece
    
    def _compute_ece(self, probs, labels, n_bins=10):
        """Compute Expected Calibration Error"""
        bin_boundaries = torch.linspace(0, 1, n_bins + 1)
        ece = 0.0
        
        for i in range(n_bins):
            in_bin = (probs > bin_boundaries[i]) & (probs <= bin_boundaries[i + 1])
            prop_in_bin = in_bin.float().mean()
            
            if prop_in_bin > 0:
                accuracy_in_bin = labels[in_bin].float().mean()
                avg_confidence_in_bin = probs[in_bin].mean()
                ece += prop_in_bin * torch.abs(accuracy_in_bin - avg_confidence_in_bin)
        
        return ece.item()
    
    def predict_with_calibration(self, prompt):
        """
        Inference với calibrated temperature
        """
        response = requests.post(
            f"{self.base_url}/chat/completions",
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            },
            json={
                "model": "gpt-4.1",
                "messages": [{"role": "user", "content": prompt}],
                "temperature": self.temperature
            }
        )
        
        result = response.json()
        raw_confidence = result.get('confidence', 0.5)
        
        # Apply temperature scaling
        logit = torch.log(torch.tensor(raw_confidence) / (1 - raw_confidence))
        calibrated_logit = logit / self.temperature
        calibrated_prob = torch.sigmoid(calibrated_logit).item()
        
        return {
            'response': result.get('content', ''),
            'raw_confidence': raw_confidence,
            'calibrated_confidence': calibrated_prob,
            'temperature': self.temperature
        }

Sử dụng

calibrator = LLMTemperatureScaling(api_key="YOUR_HOLYSHEEP_API_KEY")

Collect calibration data (nên có ít nhất 1000 samples)

calibration_prompts = [ "Câu hỏi 1", "Câu hỏi 2", # ... thêm ít nhất 1000 prompts ] calibration_labels = [1, 0, ...] calibrator.collect_calibration_data(calibration_prompts, calibration_labels)

Find optimal temperature

optimal_temp, ece = calibrator.find_optimal_temperature() print(f"Optimal Temperature: {optimal_temp:.4f}") print(f"Calibration ECE: {ece:.4f}")

Predict

result = calibrator.predict_with_calibration("Câu hỏi mới cần dự đoán") print(f"Calibrated Confidence: {result['calibrated_confidence']:.2%}")

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

1. Lỗi: Calibration Overfitting Với Dataset Quá Nhỏ

Mô tả: Khi training set quá nhỏ (< 1000 samples), calibration model sẽ overfit và không generalize được.

# ❌ SAI: Training với quá ít data
calibrator.train_platt_scaling(
    train_probs=np.array([0.8, 0.6, 0.7]),  # Chỉ 3 samples!
    train_labels=np.array([1, 0, 1])
)

✅ ĐÚNG: Đảm bảo đủ samples và sử dụng cross-validation

from sklearn.model_selection import cross_val_score def safe_platt_training(train_probs, train_labels, min_samples=1000): """ Safe Platt Scaling với validation """ if len(train_probs) < min_samples: raise ValueError(f"Cần ít nhất {min_samples} samples, hiện có {len(train_probs)}") # Sử dụng 5-fold CV để đánh giá lr = LogisticRegression() cv_scores = cross_val_score(lr, train_probs.reshape(-1,1), train_labels, cv=5) if cv_scores.mean() < 0.6: print(f"⚠️ Cảnh báo: CV accuracy thấp ({cv_scores.mean():.2%})") print("Nên thu thập thêm data hoặc cải thiện base model") # Train trên toàn bộ data lr.fit(train_probs.reshape(-1, 1), train_labels) return { 'a': lr.coef_[0][0], 'b': lr.intercept_[0], 'cv_accuracy': cv_scores.mean() }

Sử dụng an toàn

result = safe_platt_training( train_probs=large_train_probs, # ≥ 1000 samples train_labels=large_train_labels )

2. Lỗi: Confusion Giữa Confidence Và Calibration

Mô tả: Nhiều developers nhầm lẫn giữa "model confidence cao" và "model well-calibrated".

# ❌ SAI: Tin tưởng blindly vào confidence cao
if model.predict(input).confidence > 0.9:
    auto_approve()  # Nguy hiểm!

✅ ĐÚNG: Luôn kiểm tra cả confidence VÀ uncertainty

def safe_auto_decision(prediction, uncertainty_threshold=0.3): """ Safe decision making với uncertainty awareness """ confidence = prediction['calibrated_confidence'] uncertainty = prediction['uncertainty'] # High confidence + Low uncertainty → Auto approve if confidence > 0.85 and uncertainty < uncertainty_threshold: return {'action': 'auto_approve', 'risk': 'low'} # Low confidence hoặc High uncertainty → Manual review elif confidence < 0.6 or uncertainty > uncertainty_threshold: return {'action': 'manual_review', 'risk': 'high'} # Medium range → Conditional approval else: return {'action': 'conditional_approve', 'risk': 'medium'}

Ví dụ usage

prediction = { 'calibrated_confidence': 0.82, 'uncertainty': 0.45 } decision = safe_auto_decision(prediction) print(f"Action: {decision['action']}, Risk: {decision['risk']}")

3. Lỗi: Không Cập Nhật Calibration Theo Thời Gian

Mô tả: Model drift khiến calibration không còn chính xác sau vài tháng. Đây là lỗi phổ biến nhất trong production.

import time
from datetime import datetime, timedelta

class ContinuousCalibrationMonitor:
    """
    Monitor và tự động recalibrate khi phát hiện drift
    """
    
    def __init__(self, api_key, drift_threshold=0.05, recalibration_interval_days=30):
        self.api_key = api_key
        self.drift_threshold = drift_threshold
        self.recalibration_interval = timedelta(days=recalibration_interval_days)
        self.last_calibration = None
        self.calibration_data = []
        self.base_url = "https://api.holysheep.ai/v1"
    
    def log_prediction(self, prompt, predicted_prob, actual_outcome):
        """
        Log mọi prediction để theo dõi drift
        """
        self.calibration_data.append({
            'timestamp': datetime.now(),
            'predicted_prob': predicted_prob,
            'actual_outcome': actual_outcome,
            'error': abs(predicted_prob - actual_outcome)
        })
    
    def check_drift(self):
        """
        Kiểm tra xem model có bị drift không
        """
        if len(self.calibration_data) < 500:
            return {'drifted': False, 'reason': 'insufficient_data'}
        
        # So sánh recent performance với baseline
        recent_errors = [d['error'] for d in self.calibration_data[-100:]]
        baseline_errors = [d['error'] for d in self.calibration_data[:100]]
        
        avg_recent_error = np.mean(recent_errors)
        avg_baseline_error = np.mean(baseline_errors)
        
        drift = avg_recent_error - avg_baseline_error
        
        return {
            'drifted': abs(drift) > self.drift_threshold,
            'drift_amount': drift,
            'recent_avg_error': avg_recent_error,
            'baseline_avg_error': avg_baseline_error
        }
    
    def should_recalibrate(self):
        """
        Quyết định có nên recalibrate không
        """
        # Check time-based
        if self.last_calibration:
            time_since = datetime.now() - self.last_calibration
            time_check = time_since > self.recalibration_interval
        else:
            time_check = True
        
        # Check drift-based
        drift_status = self.check_drift()
        drift_check = drift_status['drifted']
        
        return time_check or drift_check
    
    def recalibrate(self):
        """
        Tự động recalibrate với HolySheep API
        """
        if not self.should_recalibrate():
            print("Không cần recalibrate")
            return None
        
        print("🔄 Bắt đầu recalibration...")
        
        # Train với data mới
        train_probs = np.array([d['predicted_prob'] for d in self.calibration_data])
        train_labels = np.array([d['actual_outcome'] for d in self.calibration_data])
        
        calibrator = HolySheepCalibratedModel(self.api_key)
        new_params = calibrator.train_platt_scaling(train_probs, train_labels)
        
        self.last_calibration = datetime.now()
        
        # Reset data sau khi calibrate
        self.calibration_data = self.calibration_data[-500:]  # Giữ lại 500 samples gần nhất
        
        return new_params

Sử dụng trong production

monitor = ContinuousCalibrationMonitor( api_key="YOUR_HOLYSHEEP_API_KEY", drift_threshold=0.05, recalibration_interval_days=30 )

Log mỗi prediction

monitor.log_prediction( prompt="Customer #12345", predicted_prob=0.75, actual_outcome=1 # sau khi biết kết quả thực tế )

Kiểm tra và recalibrate nếu cần

if monitor.should_recalibrate(): new_params = monitor.recalibrate() print(f"Recalibration thành công: {new_params}")

Triển Khai Production Với HolySheep AI

Dựa trên kinh nghiệm triển khai thực tế cho startup ở TP.HCM, đây là architecture tôi recommend cho production:

from typing import Dict, List, Optional
import hashlib
import time

class ProductionCalibratedAPI:
    """
    Production-ready calibrated API với HolySheep AI
    Features: Rate limiting, Caching, Auto-retry, Monitoring
    """
    
    def __init__(self, api_key: str, model: str = "deepseek-v3.2"):
        self.api_key = api_key
        self.model = model
        self.base_url = "https://api.holysheep.ai/v1"
        
        # Calibration components
        self.calibrator = None
        self.drift_monitor = None
        
        # Caching
        self.cache = {}
        self.cache_ttl = 300  # 5 minutes
        
        # Rate limiting
        self.request_count = 0
        self.window_start = time.time()
        
        # Pricing (HolySheep AI 2026)
        self.pricing = {
            'deepseek-v3.2': 0.42,   # $0.42/MTok
            'gemini-2.5-flash': 2.50,  # $2.50/MTok
            'claude-sonnet-4.5': 15,   # $15/MTok
            'gpt-4.1': 8              # $8/MTok
        }
    
    def init_calibration(self, historical_data: List[Dict]):
        """
        Khởi tạo calibration với historical data
        
        Args:
            historical_data: List of {'input': str, 'raw_prob': float, 'actual': int}
        """
        self.calibrator = HolySheepCalibratedModel(self.api_key)
        
        train_probs = np.array([d['raw_prob'] for d in historical_data])
        train_labels = np.array([d['actual'] for d in historical_data])
        
        self.calibrator.train_platt_scaling(train_probs, train_labels)
        
        # Initialize drift monitor
        self.drift_monitor = ContinuousCalibrationMonitor(
            api_key=self.api_key,
            drift_threshold=0.05
        )
        
        return {'status': 'calibrated', 'samples': len(historical_data)}
    
    def _check_rate_limit(self, max_requests: int = 100, window: int = 60):
        """
        Simple rate limiting
        """
        current_time = time.time()
        
        if current_time - self.window_start > window:
            self.request_count = 0
            self.window_start = current_time
        
        if self.request_count >= max_requests:
            raise Exception(f"Rate limit exceeded: {max_requests}/{window}s")
        
        self.request_count += 1
    
    def _get_cache_key(self, prompt: str) -> str:
        """Generate cache key"""
        return hashlib.md5(prompt.encode()).hexdigest()
    
    def predict(self, prompt: str, use_cache: bool = True) -> Dict:
        """
        Predict với calibration và caching
        
        Returns:
            Dict chứa prediction, confidence, uncertainty, và metadata
        """
        self._check_rate_limit()
        
        # Check cache
        if use_cache:
            cache_key = self._get_cache_key(prompt)
            if cache_key in self.cache:
                cached = self.cache[cache_key]
                if time.time() - cached['timestamp'] < self.cache_ttl:
                    return {**cached['result'], 'cached': True}
        
        # Call HolySheep API
        response = requests.post(
            f"{self.base_url}/chat/completions",
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            },
            json={
                "model": self.model,
                "messages": [{"role": "user", "content": prompt}],
                "temperature": 0.3
            }
        )
        
        result = response.json()
        raw_prob = result.get('choices', [{}])[0].get('confidence', 0.5)
        
        # Apply calibration
        calibrated = self.calibrator.calibrate_probability(raw_prob)
        uncertainty = abs(calibrated - 0.5) * 2
        
        prediction_result = {
            'response': result.get('choices', [{}])[0].get('message', {}).get('content', ''),
            'raw_confidence': raw_prob,
            'calibrated_confidence': calibrated,
            'uncertainty': uncertainty,
            'confidence_level': 'high' if uncertainty < 0.2 else 'medium' if uncertainty < 0.4 else 'low',
            'latency_ms': result.get('latency_ms', 0),
            'cached': False
        }
        
        # Cache result
        if use_cache