Sub topic 10
Checking answers against source material
This chapter assumes you can write basic Python, call an LLM through an SDK, and read JSON. It also assumes you know the earlier chapters on rule-based checks and LLM-as-judge checks.
Why grounding matters
A grounded answer is one whose claims are supported by the source material you gave the model, such as retrieved documents. A hallucination is a claim the model states as fact that the sources do not support. In a retrieval-based app, a fluent but ungrounded answer is a common failure. A grounding check is an output guardrail that compares the answer with the sources before the user sees it.
The working model
The check has three steps:
- Split the answer into individual claims, usually one per sentence.
- For each claim, look for support in the source passages.
- Decide what to do if any claim has no support.
A cheap deterministic check
A simple first check measures word overlap. It is fast and needs no model call. It catches answers that have little to do with the sources, but it cannot tell whether a claim contradicts them.
import re
def words(text: str) -> set[str]:
return set(re.findall(r"[a-z0-9]+", text.lower()))
def split_claims(answer: str) -> list[str]:
parts = re.split(r"(?<=[.!?])\s+", answer.strip())
return [p for p in parts if p]
def unsupported_claims(answer: str, sources: list[str], threshold: float = 0.6) -> list[str]:
source_words = set()
for source in sources:
source_words |= words(source)
flagged = []
for claim in split_claims(answer):
claim_words = words(claim)
if not claim_words:
continue
overlap = len(claim_words & source_words) / len(claim_words)
if overlap < threshold:
flagged.append(claim)
return flagged
sources = ["The warranty lasts 24 months and covers manufacturing defects."]
answer = "The warranty lasts 24 months. It also covers accidental water damage."
print(unsupported_claims(answer, sources))
# ['It also covers accidental water damage.']The second claim is flagged because only a few of its words appear in the source. Choose the threshold by testing on real examples. A low value misses unsupported claims. A high value flags harmless paraphrases.
A judge for the harder cases
Overlap fails when a claim reuses source words but changes the meaning. For example, "The warranty lasts 12 months" shares most of its words with the source above. For these cases, use an LLM judge from the previous chapter. Give it one claim and the sources, and ask for a narrow verdict.
import json
JUDGE_PROMPT = """Sources:
{sources}
Claim: {claim}
Is the claim fully supported by the sources? Reply with JSON only:
{{"supported": true or false, "evidence": "quote from the sources, or empty"}}"""
def claim_supported(claim: str, sources: list[str], call_model) -> bool:
prompt = JUDGE_PROMPT.format(sources="\n".join(sources), claim=claim)
try:
verdict = json.loads(call_model(prompt))
except json.JSONDecodeError:
return False # treat an unreadable verdict as unsupported
return verdict.get("supported") is True and bool(verdict.get("evidence"))Asking for a quote makes the verdict easier to audit. Treating a malformed reply as "unsupported" means the check fails closed.
Common errors
- Checking the whole answer at once. One unsupported sentence hides inside a mostly good answer. Check claim by claim.
- Using only overlap. Negations, changed numbers and swapped names pass overlap checks.
- Judging against the wrong sources. Pass the passages the model actually saw, not the whole knowledge base.
- Trusting the judge fully. The judge is a model and can be wrong, so measure it as described in the evaluation chapter.
- Flagging correct answers that come from the model's general knowledge. Decide whether your app allows outside knowledge, and say so in the prompt.
What to do on a failure
Pick the response from the failure-handling chapter. Retrying with the unsupported claims listed works well. You can also remove the flagged sentences, or answer with "I could not find that in the documents."
Exercise
The answer says "The warranty lasts 12 months" and the source says "The warranty lasts 24 months." Why might the word-overlap check pass this claim, and what check would catch it?
Show answer
Most words in the claim ("the", "warranty", "lasts", "months") appear in the source, so the overlap score is high even though the number is wrong. An LLM judge that compares the claim with the source, or a rule that extracts numbers from the claim and requires each to appear in the sources, would catch it.