Citations & grounding

In one sentence

Answer only from retrieved chunks, tag every claim with the ids of the chunks that support it, verify those citations in code, and abstain when the context doesn't contain the answer.

Analogy: A good analyst's memo: every number has a footnote to the exact page, and when the data isn't there, the memo says "unknown" instead of guessing.

Generation proposes citations; deterministic checks and an optional entailment step decide which claims survive.

How it works

  • Give each chunk a stable id like [S1] and keep its title, URL and span in your own lookup.
  • Prefer structured output (claims with source ids and quotes) or a provider's citations feature over prompt instructions alone.
  • In code, check that every cited id is in this request's context and every quote appears in its chunk.
  • The usual failure is a real citation that doesn't support its claim; for high stakes, check entailment.
  • Show links and highlighted spans in the UI, and track how often the assistant abstains.

Check yourself

Answer to mark it learned; your answers aren't scored.

In a multi-turn chat, users click [S2] in an earlier answer and land on an unrelated chunk. Each turn re-retrieves and labels the chunks S1–S5 in order. What's the fix?

Go deeper

Full explanation

Grounding means every claim in the answer is supported by the retrieved context, not by the model's memory. Citations make that checkable: each claim points at the chunk it came from.

How to build it:

  1. Label the context. Give each chunk a stable id ([S1] or doc_id:chunk) and keep title, URL and span in your own lookup table.
  2. Constrain the output. "Answer only from the sources; cite ids after each claim; if they don't contain the answer, say so." Better: structured output (claims: [{text, source_ids, quote}]) or a provider feature that returns exact spans (Anthropic Citations, OpenAI file-search annotations, Gemini grounding metadata).
  3. Quote first on long contexts: extract verbatim quotes, then answer from them. Less drift, trivial to check.
  4. Verify in code. Every cited id must exist in this request's context; every quote must appear in its chunk. For high stakes, an NLI model or LLM-as-a-judge checks that the claim is entailed. Drop or flag what fails.
  5. Abstain. "I couldn't find this in the docs" beats a fluent guess; track the abstention rate.
  6. Show sources in the UI: links and highlighted spans.

The common failure is not a missing citation but a real citation that doesn't support the claim. Measure citation precision and Measuring hallucination & groundedness in Evaluating RAG.

Code Structured citations, verified in code
pythonStructured citations, verified in code
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()
MODEL = "gpt-4.1"  # any model with structured outputs

class Claim(BaseModel):
    text: str
    source_ids: list[str]   # e.g. ["S2"]
    quote: str              # verbatim span copied from a cited source

class Answer(BaseModel):
    answerable: bool        # explicit abstention channel
    claims: list[Claim]

SYSTEM = ("Answer ONLY from the sources. For each claim give its source ids and "
          "an exact quote copied from one of them. If the sources do not contain "
          "the answer, set answerable=false and return no claims.")

def answer(question: str, chunks: dict[str, str]) -> Answer:
    context = "\n\n".join(f"[{sid}] {text}" for sid, text in chunks.items())
    resp = client.responses.parse(model=MODEL, text_format=Answer, input=[
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": f"Sources:\n{context}\n\nQuestion: {question}"},
    ])
    return verify(resp.output_parsed, chunks)

def verify(ans: Answer, chunks: dict[str, str]) -> Answer:
    norm = lambda s: " ".join(s.split())  # whitespace-insensitive match
    kept = [c for c in ans.claims
            if c.source_ids and all(s in chunks for s in c.source_ids)  # no invented ids
            and norm(c.quote)  # an empty quote would match any chunk
            and any(norm(c.quote) in norm(chunks[s]) for s in c.source_ids)]
    # High stakes: add an NLI / judge check that each quote entails its claim
    return Answer(answerable=bool(kept), claims=kept)  # nothing verified -> abstain
Real example

An insurance assistant is asked "Does my policy cover water damage from a burst pipe?". Context: S1 (coverage), S2 (exclusions), S3 (claims process). The model answers: sudden pipe bursts are covered [S1]; seepage over 14 days or more is excluded [S2]; and "claims are paid within 10 days" [S4]. Verification drops the third claim: S4 isn't in the context and its quote matches nothing. Asked "Does it cover floods?", no chunk mentions floods, so it answers "I couldn't find anything about floods in your policy documents" and links the full policy instead of guessing.

Trade-offs +3 · −3

+ You gain

  • Auditable answers: users and reviewers can click through to the exact source.
  • Cheap code checks catch invented ids and fabricated quotes before the user sees them.
  • Abstention turns silent hallucinations into visible "don't know" answers you can count and trace to retrieval gaps.

− You pay

  • A real citation isn't proof of support; entailment checks add a model call and latency.
  • Strict grounding raises refusals; tune it to the cost of a wrong answer versus no answer.
  • Quotes add output tokens, and you can't verify a claim until it has finished streaming.

Use it when

Any RAG where people act on answers (support, legal, medical, finance, internal policy) or where you must audit why the system said something. Abstention is mandatory when a wrong answer costs more than no answer.

Avoid it when

Creative writing, brainstorming or open chat where the model's own knowledge is the point. On low-stakes, latency-critical paths, skip per-claim entailment but keep the cheap id check.

Numbers to know 4
  • Liu et al. (2023), auditing 4 generative search engines: only ~51.5% of generated sentences were fully supported by their citations.
  • Same study: only ~74.5% of citations actually supported the sentence they were attached to.
  • Citation precision = citations that support their claim ÷ all citations; citation recall = fully supported claims ÷ all claims.
  • Anthropic reported its built-in Citations outperformed most custom implementations, raising recall accuracy by up to 15% (internal evals, Jan 2025).
Common pitfalls 4
  • Trusting citation markers without checking the ids exist in this request; models invent [S7] or reuse ids from earlier turns.
  • Renumbering chunks every turn, so [S2] in the history now points to a different chunk; use stable ids.
  • Treating "cites a real chunk" as "grounded": check support with a quote match or entailment.
  • No abstention path, or never measuring it: the model fills the gap from its priors.
Interview questions 2

Answer out loud first, then reveal.

How do you stop your RAG system from hallucinating?Show answer

I can't eliminate it, so I make it rare and detectable. Rare: better retrieval, a prompt that restricts answers to the sources with an explicit "not found" path, and quote-first extraction on long contexts. Detectable: each claim carries chunk ids and a verbatim quote; code checks that the ids exist in this request and the quote appears in the chunk, and for high-stakes flows an NLI model or judge checks entailment. Unsupported claims are dropped or flagged. Then I track citation precision, groundedness and abstention rate on a golden set, and treat wrong abstentions as retrieval bugs.

The model cites a real source, but the source doesn't say that. How do you catch it at scale?Show answer

That's the dominant failure: in Liu et al.'s audit only ~75% of citations supported their sentence, and an existence check misses every one of those cases. I layer three checks. A verbatim-quote requirement, so a fabricated quote fails string matching for free. Provider citation features that return exact spans, which guarantee the quote is real, though not that it supports the claim. And an entailment check, a small NLI model or LLM judge, online for high-stakes answers and on a sample offline. Citation precision per release goes on the dashboard.