👁️ Agent Observability(Agent可观测性)详解

"世界上有一种Agent,它跑起来像个黑盒——你不知道它在想什么,不知道它在做什么,直到它突然崩溃。Observability就是让黑盒变成玻璃盒..."

Agent Observability 是监控、追踪、理解 AI Agent 行为的能力集合。当 Agent 在后台自主执行任务时,如何知道它在干什么?出了问题如何调试?答案就是 Observability

🎯 核心问题

可观测性三支柱

📝 Logs 日志

记录离散事件

Agent 的每一次思考、每一个决策、每一次工具调用。

"10:32:15 调用 web_search 搜索 'OpenClaw教程'"

🔗 Traces 追踪

记录请求路径

从用户输入到最终输出的完整链条,包括所有子步骤。

"用户提问 → 搜索 → 读取 → 总结 → 回复"

📊 Metrics 指标

记录聚合数据

成功率、延迟、Token消耗、成本等可量化指标。

"过去1小时:成功率 98%,平均延迟 2.3s"

为什么 Agent 特别需要 Observability?

1. 行为不可预测

传统软件有确定的执行路径,Agent 的行为由 LLM 决定,充满不确定性。

// 传统软件
function processOrder(order) {
  validateOrder(order);    // 确定执行
  calculateTotal(order);   // 确定执行
  submitPayment(order);    // 确定执行
}

// Agent
async function handleUserRequest(request) {
  // Agent 自己决定:
  // - 需要调用什么工具?
  // - 调用多少次?
  // - 什么顺序?
  // - 什么时候结束?
  
  // 这些都是不确定的,需要 Observability 来理解
}

2. 调试困难

Agent 失败时,原因可能在任何地方:

没有完整的 Trace,调试如同大海捞针。

3. 成本敏感

Agent 调用 LLM 产生成本,需要监控:

// 成本相关指标
const costMetrics = {
  totalTokens: 125000,
  promptTokens: 85000,
  completionTokens: 40000,
  estimatedCost: 2.50,     // 美元
  
  breakdown: {
    planning: 0.30,
    toolCalling: 1.20,
    reasoning: 0.80,
    generation: 0.20
  }
};

Trace 结构详解

Span 体系

// 一个完整的 Trace 由多个 Span 组成
{
  "traceId": "tr-20260421-001",
  "spans": [
    {
      "spanId": "span-1",
      "name": "agent.session",
      "startTime": "2026-04-21T04:00:00.000Z",
      "endTime": "2026-04-21T04:00:15.000Z",
      "duration": 15000,
      "attributes": {
        "agent.id": "miaoquai-ops",
        "session.id": "sess-123"
      },
      "events": [
        {
          "name": "user.input",
          "timestamp": "2026-04-21T04:00:00.100Z",
          "attributes": { "text": "生成一篇AI新闻日报" }
        }
      ]
    },
    {
      "spanId": "span-2",
      "parentSpanId": "span-1",
      "name": "tool.web_search",
      "startTime": "2026-04-21T04:00:01.000Z",
      "endTime": "2026-04-21T04:00:03.000Z",
      "duration": 2000,
      "attributes": {
        "query": "AI news 2026",
        "results_count": 10
      }
    },
    {
      "spanId": "span-3",
      "parentSpanId": "span-1",
      "name": "llm.generation",
      "startTime": "2026-04-21T04:00:04.000Z",
      "endTime": "2026-04-21T04:00:12.000Z",
      "duration": 8000,
      "attributes": {
        "model": "claude-3-opus",
        "input_tokens": 500,
        "output_tokens": 2000
      }
    }
  ]
}

Trace 可视化

时间线视图:

|─────|─────|─────|─────|─────|─────|─────|─────|─────|─────|─────|
0s    1s    2s    3s    4s    5s    6s    7s    8s    9s    10s

[====== agent.session (0-15s) ======]
  [= web_search =]     [= llm.generation ========]
      (1-3s)                  (4-12s)
  [= web_fetch =]
      (3-4s)

OpenClaw Observability 实战

1. Session History 追踪

// 查看会话历史
const history = await sessions_history({
  sessionKey: "sess-123",
  limit: 100,
  includeTools: true  // 包含工具调用记录
});

// 历史记录包含
// - 用户消息
// - Agent 响应
// - 工具调用及结果
// - 时间戳

2. Session Status 监控

// 查看会话状态
const status = await session_status({
  sessionKey: "sess-123"
});

// 返回
{
  "usage": {
    "totalTokens": 125000,
    "promptTokens": 85000,
    "completionTokens": 40000
  },
  "duration": "15m 32s",
  "cost": {
    "estimated": 2.50,
    "currency": "USD"
  },
  "model": "tencentcodingplan/tc-code-latest",
  "reasoning": "off"
}

3. Subagent 监控

// 列出子 Agent
const subagents = await subagents({
  action: "list",
  recentMinutes: 30
});

// 每个子 Agent 的状态
[
  {
    "id": "sub-001",
    "status": "running",
    "startedAt": "2026-04-21T04:00:00Z",
    "task": "生成新闻日报"
  },
  {
    "id": "sub-002", 
    "status": "completed",
    "startedAt": "2026-04-21T03:00:00Z",
    "completedAt": "2026-04-21T03:05:00Z",
    "task": "SEO页面生成"
  }
]

4. Cron 任务监控

// 查看 cron 任务执行记录
const runs = await cron({
  action: "runs",
  jobId: "marketing-glossary-pages"
});

// 执行历史
[
  {
    "runId": "run-001",
    "startTime": "2026-04-21T04:00:00Z",
    "endTime": "2026-04-21T04:05:00Z",
    "status": "success",
    "duration": 300000
  },
  {
    "runId": "run-002",
    "startTime": "2026-04-20T20:00:00Z", 
    "status": "failed",
    "error": "DuckDuckGo rate limited"
  }
]

关键指标定义

性能指标

指标 描述 告警阈值
Latency P50 50% 请求的响应时间 < 5s
Latency P99 99% 请求的响应时间 < 30s
Time to First Token 首个 Token 输出时间 < 2s
Tool Call Latency 工具调用平均时间 < 3s

质量指标

指标 描述 告警阈值
Success Rate 任务成功率 > 95%
Error Rate 错误率 < 5%
Retry Rate 重试率 < 10%
User Satisfaction 用户满意度(反馈) > 4.0/5

成本指标

const costDashboard = {
  daily: {
    totalCost: 150.00,       // 美元
    tokenUsage: 7500000,
    avgCostPerSession: 0.15,
    avgCostPerRequest: 0.02
  },
  
  breakdown: {
    byAgent: {
      "miaoquai-ops": 80.00,
      "hr-assistant": 40.00,
      "knowledge-manager": 30.00
    },
    byOperation: {
      "planning": 20.00,
      "toolCalling": 60.00,
      "reasoning": 50.00,
      "generation": 20.00
    }
  },
  
  alerts: {
    "dailyBudget": { limit: 200, current: 150, percentUsed: 75 },
    "hourlySpike": { threshold: 20, current: 8, triggered: false }
  }
};

调试场景实战

场景:Agent 任务卡住

// 1. 查看 Trace 发现卡在工具调用
const trace = await getTrace("tr-20260421-001");
// 发现: web_fetch 卡了 60 秒没有返回

// 2. 检查工具状态
const toolStatus = await checkTool("web_fetch");
// 发现: 目标网站超时

// 3. 解决方案
// - 添加超时配置
// - 设置 fallback 机制

const newConfig = {
  tools: {
    web_fetch: {
      timeout: 10000,  // 10秒超时
      fallback: "web_search"  // 失败时用搜索替代
    }
  }
};

场景:成本异常飙升

// 1. 查看成本分布
const costs = await analyzeCosts({ period: "24h" });
// 发现: 某个 Agent 的 reasoning 成本是其他 Agent 的 10 倍

// 2. 深入分析
const traces = await getTraces({ 
  agentId: "expensive-agent",
  sortBy: "cost",
  limit: 10 
});
// 发现: 该 Agent 的 reasoning 模式开启了 verbose

// 3. 解决方案
await updateAgent("expensive-agent", {
  thinking: "off"  // 关闭详细推理
});
"Observability 不是监控 Agent 是否活着,而是理解 Agent 是否在正确地思考。它是开发者的眼睛,让不可见的思维过程变得可见..."