在 Phoenix 中构建人工标注与自动评估的反馈闭环

介绍在 Phoenix 中为支持代理的追踪数据建立质量反馈闭环的方法,包括在界面创建标注配置并人工标注、从运行代码获取 span ID 以回传用户反馈,以及用代码检查与 LLM 评估器对工具调用和检索结果做自动评估。

我们的支援代理正在运行, 并且追踪正在流入凤凰城。 我们可以看到每个 LLM 的呼叫、 工具执行和检索。 用户仍然在抱怨。 有些答复很有帮助, 其他答复完全错误。 我们需要一种方法来衡量质量, 而不仅仅是观察活动。 在本章中, 您会学会 - **用人类的反馈记录痕迹**这让我们来给你的痕迹贴上标签,找出你需要改进的地方。 - **获取应用程序中的用户反应**当用户抱怨时,请将反馈附在您的数据中,并用它来改进。 - **运行自动 LLM 即时法官评价以查找失败之处模式**。使用 LLM 将您的分析缩放到数千个痕迹上,以便您能够建立信心和数据驱动的对需要改进之处的分析。 **跟随代码** 在整个教程中,我们将包括关键代码片段,但为了看到全面执行,请检查下面的配套项目. ## TypeScript 教学 附带可运行示例的 TypeScript 项目 ## Python 教学 附带可运行示例的 Python 工程 ## 2.1 人类在UI中的说明 在将任何东西自动化之前,我们需要知道“好”的外观。 单判的答案是否比详细段落更好呢?当它无济于事时,代理人是否应该道歉? 这取决于我们的用户、品牌和我们的使用案例。人类的注释就是我们如何建立这种理解。我们通过手动审查痕迹并标记其为好、坏或介于两者之间的某处,来创建 **地面事实** - 我们也会开始注意模式:或许代理商会与多部分的问题纠缠在一起,或者当用户引用先前的消息时会感到困惑。 ## 创建注释配置 导航到 **设置 − 说明** 在凤凰城创建注释类型。 我们将创建一个简单的配置, 为我们的客服智能体标记有用性。 下面是不同注释配置的解析 。 | 类型 | 示例 | 使用大小写 | | --- | --- | --- | | 分类 | `correct` / `incorrect` | 是/否或多类标签 | | 连续 | 1 - 5规模,0 - 100% | 数字分数 | | 自由格式 | 任何文本 | 不限成员名额的说明 | ## 在 UI 中作注释 打开跟踪 ~ 点击 **注释** – 填写表格。 一旦我们有注解的痕迹,我们就可以用注解值过滤,导出到数据集,并在注解者之间进行比较。 即使是50的注解良好的痕迹也比猜想数周更能教你失败模式。 ## 2.2 程序说明(用户反馈) 手动笔记会告诉你真实情况, 但是它没有尺度。 我们可以每天检讨50的痕迹, 但你的经纪人正在处理上千个对话。 有时, 我们的用户已经告诉你什么是有效的。 每一次拇指上下, “ 这没有帮助 ” 点击, 或者升级到人类代理人就是反馈。 让我们将反馈存储在凤凰城, 这样我们就可以把它附在我们的痕迹上 。让我们模拟一下拇指上下图案,然后在凤凰城存储它,作为我们痕迹的注释。 这将给我们衡量我们的用户的特征。 ## 从运行代码中获取 Span ID 要将反馈附加到一个跟踪中, 您需要跨度 ID 。 以下是如何捕捉它 : - TypeScript - Python 键 ``` import { trace } from "@opentelemetry/api"; async function handleSupportQuery(userQuery: string) { return tracer.startActiveSpan("support-agent", async (span) => { // Capture the span ID for later feedback const spanId = span.spanContext().spanId; // ... process query ... return { response: "Your order has shipped!", spanId, // Return this to your frontend }; }); } ``` ``` from opentelemetry import trace def handle_support_query(user_query: str): tracer = trace.get_tracer("support-agent") with tracer.start_as_current_span("support-agent") as agent_span: # Capture the span ID for later feedback span_id = format_span_id(agent_span.get_span_context().span_id) # ... process query ... return { "query": user_query, "response": response, "spanId": span_id, } ``` 在网络应用程序中,您会返回 `spanId` ,然后在用户单击拇指向上/向下移动时将其发回。 ## 通过 Phoenix 客户端日志反馈 安装凤凰客户端 : - TypeScript - Python 键 ``` npm install @arizeai/phoenix-client ``` ``` pip install arize-phoenix-client ``` 然后日志注释 : - TypeScript - Python 键 ``` import { logSpanAnnotations } from "@arizeai/phoenix-client/spans"; // When user clicks thumbs up await logSpanAnnotations({ spanAnnotations: [{ spanId: "abc123...", // The span ID from your response name: "user_feedback", label: "thumbs-up", score: 1, annotatorKind: "HUMAN", metadata: { source: "web_app", userId: "user_456", }, }], sync: true, }); ``` ``` from phoenix.client.resources.spans import SpanAnnotationData from phoenix.client import Client phoenix_client = Client() # When user clicks thumbs up, store the annotation annotations = [] if answer in ["y", "1", "yes"]: annotations.append( SpanAnnotationData( name="user_feedback", span_id=resp["spanId"], annotator_kind="HUMAN", result={"label": "thumbs-up", "score": 1.0}, metadata={"category": resp["category"], "source": "interactive_tutorial"}, ) ) phoenix_client.spans.log_span_annotations( span_annotations=annotations, sync=False, ) ``` 追踪支援代理, 我们让你对追踪提供反馈, 并将说明推向凤凰城: 在代理生成回复后, - 输入 `y` 用于拇指提升(良好反应) - 输入 `n` 用于缩略图( 不良反应) - 输入 `s` 跳过 您的反馈以注解形式发送给凤凰城。 请检查 **说明** 选项卡,以查看您的收视率。 ## 2.3 LLM-as-Judge 评价 我们收集了用户的反馈,并找出了哪些反应是无益的。 现在我们需要了解 *为什么* 失败 。 工具调用返回错误吗 ? 检索是否不相关 ? 您不用手动点击每个无益的线索, 也可以自动分析。 我们将创建两个评估器, 一个用于我们 `lookupOrderStatus` 工具,以及另一个用于 FAQ 检索相关性。这些评估人员会注释孩子的跨度,因此,当你点击一个无益的跟踪时,可以立即看到出了什么问题。 ## 安装 Phoenix Evals 软件包 - TypeScript - Python 键 ``` npm install @arizeai/phoenix-evals ``` ``` pip install arize-phoenix-evals ``` ## 工具结果评价员 工具调用成功还是返回错误? 这是简单的基于代码的检查 : - TypeScript - Python 键 ``` // Filter for tool spans const toolSpans = spans.filter((span) => span.name === "ai.toolCall"); for (const span of toolSpans) { const spanId = span.context.span_id; const output = JSON.stringify(span.attributes["output.value"] || ""); // Simple check: does the output contain "error" or "not found"? const hasError = output.toLowerCase().includes("error") || output.toLowerCase().includes("not found"); const status = hasError ? "❌ ERROR" : "✅ SUCCESS"; console.log(` Tool span ${spanId.substring(0, 8)}... ${status}`); annotations.push({ spanId, name: "tool_result", label: hasError ? "error" : "success", score: hasError ? 0 : 1, explanation: hasError ? "Tool returned an error or 'not found' response" : "Tool executed successfully", annotatorKind: "LLM" as const, // Using "LLM" for consistency, though this is code-based metadata: { evaluator: "tool_result", type: "code", }, }); } ``` ``` import json from phoenix.client.resources.spans import SpanAnnotationData # Filter for tool spans (lookupOrderStatus) tool_spans = [span for span in spans if span.get("name") == "lookupOrderStatus"] # Tool Result Evaluator - code-based check tool_annotations = [] for span in tool_spans: # Access span_id from context context = span.get("context", {}) span_id = context.get("span_id", "") if isinstance(context, dict) else "" # Access attributes (may be a dict or JSON string) attributes = span.get("attributes", {}) if isinstance(attributes, str): attributes = json.loads(attributes) output_value = attributes.get("output.value", "") # Simple check: does the output contain "error" or "not found"? output_str = json.dumps(output_value) if not isinstance(output_value, str) else output_value has_error = "error" in output_str.lower() or "not found" in output_str.lower() tool_annotations.append( SpanAnnotationData( name="tool_result", span_id=span_id, annotator_kind="CODE", result={"label": "error" if has_error else "success", "score": 0.0 if has_error else 1.0}, metadata={ "evaluator": "tool_result", "type": "code", }, ) ) ``` ## 检索相关性评价员 检索到的上下文是否与问题有关? - TypeScript - Python 键 ``` import { createClassificationEvaluator } from "@arizeai/phoenix-evals"; import { openai } from "@ai-sdk/openai"; // Filter for the LLM calls that use retrieved context const llmSpans = spans.filter((span) => span.name === "ai.generateText" && String(span.attributes["gen_ai.system"] || "").includes("Answer the user's question using ONLY the information provided in the context below. Be friendly and concise.") ); // Create an LLM-as-Judge evaluator that determines if retrieved context was relevant const retrievalRelevanceEvaluator = createClassificationEvaluator({ name: "retrieval_relevance", model: openai("gpt-4o-mini"), choices: { relevant: 1, irrelevant: 0, }, promptTemplate: `You are evaluating whether the retrieved context is relevant to answering the user's prompt. Classify the retrieval as: - RELEVANT: The context contains information that directly helps answer the question - IRRELEVANT: The context does NOT contain useful information for the question You are comparing the "Context" object and the "prompt" object. [Context and Prompt]: {{input}} `, }); // Evaluate each RAG span for (const span of llmSpans) { const spanId = span.context.span_id; // Extract the system prompt (which contains the retrieved context) const input = span.attributes["input.value"] as string || ""; const result = await retrievalRelevanceEvaluator.evaluate({ input: input, }); const status = result.label === "relevant" ? "✅ RELEVANT" : "❌ IRRELEVANT"; console.log(` RAG span ${spanId.substring(0, 8)}... ${status}`); // Add annotation to be logged to Phoenix annotations.push({ spanId, name: "retrieval_relevance", label: result.label, score: result.score, explanation: result.explanation, annotatorKind: "LLM", metadata: { model: "gpt-4o-mini", evaluator: "retrieval_relevance", }, }); ``` ``` import json from phoenix.evals import LLM, ClassificationEvaluator from phoenix.client.resources.spans import SpanAnnotationData # Filter for retrieval spans (RETRIEVER kind) - FAQ retrieval retrieval_spans = [ span for span in spans if span.get("span_kind") == "RETRIEVER" or span.get("name") == "faq-retrieval" ] # Create an LLM-as-Judge evaluator that determines if retrieved context was relevant llm = LLM(provider="openai", model="gpt-4o-mini") retrieval_relevance_evaluator = ClassificationEvaluator( name="retrieval_relevance", prompt_template="""You are evaluating whether the retrieved context is relevant to answering the user's prompt. Classify the retrieval as: - RELEVANT: The context contains information that directly helps answer the question - IRRELEVANT: The context does NOT contain useful information for the question You are comparing the "Context" object and the "prompt" object. [Context and Prompt]: {input}""", llm=llm, choices={"relevant": 1, "irrelevant": 0}, ) # Evaluate each retrieval span rag_annotations = [] for span in retrieval_spans: # Access span_id from context context = span.get("context", {}) span_id = context.get("span_id", "") if isinstance(context, dict) else "" # Access attributes (may be a dict or JSON string) attributes = span.get("attributes", {}) if isinstance(attributes, str): attributes = json.loads(attributes) # Logic to extract the query and retrieved documents here # Build input for evaluator: query + retrieved context context_text = "\n\n".join(documents) evaluation_input = f"Query: {query}\n\nRetrieved Context:\n{context_text}" result = retrieval_relevance_evaluator.evaluate({"input": evaluation_input}) score_result = result[0] if isinstance(result, list) else result rag_annotations.append( SpanAnnotationData( name="retrieval_relevance", span_id=span_id, annotator_kind="LLM", result={ "label": score_result.label, "score": score_result.score if hasattr(score_result, "score") else (1.0 if score_result.label == "relevant" else 0.0), }, metadata={ "model": "gpt-4o-mini", "evaluator": "retrieval_relevance", }, ) ) ``` ## 日志评价到凤凰城 教程中完整的评价脚本处理两个评价员. - TypeScript - Python 键 ``` await logSpanAnnotations({ spanAnnotations: annotations, sync: false, // async mode - Phoenix processes in background }); ``` ``` all_eval_annotations = tool_annotations + rag_annotations phoenix_client.spans.log_span_annotations( span_annotations=all_eval_annotations, sync=False, ) ``` ## 运行评价脚本 ## 完成 TypeScript 教学 使用“% 1” 运行评价脚本 `pnpm evaluate` ## 完整 Python 教程 这将: 1. 从凤凰城获取工具和 RAG 跨度 2. 每项评价: - 工具跨度:成功与错误(基于代码的检查) - 检索跨度:无关(基于LLM) 3. 记录结果作为关于孩子跨度的说明 ## 调试工作流程 现在你有一个完整的调试工作流程: 1. **运行代理** (`pnpm start`和提供反馈(上下调) 2. **运行评价** (`pnpm evaluate`(a) 说明儿童的跨度 3. **点击到无益的痕迹** 在凤凰城 4. **请检查孩子的间隔说明 :** - `tool_result = error` 命令没有找到 - `retrieval_relevance = irrelevant` — FAQ不在知识库中 这完全告诉你了 *为什么* 追踪失败, 不只是 *那个* 例如, 我们可以看到代理给用户一个关于订单号的无益的答案。 我们可以快速检查工具跨度, 看订单号 ORD-99999 完全不在订单数据库中 。 自动电压可以快速地定位我们注释的根部错误, 因为它们可以潜入到跟踪中, 并且比人类更快地跨过数据 ! ## 内容提要 恭喜! 您现在有一个完整的质量反馈循环 : | 步骤 | 做点什么 | 你所学的 | | --- | --- | --- | | **1. 用户反馈** | 答复率为有帮助/无帮助 | 追踪失败 | | **2. 儿童散射Evals** | 运行 `pnpm evaluate` | *为什么* 它们失败( 工具错误 ? 检索失败 ) 。 | | **3. 分析** | 点击到无益的痕迹 | 根原因( 丢失命令, FAQ 不在 KB 中) | | **4. 修补** | 更新提示、知识库或工具 | 改进代理 | 这是调试的工作流程 , 实际缩放 ! 而不是手动审查每个跟踪, 您 : - 使用反馈来识别失败 - 使用自动评价来诊断 - 使用微量细节来了解根源 ## 下一个步骤 您的踪迹现在用人类反馈和自动评价来说明。 您可以识别哪些反应失败并诊断原因。 但还是有一条缺失:真正的客户支持不仅仅是一个查询,而是SupportBot与客户之间的全面对话。“我的订单状况如何? ”接着是“什么时候到? ” ,接着是“我能改变地址吗? ” **届会**让你进入整个客户之旅 不仅仅是孤立的查询 [**继续到3章:会话__.**](<https://arize.com/docs/phoenix/tracing/tutorial/sessions>) 这页有用吗? [建议编辑](<https://github.com/arize-ai/phoenix/edit/main/docs/phoenix/tracing/tutorial/annotations-and-evaluations.mdx>)提出问题

查看原始来源