Sub topic 10
Checking Answers Against Source Material
This chapter assumes you can write basic Python, call an LLM through an SDK, and read a retrieval-augmented generation (RAG) setup. In RAG, the application retrieves passages and asks the model to answer from them. You should also know the input and output checkpoints from earlier chapters, and the idea of an LLM judge. Here we apply those ideas to one risk: an answer that sounds right but isn't supported by the material you gave the model.
What grounding means
An answer is grounded when each claim in it can be traced to the source passages supplied with the request. An answer that adds facts from the model's training data, or invents them, is ungrounded. Ungrounded answers are often called hallucinations.
Grounding is a different question from truth. A passage can be outdated or wrong, and a grounded answer will repeat that error. A grounding check only asks whether the answer follows from the sources. It does not ask whether the sources are correct.
Grounding checks matter most when users rely on the answer without checking it. Typical cases are policy bots, support assistants, and summaries of documents or contracts.
Where the check runs
A grounding check is an output guardrail. It needs two inputs: the model's answer and the exact passages that were placed in the prompt. Keep the passages from the retrieval step. Do not re-retrieve them, because a second retrieval may return different text.
Deterministic checks first
Cheap checks catch a surprising share of problems. They cost almost nothing and give the same result every time. Three are worth building.
- Quote check. If the answer puts text in quotation marks, that text should appear in a source.
- Citation check. If you ask the model to cite passage IDs such as
[policy1], every cited ID must be one you supplied. - Number check. Every number in the answer should appear in a source. Numbers are where wrong answers do the most damage, and they are easy to extract.
import re
def normalize(text: str) -> str:
return re.sub(r"\s+", " ", text).strip().lower()
def strip_separators(text: str) -> str:
# "1,200" -> "1200" so thousands separators do not split a number
return re.sub(r"(?<=\d),(?=\d{3})", "", text)
def missing_quotes(answer: str, sources: dict) -> list:
corpus = " ".join(normalize(s) for s in sources.values())
quotes = re.findall(r'"([^"]{8,})"', answer)
return [q for q in quotes if normalize(q) not in corpus]
def unknown_citations(answer: str, sources: dict) -> list:
cited = set(re.findall(r"\[(\w+)\]", answer))
return sorted(cited - set(sources))
def unsupported_numbers(answer: str, sources: dict) -> list:
body = strip_separators(re.sub(r"\[\w+\]", "", answer))
source_text = strip_separators(" ".join(sources.values()))
in_answer = set(re.findall(r"\d+(?:\.\d+)?", body))
in_sources = set(re.findall(r"\d+(?:\.\d+)?", source_text))
return sorted(in_answer - in_sources)
sources = {
"policy1": "Refunds are available within 30 days of purchase. "
"Shipping costs are not refunded.",
}
answer = (
'Refunds are allowed within 30 days [policy1]. '
'The policy says "shipping costs are not refunded" [policy1]. '
'You get 14 extra days [policy3].'
)
print(missing_quotes(answer, sources))
print(unknown_citations(answer, sources))
print(unsupported_numbers(answer, sources))
# []
# ['policy3']
# ['14']The citation markers are removed before numbers are extracted. Otherwise the 1 in [policy1] would count as a number.
These checks have clear limits, and you should know them before you rely on them.
- A valid citation does not prove the cited passage supports the claim. The model can attach
[policy1]to a false sentence. - A number can appear in the sources and still be misused. "30 days" might be a refund window in the source and a shipping time in the answer.
- Paraphrase passes untouched. A fabricated claim with no numbers, quotes or citations gets through.
Treat these checks as a fast first filter. They do not prove the answer is grounded.
Claim-level checks with a model
To catch unsupported paraphrase, you need something that understands meaning. The approach from the LLM-as-judge chapter works here, but with one change: do not ask the judge to rate the whole answer. Split the answer into claims, which are single factual statements, and judge each one against the sources. Whole-answer scores hide a single bad sentence inside a mostly good paragraph. Claim-level verdicts tell you which sentence failed.
import re
JUDGE_TEMPLATE = """You check one claim against source text.
Use only the source. Ignore what you know from elsewhere.
Source:
{source}
Claim: {claim}
Answer with exactly one word: SUPPORTED or UNSUPPORTED."""
def split_claims(answer: str) -> list:
parts = re.split(r"(?<=[.!?])\s+", answer.strip())
return [p for p in parts if p]
def judge_claim(claim: str, source: str, call_model) -> bool:
prompt = JUDGE_TEMPLATE.format(source=source, claim=claim)
verdict = call_model(prompt).strip().upper()
# Anything other than an exact SUPPORTED counts as a failure.
return verdict == "SUPPORTED"
def unsupported_claims(answer: str, sources: dict, call_model) -> list:
source_text = "\n\n".join(f"[{k}] {v}" for k, v in sources.items())
return [c for c in split_claims(answer)
if not judge_claim(c, source_text, call_model)]
def fake_model(prompt: str) -> str:
claim = prompt.rsplit("Claim:", 1)[1]
return "SUPPORTED" if "30 days" in claim else "UNSUPPORTED"
sources = {"policy1": "Refunds are available within 30 days of purchase."}
answer = "Refunds are allowed within 30 days. Gift cards are never refundable."
print(unsupported_claims(answer, sources, fake_model))
# ['Gift cards are never refundable.']fake_model stands in for a real API call so the example runs on its own. In production, call_model would send the prompt to a model. Use a different model, or at least a separate call with its own instructions, from the one that wrote the answer.
The judge call fails closed. If the judge returns "Probably supported" or an empty string, the claim counts as unsupported. That choice produces more false positives, and it keeps a malformed judge reply from letting an answer through.
Dedicated entailment models
Another option is a natural language inference (NLI) model. It takes a source and a claim and outputs one of three labels: entailed, contradicted, or neutral. NLI models are small and fast, and their output is a probability you can threshold. Their weaknesses are limited input length and weaker performance on long, messy passages. Many setups use an NLI model on short passages and an LLM judge for hard cases.
Choosing a method
| Method | Catches | Misses | Cost |
|---|---|---|---|
| Quote check | Invented quotations | Anything unquoted | Negligible |
| Citation check | Citations to nonexistent passages | Real IDs on false claims | Negligible |
| Number check | Invented figures | Real figures used wrongly | Negligible |
| NLI model | Paraphrased unsupported claims | Long or multi-passage reasoning | Low |
| LLM judge per claim | Most unsupported claims | Subtle errors, judge mistakes | One call per claim |
Edge cases that cause errors
- Claim splitting is imperfect. Splitting on sentence ends breaks on abbreviations like "e.g." and on sentences that carry several claims. Pronouns also cause trouble. "It is not refunded" has no meaning without the sentence before it. For better results, ask the model to write the answer as one claim per sentence, or have a second call rewrite each claim so it stands alone.
- Synthesis is not copying. A correct answer may combine two passages or do arithmetic. Strict string matching rejects it. A judge that sees all passages together can accept it.
- Answers that say "I don't know." A refusal to answer is grounded by definition. Check for it first so the judge isn't asked to verify it.
- Judge bias. A judge often accepts an answer that sounds confident and matches its own prior knowledge. The instruction "use only the source" helps but does not fix this fully.
- Context limits. If the passages plus the claim exceed the judge's context window, the check silently truncates. Check lengths and fail loudly.
What to do on failure
Failure handling for this check follows the options from the earlier chapter, with some specifics.
- Retry with the unsupported claims listed in the prompt and an instruction to remove them. Limit this to one or two attempts.
- Strip the unsupported sentences and return the rest. This works only if the remaining text still makes sense.
- Fall back to a safe answer, such as quoting the best-matching passage directly.
- Refuse with a message that the sources do not cover the question.
For high-stakes domains, route a failure to a human reviewer rather than guessing.
Measuring the check
Build a small test set of answers labeled "grounded" or "ungrounded", including tricky paraphrases and wrong-number cases. Measure the false positive rate, which is grounded answers wrongly blocked. Measure the false negative rate too, which is ungrounded answers let through. Tightening the check usually trades one for the other, so pick the balance from the cost of each kind of error. Re-measure whenever you change the judge model or prompt.
Exercise
An answer cites "[policy2]" for the sentence "Refunds take 90 days." The passage policy2 exists, and the number 90 appears in policy2, but only in the sentence "Replacement parts ship within 90 days." Which of the three deterministic checks in this chapter flag the answer, and what would catch it?
Show answer
None of them. The citation exists, so the citation check passes. The number 90 appears in the sources, so the number check passes. There is no quote, so the quote check has nothing to test. A claim-level check catches it: an LLM judge or NLI model given the claim "Refunds take 90 days." and the policy2 text should return UNSUPPORTED, because the passage ties 90 days to shipping parts, not refunds.
Exercise
In judge_claim, why does the code compare the verdict to "SUPPORTED" with equality instead of checking whether "SUPPORTED" appears in the reply?
Show answer
A substring test would also match "UNSUPPORTED", since that word contains "SUPPORTED", so every claim would pass. Exact equality also makes any malformed reply count as a failure, which is the safe default.