为什么Agent需要可观测性?

传统软件的行为是确定性的——同样输入产生同样输出。但Agent的行为由LLM驱动,具有随机性和非确定性。这使得Agent系统更需要完善的可观测性——才能知道Agent"在做什么"、“为什么这么做”、“花了多少钱”。

可观测性三大支柱

1. 日志(Logging)

记录Agent每一步的行为:

{
  "timestamp": "2026-07-16T10:00:01.234Z",
  "session_id": "sess_abc123",
  "agent": "research_agent",
  "action": "tool_call",
  "tool": "web_search",
  "input": {"query": "AI芯片市场2025"},
  "output": {"results": 5, "top_result": "..."},
  "duration_ms": 1234,
  "tokens": {"input": 25, "output": 0},
  "cost_usd": 0.0001,
  "status": "success"
}

日志设计原则:

  • 结构化(JSON而非纯文本)
  • 可关联(session_id + step_id)
  • 可过滤(level, agent, tool等字段)
  • 采样策略(全量记录关键步骤,采样记录调试信息)

2. 指标(Metrics)

量化Agent运行状态:

业务指标:

  • 任务成功率
  • 用户满意度(评分/反馈)
  • 平均完成时间
  • 平均步数

技术指标:

  • LLM调用延迟(p50/p95/p99)
  • 工具调用延迟
  • Token消耗量
  • API错误率
  • 每任务成本

资源指标:

  • GPU利用率
  • 内存占用
  • 并发会话数
  • 队列深度

3. 追踪(Tracing)

记录一次完整任务的全链路:

Trace: sess_abc123
├── Span 1: task_planning (1.2s)
   ├── LLM call: gpt-4 (0.8s, 500 tokens)
   └── Output: [search, analyze, report]
├── Span 2: web_search (0.6s)
   ├── tool: search_api
   └── Result: 5 items
├── Span 3: content_analysis (2.1s)
   ├── LLM call: gpt-4 (1.8s, 2000 tokens)
   └── Output: analysis_summary
├── Span 4: report_generation (1.5s)
   ├── LLM call: gpt-4 (1.2s, 1500 tokens)
   └── Output: final_report.md
Total: 5.4s, 4000 tokens, $0.06

监控架构

数据采集层

# Agent执行包装器
class TracedAgent:
    def __init__(self, agent, tracer):
        self.agent = agent
        self.tracer = tracer
    
    @trace
    async def run(self, input_data):
        with self.tracer.span("agent_run") as span:
            span.set_attr("input", input_data)
            
            result = await self.agent.run(input_data)
            
            span.set_attr("output", result)
            span.set_attr("tokens", self.agent.total_tokens)
            span.set_attr("cost", self.agent.total_cost)
            
            return result
    
    @trace
    async def call_tool(self, tool, args):
        with self.tracer.span("tool_call") as span:
            span.set_attr("tool", tool.name)
            span.set_attr("args", args)
            
            start = time.time()
            result = await tool.run(args)
            duration = time.time() - start
            
            span.set_attr("duration_ms", duration * 1000)
            span.set_attr("result", result)
            
            return result

数据存储层

数据类型存储方案保留期
日志Elasticsearch / Loki30天
指标Prometheus / InfluxDB90天
追踪Jaeger / Tempo7天
会话记录PostgreSQL / MongoDB按需

可视化层

实时仪表盘:

  • 当前活跃Agent数
  • 实时延迟分布
  • 错误率趋势
  • 成本趋势

会话回放:

  • 选择某个会话
  • 逐步回放Agent的每一步操作
  • 查看输入、输出、思考过程
  • 用于调试和优化

异常检测

常见异常模式

  1. 无限循环:Agent反复执行相同操作

    • 检测:连续N步操作相同
    • 处理:强制中断并通知
  2. 成本飙升:单次任务消耗异常多token

    • 检测:单任务token > 历史均值3σ
    • 处理:自动暂停,等待人工审核
  3. 工具滥用:频繁调用同一工具但无进展

    • 检测:同一工具调用次数 > 阈值
    • 处理:限制工具调用频率
  4. 输出质量下降:LLM输出变得不连贯

    • 检测:困惑度异常高
    • 处理:降低temperature或终止

自动告警

alerts:
  - name: high_error_rate
    condition: error_rate > 5%
    duration: 5m
    action: pager_duty
  
  - name: cost_anomaly
    condition: cost_per_task > 2x average
    action: slack_notification
  
  - name: agent_loop
    condition: same_action_count > 5
    action: auto_terminate
  
  - name: latency_spike
    condition: p99_latency > 30s
    duration: 10m
    action: email

成本分析

Token成本追踪

class CostTracker:
    def __init__(self):
        self.costs = []
    
    def record(self, model, input_tokens, output_tokens):
        prices = {
            "gpt-4": {"input": 0.03, "output": 0.06},
            "gpt-4o": {"input": 0.005, "output": 0.015},
            "claude-3.5": {"input": 0.003, "output": 0.015}
        }
        
        price = prices[model]
        cost = (input_tokens * price["input"] + 
                output_tokens * price["output"]) / 1000
        
        self.costs.append({
            "model": model,
            "cost": cost,
            "timestamp": datetime.now()
        })
        return cost

成本优化

  • 模型路由:简单任务用小模型,复杂任务用大模型
  • 缓存:相同prompt的结果缓存复用
  • Prompt优化:减少不必要的context
  • 批处理:合并多个请求

调试工具

会话回放

遇到问题时,回放特定会话:

  1. 加载会话日志
  2. 按步骤重现执行过程
  3. 检查每步的输入/输出
  4. 定位问题发生的具体步骤

对比分析

A/B测试不同配置:

  • 同一批测试用例
  • 不同Prompt/模型/参数
  • 比较成功率、质量、成本

归因分析

当任务失败时:

失败原因分析:
1. LLM推理错误? → 检查LLM输出
2. 工具调用失败? → 检查工具返回
3. 流程逻辑错误? → 检查编排逻辑
4. 数据质量问题? → 检查输入数据

总结

可观测性不是可选项——它是Agent系统的生产必备基础设施。没有可观测性的Agent就像一个黑盒——出了问题不知道为什么,表现好也不知道怎么复现。通过完善的日志、指标、追踪三大支柱,加上异常检测和成本分析,才能构建真正可信赖、可维护、可优化的Agent系统。