用追踪记录定位AI代理执行链路中的问题

文章介绍如何借助追踪记录排查AI代理的异常行为,例如工具选择、上下文传递、延迟来源和流水线失败环节,并说明追踪可自动记录LLM调用与工具调用,把一次请求中的各项操作归入同一执行树,便于调试。

在构建代理和LLM应用程序时,很难看清引擎盖下到底发生了什么。 即使你设置了一个全面的代理架构,并配有多个提示,描述工具和数据检索,你仍被留下回答如下问题: - 为什么代理商要选择这个工具而不是这个工具? - 当LLM生成该响应时,实际传递到什么上下文? - 所有的时间是从哪里来的 - 是模型,检索,还是别的什么? - 用户得到一个错误的答案,但输油管的哪个步骤失败了? 在这个教程中,只要再多几行代码,你就能监视每个赋予你代理权的LLM呼叫、工具执行和检索操作。 你会学习如何更高效和高效地调试、监测和分析你的代理,把代理从个人项目转变为生产准备的应用程序。 **跟随代码** 在整个教程中,我们将包括关键代码片段,但为了看到全面执行,请检查下面的配套项目. ## TypeScript 教学 附带可运行示例的 TypeScript 项目 ## Python 教学 附带可运行示例的 Python 工程 ## SupportBot 我们这个教程的样本客服智能体: 1. **分类** 收到的查询(命令状态与FAQ) 2. **路线** 向适当的处理者: - **顺序状态**: 使用一个工具查找订单信息, 然后为客户摘要 - **FAQ**: 以嵌入方式搜索一个知识库, 然后使用 RAG 生成一个答案 问题在于我们的用户在抱怨。 反应缓慢,答案错误,但我们不知道为什么。 我们的代理人是一个黑匣子 — — 我们可以看到用户问到什么, 看看代理人是如何回答的, 但我们并没有看到我们代理中实际运行的单个组件。 让我们建立追踪以获得可见度。 ## 建立追踪 首先,安装依赖性并配置OpenTelemetry,向凤凰城发送痕迹. ## 安装依赖关系 - TypeScript - Python 键 ``` npm install ai @ai-sdk/openai @ai-sdk/otel @arizeai/phoenix-otel zod ``` AI SDK v7需要节点.js 22或更新. `@arizeai/phoenix-otel` 捆绑 OpenTelemetry 设置和 `@arizeai/openinference-vercel` 用于凤凰城的跨度处理器,用于翻译 AI SDK 跨度; `@ai-sdk/otel` 发射那些横跨。 ``` pip install "arize-phoenix-otel>=0.16.0" arize-phoenix-client openai openinference-instrumentation-openai numpy ``` `arize-phoenix-otel` **0.16.0+** 需要导入 `SpanAttributes` 和 OpenInference 上下文管理器直接从 `phoenix.otel`。在旧版本中,从 `openinference.instrumentation` 财务报告和财务报告 `openinference.semconv.trace` 换句话说。 ## 开始凤凰城 为了向凤凰发送踪迹,你需要一个凤凰公司的案例运行. - 当地 - 集装箱 - 自我住所 ``` uvx arize-phoenix serve ``` 没有 [数字 :](<https://docs.astral.sh/uv/>)? `pip install arize-phoenix && phoenix serve` 做同样的事情。 [终端设置](<https://arize.com/docs/phoenix/self-hosting/deployment-options/terminal>) 用于定制。 ``` docker run -p 6006:6006 -p 4317:4317 arizephoenix/phoenix:latest ``` 图像发布到 [Docker 枢纽系统](<https://hub.docker.com/r/arizephoenix/phoenix>)。见 [嵌入器](<https://arize.com/docs/phoenix/self-hosting/deployment-options/docker>) 用于卷, PostgreSQL, 以及其他选项。 在自己的基础设施上运行凤凰城, 由 PostgreSQL 支持, 所以痕迹会持续超过单个进程。 一旦凤凰城被共享到团队或环境, 便可以选择这样做 。 [自宿主向导](<https://arize.com/docs/phoenix/self-hosting>) 覆盖 [库伯涅斯](<https://arize.com/docs/phoenix/self-hosting/deployment-options/kubernetes>), [赫尔姆](<https://arize.com/docs/phoenix/self-hosting/deployment-options/kubernetes-helm>), [铁路](<https://arize.com/docs/phoenix/self-hosting/deployment-options/railway>), [AWS CloudFormation](<https://arize.com/docs/phoenix/self-hosting/deployment-options/aws-with-cloudformation>), [谷歌云运行](<https://arize.com/docs/phoenix/self-hosting/deployment-options/google-cloud-run>), [阿苏雷](<https://arize.com/docs/phoenix/self-hosting/deployment-options/azure>),以及 [渲染](<https://arize.com/docs/phoenix/self-hosting/deployment-options/render>),加上认证和配置。 凤凰城在端口服务其UI和OTLP HTTP **6006**,和端口的 OTLP gRPC **4317**。对于一个本地实例, 即 http://localhost:6006 。 在您工作时不要运行 。 现在把申请点到这里: - TypeScript - Python 键 创建一个 `.env` 在工程根中的文件 : ``` PHOENIX_COLLECTOR_ENDPOINT=http://localhost:6006 OPENAI_API_KEY=<ENTER YOUR OPENAI API KEY> ``` ``` import os os.environ["PHOENIX_COLLECTOR_ENDPOINT"] = "http://localhost:6006" os.environ["OPENAI_API_KEY"] = "<ENTER YOUR OPENAI API KEY>" ``` 指向部署与 [认证](<https://arize.com/docs/phoenix/self-hosting/features/authentication>) 启用? 设置 `PHOENIX_COLLECTOR_ENDPOINT` 例如,该部署的OTLP HTTP 追踪URL `https://your-phoenix.example.com/v1/traces`,以及 `PHOENIX_API_KEY` 从它的 API 密钥 **设置** 页面。如果您用 Python 追踪 `register()`,也可以通过 `protocol="http/protobuf"` 一个本地人 `phoenix serve` 不需要钥匙。 ## 配置追踪 - TypeScript - Python 键 创建一个 `instrumentation.ts` 文件 : ``` import { OpenTelemetry } from "@ai-sdk/otel"; import { registerTelemetry } from "ai"; import { register } from "@arizeai/phoenix-otel"; // Register with Phoenix - this handles all the OpenTelemetry boilerplate export const provider = register({ projectName: "support-bot", }); registerTelemetry( new OpenTelemetry({ tracer: provider.getTracer("@arizeai/phoenix-otel/ai-sdk"), headers: false, }) ); ``` 导入此文件到应用程序的顶端, 以便进行追踪 。 设置 `auto_instrument=True` 输入 `register` 函数查看已安装 [OpenInference](<https://github.com/Arize-ai/openinference>) 软件包和自动仪器,所以您不需要为每个库做手动配置 。 ``` from phoenix.otel import register tracer_provider = register( project_name="support-bot", auto_instrument=True ) ``` ## 追踪 LLM 呼叫 每一次LLM呼叫都是决定点。 模型收到什么提示 ? 它输出了什么 ? 它用了多久, 用了多少个符号 ? 没有追踪, 你被迫建立自己的日志或调试, 因此错过了阻碍你完全可观察性的关键数据 。 通过追踪, 你可以得到每个 LLM 交互的完整记录, 包括 - 输入消息( 系统、 用户、 助理即时) - LLM 输出 - 模型名称, 模型提供者 - 引用参数 - 符号计数 - 延迟 对 SupportBot 来说,追踪 LLM 的电话会让我们进入分类阶段。我们会看到我们所有支持查询的确切类别,以及导致该分类的是什么。它也会让我们进入最后生成阶段。最后的输出是如何交付给用户的,以及最终的 LLM 的电话产生了最后的输出的上下文是什么? - TypeScript - Python 键 一旦凤凰网提供商和AI SDK集成在启动时注册,AI SDK的电话会被追踪,没有按呼配置: ``` import { generateText } from "ai"; import { openai } from "@ai-sdk/openai"; const result = await generateText({ model: openai.chat("gpt-4o-mini"), instructions: "Classify the query as 'order_status' or 'faq'", prompt: userQuery, }); ``` 启用仪器时, 电话会自动追踪 : ``` user_query = "Where is my order?" result = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "Classify the query as 'order_status' or 'faq'"}, {"role": "user", "content": user_query}, ], ) ``` **在凤凰城,你会看到:** ## 追踪工具呼叫 工具允许您的代理与数据库、 API 、 外部系统交互。 要深入了解您工具的运行情况, 您需要回答诸如 - LLM是否决定调用正确的工具?. - 它提取的参数正确吗? - 工具还原了你期望的吗? 通过追踪,您可以看到完整的链条,包括LLM的决定,准确的参数通过,以及工具的响应,而无需猜测哪个步骤破裂。 当您的LLM呼叫工具时,这些处决会自动追踪到孩子的长度。 有了凤凰城,您可以看到完整的链条,包括LLM的决定,准确的参数通过,以及工具的反应。 - TypeScript - Python 键 使用 AI SDK,您可以简单地使用 AI SDK 配置来定义您的工具——工具执行会自动追踪: ``` import { generateText, isStepCount, tool } from "ai"; const result = await generateText({ model: openai.chat("gpt-4o-mini"), prompt: userQuery, tools: { lookupOrderStatus: tool({ description: "Look up order status by order ID", inputSchema: z.object({ orderId: z.string(), }), execute: async ({ orderId }) => { // Your tool logic here return orderDatabase[orderId]; }, }), }, stopWhen: isStepCount(2), }); ``` 对于OpenAI Python SDK,您需要一个帮助器功能来执行工具调用,并手动创建跨度来跟踪工具执行. ``` tools = [ # tools defined here ] # Helper function to execute tools def execute_tool_call(tool_call, database): """Execute a tool call and return the result.""" function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) with tracer.start_as_current_span( function_name, attributes={ SpanAttributes.OPENINFERENCE_SPAN_KIND: "TOOL", SpanAttributes.TOOL_NAME: function_name, SpanAttributes.TOOL_PARAMETERS: json.dumps(function_args), SpanAttributes.INPUT_VALUE: json.dumps(function_args), }, ) as tool_span: # Helper function logic here messages = [ { "role": "system", "content": "You are a helpful customer support agent....", }, {"role": "user", "content": user_query}, ] result = client.chat.completions.create( model="gpt-4o-mini", messages=messages, tools=tools, tool_choice="auto", ) message = result.choices[0].message messages.append(message) # Execute tool if called, then get final response if message.tool_calls: for tool_call in message.tool_calls: tool_result = execute_tool_call(tool_call, ORDER_DATABASE) messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(tool_result), }) # Final LLM call with tool result final_result = client.chat.completions.create( model="gpt-4o-mini", messages=messages, ) final_response = final_result.choices[0].message.content else: final_response = message.content ``` **在凤凰城,你会看到:** 1. **LLM 弹簧**: 模型决定调用 `lookupOrderStatus` 2. **工具宽**: 显示工具名称、输入(`orderId`),和产出 3. **LLM 弹簧**:模型总结结果 ## 追踪RAG管道 RAG 管道在许多地方都可能失败。 嵌入可能无法捕捉查询的意图,检索可能返回无关的文档,或者LLM 可能滥用良好的上下文。 当一个用户得到一个错误的答案时,哪个步骤失败了? 通过跟踪,你可以看到整个管道,包括哪些文件被检索,什么上下文被注入到快件中,以及LLM如何使用它。您可以精确确定出错之处。 对于 RAG , 追踪嵌入式呼叫和生成式呼叫 。 `embed` 调用成为自己的跨度 : - TypeScript - Python 键 ``` // Embed the user's query - traced automatically const { embedding } = await embed({ model: openai.embedding("text-embedding-ada-002"), value: userQuery, }); // ... semantic search logic ... // Generate with retrieved context - traced automatically const { text } = await generateText({ model: openai.chat("gpt-4o-mini"), instructions: `Answer using ONLY this context:\n\n${retrievedContext}`, prompt: userQuery, }); ``` ``` # Embed the query - traced automatically embedding_response = client.embeddings.create( model="text-embedding-ada-002", input=user_query ) query_embedding = embedding_response.data[0].embedding # Generate with retrieved context - traced automatically rag_result = client.chat.completions.create( model="gpt-4o-mini", messages=[ { "role": "system", "content": f"You are a helpful customer support agent. Answer the user's question using ONLY the information provided in the context below. Be friendly and concise.\n\nContext:\n{rag_context}", }, {"role": "user", "content": user_query}, ], ) ``` **在凤凰城,你会看到:** 生成跨度显示系统提示中检索到的上下文,这样您就可以立即看到检索是否找到正确的文档 。 ## 与父 Spans 组合操作 单一用户请求可能会触发多个LLM的呼叫、工具执行和检索。让我们将所有这些分配在一个父跨内,这样一个请求的所有操作都会被嵌入在一起。点击父跨内并看到整个执行树:分类、工具调用、检索、生成,都放在一个视图中,可以一目了然地看到时间关系。 整个代理 与分组追踪 [这儿](<https://github.com/Arize-ai/phoenix/tree/main/js/examples/apps/tracing-tutorial/support-agent.ts>). 要将单项请求的所有操作都视为一个跟踪,请使用 OpenTelemetry API 将其包裹在一个父跨 : - TypeScript - Python 键 ``` // trace and SpanStatusCode are re-exported by @arizeai/phoenix-otel, so // no direct dependency on @opentelemetry/api is needed import { trace, SpanStatusCode } from "@arizeai/phoenix-otel"; const tracer = trace.getTracer("support-agent"); async function handleSupportQuery(userQuery: string) { return tracer.startActiveSpan( "support-agent", { attributes: { "openinference.span.kind": "AGENT", "input.value": userQuery } }, async (span) => { try { // All LLM calls, tool executions, and embeddings inside here // will appear as children of this span const result = await processQuery(userQuery); span.setAttribute("output.value", result); span.setStatus({ code: SpanStatusCode.OK }); return result; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR }); throw error; } finally { span.end(); } } ); } ``` ``` from opentelemetry import trace from phoenix.otel import SpanAttributes def handle_support_query(user_query: str) -> AgentResponse: tracer = trace.get_tracer("support-agent") with tracer.start_as_current_span( "support-agent", attributes={ SpanAttributes.OPENINFERENCE_SPAN_KIND: "AGENT", SpanAttributes.INPUT_VALUE: user_query, }, ) as agent_span: try: # All LLM calls, tool executions, and embeddings inside here # will appear as children of this span agent_span.set_attribute(SpanAttributes.OUTPUT_VALUE, result) agent_span.set_status(trace.Status(trace.StatusCode.OK)) return result except Exception as error: agent_span.set_status(trace.Status(trace.StatusCode.ERROR)) raise ``` ## 运行Demo 最终的SupportBot代理将分类器,订单状态工具,和FAQ检索合并为一个代理. 教程代码运行了7针对代理的测试查询: ``` const queries = [ "What's the status of order ORD-12345?", // Order found "How can I get a refund?", // FAQ in knowledge base "Where is my order ORD-67890?", // Order found "I forgot my password", // FAQ in knowledge base "What's the status of order ORD-99999?", // Order NOT found "How do I upgrade to premium?", // FAQ NOT in knowledge base "Can you help me with something?", // Vague request ]; ``` ## 完成 TypeScript 教学 ## 完整 Python 教程 代码可能提示对每个响应的反馈 - 您现在可以跳过这个( 按 : `s`并专注于痕迹。 ## 查看您的追踪 在 http://localhost:6006 打开凤凰城。您会看到 7 `support-agent` 追踪 - 每个查询都有一个。 点击任何跟踪可以看到完整的执行树。 让我们看看两个有趣的案例: ### 追踪1:“你能帮我做点什么吗?” 我们的支持查询分类器给出了以下分类: ``` { "category": "faq", "confidence": "low", "reasoning": "The query is vague and doesn't specify a relevant topic, but it suggests a need for assistance, placing it within a general support context." } ``` 信心: 低度是一个巨大的红旗! 这告诉我们, 我们的支持查询分类器无法自信地对用户的支持查询进行分类, 显示查询可能超出我们代理的权限 。 最后一个跨度显示最相关的上下文检索到 。 ``` Context: Q: How do I reset my password? A: Go to Settings > Security > Reset Password. You'll receive an email with a reset link that expires in 24 hours. Q: How do I update my profile information? A: Go to Account Settings > Profile. You can update your name, email, phone number, and address there. ``` 这种背景与用户的问题完全无关。 因此,我们的痕迹让我们对最后的答案是: ``` I’d be happy to help, but I can only assist with questions related to account settings, passwords, and profile information. Let me know if you need help with those! ``` ### 追踪2: " ORD-99999命令的状况如何? " 我们的支持查询分类器给了我们以下分类: ``` { "category": "order_status", "confidence": "high", "reasoning": "The query directly asks about the status of a specific order, indicating it is related to order tracking." } ``` 我们的分类人员似乎认为这个问题属于我们代理人的范畴。 让我们继续吧。 我们的辅助代理人LLM跨度选择了以下工具调用 : ``` lookupOrderStatus("{\"orderId\":\"ORD-99999\"}") ``` 似乎不错... lookOrderStatus 工具电话给我们: ``` {"error":"Order ORD-99999 not found in our system"} ``` Aha! 看来ORD-99999是无效的订单号! 这就是为什么最后的输出是: ``` Hi there! I checked on your order with the ID ORD-99999, but it seems that I couldn't find any details at the moment. If you could provide me with more information or check back later, I'd be happy to assist you further! ``` ## 内容提要 恭喜你,在这个教程中,你学会了如何: - **追踪 LLM 电话** - 一旦登记追查,自动获取投入、产出、信使和延迟 - **追踪工具呼叫** - 参见工具决定、参数和在儿童期间的反应 - **跟踪RAG管道** - 监视嵌入和查看生成提示中检索到的上下文 - **带有父跨度的组** - 将所有请求的操作跟踪到一个跟踪 - **查看和分析痕迹** - 通过探索凤凰城的行刑树来调试代理行为 ## 下一个步骤 您现在可以在您的应用程序中看到 - 每个 LLM 的呼叫、 工具执行和检索都是可见的。 我们花了一些时间手动分析痕迹 。 但是, 我们如何才能看到 。 **自动化** 我们怎样才能在凤凰城储存这个分析 以便我们造出 **计量** 量度我们的应用? [下个章节](<https://arize.com/docs/phoenix/tracing/tutorial/annotations-and-evaluations>),你会学会: - 标记质量问题的标记痕迹 - 获取用户反馈( thumbs up/ down) 并附在痕迹中 - 运行自动 LLM 即时法官评价以查找失败之处模式 这页有用吗? [建议编辑](<https://github.com/arize-ai/phoenix/edit/main/docs/phoenix/tracing/tutorial/your-first-traces.mdx>)提出问题

查看原始来源