Hallucination, grounding and citations
Measure how much of each answer the passages support, make the model point at its evidence with the citations API, verify claims one by one, and abstain when the evidence is not there
You switch docqa to the citations API: each retrieved chunk goes in as a document block with citations enabled. An answer comes back in which every sentence has a citation with cited_text. What has the API guaranteed about those citations?
Retrieval from the previous chapter decides which passages the model sees. This chapter is about what the model does with them. Your docqa tool now finds the right chunk for 27 or 28 of 30 questions, and in the last step of that lab you found rows marked H (the gold answer was retrieved) with a wrong answer. Those are generation failures. Some are harmless, a number written differently. Some are the Air Canada failure on a small scale: a fluent sentence, a citation marker, and a claim the passage does not make.
You will do four things to them: measure them, make the model point at its evidence in a form you can check mechanically, check each claim, and abstain when the check fails. Each one costs something, and the last one has a price that teams forget to report.
What counts as a hallucination in a grounded system
The survey by Ji and colleagues (2023) splits hallucinations into intrinsic, output that contradicts the source, and extrinsic, output that the source can neither confirm nor refute. In a retrieval system the second kind is the common one, and it hides well, because extrinsic content is often true. Ask docqa which Postgres version the observability stack runs: the corpus says the shop runs Postgres 17 and says nothing about the observability stack’s version. A model that answers “Postgres 17” has written something plausible and possibly correct, and unsupported.
That is why grounded systems are judged on faithfulness (is every claim supported by the context the model was given?) rather than factuality (is it true?). Faithfulness is checkable against text you hold. Factuality needs the world. For a support bot or a document assistant, an unsupported true claim is still a defect: the next time it will be an unsupported false one, and nobody can tell the two apart without the evidence.
In practice the failures in a RAG answer fall into six kinds, and they need different fixes:
| Failure | Example from docqa | What catches it |
|---|---|---|
| Unsupported addition | “Grafana runs on 3000 and is backed by a Postgres database” | claim-level verification |
| Contradiction | “The observability Postgres listens on 5432” when the passage says 5433 | claim-level verification; exact-match checks on numbers |
| Misattribution | the right fact, cited to a passage that does not contain it | checking each citation’s span against its sentence |
| Answering past a retrieval miss | gold chunk not retrieved, model answers from prior knowledge | unanswerable questions in the eval; abstention |
| Blending | half from the passage, half from what the model knows about Grafana in general | claim-level verification |
| Over-abstention | “The passages do not contain the answer” when they do | answerable questions in the eval; coverage as a metric |
The last row is not a hallucination, and it belongs in the table because every fix for the first five pushes it up.
Measuring faithfulness
The measurement that works is claim decomposition. Split the answer into atomic claims, each stating one checkable fact. Check each claim against the passages: supported, contradicted, or not found. Faithfulness is supported claims divided by total claims. This is the faithfulness metric in RAGAS (Es and colleagues, 2023), and the same idea as FActScore (Min and colleagues, 2023), which scored biographies by the share of atomic facts a knowledge source supports.
Why claims and not answers? Because an answer of four sentences with one unsupported clause is three-quarters faithful, and a binary “is the answer grounded?” judgment rounds that to yes. The clause is the defect. Atomic claims also make the verifier’s job small: “the observability Postgres listens on 5433” against a passage is close to a textual entailment question, which models and even small NLI classifiers answer well. “Is this paragraph grounded?” is a holistic judgment, and holistic judgments are where judges disagree with people.
You have three choices of verifier, in order of cost:
- String and number checks. Every number, port, identifier and quoted string in the answer must appear in a passage. Free, exact, and blind to paraphrase. It catches the 5432 versus 5433 contradiction outright, and on technical corpora that is a large share of what matters.
- A natural language inference (NLI) model. A cross-encoder trained to label a (premise, hypothesis) pair as entailment, contradiction or neutral. It runs locally in milliseconds per claim. It struggles with long premises and with domain jargon.
- An LLM verifier. A small model splits claims and judges each one against the passages, returning structured output. It handles paraphrase and partial support, costs a fraction of a cent per answer on Claude Haiku 5.5, and it is a judge, so everything the LLM-as-judge chapter said about calibrating judges against human labels applies to it. The lab uses this one, and adds one mechanical check on top: the verifier must quote its evidence, and a quote that is not in the passages turns a “supported” verdict into a failure.
When you have no context to check against, there is a reference-free option. SelfCheckGPT (Manakul and colleagues, 2023) samples several answers to the same question and treats claims that the samples disagree on as likely inventions; a model that knows a fact tends to state it consistently. It costs several generations per answer. In a RAG system you have the context, so check against it.
Report faithfulness with its denominator. “Faithfulness 0.97” over 40 answers with 3 claims each is 120 claims, about 4 of them unsupported. Name them. The number is for trend lines; the list is for fixing.
The citations API
Your A1 prompt asks the model to write [2] after each claim. That works most of the time, and it fails in two ways you cannot see without checking: the number points at a passage that does not contain the claim, or the model quotes a sentence that no passage contains. The citations feature in the Messages API moves citation out of free text and into the response structure.
You send each source as a document block with citations enabled:
{"type": "document",
"source": {"type": "text", "media_type": "text/plain", "data": chunk_text},
"title": "LABS.md#3",
"citations": {"enabled": True}}
The API chunks a plain-text document into sentences, which become the smallest unit the model can cite; it can cite one sentence or a run of consecutive ones. A PDF is chunked the same way and cited by page. A custom content document ("source": {"type": "content", "content": [text blocks]}) is not chunked further: each block you supply is one citable unit, which suits a table where a row is the fact, or a transcript turn. For RAG, Anthropic’s guidance is one plain-text document per retrieved chunk if you want sentence-level citations within it. title and context are passed to the model but cannot be cited, so they are the place for source names and metadata.
The response comes back as several text blocks. Connective text has no citations; text that makes a claim carries a citations list, each entry a char_location with document_index (0-based, across every document in the request), document_title, start_char_index and end_char_index (end exclusive), and cited_text. Citations must be enabled on all documents in a request or none.
Three properties matter for engineering:
- The pointers are valid. The API extracts
cited_textfrom your document using the indices, so a quote that does not exist cannot appear. The invented-quote failure is gone. cited_textis free. It does not count toward output tokens, and when you send the response back in a later turn it does not count toward input tokens either. Enabling citations adds a little input for the instructions and the sentence chunking.- Nothing checks entailment, and nothing forces coverage. A sentence can cite a true span that does not support it, and a sentence can carry no citation at all. The docs say it plainly for extraction: check that each field has a value and at least one citation, because the API does not guarantee either.
There is one hard incompatibility. Citations and structured outputs cannot be combined: enabling citations on any document or search_result block and setting output_config.format in the same request returns a 400, because citation data is interleaved with text blocks and a strict JSON schema cannot hold it. Prompts that demand “only JSON” are allowed but suppress citations. So a grounded pipeline that also needs structured verification is two calls: generate with citations, then verify with a schema. The lab hits the 400 on purpose so you recognise it.
Citations work with prompt caching (put cache_control on the document blocks) and with batches.
Abstention
The cheapest hallucination to fix is the one on a question the corpus cannot answer. The model should say so. Your A1 system prompt already asks for an exact abstention string, and on a strong model it mostly works. “Mostly” is the problem: a near-miss question, where the passages are about the right subject and lack the specific fact, is exactly where a model reaches for what it knows.
There are three places to decide to abstain, and they fail differently:
Before generation, on retrieval scores. If the best chunk scores low, do not ask the model. It is fast and it does not work well on its own. Cosine similarities cluster in a narrow band, and the previous chapter warned that cross-encoder scores are not calibrated across queries. A paraphrased answerable question and a near-miss unanswerable one often score the same. The lab shows the overlap on your own questions. Use a retrieval threshold only to catch the obvious case, a question about a topic the corpus does not cover at all.
During generation, by instruction. The model decides from the passages. This is what you have now. Measure it with a set of unanswerable questions, written to be near misses rather than absurd: the lab adds ten, such as the observability stack’s Postgres version and a Redis password the docs never mention. An eval set with no unanswerable questions cannot measure abstention, and most eval sets have none.
After generation, on verification. Verify the answer’s claims and abstain, or drop the sentence, when any claim is not supported. It catches what the instruction missed. It also converts verifier errors into refusals: when the verifier fails to see that ‘2 000 000 rows’ supports ‘two million orders’, a correct answer becomes “the passages do not contain the answer”.
That last point is the general one. Every abstention policy trades coverage (the share of answerable questions you answer) for risk (the share of answers that are unsupported). The selective-prediction literature draws this as a risk-coverage curve, and it is the right picture: a policy that abstains on everything has zero hallucinations and no use. Report both numbers, on answerable and unanswerable questions separately, every time:
| Metric | Computed on | Bad when |
|---|---|---|
| Answered | answerable questions | low: over-abstention |
| Correct | answerable questions | low |
| Abstained | unanswerable questions | low: answering past the evidence |
| Unsupported claims | every answer given | above zero, with a list |
Where you set the policy depends on what a wrong answer costs against what a non-answer costs. A support bot that abstains hands the customer to a person, which costs minutes. A support bot that invents a refund policy costs what the Why cost. For that product, buy risk down with coverage.
Claim-level verification in production
Running a verifier on every answer adds a second model call. On Claude Haiku 5.5 with five passages that is about 2,500 input tokens and a few hundred output tokens, roughly $0.0004, and 1 to 3 seconds of latency if it runs inline. You have three ways to spend it:
- Inline and blocking. Verify before the user sees anything; drop or abstain on failure. Right when a wrong answer is expensive and a two-second delay is not: legal, medical, policy and refund questions. Stream nothing until verification passes.
- Inline, non-blocking. Stream the answer, verify in parallel, and annotate or retract unsupported sentences in the interface when the verdict lands. Users see the claim before the check, which is acceptable for low-stakes questions only.
- Sampled and offline. Verify a sample (1 to 10%) of production answers asynchronously and track faithfulness as an online metric with an alert. It catches drift, a prompt change or a corpus change that made answers less grounded, without adding latency. It fixes nothing for the user who got the bad answer.
Chain-of-Verification (Dhuliawala and colleagues, 2023) is the generation-side relative of this: the model drafts an answer, writes verification questions about its own claims, answers them independently, and revises. It reduces hallucination on list and long-form questions, at three or four times the generation cost. With retrieved context available, an external verifier against that context is cheaper and easier to audit.
What to do on a failed claim, from mildest to strongest: drop the sentence and keep the rest (works when the claim is an aside); regenerate once with the failing claim named (works for blending); abstain (works when the main claim failed). Log every one: the failing claims are the best training data your eval set will ever get.
Where it still goes wrong
The verifier shares the generator’s blind spots. If both are language models, a plausible blend can fool both. Calibrate the verifier against a few dozen hand-labelled claims, keep the mechanical checks (numbers, quoted evidence present in the passages) as a floor under it, and re-check the calibration when you change either model.
Faithful to the wrong source. Faithfulness is relative to the passages. If retrieval returned the shop’s Postgres section for a question about the observability stack, an answer of ‘5432’ is perfectly faithful to its context and wrong. That is why the eval keeps answer correctness and faithfulness as separate columns, and why retrieval quality from the previous chapter still bounds everything.
Stale and model-written context. A passage from last year’s docs makes a faithful answer out of date. A contextual-retrieval sentence written by a model can be wrong, and it is in the context the generator reads; the lab’s verifier sees only the original chunk text so that a wrong context sentence cannot launder a claim.
Partial support. “Grafana listens on 3000 with the default credentials admin / admin” is supported. “Grafana’s default credentials are safe for the lab” is an inference. Verifiers disagree on inferences, and so do people. Write down which side of the line your product takes and put examples of both in the verifier prompt.
Coverage of the citations themselves. A sentence with no citation is a claim nobody pointed at evidence for. In a strict product, uncited sentences that contain a fact are dropped mechanically before verification even runs. That rule is cheap, catches the lazy failure, and over-fires on harmless summary sentences, which the lab measures.
Work in labs/ai/docqa/ (cd labs/ai/docqa from the root of your checkout). The answer pipeline is struct-rerank from the previous chapter, so this lab needs no contextual-retrieval ingest; pass --pipeline ctx-rerank if you built that variant and want it. Nothing here changes retrieval: every difference you measure is generation.
1. Ten questions the corpus cannot answer. Each is a near miss: on topic, with passages about the right subject, and without the specific fact. Each has a trap term that must not occur anywhere in the corpus, or the question is answerable after all.
uv run python - <<'PY'
import json, pathlib, re
qs = [
{"q": "Which Postgres major version does the observability stack's database run?", "trap": None},
{"q": "What is the Redis password in the observability stack?", "trap": "redis password"},
{"q": "What does the FAULT_TIMEOUT_MS variable do in the observability lab?", "trap": "fault_timeout"},
{"q": "What does FAULT_DROP_SPANS do in the observability lab?", "trap": "fault_drop"},
{"q": "How many rows does the shipments table have at scale 1?", "trap": "shipments"},
{"q": "Which Kubernetes version do the course labs require?", "trap": "kubernetes"},
{"q": "Which port does the payments service's admin API listen on?", "trap": "admin api"},
{"q": "Which Node.js version does the ATLAS build use?", "trap": "node.js"},
{"q": "How long does Loki retain logs in the observability lab?", "trap": "retain"},
{"q": "Which email provider sends the magic-link sign-in emails?", "trap": "email provider"}]
corpus = re.sub(r"\s+", " ", " ".join(p.read_text() for p in pathlib.Path("corpus").glob("*.md"))).lower()
print("traps found in corpus:", [x["trap"] for x in qs if x["trap"] and x["trap"] in corpus])
json.dump(qs, open("questions-unans.json", "w"), indent=1)
PYtraps found in corpus: []. The first question has no trap term on purpose: the corpus does say ‘Postgres 17’, about the shop, and the observability section gives the port 5433 and no version. It is the hardest of the ten and the one a model most often answers. If a trap term is listed, your snapshot mentions it; replace that question with another near miss and re-run.2. Can retrieval scores decide abstention? Score the best chunk for every question, answerable and not, with the cross-encoder from the previous chapter. Local only, no API calls.
uv run python - <<'PY'
import json
from retrieve_v2 import PIPELINES
rows = []
for path, kind in (("questions-v2.json", "A"), ("questions-unans.json", "U")):
for x in json.load(open(path)):
top = PIPELINES["struct-rerank"](x["q"], 1)[0]
rows.append((top[4], kind, x["q"][:64]))
for score, kind, q in sorted(rows, reverse=True):
print(f"{score:7.2f} {kind} {q}")
PYA for answerable and U for unanswerable. The U rows sit mostly in the lower half, and they are interleaved with A rows: the paraphrased answerable questions from the previous chapter score as low as the near misses, and the Postgres-version and Redis-password traps score high because their passages are about the right thing. Find the threshold that abstains on all ten U rows and count the A rows it would also refuse; it is usually several. A retrieval threshold catches off-topic questions. It cannot catch a near miss.3. Answers with the citations API. Create grounded.py:
"""docqa with the citations API: one plain-text document per retrieved chunk."""
import anthropic
MODEL = "claude-opus-5-5"
ABSTAIN = "The passages do not contain the answer."
SYSTEM = ("Answer the question using only the documents. Keep it short: one to three sentences. "
"Every factual statement must come from a document. If the documents do not contain "
f"the answer, reply exactly: {ABSTAIN}")
client = anthropic.Anthropic()
def documents(chunks):
"""Rows are (id, source, chunk_no, text, score) as retrieve_v2 returns them."""
return [{"type": "document",
"source": {"type": "text", "media_type": "text/plain", "data": text},
"title": f"{src}#{n}",
"citations": {"enabled": True}}
for _, src, n, text, _ in chunks]
def answer_cited(question, chunks):
r = client.beta.messages.create(
model=MODEL, max_tokens=2048, output_config={"effort": "low"},
betas=["server-side-fallback-2026-07-01"], fallbacks="default",
system=SYSTEM,
messages=[{"role": "user", "content": documents(chunks) + [{"type": "text", "text": question}]}])
if r.stop_reason == "refusal": # the whole fallback chain declined
return {"text": "(declined)", "segments": [], "usage": r.usage}
segments = [{"text": b.text,
"cites": [{"doc": c.document_title, "quote": c.cited_text} for c in (b.citations or [])]}
for b in r.content if b.type == "text"]
return {"text": "".join(s["text"] for s in segments), "segments": segments, "usage": r.usage}
if __name__ == "__main__":
import sys
from retrieve_v2 import PIPELINES
q = sys.argv[1]
r = answer_cited(q, PIPELINES["struct-rerank"](q, 5))
for s in r["segments"]:
print(repr(s["text"]))
for c in s["cites"]:
print(f" <- {c['doc']}: {c['quote'].strip()[:90]!r}")
u = r["usage"]
print(f"\nin {u.input_tokens} out {u.output_tokens} ${(u.input_tokens * 4 + u.output_tokens * 20) / 1e6:.4f}")ANTHROPIC_API_KEY=... uv run grounded.py "Which port does the observability stack's Postgres use, and why?"'The observability stack's Postgres uses port ' has no citations; the claim segment carries one or two, for example <- LABS.md#2: 'Ports: gateway 8080, orders 8081, payments 8082, Postgres 5433 (so it does not clash with the shop), ...'. The quote is an exact sentence from the chunk, because the API cut it from your document, not from the model’s output. The cost line shows about 2,000 to 3,000 input tokens and a cent or so. Try the Postgres-version trap from step 1 and read what it cites.4. The 400 you will meet in production. Ask for citations and a JSON schema in the same request:
ANTHROPIC_API_KEY=... uv run python - <<'PY'
import anthropic
from grounded import client, documents
from retrieve_v2 import PIPELINES
q = "What port does Grafana listen on?"
try:
client.beta.messages.create(
model="claude-opus-5-5", max_tokens=1024,
betas=["server-side-fallback-2026-07-01"], fallbacks="default",
output_config={"effort": "low", "format": {"type": "json_schema", "schema": {
"type": "object", "properties": {"port": {"type": "integer"}},
"required": ["port"], "additionalProperties": False}}},
messages=[{"role": "user", "content": documents(PIPELINES["struct-rerank"](q, 3)) + [{"type": "text", "text": q}]}])
except anthropic.BadRequestError as e:
print("400:", e.message[:200])
PY400: followed by an invalid_request_error saying citations cannot be used with structured output. A rejected request generates nothing. This is why the next step is a second call: the answer is generated with citations, and the claims are checked by a verifier that uses a schema and no citations.5. The claim verifier. Create verify.py. It asks Claude Haiku 5.5 to split an answer into atomic claims and judge each against the passages, with a schema so the output always parses. Then it checks the verifier mechanically: a “supported” verdict whose evidence quote is not in the passages is downgraded.
"""Claim-level verification: atomic claims, each judged against the passages, evidence quoted."""
import json, re, anthropic
MODEL = "claude-haiku-5-5" # $0.10 / $0.50 per 1M tokens for prompts up to 100K
norm = lambda s: re.sub(r"\s+", " ", s).strip().lower()
SCHEMA = {"type": "object", "additionalProperties": False, "required": ["claims"],
"properties": {"claims": {"type": "array", "items": {
"type": "object", "additionalProperties": False,
"required": ["claim", "verdict", "evidence"],
"properties": {"claim": {"type": "string"},
"verdict": {"type": "string", "enum": ["supported", "contradicted", "not_found"]},
"evidence": {"type": "string"}}}}}}
PROMPT = """Below are numbered passages and an answer written from them.
1. Split the answer into atomic claims. Each claim states one checkable fact. Do not include a statement that the passages lack the answer.
2. Judge each claim using only the passages: supported (a passage states it or directly implies it), contradicted (a passage states something incompatible with it), or not_found.
3. For supported and contradicted claims, copy the shortest exact quote from the passage that decides it into evidence. For not_found, leave evidence empty.
Judge against the passages, not your own knowledge: a true fact the passages do not state is not_found.
<passages>
{passages}
</passages>
<answer>
{answer}
</answer>"""
client = anthropic.Anthropic()
def verify(answer, chunks):
"""Return (claims, usage). claims is None if the verifier declined."""
passages = "\n\n".join(f"[{i + 1}] {c[3]}" for i, c in enumerate(chunks))
r = client.messages.create(
model=MODEL, max_tokens=4096,
output_config={"effort": "low", "format": {"type": "json_schema", "schema": SCHEMA}},
messages=[{"role": "user", "content": PROMPT.format(passages=passages, answer=answer)}])
if r.stop_reason != "end_turn": # Haiku 5.5 has no server-side fallback: a refusal lands here
return None, r.usage
claims = json.loads(next(b.text for b in r.content if b.type == "text"))["claims"]
flat = norm(" ".join(c[3] for c in chunks))
for c in claims: # the verifier must quote real text, or its verdict does not count
if c["verdict"] == "supported" and norm(c["evidence"]) not in flat:
c["verdict"] = "bad_evidence"
return claims, r.usage
if __name__ == "__main__":
import sys
from retrieve_v2 import PIPELINES
q, answer = sys.argv[1], sys.argv[2]
claims, u = verify(answer, PIPELINES["struct-rerank"](q, 5))
for c in claims or []:
print(f"{c['verdict']:13} {c['claim']}\n{'':14}{c['evidence'][:90]!r}")
print(f"in {u.input_tokens} out {u.output_tokens} ${(u.input_tokens * 0.10 + u.output_tokens * 0.50) / 1e6:.5f}")Feed it a planted blend: one supported fact, one contradiction, one addition.
ANTHROPIC_API_KEY=... uv run verify.py "Which port does the observability stack's Postgres use, and why?" \
"The observability stack's Postgres listens on 5433 so it does not clash with the shop. It runs Postgres 16. Grafana reads from it directly."supported for 5433 with the quote Postgres 5433 (so it does not clash with the shop); not_found for Postgres 16 (or contradicted if the verifier treats the shop’s ‘Postgres 17’ as deciding, which is itself a judgment call worth noting); not_found for Grafana reading from it, since the passages give Grafana’s data sources as Prometheus, Loki and Tempo, or contradicted with that quote. About $0.0003. Run it three times: if a verdict flips between runs, that claim is one where your verifier is unreliable, and a single run would have hidden it.6. Forty questions, two generators, every claim checked. Create faithfulness.py. --mode prompt uses A1’s answer_anthropic (citations as [n] in free text); --mode cited uses grounded.py. Both read the same five chunks per question.
"""Run docqa over answerable and unanswerable questions, verify every claim, save the rows."""
import argparse, json, re
from qa import answer_anthropic
from grounded import ABSTAIN, answer_cited
from retrieve_v2 import PIPELINES
from verify import verify
norm = lambda s: re.sub(r"\s+", " ", s).strip().lower()
ap = argparse.ArgumentParser()
ap.add_argument("--mode", choices=["prompt", "cited"], default="cited")
ap.add_argument("--pipeline", default="struct-rerank", choices=list(PIPELINES))
a = ap.parse_args()
QS = ([dict(x, answerable=True) for x in json.load(open("questions-v2.json"))] +
[dict(x, answerable=False) for x in json.load(open("questions-unans.json"))])
rows = []
for i, x in enumerate(QS, 1):
chunks = PIPELINES[a.pipeline](x["q"], 5)
if a.mode == "cited":
r = answer_cited(x["q"], chunks)
text, segments = r["text"], r["segments"]
else:
text, segments = answer_anthropic(x["q"], chunks), None
abstained = norm(ABSTAIN).rstrip(".") in norm(text)
claims = [] if abstained else (verify(text, chunks)[0] or [])
rows.append({"n": i, "q": x["q"], "answerable": x["answerable"], "gold": x.get("answer"),
"answer": text, "segments": segments, "abstained": abstained,
"gold_in_answer": x["answerable"] and norm(x["answer"]) in norm(text),
"claims": claims, "correct": None})
ok = sum(c["verdict"] == "supported" for c in claims)
status = "abstained" if abstained else f"{ok}/{len(claims)} supported"
print(f"{i:>2} {'A' if x['answerable'] else 'U'} {status:15} {text[:70]!r}")
path = f"faith-{a.mode}-{a.pipeline}.json"
json.dump(rows, open(path, "w"), indent=1, ensure_ascii=False)
print("saved", path)ANTHROPIC_API_KEY=... uv run faithfulness.py --mode prompt
ANTHROPIC_API_KEY=... uv run faithfulness.py --mode citedA rows first. Most A rows read 2/2 supported or 3/3 supported. Expect the strong model to abstain on 7 to 10 of the 10 U rows; the ones it answers are almost always the Postgres-version trap (‘Postgres 17’, borrowed from the shop) and sometimes the Loki retention or Redis questions, answered from general knowledge of those tools. Those answers show up as 0/1 supported: an extrinsic hallucination, caught. Each run costs about $0.60 for generation and a few cents for verification. Open the two JSON files, set correct on the A rows by reading them as in the previous chapter, and keep them: the next step scores them without another API call.7. Abstention policies, and what they cost. Create abstain.py. It re-scores the saved runs under three policies without calling any model: as-is; strict-cite, which drops any uncited segment that states something (five or more words, or a digit) and abstains if nothing cited is left; and verified, which abstains whenever any claim is not supported.
"""Score saved faithfulness runs under three abstention policies. No API calls."""
import json, re, sys
def states_something(s):
return bool(re.search(r"\d", s)) or len(re.findall(r"\w+", s)) >= 5
def apply(policy, r):
"""Return (abstained, claims_kept) for one saved row."""
if r["abstained"] or policy == "as-is":
return r["abstained"], r["claims"]
if policy == "verified":
bad = any(c["verdict"] != "supported" for c in r["claims"])
return bad, ([] if bad else r["claims"])
if policy == "strict-cite":
if r["segments"] is None: # prompt mode has no structured citations
return r["abstained"], r["claims"]
if not any(s["cites"] for s in r["segments"]):
return True, []
dropped = [s["text"] for s in r["segments"] if not s["cites"] and states_something(s["text"])]
# claims that came only from dropped text no longer count against the answer
kept = [c for c in r["claims"] if not any(c["claim"][:25].lower() in d.lower() for d in dropped)]
return False, kept
print(f"{'run':28} {'policy':12} {'answered':>8} {'correct':>7} {'U abstained':>11} {'claims':>6} {'unsupp':>6} {'faith':>5}")
for path in sys.argv[1:]:
rows = json.load(open(path))
A, U = [r for r in rows if r["answerable"]], [r for r in rows if not r["answerable"]]
for policy in ("as-is", "strict-cite", "verified"):
res = [(r, *apply(policy, r)) for r in rows]
answered = sum(1 for r, ab, _ in res if r["answerable"] and not ab)
correct = sum(1 for r, ab, _ in res if r["answerable"] and not ab and r["correct"])
u_abst = sum(1 for r, ab, _ in res if not r["answerable"] and ab)
claims = [c for r, ab, cs in res if not ab for c in cs]
unsup = sum(c["verdict"] != "supported" for c in claims)
faith = (len(claims) - unsup) / len(claims) if claims else 1.0
print(f"{path:28} {policy:12} {answered:>5}/{len(A)} {correct:>7} {u_abst:>8}/{len(U)} "
f"{len(claims):>6} {unsup:>6} {faith:>5.2f}")uv run abstain.py faith-prompt-struct-rerank.json faith-cited-struct-rerank.jsonas-is shows the raw trade: answered 27 to 30 of 30, unanswerable abstained 7 to 10 of 10, faithfulness 0.93 to 0.99 over 60 to 90 claims. verified drives unsupported claims to 0 and raises unanswerable abstention to 10/10, and it costs answered questions: typically one to four correct answers become abstentions, because the verifier marked a paraphrase (‘two million’ for ‘2 000 000’) or an inference as not_found. Find those rows; they are verifier errors, and they are what you would fix in the verifier prompt before shipping this policy. strict-cite changes little on the cited run when the model cites every claim; where it does change something, read the dropped segment. The correct column only counts rows you marked true in step 6.Add a section to RESULTS.md: the six-row table, the unsupported claims listed one by one with their failure type from the chapter’s table, the verifier errors you found, and the policy you would ship for a support product and for an internal docs search.
grounded.py, delete the last sentence of SYSTEM (the abstention instruction) and re-run uv run faithfulness.py --mode cited, then uv run abstain.py faith-cited-struct-rerank.json. The as-is row’s unanswerable abstentions fall, often to 2 or 3 of 10, and the answered rows look as fluent as before; most of the new answers even carry citations, to passages that are about Redis or Loki in general and do not contain the fact. Citations made those hallucinations look better sourced, not less likely. The verified row recovers most of them, at the coverage cost you measured. Put the instruction back: it is the cheapest control in the pipeline, and verification is the net under it, not a replacement.Template
# Grounding and citation policy: <assistant>, <date>
Owner: <role>. Approver: <role>. Version <n>, review by <date>.
Decision needed: <what, from whom, by when>. Scope: <channels, sources, topics>. Out of scope: <what this does not cover>.
## 1. What the assistant may say without a source
<the short list: greetings, connective text, the abstention string>. Everything else is a claim.
## 2. Citations
- Every sentence that states a fact carries <what kind of citation>, shown to the user as <how>.
- Checked by <mechanical check> and <claim verifier>, on <every answer / a sample of n%>.
- Source of truth: <document>, version <x>, refreshed <when>.
## 3. When the assistant abstains
Wording: <string>. Triggers: <rule>. What happens next: <hand-off>.
## 4. Error audit
Sample: <n answers, how chosen, answerable / unanswerable>. Judged by: <method>. Claims checked: <n>.
| Error type | Count | Example | Cost if it reached a customer |
Faithfulness <x> over <n> claims. Answered <a>/<b>. Unanswerable abstained <c>/<d>. Answerable refused by the policy: <e>.
## 5. Actions taken
| Action | Answers which error | Owner | Date | Evidence it worked |
## 6. How this could be wrong
<one way, and what would show it>
## 7. Sign-off
Prepared <name, date>. Approved <name, date>. WORKED EXAMPLE
At a company the engineer who owns docqa writes this with the support lead, and the head of engineering approves it. Header: Owner engineer; Approver head of engineering; review by 31 January 2027; decision needed: whether policy answers ship with verified; scope: policy answers on the help page, English only. The sample is the 40 answers of the lab’s cited run (30 answerable, 10 unanswerable), every claim checked by verify.py. Every count below is an assumed value, chosen inside the range the lab prints, not a result. 78 claims (the lab expects 60 to 90), 5 flagged by the verifier, so faithfulness is 73/78 = 0.94 (the lab expects 0.93 to 0.99).
Without a source docqa may say only connective text and the exact string ‘The passages do not contain the answer.’ Every sentence stating a fact carries a citation, shown as the quoted sentence and its title, such as LABS.md#2. Uncited sentences with a fact are dropped (strict-cite), and verified abstains when any claim is not supported.
Audit (assumed counts). Answered 28/30 as-is (the lab expects 27 to 30); unanswerable abstained 9/10 (7 to 10). Reading the 5 flagged claims by hand: 1 answering past a retrieval miss (the Postgres-version trap, ‘Postgres 17’, borrowed from the shop), 1 unsupported addition, 1 contradiction, and 2 verifier errors, which are not hallucinations. Under verified, unsupported claims fall to 0, unanswerable abstention rises to 10/10 and answered falls to 24/30: 2 answers refused rightly, and 2 correct answers refused wrongly (the lab expects 1 to 4), where the verifier marked ‘two million’ against ‘2 000 000’ as not_found.
Actions. Add that paraphrase to the verifier prompt (engineer, next sprint). Ship verified for policy answers, strict-cite for docs search. Log every failed claim.
Could be wrong: 40 answers is a small sample, and a verifier shares the generator’s blind spots. A hand-labelled check of 30 claims would show it.
Now you
You work for Lumora Mobile, a mobile network operator with 6,000 staff and 31 million subscribers, head office in Lagos. Its assistant answers customer questions about tariffs and plans, and must cite the current tariff sheet. You have no live traffic to audit, so build the audit from your own lab run: use the 40 answers from step 6 as the sample, and treat your docs corpus as if it were the tariff sheet. Take the counts from your abstain.py table and your RESULTS.md list of unsupported claims, and state as an assumption anything you did not measure, such as how often the sheet is refreshed. Write one thing the assistant may say without the sheet, and decide what it does when the sheet is silent or out of date. The head of customer care and the compliance lead read it, and it supports their decision on whether the assistant answers customers without a human check.
Self-check
You run the answer bot on an insurer's customer help page. It answers policy questions from 4,000 policy documents through RAG on claude-sonnet-5-5, with p95 latency 2.4 s against a 5 s budget. A sampled audit of 400 answers found 3.5% contain at least one claim the retrieved passages do not support, two of them about cover that the policy excludes. Product wants zero unsupported claims about cover and will accept some answers being handed to a human. What do you build?
- PAPER Survey of Hallucination in Natural Language Generation Ji et al., 2023
The taxonomy this chapter uses: intrinsic and extrinsic hallucination, faithfulness against factuality, and a catalogue of the metrics people have tried, with their weaknesses. Published in ACM Computing Surveys. Read: sections 1 to 4 for definitions and metrics; skim the per-task sections for the ones you build.
- PAPER RAGAS: Automated Evaluation of Retrieval Augmented Generation Es, James, Espinosa-Anke and Schockaert, 2023
The claim-decomposition faithfulness metric used in the lab, defined in a page. Read the prompts in the appendix to see how much of the metric is the judge model. Read: section 3, the definitions of faithfulness, answer relevance and context relevance.
- PAPER FActScore: Fine-grained Atomic Evaluation of Factual Precision in Long Form Text Generation Min et al., 2023
Why scoring atomic facts beats scoring whole answers, with the human-agreement numbers that justify automating it. Read: sections 2 and 3 for atomic facts and the estimator; section 4 for how well the automatic version agrees with people.
- DOC Citations Anthropic
Document types and how each is chunked, the response structure, token costs, the incompatibility with structured outputs, and caching with citations. Read 'How citations work' and 'Response structure'; skip the per-language tabs you do not use.
- PAPER SelfCheckGPT: Zero-Resource Black-Box Hallucination Detection for Generative Large Language Models Manakul, Liusie and Gales, 2023
The reference-free alternative for when you have no context to check against: sample several answers and treat inconsistency as a hallucination signal. Useful to know what it costs and when it fails. Read: sections 1 to 4.
- PAPER Chain-of-Verification Reduces Hallucination in Large Language Models Dhuliawala et al., 2023
The generation-side approach: plan verification questions, answer them independently, revise. Read it to compare its cost with an external verifier over retrieved context. Read: sections 1 to 3 for the method; the results tables for which variant helps.
- PAPER Hallucination-Free? Assessing the Reliability of Leading AI Legal Research Tools Magesh et al., 2024
A careful audit of commercial RAG products that separates incorrect answers from misgrounded ones, the distinction this chapter's failure table makes. The typology transfers to any domain. Read: sections 3 and 4: the definition of a misgrounded answer and the error typology.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.