Scoring Groundedness on a Sample
Draw a reproducible sample of logged answers, label each claim against its cited passage with a written rubric, report the share of supported claims with an interval that respects how failures cluster in answers, and check an LLM judge against the human labels before trusting its numbers.
Contentsand lesson path
On this page
- The problem
- Step 1: Draw a sample and split answers into claims
- Step 2: Label claims with a written rubric
- Step 3: Report the supported share with its uncertainty
- Step 4: Check a judge against the people
- Step 5: The real judge
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Grounding & Citations
- Grounded Versus Fluent: Kinds of Unsupported Claims Concept · 15 min
- Asking for Citations and Validating Them Worked example · 20 min
- Lab: Abstain When Evidence Is Missing Lab · 25 min
- Scoring Groundedness on a Sample Worked example · 20 min
- Check: Judge Five Answers for Support Knowledge check · 6 questions
What you will learn
- Measure groundedness by checking a sample of answer claims against their cited passages.
Prerequisites: RAG Foundations
01. The problem
After the last two lessons every answer from the Lumen assistant has validated citations and a way to abstain. The product manager asks a plain question: how often do the answers say something the sources do not support? Citation validation cannot answer it, because it only proves that each cited ID was retrieved. Someone has to read claims against passages.
Reading every answer is out of the question, so you measure a sample and say how sure you are. This worked example:
- draws a reproducible random sample of logged answers and splits them into claims;
- labels each claim against its cited passage with a written rubric;
- reports the share of supported claims with a 95% interval, computed two ways;
- checks whether an LLM judge could take over the labelling, by comparing it with the human labels.
Steps 1 to 4 run offline with Python 3.12 or later and the standard library. Copy corpus.py and retrieve.py from the lab into a new folder. The judge in step 4 is a FAKE heuristic, so that you can see what a poor judge looks like in the numbers; step 5 shows the real judge call.
02. Step 1: Draw a sample and split answers into claims
Sample from the traffic you want to describe, such as last week's answers, and fix the random seed so that anyone can draw the same sample again. Do not hand-pick interesting answers: a sample you chose describes your choices, not your traffic.
import random
logged = [f"a{n:04d}" for n in range(1, 1201)] # IDs of last week's 1,200 answers
rng = random.Random(2026) # a fixed seed makes the sample reproducible
print(*sorted(rng.sample(logged, k=10)))a0211 a0244 a0458 a0655 a0862 a1030 a1049 a1122 a1140 a1173Because the assistant returns claims (lesson 2), the split is already done: each claim and its cited IDs are fields in the log. For answers stored as prose, split them before labelling, by hand or with a prompt such as "Rewrite this answer as a list of standalone factual claims, one fact each, keeping the citation markers", and check a few splits yourself, because a bad split changes the score.
Leave out text that makes no factual claim, such as greetings. Leave out abstentions too: whether the assistant refused when it should have is a separate measure, the one the lab tracked with in-scope and out-of-scope questions.
03. Step 2: Label claims with a written rubric
Write the rubric down before anyone labels, so that two reviewers apply the same rule:
Read only the cited passage. Label the whole claim.
S supported A careful reader of the passage alone would accept the claim.
Paraphrase is fine. Numbers, plans, dates, conditions and
negations must match.
P partial The passage states part of the claim; the rest is missing.
U unsupported The passage does not state the claim, or contradicts it. This
includes true facts that the passage does not contain.
For every P and U, note the kind (fabrication, over-generalisation, value
drift, contradiction, inference, wrong citation) and any passage that would
support the claim.Two reviewers label the claims independently and then discuss where they differ; disagreements usually show where the rubric is vague. Here is the labelled sample:
"""Ten sampled answers split into claims, each with its cited passage and a label.
Answer IDs are the sample from step 1. Labels from two reviewers using the rubric:
S supported, P partial, U unsupported.
"""
LABELLED = [ # (answer, claim, cited passage, human label)
("a0211", "Annual plans can be refunded within 30 days of purchase.",
"billing-refunds#1", "S"),
("a0211", "After 30 days the current term is refunded pro rata.",
"billing-refunds#1", "U"),
("a0211", "Refunds are paid as account credit.", "billing-refunds#2", "U"),
("a0244", "Open Settings > Billing > Invoices to request a refund.",
"billing-refunds#2", "S"),
("a0244", "Refunds reach the original payment method within 10 business days.",
"billing-refunds#2", "S"),
("a0458", "Monthly plans can be refunded within 14 days of a charge.",
"billing-refunds#1", "S"),
("a0458", "The money goes back to the original payment method.",
"billing-refunds#2", "S"),
("a0655", "Business plan uploads can be up to 250 MB per file.",
"files-limits#1", "S"),
("a0655", "Pro plan uploads are limited to 250 MB per file.",
"files-limits#1", "U"),
("a0862", "Guests can comment on the projects they are invited to.",
"guests#1", "S"),
("a0862", "A workspace may have no more than 50 guests.", "guests#1", "S"),
("a0862", "Guests can create projects in any workspace.", "guests#1", "U"),
("a1030", "Admins can export all projects as CSV or JSON.", "export#1", "S"),
("a1030", "Large exports are emailed within 24 hours, in CSV only.",
"export#1", "U"), # contradiction: the passage allows CSV or JSON
("a1030", "Exports include all file attachments.", "export#1", "U"),
("a1049", "SAML single sign-on is available on the Business plan.", "sso#1", "S"),
("a1049", "Okta and Google Workspace are supported identity providers.",
"sso#1", "S"),
("a1049", "Microsoft Entra ID is supported as well.", "sso#1", "S"),
("a1122", "You can sign in with one of your ten backup codes.", "2fa#1", "S"),
("a1122", "Without backup codes, a workspace admin can reset two-factor"
" authentication.", "2fa#1", "S"),
("a1140", "Lumen connects to Slack, GitHub and Google Drive.",
"integrations#1", "S"),
("a1140", "Integrations are set up by workspace admins.", "integrations#1", "S"),
("a1173", "Requests over the limit are queued and retried automatically.",
"api-limits#1", "U"),
("a1173", "The limit can be raised to 6,000 requests a minute on request.",
"api-limits#1", "U"),
]Twenty-four claims from ten answers, and the failures cluster: a0211, a1030 and a1173 hold six of the eight claims that are not supported. That is typical, because one poor retrieval or one misread passage spoils several claims at once, and it matters for the interval in step 3.
04. Step 3: Report the supported share with its uncertainty
Count the supported claims, then attach two 95% intervals: one that treats claims as independent and one that resamples whole answers. Also count the answers in which every claim is supported.
"""Share of supported claims, with two 95% intervals."""
import math
import random
from collections import defaultdict
from sample import LABELLED
def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
"""Wilson score interval for k successes out of n."""
p = k / n
centre = (p + z * z / (2 * n)) / (1 + z * z / n)
half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return centre - half, centre + half
def bootstrap(answers: list[list[bool]], rounds: int = 5000, seed: int = 0):
"""Resample whole answers, so claims from one answer stay together."""
rng = random.Random(seed)
shares = []
for _ in range(rounds):
picked = rng.choices(answers, k=len(answers))
claims = [ok for answer in picked for ok in answer]
shares.append(sum(claims) / len(claims))
shares.sort()
return shares[int(0.025 * rounds)], shares[int(0.975 * rounds) - 1]
supported = [label == "S" for _, _, _, label in LABELLED]
grouped: dict[str, list[bool]] = defaultdict(list)
for (answer_id, *_), ok in zip(LABELLED, supported, strict=True):
grouped[answer_id].append(ok)
answers = list(grouped.values())
k, n = sum(supported), len(supported)
low, high = wilson(k, n)
b_low, b_high = bootstrap(answers)
print(f"{n} claims from {len(answers)} answers")
print(f"supported claims: {k}/{n} = {k / n:.1%}")
print(f" Wilson 95% (claims as independent): {low:.1%} to {high:.1%}")
print(f" bootstrap 95% (resampling answers): {b_low:.1%} to {b_high:.1%}")
full = sum(all(answer) for answer in answers)
f_low, f_high = wilson(full, len(answers))
print(f"answers with every claim supported: {full}/{len(answers)}"
f" (Wilson 95%: {f_low:.1%} to {f_high:.1%})")python groundedness.py24 claims from 10 answers
supported claims: 16/24 = 66.7%
Wilson 95% (claims as independent): 46.7% to 82.0%
bootstrap 95% (resampling answers): 45.8% to 87.0%
answers with every claim supported: 5/10 (Wilson 95%: 23.7% to 76.3%)Read it from the top:
- 16 of 24 claims supported, 66.7%. This is the groundedness score in the same sense as Ragas faithfulness, computed over the sample instead of per answer. Partial counts as not supported, because part of the claim has no evidence.
- The Wilson interval, 46.7% to 82.0%, is a standard interval for a proportion that behaves well with small samples and with shares near 0 or 1. It treats the 24 claims as independent.
- The bootstrap interval, 45.8% to 87.0%, is the bootstrap you used to compare retrieval results in earlier skills, with one change: it resamples whole answers, not single claims. It is wider because claims in one answer fail together, so 24 clustered claims carry less information than 24 independent ones. With only ten answers it is rough too; read both intervals as the scale of the uncertainty, not as exact bounds.
- 5 of 10 answers have every claim supported. This is closer to what a user experiences: one unsupported sentence can spoil an otherwise correct answer.
The width is the message. With 24 claims the true share could be under half or above 80%, so a change that moves the point estimate by five points proves nothing. To compare two versions, run both on the same sampled questions and label the claims that differ, or label enough to narrow the interval. The width shrinks roughly with the square root of the sample size: halving it takes about four times as many answers.
05. Step 4: Check a judge against the people
Labelling 24 claims takes a reviewer roughly half an hour, and a weekly sample of hundreds does not scale. An LLM judge can apply the rubric, but only after you have shown that it agrees with people on claims they labelled. The FAKE judge below is deliberately naive: it passes a claim when all of its numbers and most of its words appear in the passage. Word-overlap checks like this are cheap and common, and they show clearly what to look for.
"""FAKE judge: word overlap plus a number check. Not an LLM, and easy to fool."""
from retrieve import words
def fake_judge(claim: str, passage: str) -> str:
claim_words, passage_words = words(claim), words(passage)
if any(w.isdigit() and w not in passage_words for w in claim_words):
return "U" # a number the passage does not contain
overlap = sum(w in passage_words for w in claim_words) / len(claim_words)
return "S" if overlap >= 0.6 else "P" if overlap >= 0.4 else "U""""Check a judge against the human labels before trusting its scores."""
from collections import Counter
from corpus import BY_ID
from fake_judge import fake_judge
from sample import LABELLED
judge = fake_judge # to test a real judge: from claude_judge import claude_judge
pairs = [ # (people say supported, judge says supported)
(human == "S", judge(claim, BY_ID[cited].text) == "S")
for _, claim, cited, human in LABELLED
]
counts = Counter(pairs)
n = len(pairs)
agree = (counts[True, True] + counts[False, False]) / n
human_yes = (counts[True, True] + counts[True, False]) / n
judge_yes = (counts[True, True] + counts[False, True]) / n
chance = human_yes * judge_yes + (1 - human_yes) * (1 - judge_yes)
kappa = (agree - chance) / (1 - chance)
caught = counts[False, False] / (counts[False, False] + counts[False, True])
print(" judge: supported judge: not")
print(f"people: supported {counts[True, True]:>16} {counts[True, False]:>10}")
print(f"people: not {counts[False, True]:>16} {counts[False, False]:>10}")
print(f"agreement {agree:.0%}, Cohen's kappa {kappa:.2f}")
print(f"unsupported claims the judge caught: {caught:.0%}")
print(f"score from people {human_yes:.1%}, score from judge {judge_yes:.1%}")
for (human, judged), (_, claim, _, _) in zip(pairs, LABELLED, strict=True):
if judged and not human:
print(" judge passed:", claim)python compare_judge.py judge: supported judge: not
people: supported 14 2
people: not 4 4
agreement 75%, Cohen's kappa 0.40
unsupported claims the judge caught: 50%
score from people 66.7%, score from judge 75.0%
judge passed: After 30 days the current term is refunded pro rata.
judge passed: Pro plan uploads are limited to 250 MB per file.
judge passed: Guests can create projects in any workspace.
judge passed: Large exports are emailed within 24 hours, in CSV only.Agreement of 75% sounds respectable, but it hides the failure that matters. People marked eight claims as not supported and the judge caught only four. The four it passed include two contradictions (pro rata refunds, and CSV only where the passage allows CSV or JSON), a value drift (the Pro limit) and a lost negation (guests creating projects): word overlap cannot see meaning. Because its mistakes go mostly one way, the judge reports 75.0% groundedness where people found 66.7%.
Cohen's kappa corrects agreement for chance. When most claims are supported, a judge that says supported to everything still agrees most of the time; kappa gives that judge zero. Here kappa is 0.40, well below the values above about 0.8 that are usually read as strong agreement.
Decide the bar before you run the comparison, and include the number that protects users: the share of unsupported claims the judge catches. If a judge passes on one labelled set, confirm it on a second, keep a few claims a week for human review, and check again whenever the judge model or prompt changes. These numbers carry uncertainty too: 4 caught out of 8 has a Wilson interval of roughly 22% to 78%, so validate on enough labelled claims to include a few dozen unsupported ones. The AI evaluation skill builds a full judge-validation lab on the same idea.
06. Step 5: The real judge
A real judge sends the rubric as the system prompt and one claim with its cited passage per request, and returns a structured verdict. reason comes before label in the schema, so the model states its evidence before it commits to a label; both fields are required, and the Claude docs say structured outputs keep required properties in schema order. Use a strong model: it runs on a sample, so the cost stays small.
"""An LLM judge that applies the rubric. Needs ANTHROPIC_API_KEY and JUDGE_MODEL."""
import os
from typing import Literal
import anthropic
from pydantic import BaseModel
RUBRIC = """You check whether a passage supports a claim. Use only the passage.
- S (supported): a careful reader of the passage alone would accept the whole
claim. Paraphrase is fine; numbers, plans, conditions and negations must match.
- P (partial): the passage states part of the claim and not the rest.
- U (unsupported): the passage does not state the claim or contradicts it.
Give a one-sentence reason that points to the passage, then the label."""
class Verdict(BaseModel):
reason: str # before the label, so the judge states its evidence first
label: Literal["S", "P", "U"]
client = anthropic.Anthropic()
FORMAT = {"type": "json_schema", "schema": anthropic.transform_schema(Verdict)}
def claude_judge(claim: str, passage: str) -> str:
response = client.messages.create(
model=os.environ["JUDGE_MODEL"], # for example claude-opus-5-5
max_tokens=16000,
system=RUBRIC,
messages=[{"role": "user", "content":
f"<passage>\n{passage}\n</passage>\n<claim>\n{claim}\n</claim>"}],
output_config={"format": FORMAT},
)
if response.stop_reason != "end_turn": # refusal or cut off: no verdict
raise RuntimeError(f"judge stopped with {response.stop_reason}")
text = "".join(block.text for block in response.content if block.type == "text")
return Verdict.model_validate_json(text).labelTo validate it, replace the judge = fake_judge line in compare_judge.py with from claude_judge import claude_judge and judge = claude_judge, then run the script with JUDGE_MODEL set, for example JUDGE_MODEL=claude-opus-5-5 python compare_judge.py, and read the same numbers. Judge one claim per request rather than a whole answer, so that one verdict cannot sway another, and store the reasons: where the judge and the people disagree, the reason shows whether the rubric or the judge is at fault.
07. Common mistakes
08. Check your understanding
09. Apply it
Score your RAG tool:
- Draw a seeded sample of at least 20 answered questions from the practice-project runs (log more if you need to) and split the answers into claims.
- Label every claim with the rubric, ideally with a second person labelling the same claims, and settle the disagreements.
- Report the supported share with both intervals, the share of fully supported answers, and the three most common kinds of failure with one example each.
- Run an LLM judge on the same claims and report agreement, kappa and the share of unsupported claims it caught. Decide in writing whether you would let it label next week's sample, and what you would check every week if you did.
10. Review prompt
Without looking back:
- How do you draw a sample that others can reproduce, and why not pick the answers yourself?
- What are the three labels of the rubric, and what is the one rule a reviewer must never break?
- What do the Wilson and the answer-level bootstrap intervals assume, and why was the bootstrap wider here?
- Which two numbers would you need before letting an LLM judge label claims instead of people?
References
- Ragas: Faithfulness
- FActScore: Fine-grained Atomic Evaluation of Factual Precision (Min et al., 2023)
- Enabling Large Language Models to Generate Text with Citations (Gao et al., 2023)
- Measuring Attribution in Natural Language Generation Models (Rashkin et al.)
- statsmodels: proportion_confint (Wilson interval)
- scikit-learn: cohen_kappa_score
- Claude docs: Structured outputs
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.