Skip to main content
Hallucination Detection: Grounding and Citations for RAG

Hallucination Detection: Grounding and Citations for RAG

KU
· Founder & Chief Editor
• 8 min read•Updated •77 views

A RAG system that invents facts erodes trust fast. Here is how we ground answers, force citations, and catch the fabrications before users do.

Key takeaways

  • In RAG, a hallucination is any answer claim the retrieved context does not support, which makes it checkable.
  • Prevent it with a prompt that allows only context, demands citations and has a fixed refusal string.
  • Detect the rest with span verification, then an entailment model or LLM judge, and track faithfulness and refusal rate on a golden set.

To detect RAG hallucinations, check every answer claim against the retrieved context: force passage citations with a fixed refusal string, verify quoted spans exist verbatim, then run an entailment model or a narrow LLM faithfulness judge on what remains. Measure faithfulness and refusal rate separately on a golden set, and re-run it on every prompt or model change.

Verified against

Claude Sonnet 5.5 (model id claude-sonnet-5-5), against the Claude docs on reducing hallucinations and the models overview, plus the Ragas faithfulness metric docs. Checked October 2026.

The first hallucination that hurt us in production was a confident, well-formatted answer about a refund policy that did not exist. Retrieval had pulled the right documents. The model read them and then wrote something adjacent to the truth but not in the text. Nobody caught it until a support agent quoted it back to a customer.

In a RAG setup, a hallucination has a narrower, more testable meaning than "the model made something up." It means the answer contains a claim not supported by the retrieved context. That definition is useful because it is checkable: you have the context, you have the answer, and you can ask whether one entails the other. You do not need ground truth about the world. You need agreement between two strings you already hold.

Grounding: make the model stay inside the context

Most fabrications start with a prompt that invites them. If you ask "answer the question" and paste some documents, the model treats the documents as a hint and its parametric memory as the rest. The fix is to move the boundary explicitly.

Three instructions carry most of the weight, and they match what Anthropic's own guide to reducing hallucinations recommends: restrict the model to the documents, let it say it doesn't know, and make it cite. Answer only from the provided context. Cite the source of every claim. Refuse when the context does not contain the answer. That refusal path is the part people skip, and it is the part that stops the worst failures.

Text
# prompts/grounded-answer.txt
You answer questions using ONLY the numbered context passages below.

Rules:
- Every factual sentence must be supported by at least one passage.
- After each sentence, cite the passage id(s) in brackets, e.g. [3].
- If the context does not contain enough information to answer,
  reply exactly: "I don't have enough information to answer that."
- Do not use outside knowledge. Do not guess.

Context:
[1] {chunk_1}
[2] {chunk_2}
[3] {chunk_3}

Question: {question}

The refusal string is deliberately fixed. A literal marker is easy to detect downstream, route to a human, or count in metrics. If you let the model phrase its own uncertainty, you get twelve variants and none of them are greppable.

We wrote more about how these pieces fit into a reliable pipeline in our notes on retrieval-augmented generation.

Citations that point at spans, not vibes

Bracketed passage ids are a start. They let a reader jump to the source, and they give you a cheap signal: an answer sentence with no citation is a candidate hallucination. But passage-level citations still let the model cite chunk 3 while paraphrasing something chunk 3 never said.

The stronger pattern is span attribution. Ask the model to return, for each claim, the exact substring of the context it relied on. Then you can verify that the substring actually appears in the chunk.

Python
# rag/verify_spans.py
def verify_spans(answer_claims: list[dict], chunks: dict[int, str]) -> list[dict]:
    """Each claim: {"text": ..., "chunk_id": int, "quote": str}."""
    results = []
    for claim in answer_claims:
        source = chunks.get(claim["chunk_id"], "")
        supported = claim["quote"].strip() in source
        results.append({
            "claim": claim["text"],
            "chunk_id": claim["chunk_id"],
            "span_found": supported,
        })
    return results

Exact-match on the quote is strict and it should be. If the model cannot point at a literal span, that is worth flagging even when the claim happens to be true. In the UI we highlight the quoted span inside the source chunk so a user can confirm attribution in one glance.

Automated detection

String overlap is the crudest signal and still catches a surprising amount. If an answer sentence shares almost no tokens with any retrieved chunk, it probably came from somewhere else. It is a filter, not a verdict.

The check we trust more is entailment. Treat each answer sentence as a hypothesis and the retrieved context as the premise, then ask whether the premise supports the hypothesis. A natural-language-inference model gives you entailment / neutral / contradiction per sentence. Anything that is not entailment gets a second look.

When we do not want to host an NLI model, we use an LLM as a faithfulness judge. Keep the judge prompt narrow: it grades support, not helpfulness or style.

Python
# rag/faithfulness_judge.py
import json

JUDGE_PROMPT = """You are checking whether an ANSWER is fully supported
by the CONTEXT. Do not judge whether the answer is helpful or correct in
general; only whether every claim is backed by the context.

CONTEXT:
{context}

ANSWER:
{answer}

Return JSON:
{{"supported": true|false,
  "unsupported_claims": ["..."],
  "verdict": "one sentence explaining the decision"}}"""

def faithfulness_check(client, context: str, answer: str) -> dict:
    resp = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=500,
        messages=[{
            "role": "user",
            "content": JUDGE_PROMPT.format(context=context, answer=answer),
        }],
    )
    return json.loads(resp.content[0].text)

Two things matter here. Pin the judge model and prompt, and keep sampling as deterministic as your model allows, so the verdict is stable across reruns; re-run any sample where two passes disagree. And feed it the same context the answering model saw, not a fresh retrieval, or you are grading a different question.

Confidence signals help as a cheap prefilter. Low token probabilities on named entities and numbers correlate with fabrication, and answers where the model hedged in its own words are worth routing to the judge. None of these are proof on their own. Stack them: overlap flags a candidate, entailment or the judge confirms it.

Measuring the rate

You cannot improve a number you do not track. Build a golden set of maybe 100 to 200 question-and-context pairs, each labelled by a human as answerable or not, with the supported answer written out. Run your pipeline over it and count how often the generated answer contains an unsupported claim. That fraction is your hallucination rate. Ragas calls the inverse "faithfulness": the share of answer claims the context supports, scored from 0 to 1. Retrieval quality is a separate number, and an offline harness for RAG retrieval evaluation keeps the two from blurring.

Watch two failure modes separately. On answerable questions, measure faithfulness: did the answer stay inside the context. On unanswerable questions, measure the refusal rate: did the system correctly say it did not know instead of inventing something. A system that never refuses will look great on the first metric and fail every user who asks about something you do not cover.

Re-run the set on every prompt change and every model swap. A typical catch: a new model version is more fluent and more willing to fill gaps, and the golden-set faithfulness score drops before anything ships.

Questions people ask

How do you detect hallucinations in a RAG system?

Treat each answer sentence as a claim and check it against the context the model actually saw. Cheap checks run first: sentences with no citation, quoted spans that do not appear verbatim in the cited chunk, and near-zero token overlap. Anything flagged goes to an entailment model or a narrow LLM judge that grades support only, not helpfulness. Track the rate on a labelled golden set.

Do citations stop an LLM from hallucinating?

No, they make hallucinations auditable. A model can cite passage 3 while paraphrasing something passage 3 never said. Citations help because an uncited sentence is an easy flag, and span-level citations let you verify the quote exists in the source. Pair them with a fixed refusal string so the model has a sanctioned way to say the context does not cover the question.

What is a faithfulness score?

Faithfulness is the fraction of claims in an answer that the retrieved context supports, from 0 to 1, as Ragas defines it. A score of 1 means every claim is backed by the context. It says nothing about whether retrieval found the right documents, so measure retrieval recall separately, and score unanswerable questions on whether the system refused.

The call we'd make

Ground first, detect second. A citation-enforcing prompt with a hard refusal string removes more hallucinations than any downstream classifier, and it costs you one prompt rewrite. Then add span verification because it is cheap and deterministic, and an entailment or judge check on the sentences that fail the cheap checks. Track faithfulness and refusal separately on a golden set you actually maintain. Skip the fancy confidence math until the basics are in place: most teams do not have a detection problem, they have a prompt that quietly invited the model to guess.

Sources

Explore topics:LLMAI
React
Share this post
Cite this article
Plain text

Kiril Urbonas (2026). Hallucination Detection: Grounding and Citations for RAG. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/hallucination-detection-grounding-and-citations

Markdown

[Hallucination Detection: Grounding and Citations for RAG](https://www.devopsness.com/blog/hallucination-detection-grounding-and-citations) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)

KU

Kiril Urbonas

Founder & Chief Editor

586 articles
View all articles by Kiril Urbonas

You might have missed

Evergreen posts worth revisiting.