Kiln RAG 评估模板库设计:基于 `llm_judge` 的六大检索增强生成质量度量
Kiln RAG 评估模板库设计:基于 llm_judge 的六大检索增强生成质量度量
本文是 Kiln 项目中 Evals V2 阶段针对 RAG(检索增强生成)评估场景的一套第一方 llm_judge 模板库设计。它定义了三个规范化的 reference key(retrieved_context、ground_truth_context、reference_answer),并以此为基础提供了 Faithfulness、Answer Relevance、Context Relevance、Context Precision、Hallucination、Answer Correctness 六个可直接落地的评判提示词模板。读完本文,你将理解 Kiln 如何在零 schema 改动的前提下用 llm_judge 类型支撑 RAG 评估,掌握每个模板的评分语义、Jinja2 模板变量约定、缺失数据时的 skip 行为,以及模板的验证与发布标准。本文核心设计来源为仓库中的 29_rag_judge_templates.md(状态为 deferred,设计保留供后续参考),并辅以 50_reference_data.md、21_type_llm_judge.md、40_template_and_extraction.md 以及 libs/core 中的真实实现相互印证。
1. 目标与范围:不引入新类型的 RAG 评估
该模板库的设计目标是:交付 6 个第一方 llm_judge 模板,使 Kiln 在 V2.0 中具备可信的 RAG 评估能力,且无需任何 schema 层面的新增工作。
每一个模板都是一个生产级的 judge prompt,负责对 RAG 流水线的某一维度进行评分,消费 EvalInput.reference: dict[str, JsonValue](依 A1.2 定义)中的某个文档化 reference key 子集。该交付物与 llm_judge 类型设计本身(21_type_llm_judge.md)相互独立——它只是为已设计好的 EvalConfigType 提供模板内容。
明确不在范围内的事项(原设计文档第 1 节、第 7 节):
- 基于 embedding 的相似度度量(Answer Similarity、embedding 增强的 Context Recall),推迟到 Phase 7,与
embedding_similarity类型一并交付; - 端到端检索执行——Kiln 不运行 retriever,
retrieved_context由用户在建 EvalInput 时提供; - RAGAS 式复合评分(依赖
composite类型,Phase 7 候选); - 生产 trace 摄入(Langfuse、Phoenix 等连接器在 V2 中完全超出范围);
- 多轮 RAG 评估(与
MultiTurnSyntheticEvalInputData相关的独立设计关注点); - 自定义 RAG 指标——超出这 6 个模板之外的用户需求,可直接依据同一 reference-key 契约自行撰写
llm_judge提示词,无需特殊框架。
注意:该设计文档本身标注为 Deferred from V2.0——实现被移除,RAG judge 模板与持续评分被推迟到未来项目,设计保留在此供参考。带回计划见 specs/projects/rag_templates/project_overview.md。
2. Reference-key 契约:三个规范键
依照 A1.2,EvalInput.reference 的类型为 dict[str, JsonValue] | None;依照 A1.3,每个 EvalConfig 声明自己消费哪些键,校验发生在 config 绑定(bind)时而非 EvalInput 创建时。这套库中的六个模板消费三个规范化 reference key。使用这些模板的项目必须在运行评估前,为每个 EvalInput 填充相应的键。
2.1 retrieved_context
- 类型:
list[str] - 语义:RAG 检索系统针对用户查询返回的文本块。每个字符串是一个 chunk(一个段落、一个文档小节、一条搜索结果摘要)。顺序应反映检索排名(如有)。
- 填充时机:EvalInput 创建时,由用户的数据流水线或导入流程填充。通常从生产 RAG 日志、检索 API 响应中提取,或为测试用例手工编写。
- 校验规则:必须是非空列表;每个元素必须是非空字符串。模板 prompt 会指示 judge 处理上下文稀薄(单个短 chunk)的情况,但空列表属于输入错误而非边界情况。
- 消费方:Faithfulness、Context Relevance、Context Precision、Hallucination。
- 示例值:
[ "The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris, France. It was constructed from 1887 to 1889.", "The tower is 330 metres tall and was the tallest man-made structure in the world until 1930.", "Gustave Eiffel's company designed and built the tower for the 1889 World's Fair." ]
2.2 ground_truth_context
- 类型:
list[str] - 语义:本应被检索到的理想源片段——一个完美 retriever 应当返回的权威、完整片段集合。通过与实际检索结果对比来评估检索质量。
- 填充时机:EvalInput 创建时。通常由领域专家编写、从策展知识库提取,或来自标注过的评估数据集。产出成本高于
retrieved_context。 - 校验规则:必须是非空列表;每个元素必须是非空字符串。
- 消费方:Context Precision(可选——可用时提升评分)。Context Recall 推迟到 Phase 7(依赖 embedding 相似度)。
- 示例值:
[ "The Eiffel Tower was built by Gustave Eiffel's engineering company for the 1889 Exposition Universelle (World's Fair) held in Paris.", "At 330 metres, the Eiffel Tower was the world's tallest structure from its completion in 1889 until the Chrysler Building in New York surpassed it in 1930." ]
2.3 reference_answer
- 类型:
str - 语义:针对用户查询的金标准答案——人类专家会给出的事实正确、完整的回答。用于在独立于检索上下文的前提下评估模型输出的事实准确性与完整性。
- 填充时机:EvalInput 创建时,由领域专家编写或来自策展 Q&A 数据集。仅做上下文或忠实度评估时可不提供。
- 校验规则:必须是非空字符串。
- 消费方:Answer Correctness。
- 示例值:
"The Eiffel Tower is a wrought-iron lattice tower located on the Champ de Mars in Paris. It was designed by Gustave Eiffel's engineering company and built between 1887 and 1889 for the 1889 World's Fair. It stands 330 metres tall."
2.4 键位汇总表
| Key | 类型 | 模板必需 | 对谁可选 |
|---|---|---|---|
retrieved_context |
list[str] |
Faithfulness、Context Relevance、Context Precision、Hallucination | -- |
ground_truth_context |
list[str] |
-- | Context Precision |
reference_answer |
str |
Answer Correctness | -- |
按照 A1.3,下文每个模板都会通过 LlmJudgeProperties 上的 required_var Jinja2 表达式声明自己消费哪些 reference key。运行时,runner 校验 EvalInput 的 reference dict 中存在必需键;缺失时该 case 以 SkippedReason.missing_reference_key 被跳过(仅做存在性检查,不做类型检查)。
3. 模板运行机制:四个保留变量与"先推理后裁决"
每个模板都是一个完整的 llm_judge EvalConfig。judge prompt 使用 Kiln 的模板变量语法(见 40_template_and_extraction.md 第 2 节):
{{ final_message }}——待评估的模型输出;{{ task_input }}——原始用户输入;{{ reference_data.retrieved_context }}、{{ reference_data.reference_answer }}、{{ reference_data.ground_truth_context }}——对应的 reference-key 值。
这四个保留的顶层变量(final_message、trace、reference_data、task_input)由 eval runner 的 EvalTaskInput 组装阶段填充。这一设计在源码中得到了完全印证:libs/core/kiln_ai/datamodel/eval.py 中的 EvalTaskInput 模型正是这四个字段(final_message、trace、reference_data、task_input),其 from_trace() 类方法在 source 为 EvalInput 时直接把 source.reference 赋给 reference_data,在 source 为 TaskRun 数据集条目时把该条目存储的 output 包装为 {"reference_answer": source.output.output}。
六个模板均采用"先推理后裁决"结构:judge 被要求逐步推理后再产出分数。这与 A2.2 中记录的 G-Eval 式 chain-of-thought 模式一致——但这些模板不使用 g_eval(token log-prob 打分),而是采用标准的结构化输出打分。在实现上,v2_eval_llm_judge.py 的 LlmJudgeEval.evaluate() 根据 LlmJudgeProperties.g_eval 开关分流:g_eval=False 走 build_llm_as_judge_score(结构化输出),g_eval=True 才走 build_g_eval_score(需要 provider 支持 logprobs,top_logprobs=10)。
4. 六大模板详解
4.1 Faithfulness(忠实度)
- 目的:度量模型输出中被检索上下文支持的 claim 所占比例。这是 RAG 系统幻觉检测的核心指标,回答的问题是:"模型是否忠于 retriever 给它的材料?"
- 消费的 reference key:
retrieved_context - 评分类型:0-1 连续值(忠实 claim 的比例)
Judge prompt:
You are an expert fact-checker evaluating whether a response is faithful to its source context. Your task is to determine what fraction of the claims in the response are supported by the provided context.
## Inputs
**User query:**
{{ task_input }}
**Retrieved context (the only information the system had access to):**
{% for chunk in reference_data.retrieved_context %}
[Chunk {{ loop.index }}]: {{ chunk }}
{% endfor %}
**Response to evaluate:**
{{ final_message }}
## Instructions
Follow these steps precisely:
### Step 1: Extract claims
Break the response into individual, atomic factual claims. Each claim should be a single assertion that can be independently verified. Ignore filler phrases, hedging language, and meta-commentary (e.g., "Based on the provided information..."). If the response contains no factual claims (e.g., it is a refusal or a clarifying question), note this.
### Step 2: Verify each claim
For each extracted claim, determine whether it is:
- **Supported**: The claim is directly stated in or logically entailed by the retrieved context.
- **Not supported**: The claim cannot be verified from the retrieved context. This includes claims that are plausible but not present in the context, as well as claims that contradict the context.
A claim is "supported" only if the retrieved context provides sufficient evidence. General knowledge or common sense does NOT count as support -- only the retrieved context matters.
### Step 3: Calculate the faithfulness score
Faithfulness = (number of supported claims) / (total number of claims).
If there are zero claims, the score is 1.0.
## Output format
Return your analysis as JSON with this exact structure:
{
"claims": [
{"claim": "<atomic claim text>", "supported": true, "evidence": "<quote or paraphrase from context, or null if not supported>"},
...
],
"num_supported": <integer>,
"num_total": <integer>,
"score": <float between 0.0 and 1.0>,
"reasoning": "<1-2 sentence summary of the faithfulness assessment>"
}
期望输出格式:JSON 对象,含 claims 数组(每项含 claim、supported、evidence)、num_supported、num_total、score(0-1 浮点)与 reasoning。
Prompt 处理的边界情况:
- 空/拒绝回答:提取出零个 claim,分数默认为 1.0(没有不忠实的 claim);
- 单 chunk 上下文:同样工作,claim 仅针对唯一可用 chunk 校验;
- 响应逐字复述上下文:全部 claim 受支持,分数 1.0。这是正确行为——忠实度不惩罚缺乏综合;
- 混合支持/不支持:部分分数反映比例;
- 上下文不包含的常识:视为不支持。这是有意为之——忠实度度量的是对给定上下文的锚定,而非一般准确性。
验证策略:对 50-100 个 RAG 响应样本进行逐 claim 人工标注,与模板分数对比,目标 Spearman rho ≥ 0.7;与 DeepEval 的 Faithfulness 指标在同一数据集上交叉验证;在"上下文事实与貌似合理的编造混合"的对抗性样本上测试。
4.2 Answer Relevance(回答相关性)
- 目的:评估模型输出是否真正回应了用户查询,检测离题、跑题或回避式回答——无论其是否事实上有依据。
- 消费的 reference key:无(只用
{{ final_message }}与{{ task_input }}) - 评分类型:0-1 连续值
Judge prompt:
You are an expert evaluator assessing whether a response is relevant to the user's query. A relevant response directly addresses what the user asked, provides information the user was seeking, and stays on topic.
## Inputs
**User query:**
{{ task_input }}
**Response to evaluate:**
{{ final_message }}
## Instructions
Follow these steps precisely:
### Step 1: Identify the user's intent
Determine what the user is asking for. Identify the core question or request, including any specific constraints (e.g., time period, format, scope).
### Step 2: Assess relevance dimensions
Evaluate the response on three dimensions:
1. **Addresses the question:** Does the response provide an answer to what was actually asked? A response that discusses the right topic but answers a different question is not fully relevant.
2. **Completeness:** Does the response cover the key aspects of the query, or does it address only a tangential part?
3. **Conciseness:** Is the response free of substantial irrelevant content that dilutes the answer? Minor filler is acceptable; large irrelevant digressions are not.
### Step 3: Assign a score
- **1.0**: The response directly and completely addresses the query with no significant irrelevant content.
- **0.7-0.9**: The response addresses the query but is partially incomplete or contains some irrelevant content.
- **0.4-0.6**: The response is tangentially related to the query but misses the core question or includes substantial irrelevant material.
- **0.1-0.3**: The response is mostly irrelevant to the query, addressing a different topic or providing unusable information.
- **0.0**: The response is completely irrelevant, a non-sequitur, or a refusal to answer without justification.
Note: A well-justified refusal (e.g., "I don't have enough information to answer that") should score 0.3-0.5 depending on whether the refusal is appropriate given the context.
## Output format
Return your analysis as JSON with this exact structure:
{
"user_intent": "<1-2 sentence summary of what the user is asking>",
"addresses_question": "<assessment of whether the response answers what was asked>",
"completeness": "<assessment of coverage>",
"conciseness": "<assessment of irrelevant content>",
"score": <float between 0.0 and 1.0>,
"reasoning": "<1-2 sentence summary>"
}
期望输出格式:JSON 对象,含 user_intent、addresses_question、completeness、conciseness、score(0-1 浮点)与 reasoning。
边界情况:
- 拒绝回答:按上下文评分(0.3-0.5),而非二元失败——有依据的拒绝优于不相关回答;
- 部分回答:中间分数(0.7-0.9)捕捉相关但不完整的响应;
- 冗长但正确:简洁性维度惩罚稀释而不惩罚详尽;
- 含糊查询:judge 从查询文本推断意图,含糊性记录在 reasoning 中。
验证策略:对 50-100 个查询-响应对在 5 分相关性标尺上人工标注,转换为 0-1 后与模板分数对比,目标 Spearman rho ≥ 0.7;包含"流畅自信但答非所问"的对抗性样本。
4.3 Context Relevance(上下文相关性)
- 目的:评估
retrieved_context中的 chunk 是否与用户查询相关。度量的是 retriever 质量(查询-上下文对齐),而非生成器质量。低分表明 retriever 在返回噪声。 - 消费的 reference key:
retrieved_context - 评分类型:0-1 连续值(相关 chunk 的比例)
Judge prompt:
You are an expert evaluator assessing the relevance of retrieved context to a user's query. Your task is to determine what fraction of the retrieved chunks contain information that is useful for answering the query.
## Inputs
**User query:**
{{ task_input }}
**Retrieved context chunks:**
{% for chunk in reference_data.retrieved_context %}
[Chunk {{ loop.index }}]: {{ chunk }}
{% endfor %}
## Instructions
Follow these steps precisely:
### Step 1: Identify the information need
Determine what information would be needed to answer the user's query comprehensively. List the key topics, entities, or facts required.
### Step 2: Evaluate each chunk
For each retrieved chunk, determine whether it is:
- **Relevant**: The chunk contains information that would be useful for answering the query. It does not need to fully answer the query -- partial relevance counts. A chunk about a related sub-topic that provides necessary context is relevant.
- **Irrelevant**: The chunk does not contain information useful for answering the query. It may discuss unrelated topics, or the same broad domain but a different specific question.
Be generous with relevance -- if a chunk provides any useful background, definitions, or context that supports answering the query, it is relevant. Only mark chunks as irrelevant if they would not help a knowledgeable person construct an answer.
### Step 3: Calculate the context relevance score
Context Relevance = (number of relevant chunks) / (total number of chunks).
## Output format
Return your analysis as JSON with this exact structure:
{
"information_need": "<summary of what information is needed to answer the query>",
"chunk_evaluations": [
{"chunk_index": 1, "relevant": true, "reason": "<why this chunk is or is not relevant>"},
...
],
"num_relevant": <integer>,
"num_total": <integer>,
"score": <float between 0.0 and 1.0>,
"reasoning": "<1-2 sentence summary of retrieval quality>"
}
期望输出格式:JSON 对象,含 information_need、chunk_evaluations 数组(每项含 chunk_index、relevant、reason)、num_relevant、num_total、score(0-1 浮点)与 reasoning。
边界情况:
- 单 chunk 检索:分数是二元的(0.0 或 1.0),模板自然处理;
- 全部 chunk 不相关:分数 0.0,reasoning 字段解释 retriever 为何失败;
- 部分相关 chunk:提供有用背景但未直接回答查询的 chunk 标记为相关——prompt 要求宽松的相关性阈值;
- 超长 chunk:judge 把 chunk 作为整体评估相关性,而非逐句评估;
- 重复 chunk:各自独立评估。该指标不惩罚重复(那是 retriever 效率指标,超出范围)。
验证策略:对 50-100 个查询-上下文对在 chunk 级人工标注(逐 chunk 相关/不相关),与模板的 chunk 级判断对比,目标逐 chunk 一致率 ≥ 80%;与 DeepEval 的 Contextual Relevancy 指标在同一数据集上对比聚合分数。
4.4 Context Precision(上下文精度)
- 目的:度量
retrieved_context中真正对产出正确回答有用的 chunk 占比,评估 retriever 的信噪比:高精度 retriever 返回的几乎全是有用 chunk,低精度 retriever 用噪声稀释了相关 chunk。若提供ground_truth_context则可选地与其对比,获得更强信号。 - 消费的 reference key:
retrieved_context,可选ground_truth_context - 评分类型:0-1 连续值(有用 chunk 的比例)
Judge prompt:
You are an expert evaluator measuring the precision of a retrieval system. Your task is to determine what fraction of the retrieved context chunks were actually useful for producing a correct, complete answer to the user's query.
## Inputs
**User query:**
{{ task_input }}
**Retrieved context chunks:**
{% for chunk in reference_data.retrieved_context %}
[Chunk {{ loop.index }}]: {{ chunk }}
{% endfor %}
{% if reference_data.ground_truth_context %}
**Ground truth context (the ideal passages that should have been retrieved):**
{% for chunk in reference_data.ground_truth_context %}
[Ground Truth {{ loop.index }}]: {{ chunk }}
{% endfor %}
{% endif %}
## Instructions
Follow these steps precisely:
### Step 1: Understand the ideal answer
{% if reference_data.ground_truth_context %}
Use the ground truth context to understand what a complete, correct answer looks like. The ground truth passages represent the authoritative source material.
{% else %}
Based on the query, determine what information would be needed for a complete, correct answer. Use your best judgment about what constitutes a useful passage for this query.
{% endif %}
### Step 2: Evaluate each retrieved chunk for usefulness
For each retrieved chunk, determine whether it is:
{% if reference_data.ground_truth_context %}
- **Useful**: The chunk contains information that overlaps with or supports the ground truth context. It provides facts, evidence, or explanations that would help produce the correct answer as represented by the ground truth.
- **Not useful**: The chunk does not contain information relevant to the ground truth context. It may be topically related but does not contribute to producing the correct answer.
{% else %}
- **Useful**: The chunk contains information that directly contributes to answering the query correctly. It provides facts, evidence, or explanations needed for a good answer.
- **Not useful**: The chunk does not contribute meaningful information toward answering the query. It may be topically adjacent but does not help produce a correct answer.
{% endif %}
### Step 3: Calculate the precision score
Context Precision = (number of useful chunks) / (total number of retrieved chunks).
## Output format
Return your analysis as JSON with this exact structure:
{
"mode": "{{ 'with_ground_truth' if reference_data.ground_truth_context else 'without_ground_truth' }}",
"chunk_evaluations": [
{"chunk_index": 1, "useful": true, "reason": "<why this chunk is or is not useful>"},
...
],
"num_useful": <integer>,
"num_total": <integer>,
"score": <float between 0.0 and 1.0>,
"reasoning": "<1-2 sentence summary of retrieval precision>"
}
期望输出格式:JSON 对象,含 mode(指示是否使用了 ground truth)、chunk_evaluations 数组(每项含 chunk_index、useful、reason)、num_useful、num_total、score(0-1 浮点)与 reasoning。
边界情况:
- 未提供
ground_truth_context:prompt 优雅降级为仅基于查询的有用性评估,输出的mode字段记录走了哪条路径; - 全部检索 chunk 有用:分数 1.0——retriever 精度完美(但不代表召回,那是独立指标);
- 单 chunk 检索:二元分数;
- ground truth 与检索上下文部分重叠:judge 针对完整 ground truth 片段集合逐 chunk 独立评估。
验证策略:对 50-100 个查询-上下文对逐 chunk 人工标注有用性;有 ground truth 时与 DeepEval 的 Contextual Precision 对比,目标聚合分数 Spearman rho ≥ 0.7。
4.5 Hallucination(幻觉)
- 目的:检测模型输出中是否包含与检索上下文矛盾或凭空编造(上下文未提及)的 claim。这是 Faithfulness 的反向框架——二者检测同一失败模式,但 Hallucination 以缺陷检测指标呈现(分数越高 = 幻觉越多 = 越差)。同时发布两个模板是有意为之:从 DeepEval 或 LangSmith 迁移而来的用户期望按名字找到 "Hallucination" 指标,且反向框架对缺陷跟踪仪表盘更直观。
- 消费的 reference key:
retrieved_context - 评分类型:0-1 连续值(幻觉 claim 的比例;0.0 = 无幻觉 = 最佳)
Judge prompt:
You are an expert fact-checker detecting hallucinations in a response. A hallucination is any claim in the response that is either contradicted by the retrieved context or fabricated (not present in the context at all). Your task is to determine what fraction of the response's claims are hallucinated.
## Inputs
**User query:**
{{ task_input }}
**Retrieved context (the only information the system had access to):**
{% for chunk in reference_data.retrieved_context %}
[Chunk {{ loop.index }}]: {{ chunk }}
{% endfor %}
**Response to evaluate:**
{{ final_message }}
## Instructions
Follow these steps precisely:
### Step 1: Extract claims
Break the response into individual, atomic factual claims. Each claim should be a single assertion that can be independently verified. Ignore meta-commentary, hedging phrases, and discourse markers.
If the response contains no factual claims (e.g., it is a refusal or purely a question), note this.
### Step 2: Classify each claim
For each extracted claim, classify it as:
- **Grounded**: The claim is directly stated in or logically entailed by the retrieved context.
- **Hallucinated (contradiction)**: The claim directly contradicts information in the retrieved context.
- **Hallucinated (fabrication)**: The claim introduces information not present in the retrieved context. This includes plausible-sounding facts, specific numbers, dates, or attributions that cannot be verified from the context.
Important: A claim based on common knowledge or general reasoning that is NOT in the retrieved context counts as a fabrication for this metric. The retrieved context is the only valid source of truth.
### Step 3: Calculate the hallucination score
Hallucination Score = (number of hallucinated claims) / (total number of claims).
If there are zero claims, the score is 0.0 (no hallucination).
Note: This score is INVERTED relative to Faithfulness. A score of 0.0 means no hallucination (best). A score of 1.0 means every claim is hallucinated (worst).
## Output format
Return your analysis as JSON with this exact structure:
{
"claims": [
{"claim": "<atomic claim text>", "classification": "grounded|hallucinated_contradiction|hallucinated_fabrication", "evidence": "<quote from context if grounded, or explanation of the contradiction/fabrication>"},
...
],
"num_hallucinated": <integer>,
"num_total": <integer>,
"score": <float between 0.0 and 1.0>,
"reasoning": "<1-2 sentence summary of hallucination assessment>"
}
期望输出格式:JSON 对象,含 claims 数组(每项含 claim、classification 枚举、evidence)、num_hallucinated、num_total、score(0-1 浮点,0 为最佳)与 reasoning。
边界情况:
- 响应无 claim:分数 0.0(未检测到幻觉)。与 Faithfulness 模板一致(零 claim 返回 1.0)——同一 claim 集下两个分数之和应约为 1.0;
- 矛盾 vs. 编造:二者都归类为幻觉,但区别保留在
classification字段中,允许用户按类型过滤; - 部分正确的 claim:大体正确但含编造细节(如实体正确、日期错误)的 claim 归类为幻觉,
evidence字段解释部分不匹配; - 常识:视为编造——prompt 明确声明检索上下文是唯一有效信源。
与 Faithfulness 的关系:对任意给定响应,Hallucination.score 应近似等于 1.0 - Faithfulness.score。二者使用相同的 claim 提取方法学但以相反方向报告。用户可按仪表盘偏好同时运行或任选其一。模板独立维护,允许差异化演进(例如未来 Hallucination 可增加严重度加权而不影响 Faithfulness)。
验证策略:与 Faithfulness 模板交叉验证——对 50+ 样本验证 Hallucination.score + Faithfulness.score 在 1.0 的 0.05 范围内(允许独立运行间轻微的 claim 提取差异);对 50 个含已知编造的响应人工标注,目标幻觉 claim 检出精确率 ≥ 85%、召回率 ≥ 75%;与 DeepEval 的 Hallucination 指标在同一数据集上对比。
4.6 Answer Correctness(回答正确性)
- 目的:对照金标准参考回答评估模型输出的事实准确性与完整性。与 Faithfulness(检查上下文锚定)不同,Answer Correctness 检查最终回答是否真正正确,无论当时可用的上下文是什么。
- 消费的 reference key:
reference_answer - 评分类型:0-1 连续值
Judge prompt:
You are an expert evaluator assessing the factual correctness of a response by comparing it against a verified reference answer. Your task is to determine how accurate and complete the response is relative to the ground truth.
## Inputs
**User query:**
{{ task_input }}
**Reference answer (verified ground truth):**
{{ reference_data.reference_answer }}
**Response to evaluate:**
{{ final_message }}
## Instructions
Follow these steps precisely:
### Step 1: Extract key facts from the reference answer
Identify the essential factual assertions in the reference answer. These are the facts that a correct response MUST include or be consistent with. Distinguish between:
- **Core facts**: Central to answering the query. Missing these means the answer is fundamentally wrong or incomplete.
- **Supporting details**: Provide additional context or precision. Missing these reduces quality but does not make the answer wrong.
### Step 2: Check the response against each fact
For each fact from the reference answer, determine whether the response:
- **Matches**: States the fact correctly (exact match or semantically equivalent paraphrase).
- **Contradicts**: States something that conflicts with the fact.
- **Omits**: Does not mention the fact.
### Step 3: Check for fabricated content
Identify any claims in the response that are not present in the reference answer. Classify each as:
- **Correct elaboration**: True additional detail that is consistent with the reference (do not penalize).
- **Incorrect addition**: A false or misleading claim not supported by the reference (penalize).
### Step 4: Calculate the correctness score
Consider the following factors:
- Coverage of core facts (heaviest weight)
- Coverage of supporting details (moderate weight)
- Contradictions (heavy penalty)
- Incorrect additions (moderate penalty)
- Correct elaborations (no penalty)
Scoring guide:
- **1.0**: All core facts and most supporting details match. No contradictions. No incorrect additions.
- **0.7-0.9**: All core facts match. Minor omissions of supporting details or minor incorrect additions.
- **0.4-0.6**: Most core facts match but some are omitted or contradicted. Or significant incorrect additions.
- **0.1-0.3**: Few core facts match. Major contradictions or omissions.
- **0.0**: No core facts match or the response fundamentally contradicts the reference.
## Output format
Return your analysis as JSON with this exact structure:
{
"reference_facts": [
{"fact": "<fact from reference>", "type": "core|supporting", "status": "matches|contradicts|omits", "response_text": "<relevant quote from response, or null if omitted>"},
...
],
"fabricated_content": [
{"claim": "<claim not in reference>", "classification": "correct_elaboration|incorrect_addition"},
...
],
"num_core_matched": <integer>,
"num_core_total": <integer>,
"num_contradictions": <integer>,
"num_incorrect_additions": <integer>,
"score": <float between 0.0 and 1.0>,
"reasoning": "<1-2 sentence summary of correctness assessment>"
}
期望输出格式:JSON 对象,含 reference_facts 数组(每项含 fact、type、status、response_text)、fabricated_content 数组(每项含 claim、classification)、汇总计数、score(0-1 浮点)与 reasoning。
边界情况:
- 响应比参考更详细:正确阐述不惩罚,仅事实错误的添加降低分数;
- 响应措辞不同:接受语义等价,prompt 要求匹配而非逐字复述;
- 部分回答:正确回答部分查询但遗漏大段的响应获得中间分数;
- 多个有效答案:若参考回答覆盖一种有效解释而响应覆盖另一种同样有效的解释,judge 应在 reasoning 中注明。这是已知局限——参考回答被视为权威;
- 空响应:分数 0.0(无事实匹配)。
验证策略:对 50-100 个查询-参考-响应三元组人工标注 5 分制正确性,转换 0-1 后与模板对比,目标 Spearman rho ≥ 0.7;与 DeepEval 的 Answer Correctness 和 Braintrust 的 Answer Correctness scorer 在同一数据集上对比;包含"自信流畅但事实错误"的对抗性样本。
5. 模板的底层运行机制:从源码看 llm_judge 适配器
这套模板最终由 libs/core/kiln_ai/adapters/eval/v2_eval_llm_judge.py 中的 LlmJudgeEval.evaluate() 执行。理解这段实现有助于正确使用模板:
1)reference key 预检查(在渲染与任何模型调用之前)。LlmJudgeProperties 上有一个 reference_keys: list<a href="https://link.gitcode.com/i/da164e0330dc0b8546f16c3962d169fc" target="_blank">str] 字段(见 [eval.py 第 103-115 行),适配器对每个声明的 key 调用 check_reference_key()(位于 v2_eval_helpers.py 第 114-141 行)做存在性检查——reference_data 为 None、key 不存在、或值为 None 均返回 SkippedReason.missing_reference_key。源码注释明确这一设计意图:"a judge that declares a reference key it cannot get must skip loudly, not score blind"(声明了却拿不到的 reference key 必须响亮地跳过,而不是盲目打分)。这就是原文档第 2.4 节所述"缺失 key 导致 case 被跳过(仅存在性检查,无类型检查)"的落点。
2)Jinja2 沙箱渲染。模板用 libs/core/kiln_ai/utils/jinja_engine.py 中的 SandboxedEnvironment(undefined=StrictUndefined, ...) 渲染。原文档开放问题(O-rag-template-var-rendering,RESOLVED 2026-06-06)确认:{% for chunk in reference_data.retrieved_context %} 与 {{ loop.index }} 是 Jinja2 核心控制结构,沙箱只限制不安全的属性/内建访问,不限制对 list[str] 的迭代,因此无需任何预格式化。若渲染抛出 UndefinedError,适配器会用 _unknown_template_variables() 区分"模板作者拼错变量名"(extraction_failed)与"确实缺失 reference 数据"(missing_reference_key)。
3)可选的 required_var 作者规则。原文档第 6 节增加的作者规则:每个模板必须在 EvalConfig 的 required_var 列表中声明其必需 reference key(如 retrieved_context),使缺失 key 在渲染前产生干净的 skip(extraction_failed / missing_reference_key,依 C.runner.1),而非渲染时的硬 StrictUndefined 错误;可选 key(如 ground_truth_context)则保留在 {% if reference_data.<key> %} 保护内并从 required_var 中省略。50_reference_data.md 第 3.2 节给出了 required_var=<a href="https://link.gitcode.com/i/206066b5a4a986e5511fcaaceca24bf0" target="_blank">"reference_data.reference_answer"] 的声明示例。在 V2 数据模型中,SkippedReason 枚举([eval.py 第 517-526 行)把 missing_reference_key 与 extraction_failed 作为终态 skip 原因持久化,且 skip 计入指标 provenance 的 n_excluded,但不是硬失败——其他不依赖缺失 key 的 EvalConfig 仍会针对该 EvalInput 继续运行(C.runner.1 契约:尽力而为的部分评估)。
4)judge 模型调用。渲染出的 prompt 通过临时 _LlmJudgeTask(一个携带 system prompt 与输出 JSON schema 的临时 Task)经 adapter_for_task() 调用用户配置的 judge 模型(LlmJudgeProperties.model_name / .model_provider),结构化输出模式自动选择(默认 json_schema,禁用 function_calling 相关模式)。
6. Builder UX 集成:降低 RAG 评估的落地门槛
与 Batch G(70_builder_and_onboarding.md)协同,原设计文档第 4 节规定了以下集成点:
- RAG 目标检测:用户在 builder 问卷中选择 "RAG evaluation"(或同义目标,如 "evaluate my retrieval pipeline"、"check for hallucinations")时,系统应从该模板库预填充一组默认 EvalConfig。推荐默认组合:Faithfulness + Answer Relevance + Context Relevance——三者只需
retrieved_context,是用户最可能已有的数据。 - Reference-key 脚手架:选中 RAG 模板时,builder 应为新 EvalInput 自动搭建预期的 reference key:提示用户填充
retrieved_context(多数 RAG 模板必需)、可选reference_answer(选中 Answer Correctness 时)、可选ground_truth_context(希望做带 ground truth 的 Context Precision 时)。 retrieved_context填充指引:builder 应包含行内指引:"为每个查询填充retrieved_context,内容是 RAG 流水线返回的文本块。若使用 Langfuse、Phoenix 或其他 tracing 工具,可从生产 trace 导出检索结果;手工测试时直接粘贴 chunk。"生产 trace 摄入连接器(Langfuse、Phoenix)在 V2 中超出范围,但应标注为未来集成点。- 模板选择 UI:6 个模板应可单独勾选;builder 应展示每个模板需要的 reference key,让用户在提交前理解数据要求。
7. 验证计划:模板上线的量化门槛
7.1 每模板金标准数据集
为 6 个模板各构建 50-100 样本的人工标注金标准数据集:
- Faithfulness / Hallucination:带逐 claim 人工标签(grounded / fabricated / contradicted)的 RAG 响应;
- Answer Relevance:带人工相关性分数(5 分制转 0-1)的查询-响应对;
- Context Relevance:带逐 chunk 人工相关性标签的查询-上下文对;
- Context Precision:带逐 chunk 有用性标签的查询-上下文对,一半带 ground truth 上下文、一半不带;
- Answer Correctness:带人工正确性分数的查询-参考-响应三元组。
7.2 相关性目标
- 主要指标:模板分数与人工标签的 Spearman 秩相关;
- 目标:每个模板 rho ≥ 0.7;
- 次要指标:claim 级与 chunk 级模板(Faithfulness、Hallucination、Context Relevance、Context Precision)的逐 claim/逐 chunk 一致率 ≥ 80%。
7.3 跨工具基准对比
- 与 DeepEval 的 RAG 指标(Faithfulness、Contextual Relevancy、Contextual Precision、Answer Correctness)在同一数据集上 A/B 测试,Kiln 模板应达到与人工标签相当或更好的相关度;
- 与 Braintrust 的 autoevals RAG scorer(Faithfulness、Context Precision、Answer Relevancy、Answer Correctness)在同一数据集上 A/B 测试;
- 记录任何系统性分歧并解释(如 claim 提取粒度差异、相关性阈值差异)。
7.4 RAGAS 基准相关性
在已发表的 RAGAS 评估基准(faithfulness、context recall)上,将 Kiln 模板分数与 RAGAS 分数对比。注意:RAGAS 部分指标采用 NLI 方法,方法学差异可能解释分数分歧,需记录。
7.5 上线签收标准
模板可发布当满足:
- 金标准数据集上对人工标签的 Spearman rho ≥ 0.7;
- 对抗性测试中无系统性失败模式;
- 跨工具对比未显示与既有实现出现意外分歧。
8. 开放问题与设计决策记录
原设计文档第 6 节记录了以下决策(截至 2026-06-06 多数已解决):
- 默认 judge 模型(RESOLVED — Steve, 2026-06-06):claim 提取类模板(Faithfulness、Hallucination、Context Precision)需要较强的 judge 模型,但无需强制执行、无需新机制——Kiln 现有的模型选择器已引导用户使用 frontier 级模型,这就是操作性建议。模板假定 judge 能力不低于 Claude Sonnet 4 / GPT-4o 级别,在小模型上会退化;无硬性门禁。judge 模型即用户配置的
llm_judge模型(LlmJudgeProperties.model_name/.model_provider)。Phase 6 的金标准数据验证可在后续细化措辞。 - Hallucination 作为独立模板 vs.
1 - Faithfulness:设计上两者同时发布。保留双模板的理由:(a) DeepEval/LangSmith 生态的用户预期;(b) 两个指标可能独立演进(如 Hallucination 未来可加严重度加权);(c) 反向框架对缺陷仪表盘更自然。合并的理由:(a) 计算冗余;(b) 分数应和为 1.0,任何偏差都令人困惑。决策:V2.0 同时发布;若用户反馈冗余造成困惑再重新评估。 - 未来复合 "RAG score" 汇总:多个竞品(DeepEval 的 RAGAS composite、Promptfoo 的 derivedMetrics)提供单一复合 RAG 分数。V2.0 超出范围——需要
compositeEvalConfigType(依 A2.4 推迟到 Phase 7)。记为 Phase 7 候选。 - 基于 embedding 的指标:Answer Similarity(输出与参考之间的 embedding 余弦相似度)与 Context Recall(检索上下文与 ground truth 上下文之间的 embedding 重叠)推迟到 Phase 7,随
embedding_similarityEvalConfigType 交付。二者需要llm_judge类型不提供的 embedding 模型基础设施。 - 模板变量渲染(O-rag-template-var-rendering — RESOLVED 2026-06-06):原样支持,无 schema 或引擎改动。
llm_judge模板引擎是 Jinja2SandboxedEnvironment(components/06节,经libs/core共享)。{% for chunk in reference_data.retrieved_context %}与{{ loop.index }}是核心 Jinja2 控制结构——沙箱仅限制不安全的属性/内建访问,不限制对list[str]的迭代,无需预格式化。作者规则(新增):每个模板必须在 EvalConfig 的required_var列表中声明必需 reference key,使缺失 key 产生干净的渲染前 skip(extraction_failed/missing_reference_key,依 C.runner.1)而非渲染时的硬StrictUndefined错误;可选 key 由{% if reference_data.<key> %}保护并省略出required_var。这一规则与源码中SkippedReason枚举、check_reference_key()的存在性检查实现完全对应。 - Claim 提取一致性:Faithfulness 与 Hallucination 各自独立做 claim 提取。同一响应上的两次独立 judge 调用可能提取出略有差异的 claim 集。这是可接受的(每个模板是独立 eval),但可能导致
Faithfulness.score + Hallucination.score轻微偏离 1.0。文档要求记录此预期方差。
9. Opens 状态
截至 Stage 5(2026-06-06),此前跟踪的所有 opens 均已解决,原文档第 8 节记录了决议:
- (O-rag-template-var-rendering) RESOLVED——沙箱化 Jinja2 支持对
reference_data列表子路径的{% for %}迭代,无需预格式化。见第 8 节 "Template variable rendering" 的决议与required_var作者规则。 - (O-rag-min-judge-model) RESOLVED(Steve)——仅记录建议(capable/frontier 级 judge);Kiln 现有模型选择器已引导用户到 frontier 模型。无门禁。见第 8 节 "Default judge model"。
- RAG Quick Start 指南 RESOLVED——不是 V2.0 设计阻塞;依靠第 6 节的 builder UX 呈现工作流。独立 quick-start 指南是可选的文档期加分项,不是设计依赖。
- 缺失必需 key 的行为 RESOLVED——通过
required_var预检查实现干净的 skip(非硬失败),在渲染前以extraction_failed/missing_reference_key跳过(C.runner.1 /components/45)。已由第 8 节的作者规则承载。 - [ ] 未决:
ground_truth_context是否应提升为 Context Precision 的必需键(而非可选),还是保留"仅查询有用性"的降级模式更有价值。
10. 总结:如何在项目中使用这套模板
综合原文档与源码,落地这套 RAG 评估模板的完整路径是:
- 数据准备:在创建 EvalInput 时填充
referencedict——至少提供retrieved_context(list[str],非空);按需提供reference_answer(str)与ground_truth_context(list[str])。 - 配置选择:在 EvalConfig 中以
llm_judge类型装载对应模板的prompt_template,在LlmJudgeProperties.reference_keys(或required_var)中声明消费的 reference key,并设置model_name/model_provider为能力足够的 judge 模型。 - 运行与解读:runner 在渲染前校验 reference key 存在性,缺失即 skip(
missing_reference_key)而非硬失败;渲染失败会区分模板笔误(extraction_failed)与数据缺失。Hallucination 与 Faithfulness 成对解读(二者之和约为 1.0),Context Precision 的mode字段可确认是否使用了 ground truth 路径。 - 质量把关:按第 7 节的验证计划对标人工标注(Spearman rho ≥ 0.7、逐 claim/chunk 一致率 ≥ 80%),并对照 DeepEval / Braintrust / RAGAS 的既有实现记录系统分歧。
这套设计通过"三个规范 reference key + 六个结构化 judge prompt + 干净的 skip 语义"在零 schema 改动的约束下为 Kiln 补齐了 RAG 评估能力,其模板变量约定、required_var 作者规则与缺失键处理均已在 libs/core 的 V2 llm_judge 适配器中得到实现级印证(v2_eval_llm_judge.py、v2_eval_helpers.py、eval.py)。此外,项目数据模型中的 rag.py(RagConfig)已承载 RAG 流水线各环节的配置(extractor、chunker、embedding、vector store、reranker),本模板库可与之一同构成完整的 RAG 开发与评估闭环。