AI 编程教程中文版
官方教程中文版SDK 与自定义 Agent

可观测性

说明 Copilot SDK 的 OpenTelemetry 支持、trace context 传播、tool spans 和生产化观测清单。

可观测性(observability)让团队知道 agent 做了什么、调用了什么工具、哪里失败、耗时在哪里。没有 trace 和日志,自定义 agent 不能进入生产流程。

Copilot SDK 支持把 OpenTelemetry 配置到 CLI 进程,并在 SDK 和 CLI 之间传播 W3C Trace Context(W3C 标准的追踪上下文)。这条机制是把"agent 应用"接进现有可观测性栈的关键,而不是另起一套日志系统。

1. 官方能力边界

GitHub 官方 observability 页面说明:

  • SDK 有内置 telemetry 支持。
  • 可以配置 OpenTelemetry 到 CLI process。
  • SDK 和 CLI 之间支持 W3C Trace Context 传播。
  • Outbound 方向可以通过 onGetTraceContext 提供 trace context。
  • Inbound 方向,CLI 调用 tool handler 时,traceparenttracestate 会出现在 ToolInvocation 对象上。
flowchart TD
    App["Your app span"] --> SDK["Copilot SDK"]
    SDK --> CLI["Copilot CLI process"]
    CLI --> Session["Session span"]
    Session --> Tool["Tool invocation"]
    Tool --> Handler["Your tool handler"]
    Handler --> Child["Child span"]
    Child --> Backend["Backend / API / DB"]

    style SDK fill:#dbeafe,stroke:#2563eb,stroke-width:2px
    style Tool fill:#fef3c7,stroke:#d97706,stroke-width:2px
    style Child fill:#dcfce7,stroke:#16a34a,stroke-width:2px

2. 要记录什么

最小观测字段:

  • session id。
  • user id 或 tenant id。
  • model。
  • prompt metadata,不记录原始敏感内容。
  • tool name。
  • tool args 摘要。
  • tool result 状态。
  • duration。
  • error category。
  • trace id。
  • cost 或 request metadata。

不要把原始 prompt、密钥、客户数据、完整文件内容直接打进日志。

3. Trace 怎么用

推荐 span 层级:

  1. HTTP request 或 job span。
  2. SDK session span。
  3. model response span。
  4. tool invocation span。
  5. downstream API / DB span。

这样排障时可以回答:

  • 这次 agent 为什么慢?
  • 哪个 tool 调用失败?
  • 是模型、SDK、CLI、MCP server,还是外部 API 出错?
  • 某个用户或团队是否触发异常用量?

4. 观测和 hooks 要配合

Hooks 捕获事件,OpenTelemetry 负责串 trace。推荐组合:

  • onSessionStart:写入 session metadata 和 trace context。
  • onUserPromptSubmitted:记录 prompt 类型和长度,不记录敏感原文。
  • onPreToolUse:记录工具申请和权限决策。
  • onPostToolUse:记录结果状态、耗时和错误。
  • onErrorOccurred:记录 error category 和降级路径。

5. 上线检查

上线前至少确认:

  • 每个 session 都能查到 trace id。
  • 每个 tool call 都能查到 tool name 和结果状态。
  • 错误有分类,不是只记录 stack trace。
  • 日志已脱敏。
  • 高风险操作能关联到用户和审批。
  • 监控系统能按模型、功能、团队、工具聚合。
深读:可观测性不是事后补日志

Agent 行为是多阶段的:prompt、planning、tool call、MCP、外部 API、response。事后只看最终文本,无法解释中间发生了什么。

生产级 agent 必须在设计时就带 trace,而不是出事故后再 grep 日志。

本章自检

  1. 是否能把一次用户请求追踪到 SDK session?
  2. 是否能定位每个 tool call 的耗时和结果?
  3. 是否避免记录原始敏感内容?
  4. 是否把 hooks 和 trace 串起来?
  5. 是否能区分模型失败、工具失败和外部系统失败?

通过标准:任意一次 agent 执行都能查到 trace、工具调用、错误和成本线索。

官方来源

接下来去哪

本页目录