LlamaIndex 响应相关性评估指南QueryResponseEvaluator 与 RelevancyEvaluator 用法、原理与源码解读【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_indexQueryResponseEvaluator其现名实现为 RelevancyEvaluator是 LlamaIndex 面向 RAG 问答链路提供的一类基于 LLM 的相关性评估器它同时考察「查询query」、「检索到的上下文contexts」与「生成的回答response」三者是否相互匹配、一致。本文以官方 API 引用页 docs/api_reference/api_reference/evaluation/query_response.md 为骨架结合核心实现 relevancy.py、基类 base.py 与官方使用模式文档 usage_pattern.md系统讲解这两个类的构造参数、内置 Prompt 模板、逐源per-source与整体whole-response两种评估调用方式以及评估结果对象 EvaluationResult 的字段含义。读完本文你将能在自己的 LlamaIndex 应用中加入「上下文/回答是否真的回答了用户问题」的自动化质量门禁。一、被引用页面究竟指代什么先看关联文档的全部内容它是一段标准的 mkdocstrings 指令::: llama_index.core.evaluation options: members: - QueryResponseEvaluator - RelevancyEvaluator这段指令的含义是在构建 API 文档时自动抓取llama_index.core.evaluation包内被显式列出的两个公开成员——QueryResponseEvaluator与RelevancyEvaluator——并将它们的类签名、docstring、方法与属性渲染成结构化 API 页面。也就是说本文围绕的「文档」本质上是对这两个类的 API 说明因此后续所有论述都应当落到真实类实现之上。两个类的真实定义位置为 llama-index-core/llama_index/core/evaluation/relevancy.py并且它们并非两个独立实现。该文件最末一行给出了关键结论QueryResponseEvaluator RelevancyEvaluatorQueryResponseEvaluator只是历史遗留的向后兼容别名指向同一个RelevancyEvaluator类。在init.py 的导出列表中QueryResponseEvaluator同样被注释为 “legacy: kept for backward compatibility”。因此阅读这两个名字时只需要关注RelevancyEvaluator一套实现即可。二、评估语义RelevancyEvaluator 在衡量什么类 docstring 对自身语义的定义如下见 relevancy.pyEvaluates the relevancy of retrieved contexts and response to a query. This evaluator considers the query string, retrieved contexts, and response string.也就是说它不是只判断「回答对不对」而是综合判断三层关系检索到的上下文与查询是否相关生成的回答与查询是否相关回答是否与给定上下文保持一致是否有脱离语料的编造。在官方使用模式文档 usage_pattern.md 中其定位被概括为评估「检索上下文与回答对给定查询是否相关且一致」。与之互补的是同一评估体系里的FaithfulnessEvaluator判断回答是否忠实于检索上下文即是否存在幻觉。二者分工不同Faithfulness 侧重「答非所问/编造」Relevancy 侧重「上下文与回答是否答到了问题上」。整个评估子系统的可用评估器都集中导出在 llama_index/core/evaluation/init.py包括 CorrectnessEvaluator、SemanticSimilarityEvaluator、PairwiseComparisonEvaluator、GuidelineEvaluator 等便于在评测时组合使用。三、构造参数详解RelevancyEvaluator的构造函数签名relevancy.pydef __init__( self, llm: Optional[LLM] None, raise_error: bool False, eval_template: Optional[Union[str, BasePromptTemplate]] None, refine_template: Optional[Union[str, BasePromptTemplate]] None, ) - None:参数类型默认值作用llmOptional[LLM]Settings.llm执行评估判定的语言模型。不传时自动回退到全局Settings.llm因此可先Settings.llm ...统一配置raise_errorboolFalse当模型判定「回答不相关」时是否抛出异常。默认False只把passing置为False为True时在判定为否的情况下抛出ValueErroreval_templatestr/BasePromptTemplate内置DEFAULT_EVAL_TEMPLATE主评估模板。若传字符串会先包装为PromptTemplaterefine_templatestr/BasePromptTemplate内置DEFAULT_REFINE_TEMPLATE精炼模板用于结合更多上下文再次确认 YES/NO 判定一个最小的构造示例来自 usage_pattern.mdfrom llama_index.core.evaluation import RelevancyEvaluator from llama_index.llms.openai import OpenAI llm OpenAI(modelgpt-4, temperature0.0) evaluator RelevancyEvaluator(llmllm)评估属于判别任务实践中建议把 LLM 的temperature设为 0以获得稳定、可复现的 YES/NO 判定。四、内置 Prompt评估与精炼两段式4.1 主评估模板 DEFAULT_EVAL_TEMPLATE定义于 relevancy.pyDEFAULT_EVAL_TEMPLATE PromptTemplate( Your task is to evaluate if the response for the query \ is in line with the context information provided.\n You have two options to answer. Either YES/ NO.\n Answer - YES, if the response for the query \ is in line with context information otherwise NO.\n Query and Response: \n {query_str}\n Context: \n {context_str}\n Answer: )它要求模型输出二选一的YES或NO输入占位符有两个{query_str}由评估器拼好的「Question Response」组合文本{context_str}检索到的上下文内容。4.2 精炼模板 DEFAULT_REFINE_TEMPLATE定义于 relevancy.pyDEFAULT_REFINE_TEMPLATE PromptTemplate( We want to understand if the following query and response is in line with the context information: \n {query_str}\n We have provided an existing YES/NO answer: \n {existing_answer}\n We have the opportunity to refine the existing answer (only if needed) with some more context below.\n ------------\n {context_msg}\n ------------\n If the existing answer was already YES, still answer YES. If the information is present in the new context, answer YES. Otherwise answer NO.\n )该模板对应的是长文本评估的「分块精炼」策略当上下文过长无法一次放入模型时系统先基于一部分上下文给出初步 YES/NO再结合其余上下文调用精炼模板做二次确认。规则是「已判定 YES 则保持 YES新上下文中有支撑信息则改为 YES否则保持 NO」。模板中的{existing_answer}由text_qa_template体系自动传入初判结果。五、内部运行原理从输入到 EvaluationResultRelevancyEvaluator的核心逻辑在异步方法aevaluate中relevancy.py。以默认构造为例一次评估的执行链路如下输入校验query、contexts、response三者缺一不可任一为None都会抛出ValueError。构建内存索引把每个上下文文本包装成Document用SummaryIndex.from_documents(docs)在内存中建一个摘要索引——这正是它可以处理「上下文总量超过单次模型窗口」的原因检索 摘要/精炼由索引查询引擎承担。拼接评估问题将输入组合为Question: {query}\nResponse: {response}字符串作为被评估对象。调用查询引擎通过index.as_query_engine(llm..., text_qa_templateeval_template, refine_templaterefine_template)创建查询引擎并执行aquery(query_response)。主模板充当text_qa_template精炼模板充当refine_templateLLM 的回答文本即评估结论。解析 YES/NO将原始回答转为小写只要包含子串yes即判定通过否则若raise_errorTrue抛出ValueError(The response is invalid)若为False则passingFalse。生成结构化结果封装为EvaluationResult其中score直接取二值——通过为1.0不通过为0.0feedback保存 LLM 的原始判定文本。完整流程示意如下图所示——查询驱动索引产出回答与来源评估模块对「回答是否与查询/上下文匹配」给出最终 YES/NO 判定该方法同步路径evaluate只是对aevaluate的封装基类 base.py 用asyncio_run把异步评估跑成一个阻塞调用方便在脚本、notebook 中直接同步使用。六、方法体系BaseEvaluator 提供的四种调用方式RelevancyEvaluator继承自BaseEvaluator实际可用的方法在 base.py 中定义方法同步/异步输入形态说明evaluate(query, response, contexts, **kwargs)同步三个字符串最底层调用底层是asyncio_run(aevaluate(...))aevaluate(...)异步同上真正的实现入口子类覆写evaluate_response(query, response: Response)同步传入Response对象自动从response.source_nodes抽取每个节点的文本作为contexts无需手动准备aevaluate_response(...)异步同上异步版本evaluate_response的便利性在于直接从查询引擎返回的Response对象中取response.response作为回答文本并遍历source_nodes生成上下文列表屏蔽了手工拆字段的样板代码。正因为如此官方使用文档特别提示使用RelevancyEvaluator时必须把query一并传入——它不像 Faithfulness 评估器那样可以只靠 response contexts 自证。EvaluationResult是全部评估器统一返回的数据结构base.py核心字段如下字段类型含义querystr被评估的查询contextsSequence[str]本次评估使用的上下文responsestr被评估的回答passingbool二值结论是否通过feedbackstr模型给出的原始判定/理由文本scorefloat分数Relevancy 场景下为 1.0/0.0invalid_result/invalid_reasonbool/str评估是否无效及原因七、实战一对整份回答做一次综合评估官方推荐的标准用法是「查索引 → 得到 Response → 交给evaluate_response」。核心代码usage_pattern.mdfrom llama_index.core import VectorStoreIndex from llama_index.llms.openai import OpenAI from llama_index.core.evaluation import RelevancyEvaluator # 配置评估用 LLM llm OpenAI(modelgpt-4, temperature0.0) # 构建索引示例中索引内为关于纽约市历史的文章 # vector_index VectorStoreIndex.from_documents(...) # 实例化评估器 evaluator RelevancyEvaluator(llmllm) # 查询索引得到 Response 对象 query_engine vector_index.as_query_engine() query What battles took place in New York City in the American Revolution? response query_engine.query(query) # 用 Response 对象直接评估自动取全部 source_nodes 作为上下文 eval_result evaluator.evaluate_response(queryquery, responseresponse) print(str(eval_result))当回答整体符合检索上下文时输出中的passingTrue、score1.0反之passingFalse。由于该方法把全部来源一起喂给内存中的SummaryIndex做综合检索与摘要判定它回答的是「这份回答作为一个整体是否站得住脚」的问题。八、实战二逐来源per-source评估定位问题片段evaluate_response给出的是整体结论但它无法告诉你「到底是哪一个检索片段拖累了相关性」。若想定位到具体来源可以遍历response.source_nodes把每个节点单独作为上下文做一次评估usage_pattern.mdfrom llama_index.core import VectorStoreIndex from llama_index.llms.openai import OpenAI from llama_index.core.evaluation import RelevancyEvaluator llm OpenAI(modelgpt-4, temperature0.0) evaluator RelevancyEvaluator(llmllm) query_engine vector_index.as_query_engine() query What battles took place in New York City in the American Revolution? response query_engine.query(query) response_str response.response # 逐来源评估contexts 只放当前节点内容 for source_node in response.source_nodes: eval_result evaluator.evaluate( queryquery, responseresponse_str, contexts[source_node.get_content()], ) print(str(eval_result.passing))返回的结果列表与response.source_nodes一一对应从而可以直观看出哪个检索来源是「有效证据」、哪些是检索系统误召回的不相关内容。下图为一次逐源评估的典型结果面对查询「谁是纽约市市长」来源 2 被判定为YES直接相关而来源 1、来源 3 分别被判定为NO不相关/仅背景资料逐来源评估在生产中有很强的实用价值它可以把「整体回答不相关」这个模糊信号拆解成「召回质量差」与「生成偏离上下文」两类可定位的问题进而指导检索参数如similarity_top_k或重排序策略的调优。九、进阶定制与工程化建议9.1 自定义评估 Prompt当默认英文模板不满足需求例如需要中文判定、输出结构化理由、遵循特定打分口径时可传入自定义字符串模板。字符串会被自动包装成PromptTemplate只要模板中保留{query_str}与{context_str}占位符并保持 YES/NO 输出协议解析逻辑即可正常工作custom_eval ( 你是 RAG 质量评审员。请判断针对问题回答是否与提供的资料一致 且真正回应了问题。只回答 YES 或 NO。\n Query and Response: \n {query_str}\n Context: \n {context_str}\n Answer: ) evaluator RelevancyEvaluator(llmllm, eval_templatecustom_eval)同时由于RelevancyEvaluator继承自PromptMixin其内部 Prompt 可通过_get_prompts()/_update_prompts()relevancy.py以eval_template、refine_template为键统一管理适合在框架层做集中定制。9.2 用 raise_error 构建质量门禁把raise_errorTrue放进批处理流水线后只要出现相关性判定为否的样本评估器就会直接抛出ValueError可以配合异常捕获实现「出现低质回答即中断/告警」的硬门禁而在离线数据分析阶段则保持默认False靠passing与score统计通过率。9.3 控制调用频率与异步并发aevaluate还暴露了sleep_time_in_seconds: int 0参数可用于在批量评估时对 LLM 请求做限速规避速率限制。配合BatchEvalRunner同在 evaluation 包中导出可以并行跑多个评估器需要高吞吐时优先使用aevaluate_response这类异步接口。9.4 自动化评估闭环LlamaIndex 的评估流程并不止于相关性判断。官方使用文档指出RelevancyEvaluator可与DatasetGenerator自动基于文档生成「问题-回答」数据集搭配构建「自动出题 → 自动问答 → 自动评估」的完整回归闭环仓库自带的 relevancy_eval.ipynb 与 answer_and_context_relevancy.ipynb 提供了可在本地直接运行参考的完整示例。十、结语与进一步阅读QueryResponseEvaluator与其现名RelevancyEvaluator是 LlamaIndex 评估体系中最常被用到的评估器之一它的实现思路也很有代表性把「LLM 评估」本身建模为一个基于内存SummaryIndex的小型问答任务通过text_qa_templaterefine_template两段式 Prompt 在长上下文中给出稳定的 YES/NO 判定最后归一化为EvaluationResult的passing/score/feedback。理解了这条链路你就同时掌握了自定义其他 LLM-as-a-judge 评估器的通用范式。建议按以下顺序在仓库中继续深挖API 引用原点docs/api_reference/api_reference/evaluation/query_response.md类实现与全部内置模板llama-index-core/llama_index/core/evaluation/relevancy.py基类与EvaluationResult定义llama-index-core/llama_index/core/evaluation/base.py评估子系统导出清单llama-index-core/llama_index/core/evaluation/init.py官方使用模式教程含 FaithfulnessEvaluator 对照docs/src/content/docs/framework/module_guides/evaluating/usage_pattern.md可运行 Notebookrelevancy_eval.ipynb、answer_and_context_relevancy.ipynb【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考