Skip to content

Metrics and RAGAS

Chapter 9 2 code blocks 2605 words

Metrics: how to know a RAG system is good

Say this

I measure each part separately, because a bad answer can come from retrieval or from generation and the fix is different. Retrieval: did the right chunk come back, and how high? Recall@k, MRR and nDCG on questions labelled with their correct chunk. Generation: is every claim supported by the evidence (faithfulness), does it answer the question (relevance), and does it match the reference answer (correctness)? Refusals: does it answer what it can and refuse what it can't? I count wrong answers to unanswerable questions as the worst error. Plus operations: p95 latency, tokens and cost per question. In my project, 23 labelled questions run end to end, 15 that must be answered and 8 that must be refused, all passing, and every question is traced with its chunks and latency.

Retrieval
  • Recall@k
  • MRR, nDCG
  • Context precision
  • Context recall
Generation
  • Faithfulness
  • Answer relevance
  • Citation validity
Answer
  • Correctness
  • Refusal accuracy
Operations: latency p50/p95, tokens, cost
Online: thumbs up/down, follow-ups, escalations

1. Retrieval metrics

(need: each question labelled with its correct chunk ids)

MetricFormula / meaningAnswers the question
Recall@k (hit rate)share of questions whose correct chunk is in the top k"Did we find it at all?" The most important one
Precision@krelevant chunks in top k ÷ k"How much of what we send is useful?"
MRRmean of 1 ÷ rank of the first correct chunk"Is the right one near the top?"
nDCG@k∑k=1relklog2(k+1), divided by the ideal order's value"Is the whole order good?" (graded relevance)
∑k=1relklog2(k+1)
relkhow relevant the result at position k is (0, 1, 2 …)
log2(k+1)the discount: lower positions count less
÷ IDCGdivide by the same sum for the perfect order, so the result is between 0 and 1

Worked example: 3 questions, top 5

Q1
correct chunk at rank 1
  • hit · 1/1 = 1.00
Q2
correct chunk at rank 3
  • hit · 1/3 = 0.33
Q3
not in the top 5
  • miss · 0
Recall@5 = 2/3 = 0.67
MRR = (1 + 0.33 + 0) / 3 = 0.44
nDCG for Q2 (one relevant, at rank 3) = (1/log₂4) / (1/log₂2) = 0.5

Low Recall@k → fix retrieval (chunking, hybrid search, embedding model). Good recall but low MRR → fix ordering (reranker).

2. Generation metrics

MetricMeaningHow to measure
Faithfulness (groundedness)supported claims ÷ all claims in the answersplit the answer into claims; check each against the evidence (an LLM judge or an NLI model)
Answer relevancedoes the answer address the question, not something nearby?a judge, or embed questions generated from the answer and compare with the real question
Answer correctnessdoes it match the reference answer?exact or keyword match for facts; a judge for free text
Citation validityevery cited ID exists and supports its sentencecode check (I do this) + a judge for the "supports" part
Context precision / recall (RAGAS)were the useful chunks ranked high / did the context contain everything needed?a judge against the reference answer

3. Answer vs refuse: the confusion matrix

System ANSWEREDSystem REFUSED
Answerable question✔ correct / ✘ wrong✘ false refusal (annoying)
Unanswerable question✘ HALLUCINATION (worst)✔ correct refusal

Report both rates: false refusals (users lose trust) and answers to unanswerable questions (users get wrong information). For a bank or a government system, the second costs far more, so I tune toward refusing when unsure.

4. Operations and online

: p50/p95 latency (the slow tail matters), tokens and cost per question, refusal rate over time; online thumbs up/down, rephrased follow-ups ("no, I meant…"), escalations to a human.

Example project

  • RAG: eval_rag.py, 23 end-to-end cases. 15 answerable (Uzbek, Russian, English): pass if not refused and the answer contains an expected keyword ("perth", "52", "2022", "venv"…). 8 unanswerable (France, World Cup, bread, Tashkent weather, a prompt injection, "the ship Perth sailed on"): pass only with the exact refusal sentence. Result: 23/23, so 15/15 answered and 8/8 correctly refused. 23 offline unit tests for the chunker, threshold and citation check. retrieval_traces keeps chunk ids and latency for every question.
  • Tez: 1,410 requests scored by executing the plan and comparing result tables: right, silent wrong (runs, looks right, wrong result) and should-ask caught. Headline metric: precision of delivered answers, because a wrong number shown confidently is worse for a bank than a question. tez8 → tez17: right 1,066 → 1,298, silent wrong 138 → 55.

Building the evaluation set

  • Real user questions first; add hard cases on purpose: names, numbers, multi-hop, follow-ups, other languages, typos.
  • Include unanswerable questions (about 20–30%), including on-topic ones whose answer isn't in the documents.
  • Label the correct chunk ids and a short reference answer.
  • Never tune prompts on the test set; keep a held-out part.
  • Run it on every change (CI); compare to the last good run, never look at one number alone.

Trap questions

  • "Can you trust an LLM judge?" Only after checking it against about 50–100 human labels and reporting how often they agree. Use a judge at least as strong as the model being judged.
  • "Your 23 questions: enough?" Enough to catch big breaks, not for fine comparisons: one failure moves the score by about 4 points. For real decisions I'd use 200+ and confidence intervals (bootstrap), as I did in Tez.
  • "BLEU or ROUGE?" Weak for RAG: they count word overlap, so a correct paraphrase scores low and a fluent wrong answer can score high.
  • "Which single metric matters most?" Recall@k for retrieval, because the LLM can't use what wasn't retrieved, plus the hallucination rate on unanswerable questions for trust.

Gap I would fix

My RAG eval checks end-to-end results but doesn't yet measure Recall@k and MRR directly. I'd label the correct chunk id for each question, grow the set to 200+ including on-topic unanswerable questions, report Recall@6, MRR, faithfulness and both refusal rates, and run it in CI so a change that lowers quality is blocked.

RAG evaluation with RAGAS: everything, including the holes

Say this

RAGAS is an open-source framework that scores a RAG system with an LLM as the judge. For each test question you give it the question, the system's answer, the retrieved chunks, and ideally a reference answer. It then computes four core metrics. Faithfulness: the judge splits the answer into statements and checks each against the retrieved context; supported ÷ total. Answer relevancy: it generates questions from the answer and measures how close they are to the real question. Context precision: are the relevant chunks ranked at the top? Context recall: does the retrieved context contain every fact in the reference answer? The first two need no reference, so you can run them on live traffic. But it's an LLM judge, so it's noisy, it costs calls, and it's weaker in Uzbek. I'd check it against human labels before trusting it, evaluate refusals separately, and keep deterministic checks like my citation check alongside it.

One test row (the data RAGAS needs)

json7 lines
{
  "user_input":         "Gumonlanuvchi necha yoshda?",          question
  "response":           "Gumonlanuvchi 52 yoshda [E1].",        my system's answer
  "retrieved_contexts": ["...52 yoshli bog'cha direktori..."],  chunk texts sent to the LLM
  "reference":          "52 yoshda."                            human-written correct answer
}
(older RAGAS versions call these question / answer / contexts / ground_truth)

The four core metrics, how each is really computed

F

Faithfulness: is the answer supported by the retrieved context?

How
1 The judge splits the answer into simple statements. 2 For each statement it decides: can this be inferred from the retrieved context, yes or no? 3 Score = supported ÷ total.
Example
The answer has 4 statements and 3 are in the context → 0.75. The 4th came from the model's memory, which is a hallucination even if it happens to be true.
Needs reference?
No. Works on live traffic.
Catches
Hallucination and adding outside knowledge. My system's main risk.
AR

Answer relevancy: does the answer address the question?

How
1 The judge reads only the answer and writes a few questions (about 3) it would answer. 2 Embed those and the real question. 3 Score = average cosine similarity. Vague, noncommittal answers are penalised.
Example
Similarities 0.91, 0.88, 0.85 → 0.88.
Needs reference?
No.
Catches
Answers that are true but off the point, or padded.
CP

Context precision: are the useful chunks ranked at the top?

How
The judge marks each retrieved chunk relevant (1) or not (0), using the reference. Then: ∑kprecision@k·relknumber of relevant chunks.
∑kprecision@k·relknumber of relevant chunks
precision@kshare of relevant chunks in the top k
relk1 if the chunk at position k is relevant, else 0
Example
Order [relevant, not, relevant]: precision@1 = 1, precision@3 = 2/3 → (1 + 0.67) ÷ 2 = 0.83. Put both relevant ones first and it's 1.0.
Needs reference?
The standard version yes; there is also a version that judges against the response instead.
Catches
Bad ordering, the reranker's job.
CR

Context recall: did retrieval bring everything needed?

How
1 Split the reference answer into claims. 2 For each claim: is it supported by the retrieved context? 3 Score = supported ÷ total.
Example
The reference has 4 facts and the chunks contain 3 → 0.75. One needed fact was never retrieved.
Needs reference?
Yes.
Catches
Missing chunks: chunking, k, hybrid search, embedding model.

More metrics worth knowing

  • Answer correctness: compares the answer with the reference: factual overlap (true positive, false positive and false negative claims → F1) combined with semantic similarity, by default weighted mostly on the factual part.
  • Answer / semantic similarity: embedding similarity between the answer and the reference.
  • Context entity recall: share of the reference's named entities (people, places, numbers) found in the context.
  • Noise sensitivity: how often irrelevant chunks lead the answer into wrong claims.
  • Aspect critique / rubric metrics: yes/no or scored judgments you define ("is it harmful?", "is it in Uzbek?").
  • Agent metrics: tool call accuracy, topic adherence, goal completion, for tool-using agents.
MetricPart it testsNeeds referenceLow score → fix
Faithfulnessgenerationnoprompt rules, grounding check, lower temperature
Answer relevancygenerationnoprompt (answer the question directly), query rewriting
Context precisionretrieval orderyes*reranker, threshold
Context recallretrieval coverageyeschunking, larger k, hybrid search, embedder
Answer correctnessend to endyeswhichever part the others point to

How I'd run it on my own system (local judge, no cloud)

python23 lines
from langchain_ollama import ChatOllama, OllamaEmbeddings
from ragas import EvaluationDataset, evaluate
from ragas.llms import LangchainLLMWrapper
from ragas.embeddings import LangchainEmbeddingsWrapper
from ragas.metrics import (Faithfulness, ResponseRelevancy,
                           LLMContextPrecisionWithReference, LLMContextRecall)

judge = LangchainLLMWrapper(ChatOllama(model="qwen3:8b", temperature=0, num_ctx=24576))
embed = LangchainEmbeddingsWrapper(OllamaEmbeddings(model="qwen3-embedding:4b"))

rows = []
for question, reference in labelled_questions:
    out = app.answer(question)                 # my RAG
    rows.append({"user_input": question,
                 "response": out["answer"],
                 "retrieved_contexts": out["chunk_texts"],
                 "reference": reference})

result = evaluate(EvaluationDataset.from_list(rows),
                  metrics=[Faithfulness(), ResponseRelevancy(),
                           LLMContextPrecisionWithReference(), LLMContextRecall()],
                  llm=judge, embeddings=embed)
print(result.to_pandas())                     # one row per question, one column per metric

Two honest notes: my answer() returns source ids and URLs, not chunk texts, so I'd add the texts in an evaluation mode; and RAGAS class names change between versions, so pin the version and check its docs.

The holes: what RAGAS doesn't tell you, and how I'd cover each

  1. The judge is noisy. The same row can score differently between runs. → Temperature 0, run 3 times, report the mean and spread.
  2. The judge has to be validated. → Label 50–100 rows by hand and measure agreement (percent and Cohen's kappa; under about 0.6, fix the setup before trusting it).
  3. Weak in Uzbek. Judge models are weaker in low-resource languages, so Uzbek scores are less reliable. → Validate per language; report Uzbek, Russian and English separately.
  4. Small local judges break the format. An 8B model may not return the strict JSON RAGAS expects, giving parse errors or NaN. → Count NaNs per metric and never drop them silently; use the strongest judge you can.
  5. Self-judging bias. A model judging its own answers tends to be generous. → Use a different, preferably stronger, judge than the generator.
  6. Refusals don't fit. "Insufficient evidence" has no statements, so faithfulness is empty or NaN and answer relevancy is penalised as noncommittal, even when refusing is correct. → Evaluate refusals separately with the answer/refuse confusion matrix.
  7. Faithful isn't correct. An answer faithfully copied from the wrong chunk scores 1.0 on faithfulness. → Always pair it with context precision and answer correctness.
  8. Context length. 6 chunks × 1800 tokens can exceed the judge's context window and get cut silently, so the judge can't see the evidence. → Set the judge's num_ctx too (the same lesson as my generate fix).
  9. References carry bias. Context recall and correctness are only as good as the reference answers. → Have two people write or check references.
  10. Synthetic test sets are too easy. Generated questions are cleaner than real users' ("filial bo'yicha qarz?"). → Mix in real questions, typos and other languages; keep a held-out set.
  11. Scores aren't comparable across RAGAS versions, judge models or embedding models. → Freeze all three when comparing systems.
  12. Optimizing for the judge. Tuning prompts until the judge is happy can overfit to the judge. → A held-out set, plus human spot checks.
  13. Cost and time. Several LLM calls per metric per row: 200 rows × 4 metrics is thousands of calls. → Run the full set nightly or per release, a small set on every change.
  14. Not covered at all: latency, cost per question, prompt injection, safety, multi-turn follow-ups, access control. → Separate tests for each.
  15. Small sets mislead. With 23 questions, one row moves the score about 4 points. → 200+ rows and bootstrap confidence intervals before claiming an improvement.

Alternatives and neighbours

  • TruLens "RAG triad": context relevance, groundedness, answer relevance. The same idea with different names.
  • DeepEval: pytest-style, includes G-Eval (rubric judged by an LLM with step-by-step criteria); good for CI.
  • Arize Phoenix, LangSmith, Langfuse: tracing plus evaluation on live traffic.
  • promptfoo: YAML test suites for prompts, runs in CI.
  • Deterministic checks: exact or keyword match, citation validity, refusal string, number match. Cheap, stable, no judge needed. Always keep some.

How this maps to what my project already has

RAGAS ideaWhat I have todayGap
Faithfulnessdeterministic citation + word-overlap check on every answer, in productioncan't catch a misreading inside a cited chunk → add an LLM or NLI faithfulness score offline
Answer correctnesseval_rag.py: expected keywords for 15 answerable questionskeywords are coarse → reference answers + correctness
Refusal quality8 must-refuse questions, exact refusal stringmore on-topic unanswerable questions
Context precision / recallchunk ids in retrieval_tracesno labelled correct chunks yet → label them, report Recall@6 and MRR
Operationslatency in ms per questionp95 report, token counts

Trap questions

  • "Faithfulness is high but users complain. Why?" Faithful to the wrong chunk, or faithful but incomplete. Check context precision, context recall and correctness.
  • "Context recall is low. What do you change?" Retrieval: chunking, k, hybrid search, the embedding model, query rewriting. Not the prompt.
  • "Can you run RAGAS without reference answers?" Yes for faithfulness and answer relevancy, so they can monitor live traffic. Recall and correctness need references.
  • "Which judge model?" Different from the generator, at least as strong, validated against human labels, and frozen when comparing.
  • "Is RAGAS enough to ship?" No: add deterministic checks, refusal tests, latency and cost, injection tests, and human review of a sample.

Questions about this chapter?

The course, homework review and the other five books are in Uzbek. Questions in English are welcome on Telegram.

Write on Telegram Contents