Learning path: Build and Measure a RAG System · Step 12 of 12
RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
Four answers to "How long until I get my refund?": a good one, one with made-up details, one that answers a different question and one that cites the wrong passage. Each fails a different metric: B scores 0.00 faithful, C 0.40 relevant, D 1.00 faithful but 0.00 grounded. Only A gets three greens.
What you will learn
- Explain why a RAG answer is scored on properties, not compared to one right string
- Split an answer into claims at its citations and check each claim
- Tell faithfulness (in any passage) from groundedness (in the cited passage)
- Score relevance with embeddings and know what it can't catch
Before you start
- Why You Cannot Ship an LLM Feature Without an Eval
- RAG Prompt Assembly and Citations
A RAG system has two halves to score. Retrieval metrics grade the documents it found. This article scores the second half: the answer itself.
The tricky part is that a good answer has no single right form, so we check it one claim at a time with three metrics: faithfulness, groundedness and relevance. The project runs with no API key: a word-overlap rule stands in for a judge model, and a small local embedding model scores relevance.
Three pens for one answer
A student hands in a book report. The question was: why does the hero leave home? The teacher picks up three pens.
- A blue pen: did the report answer that question? That's relevance.
- A green pen: is every line actually in the book? The red car isn't, so that line fails. That's faithfulness.
- A pink pen: do the page numbers check out? One line points to the wrong page. That's groundedness.
Each check can fail on its own. A report can answer the question and still make things up.
No single right answer
Why not compare the answer to a correct one? Take How long until I get my refund? One good answer says "five business days". Another says "about five working days", in completely different words. Both are right, but the strings don't match, so there's no exact text to compare against. Instead, we ask questions about the answer. We score properties of the answer, not its exact words.
One question, four answers
The test case is case.json: the refund question, two help-centre passages, and four answers. Every claim ends with a citation like [1].
{
"question": "How long until I get my refund?",
"passages": {
"1": "Refunds go back to the original payment method within 5 business days of the return arriving at our warehouse.",
"2": "Orders paid with a gift card are refunded as store credit."
},
"answers": {
"A": "Your refund goes back to your original payment method within 5 business days of the return arriving. [1]",
"B": "Your refund arrives within 24 hours. [1] You also get a 10% voucher. [2]",
"C": "Orders paid with a gift card are refunded as store credit. [2]",
"D": "Your refund goes back to your original payment method within 5 business days. [2]"
}
}
A is the good one. B adds made-up details. C is true, but answers a different question. D is true, but cites the wrong passage. Each wrong answer is wrong in a different way, and a good set of metrics should catch each of them.
Break the answer into claims
"""Split an answer into claims; check each against a passage."""
import re
STOP = {"the", "a", "an", "and", "of", "to", "your", "you",
"our", "is", "are", "with", "for", "get", "also", "goes"}
CLAIM = r"(.+?)\[(\d+)\]" # text up to its [n] citation
def claims(answer):
"""[(sentence, cited passage id), ...]"""
found = re.findall(CLAIM, answer)
return [(text.strip(), cite) for text, cite in found]
def words(text):
found = re.findall(r"[a-z0-9%]+", text.lower())
return {w.rstrip("s") for w in found if w not in STOP}
def supports(passage, claim, need=0.7):
"""most of the claim's words are in the passage
(a stand-in for a judge model)"""
w = words(claim)
return len(w & words(passage)) / len(w) >= need
claims cuts the text at each citation, so answer B becomes two claims, each with the passage it cites. words keeps the content words. B's first claim, "Your refund arrives within 24 hours", shares "refund" and "within" with passage 1, but "24", "hours" and "arrives" aren't there. supports divides the shared words by all the words: 0.4, below our line of 0.7, so the claim is not supported.
The stand-in: in a real system, a judge model answers this yes-or-no question ("does this passage support this claim?"). Here the word rule stands in for the judge, so it runs without a key. With an API key you would send the same question to a judge model instead. See LLM-as-Judge.
Faithfulness: is every claim in the context?
"""Three generation metrics for one answer."""
from claims import claims, supports
def faithfulness(answer, passages):
"""share of claims that ANY passage supports"""
found = [any(supports(p, c) for p in passages.values())
for c, _ in claims(answer)]
return sum(found) / len(found)
Any passage will do. Answer A has one claim, and passage 1 supports it: 1.00. Answer B has two claims; "24 hours" isn't in any passage, and neither is the 10% voucher: 0.00. Faithfulness is what catches made-up details.
Groundedness: does the cited passage back it?
def groundedness(answer, passages):
"""share of claims that the passage they CITE supports"""
found = [supports(passages[cite], c) for c, cite in claims(answer)]
return sum(found) / len(found)
Groundedness is stricter: it only checks the passage the claim cites. Answer D's claim is true and passage 1 supports it, but D cites passage 2. So faithfulness gives D 1.00, while groundedness gives it 0.00. Right fact, wrong source. A customer who clicks that citation finds nothing about refund times.
Faithful asks "is it in there somewhere?". Grounded asks "is it where you said?". Some tools use these two names for nearly the same idea, so always check how a tool defines them.
Relevance: does it answer this question?
def relevance(question, answer, model):
"""cosine similarity of question and answer embeddings"""
q, a = model.encode([question, answer], normalize_embeddings=True)
return float(q @ a)
model.encode turns the question and the answer into embeddings. Answers about the same thing point in a similar direction, and the dot product of two normalised vectors is their cosine similarity (see Cosine, Dot Product or Euclidean Distance). A scores 0.77, and C, the gift-card answer, scores 0.40. C is true and grounded, but it answers a different question, and relevance is the one that catches it.
But look at B: it's invented, and it still scores 0.72, because it talks about refunds. Relevance catches the off-topic answer, not the false one.
Four answers, three checks
"""Scores four answers to one question with three metrics."""
import json
from pathlib import Path
from sentence_transformers import SentenceTransformer
from metrics import faithfulness, groundedness, relevance
CASE = json.loads(Path(__file__).with_name("case.json").read_text("utf-8"))
if __name__ == "__main__":
model = SentenceTransformer("all-MiniLM-L6-v2")
q, passages = CASE["question"], CASE["passages"]
print("answer faithful grounded relevant")
for name, answer in CASE["answers"].items():
f = faithfulness(answer, passages)
g = groundedness(answer, passages)
r = relevance(q, answer, model)
print(f"{name:<8}{f:>8.2f}{g:>9.2f}{r:>9.2f}")
python evaluate.py
answer faithful grounded relevant
A 1.00 1.00 0.77
B 0.00 0.00 0.72
C 1.00 1.00 0.40
D 1.00 0.00 0.77
| Answer | What's wrong | Faithful | Grounded | Relevant |
|---|---|---|---|---|
| A | Nothing | 1.00 | 1.00 | 0.77 |
| B | Made-up details | 0.00 | 0.00 | 0.72 |
| C | True, wrong question | 1.00 | 1.00 | 0.40 |
| D | True, wrong citation | 1.00 | 0.00 | 0.77 |
Each wrong answer fails a different column. The good answer is the only one with three greens, and that's why you need all three.
Common mistakes
- Exact-match scoring. "5 business days" and "about five working days" are both right; a string compare calls one of them wrong.
- Scoring the whole answer at once. One true sentence can hide a made-up one. Split into claims first.
- Treating relevance as correctness. Invented answer B still scored 0.72 on relevance.
- Checking only faithfulness. A right fact with the wrong citation (D) sends the customer to the wrong page.
- Trusting a tool's metric names. Read its definitions; "faithfulness" and "groundedness" mean different things in different libraries.
Quick recap
| Metric | Question it asks | Catches |
|---|---|---|
| Faithfulness | Is every claim in some passage? | Made-up details (B) |
| Groundedness | Is every claim in the passage it cites? | Right fact, wrong source (D) |
| Relevance | Does it answer this question? | True but off-topic (C) |
Try it yourself
Add an answer E to case.json that is true to passage 1 but cites [2]. Before you run python evaluate.py, predict its three scores. To run these checks with a library and add your own rules on top, see RAGAS and Custom Evals.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.
Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.
Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.