Observability cho Agent: Metrics, tracing và error tracking sản xuất
Giải pháp giám sát AI agent production với OpenTelemetry, Prometheus và Grafana. Theo dõi tool calls, memory I/O và multi-agent handoffs để phát hiện lỗi ngầ...
Agent của bạn có thể trả về HTTP 200, latency dưới 200ms, tiêu tốn hàng nghìn token mỗi phút — và vẫn đang gọi sai API, đọc nhầm dữ liệu của user khác, hoặc lặp vô hạn trong "vòng lặp suy nghĩ" mà không ai hay biết. Đó là giới hạn của monitoring truyền thống khi đối mặt với hệ thống non-deterministic.
Vấn đề
Web service truyền thống là deterministic: cùng một request đi qua cùng một code path, cho ra cùng một output. Health check đơn giản (ping → pong) đủ để xác định hệ thống "sống" hay "chết". Nhưng AI agent là stateful narratives — cùng một prompt có thể dẫn đến 10 quỹ đạo suy nghĩ khác nhau, mỗi quỹ đạo lại gọi các tool khác nhau, truy cập memory khác nhau, và cuối cùng cho ra kết quả đúng hoặc sai một cách ngẫu nhiên.
Vấn nạn silent failure trong agent production:
- Tool hallucination: Agent gọi
delete_user_accountvớiuser_idlà chuỗi rỗng vì parse JSON sai, nhưng API trả về 404 → agent hiểu nhầm là "đã xóa thành công". - Memory staleness: Vector DB đã cập nhật nhưng agent vẫn retrieve bản cũ, trả lời user bằng thông tin lỗi thời.
- Goal drift: Sau 20 bước reasoning, agent quên mất mục tiêu ban đầu, bắt đầu optimize cho metric sai (ví dụ: viết code đẹp thay vì fix bug).
- Cross-user contamination: RAG retrieval nhầm context của user A trong session của user B vì cache key lỗi.
Traditional "three pillars" (logs, metrics, traces) chỉ nhìn thấy biên ngoài: request vào, response ra. Chúng không thể bắt được logic errors bên trong — nơi mà agent "tưởng" mình đang làm đúng nhưng thực chất đang đi lệch hướng từ bước thứ 3.
Ý tưởng cốt lõi
Observability cho agent mở rộng ba trụ cột truyền thống để capture cognitive trajectory — toàn bộ quỹ đạo suy nghĩ gồm tool invocations, memory I/O, branching decisions và sub-agent handoffs. Thay vì hỏi "API có chậm không?", ta hỏi "Agent có đang gọi đúng tool với đúng parameters không?"
Span-Based Execution Graphs
Mỗi bước reasoning của agent là một span trong OpenTelemetry trace. Cấu trúc phân cấp như sau:
Trace: process_refund_request
├── Span: Planning (LLM call)
│ ├── Span: retrieve_policy (tool call)
│ │ └── Span: vector_search (memory I/O)
│ └── Span: validate_order (tool call)
└── Span: Execution (action)
└── Span: send_email (side effect)Khác với microservices nơi span thường là RPC giữa các service, span trong agent là cognitive steps: một lần LLM generation, một lần parse output, một lần gọi Python interpreter. Điều này cho phép reconstruct "thought process" khi debug: nếu kết quả cuối sai, ta trace ngược lên thấy ngay tại sao — ví dụ: retrieve_policy trả về document cũ (stale read) dẫn đến decision sai ở Planning.
Tool-Call Tracing: Chiếu kính vào "tay chân"
Mỗi lần agent quyết định dùng tool, hệ thống ghi lại:
- Selection rationale: Embedding của intent tại thời điểm chọn tool (tại sao chọn
search_ordersthay vìcreate_ticket?) - Argument construction: Raw JSON generated bởi LLM trước khi parse — để bắt hallucinate parameters (ví dụ:
date="next Tuesday"thay vì ISO format) - Raw output: Cả nội dung lỗi từ tool (thường bị LLM summarize sai khi truyền lên context window)
- Retry loops: Số lần thử lại khi tool fail (ẩn tốn token nếu agent stuck trong vòng lặp tự sửa lỗi)
Trong Grafana, bạn có thể vẽ panel tool_error_rate filtered by agent_id và tool_name, phát hiện ngay khi một agent cụ thể bắt đầu "lạm dụng" tool sai cách.
Memory Observability: Chống quên và nhầm
Agent dựa vào vector DB và cache để duy trì context. Ta cần metrics:
- Retrieval relevance score: Cosine similarity giữa query và retrieved chunks — nếu đột ngột giảm, có thể embedding model bị drift hoặc data bị corrupted.
- Staleness detection: Timestamp của retrieved document vs. last update time — phát hiện agent đang đọc "báo cũ".
- Cross-user contamination alerts: Kiểm tra nếu
user_idtrong retrieved memory không khớp vớiuser_idcủa session hiện tại (chỉ khả thi nếu bạn tag span với user context).
Agent-Specific Metrics: Kinh tế học token
Production monitoring cần metrics đặc thù cho agent economy:
- Loop rate: Số iterations (LLM calls) trên một task hoàn thành. Target là dưới 3; nếu trên 5, agent đang "loay hoay" (planning failure).
- Cost-per-successful-task: Tổng chi phí API (input + output tokens) chia cho số task thực sự hoàn thành đúng. Thường cao gấp 3-10 lần cost-per-request thô vì retry loops và tool calls thừa.
- Groundedness score: Tỷ lệ output của agent có citations thực sự xuất hiện trong retrieved context — phát hiện hallucination sớm.
Ví dụ cấu hình Prometheus cho GoClaw agent:
# prometheus.yml
scrape_configs:
- job_name: 'goclaw-agents'
static_configs:
- targets: ['agent-api:8080']
metrics_path: '/metrics'
scrape_interval: 15svà trong code GoClaw (hoặc wrapper), export các custom metrics:
agentToolErrorRate := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "agent_tool_errors_total",
Help: "Total tool errors by agent and tool",
},
[]string{"agent_id", "tool_name"},
)Tại sao nó hoạt động
Phát hiện lỗi propagation: Trong hệ thống agent, lỗi lan truyền theo cấp số nhân. Một retrieval sai ở bước 3 dẫn đến reasoning sai ở bước 5, rồi hallucinate ở bước 8. Traditional logging chỉ thấy lỗi ở bước 8. Span-based tracing cho phép root cause analysis bằng cách nhìn thấy toàn bộ chain.
Economic optimization: Metrics cost-per-successful-task giúp bạn trade-off giữa accuracy và chi phí. Có thể phát hiện rằng agent dùng GPT-4 cho tất cả các bước (kể cả trivial ones) đang đốt 80% budget vào các task con đơn giản — từ đó optimize bằng routing logic (dùng GPT-3.5 cho sub-tasks dễ).
Backpressure và circuit breaking: Khi loop_rate của một agent instance vượt ngưỡng, có thể trigger circuit breaker để ngăn agent "điên" tiêu tốn token vô hạn. Observability không chỉ để "xem" mà để hành động.
Non-determinism management: Vì agent là stochastic, bạn không thể "replay" để reproduce bug. Trace là artifact duy nhất cho phép forensic analysis — giống như black box của máy bay.
Trade-offs:
- Cardinality explosion: Một request user có thể sinh ra 50-100 spans (tool calls, memory lookups, LLM generations). Với 1000 concurrent agents, đây là "million traces per minute" problem — cần tail-based sampling (chỉ giữ 100% trace của requests bị lỗi, sampling 1% của requests healthy).
- Latency overhead: Structured logging và span creation thêm 10-50ms mỗi bước. Với real-time voice agents, đây là vấn đề — cần async fire-and-forget telemetry.
- Storage cost: Trace của agent rất "nặng" vì chứa full prompts và completions. Cần retention policy ngắn (3-7 ngày) cho raw data, aggregate metrics dài hạn.
Ý nghĩa thực tế
| Tiêu chí | Traditional APM | Agent Observability |
|---|---|---|
| Đơn vị giám sát | HTTP request | Agent trajectory (nhiều LLM turns) |
| Success metric | Status 200 | Task completion + groundedness score |
| Latency focus | TTFB (Time To First Byte) | Time To First Token vs Total Loop Time |
| Error detection | Exception thrown | Tool misuse, memory staleness, goal drift |
| Cost tracking | Request count | Cost-per-successful-task |
Case study thực chiến:
Một team deploy GoClaw trên Kubernetes với HPA (Horizontal Pod Autoscaler). Thay vì scale theo CPU/memory, họ scale theo agent_queue_depth và average_loop_rate. Khi loop_rate trung bình vượt quá 5 (agent đang struggle), hệ thống tự động scale thêm pod — không phải vì CPU cao, mà vì "cognitive load" cao.
Multi-agent handoffs: Khi Agent A (Router) handoff sang Agent B (Executor) qua A2A protocol, trace context được truyền qua OpenTelemetry Baggage. Điều này cho phép trace xuyên suốt qua nhiều agent, thấy được rằng lỗi xuất phát từ việc Router truyền sai context chứ không phải Executor thực thi sai.
Limitations không thể giải quyết:
- Observability không phải Interpretability: Bạn thấy agent chọn tool X, nhưng không thấy tại sao LLM quyết định vậy (attention weights không export được).
- State reconstruction: Bạn thấy retrieved documents, nhưng không thấy chính xác "mental state" của LLM (context window compression, attention patterns).
- Debugging paradox: Chính việc thêm telemetry có thể làm thay đổi hành vi agent (Heisenberg effect) hoặc làm chậm hệ thống đến mức timeout.
Đào sâu hơn
Tài liệu chính thức:
- OpenTelemetry Instrumentation for AI Agents — Chuẩn trace propagation cho multi-agent systems.
- LangSmith Documentation — Platform chuyên biệt cho LLM observability với trajectory visualization.
- Braintrust Agent Observability — Best practices về cost tracking và evals integration.
Cùng cụm: Production Deployment:
Deploy bằng Docker Compose
Thiết lập Prometheus + Grafana cùng agent stack trong docker-compose.yml
Performance Tuning
Goroutine pool và connection pooling để agent chịu tải monitoring overhead
Disaster Recovery
Backup trace history và replay trajectories cho post-mortem analysis
Đọc tiếp:
Kiến trúc Memory nâng cao
Hiểu sâu memory architecture để thiết kế metrics đúng
Agent Teams Architecture
Trace propagation qua multi-agent handoffs và shared context
Hooks Overview
Dùng 25+ lifecycle hooks để inject telemetry không làm chậm agent loop
Deploy trên Kubernetes: Scaling agent fleet — Khi một container không đủ
Từ docker-compose singleton đến K8s fleet: Cách triển khai agent fleet hàng nghìn instance với GitOps, HPA tự động scale và quản lý vòng đời agent trên Kuber...
Performance Tuning: Goroutine pool, connection pooling, caching — Tối ưu agent runtime cho 10,000 concurrent tool calls
Tuning goroutine pool, connection pooling và caching để agent platform xử lý 10,000 concurrent tool calls không crash. Từ sync.Pool đến HTTP/2 connection reuse.