evaluate-rag

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Evaluate RAG

评估RAG

Overview

概述

  1. Do error analysis on end-to-end traces first. Determine whether failures come from retrieval, generation, or both.
  2. Build a retrieval evaluation dataset: queries paired with relevant document chunks.
  3. Measure retrieval quality with Recall@k (most important for first-pass retrieval).
  4. Evaluate generation separately: faithfulness (grounded in context?) and relevance (answers the query?).
  5. If retrieval is the bottleneck, optimize chunking via grid search before tuning generation.
  1. 首先对端到端轨迹进行错误分析,确定故障来自检索、生成还是两者皆有。
  2. 构建检索评估数据集:将查询与相关文档分块配对。
  3. 使用Recall@k衡量检索质量(对首次检索最为重要)。
  4. 单独评估生成内容:忠实性(是否基于上下文?)和相关性(是否回答了查询?)。
  5. 如果检索是瓶颈,在调优生成之前通过网格搜索优化分块策略。

Prerequisites

前提条件

Complete error analysis on RAG pipeline traces before selecting metrics. Inspect what was retrieved vs. what the model needed. Determine whether the problem is retrieval, generation, or both. Fix retrieval first.
完成RAG流水线轨迹的错误分析后再选择指标。检查检索到的内容与模型所需内容之间的差异,确定问题出在检索、生成还是两者皆有。优先修复检索问题。

Core Instructions

核心指南

Evaluate Retrieval and Generation Separately

分别评估检索与生成

Measure each component independently. Use the appropriate metric for each retrieval stage:
  • First-pass retrieval: Optimize for Recall@k. Include all relevant documents, even at the cost of noise.
  • Reranking: Optimize for Precision@k, MRR, or NDCG@k. Rank the most relevant documents first.
独立衡量每个组件。为每个检索阶段选择合适的指标:
  • 首次检索: 针对Recall@k进行优化。即使引入噪声,也要覆盖所有相关文档。
  • 重排序: 针对Precision@k、MRR或NDCG@k进行优化。将最相关的文档排在首位。

Building a Retrieval Evaluation Dataset

构建检索评估数据集

You need queries paired with ground-truth relevant document chunks.
Manual curation (highest quality): Write realistic questions and map each to the exact chunk(s) containing the answer.
Synthetic QA generation (scalable): For each document chunk, prompt an LLM to extract a fact and generate a question answerable only from that fact.
Synthetic QA prompt template:
Given a chunk of text, extract a specific, self-contained fact from it.
Then write a question that is directly and unambiguously answered
by that fact alone.

Return output in JSON format:
{ "fact": "...", "question": "..." }

Chunk: "{text_chunk}"
Adversarial question generation: Create harder queries that resemble content in multiple chunks but are only answered by one.
Process:
  1. Select target chunk A containing a clear fact.
  2. Find similar chunks B, C using embedding search (chunks that share terminology but lack the answer).
  3. Prompt the LLM to write a question using terminology from B and C that only chunk A answers.
Example:
  • Chunk A: "In April 2020, the company reported a 17% drop in quarterly revenue, its largest decline since 2008."
  • Chunk B: "The company experienced significant losses in 2008 during the financial crisis."
  • Generated question: "When did the company experience its largest revenue decline since the 2008 financial crisis?"
Only chunk A contains the answer. Chunk B is a plausible distractor.
Filtering synthetic questions: Rate synthetic queries for realism using few-shot LLM scoring. Keep only those rated realistic (4-5 on a 1-5 scale). Likert scoring is appropriate here, since the goal is fuzzy ranking for dataset curation, not measuring failure rates.
你需要将查询与真实相关的文档分块配对。
人工整理(最高质量): 编写贴合实际的问题,并将每个问题映射到包含答案的具体分块。
合成问答生成(可扩展): 针对每个文档分块,提示大语言模型(LLM)提取一个事实,并生成只能通过该事实回答的问题。
合成问答提示模板:
Given a chunk of text, extract a specific, self-contained fact from it.
Then write a question that is directly and unambiguously answered
by that fact alone.

Return output in JSON format:
{ "fact": "...", "question": "..." }

Chunk: "{text_chunk}"
对抗式问题生成: 创建难度更高的查询,这些查询与多个分块的内容相似,但只能由其中一个分块回答。
流程:
  1. 选择包含明确事实的目标分块A。
  2. 使用嵌入搜索找到相似分块B、C(这些分块共享术语但不包含答案)。
  3. 提示LLM使用B和C中的术语编写一个只能由分块A回答的问题。
示例:
  • 分块A:"In April 2020, the company reported a 17% drop in quarterly revenue, its largest decline since 2008."
  • 分块B:"The company experienced significant losses in 2008 during the financial crisis."
  • 生成的问题:"When did the company experience its largest revenue decline since the 2008 financial crisis?"
只有分块A包含答案,分块B是一个合理的干扰项。
过滤合成问题: 使用少样本LLM评分对合成查询的真实性进行评级。仅保留评级为真实的查询(1-5分制中的4-5分)。此处适合使用李克特评分,因为目标是对数据集整理进行模糊排序,而非衡量失败率。

Retrieval Metrics

检索指标

Recall@k: Fraction of relevant documents found in the top k results.
Recall@k = (relevant docs in top k) / (total relevant docs for query)
Prioritize recall for first-pass retrieval. LLMs can ignore irrelevant content but cannot generate from missing content.
Precision@k: Fraction of top k results that are relevant.
Precision@k = (relevant docs in top k) / k
Use for reranking evaluation.
Mean Reciprocal Rank (MRR): How early the first relevant document appears.
MRR = (1/N) * sum(1/rank_of_first_relevant_doc)
Best for single-fact lookups where only one key chunk is needed.
NDCG@k (Normalized Discounted Cumulative Gain): For graded relevance where documents have varying utility. Rewards placing more relevant items higher.
DCG@k  = sum over i=1..k of: rel_i / log2(i+1)
IDCG@k = DCG@k with documents sorted by decreasing relevance
NDCG@k = DCG@k / IDCG@k
Caveat: Optimal ranking of weakly relevant documents can outscore a highly relevant document ranked lower. Supplement with Recall@k.
Choosing k: k varies by query type. A factual lookup uses k=1-2. A synthesis query ("summarize market trends") uses k=5-10.
Recall@k: 在前k个结果中找到的相关文档占比。
Recall@k = (relevant docs in top k) / (total relevant docs for query)
首次检索优先考虑召回率。LLM可以忽略无关内容,但无法基于缺失内容生成回答。
Precision@k: 前k个结果中相关文档的占比。
Precision@k = (relevant docs in top k) / k
用于重排序评估。
Mean Reciprocal Rank (MRR): 第一个相关文档出现的位置有多靠前。
MRR = (1/N) * sum(1/rank_of_first_relevant_doc)
最适用于仅需一个关键分块的单事实查询。
NDCG@k(归一化折损累积增益): 适用于文档效用不同的分级相关性场景。奖励将更相关的内容排在更靠前的位置。
DCG@k  = sum over i=1..k of: rel_i / log2(i+1)
IDCG@k = DCG@k with documents sorted by decreasing relevance
NDCG@k = DCG@k / IDCG@k
注意:弱相关文档的最优排名可能超过排名较低的高度相关文档。需结合Recall@k使用。
选择k值: k值因查询类型而异。事实查询使用k=1-2,综合查询(如“总结市场趋势”)使用k=5-10。

Metric Selection

指标选择

Query TypePrimary Metric
Single-fact lookupsMRR
Broad coverage neededRecall@k
Ranked quality mattersNDCG@k or Precision@k
Multi-hop reasoningTwo-hop Recall@k
查询类型核心指标
单事实查询MRR
需要广泛覆盖Recall@k
排名质量重要NDCG@k 或 Precision@k
多跳推理Two-hop Recall@k

Evaluating and Optimizing Chunking

评估与优化分块策略

Treat chunking as a tunable hyperparameter. Even with the same retriever, metrics vary based on chunking alone.
Grid search for fixed-size chunking: Test combinations of chunk size and overlap. Re-index the corpus for each configuration. Measure retrieval metrics on your evaluation dataset.
Example search grid:
Chunk sizeOverlapRecall@5NDCG@5
128 tokens00.820.69
128 tokens640.880.75
256 tokens00.860.74
256 tokens1280.890.77
512 tokens00.800.72
512 tokens2560.830.74
Content-aware chunking: When fixed-size chunks split related information:
  • Use natural document boundaries (sections, paragraphs, steps).
  • Augment chunks with context: prepend document title and section headings to each chunk before embedding.
将分块视为可调超参数。即使使用相同的检索器,指标也会因分块方式不同而变化。
固定大小分块的网格搜索: 测试分块大小与重叠度的组合。为每种配置重新索引语料库,在评估数据集上衡量检索指标。
示例搜索网格:
分块大小重叠度Recall@5NDCG@5
128 tokens00.820.69
128 tokens640.880.75
256 tokens00.860.74
256 tokens1280.890.77
512 tokens00.800.72
512 tokens2560.830.74
基于内容的分块: 当固定大小分块拆分相关信息时:
  • 使用自然文档边界(章节、段落、步骤)。
  • 为分块添加上下文:在嵌入前为每个分块添加文档标题和章节标题。

Evaluating Generation Quality

评估生成质量

After confirming retrieval works, evaluate what the LLM does with the retrieved context along two dimensions:
Answer faithfulness: Does the output accurately reflect the retrieved context? Check for:
  • Hallucinations: Information absent from source documents. In RAG, even correct facts from the LLM's own knowledge count as hallucinations.
  • Omissions: Relevant information from the context ignored in the output.
  • Misinterpretations: Context information represented inaccurately.
Answer relevance: Does the output address the original query? An answer can be faithful to the context but fail to answer what the user asked.
Use error analysis to discover specific manifestations in your pipeline. Identify what kind of information gets hallucinated and which constraints get omitted.
确认检索正常工作后,从两个维度评估LLM对检索到的上下文的处理情况:
回答忠实性: 输出是否准确反映检索到的上下文?检查以下问题:
  • 幻觉: 源文档中不存在的信息。在RAG中,即使是LLM自身知识中的正确事实也属于幻觉。
  • 遗漏: 忽略了上下文中的相关信息。
  • 误解: 上下文信息被错误呈现。
回答相关性: 输出是否回应了原始查询?回答可能忠实于上下文,但未能解答用户的问题。
使用错误分析发现流水线中的具体问题表现,确定哪些信息会产生幻觉,哪些约束被遗漏。

Diagnosing Failures by Metric Pattern

按指标模式诊断故障

Context RelevanceFaithfulnessAnswer RelevanceDiagnosis
HighHighLowGenerator attended to wrong section of a correct document
HighLow--Hallucination or misinterpretation of retrieved content
Low----Retrieval problem. Fix chunking, embeddings, or query preprocessing
上下文相关性忠实性回答相关性诊断结果
生成器关注了正确文档的错误部分
--对检索内容产生幻觉或误解
----检索问题。修复分块、嵌入或查询预处理

Multi-Hop Retrieval Evaluation

多跳检索评估

For queries requiring information from multiple chunks:
Two-hop Recall@k: Fraction of 2-hop queries where both ground-truth chunks appear in the top k results.
TwoHopRecall@k = (1/N) * sum(1 if {Chunk1, Chunk2} ⊆ top_k_results)
Diagnose failures by classifying: hop 1 miss, hop 2 miss, or rank-out-of-top-k.
针对需要从多个分块获取信息的查询:
Two-hop Recall@k: 两个真实分块均出现在前k个结果中的多跳查询占比。
TwoHopRecall@k = (1/N) * sum(1 if {Chunk1, Chunk2} ⊆ top_k_results)
通过分类诊断故障:第一跳未命中、第二跳未命中,或排名超出前k位。

Anti-Patterns

反模式

  • Using a single end-to-end correctness metric without separating retrieval and generation measurement.
  • Jumping directly to metrics without reading traces first.
  • Overfitting to synthetic evaluation data. Validate against real user queries regularly.
  • Using similarity metrics (ROUGE, BERTScore, cosine similarity) as primary generation evaluation. Use binary evaluators driven by error analysis.
  • Evaluating generation without checking context grounding.
  • 使用单一端到端正确性指标,而非分开衡量检索与生成。
  • 未先查看轨迹就直接使用指标。
  • 过度拟合合成评估数据。定期用真实用户查询验证。
  • 将相似性指标(ROUGE、BERTScore、余弦相似度)作为生成评估的主要指标。使用由错误分析驱动的二元评估器。
  • 评估生成内容时未检查上下文关联性。