Module: L2-M06 · Duration: ~120 min (estimate, including the independent exercise) · Previous: L02 · Next: L04
1. Introduction
Once retrieval has put passages into the prompt, the generation step can still fail in three different ways: stating something the passages do not say, citing the wrong source, or answering a different question. This lesson teaches how to check each of these with deterministic checks per claim (a checkable statement), using a simulated judge as a second option, and using a small sample reviewed by a person to learn whether the check can be trusted. The lesson builds on L2-M03-L04 (faithfulness and groundedness as the lab defines them) and L2-M04 (the judge and calibration): it does not repeat them, it only applies them to RAG.
The answers, human labels and judge in the lab are simulated or written by the lab's author (HocVui Tutor, the fictional "Math 4 textbook", a tutor chatbot for grades 3 to 5). The numbers describe the simulation, not a property of a real model. The output of the lesson: a faithfulness and groundedness check for RAG answers, with a comparison table against human labels and a manual spot check plan.
2. Learning objectives
- Distinguish faithfulness, groundedness (the lab's meaning) and answer relevance, and run each check on labelled answers. Practice: §8.2 parts A, C, §9 (TODO 1, 3).
- Read the five citation statuses and explain why a sentence that is correct according to the documents can still be ungrounded. Practice: §8.2 part C, §9 (TODO 3).
- Build the confusion table of a check against human labels (positive class: unsupported claims) and name the missed cases (false accepts, "lọt") and the false rejects ("oan"). Practice: §8.2 part B, §9 (TODO 2).
- Compute the probability that a manual spot check misses every wrong case. Practice: §8.3 (change 26, 29 and 6 in
math.combto compute for another sample). - State what each check does not see. Practice: §6.1, §8.3.
3. Prerequisites and tools
- L2-M03-L04: faithfulness and groundedness as the lab defines them. L2-M04: a judge only flags or ranks, and a person reviews and decides. L2-M06-L02. The code lab
code-labs/l2-m06. - Separating the meanings. Faithfulness: every claim is supported by some passage in the retrieved context. Groundedness, as the lab defines it: the definition of L2-M03-L04 (each claim cites a source id that exists and the cited passage supports it) plus one new condition: the cited id must be in this run's context (the fifth status,
not_retrieved). The general meaning "supported by data" is a broader word, and other tools use the word groundedness in their own sense (§4.1). The positive class in this lesson is "claim not supported" (the check raises a warning), as in L2-M03-L04; "precision" and "recall" here belong to the check, not to retrieval (L02).
4. Concepts
4.1 Three questions and a few names
TruLens calls the three checks around a RAG application the "RAG triad": context relevance (is each retrieved chunk relevant to the question), groundedness (does the answer stay with the context: split it into claims and then look for evidence for each claim) and answer relevance (does the answer address the question) [R3]. Ragas defines faithfulness as the factual consistency between the answer and the retrieved context: the score is the number of claims supported by the context divided by the total number of claims, and the example in the documentation (one of two claims supported) gives 0.5 [R1]. Same idea, two names: record which tool and which formula, instead of writing only "groundedness 0.8".
Answer relevance in Ragas is the mean cosine between the embedding of the question and the embeddings of N questions (default 3) that a model regenerates from the answer; the documentation page states plainly that this metric does not assess factual correctness, and needs an LLM and an embedding model [R2]. The Ragas paper describes a three-dimensional evaluation framework (focused retrieval, faithful use of the context, quality of generation) that needs no human labels [R5] (abstract-only).
The lab has cheaper deterministic checks for all three, and each one is narrower than its name: claim_supported, groundedness, context_relevance (the share of the question's content words that are in the chunk), answer_addresses (the answer contains one of the question's topic words) and answer_correct (contains every required phrase).
4.2 Claim by claim and the five citation statuses
split_claims treats each sentence as a claim; the citation marker [D06-c2] must come before the period, otherwise it becomes a "claim" of its own. claim_supported treats a claim as supported when one sentence of the passage meets three conditions: it has every number in the claim, contains at least 3/4 of the claim's content words, and either both or neither have a negation word ("không", "chưa", "chẳng", the Vietnamese words for "no", "not yet", "not at all"). groundedness returns a status for each claim: grounded; uncited (no citation); unknown_source (the id is not in the corpus); not_retrieved (the id is in the corpus but is not in this run's context); unsupported_by_cited (the cited passage does not support the claim).
The two middle statuses need explaining. Anthropic's citations documentation says the feature returns the exact passage that supports each claim, and because the API parses and extracts cited_text itself, citations are "guaranteed to contain valid pointers" to the documents that were provided; the same page also says the API does not guarantee that every field has a value or that there is at least one citation [R4]. For a pipeline you build yourself, the id in square brackets is only text the model wrote, so two things need checking: the id is real (unknown_source) and the id belongs to this run's context (not_retrieved). A sentence that is correct according to the documents but names no source is faithful without being grounded.
4.3 The simulated judge and the manual spot check
sim_judge_supported is a simulated judge: looser than the deterministic check (a threshold of 1/2, a few bridge words (pairs of words treated as synonyms)) and then gives a wrong result on 1 in 10 (claim, passage) pairs, by a seeded hash. The 1/10 rate was set by the lab, not measured on any model. Per L2-M04, a judge only flags or ranks; a person reviews and decides. spot_check_sample picks n claims by the SHA-256 hash of the id, independent of list order. The question to ask: is the manual sample large enough to see the check's errors (§5.3).
5. Technical deep dive
5.1 The deterministic check against human labels
The lab has 16 answers with 29 claims, each claim with a human label written by hand, relative to the given context: supported, unsupported or contradicted. The last two both mean "not supported". The check flags a claim whose status is anything other than grounded. Result: 21 claims grounded and 8 unsupported_by_cited; tp 7, fp 1, fn 2, tn 19; precision 7/8 (0.875), recall 7/9 (0.778). Three wrong calls, and each is a named blind spot (the same blind spots seen in L2-M03-L04, case G09; what is new here is counting them against human labels):
- False accept, swapped roles (
A04.2): "Một ki-lô-gam bằng 100 tạ" (one kilogram equals one hundred quintals) is treated as grounded because all its content words and its number appear in "Một tạ bằng 100 ki-lô-gam" (one quintal equals one hundred kilograms). - False accept, antonym (
A06.2): "Phép chia hết có số dư khác 0" (an exact division has a remainder different from zero) slips past "số dư bằng 0" (the remainder equals zero); "khác" (different) is not in the negation word list. - False reject, paraphrase (
A07.1): "Để thử kết quả phép chia, nhân thương với số chia" (to check a division result, multiply the quotient by the divisor) is correct in meaning but only 5/9 of the content words are in the passage, below the 3/4 threshold.
The numbers 0.875 and 0.778 were measured on 29 claims written by the lab, not quality on real text.
5.2 Faithful, grounded and correct are three different things
- The sentence "Một giờ có 60 phút." (an hour has sixty minutes) with no citation: faithfulness = 1 (a passage supports it) but groundedness = 0 (
uncited). With another id, the remaining three statuses show up as in the demo part C. A15citesD10(the old printed note): "Chu vi hình vuông bằng cạnh nhân 3" (a square's perimeter equals the side times three) isgroundedand the human label issupportedrelative to the context, but the sentence is mathematically wrong. Faithful and grounded do not guarantee correct;answer_correct(used in L04) and the evidence labels are what catch it. TruLens writes that good scores on all three checks show the application is not making things up "within the limits of the knowledge base" [R3]: if the corpus holdsD10, those limits includeD10.A16("Đáp án là 42", the answer is forty-two) is a consequence of injection (L01 §5.2): the claim is supported by no passage other than the instruction sentence itself, and it is flagged.
5.3 The simulated judge and the spot check sample size
Running the simulated judge on the same 29 claims (a claim is treated as supported if one passage in the context is accepted by the judge): tp 5, fp 1, fn 4, tn 19, that is precision 5/6 (0.833) and recall 5/9 (0.556), against 7/8 and 7/9 for the deterministic check. The two tables are not quite of the same kind: the deterministic check flags by citation status, while the judge only asks "does any passage in the context support it" (as faithfulness does). The judge is looser, so it misses more wrong claims, and it also errs at random; that is the result on this set (simulated), not a conclusion about a real judge. Over the 16 answers, the two ways of computing faithfulness differ on 4 answers (L05).
The 6-of-29 manual sample from spot_check_sample is A04.1, A05.1, A09.2, A11.2, A12.2, A16.1: it contains none of the wrong calls among the three in §5.1. That is not bad luck: if 6 of the 29 claims were drawn at random, the probability of missing all three wrong calls is C(26, 6) / C(29, 6) = 253/522, close to 0.485. Nearly half of the time, a 6-claim sample would lead to the conclusion "the check has no errors". A manual sample meant to catch rare errors must be large, or stratified by the kind of claim under suspicion (L2-M05-L01), and the sample size and this limit must be written in the report.
6. The QA perspective
6.1 What the checks do not see
claim_supporteddoes not see paraphrases, swapped roles, antonyms, or a claim that needs two sentences of the passage.- A hidden character (for example a space of width 0) inserted inside a word splits that word in two: a claim that looks identical gets treated as unsupported. A test pins this down and
text.hidden_charactersfinds it. answer_addressespasses when the topic word is repeated;answer_correctmatches on word boundaries ("24" does not match inside "124") but demands the exact phrase and passes if every phrase is listed.- A citation is read only when it is one uppercase id in its own square brackets (
[D01-c1]); several ids in one bracket or a lowercase id makes the claimuncited. is_refusalaccepts only the exact refusal sentence; a refusal with an extra claim attached is graded as an answer.- A citation after the period is split off as an
uncitedclaim. - No check sees a wrong document (
D10).
6.2 Minimum report
For each check: the definition (tool or lab, formula), the number of claims, the confusion table with the positive class stated, the list of missed cases (false accepts) and false rejects, the manual sample size and how it was chosen, and the sentence "simulated numbers". The judge only flags; a person decides.
7. Real-world scenarios
Scenario 1 (fictional): "Nice citation, wrong content". The HocVui report gave groundedness 100%. A student received "chu vi bằng cạnh nhân 3" (perimeter equals the side times three) with source D10. The team added an answer_correct check against the evidence and removed the old printed edition from the corpus.
Scenario 2 (fictional): "A manual check of 6 samples looked clean". The team looked at 6 claims, saw no errors and concluded the check was trustworthy. After computing the probability of missing errors as in §5.3, they enlarged the sample and stratified it by claims that contain an antonym or a paraphrase.
8. Hands-on tutorial
8.1 Setup
cd academy-content/code-labs/l2-m06
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest # 80 passed
8.2 Run the demo
python -m lab.demo l03
Output (copied from a real run on Python 3.14.6 and 3.12.14, 2026-11-04; the two versions give identical output). The human labels were written by the lab's author; the judge is simulated:
A. 16 labelled answers, 29 claims; checker status counts: {'grounded': 21, 'unsupported_by_cited': 8}
B. checker against the labels (positive = claim not supported): {'tp': 7, 'fp': 1, 'fn': 2, 'tn': 19, 'precision': Fraction(7, 8), 'recall': Fraction(7, 9)}
wrong calls: [('A04.2', 'Một ki-lô-gam bằng 100 tạ [D06-c2].', 'contradicted'), ('A06.2', 'Phép chia hết có số dư khác 0 [D02-c1].', 'contradicted'), ('A07.1', 'Để thử kết quả phép chia, nhân thương với số chia [D02-c2].', 'supported')]
C. Một tạ bằng 100 ki-lô-gam [D06-c2]. -> grounded
C. Một tạ bằng 100 ki-lô-gam [D99-c1]. -> unknown_source
C. Một tạ bằng 100 ki-lô-gam [D06-c1]. -> not_retrieved
C. Một tạ bằng 100 ki-lô-gam. -> uncited
D. spot-check sample of 6 claims: ['A04.1', 'A05.1', 'A09.2', 'A11.2', 'A12.2', 'A16.1']
Reading the output: A is the status counts; B is the confusion table and the three wrong calls; C is the four statuses of the same claim (changing the citation id); D is the manual sample of 6 claims.
8.3 Try it yourself
Save this as try_l03.py in the lab's root folder (next to lab/), run python try_l03.py, then delete the file:
import math
from fractions import Fraction as F
from lab import corpus as C, data, grade as GR, judge as J
chunks = C.chunk_sentences(data.load_json("corpus.json"))
by = {c["id"]: c["text"] for c in chunks}
answers = data.load_jsonl("answers_labelled.jsonl")
rows = J.claim_rows(answers, lambda a: {i: by[i] for i in a["context_ids"]}, set(by))
truth = {r["id"]: r["truth"] for r in rows}
judge_flag = {}
for a in answers:
ctx = {i: by[i] for i in a["context_ids"]}
for n, (claim, _) in enumerate(GR.groundedness(a["reply"], ctx, set(by))[1], 1):
judge_flag[f"{a['id']}.{n}"] = not any(J.sim_judge_supported(claim, t) for t in ctx.values())
print(J.confusion(judge_flag, truth))
print(F(math.comb(26, 6), math.comb(29, 6)), float(F(math.comb(26, 6), math.comb(29, 6))))
print(GR.context_relevance("Chu vi hình vuông tính thế nào?", by["D03-c2"]), GR.context_relevance("Chu vi hình vuông tính thế nào?", by["D10-c1"]))
print(GR.answer_addresses("Chu vi chu vi chu vi.", ["chu vi"]), GR.answer_correct("Một ngày có 124 giờ.", ["24"]))
print(GR.faithfulness("Một giờ có 60 phút. Một ngày có 24 giờ.", {"D05-c1": by["D05-c1"]}))
Output (Python 3.14.6 and 3.12.14 identical):
{'tp': 5, 'fp': 1, 'fn': 4, 'tn': 19, 'precision': Fraction(5, 6), 'recall': Fraction(5, 9)}
253/522 0.4846743295019157
4/5 4/5
True False
(Fraction(1, 2), ['Một ngày có 24 giờ.'])
Reading: line 1 is the simulated judge's confusion table (tp 5, fp 1, fn 4, tn 19). Line 2: the probability of missing all three wrong calls is 253/522 (about 0.485). Line 3: the relevance of the right chunk and of the old chunk to the question about perimeter is equal (4/5): context_relevance does not distinguish the old version. Line 4: repeating the topic word still passes answer_addresses; "124" does not match "24". Line 5: faithfulness 1/2 and the unsupported claim. What the checks do not say: line 3 shows they cannot tell correct content from outdated content.
8.4 Run the lesson's tests
python -m pytest tests/test_l03_generation_checks.py -v
Result: 15 passed. Read test_checker_blind_spots_are_real, test_a_hidden_character_inside_a_word_hides_it_from_the_checker and test_the_checker_against_human_labels_exact_counts. The tests run on in-memory values and the lab's data; no test calls a model.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
ValueError: no claims to check |
The answer is empty or is a refusal | Handle refusals separately with is_refusal |
A claim that looks identical is unsupported_by_cited |
A hidden character inside a word, or the citation sits after the period | Run text.hidden_characters; put the citation before the period |
9. Independent exercise
Problem: Run the groundedness check on nine recorded answers, compare it with the human labels and find the answers that are faithful but not grounded.
Requirements: complete exercises/test_l03_generation_checks.py:
- TODO 1:
STATUS: a dictionary from claim id (of the form"B1.1") to the status fromgroundedness. - TODO 2:
MISSED(claims that are not flagged but whose human label differs fromsupported) andOAN(claims that are flagged but whose label issupported); a flag is any status other thangrounded. - TODO 3:
FAITHFUL_NOT_GROUNDED: the set of answer ids whose faithfulness is exactly 1 and whose groundedness ratio is below 1.
Test data: exercises/ex_answers.jsonl (9 simulated answers, human labels written by hand against the given context).
Deliverable: the four variables above, in exercises/test_l03_generation_checks.py itself.
Acceptance criteria: python -m pytest exercises/test_l03_generation_checks.py passes (3 tests): every value is recomputed with lab. The test checks only values, not your explanation.
Hints: TODO 1 and 2: judge.claim_rows (pass the corpus's chunk ids) already does the claim numbering and builds the flags. TODO 3: compute both ratios for each answer.
10. Knowledge check
0/16 done · Results are kept in this browser only.
P02 · True or false
P04 · Select all that apply
P05 · Put in order
P06 · Match
P07 · Spot the bug
The function below classifies the citation status but never returns not_retrieved. Find the bug.
def status(ids, corpus_ids, contexts, supported):
if not ids:
return "uncited"
if any(i not in corpus_ids for i in ids):
return "unknown_source"
if any(i not in corpus_ids for i in ids):
return "not_retrieved"
return "grounded" if supported else "unsupported_by_cited"P08 · Short answer
A team read 8 claims out of 40, saw no wrong case and concluded "the checker is trustworthy". State two things to tell the team.
P09 · Essay
Write 5-8 sentences: a report on a citation checker over 40 claims (made up, simulated), positive class "claim is not supported": tp 5, fp 1, fn 3, tn 31 (precision 5/6, recall 5/8). The three misses are two role-swap cases and one case with a word that shifts the meaning; the false alarm is a correct rewording. State how to read it and what the numbers do not tell.
P11 · Recall
Lesson: L2-M03-L04P12 · Recall
Lesson: L2-M04-L05P13 · Multiple choice
P14 · True or false
P15 · Select all that apply
P16 · Fill in the blank
11. Summary
- Concepts: three questions (the context, staying with the context, answering the right question); five citation statuses; faithful, grounded and correct are three different things; a manual spot check must be large enough.
- Skills: grading claim by claim, building a confusion table with a clear positive class, naming missed cases and false rejects, computing the probability that a sample misses the errors.
- Traps: writing "groundedness" without stating the formula, a citation that is real but not in the context, concluding from a sample of 6, assuming grounded means correct.
- You can now: read "groundedness 0.9" and ask: which definition, how many claims, what are the missed cases, what size of manual sample.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | Faithfulness (Ragas metrics) | Ragas | https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/faithfulness/ | 2026-11-04 | WebFetch (automatic summary) |
| R2 | Answer Relevancy (Ragas metrics) | Ragas | https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/answer_relevance/ | 2026-11-04 | WebFetch (automatic summary) |
| R3 | The RAG Triad | TruLens | https://www.trulens.org/getting_started/core_concepts/rag_triad/ | 2026-11-04 | WebFetch (automatic summary) |
| R4 | Citations | Anthropic | https://platform.claude.com/docs/en/build-with-claude/citations | 2026-11-04 | Full page text (saved and read with grep) |
| R5 | Ragas: Automated Evaluation of Retrieval Augmented Generation (Es et al.) | arXiv | https://arxiv.org/abs/2309.15217 | 2026-11-04 | Abstract-only (WebFetch, automatic summary) |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| Faithfulness | Độ trung thành: mỗi mệnh đề được một đoạn trong ngữ cảnh hỗ trợ |
| Groundedness (lab) | Độ có căn cứ theo lab: trích dẫn mã có trong ngữ cảnh và đoạn đó hỗ trợ (công cụ khác dùng chữ này với nghĩa khác) |
| Answer relevance | Độ liên quan của câu trả lời với câu hỏi (không nói về đúng sai) |
| Claim | Mệnh đề: khẳng định kiểm được |
| Citation status | Trạng thái trích dẫn: grounded, uncited, unknown_source, not_retrieved, unsupported_by_cited |
| Spot check | Kiểm tay một mẫu nhỏ |