Metrics and RAGAS
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.
- Recall@k
- MRR, nDCG
- Context precision
- Context recall
- Faithfulness
- Answer relevance
- Citation validity
- Correctness
- Refusal accuracy
1. Retrieval metrics
(need: each question labelled with its correct chunk ids)
| Metric | Formula / meaning | Answers 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@k | relevant chunks in top k ÷ k | "How much of what we send is useful?" |
| MRR | mean of 1 ÷ rank of the first correct chunk | "Is the right one near the top?" |
| nDCG@k | , divided by the ideal order's value | "Is the whole order good?" (graded relevance) |
Worked example: 3 questions, top 5
- hit · 1/1 = 1.00
- hit · 1/3 = 0.33
- miss · 0
Low Recall@k → fix retrieval (chunking, hybrid search, embedding model). Good recall but low MRR → fix ordering (reranker).
2. Generation metrics
| Metric | Meaning | How to measure |
|---|---|---|
| Faithfulness (groundedness) | supported claims ÷ all claims in the answer | split the answer into claims; check each against the evidence (an LLM judge or an NLI model) |
| Answer relevance | does the answer address the question, not something nearby? | a judge, or embed questions generated from the answer and compare with the real question |
| Answer correctness | does it match the reference answer? | exact or keyword match for facts; a judge for free text |
| Citation validity | every cited ID exists and supports its sentence | code 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 ANSWERED | System 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_traceskeeps 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)
{
"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
Faithfulness: is the answer supported by the retrieved context?
Answer relevancy: does the answer address the question?
Context precision: are the useful chunks ranked at the top?
Context recall: did retrieval bring everything needed?
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.
| Metric | Part it tests | Needs reference | Low score → fix |
|---|---|---|---|
| Faithfulness | generation | no | prompt rules, grounding check, lower temperature |
| Answer relevancy | generation | no | prompt (answer the question directly), query rewriting |
| Context precision | retrieval order | yes* | reranker, threshold |
| Context recall | retrieval coverage | yes | chunking, larger k, hybrid search, embedder |
| Answer correctness | end to end | yes | whichever part the others point to |
How I'd run it on my own system (local judge, no cloud)
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 metricTwo 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
- The judge is noisy. The same row can score differently between runs. → Temperature 0, run 3 times, report the mean and spread.
- 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).
- 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.
- 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.
- Self-judging bias. A model judging its own answers tends to be generous. → Use a different, preferably stronger, judge than the generator.
- 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.
- 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.
- 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_ctxtoo (the same lesson as my generate fix). - References carry bias. Context recall and correctness are only as good as the reference answers. → Have two people write or check references.
- 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.
- Scores aren't comparable across RAGAS versions, judge models or embedding models. → Freeze all three when comparing systems.
- Optimizing for the judge. Tuning prompts until the judge is happy can overfit to the judge. → A held-out set, plus human spot checks.
- 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.
- Not covered at all: latency, cost per question, prompt injection, safety, multi-turn follow-ups, access control. → Separate tests for each.
- 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 idea | What I have today | Gap |
|---|---|---|
| Faithfulness | deterministic citation + word-overlap check on every answer, in production | can't catch a misreading inside a cited chunk → add an LLM or NLI faithfulness score offline |
| Answer correctness | eval_rag.py: expected keywords for 15 answerable questions | keywords are coarse → reference answers + correctness |
| Refusal quality | 8 must-refuse questions, exact refusal string | more on-topic unanswerable questions |
| Context precision / recall | chunk ids in retrieval_traces | no labelled correct chunks yet → label them, report Recall@6 and MRR |
| Operations | latency in ms per question | p95 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.