AgentScope 可观测体系:OpenTelemetry 全链路追踪与 AgentScope Studio 诊断

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, costAgent 执行链路推理→工具→响应的完整路径agent_duration, tool_calls工具调用耗时各工具的执行时间tool_latency, tool_success_rate记忆读写记忆的增删改查操作memory_read_latency, memory_write_count二、配置 OpenTelemetry 追踪2.1 基础配置importagentscope# 初始化 OpenTelemetry 追踪agentscope.init(# 启用追踪trace_enabledTrue,# OTLP 导出器配置trace_exporterotlp,trace_endpointhttp://localhost:4318,# 服务信息service_namemy-agent-app,service_version1.0.0,# 采样率trace_samplerparent_always,# 100% 采样)# 创建 AgentagentReActAgent.builder().name(智能助手).model(gpt4_model).build()# 运行时自动追踪responseagent.run(message用户问题)2.2 集成第三方平台Langfuse 集成agentscope.init(trace_enabledTrue,# Langfuse 配置langfuse_public_keypk-xxx,langfuse_secret_keysk-xxx,langfuse_hosthttps://cloud.langfuse.com)Arize Phoenix 集成agentscope.init(trace_enabledTrue,# Phoenix 配置phoenix_endpointhttp://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 调用自动追踪modelChatModel(model_namegpt-4,api_keysk-xxx)# 这个调用会被自动追踪responsemodel.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_tokens200, completion150 │ │ │ └─ Events: llm.start, llm.end │ │ └─ Span 1.4: Memory Write (50ms) │ │ └─ Attributes: memory_typeshort_term, msg_count1 │ └─────────────────────────────────────────────────────────────┘4.2 追踪 Agent 生命周期fromagentscope.hooksimportTraceHookclassAgentTraceHook:TraceHookdeftrace_agent_run(self,agent,run_context):追踪 Agent 运行# 创建根 Spanroot_spantracer.start_span(agent.run)withtracer.start_as_current_span(agent.reasoning):# 推理阶段thoughtagent.reason(run_context.message)withtracer.start_as_current_span(agent.tool_execution):# 工具执行阶段fortool_callinthought.tools:tool_spantracer.start_span(ftool.{tool_call.name})resultagent.toolkit.execute(tool_call)tool_span.end()withtracer.start_as_current_span(agent.response):# 响应生成阶段responseagent.generate_response(thought,result)root_span.end()returnresponse五、工具调用追踪5.1 工具调用指标fromagentscope.toolsimportToolTracer# 启用工具追踪tracerToolTracer()# 工具调用自动追踪tracer.trace_tooldefmy_tool(param:str)-ToolResponse:# 工具执行resultdo_something(param)returnToolResponse(contentresult)# 追踪数据# - tool.name: 工具名称# - tool.latency_ms: 执行耗时# - tool.success: 是否成功# - tool.error_message: 错误信息(如有)5.2 工具调用统计fromagentscope.telemetryimportToolMetrics# 收集工具指标metricsToolMetrics()# 查询统计statsmetrics.get_tool_stats(tool_namesearch_knowledge,time_range1h)print(f调用次数:{stats[call_count]})print(f平均耗时:{stats[avg_latency_ms]}ms)print(f成功率:{stats[success_rate]}%)print(fP95 耗时:{stats[p95_latency_ms]}ms)六、记忆读写追踪6.1 记忆操作追踪fromagentscope.memoryimportMemoryTracer# 启用记忆追踪memory_tracerMemoryTracer()# 记忆操作自动追踪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# 分析记忆性能metricsMemoryMetrics()# 获取性能报告reportmetrics.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 项目管理# 创建项目projectStudioClient.create_project(name智能客服系统,description基于 AgentScope 的客服助手,tags[customer-service,nlp])# 创建运行记录runproject.create_run(run_nametest_run_001,agent_config{name:客服助手,model:gpt-4})# 执行 Agentresponseagent.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_id12345) ││ │ │ [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# 分析调用链路analyzerTraceAnalyzer(trace_data)# 识别关键路径critical_pathanalyzer.find_critical_path()print(关键路径:)forspanincritical_path:print(f -{span[name]}:{span[duration_ms]}ms)# 识别性能瓶颈bottlenecksanalyzer.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 月为销售高峰,可提前备货 │ └─────────────────────────────────────────────────────┘ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━异常调用高亮# 高亮显示异常调用analyzerTraceAnalyzer(trace_data)# 标记异常analyzer.highlight_errors()# 标记慢调用analyzer.highlight_slow_calls(threshold_ms1000)# 标记高频调用analyzer.highlight_frequent_calls(count_threshold10)# 在 Studio 中可视化显示studio.render_trace(analyzer.highlighted_trace)八、实战案例8.1 性能优化诊断fromagentscope.telemetryimportPerformanceProfiler# 性能分析profilerPerformanceProfiler()# 分析报告reportprofiler.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# 成本分析analyzerCostAnalyzer(trace_data)# LLM 成本llm_costanalyzer.calculate_llm_cost()print(fLLM 总成本: ¥{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_featureanalyzer.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 配置指南