ๅ่จ #
2026 ๅนด๏ผAI ๅบ็จๅทฒ็ปๅนฟๆณๅบ็จไบ็ไบง็ฏๅขใไฝ AI ๅบ็จๆๅ ถ็ฌ็นๆง๏ผๆจกๅ่พๅบไธ็จณๅฎใๅปถ่ฟ้ซใๆๆฌ้พไปฅ้ขๆตใ
ไผ ็ป็ๅบ็จ็ๆง๏ผAPM๏ผๆ ๆณๆปก่ถณ AI ็ๆง็้ๆฑใๆฌๆไป็ป AI ๅบ็จๅฏ่งๆตๆง็ๆ ธๅฟๆนๆณใ
ไปไนๆฏ AI ๅฏ่งๆตๆง #
ไผ ็ป็ๆง vs AI ็ๆง
| ็ปดๅบฆ | ไผ ็ป็ๆง | AI ็ๆง |
|------|---------|---------|
| ๅปถ่ฟ | HTTP ่ฏทๆฑ่ๆถ | API ่ฐ็จ + ๆจกๅๆจ็่ๆถ |
| ้่ฏฏ็ | 4xx/5xx ็ถๆ็ | ๆ็ปใๅนป่งใๆ ผๅผ้่ฏฏ |
| ๆๆฌ | ๅบๅฎไบ่ตๆบ | Token ๆถ่ๆณขๅจ |
| ่ดจ้ | ๅฏ็ฒพ็กฎๆต้ | ้่ฆ้ขๅค่ฏไผฐ |
AI ๅฏ่งๆตๆงๅๅคงๆฏๆฑ
โโโ Logging๏ผAI ่ฏทๆฑๆฅๅฟ๏ผ
โโโ Metrics๏ผToken ๆถ่ใๅปถ่ฟใๆๆฌ๏ผ
โโโ Tracing๏ผAI ่ฐ็จ้พ่ทฏ่ฟฝ่ธช๏ผ
โโโ Evaluation๏ผ่พๅบ่ดจ้่ฏไผฐ๏ผ
ๆ ธๅฟๆๆ ไฝ็ณป #
1. ๅปถ่ฟๆๆ
import time
from functools import wraps
class AILatencyTracker:
def __init__(self):
self.latencies = []
def track(self, func):
"""่ฃ
้ฅฐๅจ่ฟฝ่ธชๅปถ่ฟ"""
@wraps(func)
async def async_wrapper(*args, **kwargs):
start = time.time()
result = await func(*args, **kwargs)
elapsed = time.time() - start
self.record("success", elapsed)
return result
except Exception as e:
elapsed = time.time() - start
self.record("error", elapsed)
@wraps(func)
def sync_wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
self.record("success", elapsed)
return result
except Exception as e:
elapsed = time.time() - start
self.record("error", elapsed)
import asyncio
if asyncio.iscoroutinefunction(func):
return async_wrapper
return sync_wrapper
def record(self, status: str, latency: float):
self.latencies.append({
"timestamp": time.time(),
"status": status,
"latency_ms": latency * 1000
def get_stats(self) -> dict:
"""่ทๅ็ป่ฎกไฟกๆฏ"""
if not self.latencies:
latencies = [l["latency_ms"] for l in self.latencies]
"count": len(latencies),
"avg_ms": sum(latencies) / len(latencies),
"p50_ms": sorted(latencies)[len(latencies) // 2],
"p95_ms": sorted(latencies)[int(len(latencies) * 0.95)],
"p99_ms": sorted(latencies)[int(len(latencies) * 0.99)],
2. Token ๆถ่ๆๆ
class TokenTracker:
def __init__(self):
self.records = []
self.total_input_tokens = 0
self.total_output_tokens = 0
def record(self, model: str, input_tokens: int, output_tokens: int, cost: float):
"""่ฎฐๅฝ Token ๆถ่"""
self.total_input_tokens += input_tokens
self.total_output_tokens += output_tokens
self.records.append({
"timestamp": time.time(),
"model": model,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"total_tokens": input_tokens + output_tokens,
"cost": cost
def get_daily_cost(self) -> dict:
"""่ทๅๆฏๆฅๆๆฌ"""
today = time.time() - 86400 # 24ๅฐๆถๅ
recent = [r for r in self.records if r["timestamp"] > today]
total_cost = sum(r["cost"] for r in recent)
total_tokens = sum(r["total_tokens"] for r in recent)
"cost_today": total_cost,
"tokens_today": total_tokens,
"avg_cost_per_request": total_cost / len(recent) if recent else 0
def get_model_breakdown(self) -> dict:
"""ๆๆจกๅๅ็ฑป็ป่ฎก"""
breakdown = {}
for r in self.records:
model = r["model"]
if model not in breakdown:
breakdown[model] = {"cost": 0, "tokens": 0, "count": 0}
breakdown[model]["cost"] += r["cost"]
breakdown[model]["tokens"] += r["total_tokens"]
breakdown[model]["count"] += 1
return breakdown
3. ้่ฏฏๅ็ฑป
class AIErrorClassifier:
ERROR_TYPES = {
"rate_limit": {"retry": True, "severity": "medium"},
"auth_error": {"retry": False, "severity": "high"},
"model_error": {"retry": True, "severity": "medium"},
"timeout": {"retry": True, "severity": "low"},
"invalid_request": {"retry": False, "severity": "high"},
"content_filtered": {"retry": False, "severity": "medium"},
@classmethod
def classify(cls, error: Exception) -> dict:
"""ๅ็ฑป้่ฏฏ็ฑปๅ"""
error_str = str(error).lower()
if "429" in error_str or "rate_limit" in error_str:
return {"type": "rate_limit", **cls.ERROR_TYPES["rate_limit"]}
elif "401" in error_str or "auth" in error_str:
return {"type": "auth_error", **cls.ERROR_TYPES["auth_error"]}
elif "500" in error_str or "internal" in error_str:
return {"type": "model_error", **cls.ERROR_TYPES["model_error"]}
elif "timeout" in error_str:
return {"type": "timeout", **cls.ERROR_TYPES["timeout"]}
elif "400" in error_str or "invalid" in error_str:
return {"type": "invalid_request", **cls.ERROR_TYPES["invalid_request"]}
elif "filtered" in error_str or "content" in error_str:
return {"type": "content_filtered", **cls.ERROR_TYPES["content_filtered"]}
return {"type": "unknown", "retry": False, "severity": "high"}
@classmethod
def should_retry(cls, error: Exception) -> bool:
"""ๅคๆญๆฏๅฆๅบ่ฏฅ้่ฏ"""
classification = cls.classify(error)
return classification.get("retry", False)
ๆฅๅฟไฝ็ณป #
็ปๆๅ AI ๆฅๅฟ
import json
import logging
from datetime import datetime
class AILogger:
def __init__(self, log_file: str = "ai_logs.jsonl"):
self.log_file = log_file
self.logger = logging.getLogger("ai")
self.logger.setLevel(logging.INFO)
handler = logging.FileHandler(log_file)
handler.setFormatter(logging.Formatter('%(message)s'))
self.logger.addHandler(handler)
def log_request(self,
request_id: str,
model: str,
prompt: str,
response: str = None,
latency_ms: float = None,
tokens_used: int = None,
cost: float = None,
error: str = None):
"""่ฎฐๅฝ AI ่ฏทๆฑ"""
log_entry = {
"timestamp": datetime.utcnow().isoformat(),
"type": "ai_request",
"request_id": request_id,
"model": model,
"prompt_length": len(prompt),
"response_length": len(response) if response else None,
"latency_ms": latency_ms,
"tokens_used": tokens_used,
"cost": cost,
"error": error,
"success": error is None
self.logger.info(json.dumps(log_entry, ensure_ascii=False))
def log_evaluation(self, request_id: str, quality_score: float, categories: dict):
"""่ฎฐๅฝ่ดจ้่ฏไผฐ็ปๆ"""
log_entry = {
"timestamp": datetime.utcnow().isoformat(),
"type": "quality_evaluation",
"request_id": request_id,
"quality_score": quality_score,
"categories": categories
self.logger.info(json.dumps(log_entry, ensure_ascii=False))
ai_logger = AILogger("ai_production_logs.jsonl")
ai_logger.log_request(
request_id="req_001",
model="gpt-5.4",
prompt="่งฃ้ไปไนๆฏๆบๅจๅญฆไน ",
response="ๆบๅจๅญฆไน ๆฏ...",
latency_ms=250,
tokens_used=1500,
ๆฅๅฟๅๆๆฅ่ฏข
import json
class LogAnalyzer:
def __init__(self, log_file: str):
self.log_file = log_file
def load_logs(self, limit: int = None):
with open(self.log_file, 'r') as f:
for i, line in enumerate(f):
if limit and i >= limit:
logs.append(json.loads(line))
return logs
def get_error_rate(self, hours: int = 24) -> float:
"""่ฎก็ฎ้่ฏฏ็"""
cutoff = datetime.utcnow().timestamp() - hours * 3600
logs = self.load_logs()
recent = [l for l in logs if datetime.fromisoformat(l["timestamp"]).timestamp() > cutoff]
if not recent:
errors = sum(1 for l in recent if not l.get("success", True))
return errors / len(recent)
def get_expensive_requests(self, top_n: int = 10) -> list:
"""่ทๅๆ่ดต็่ฏทๆฑ"""
logs = self.load_logs()
sorted_logs = sorted(
[l for l in logs if l.get("cost")],
key=lambda x: x.get("cost", 0),
reverse=True
return sorted_logs[:top_n]
def get_slow_requests(self, threshold_ms: float = 5000) -> list:
"""่ทๅๆ
ข่ฏทๆฑ"""
logs = self.load_logs()
return [l for l in logs if l.get("latency_ms", 0) > threshold_ms]
่ฟฝ่ธช้พ่ทฏ #
LangChain + OpenTelemetry
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
provider = TracerProvider()
processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
class AIServiceWithTracing:
def __init__(self):
self.llm = OpenAI()
self.vector_db = VectorDB()
@tracer.start_as_current_span("ai_request")
async def process_request(self, user_input: str, user_id: str):
span = trace.get_current_span()
span.set_attribute("user_id", user_id)
span.set_attribute("input_length", len(user_input))
with tracer.start_as_current_span("retrieve_context") as span:
docs = self.vector_db.search(user_input)
span.set_attribute("docs_retrieved", len(docs))
with tracer.start_as_current_span("llm_call") as span:
start = time.time()
response = self.llm.generate(user_input, docs)
span.set_attribute("model", "gpt-5.4")
span.set_attribute("latency_ms", (time.time() - start) * 1000)
span.set_attribute("response_length", len(response))
span.set_attribute("success", True)
return response
except Exception as e:
span.set_attribute("success", False)
span.set_attribute("error", str(e))
่พๅบ่ดจ้่ฏไผฐ #
่ชๅจ่ดจ้่ฏไผฐ
class AIOutputEvaluator:
def __init__(self):
self.llm = OpenAI()
def evaluate(self, prompt: str, response: str) -> dict:
"""่ฏไผฐ่พๅบ่ดจ้"""
evaluation_prompt = f"""
่ฏไผฐไปฅไธ AI ่พๅบ็่ดจ้๏ผ
็จๆท่พๅ
ฅ๏ผ{prompt}
AI ่พๅบ๏ผ{response}
่ฏไผฐ็ปดๅบฆ๏ผๆฏ้กน 1-5 ๅ๏ผ๏ผ
1. ็ธๅ
ณๆง๏ผ่พๅบๆฏๅฆไธ้ฎ้ข็ธๅ
ณ
2. ๅ็กฎๆง๏ผไฟกๆฏๆฏๅฆๆญฃ็กฎ
3. ๅฎๆดๆง๏ผๆฏๅฆๅฎๆดๅ็ญไบ้ฎ้ข
4. ๆธ
ๆฐๅบฆ๏ผ่กจ่พพๆฏๅฆๆธ
ๆฐๆ่ฏป
5. ๅฎๅ
จๆง๏ผๆฏๅฆๆไธๅฝๅ
ๅฎน
"relevance": 4,
"accuracy": 5,
"completeness": 4,
"clarity": 5,
"safety": 5,
"overall_score": 4.6,
"issues": ["้ฎ้ข1", "้ฎ้ข2"],
"suggestions": ["ๅปบ่ฎฎ1", "ๅปบ่ฎฎ2"]
result = self.llm.generate(evaluation_prompt)
return json.loads(result)
return {"error": "่ฏไผฐ่งฃๆๅคฑ่ดฅ", "raw": result}
def batch_evaluate(self, requests: list) -> list:
results = []
for req in requests:
evaluation = self.evaluate(req["prompt"], req["response"])
results.append({
"request_id": req["id"],
**evaluation
return results
def detect_hallucination(self, response: str, context: str) -> dict:
detection_prompt = f"""
ๆฃๆตไปฅไธๅ็ญๆฏๅฆๅญๅจๅนป่ง๏ผ็ผ้ ไธๅญๅจ็ไฟกๆฏ๏ผ๏ผ
ไธไธๆ/่ๆฏ๏ผ{context}
AI ๅ็ญ๏ผ{response}
1. ๆฏๅฆๆๅ
ทไฝไบๅฎ๏ผไบบๅใๆฅๆใๆฐๅญ๏ผ้่ฆ้ช่ฏ
2. ่ฟไบไบๅฎๆฏๅฆๅจไธไธๆไธญ
3. ๆฏๅฆๆๆๆพ็ผ้ ็ๅ
ๅฎน
"has_hallucination": true/false,
"confidence": 0.85,
"risky_content": ["ๅ
ทไฝๅฏ็ๅ
ๅฎน"],
"reason": "ๅคๆญ็็ฑ"
result = self.llm.generate(detection_prompt)
return json.loads(result)
return {"has_hallucination": False, "confidence": 0}
Prometheus ็ๆง้ขๆฟ #
ๆๆ ๅฏผๅบ
from prometheus_client import Counter, Histogram, Gauge, generate_latest
REQUEST_COUNT = Counter(
'ai_requests_total',
'Total AI requests',
['model', 'status']
REQUEST_LATENCY = Histogram(
'ai_request_latency_seconds',
'AI request latency',
TOKEN_USAGE = Counter(
'ai_tokens_used_total',
'Total tokens used',
['model', 'type'] # type: input/output
COST_USAGE = Counter(
'ai_cost_total',
'Total API cost',
ACTIVE_REQUESTS = Gauge(
'ai_active_requests',
'Number of active requests',
@app.middleware("http")
async def track_requests(request: Request, call_next):
model = request.headers.get("X-Model", "unknown")
ACTIVE_REQUESTS.labels(model=model).inc()
start = time.time()
response = await call_next(request)
latency = time.time() - start
REQUEST_COUNT.labels(model=model, status=response.status_code).inc()
REQUEST_LATENCY.labels(model=model).observe(latency)
ACTIVE_REQUESTS.labels(model=model).dec()
return response
@app.get("/metrics")
def metrics():
return Response(content=generate_latest())
ๅ่ญฆ้ ็ฝฎ #
ๅ ณ้ฎๅ่ญฆ่งๅ
- name: ai_application
- alert: HighAIErrorRate
sum(rate(ai_requests_total{status="error"}[5m]))
sum(rate(ai_requests_total[5m])) > 0.05
severity: critical
annotations:
summary: "AI ่ฏทๆฑ้่ฏฏ็่ถ
่ฟ 5%"
- alert: HighAILatency
histogram_quantile(0.95,
sum(rate(ai_request_latency_seconds_bucket[5m])) by (le)
severity: warning
annotations:
summary: "AI ่ฏทๆฑ P95 ๅปถ่ฟ่ถ
่ฟ 10 ็ง"
- alert: HighAICost
increase(ai_cost_total[1h]) > 100
severity: warning
annotations:
summary: "AI ่ฐ็จๆๆฌๅฐๆถๅข้ฟ่ถ
่ฟ $100"
- alert: AIRateLimit
increase(ai_requests_total{status="429"}[5m]) > 10
severity: warning
annotations:
summary: "AI API ้ๆต้ข็นๅ็"
Grafana ไปช่กจๆฟ #
ๅ ณ้ฎ้ขๆฟ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AI Application Dashboard โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ
โ โ Requests โ โ Error Rate โ โ Avg Latency โ โ
โ โ 12,345 โ โ 2.3% โ โ 1.2s โ โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Token Usage Over Time โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Cost by Model โ โ
โ โ GPT-5.4: $45.2 (67%) โ โ
โ โ Claude: $22.1 (33%) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Quality Score Distribution โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ๆไฝณๅฎ่ทต #
1. ๆฐๆฎ้ๆ ท
class SamplingLogger:
"""้ๆ ท่ฎฐๅฝ๏ผ้ฟๅ
ๅญๅจๆๆฌ่ฟ้ซ"""
SAMPLE_RATE = 0.1 # 10% ้ๆ ท
def __init__(self):
self.full_logger = AILogger()
self.sample_count = 0
def should_log(self) -> bool:
"""ๅคๆญๆฏๅฆๅบ่ฏฅ่ฎฐๅฝๅฎๆดๆฅๅฟ"""
self.sample_count += 1
if self.sample_count % int(1 / self.SAMPLE_RATE) == 0:
return True
return False
def log(self, entry: dict):
if self.should_log():
self.full_logger.log_request(**entry)
2. ๆๆฌ้ข่ญฆ
class CostAlert:
def __init__(self, threshold_daily: float = 100):
self.threshold_daily = threshold_daily
self.token_tracker = TokenTracker()
def check_and_alert(self):
"""ๆฃๆฅๆๆฌๅนถๅ่ญฆ"""
daily = self.token_tracker.get_daily_cost()
if daily["cost_today"] > self.threshold_daily:
"alert": True,
"message": f"ไปๆฅ AI ๆๆฌ ${daily['cost_today']:.2f} ่ถ
่ฟ้ๅผ ${self.threshold_daily}",
"action": "review_recent_requests"
return {"alert": False}
ๆป็ป #
AI ๅบ็จๅฏ่งๆตๆงๆฏ็ไบง็ฏๅข็ๅฟ ๅค๏ผ
ๅปถ่ฟ่ฟฝ่ธช๏ผP50/P95/P99 ๅปถ่ฟๆๆ ** Token ๆถ่**๏ผๆๆจกๅใๆๆถ้ด็ๆๆฌๅๆ้่ฏฏๅ็ฑป๏ผๅบๅๅฏ้่ฏๅไธๅฏ้่ฏ้่ฏฏ่ดจ้่ฏไผฐ๏ผ่ชๅจ่ฏไผฐ่พๅบ่ดจ้๏ผๆฃๆตๅนป่งๅ่ญฆ้ ็ฝฎ๏ผ้่ฏฏ็ใๅปถ่ฟใๆๆฌๅ่ญฆ
ๆฒกๆๅฏ่งๆตๆง๏ผๅฐฑๆฒกๆ AI ๅบ็จ็็ไบงๆฒป็ใ
ๆฌๆๆฏ AI ๅทฅ็จๅ็ณปๅไนไธใ
This article contains affiliate links. If you sign up through the links above, I may earn a commission at no additional cost to you.
Ready to Build Your AI Business? #
** Get started with Systeme.io for free** โ All-in-one platform for building your online business with AI tools.