AgentScope 可观测体系:OpenTelemetry 全链路追踪与 AgentScope Studio 诊断
AgentScope 可观测体系:OpenTelemetry 全链路追踪与 AgentScope Studio 诊断
导读:可观测性是生产级 AI 系统的生命线。AgentScope 基于 OpenTelemetry 标准构建了完整的可观测体系,支持 Trace/Metrics/Logs 三支柱追踪,并提供 AgentScope Studio 可视化诊断平台。本文深入解析全链路追踪维度、调用链路分析和 Thinking Mode 可视化。
一、OpenTelemetry 集成架构
1.1 可观测性三支柱
┌─────────────────────────────────────────────────────────┐ │ AgentScope 可观测体系 │ ├─────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Trace │ │ Metrics │ │ Logs │ │ │ │ - 调用链路 │ │ - 性能指标 │ │ - 结构日志 │ │ │ │ - 分布追踪 │ │ - 资源监控 │ │ - 事件记录 │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ │ │ │ │ │ └─────────────────┴─────────────────┘ │ │ │ │ │ ┌──────▼──────┐ │ │ │ OpenTelemetry│ │ │ │ Exporter │ │ │ └──────┬──────┘ │ │ │ │ │ ┌──────────────────┼──────────────────┐ │ │ ↓ ↓ ↓ │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │ Jaeger │ │ Langfuse│ │ Loki │ │ │ └─────────┘ └─────────┘ └─────────┘ │ │ │ └─────────────────────────────────────────────────────────┘1.2 追踪维度
AgentScope 支持 4 大核心追踪维度:
| 维度 | 追踪内容 | 典型指标 |
|---|---|---|
| LLM 调用 | 输入/输出/Token 消耗/延迟 | latency, token_usage, cost |
| Agent 执行链路 | 推理→工具→响应的完整路径 | agent_duration, tool_calls |
| 工具调用耗时 | 各工具的执行时间 | tool_latency, tool_success_rate |
| 记忆读写 | 记忆的增删改查操作 | memory_read_latency, memory_write_count |
二、配置 OpenTelemetry 追踪
2.1 基础配置
importagentscope# 初始化 OpenTelemetry 追踪agentscope.init(# 启用追踪trace_enabled=True,# OTLP 导出器配置trace_exporter="otlp",trace_endpoint="http://localhost:4318",# 服务信息service_name="my-agent-app",service_version="1.0.0",# 采样率trace_sampler="parent_always",# 100% 采样)# 创建 Agentagent=ReActAgent.builder().name("智能助手").model(gpt4_model).build()# 运行时自动追踪response=agent.run(message="用户问题")2.2 集成第三方平台
Langfuse 集成
agentscope.init(trace_enabled=True,# Langfuse 配置langfuse_public_key="pk-xxx",langfuse_secret_key="sk-xxx",langfuse_host="https://cloud.langfuse.com")Arize Phoenix 集成
agentscope.init(trace_enabled=True,# Phoenix 配置phoenix_endpoint="http://localhost:6006")三、LLM 调用追踪
3.1 完整的 LLM 追踪数据
# Span 数据结构示例{"trace_id":"trace_abc123","span_id":"span_def456","name":"llm.call","attributes":{"llm.provider":"openai","llm.model":"gpt-4","llm.prompt_tokens":150,"llm.completion_tokens":300,"llm.total_tokens":450,"llm.latency_ms":2340,"llm.cost_usd":0.018,"llm.temperature":0.7,"llm.max_tokens":1000},"events":[{"name":"llm.start","timestamp":"2026-03-21T10:00:00Z"},{"name":"llm.end","timestamp":"2026-03-21T10:00:02Z"}]}3.2 自动追踪 LLM 调用
fromagentscope.modelsimportChatModel# 所有 LLM 调用自动追踪model=ChatModel(model_name="gpt-4",api_key="sk-xxx")# 这个调用会被自动追踪response=model.chat(messages=[{"role":"user","content":"你好"}])# 在 Jaeger 中查看# - Trace: LLM 完整调用链# - Span: 单次 LLM 调用# - Attributes: Token 消耗、延迟、成本四、Agent 执行链路追踪
4.1 调用链路可视化
Trace: conversation_001 ┌─────────────────────────────────────────────────────────────┐ │ Span 1: Agent Execution (2000ms) │ │ ├─ Span 1.1: Reasoning (500ms) │ │ │ ├─ Event: thought.start │ │ │ └─ Event: thought.end │ │ ├─ Span 1.2: Tool Call - search_knowledge (800ms) │ │ │ ├─ Span 1.2.1: HTTP Request (600ms) │ │ │ └─ Span 1.2.2: Response Processing (200ms) │ │ ├─ Span 1.3: LLM Generation (700ms) │ │ │ ├─ Attributes: prompt_tokens=200, completion=150 │ │ │ └─ Events: llm.start, llm.end │ │ └─ Span 1.4: Memory Write (50ms) │ │ └─ Attributes: memory_type="short_term", msg_count=1 │ └─────────────────────────────────────────────────────────────┘4.2 追踪 Agent 生命周期
fromagentscope.hooksimportTraceHookclassAgentTraceHook:@TraceHookdeftrace_agent_run(self,agent,run_context):"""追踪 Agent 运行"""# 创建根 Spanroot_span=tracer.start_span("agent.run")withtracer.start_as_current_span("agent.reasoning"):# 推理阶段thought=agent.reason(run_context.message)withtracer.start_as_current_span("agent.tool_execution"):# 工具执行阶段fortool_callinthought.tools:tool_span=tracer.start_span(f"tool.{tool_call.name}")result=agent.toolkit.execute(tool_call)tool_span.end()withtracer.start_as_current_span("agent.response"):# 响应生成阶段response=agent.generate_response(thought,result)root_span.end()returnresponse五、工具调用追踪
5.1 工具调用指标
fromagentscope.toolsimportToolTracer# 启用工具追踪tracer=ToolTracer()# 工具调用自动追踪@tracer.trace_tooldefmy_tool(param:str)->ToolResponse:# 工具执行result=do_something(param)returnToolResponse(content=result)# 追踪数据# - tool.name: 工具名称# - tool.latency_ms: 执行耗时# - tool.success: 是否成功# - tool.error_message: 错误信息(如有)5.2 工具调用统计
fromagentscope.telemetryimportToolMetrics# 收集工具指标metrics=ToolMetrics()# 查询统计stats=metrics.get_tool_stats(tool_name="search_knowledge",time_range="1h")print(f"调用次数:{stats['call_count']}")print(f"平均耗时:{stats['avg_latency_ms']}ms")print(f"成功率:{stats['success_rate']}%")print(f"P95 耗时:{stats['p95_latency_ms']}ms")六、记忆读写追踪
6.1 记忆操作追踪
fromagentscope.memoryimportMemoryTracer# 启用记忆追踪memory_tracer=MemoryTracer()# 记忆操作自动追踪classTracedMemory(Memory):defadd(self,message:Msg):withmemory_tracer.trace_memory_operation("add"):super().add(message)defget(self,**kwargs):withmemory_tracer.trace_memory_operation("get"):returnsuper().get(**kwargs)# 追踪数据# - memory.operation: add/get/delete# - memory.type: short_term/long_term# - memory.latency_ms: 操作耗时# - memory.message_count: 消息数量6.2 记忆性能分析
fromagentscope.telemetryimportMemoryMetrics# 分析记忆性能metrics=MemoryMetrics()# 获取性能报告report=metrics.get_performance_report()print("短期记忆:")print(f" 平均读取延迟:{report['short_term']['avg_read_latency_ms']}ms")print(f" 平均写入延迟:{report['short_term']['avg_write_latency_ms']}ms")print("\n长期记忆:")print(f" 平均检索延迟:{report['long_term']['avg_search_latency_ms']}ms")print(f" 检索准确率:{report['long_term']['accuracy']}%")七、AgentScope Studio 诊断
7.1 项目管理
# 创建项目project=StudioClient.create_project(name="智能客服系统",description="基于 AgentScope 的客服助手",tags=["customer-service","nlp"])# 创建运行记录run=project.create_run(run_name="test_run_001",agent_config={"name":"客服助手","model":"gpt-4"})# 执行 Agentresponse=agent.run(message="用户问题")# 上传运行数据run.upload_trace(trace_data)run.upload_logs(log_data)run.upload_metrics(metric_data)7.2 运行时可视化
Chatbot 交互界面
┌─────────────────────────────────────────────────────────┐ │ AgentScope Studio - 运行时查看 │ ├─────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────────────────────────────────────────┐│ │ │ 实时对话流 ││ │ │ [10:00:00] 用户: 帮我查一下订单状态 ││ │ │ [10:00:01] 思考: 需要调用订单查询工具... ││ │ │ [10:00:02] 工具: query_order(order_id="12345") ││ │ │ [10:00:03] 结果: 订单已发货 ││ │ │ [10:00:04] 助手: 您的订单已发货,预计明天送达 ││ │ └─────────────────────────────────────────────────────┘│ │ │ │ ┌─────────────────────────────────────────────────────┐│ │ │ 流式输出 ││ │ │ 您的订单已发│货,预计明天│送达 ││ │ │ (逐字显示) ││ │ └─────────────────────────────────────────────────────┘│ │ │ └─────────────────────────────────────────────────────────┘7.3 调用链路分析
瀑布图展示
调用链路瀑布图 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Timeline (ms) 0ms ▶ [Agent.run] │ 100ms │ └─ [Reasoning] ████████ 400ms │ 500ms │ └─ [Tool.call.search] ████████████ 800ms │ └─ [HTTP.request] ██████████ 600ms │ └─ [Response.parse] ███ 200ms │ 1300ms│ └─ [LLM.generate] ██████████ 700ms │ ├─ Prompt: 200 tokens │ └─ Completion: 150 tokens │ 2000ms│ └─ [Memory.write] █ 50ms │ 2050ms│ [Agent.run] 完成 总耗时: 2050ms LLM Token: 350 (200 input + 150 output) 工具调用: 1 次关键路径识别
fromagentscope.studioimportTraceAnalyzer# 分析调用链路analyzer=TraceAnalyzer(trace_data)# 识别关键路径critical_path=analyzer.find_critical_path()print("关键路径:")forspanincritical_path:print(f" -{span['name']}:{span['duration_ms']}ms")# 识别性能瓶颈bottlenecks=analyzer.find_bottlenecks()print("\n性能瓶颈:")forbottleneckinbottlenecks:print(f" -{bottleneck['name']}:{bottleneck['duration_ms']}ms")7.4 诊断模式
Thinking Mode 可视化
Thinking Mode - 推理过程可视化 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 1: 用户输入 ┌─────────────────────────────────────────────────────┐ │ 用户: 帮我分析一下这个数据集 │ │ 数据: sales_data_2026.csv (1000 rows) │ └─────────────────────────────────────────────────────┘ Step 2: Agent 推理 ┌─────────────────────────────────────────────────────┐ │ 🤔 思考: │ │ 1. 需要了解数据集的基本结构 │ │ 2. 识别关键指标和趋势 │ │ 3. 生成可视化图表 │ │ │ │ 📊 计划: │ │ - 调用 load_data 读取文件 │ │ - 调用 analyze_stats 计算统计信息 │ │ - 调用 generate_chart 生成图表 │ └─────────────────────────────────────────────────────┘ Step 3: 工具执行 ┌─────────────────────────────────────────────────────┐ │ ✓ load_data: 成功 (120ms) │ │ - 读取 1000 行数据 │ │ - 列: date, product, sales, region │ │ │ │ ✓ analyze_stats: 成功 (450ms) │ │ - 总销售额: ¥1,234,567 │ │ - 平均月销售额: ¥102,880 │ │ - 最高销售额: ¥45,678 (产品A, 3月) │ │ │ │ ✓ generate_chart: 成功 (890ms) │ │ - 生成趋势图: sales_trend.png │ │ - 生成饼图: product_share.png │ └─────────────────────────────────────────────────────┘ Step 4: 最终响应 ┌─────────────────────────────────────────────────────┐ │ 💡 响应: │ │ 已完成数据分析: │ │ 1. 数据集包含 2026 年销售数据(1000 条记录) │ │ 2. 总销售额: ¥1,234,567 │ │ 3. 最佳表现: 产品 A 在 3 月销售额达 ¥45,678 │ │ 4. 生成图表: sales_trend.png, product_share.png │ │ │ │ 📈 建议: │ │ - 产品 A 表现优异,可增加投入 │ │ - 3 月为销售高峰,可提前备货 │ └─────────────────────────────────────────────────────┘ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━异常调用高亮
# 高亮显示异常调用analyzer=TraceAnalyzer(trace_data)# 标记异常analyzer.highlight_errors()# 标记慢调用analyzer.highlight_slow_calls(threshold_ms=1000)# 标记高频调用analyzer.highlight_frequent_calls(count_threshold=10)# 在 Studio 中可视化显示studio.render_trace(analyzer.highlighted_trace)八、实战案例
8.1 性能优化诊断
fromagentscope.telemetryimportPerformanceProfiler# 性能分析profiler=PerformanceProfiler()# 分析报告report=profiler.analyze_trace(trace_data)print("性能瓶颈:")forbottleneckinreport.bottlenecks:print(f" -{bottleneck['name']}: "f"{bottleneck['duration_ms']}ms "f"({bottleneck['impact']}% impact)")# 优化建议print("\n优化建议:")forsuggestioninreport.suggestions:print(f" -{suggestion}")8.2 成本分析
fromagentscope.telemetryimportCostAnalyzer# 成本分析analyzer=CostAnalyzer(trace_data)# LLM 成本llm_cost=analyzer.calculate_llm_cost()print(f"LLM 总成本: ¥{llm_cost['total_cost']:.2f}")print(f" - GPT-4: ¥{llm_cost['by_model']['gpt-4']:.2f}")print(f" - GPT-3.5: ¥{llm_cost['by_model']['gpt-3.5-turbo']:.2f}")# 按功能分类cost_by_feature=analyzer.cost_by_feature()forfeature,costincost_by_feature.items():print(f"{feature}: ¥{cost:.2f}")九、总结
AgentScope 基于 OpenTelemetry 标准构建了完整的可观测体系:
- 三支柱追踪:Trace(调用链路)、Metrics(性能指标)、Logs(结构日志)
- 多维度追踪:LLM 调用、Agent 执行、工具调用、记忆读写
- 第三方集成:Jaeger、Langfuse、Arize Phoenix 等平台支持
- Studio 诊断:运行时可视化、瀑布图分析、Thinking Mode、异常高亮
- 实战价值:性能优化、成本分析、问题诊断
这套可观测体系让 Agent 系统从"黑盒"变为"白盒",为生产部署提供坚实的监控基础。
延伸阅读:
- OpenTelemetry 文档
- AgentScope Studio 文档
- Telemetry 配置指南
