Skip to main content
Back to all articles
AI Engineering 6 min readUpdated August 31, 2026

Citations Are Not Grounding: Verifying RAG Claims Before They Ship

A citation link proves that a source exists; it does not prove the source supports the sentence beside it. This article builds a claim-level grounding check for RAG answers in TypeScript and Python.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#rag#grounding#citations#hallucination#verification#typescript#python
On this page

A RAG answer can contain three valid source links and still invent the most important sentence in the response.

That distinction matters because citations create confidence. Once a user sees a source marker beside a claim, they reasonably assume the source supports it. If the link opens a real document but the document says something different, the system has not become safer by citing its answer. It has made the hallucination look audited.

Retrieval quality and grounding quality are separate things.

Retrieval asks: did we fetch evidence that could answer the question?

Grounding asks: does each factual claim we are about to send actually follow from that evidence?

I like to keep those as two explicit stages. A knowledge assistant can pass retrieval evaluation and still fail grounding, especially when the model combines multiple chunks, fills in a missing number, or writes a stronger statement than any source supports.

The example here is a document-analysis service used to answer questions about internal policies. The same design applies to support agents, research assistants, compliance tools, and any RAG workflow where the user expects citations to mean something.

Store provenance at chunk level

Grounding is much harder if the prompt contains anonymous text blobs.

Each piece of evidence should have a stable identity that survives retrieval and generation:

TypeScript
type Evidence = {  id: string;  documentId: string;  title: string;  sourceUrl: string;  text: string;};

Python:

Python
from dataclasses import dataclass​@dataclass(frozen=True)class Evidence:    id: str    document_id: str    title: str    source_url: str    text: str

When I build the generation prompt, I label evidence with those IDs instead of hoping the model can reconstruct provenance later.

For example:

Text
[E12] Refunds requested within 30 calendar days are eligible...[E19] Enterprise contracts may define a different refund period...

The answer generator can now return citations as evidence IDs. That is useful, but it is still only a proposal. The model saying “this claim came from E12” does not prove that E12 actually supports the claim.

Make factual claims inspectable

A long paragraph is a poor unit for verification. It may contain one supported fact, one inference, and one invented number.

I prefer to turn the generated answer into a small set of atomic claims before release.

TypeScript
type DraftClaim = {  id: string;  text: string;  citedEvidenceIds: string[];};​type DraftAnswer = {  intro?: string;  claims: DraftClaim[];};

A claim should be narrow enough that “supported” has a useful meaning. “The account is eligible for a refund and it will arrive tomorrow” contains two claims and should be split.

This does not mean the user has to see a robotic list. The final renderer can still produce natural prose. The structure is an internal contract between generation and verification.

Treat support as a separate decision

The verifier gets exactly two things: a claim and the evidence cited for it. It should not see the original conversation, hidden chain-of-thought, unrelated retrieved chunks, or extra facts that make it easier to rationalize the answer.

A small result type is enough:

TypeScript
type SupportResult = {  supported: boolean;  confidence: number;  reason: string;};​interface ClaimVerifier {  verify(claim: string, evidence: Evidence[]): Promise<SupportResult>;}

And in Python:

Python
from typing import Protocol​@dataclass(frozen=True)class SupportResult:    supported: bool    confidence: float    reason: str​class ClaimVerifier(Protocol):    async def verify(        self,        claim: str,        evidence: list[Evidence],    ) -> SupportResult: ...

The verifier can be an NLI model, a constrained LLM call, or a deterministic rule for narrow domains. I do not want the rest of the application to care.

The important part is that generation and verification are different calls with different instructions and preferably different failure modes.

Build an egress gate around unsupported claims

Once claims can be checked, the release rule becomes ordinary application code.

TypeScript
class GroundingError extends Error {  constructor(public readonly claimIds: string[]) {    super(`Unsupported claims: ${claimIds.join(", ")}`);  }}​async function verifyDraft(  draft: DraftAnswer,  evidenceById: Map<string, Evidence>,  verifier: ClaimVerifier,): Promise<DraftAnswer> {  const unsupported: string[] = [];​  for (const claim of draft.claims) {    const evidence = claim.citedEvidenceIds      .map((id) => evidenceById.get(id))      .filter((item): item is Evidence => Boolean(item));​    if (evidence.length === 0) {      unsupported.push(claim.id);      continue;    }​    const result = await verifier.verify(claim.text, evidence);​    if (!result.supported || result.confidence < 0.8) {      unsupported.push(claim.id);    }  }​  if (unsupported.length > 0) {    throw new GroundingError(unsupported);  }​  return draft;}

The threshold is deliberately configuration, not truth. A medical or financial workflow may require a stricter release policy than an internal developer assistant.

Python keeps the same behavior:

Python
class GroundingError(RuntimeError):    def __init__(self, claim_ids: list[str]):        super().__init__(f"Unsupported claims: {', '.join(claim_ids)}")        self.claim_ids = claim_ids​async def verify_draft(    claims: list[dict],    evidence_by_id: dict[str, Evidence],    verifier: ClaimVerifier,) -> None:    unsupported: list[str] = []​    for claim in claims:        evidence = [            evidence_by_id[evidence_id]            for evidence_id in claim["cited_evidence_ids"]            if evidence_id in evidence_by_id        ]​        if not evidence:            unsupported.append(claim["id"])            continue​        result = await verifier.verify(claim["text"], evidence)        if not result.supported or result.confidence < 0.8:            unsupported.append(claim["id"])​    if unsupported:        raise GroundingError(unsupported)

What happens after the exception is a product decision. I normally choose one of three paths:

  • remove the unsupported claim if the remaining answer is still useful;
  • regenerate only the failed claims with stricter evidence constraints;
  • return an explicit “I do not have enough evidence” response.

What I do not do is silently ship the original draft because the verifier was inconvenient.

Regeneration should be targeted

If one sentence fails grounding, asking the model to rewrite the entire answer wastes tokens and can damage the sentences that were already correct.

A targeted repair request can contain:

  • the unsupported claim;
  • the exact evidence it was supposed to use;
  • the verification reason;
  • a rule to either rewrite from the evidence or drop the claim.

That produces a much smaller blast radius.

It also needs a hard repair budget. A model that cannot support a claim after one careful rewrite probably lacks the evidence. Repeating the same generation loop five times is not “self-correction”; it is expensive denial.

Numbers and dates deserve special treatment

A large share of harmful RAG hallucinations are small substitutions: 14 days becomes 30, 2.5% becomes 5%, 2025 becomes 2026.

For high-value domains I add deterministic checks before the semantic verifier.

If a generated claim contains a date, amount, percentage, identifier, or version number, extract those literals and confirm they appear in the cited evidence or are produced by an explicitly trusted calculation tool.

That catches a class of errors cheaply.

A verifier model is useful for meaning. It should not be the first line of defense for whether $12,450 appears in a document.

Citation rendering should follow verification

Another common mistake is to render citations during generation and treat them as part of the answer text.

I prefer a structured draft with evidence IDs, then verification, then citation rendering.

That ordering prevents several awkward cases:

  • the model cites an evidence ID that does not exist;
  • a claim is removed but leaves a dangling citation marker;
  • two claims use the same source and create duplicate links;
  • the user receives a source link that was never actually checked.

The renderer is deterministic. It maps validated IDs to titles and URLs after the gate passes.

Grounding evaluation is different from answer evaluation

A useful test set for this layer contains claims and evidence pairs, not just questions and ideal answers.

I would include cases such as:

  • evidence directly supports the claim;
  • evidence is on-topic but does not support the claim;
  • evidence contradicts the claim;
  • evidence supports only half of a compound claim;
  • the claim is a reasonable inference but not explicitly stated;
  • two pieces of evidence are required together;
  • evidence is stale compared with a newer source.

That test set lets you change the verifier without conflating it with retrieval or writing quality.

The production metric I care about is not “percentage of answers with citations.” That is easy to game. Better signals are unsupported-claim rate, repair rate, abstention rate, and the percentage of cited claims that pass verification.

The latency tradeoff is real

Claim verification adds work after generation. If an answer contains eight claims and each is verified serially with a model call, the architecture is obviously too slow.

There are several ways to keep the cost sane:

  • batch claims that cite the same evidence;
  • verify independent claims concurrently with a bounded semaphore;
  • run cheap literal checks first;
  • skip verification for purely conversational sentences;
  • use a smaller verifier where evaluation shows it is sufficient;
  • reserve the strictest gate for responses where a wrong claim matters.

I would rather verify four meaningful factual claims well than mechanically send every sentence through an expensive judge.

When a grounding gate is overkill

Not every RAG feature needs this layer.

If the output is a brainstorming assistant over public documents and the UI already shows the retrieved passages beside the answer, direct evidence visibility may be enough.

If the system makes policy claims, financial claims, compliance statements, or other assertions users will act on, citation correctness deserves stronger treatment.

The practical test is simple: what happens when a source link is real but the sentence next to it is false?

If the answer is “we have an incident,” grounding should be an application boundary, not another line in the system prompt.

A citation is metadata. Grounding is evidence. Production RAG becomes much easier to trust once the system stops treating those as the same thing.

KEEP READING

Related engineering notes