บทนำ
การใช้งาน AI API ในปัจจุบันมีความซับซ้อนและต้นทุนที่สูงขึ้นเรื่อยๆ โดยเฉพาะอย่างยิ่งเมื่อต้องรับมือกับคำขอจำนวนมาก การตรวจสอบการใช้งาน (流量监控) และการตรวจจับความผิดปกติ (异常检测) จึงกลายเป็นสิ่งจำเป็นอย่างยิ่งสำหรับนักพัฒนาทุกคน ในบทความนี้ผมจะแบ่งปันประสบการณ์ตรงในการสร้างระบบมอนิเตอร์ที่ครอบคลุม พร้อมโค้ดที่พร้อมใช้งานจริง
เปรียบเทียบบริการ AI API ยอดนิยม
| บริการ | อัตราแลกเปลี่ยน | วิธีชำระเงิน | Latency | เครดิตฟรี | ราคา/MTok |
|--------|----------------|-------------|---------|-----------|-----------|
| **HolySheep AI** | ¥1 = $1 (ประหยัด 85%+) | WeChat, Alipay | < 50ms | ✅ มีเมื่อลงทะเบียน | GPT-4.1 $8, Claude Sonnet 4.5 $15, Gemini 2.5 Flash $2.50, DeepSeek V3.2 $0.42 |
| API อย่างเป็นทางการ | อัตราปกติ | บัตรเครดิต | 50-200ms | จำกัด | $15-60 |
| บริการรีเลย์อื่น | ผันแปร | จำกัด | 100-500ms | หาได้ยาก | $10-40 |
จากตารางจะเห็นได้ชัดว่า
สมัครที่นี่ HolySheep AI ให้ความคุ้มค่าสูงสุดด้วยอัตราแลกเปลี่ยนที่เหลือเชื่อ และความเร็วตอบสนองที่ต่ำกว่า 50ms ซึ่งเหมาะอย่างยิ่งสำหรับการสร้างระบบมอนิเตอร์แบบ real-time
สถาปัตยกรรมระบบตรวจสอบ AI API
ระบบที่ดีต้องประกอบด้วยองค์ประกอบหลัก 4 ส่วน ได้แก่ Data Collector, Metrics Store, Anomaly Detector และ Alert System โดยใช้ HolySheep AI API เป็นฐานหลักในการประมวลผล
ระบบตรวจสอบการจราจร AI API - Data Collector
ติดตั้ง: pip install requests prometheus-client
import requests
import time
import json
from datetime import datetime
from collections import defaultdict
from prometheus_client import Counter, Histogram, Gauge, start_http_server
class APITrafficCollector:
"""
คลาสสำหรับเก็บข้อมูลการใช้งาน API จาก HolySheep AI
ใช้ในการวิเคราะห์ patterns และตรวจจับความผิดปกติ
"""
def __init__(self, api_key, base_url="https://api.holysheep.ai/v1"):
self.api_key = api_key
self.base_url = base_url
self.request_history = []
self.error_log = []
self.usage_stats = defaultdict(lambda: {"count": 0, "tokens": 0, "errors": 0})
# Prometheus metrics
self.api_requests_total = Counter(
'api_requests_total',
'Total API requests',
['model', 'status']
)
self.api_latency = Histogram(
'api_latency_seconds',
'API request latency',
['model']
)
self.active_requests = Gauge(
'active_requests',
'Currently active requests'
)
def make_request(self, model, messages, temperature=0.7):
"""ส่งคำขอไปยัง API และบันทึก metrics"""
start_time = time.time()
self.active_requests.inc()
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": messages,
"temperature": temperature
}
try:
response = requests.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=payload,
timeout=30
)
latency = time.time() - start_time
# บันทึก metrics
status = "success" if response.status_code == 200 else "error"
self.api_requests_total.labels(model=model, status=status).inc()
self.api_latency.labels(model=model).observe(latency)
# เก็บประวัติ
record = {
"timestamp": datetime.now().isoformat(),
"model": model,
"latency_ms": round(latency * 1000, 2),
"status": response.status_code,
"tokens_used": 0
}
if response.status_code == 200:
data = response.json()
usage = data.get("usage", {})
record["tokens_used"] = usage.get("total_tokens", 0)
self.usage_stats[model]["count"] += 1
self.usage_stats[model]["tokens"] += record["tokens_used"]
else:
self.usage_stats[model]["errors"] += 1
self.error_log.append({
"timestamp": record["timestamp"],
"error": response.text,
"status": response.status_code
})
self.request_history.append(record)
# เก็บเฉพาะ 1000 รายการล่าสุด
if len(self.request_history) > 1000:
self.request_history.pop(0)
return response.json()
except Exception as e:
self.error_log.append({
"timestamp": datetime.now().isoformat(),
"error": str(e)
})
raise
finally:
self.active_requests.dec()
def get_stats(self):
"""ส่งคืนสถิติการใช้งาน"""
return {
"models": dict(self.usage_stats),
"total_requests": sum(s["count"] for s in self.usage_stats.values()),
"recent_errors": self.error_log[-10:]
}
เริ่มเซิร์ฟเวอร์ Prometheus ที่ port 8000
start_http_server(8000)
print("Prometheus metrics server started on port 8000")
ระบบตรวจจับความผิดปกติแบบ Real-time
การตรวจจับความผิดปกติเป็นหัวใจสำคัญของระบบมอนิเตอร์ ผมใช้วิธีการหลายแบบผสมผสานกัน ได้แก่ Statistical Threshold, Moving Average และ Rate of Change Detection
ระบบตรวจจับความผิดปกติ - Anomaly Detector
import statistics
from typing import List, Dict, Tuple
class AnomalyDetector:
"""
ตรวจจับความผิดปกติในการใช้งาน API
ใช้หลายวิธีการเพื่อความแม่นยำสูงสุด
"""
def __init__(self, z_score_threshold=3.0, rate_change_threshold=2.0):
self.z_score_threshold = z_score_threshold
self.rate_change_threshold = rate_change_threshold
self.latency_history = []
self.request_rate_history = []
self.error_rate_history = []
def add_latency_sample(self, latency_ms: float):
"""เพิ่ม sample ของ latency"""
self.latency_history.append({
"timestamp": time.time(),
"value": latency_ms
})
# เก็บเฉพาะ 5 นาทีล่าสุด
cutoff = time.time() - 300
self.latency_history = [x for x in self.latency_history if x["timestamp"] > cutoff]
def detect_latency_anomaly(self) -> Tuple[bool, str, float]:
"""ตรวจจับความผิดปกติของ latency ด้วย Z-Score"""
if len(self.latency_history) < 10:
return False, "", 0.0
values = [x["value"] for x in self.latency_history]
mean = statistics.mean(values)
stdev = statistics.stdev(values) if len(values) > 1 else 0
if stdev == 0:
return False, "", 0.0
latest = values[-1]
z_score = (latest - mean) / stdev
if abs(z_score) > self.z_score_threshold:
return True, f"Latency {latest:.2f}ms (z={z_score:.2f}, mean={mean:.2f}ms)", z_score
return False, "", z_score
def detect_rate_anomaly(self, current_rate: float, window_seconds=60) -> Tuple[bool, str]:
"""ตรวจจับการเปลี่ยนแปลงอัตราคำขอที่ผิดปกติ"""
if not self.request_rate_history:
self.request_rate_history.append({
"timestamp": time.time(),
"rate": current_rate
})
return False, ""
last_rate = self.request_rate_history[-1]["rate"]
self.request_rate_history.append({
"timestamp": time.time(),
"rate": current_rate
})
# เก็บเฉพาะ window ล่าสุด
cutoff = time.time() - window_seconds
self.request_rate_history = [x for x in self.request_rate_history if x["timestamp"] > cutoff]
if last_rate > 0:
change_ratio = current_rate / last_rate
# ตรวจจับทั้ง increase และ decrease ที่ผิดปกติ
if change_ratio > self.rate_change_threshold or change_ratio < (1 / self.rate_change_threshold):
direction = "increase" if change_ratio > 1 else "decrease"
return True, f"Rate {direction}: {last_rate:.2f} -> {current_rate:.2f} (ratio={change_ratio:.2f})"
return False, ""
def detect_error_rate_anomaly(self, total_requests: int, errors: int, threshold=0.05) -> Tuple[bool, str]:
"""ตรวจจับอัตราความผิดพลาดที่สูงผิดปกติ"""
if total_requests == 0:
return False, ""
error_rate = errors / total_requests
self.error_rate_history.append({
"timestamp": time.time(),
"rate": error_rate,
"total": total_requests,
"errors": errors
})
# เก็บเฉพาะ 100 รายการล่าสุด
self.error_rate_history = self.error_rate_history[-100:]
if error_rate > threshold:
return True, f"Error rate {error_rate*100:.2f}% exceeds threshold {threshold*100:.2f}% ({errors}/{total_requests})"
return False, ""
def get_comprehensive_report(self, current_rate: float, total_requests: int, errors: int) -> Dict:
"""ส่งคืนรายงานความผิดปกติแบบครอบคลุม"""
report = {
"timestamp": datetime.now().isoformat(),
"anomalies": [],
"status": "normal"
}
# ตรวจจับ latency anomaly
lat_anomaly, lat_msg, z_score = self.detect_latency_anomaly()
if lat_anomaly:
report["anomalies"].append({
"type": "latency",
"severity": "high" if abs(z_score) > 4 else "medium",
"message": lat_msg
})
# ตรวจจับ rate anomaly
rate_anomaly, rate_msg = self.detect_rate_anomaly(current_rate)
if rate_anomaly:
report["anomalies"].append({
"type": "rate_change",
"severity": "high",
"message": rate_msg
})
# ตรวจจับ error rate anomaly
error_anomaly, error_msg = self.detect_error_rate_anomaly(total_requests, errors)
if error_anomaly:
report["anomalies"].append({
"type": "error_rate",
"severity": "critical",
"message": error_msg
})
if report["anomalies"]:
report["status"] = "alert"
return report
ทดสอบการทำงาน
if __name__ == "__main__":
detector = AnomalyDetector(z_score_threshold=2.5)
# เพิ่ม sample latency ปกติ (30-50ms)
for _ in range(20):
detector.add_latency_sample(35 + (hash(str(_)) % 15))
# ตรวจจับ - ควรปกติ
is_anomaly, msg, z = detector.detect_latency_anomaly()
print(f"Normal check: anomaly={is_anomaly}, z={z:.2f}")
# เพิ่ม outlier (500ms)
detector.add_latency_sample(500)
# ตรวจจับอีกครั้ง - ควรพบความผิดปกติ
is_anomaly, msg, z = detector.detect_latency_anomaly()
print(f"Outlier check: anomaly={is_anomaly}, z={z:.2f}, msg={msg}")
# ทดสอบ rate anomaly
is_anomaly, msg = detector.detect_rate_anomaly(current_rate=100)
is_anomaly, msg = detector.detect_rate_anomaly(current_rate=250) # เพิ่ม 2.5 เท่า
print(f"Rate check: anomaly={is_anomaly}, msg={msg}")
การส่ง Alert และการแจ้งเตือน
ระบบ Alert ที่ดีต้องมีความยืดหยุ่นและเชื่อถือได้ ผมแนะนำให้ส่งแจ้งเตือนหลายช่องทางพร้อมกันเพื่อให้มั่นใจว่าจะไม่พลาดสิ่งสำคัญ
ระบบ Alert และการแจ้งเตือน
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import httpx
class AlertManager:
"""
จัดการการแจ้งเตือนหลายช่องทาง
รองรับ: Email, LINE Notify, Slack, Webhook
"""
def __init__(self, config: dict):
self.config = config
self.alert_history = []
def send_alert(self, anomaly_type: str, severity: str, message: str, data: dict = None):
"""ส่งการแจ้งเตือนไปยังทุกช่องทางที่กำหนด"""
alert = {
"timestamp": datetime.now().isoformat(),
"type": anomaly_type,
"severity": severity,
"message": message,
"data": data
}
self.alert_history.append(alert)
# เก็บเฉพาะ 100 รายการล่าสุด
if len(self.alert_history) > 100:
self.alert_history.pop(0)
# กำหนดว่าจะส่งไปช่องทางไหนตาม severity
if severity == "critical":
self._send_all_channels(alert)
elif severity == "high":
self._send_critical_channels(alert)
elif severity == "medium":
self._send_medium_channels(alert)
def _send_all_channels(self, alert):
"""ส่งไปทุกช่องทาง"""
if "email" in self.config:
self._send_email(alert)
if "line_notify" in self.config:
self._send_line_notify(alert)
if "slack" in self.config:
self._send_slack(alert)
if "webhook" in self.config:
self._send_webhook(alert)
def _send_critical_channels(self, alert):
"""ส่งไปช่องทางสำคัญ"""
if "email" in self.config:
self._send_email(alert)
if "line_notify" in self.config:
self._send_line_notify(alert)
def _send_medium_channels(self, alert):
"""ส่งไปช่องทางที่ไม่ฉุกเฉิน"""
if "webhook" in self.config:
self._send_webhook(alert)
def _send_email(self, alert):
"""ส่งอีเมลแจ้งเตือน"""
if "email" not in self.config:
return
email_config = self.config["email"]
msg = MIMEMultipart()
msg['From'] = email_config["from"]
msg['To'] = ", ".join(email_config["to"])
msg['Subject'] = f"[{alert['severity'].upper()}] API Alert: {alert['type']}"
body = f"""
🚨 API Alert Detected
| Type: | {alert['type']} |
| Severity: | {alert['severity']} |
| Message: | {alert['message']} |
| Time: | {alert['timestamp']} |
{f'{json.dumps(alert.get("data", {}), indent=2)}' if alert.get('data') else ''}
"""
msg.attach(MIMEText(body, 'html'))
try:
with smtplib.SMTP(email_config["smtp_server"], email_config["smtp_port"]) as server:
server.starttls()
server.login(email_config["username"], email_config["password"])
server.send_message(msg)
print(f"Email alert sent successfully")
except Exception as e:
print(f"Failed to send email: {e}")
def _send_line_notify(self, alert):
"""ส่ง LINE Notify"""
if "line_notify" not in self.config:
return
emoji = "🔴" if alert["severity"] == "critical" else "🟠" if alert["severity"] == "high" else "🟡"
message = f"""
{emoji} API Alert
━━━━━━━━━━━━━━━
Type: {alert['type']}
Severity: {alert['severity']}
Message: {alert['message']}
Time: {alert['timestamp']}
"""
try:
response = httpx.post(
"https://notify-api.line.me/api/notify",
headers={"Authorization": f"Bearer {self.config['line_notify']['token']}"},
data={"message": message}
)
if response.status_code == 200:
print("LINE Notify sent successfully")
except Exception as e:
print(f"Failed to send LINE Notify: {e}")
def _send_slack(self, alert):
"""ส่ง Slack webhook"""
if "slack" not in self.config:
return
color = "danger" if alert["severity"] == "critical" else "warning" if alert["severity"] == "high" else "good"
payload = {
"attachments": [{
"color": color,
"title": f"API Alert: {alert['type']}",
"text": alert["message"],
"fields": [
{"title": "Severity", "value": alert["severity"], "short": True},
{"title": "Time", "value": alert["timestamp"], "short": True}
]
}]
}
try:
response = httpx.post(self.config["slack"]["webhook_url"], json=payload)
if response.status_code == 200:
print("Slack message sent successfully")
except Exception as e:
print(f"Failed to send Slack message: {e}")
def _send_webhook(self, alert):
"""ส่ง generic webhook"""
if "webhook" not in self.config:
return
try:
response = httpx.post(
self.config["webhook"]["url"],
json=alert,
headers=self.config["webhook"].get("headers", {})
)
print(f"Webhook sent, status: {response.status_code}")
except Exception as e:
print(f"Failed to send webhook: {e}")
ตัวอย่างการใช้งาน
if __name__ == "__main__":
alert_manager = AlertManager({
# "email": {
# "from": "[email protected]",
# "to": ["[email protected]"],
# "smtp_server": "smtp.gmail.com",
# "smtp_port": 587,
# "username": "your-email",
# "password": "your-password"
# },
# "line_notify": {
# "token": "your-line-notify-token"
# },
"webhook": {
"url": "https://your-webhook-endpoint.com/alerts"
}
})
# ทดสอบการส่ง alert
alert_manager.send_alert(
anomaly_type="error_rate",
severity="high",
message="Error rate exceeded 5% threshold",
data={"error_rate": 0.08, "total_requests": 1000, "errors": 80}
)
การรวมทุกอย่างเข้าด้วยกัน
หลังจากมีทุกส่วนประกอบแล้ว มาดูการนำมารวมกันเป็นระบบ ho ูมแบบครบวงจรที่พร้อมใช้งานจริง
ระบบ ho ูมสมบูรณ์ - API Traffic Monitor
import threading
import time
import schedule
class APITrafficMonitor:
"""
ระบบมอนิเตอร์การใช้งาน AI API แบบครบวงจร
ใช้ HolySheep AI เป็น API provider
"""
def __init__(self, api_key: str):
self.collector = APITrafficCollector(api_key)
self.detector = AnomalyDetector()
self.alert_manager = None # ตั้งค่าหลังจากนี้
self.is_running = False
self.monitoring_thread = None
# เก็บสถิติเพิ่มเติม
self.minute_requests = 0
self.last_minute_check = time.time()
def set_alert_manager(self, config: dict):
"""ตั้งค่า Alert Manager"""
self.alert_manager = AlertManager(config)
def start(self):
"""เริ่มการทำงานของระบบมอนิเตอร์"""
self.is_running = True
self.monitoring_thread = threading.Thread(target=self._monitoring_loop)
self.monitoring_thread.daemon = True
self.monitoring_thread.start()
print("API Traffic Monitor started successfully")
def stop(self):
"""หยุดการทำงาน"""
self.is_running = False
if self.monitoring_thread:
self.monitoring_thread.join(timeout=5)
print("API Traffic Monitor stopped")
def _monitoring_loop(self):
"""ลูปหลักสำหรับการมอนิเตอร์"""
# ตรวจสอบทุก 5 วินาที
schedule.every(5).seconds.do(self._check_anomalies)
# สรุปรายงานทุก 1 นาที
schedule.every(1).minutes.do(self._generate_report)
while self.is_running:
schedule.run_pending()
time.sleep(1)
def _check_anomalies(self):
"""ตรวจสอบความผิดปกติ"""
stats = self.collector.get_stats()
# คำนวณ request rate
current_time = time.time()
time_diff = current_time - self.last_minute_check
if time_diff >= 1:
current_rate = self.minute_requests / time_diff
self.minute_requests = 0
self.last_minute_check = current_time
total_requests = sum(s["count"] for s in stats["models"].values())
total_errors = sum(s["errors"] for s in stats["models"].values())
# ตรวจจับความผิดปกติ
report = self.detector.get_comprehensive_report(
current_rate=current_rate * 60, # requests per minute
total_requests=total_requests,
errors=total_errors
)
# ส่ง alert หากพบความผิดปกติ
if report["anomalies"] and self.alert_manager:
for anomaly in report["anomalies"]:
self.alert_manager.send_alert(
anomaly_type=anomaly["type"],
severity=anomaly["severity"],
message=anomaly["message"],
data=report
)
def _generate_report(self):
"""สร้างรายงานสรุป"""
stats = self.collector.get_stats()
print("\n" + "="*50)
print("API Traffic Report")
print("="*50)
print(f"Total Requests: {stats['total_requests']}")
print(f"Models: {json.dumps(stats['models'], indent=2)}")
if stats['recent_errors']:
print(f"Recent Errors: {len(stats['recent_errors'])}")
def test_api_connection(self):
"""ทดสอบการเชื่อมต่อ API"""
try:
response = self.collector.make_request(
model="gpt-4.1",
messages=[{"role": "user", "content": "Hello"}]
)
print("API connection test successful!")
print(f"Response: {response.get('choices', [{}])[0].get('message', {}).get('content', 'N/A')}")
return True
except Exception as e:
print(f"API connection test failed: {e}")
return False
การใช้งานจริง
if __name__ == "__main__":
# สร้าง monitor instance
api_key = "YOUR_HOLYSHEEP_API_KEY" # แทนที่ด้วย API key จริง
monitor = APITrafficMonitor(api_key)
# ตั้งค่า alert
monitor.set_alert_manager({
"webhook": {
"url": "https://your-server.com/alerts"
}
})
# ทดสอบการเชื่อมต่อ
if monitor.test_api_connection():
# เริ่มการมอนิเตอร์
monitor.start()
# รัน 5 นาทีแล้วหยุด (สำหรับทดสอบ)
# ในการใช้งานจริง ปิด comment บรรทัดด้านล่าง
# time.sleep(300)
# monitor.stop()