@arizeai/phoenix-evals:用 TypeScript 构建 LLM 评估器与分类指标评估体系
可观测性AI 评测LLMOpsAI 应用人工智能【免费下载链接】phoenixAI Observability Evaluation项目地址https://gitcode.com/gh_mirrors/phoenix13/phoenix点击查看免费下载本指南围绕 Phoenix 开源仓库中的 TypeScript 评估库arizeai/phoenix-evalsjs/packages/phoenix-evals/README.md展开。该库提供一套框架无关vendor agnostic的 TypeScript 评估方案既能用createClassifier与预置 LLM 评估器完成幻觉检测、相关性评分、工具调用等分类任务也能用纯确定性的代码评估器计算 precision / recall / F-beta 等分类指标还能通过bindEvaluator将任意数据形状映射到评估器输入并与arizeai/phoenix-client深度集成跑实验。读完本文你将掌握在 Node.js 项目中安装、配置并实际运行这些评估器的完整方法以及它们背后的源码实现原理。安装与运行环境# or yarn, pnpm, bun, etc... npm install arizeai/phoenix-evals该包基于 AI SDK v7package.json 中依赖ai: ^7.0.107而 AI SDK v7 是 ESM-only 的因此对运行环境有明确要求Node.js 22.12 或更高版本package.json的engines字段明确声明node: 22.12CommonJS 构建依赖对 ESM 的require()。必须搭配 AI SDK v7 兼容的模型提供方包例如ai-sdk/openaiv4README 中示例使用的openai(gpt-4o-mini)即来自该包。仓库的 devDependencies 中还使用了ai-sdk/google说明 Google 等模型同样可接入。包通过exports字段暴露了多个子路径入口按功能模块划分清晰arizeai/phoenix-evals/llmLLM 评估器、arizeai/phoenix-evals/code代码评估器、arizeai/phoenix-evals/template模板工具、arizeai/phoenix-evals/helpers辅助函数等。后续示例均按这些子路径导入。评估器的统一抽象Evaluator 与 EvaluationResult在深入具体 API 之前先理解库的底层抽象。所有评估器无论 LLM 还是代码类型都继承自 EvaluatorBase核心字段定义在 src/types/evals.tsname评估器产生的指标名称例如correctness、faithfulness。kind评估类型取值为LLM或CODE。optimizationDirection指标优化方向MAXIMIZE越大越好、MINIMIZE越小越好或NEUTRAL。inputMapping可选的输入映射用于把待评估数据重映射为评估器期望的形状。telemetry遥测配置。所有评估器统一实现evaluate(example): PromiseEvaluationResult返回的EvaluationResult结构为interface EvaluationResult { score?: number; // 评分如 0.95 label?: string; // 标签如 correct explanation?: string; // 模型给出的解释 metadata?: Recordstring, unknown; // 额外信息如评估模型的标签概率 }LLMEvaluatorsrc/llm/LLMEvaluator.ts在构造时自动注入kind: LLM而代码类评估器则标记为CODE。这一统一抽象是后续所有用法的基础——无论是预置评估器、自定义分类器还是代码指标评估器最终都以{ label?, score?, explanation? }的形式产出结果可直接接入实验与可视化流程。自定义分类器createClassifiercreateClassifier是库中从零定义评估任务的核心入口适用于幻觉检测、相关性评分以及任意二分类/多分类场景。它接受model、choices标签到分数的映射和promptTemplate提示词模板三个关键参数import { createClassifier } from arizeai/phoenix-evals/llm; import { openai } from ai-sdk/openai; const model openai(gpt-4o-mini); const promptTemplate In this task, you will be presented with a query, a reference text and an answer. The answer is generated to the question based on the reference text. The answer may contain false information. You must use the reference text to determine if the answer to the question contains false information, if the answer is a hallucination of facts. Your objective is to determine whether the answer text contains factual information and is not a hallucination. A hallucination refers to an answer that is not based on the reference text or assumes information that is not available in the reference text. Your response should be a single word: either factual or hallucinated, and it should not include any other text or characters. [BEGIN DATA] ************ [Query]: {{input}} ************ [Reference text]: {{reference}} ************ [Answer]: {{output}} ************ [END DATA] Is the answer above factual or hallucinated based on the query and reference text? ; // Create the classifier const evaluator await createClassifier({ model, choices: { factual: 1, hallucinated: 0 }, promptTemplate: promptTemplate, }); // Use the classifier const result await evaluator({ output: Arize is not open source., input: Is Arize Phoenix Open Source?, reference: Arize Phoenix is a platform for building and deploying AI applications. It is open source., }); console.log(result); // Output: { label: hallucinated, score: 0 }完整的可运行示例见 examples/classifier_example.ts。createClassifier 的底层实现从源码看createClassifierFn 是createClassifier背后的工厂函数其执行链路清晰模板渲染把待评估记录如{ input, output, reference }作为模板变量调用formatTemplate渲染出最终提示词。标签提取通过choicesToLabels取出choices的所有 key 作为合法标签集合若choices为空会直接抛出No choices provided错误。LLM 分类调用generateClassification让模型在标签集合中选一个。分数映射score choices[classification.label]把模型输出的标签映射回你定义的分数如factual - 1、hallucinated - 0最终返回{ score, ...classification }含 label 与 explanation。而 generateClassification 中对常规语言模型会使用 AI SDK 的generateObject并配合 zod 定义输出结构const result await generateObject({ model, schema: z.object({ explanation: z.string(), // 先让模型用自然语言推理再给出标签 label: z.enum(labels), }), telemetry: telemetryOptions, allowSystemInMessages: true, // 允许模板中包含 system 消息 ...prompt, });这意味着每个分类结果天然附带explanation推理说明和label两个字段。若传入的是 AI SDK 的evaluation model例如 TypeSafe 的 Jev一种不能生成文本、只能做分类的模型则自动改走experimental_evaluate路径把渲染后的提示词作为评估状态、把标签作为单选题选项此时不返回explanation而是通过metadata返回probabilities各标签概率与modelId。遥测默认开启telemetry?.isEnabled ?? true每次分类都会通过 OpenInference 协议发出 span便于后续在 Phoenix 中追踪分析。预置 LLM 评估器开箱即用的分类任务库内置了一批针对常见评估任务的预置评估器均自带优化过的提示词可直接搭配任意 AI SDK 模型使用。它们统一从arizeai/phoenix-evals/llm模块导出EvaluatorFunctionDescriptionFaithfulnesscreateFaithfulnessEvaluator检测幻觉——检查输出是否 grounded 在给定上下文中CompletenesscreateCompletenessEvaluator检查对话中每个活跃的用户请求是否都被真正完成ConcisenesscreateConcisenessEvaluator评估回复是否足够简洁CorrectnesscreateCorrectnessEvaluator检查输出在给定输入下是否事实正确Retrieval RelevancecreateRetrievalRelevanceEvaluator衡量检索到的信息与请求的相关性RefusalcreateRefusalEvaluator检测模型是否拒绝作答Tool InvocationcreateToolInvocationEvaluator评估是否正确调用了工具且参数正确Tool SelectioncreateToolSelectionEvaluator检查是否为任务选择了正确的工具Tool Response HandlingcreateToolResponseHandlingEvaluator评估模型使用工具响应的质量PII DetectioncreatePiiDetectionEvaluator筛查对话记录中的个人身份信息PII对应实现分散在 src/llm 目录下每个create*Evaluator工厂对应一个文件例如createCorrectnessEvaluator.ts、createRetrievalRelevanceEvaluator.ts、createPiiDetectionEvaluator.ts等。使用示例import { createFaithfulnessEvaluator, createConcisenessEvaluator, createCorrectnessEvaluator, createRetrievalRelevanceEvaluator, createRefusalEvaluator, } from arizeai/phoenix-evals/llm; import { openai } from ai-sdk/openai; const model openai(gpt-4o-mini); // Faithfulness: checks if the output is grounded in the context const faithfulnessEvaluator createFaithfulnessEvaluator({ model }); const faithfulnessResult await faithfulnessEvaluator.evaluate({ input: What is the capital of France?, context: France is a country in Europe. Paris is its capital city., output: The capital of France is London., }); console.log(faithfulnessResult); // Output: { label: unfaithful, score: 0, explanation: ... } // Correctness: checks if the output is factually correct const correctnessEvaluator createCorrectnessEvaluator({ model }); const correctnessResult await correctnessEvaluator.evaluate({ input: What is the capital of France?, output: Paris is the capital of France., }); console.log(correctnessResult); // Output: { label: correct, score: 1, explanation: ... } // Retrieval Relevance: checks if retrieved information is relevant to the request const relevanceEvaluator createRetrievalRelevanceEvaluator({ model }); const relevanceResult await relevanceEvaluator.evaluate({ input: What is the capital of France?, context: Paris is the capital of France and a major European city., }); console.log(relevanceResult); // Output: { label: relevant, score: 1, explanation: ... }注意createFaithfulnessEvaluator期望的记录形状为{ input, output, context? }见 createFaithfulnessEvaluator.ts 中的FaithfulnessEvaluationRecord类型而createRetrievalRelevanceEvaluator只需input与context。预置评估器的默认配置来自生成模板预置评估器的提示词、标签分数映射与优化方向并非硬编码在工厂函数里而是引用src/__generated__/default_templates/下自动生成的配置文件。以 Faithfulness 为例FAITHFULNESS_CLASSIFICATION_EVALUATOR_CONFIG.ts 定义了name: faithfulnessoptimizationDirection: MAXIMIZE分数越高越好一段结构化提示词模板把{{input}}、{{context}}、{{output}}组织进query、context、response数据块中并要求模型只输出faithful或unfaithful一个词choices: { faithful: 1, unfaithful: 0 }。createFaithfulnessEvaluator把这些值作为默认参数透传给createClassificationEvaluator因此你无需重复编写提示词即可获得一个经过调优、行为确定的评估器。如果默认行为不完全符合你的场景这些工厂函数也允许覆盖choices、promptTemplate、optimizationDirection与name。该目录下还有COMPLETENESS、CONCISENESS、CORRECTNESS、DOCUMENT_RELEVANCE、HALLUCINATION、PII_DETECTION、REFUSAL、RETRIEVAL_RELEVANCE、TOOL_INVOCATION、TOOL_RESPONSE_HANDLING、TOOL_SELECTION、TOXICITY、USER_FRICTION等配置与 README 的预置评估器表格一一对应仓库中还有createToxicityEvaluator、createUserFrictionEvaluator、createDocumentRelevanceEvaluator、createHallucinationEvaluator等额外实现。从模板系统的实现看src/template 目录模板基于 Mustache 语法渲染formatTemplate负责把变量注入模板getTemplateVariables与createTemplateVariablesProxy则用于动态解析模板中的变量名。ClassificationEvaluator类src/llm/ClassificationEvaluator.ts会缓存模板变量列表promptTemplateVariablesgetter并在evaluate时先应用inputMapping重映射再执行分类。代码评估器确定性的分类指标计算与逐条记录调用 LLM 的评估器不同库还内置了一批**确定性非 LLM**的代码评估器用于计算常见分类指标precision精确率、recall召回率与 F-beta含 F1。它们从arizeai/phoenix-evals/code模块导出作用于一批期望标签 vs 预测标签同时支持二分类通过positiveLabel与多分类通过macro/micro/weighted平均策略。三个指标的定义底层实现在 src/code/classificationMetrics.tsPrecision—— 在所有被预测为某类的样本中真正属于该类别的比例TP / (TP FP)。precision 低意味着误报false alarm多。Recall—— 在所有真正属于某类的样本中模型找回来的比例TP / (TP FN)。recall 低意味着漏报多。F-beta—— precision 与 recall 的加权调和平均数。beta 1即 F1默认值时两者权重相同beta 1更看重 recall适用于漏掉真阳性代价更高的场景如医疗筛查beta 1更看重 precision适用于误报代价更高的场景如垃圾邮件过滤。基础用法F1import { createPrecisionEvaluator, createRecallEvaluator, createF1Evaluator, createPrecisionRecallFScoreEvaluators, } from arizeai/phoenix-evals/code; const f1 createF1Evaluator(); const result await f1.evaluate({ expected: [cat, dog, cat, bird], output: [cat, cat, cat, bird], }); console.log(result); // Output: { score: 0.6 } // Or create matching precision/recall/F-score evaluators at once const { precision, recall, fScore } createPrecisionRecallFScoreEvaluators({ average: weighted, });createPrecisionRecallFScoreEvaluators一次返回三个共享同一份 options 的评估器{ precision, recall, fScore }每个评估器产出单一分数与单独工厂createPrecisionEvaluator/createRecallEvaluator/createF1Evaluator的行为一致。需要 F1 以外的 F 分数时使用createFBetaEvaluator({ beta })例如beta: 2表示 recall 权重高于 precision。多分类的平均策略对于多分类数据average参数决定如何把每个类别的分数合并为一个数值macro默认每个类别权重相同适合发现稀有类别是否被忽略的问题weighted按每个类别的出现频次加权适合更关心整体表现、而非类别间均衡的场合micro先把所有类别的 TP/FP/FN 分别汇总再计算指标——对单标签多分类问题而言该值等于整体准确率。从源码看computePrecisionRecallFScore的聚合逻辑刻意对齐了 scikit-learn 的average语义macro/weighted是逐类算 F 再平均而非从汇总的 precision/recall 反推 Fmicro则是先合并混淆计数再算。此外还提供了一些边界行为beta必须 0否则抛出beta must be 0zeroDivision默认0用于替代 0/0 这类未定义指标值positiveLabel显式指定二分类正类one-vs-rest若未指定且average保持默认macro、标签恰好为数值集合{0, 1}会自动把1当作正类一旦显式配置了非默认average自动检测会被跳过避免显式配置被数据形状悄悄覆盖expected与output必须是长度相等且非空的标签数组否则抛出对应错误标签比较采用与Map/Set键查找一致的 SameValueZero 语义两个NaN视为相等。重要提示与上面逐条记录的 LLM 评估器不同这些分类指标评估器是batch/dataset 级别的expected/output是所有样本的完整标签序列而不是单条记录的标签。不要把它们直接接进runExperiment作为逐行评估器——正确做法是先收集每一行的期望/预测标签再对完整数组调用一次.evaluate({ expected, output })。F-beta 权衡、三种平均策略的完整可运行讲解见 examples/classification_metrics_example.ts底层公式与 precision/recall 取舍的引用文献见 README 中引用的 Precision / Recall / F-Score 文档。数据映射bindEvaluator 适配任意数据形状当你的数据结构和评估器期望的输入不一致时用bindEvaluator把字段映射到评估器期望的输入格式即可无需改写业务数据结构import { bindEvaluator } from arizeai/phoenix-evals; import { createFaithfulnessEvaluator } from arizeai/phoenix-evals/llm; import { openai } from ai-sdk/openai; const model openai(gpt-4o-mini); type ExampleType { question: string; context: string; answer: string; }; const evaluator bindEvaluatorExampleType( createFaithfulnessEvaluator({ model }), { inputMapping: { input: question, // Map input from question context: context, // Map context from context output: answer, // Map output from answer }, } ); const result await evaluator.evaluate({ question: Is Arize Phoenix Open Source?, context: Arize Phoenix is a platform for building and deploying AI applications. It is open source., answer: Arize is not open source., });完整的可运行示例见 examples/bind_evaluator_example.ts。映射表达式支持映射支持多种取值方式定义于 src/utils/bindEvaluator.ts 的BindingContext类型简单属性fieldName点号路径user.profile.name数组下标items[0].idJSONPath 表达式$.items[*].id库依赖jsonpath-plus实现函数提取器(data) data.customField函数提取器特别适合做数据转换例如把上下文数组拼接成字符串reference: (data) data.contexts.join(\n\n)或从多轮对话中筛选出最后一条用户消息input: $.conversation.messages[?(.roleuser)].content[-1]。bindEvaluator 的底层机制bindEvaluator本身是薄封装它调用评估器的bindInputMapping方法并返回一个带着 inputMapping 的新评估器副本ClassificationEvaluator.bindInputMapping通过new ClassificationEvaluator({ ...this, inputMapping })实现不会修改原评估器。真正做字段重映射的是remapObjectsrc/utils/objectMappingUtils.tsClassificationEvaluator.evaluate在执行分类前会先调用它把原始记录转成评估器期望的形状。测试覆盖见 test/utils/bindEvaluator.test.ts。与 Phoenix 集成数据集、实验与自动追踪该包可与arizeai/phoenix-client无缝协作实现完整的实验工作流创建数据集、运行实验并自动追踪每次评估调用以便分析与调试。首先安装 phoenix-clientnpm install arizeai/phoenix-client然后按以下模式运行实验import { createFaithfulnessEvaluator } from arizeai/phoenix-evals/llm; import { openai } from ai-sdk/openai; import { createDataset } from arizeai/phoenix-client/datasets; import { asExperimentEvaluator, runExperiment, } from arizeai/phoenix-client/experiments; // Create your evaluator const faithfulnessEvaluator createFaithfulnessEvaluator({ model: openai(gpt-4o-mini), }); // Create a dataset for your experiment const dataset await createDataset({ name: faithfulness-eval, description: Evaluate the faithfulness of the model, examples: [ { input: { question: Is Phoenix Open-Source?, context: Phoenix is Open-Source., }, }, // ... more examples ], }); // Define your experimental task const task async (example) { // Your AI systems response to the question return Phoenix is not Open-Source; }; // Create a custom evaluator to validate results const faithfulnessCheck asExperimentEvaluator({ name: faithfulness, kind: LLM, evaluate: async ({ input, output }) { // Use the faithfulness evaluator from phoenix-evals const result await faithfulnessEvaluator({ input: input.question, context: input.context, output: output, }); return result; // Return the evaluation result }, }); // Run the experiment with automatic tracing runExperiment({ experimentName: faithfulness-eval, experimentDescription: Evaluate the faithfulness of the model, dataset: dataset, task, evaluators: [faithfulnessCheck], });这里的关键点在于phoenix-evals评估器的返回值EvaluationResult可以直接透传给asExperimentEvaluator包装的evaluate回调并作为实验结果返回二者在数据结构上天然兼容。runExperiment会负责自动追踪 task 与评估器的执行轨迹你可以在 Phoenix 的 Web 界面中逐条查看输入、输出与评估分数。运行仓库中的示例仓库的 examples 目录提供了多个可直接运行的示例脚本classifier_example.ts自定义分类器、classification_metrics_example.ts分类指标与平均策略、bind_evaluator_example.ts数据映射、faithfulness_example.ts、format_template_example.ts、create_evaluator_example.ts、phoenix_integration_example.ts与 Phoenix 集成等。使用pnpm安装依赖后即可运行pnpm install pnpx tsx examples/classifier_example.ts # change the file name to run other examples运行前需配置好模型提供方的 API 密钥如 OpenAI。仓库内部通过 Vitest 提供了完整测试集test 目录覆盖createClassifierFn、generateClassification、bindEvaluator、applyTemplate、classificationMetrics等可用pnpm test执行便于深入理解各 API 的预期行为。总结arizeai/phoenix-evals提供了一条从自定义分类评估到预置 LLM 评估器再到确定性分类指标的完整 TypeScript 评估链路自定义分类器createClassifier用提示词模板 标签分数映射定义任意二分类/多分类任务底层通过 AI SDKgenerateObject输出结构化的label explanation并支持 evaluation model 与自动遥测。预置 LLM 评估器Faithfulness、Correctness、Retrieval Relevance、PII Detection、工具调用系列等 10 个开箱即用的评估器默认模板由src/__generated__/default_templates自动生成并允许覆盖。代码评估器在批量标签上确定性地计算 Precision / Recall / F-beta支持二分类positiveLabel与多分类macro/micro/weighted底层实现对齐 scikit-learn 语义。数据映射bindEvaluator 点号/数组/JSONPath/函数提取器把任意数据形状无损适配到评估器输入。实验集成与arizeai/phoenix-client的createDataset/runExperiment/asExperimentEvaluator配合实现数据集管理、批量实验与自动追踪。赞分享可观测性AI 评测LLMOpsAI 应用人工智能【免费下载链接】phoenixAI Observability Evaluation项目地址https://gitcode.com/gh_mirrors/phoenix13/phoenix点击查看免费下载相关推荐Phoenix LLM Evaluators Python 指南用 LLM 构建分类评估器与大规模评测Phoenix LLM Evaluators Python 指南用 LLM 构建分类评估器与大规模评测 导读 本指南围绕 PhoenixAI Observa可观测性AI 评测LLMOpsAI 应用人工智能从 0.0.2 到 2.6.0读懂 arizeai/phoenix-evals 的演进脉络与预构建评估器家族从 0.0.2 到 2.6.0读懂 arizeai/phoenix evals 的演进脉络与预构建评估器家族 arizeai/phoenix evals可观测性AI 评测LLMOpsAI 应用人工智能Phoenix TypeScript 实验数据集指南用 arizeai/phoenix-client 创建与管理评估数据集Phoenix TypeScript 实验数据集指南用 arizeai/phoenix client 创建与管理评估数据集 本指南以 Phoenix 的 T可观测性AI 评测LLMOpsAI 应用人工智能上一篇【亲测免费】 探索高质量代码注释的艺术eslint-plugin-jsdoc下一篇【亲测免费】 推荐开源项目Horizon EDA - 全面的电路设计自动化工具创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考