บทนำ

การดูแลระบบ AI API ในระดับ Production ไม่ใช่แค่การให้บริการ LLM แต่เป็นเรื่องของ "การเงิน" ที่ซับซ้อน ในบทความนี้ ผมจะแชร์ประสบการณ์ตรงจากการสร้างระบบ Monitor อัตรากำไร (Margin Monitoring) ที่สามารถติดตามการเปลี่ยนแปลง Gross Margin แยกตาม Model, Customer, Channel และ Cache Hit Ratio โดยใช้ HolySheep AI เป็น Backend หลัก ปัญหาหลักที่ทีมพบเจอคือ: Revenue ดูสูงแต่ Margin ต่ำกว่าที่คาดไว้ถึง 30% จากการที่ไม่มี Visibility ว่า Cost ไปจบที่ Model ไหน, Customer ไหน และ Channel ไหนบ้าง

สถาปัตยกรรมระบบ Margin Monitoring

┌─────────────────────────────────────────────────────────────┐
│                    Margin Monitoring System                 │
├─────────────┬─────────────┬─────────────┬──────────────────┤
│   Input     │  Analysis   │   Alerting  │    Reporting     │
│   Layer     │    Layer    │    Layer    │      Layer       │
├─────────────┼─────────────┼─────────────┼──────────────────┤
│ API Calls   │ Cost Calc   │ Threshold   │ Dashboard        │
│ Token Usage │ Margin %    │ Anomaly     │ Breakdown        │
│ Cache Stats │ Trend       │ Slack/Email │ Export           │
└─────────────┴─────────────┴─────────────┴──────────────────┘

การคำนวณ Margin แบบ Real-time

สูตรหลักของ Margin Calculation คือ:
Gross Margin = (Revenue - COGS) / Revenue × 100

โดยที่:
- Revenue = Σ(tokens × price_per_model)
- COGS = Σ(API_calls × cost_per_1M_tokens)
- Cache Savings = (cache_hit_ratio × raw_cost) - cached_cost
#!/usr/bin/env python3
"""
HolySheep API Profit Margin Calculator
คำนวณอัตรากำไรแบบ Real-time แยกตาม Model/Customer/Channel
"""

import asyncio
import httpx
from dataclasses import dataclass, field
from typing import Dict, List, Optional
from datetime import datetime, timedelta
from collections import defaultdict
import statistics

@dataclass
class ModelPricing:
    """ราคาต่อ 1M tokens ของแต่ละ Model"""
    gpt41: float = 8.0          # $8.00 / MTok
    claude_sonnet45: float = 15.0   # $15.00 / MTok
    gemini_flash25: float = 2.50    # $2.50 / MTok
    deepseek_v32: float = 0.42      # $0.42 / MTok

@dataclass
class APICallRecord:
    """Record ของการเรียก API 1 ครั้ง"""
    call_id: str
    timestamp: datetime
    model: str
    customer_id: str
    channel: str  # web, api, sdk, partner
    input_tokens: int
    output_tokens: int
    cache_hit: bool
    cache_credit: float = 0.0  # ส่วนลดจาก cache

@dataclass
class MarginResult:
    """ผลลัพธ์การคำนวณ Margin"""
    dimension: str  # model, customer, channel
    dimension_value: str
    total_revenue: float
    total_cost: float
    gross_margin_pct: float
    cache_savings: float
    call_count: int
    avg_latency_ms: float

class HolySheepMarginCalculator:
    """
    คลาสหลักสำหรับคำนวณ Margin จาก HolySheep API
    """
    
    BASE_URL = "https://api.holysheep.ai/v1"
    
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.pricing = ModelPricing()
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
    
    def get_cost_per_token(self, model: str, is_cache_hit: bool = False) -> float:
        """
        คำนวณ Cost ต่อ Token ตาม Model และ Cache Status
        
        HolySheep มีส่วนลดพิเศษสำหรับ Cache Hit:
        - Cache Hit: 90% ส่วนลด (จ่ายแค่ 10% ของราคาปกติ)
        - Cache Miss: จ่ายเต็มราคา
        """
        model_costs = {
            "gpt-4.1": self.pricing.gpt41 / 1_000_000,
            "claude-sonnet-4.5": self.pricing.claude_sonnet45 / 1_000_000,
            "gemini-2.5-flash": self.pricing.gemini_flash25 / 1_000_000,
            "deepseek-v3.2": self.pricing.deepseek_v32 / 1_000_000,
        }
        
        base_cost = model_costs.get(model, 0.0)
        
        if is_cache_hit:
            return base_cost * 0.10  # 90% discount for cache hits
        return base_cost
    
    def calculate_single_call_cost(self, record: APICallRecord) -> Dict[str, float]:
        """คำนวณ Cost และ Revenue ของ API Call เดียว"""
        
        input_cost = self.get_cost_per_token(record.model, record.cache_hit)
        output_cost = self.get_cost_per_token(record.model, False)  # Output ไม่มี cache
        
        total_cost = (record.input_tokens * input_cost) + \
                     (record.output_tokens * output_cost)
        
        # Revenue สมมติ (ใช้ Price Markup 1.5x จาก Cost)
        markup = 1.5
        revenue = total_cost * markup
        
        return {
            "cost": total_cost,
            "revenue": revenue,
            "margin": revenue - total_cost,
            "margin_pct": ((revenue - total_cost) / revenue * 100) if revenue > 0 else 0
        }
    
    async def fetch_usage_logs(self, 
                               start_date: datetime,
                               end_date: datetime,
                               customer_id: Optional[str] = None) -> List[APICallRecord]:
        """
        ดึงข้อมูล Usage Logs จาก HolySheep API
        
        Endpoint: GET /v1/usage/logs
        """
        async with httpx.AsyncClient(timeout=30.0) as client:
            params = {
                "start": start_date.isoformat(),
                "end": end_date.isoformat(),
            }
            if customer_id:
                params["customer_id"] = customer_id
            
            response = await client.get(
                f"{self.BASE_URL}/usage/logs",
                headers=self.headers,
                params=params
            )
            response.raise_for_status()
            
            data = response.json()
            return [self._parse_record(r) for r in data.get("logs", [])]
    
    def _parse_record(self, raw: Dict) -> APICallRecord:
        """Parse raw API response เป็น APICallRecord"""
        return APICallRecord(
            call_id=raw["id"],
            timestamp=datetime.fromisoformat(raw["timestamp"]),
            model=raw["model"],
            customer_id=raw["customer_id"],
            channel=raw.get("channel", "unknown"),
            input_tokens=raw["usage"]["input_tokens"],
            output_tokens=raw["usage"]["output_tokens"],
            cache_hit=raw.get("cache_hit", False),
            cache_credit=raw.get("cache_credit", 0.0)
        )
    
    def analyze_margin_by_dimension(self, 
                                    records: List[APICallRecord],
                                    dimension: str) -> List[MarginResult]:
        """
        วิเคราะห์ Margin แยกตาม Dimension (model, customer, channel)
        """
        buckets = defaultdict(lambda: {
            "revenue": 0.0,
            "cost": 0.0,
            "cache_savings": 0.0,
            "count": 0,
            "latencies": []
        })
        
        for record in records:
            if dimension == "model":
                key = record.model
            elif dimension == "customer":
                key = record.customer_id
            elif dimension == "channel":
                key = record.channel
            else:
                key = "all"
            
            calc = self.calculate_single_call_cost(record)
            buckets[key]["revenue"] += calc["revenue"]
            buckets[key]["cost"] += calc["cost"]
            buckets[key]["count"] += 1
            
            # คำนวณ Cache Savings
            if record.cache_hit:
                full_cost = self.get_cost_per_token(record.model, False) * \
                           (record.input_tokens + record.output_tokens)
                buckets[key]["cache_savings"] += full_cost - calc["cost"]
        
        results = []
        for dim_value, data in buckets.items():
            margin_pct = ((data["revenue"] - data["cost"]) / data["revenue"] * 100) \
                        if data["revenue"] > 0 else 0
            
            results.append(MarginResult(
                dimension=dimension,
                dimension_value=dim_value,
                total_revenue=data["revenue"],
                total_cost=data["cost"],
                gross_margin_pct=margin_pct,
                cache_savings=data["cache_savings"],
                call_count=data["count"],
                avg_latency_ms=0  # ควรดึงจาก actual metrics
            ))
        
        return sorted(results, key=lambda x: x.gross_margin_pct)

ตัวอย่างการใช้งาน

async def main(): calculator = HolySheepMarginCalculator(api_key="YOUR_HOLYSHEEP_API_KEY") # ดึงข้อมูล 7 วันย้อนหลัง end_date = datetime.now() start_date = end_date - timedelta(days=7) try: logs = await calculator.fetch_usage_logs(start_date, end_date) # วิเคราะห์ตาม Model model_analysis = calculator.analyze_margin_by_dimension(logs, "model") print("=" * 60) print("MARGIN ANALYSIS BY MODEL (7 วัน)") print("=" * 60) for r in model_analysis: print(f"Model: {r.dimension_value}") print(f" Revenue: ${r.total_revenue:.2f}") print(f" Cost: ${r.total_cost:.2f}") print(f" Margin: {r.gross_margin_pct:.1f}%") print(f" Cache Savings: ${r.cache_savings:.2f}") print() # วิเคราะห์ตาม Customer customer_analysis = calculator.analyze_margin_by_dimension(logs, "customer") print("=" * 60) print("MARGIN ANALYSIS BY CUSTOMER (7 วัน)") print("=" * 60) for r in sorted(customer_analysis, key=lambda x: x.total_revenue, reverse=True)[:10]: print(f"Customer: {r.dimension_value}") print(f" Revenue: ${r.total_revenue:.2f} | Margin: {r.gross_margin_pct:.1f}%") except httpx.HTTPStatusError as e: print(f"API Error: {e.response.status_code} - {e.response.text}") except Exception as e: print(f"Error: {e}") if __name__ == "__main__": asyncio.run(main())

การ Monitor Cache Hit Ratio ที่ส่งผลต่อ Margin

Cache Hit Ratio เป็นตัวแปรสำคัญที่สุดในการควบคุม Margin บน HolySheep มีการคิดราคาพิเศษ:
#!/usr/bin/env python3
"""
Cache Hit Ratio Optimization & Monitoring
ติดตามและ optimize cache performance เพื่อเพิ่ม Margin
"""

import asyncio
import httpx
from datetime import datetime, timedelta
from typing import Dict, List, Tuple
from collections import defaultdict
import statistics

class CacheMetricsMonitor:
    """
    Monitor Cache Hit Ratio และคำนวณ Impact ต่อ Margin
    """
    
    BASE_URL = "https://api.holysheep.ai/v1"
    
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        # ราคาเต็มต่อ MTok (สำหรับคำนวณ savings)
        self.model_prices = {
            "gpt-4.1": 8.0,
            "claude-sonnet-4.5": 15.0,
            "gemini-2.5-flash": 2.50,
            "deepseek-v3.2": 0.42,
        }
    
    async def get_cache_stats(self, 
                            start: datetime,
                            end: datetime) -> Dict:
        """
        ดึง Cache Statistics จาก HolySheep API
        
        GET /v1/monitoring/cache
        Response includes:
        - total_requests
        - cache_hits
        - cache_misses  
        - hit_ratio (percentage)
        - savings_amount (USD)
        """
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"{self.BASE_URL}/monitoring/cache",
                headers=self.headers,
                params={
                    "start": start.isoformat(),
                    "end": end.isoformat()
                }
            )
            response.raise_for_status()
            return response.json()
    
    async def get_cache_breakdown(self,
                                 granularity: str = "daily") -> List[Dict]:
        """
        ดึง Cache Breakdown แยกตาม Model/Customer
        
        GET /v1/monitoring/cache/breakdown
        """
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"{self.BASE_URL}/monitoring/cache/breakdown",
                headers=self.headers,
                params={"granularity": granularity}
            )
            response.raise_for_status()
            return response.json().get("breakdown", [])
    
    def calculate_cache_impact(self, 
                              cache_stats: Dict,
                              model_prices: Dict) -> Dict:
        """
        คำนวณผลกระทบของ Cache ต่อ Margin
        
        Formula:
        - Without Cache Cost = total_tokens × price_per_MTok / 1M
        - With Cache Cost = (hits × 0.1 + misses × 1.0) × price_per_MTok / 1M
        - Savings = Without Cache - With Cache
        """
        results = {
            "total_savings": 0.0,
            "by_model": {},
            "overall_hit_ratio": cache_stats.get("hit_ratio", 0),
            "projected_monthly_savings": 0.0
        }
        
        breakdown = cache_stats.get("breakdown", [])
        
        for item in breakdown:
            model = item["model"]
            price_per_mtok = model_prices.get(model, 0)
            
            input_tokens = item.get("input_tokens", 0)
            cache_hits = item.get("cache_hits", 0)
            cache_misses = item.get("cache_misses", 0)
            
            # คำนวณ Cost ถ้าไม่มี Cache
            cost_without_cache = (input_tokens / 1_000_000) * price_per_mtok
            
            # คำนวณ Cost ปัจจุบัน (มี Cache)
            hit_cost = (cache_hits / 1_000_000) * price_per_mtok * 0.10
            miss_cost = (cache_misses / 1_000_000) * price_per_mtok
            cost_with_cache = hit_cost + miss_cost
            
            # Savings
            savings = cost_without_cache - cost_with_cache
            hit_ratio = (cache_hits / input_tokens * 100) if input_tokens > 0 else 0
            
            results["by_model"][model] = {
                "total_tokens": input_tokens,
                "cache_hits": cache_hits,
                "cache_misses": cache_misses,
                "hit_ratio_pct": hit_ratio,
                "cost_without_cache": cost_without_cache,
                "cost_with_cache": cost_with_cache,
                "savings": savings,
                "savings_pct": (savings / cost_without_cache * 100) if cost_without_cache > 0 else 0
            }
            
            results["total_savings"] += savings
        
        # Project เป็นรายเดือน (假设 linear growth)
        days_in_period = cache_stats.get("days", 7)
        results["projected_monthly_savings"] = results["total_savings"] * (30 / days_in_period)
        
        return results
    
    def identify_cache_optimization_opportunities(self,
                                                   breakdown: List[Dict]) -> List[Dict]:
        """
        ระบุโอกาสในการ optimize Cache Hit Ratio
        
        Strategies:
        1. Prompt Caching - ใช้ prompt prefix ที่ซ้ำกัน
        2. Semantic Caching - cache based on semantic similarity
        3. Temperature/Parameter Tuning - ลด randomness เพื่อเพิ่ม cache hits
        """
        opportunities = []
        
        for item in breakdown:
            model = item["model"]
            hit_ratio = item.get("hit_ratio", 0)
            total_tokens = item.get("input_tokens", 0)
            
            # ถ้า Cache Hit < 50% แสดงว่ามีโอกาสปรับปรุง
            if hit_ratio < 50 and total_tokens > 1_000_000:
                potential_improvement = min(70 - hit_ratio, 30)  # Target 70%
                potential_savings = total_tokens / 1_000_000 * \
                                   self.model_prices.get(model, 0) * \
                                   (potential_improvement / 100) * 0.9
                
                opportunities.append({
                    "model": model,
                    "current_hit_ratio": hit_ratio,
                    "target_hit_ratio": 70,
                    "potential_improvement": potential_improvement,
                    "potential_monthly_savings": potential_savings * 30,
                    "recommendation": self._get_recommendation(model, hit_ratio)
                })
        
        return sorted(opportunities, key=lambda x: x["potential_monthly_savings"], reverse=True)
    
    def _get_recommendation(self, model: str, hit_ratio: float) -> str:
        """แนะนำวิธีการปรับปรุงตาม Model และ Hit Ratio"""
        recommendations = {
            "low_volume": "เพิ่ม Prompt Templates ที่ใช้บ่อยเป็น System Prompts",
            "high_temp": "ลด Temperature จาก 0.9 → 0.3 เพื่อเพิ่มความสม่ำเสมอ",
            "semantic": "ใช้ Semantic Caching สำหรับคำถามที่คล้ายกัน",
            "batch": "รวม Requests ที่คล้ายกันเป็น Batch"
        }
        
        if hit_ratio < 20:
            return f"⚠️ Critical: {recommendations['low_volume']} + {recommendations['semantic']}"
        elif hit_ratio < 35:
            return f"🔧 Medium: {recommendations['high_temp']} + {recommendations['batch']}"
        else:
            return f"📈 Good: {recommendations['semantic']}"

async def main():
    monitor = CacheMetricsMonitor(api_key="YOUR_HOLYSHEEP_API_KEY")
    
    # ดึงข้อมูล 7 วัน
    end = datetime.now()
    start = end - timedelta(days=7)
    
    try:
        # ดึง Cache Stats
        stats = await monitor.get_cache_stats(start, end)
        print("=" * 70)
        print("CACHE PERFORMANCE DASHBOARD")
        print("=" * 70)
        print(f"Overall Hit Ratio: {stats.get('hit_ratio', 0):.1f}%")
        print(f"Total Requests: {stats.get('total_requests', 0):,}")
        print(f"Cache Hits: {stats.get('cache_hits', 0):,}")
        print(f"Cache Misses: {stats.get('cache_misses', 0):,}")
        print()
        
        # คำนวณ Impact
        impact = monitor.calculate_cache_impact(stats, monitor.model_prices)
        print(f"Total Savings (7 days): ${impact['total_savings']:.2f}")
        print(f"Projected Monthly Savings: ${impact['projected_monthly_savings']:.2f}")
        print()
        
        # แสดงรายละเอียดตาม Model
        print("=" * 70)
        print("BREAKDOWN BY MODEL")
        print("=" * 70)
        for model, data in impact["by_model"].items():
            print(f"\n📊 {model}")
            print(f"   Tokens: {data['total_tokens']:,}")
            print(f"   Hit Ratio: {data['hit_ratio_pct']:.1f}%")
            print(f"   Savings: ${data['savings']:.2f} ({data['savings_pct']:.1f}%)")
        
        # แสดง Optimization Opportunities
        breakdown = await monitor.get_cache_breakdown("daily")
        opportunities = monitor.identify_cache_optimization_opportunities(breakdown)
        
        if opportunities:
            print("\n" + "=" * 70)
            print("🚨 OPTIMIZATION OPPORTUNITIES")
            print("=" * 70)
            for opt in opportunities[:3]:
                print(f"\n{opt['model']}:")
                print(f"   Current: {opt['current_hit_ratio']:.1f}% → Target: {opt['target_hit_ratio']}%")
                print(f"   💰 Potential Monthly Savings: ${opt['potential_monthly_savings']:.2f}")
                print(f"   📝 {opt['recommendation']}")
                
    except httpx.HTTPStatusError as e:
        print(f"API Error: {e.response.status_code}")
        if e.response.status_code == 401:
            print("❌ Invalid API Key. Please check YOUR_HOLYSHEEP_API_KEY")
        elif e.response.status_code == 429:
            print("⏳ Rate Limited. Please wait and retry.")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    asyncio.run(main())

การตั้ง Alert เมื่อ Margin ต่ำกว่า Threshold

#!/usr/bin/env python3
"""
Margin Alert System - ส่ง Alert เมื่อ Margin ต่ำกว่าเกณฑ์
รองรับ Slack, Email และ Webhook
"""

import asyncio
import httpx
from datetime import datetime, timedelta
from dataclasses import dataclass
from typing import List, Optional, Callable
from enum import Enum
import json
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

class AlertLevel(Enum):
    INFO = "info"
    WARNING = "warning"  # Margin 40-50%
    CRITICAL = "critical"  # Margin < 40%
    EMERGENCY = "emergency"  # Margin < 25%

@dataclass
class MarginAlert:
    level: AlertLevel
    dimension: str
    dimension_value: str
    current_margin: float
    threshold: float
    revenue: float
    cost: float
    timestamp: datetime
    recommendation: str

class MarginAlertSystem:
    """
    ระบบ Alert อัตโนมัติเมื่อ Margin ต่ำกว่า Threshold
    """
    
    def __init__(self, holy_sheep_key: str):
        self.api_key = holy_sheep_key
        self.base_url = "https://api.holysheep.ai/v1"
        self.headers = {"Authorization": f"Bearer {api_key}"}
        
        # Default Thresholds
        self.thresholds = {
            AlertLevel.EMERGENCY: 25.0,
            AlertLevel.CRITICAL: 40.0,
            AlertLevel.WARNING: 50.0,
        }
        
        # Alert Handlers
        self.handlers: List[Callable] = []
    
    def add_handler(self, handler: Callable[[MarginAlert], None]):
        """เพิ่ม Alert Handler (Slack, Email, Webhook, etc.)"""
        self.handlers.append(handler)
    
    def check_margin(self, 
                    margin: float,
                    dimension: str,
                    dimension_value: str,
                    revenue: float,
                    cost: float) -> Optional[MarginAlert]:
        """ตรวจสอบ Margin และสร้าง Alert ถ้าจำเป็น"""
        
        alert = None
        
        if margin < self.thresholds[AlertLevel.EMERGENCY]:
            alert = MarginAlert(
                level=AlertLevel.EMERGENCY,
                dimension=dimension,
                dimension_value=dimension_value,
                current_margin=margin,
                threshold=self.thresholds[AlertLevel.EMERGENCY],
                revenue=revenue,
                cost=cost,
                timestamp=datetime.now(),
                recommendation=self._get_emergency_recommendation(dimension, dimension_value)
            )
        elif margin < self.thresholds[AlertLevel.CRITICAL]:
            alert = MarginAlert(
                level=AlertLevel.CRITICAL,
                dimension=dimension,
                dimension_value=dimension_value,
                current_margin=margin,
                threshold=self.thresholds[AlertLevel.CRITICAL],
                revenue=revenue,
                cost=cost,
                timestamp=datetime.now(),
                recommendation=self._get_critical_recommendation(dimension, dimension_value)
            )
        elif margin < self.thresholds[AlertLevel.WARNING]:
            alert = MarginAlert(
                level=AlertLevel.WARNING,
                dimension=dimension,
                dimension_value=dimension_value,
                current_margin=margin,
                threshold=self.thresholds[AlertLevel.WARNING],
                revenue=revenue,
                cost=cost,
                timestamp=datetime.now(),
                recommendation=self._get_warning_recommendation(dimension, dimension_value)
            )
        
        return alert
    
    def _get_emergency_recommendation(self, dim: str, val: str) -> str:
        return f"""🚨 EMERGENCY: {dim}={val} กำลังขาดทุน!
1. หยุด service ทันที
2. ตรวจสอบ pricing ของ customer นี้
3. เปลี่ยนไปใช้ DeepSeek V3.2 ($0.42/MTok) ถ้าเป็นไปได้
4. ติดต่อ HolySheep Support: [email protected]"""
    
    def _get_critical_recommendation(self, dim: str, val: str) -> str:
        return f"""⚠️ CRITICAL: {dim}={val} Margin ต่ำกว่า 40%
1. ทบทวน pricing strategy
2. เพิ่ม Cache Hit Ratio (target >70%)
3. พิจารณาใช้ model ราคาถูกลง (Gemini Flash $2.50/MTok)
4. ตั้ง budget limit สำหรับ customer นี้"""
    
    def _get_warning_recommendation(self, dim: str, val: str) -> str:
        return f"""📈 WARNING: {dim}={val} Margin ลดลงใกล้ 50%
1. Monitor ต่อ 24 ชม.
2. ตรวจสอบ cache performance
3. พิจารณาเพิ่ม markup 5-10%"""

========== Alert Handlers ==========

class SlackAlertHandler: """ส่ง Alert ไปยัง Slack Channel""" def __init__(self, webhook_url: str, channel: str = "#margin-alerts"): self.webhook_url = webhook_url self.channel = channel def send(self, alert: MarginAlert): """ส่ง Slack