cd /news/artificial-intelligence/ai-2026ai ยท home โ€บ topics โ€บ artificial-intelligence โ€บ article
[ARTICLE ยท art-4181] src=dev.to โ†— pub= topic=artificial-intelligence verified=true sentiment=ยท neutral

AI 2026AI

In 2026, AI applications are widely deployed in production but present unique challenges such as unstable model outputs, high latency, and unpredictable costs, which traditional application performance monitoring (APM) cannot address. The article introduces core methods for AI application observability, including logging, metrics (token consumption, latency, cost), tracing, and evaluation, and provides Python code examples for tracking AI latency, token usage, and classifying AI-specific errors.

read7 min views18 publishedMay 20, 2026

ๅ‰่จ€ #

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.

โ”€โ”€ more in #artificial-intelligence 4 stories ยท sorted by recency
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain โ€” perfect for shipping the agent you just read about.

$git push zahid main
โ†’ Live at https://your-agent.zahid.host โœ“
Get free account โ†’ Pricing
from โ‚ฌ0/mo ยท no card required
LIVE [news/ai-2026ai] indexed:0 read:7min 2026-05-20 ยท โ€”