Code examples:

RAG with Citations and Source Verification — Making Every Claim Prove Itself

November 24, 2026 14 min read By Jaffar Kazi
Real-World AI Engineering RAG Grounding
C# Python Azure

What You'll Learn

  • Why a citation that nobody checks is decoration, and the three ways it fails
  • How stable chunk IDs and a JSON citation contract make claims checkable
  • How a deterministic verifier rejects fabricated IDs, uncited claims and citations that don't support the claim
  • How to choose an abstention policy and shape an API response around validated citations
  • How to test the whole layer by mocking only the LLM call

The Problem

A RAG system retrieves four chunks from a leave policy and answers: "Employees accrue 20 days of leave, and unused days roll over [2]." The answer is fluent, it carries a citation, and it looks audited. But nothing checked that source [2] exists in the retrieved set, that it says anything about rollover, or that the number 20 came from the documents rather than from the model's general knowledge of employment practice.

A citation is a claim about evidence. Unchecked, it is decoration, and decoration is worse than nothing because it makes a wrong answer look verified. Three distinct failures hide behind the same fluent sentence:

  • Fabricated identifier. The answer cites a source that was never retrieved, or never existed.
  • Unsupported claim. A statement carries no citation at all, usually because it came from the model's memory instead of the context.
  • Citation laundering. A real source ID is attached to a claim that source does not support. This is the hardest to catch, because every structural check passes.

The previous article in this series built a retrieval step that returns visible hits and abstains when similarity is too low. That decision is about whether evidence exists. This one is about whether the answer actually uses it, and whether each claim can be traced to a passage a reader can check.

The Shape of a Real Solution

The principle is that the model proposes and code disposes. The model that wrote a citation is never the one that decides whether it is valid. Five pieces sit at the boundary:

  • Stable IDs on every chunk, assigned at ingestion from the document, page and position.
  • A citation contract: the prompt lists sources by ID, and the model must return JSON claims, each with the IDs that support it.
  • A verifier in ordinary code that checks every claim against the chunks retrieved for this request.
  • A response shape carrying the answer, the validated citations (source name, page, excerpt) and the claims that were rejected.
  • An abstention path for when no claim survives verification.

Architecture Overview

Architecture diagram showing a question flowing to a retriever that returns chunks with stable IDs, then a prompt builder, an LLM that returns JSON claims with source IDs, a parser, and a deterministic verifier with three checks (claim has a citation, every cited ID is in the retrieved set, cited chunk supports the claim). Verified claims produce a response with validated citations; if none are verified the system abstains. Two earlier abstain exits exist for no retrieved chunks and malformed output.
  • Two abstention exits come before verification. No retrieved chunks means no LLM call at all. Malformed model output means nothing to verify.
  • The verifier is plain code. It costs no tokens, gives the same answer every time and is unit-testable.
  • It checks against this request's retrieved set, not the whole corpus. A real ID from a document that was never retrieved is still a fabrication for this answer.
  • Rejected claims are kept, but for logs and diagnostics, not for the end user.

Core Implementation: Stable IDs and the Citation Contract

Numbering sources [1], [2], [3] by retrieval rank is the obvious approach and a fragile one. The same chunk gets a different number on the next request, so logs, caches, evaluation datasets and any link back to a passage stop lining up. A stable ID such as leave-p2-c1 (document, page, chunk index on that page) is assigned once at ingestion and means the same thing forever. It also makes failures readable: a log line saying the model cited leave-p9-c4 tells an engineer immediately that the document has no page 9 chunk.

The cost is a few extra tokens per ID, and models occasionally mistype a long ID. That is acceptable, because a mistyped ID simply fails the existence check and the claim is rejected. A common alternative is to show the model short per-request aliases (S1 to S4) and map them back to stable IDs in code, which shortens the prompt at the price of a mapping layer.

The contract itself is simple. The prompt lists each source as [id] (source, page N): text, tells the model to use only those IDs, and asks for JSON of the form {"claims": [{"text": "...", "source_ids": ["..."]}]}. An empty claims list is the model's own way of saying the sources don't answer the question.

Models.cs / cited_rag.py

using System.Text.Json;

public interface IRetriever
{
    Task<IReadOnlyList<Chunk>> RetrieveAsync(string question, CancellationToken ct = default);
}

public interface ILlm
{
    Task<string> CompleteAsync(string prompt, CancellationToken ct = default);
}

public record Chunk(string Id, string Source, int Page, string Text);
public record Claim(string Text, IReadOnlyList<string> SourceIds);
public record Citation(string SourceId, string Source, int Page, string Excerpt);
public record VerifiedClaim(string Text, IReadOnlyList<Citation> Citations);
public record RejectedClaim(string Text, string Reason);   // no_citation | unknown_source_id | not_supported

public record CitedAnswer(
    string Text,
    IReadOnlyList<VerifiedClaim> Claims,
    IReadOnlyList<RejectedClaim> Rejected,
    bool Abstained,
    string? AbstainReason);                                // no_evidence | malformed_output | no_verified_claims

public static class Prompts
{
    // Stable: derived from where the text lives, not from retrieval rank, so IDs survive across requests.
    public static string MakeChunkId(string doc, int page, int index) => $"{doc}-p{page}-c{index}";

    public static string Build(string question, IReadOnlyList<Chunk> chunks)
    {
        var sources = string.Join("\n", chunks.Select(c => $"[{c.Id}] ({c.Source}, page {c.Page}): {c.Text}"));
        return "Answer using only the sources below. Break your answer into claims. Every claim must list " +
               "the IDs of the sources that support it. Use only IDs that appear in the sources.\n" +
               "Respond with JSON only: {\"claims\": [{\"text\": \"...\", \"source_ids\": [\"...\"]}]}\n" +
               "If the sources do not answer the question, respond with {\"claims\": []}.\n\n" +
               $"Sources:\n{sources}\n\nQuestion: {question}";
    }

    public static List<Claim>? ParseClaims(string raw)
    {
        try
        {
            using var doc = JsonDocument.Parse(raw);
            var claims = new List<Claim>();
            foreach (var c in doc.RootElement.GetProperty("claims").EnumerateArray())
            {
                var ids = c.TryGetProperty("source_ids", out var s)
                    ? s.EnumerateArray().Select(e => e.GetString() ?? "").ToList()
                    : new List<string>();
                claims.Add(new Claim(c.GetProperty("text").GetString() ?? "", ids));
            }
            return claims;
        }
        catch (Exception e) when (e is JsonException or KeyNotFoundException or InvalidOperationException)
        {
            return null;   // malformed output is a result, not an exception
        }
    }
}

import json
import re
from dataclasses import dataclass, field
from typing import Protocol

NOT_FOUND = "I couldn't find enough evidence in the documents to answer that."


class Retriever(Protocol):
    def retrieve(self, question: str) -> list["Chunk"]: ...


class Llm(Protocol):
    def complete(self, prompt: str) -> str: ...


@dataclass(frozen=True)
class Chunk:
    id: str
    source: str
    page: int
    text: str


@dataclass(frozen=True)
class Claim:
    text: str
    source_ids: list[str]


@dataclass(frozen=True)
class Citation:
    source_id: str
    source: str
    page: int
    excerpt: str


@dataclass(frozen=True)
class VerifiedClaim:
    text: str
    citations: list[Citation]


@dataclass(frozen=True)
class RejectedClaim:
    text: str
    reason: str  # no_citation | unknown_source_id | not_supported


@dataclass(frozen=True)
class CitedAnswer:
    text: str
    claims: list[VerifiedClaim] = field(default_factory=list)
    rejected: list[RejectedClaim] = field(default_factory=list)
    abstained: bool = False
    abstain_reason: str | None = None  # no_evidence | malformed_output | no_verified_claims


def make_chunk_id(doc: str, page: int, index: int) -> str:
    # Stable: derived from where the text lives, not from retrieval rank, so IDs survive across requests.
    return f"{doc}-p{page}-c{index}"


def build_prompt(question: str, chunks: list[Chunk]) -> str:
    sources = "\n".join(f"[{c.id}] ({c.source}, page {c.page}): {c.text}" for c in chunks)
    return (
        "Answer using only the sources below. Break your answer into claims. Every claim must list "
        "the IDs of the sources that support it. Use only IDs that appear in the sources.\n"
        'Respond with JSON only: {"claims": [{"text": "...", "source_ids": ["..."]}]}\n'
        'If the sources do not answer the question, respond with {"claims": []}.\n\n'
        f"Sources:\n{sources}\n\nQuestion: {question}"
    )


def parse_claims(raw: str) -> list[Claim] | None:
    try:
        data = json.loads(raw)
        return [Claim(str(c["text"]), [str(i) for i in c.get("source_ids", [])]) for c in data["claims"]]
    except (json.JSONDecodeError, KeyError, TypeError, AttributeError):
        return None  # malformed output is a result, not an exception

Parsing is a boundary too. Malformed JSON is a normal outcome from a language model, so the parser returns null (or None) instead of throwing, and the service turns that into an abstention. Provider structured-output modes reduce malformed output but don't remove the need for this path; the structured-output article earlier in this series covers that in depth.

Core Implementation: The Verifier

The verifier applies three checks to each claim, in order, and records why a claim failed so that failures can be counted later.

  1. Is there a citation? A claim with no source IDs is rejected as no_citation.
  2. Do the cited IDs exist in the retrieved set? Any unknown ID rejects the whole claim as unknown_source_id. This is deliberately strict: a fabricated ID is evidence the model was not reading the sources for that claim, so keeping the claim and dropping only the bad ID would trust the part that is probably also invented.
  3. Does the cited chunk support the claim? A claim is kept only with the citations that pass a support check, and rejected as not_supported if none do.

For each surviving citation the verifier also extracts an excerpt, the single sentence in the chunk that best matches the claim. That is what turns a bare ID into evidence a reader can check in a glance, without opening the document.

Verifier.cs / cited_rag.py

using System.Text.RegularExpressions;

public static class Verifier
{
    public const double MinSupport = 0.6;   // share of a claim's content words that must appear in the cited chunk

    static readonly HashSet<string> Stop = new()
    {
        "a", "an", "the", "of", "to", "in", "on", "for", "and", "or", "is", "are", "be", "can", "may",
        "up", "over", "per", "by", "at", "as", "it", "its", "that", "this", "with", "from", "do",
        "does", "you", "i", "my", "am", "how", "much", "what",
    };

    static HashSet<string> ContentWords(string text) =>
        Regex.Matches(text.ToLowerInvariant(), "[a-z0-9]+")
             .Select(m => m.Value)
             .Where(w => !Stop.Contains(w))
             // Light stemming so "days" matches "day"; stopwords carry no evidence.
             .Select(w => w.Length > 3 && w.EndsWith('s') && !w.EndsWith("ss") ? w[..^1] : w)
             .ToHashSet();

    static HashSet<string> Numbers(string text) =>
        Regex.Matches(text, @"\d+(?:\.\d+)?").Select(m => m.Value).ToHashSet();

    public static double SupportScore(string claim, string chunkText)
    {
        // A figure the chunk doesn't contain can't be supported by it.
        if (!Numbers(claim).IsSubsetOf(Numbers(chunkText))) return 0;

        var claimWords = ContentWords(claim);
        if (claimWords.Count == 0) return 0;
        return (double)claimWords.Intersect(ContentWords(chunkText)).Count() / claimWords.Count;
    }

    public static string BestExcerpt(string claim, string chunkText) =>
        Regex.Split(chunkText.Trim(), @"(?<=[.!?])\s+")
             .MaxBy(s => SupportScore(claim, s))!;

    public static (List<VerifiedClaim> Verified, List<RejectedClaim> Rejected) Verify(
        IEnumerable<Claim> claims, IReadOnlyList<Chunk> retrieved)
    {
        var byId = retrieved.ToDictionary(c => c.Id);
        var verified = new List<VerifiedClaim>();
        var rejected = new List<RejectedClaim>();

        foreach (var claim in claims)
        {
            if (claim.SourceIds.Count == 0)
            {
                rejected.Add(new RejectedClaim(claim.Text, "no_citation"));
            }
            else if (claim.SourceIds.Any(id => !byId.ContainsKey(id)))
            {
                rejected.Add(new RejectedClaim(claim.Text, "unknown_source_id"));   // a fabricated ID taints the claim
            }
            else
            {
                var supporting = claim.SourceIds.Select(id => byId[id])
                    .Where(c => SupportScore(claim.Text, c.Text) >= MinSupport).ToList();
                if (supporting.Count == 0)
                    rejected.Add(new RejectedClaim(claim.Text, "not_supported"));
                else
                    verified.Add(new VerifiedClaim(claim.Text, supporting
                        .Select(c => new Citation(c.Id, c.Source, c.Page, BestExcerpt(claim.Text, c.Text)))
                        .ToList()));
            }
        }
        return (verified, rejected);
    }
}

MIN_SUPPORT = 0.6  # share of a claim's content words that must appear in the cited chunk

STOPWORDS = {
    "a", "an", "the", "of", "to", "in", "on", "for", "and", "or", "is", "are", "be", "can", "may",
    "up", "over", "per", "by", "at", "as", "it", "its", "that", "this", "with", "from", "do",
    "does", "you", "i", "my", "am", "how", "much", "what",
}


def _content_words(text: str) -> set[str]:
    words = re.findall(r"[a-z0-9]+", text.lower())
    # Light stemming so "days" matches "day"; stopwords carry no evidence.
    return {w[:-1] if len(w) > 3 and w.endswith("s") and not w.endswith("ss") else w
            for w in words if w not in STOPWORDS}


def _numbers(text: str) -> set[str]:
    return set(re.findall(r"\d+(?:\.\d+)?", text))


def support_score(claim: str, chunk_text: str) -> float:
    # A figure the chunk doesn't contain can't be supported by it.
    if not _numbers(claim) <= _numbers(chunk_text):
        return 0.0
    claim_words = _content_words(claim)
    if not claim_words:
        return 0.0
    return len(claim_words & _content_words(chunk_text)) / len(claim_words)


def best_excerpt(claim: str, chunk_text: str) -> str:
    sentences = re.split(r"(?<=[.!?])\s+", chunk_text.strip())
    return max(sentences, key=lambda s: support_score(claim, s))


def verify(claims: list[Claim], retrieved: list[Chunk]) -> tuple[list[VerifiedClaim], list[RejectedClaim]]:
    by_id = {c.id: c for c in retrieved}
    verified: list[VerifiedClaim] = []
    rejected: list[RejectedClaim] = []
    for claim in claims:
        if not claim.source_ids:
            rejected.append(RejectedClaim(claim.text, "no_citation"))
        elif any(i not in by_id for i in claim.source_ids):
            rejected.append(RejectedClaim(claim.text, "unknown_source_id"))  # a fabricated ID taints the claim
        else:
            supporting = [by_id[i] for i in claim.source_ids
                          if support_score(claim.text, by_id[i].text) >= MIN_SUPPORT]
            if not supporting:
                rejected.append(RejectedClaim(claim.text, "not_supported"))
            else:
                verified.append(VerifiedClaim(claim.text, [
                    Citation(c.id, c.source, c.page, best_excerpt(claim.text, c.text)) for c in supporting]))
    return verified, rejected

Key Technical Challenge: Citation Laundering

The first two checks are structural, and they are the easy ones. The difficult case is a real ID attached to a claim the chunk doesn't support: the model cites leave-p2-c1 for a statement about business-class flights. The ID exists, the claim is cited, and only a look at the chunk's content reveals the mismatch.

The support check here is lexical: the share of the claim's content words (stopwords removed, light stemming) that appear in the cited chunk, with a threshold of 0.6. It catches off-topic citations cheaply and deterministically. Numbers get special treatment, because they are the most damaging thing to get wrong and the easiest to slip through a word-overlap score: a claim of "25 days" against a chunk that says "20 days" shares almost every other word and would pass at 0.89. So every figure in the claim must appear in the cited chunk, or the score is zero.

The honest limit is that word overlap is not entailment. It cannot see negation ("may not be carried over" shares the same words as "may be carried over"), reversed relationships, or a number written as a word in one place and digits in another. The threshold also has the same property as the retrieval threshold in the previous article: 0.6 is a starting point, and the right value comes from labelled examples of supported and unsupported claims from your own documents.

When overlap isn't strong enough, two upgrades exist. A natural-language-inference model scores whether the chunk entails the claim. A second LLM call acts as a judge, given only the claim and the cited chunk. Both are better at meaning and worse at being cheap and predictable, and the cost section prices the second one. For high-stakes domains the excerpt in the response matters most, because it lets a person make the final call in seconds.

Key Technical Challenge: Abstention Policy and Response Shape

When some claims pass and others fail, the system needs a policy. There are three reasonable ones:

  • Drop failures, keep the rest. This is what the code below does. It maximises useful answers, but a partial answer can mislead by omission, for example when the dropped claim carried the caveat. Expose the rejected count so a client can flag the answer as partial.
  • Reject the whole answer if any claim fails. Simpler to reason about and appropriate for compliance or legal content, at the price of a higher abstention rate.
  • Retry once with the failure reasons in the prompt. This often repairs fabricated IDs, and it adds a second model call to the worst case.

The response shape follows the deliverable: the answer, and a list of validated citations. Each citation carries the source name, page and excerpt. The abstained flag and reason are part of the contract, so a client can show "no answer" differently from "answer with evidence". Rejected claims stay in logs by default, since showing users the claims that were just judged unsupported defeats the purpose.

{
  "text": "Full-time employees accrue 20 days of annual leave per year. [leave-p2-c1] Up to five days of unused leave can be carried over. [leave-p2-c1]",
  "abstained": false,
  "claims": [
    {
      "text": "Full-time employees accrue 20 days of annual leave per year.",
      "citations": [
        { "sourceId": "leave-p2-c1", "source": "leave-policy.pdf", "page": 2,
          "excerpt": "Full-time employees accrue 20 days of annual leave per year." }
      ]
    }
  ]
}

The service ties the pieces together. It abstains before the LLM call when retrieval returns nothing, treats unparseable output as an abstention, and abstains with the rejected list when no claim survives.

CitedRagService.cs / cited_rag.py

public class CitedRagService(IRetriever retriever, ILlm llm)
{
    public const string NotFound = "I couldn't find enough evidence in the documents to answer that.";

    static readonly IReadOnlyList<VerifiedClaim> NoClaims = Array.Empty<VerifiedClaim>();
    static readonly IReadOnlyList<RejectedClaim> NoRejected = Array.Empty<RejectedClaim>();

    public async Task<CitedAnswer> AskAsync(string question, CancellationToken ct = default)
    {
        var chunks = await retriever.RetrieveAsync(question, ct);
        if (chunks.Count == 0)   // no LLM call: nothing to ground on
            return new CitedAnswer(NotFound, NoClaims, NoRejected, true, "no_evidence");

        var claims = Prompts.ParseClaims(await llm.CompleteAsync(Prompts.Build(question, chunks), ct));
        if (claims is null)
            return new CitedAnswer(NotFound, NoClaims, NoRejected, true, "malformed_output");

        var (verified, rejected) = Verifier.Verify(claims, chunks);
        if (verified.Count == 0)
            return new CitedAnswer(NotFound, NoClaims, rejected, true, "no_verified_claims");

        var text = string.Join(" ", verified.Select(c =>
            $"{c.Text} [{string.Join(", ", c.Citations.Select(x => x.SourceId))}]"));
        return new CitedAnswer(text, verified, rejected, false, null);
    }
}

class CitedRagService:
    def __init__(self, retriever: Retriever, llm: Llm) -> None:
        self._retriever = retriever
        self._llm = llm

    def ask(self, question: str) -> CitedAnswer:
        chunks = self._retriever.retrieve(question)
        if not chunks:
            return CitedAnswer(NOT_FOUND, abstained=True, abstain_reason="no_evidence")  # no LLM call

        claims = parse_claims(self._llm.complete(build_prompt(question, chunks)))
        if claims is None:
            return CitedAnswer(NOT_FOUND, abstained=True, abstain_reason="malformed_output")

        verified, rejected = verify(claims, chunks)
        if not verified:
            return CitedAnswer(NOT_FOUND, rejected=rejected, abstained=True, abstain_reason="no_verified_claims")

        text = " ".join(f"{c.text} [{', '.join(x.source_id for x in c.citations)}]" for c in verified)
        return CitedAnswer(text, verified, rejected)

What This Costs

The verifier itself costs nothing: it runs no model and no tokens. The cost of citations is on the generation side, where the model now emits structured claims with IDs. The table uses OpenAI's published list prices at the time of writing, per million input and output tokens: GPT-5.4 mini at $0.75 and $4.50, GPT-5.4 at $2.50 and $15.00, and GPT-5.5 at $5.00 and $30.00. The token counts are assumptions for illustration, not measurements: four chunks of about 150 words (roughly 780 tokens) plus instructions and the question for about 1,100 input tokens, and about 200 output tokens of JSON claims against about 150 for a plain answer.

ScenarioGPT-5.4 miniGPT-5.4GPT-5.5
Plain answer, no citations (1,100 in, 150 out)about $0.0015about $0.0050about $0.0100
Cited answer with deterministic verifier (1,100 in, 200 out)about $0.0017about $0.0058about $0.0115
Cited answer plus an LLM-judge pass (extra 1,000 in, 100 out)about $0.0029about $0.0098about $0.0195
Abstained before the LLM (no chunks retrieved)no generation cost

Cost Reality

Asking for citations adds about 50 output tokens, roughly 15% to the cost of an answer. Verification with code is free, while a judge pass adds about 70% to the cost of a GPT-5.4 answer (from $0.0058 to $0.0098). Rejected answers still pay for the model call, so a high rejection rate is a cost problem as well as a quality one.

These are OpenAI direct list prices and they change, so check current pricing. Azure OpenAI is priced separately and varies by deployment tier: Global Standard, Data Zone and regional deployments, Batch (discounted, with a 24-hour turnaround) and Provisioned throughput (reserved capacity). Each tier suits a different purpose, such as interactive traffic, bulk offline jobs or steady high-volume workloads. Azure rates could not be retrieved at the time of writing, so none are quoted here, and the figures in this article may be slightly out of date for Azure deployments.

Observability

Log what the verification layer decided, not what anyone wrote. For each request record the retrieved chunk IDs, how many claims the model produced, how many were verified, the rejection reason for each failure, the abstain reason if any, and the number of LLM calls.

The rejection reasons are the most useful signal because each points at a different cause. A rising unknown_source_id rate suggests a prompt or model change. A rising not_supported rate suggests retrieval drift or a model that paraphrases more loosely. A rising no_citation rate means the model is answering from memory. Claims that pass with a support score just above the threshold make a good review queue. As with retrieval logging, avoid storing question text and chunk text by default, since both can contain personal or confidential data.

Testing

The LLM call is the only non-deterministic part, so it is the only thing replaced. A fake LLM returns canned JSON that stands in for what a model might say, a fake retriever returns fixed chunks, and everything else (parsing, ID checks, support scoring, excerpts, abstention) is ordinary code under ordinary tests.

The tests cover the three scenarios from the brief. A correct answer returns citations with source, page and excerpt. A fabricated ID is rejected, and the answer abstains when it was the only claim. An unsupported claim is rejected, whether it has no citation, a real ID that doesn't support it, or a number the chunk doesn't contain. A mixed answer keeps only the verified claim and reports the rest. The call-count assertions prove the control flow: zero LLM calls when nothing was retrieved, one otherwise.

These tests prove the verifier handles each failure mode correctly. They do not prove that a real model cites well. Measure the fabricated-ID rate, the uncited-claim rate and the laundering rate against your own questions and documents before trusting any threshold.

CitedRagTests.cs / test_cited_rag.py

using System.Text.Json;
using Xunit;

public class CitedRagTests
{
    static readonly Chunk Leave = new("leave-p2-c1", "leave-policy.pdf", 2,
        "Full-time employees accrue 20 days of annual leave per year. Unused leave may be carried over up to five days.");
    static readonly Chunk Remote = new("remote-p1-c1", "remote-work-policy.pdf", 1,
        "Employees may work remotely up to three days per week. Remote days must be agreed with a manager in advance.");
    const string Question = "How much annual leave do I get, and can I carry it over?";

    static readonly object GoodAccrual = new { text = "Full-time employees accrue 20 days of annual leave per year.", source_ids = new[] { "leave-p2-c1" } };
    static readonly object GoodCarry = new { text = "Up to five days of unused leave can be carried over.", source_ids = new[] { "leave-p2-c1" } };

    class FakeRetriever(params Chunk[] chunks) : IRetriever
    {
        public Task<IReadOnlyList<Chunk>> RetrieveAsync(string question, CancellationToken ct = default) =>
            Task.FromResult<IReadOnlyList<Chunk>>(chunks);
    }

    class FakeLlm(string reply) : ILlm
    {
        public int Calls;
        public Task<string> CompleteAsync(string prompt, CancellationToken ct = default)
        {
            Calls++;
            return Task.FromResult(reply);
        }
    }

    static async Task<(CitedAnswer Answer, FakeLlm Llm)> Ask(string reply, params Chunk[] chunks)
    {
        var llm = new FakeLlm(reply);
        return (await new CitedRagService(new FakeRetriever(chunks), llm).AskAsync(Question), llm);
    }

    static string Claims(params object[] claims) => JsonSerializer.Serialize(new { claims });

    [Fact]
    public async Task CorrectAnswerReturnsVerifiableCitations()
    {
        var (answer, llm) = await Ask(Claims(GoodAccrual, GoodCarry), Leave, Remote);
        Assert.False(answer.Abstained);
        Assert.Empty(answer.Rejected);
        var citation = answer.Claims[0].Citations[0];
        Assert.Equal(("leave-p2-c1", "leave-policy.pdf", 2), (citation.SourceId, citation.Source, citation.Page));
        Assert.Equal("Full-time employees accrue 20 days of annual leave per year.", citation.Excerpt);
        Assert.Equal("Unused leave may be carried over up to five days.", answer.Claims[1].Citations[0].Excerpt);
        Assert.Equal(1, llm.Calls);
    }

    [Fact]
    public async Task FabricatedCitationIdIsRejectedAndAnswerAbstains()
    {
        var fake = new { text = "Full-time employees accrue 20 days of annual leave per year.", source_ids = new[] { "leave-p9-c4" } };
        var (answer, _) = await Ask(Claims(fake), Leave, Remote);
        Assert.True(answer.Abstained);
        Assert.Equal("no_verified_claims", answer.AbstainReason);
        Assert.Equal(new[] { "unknown_source_id" }, answer.Rejected.Select(r => r.Reason));
        Assert.Equal(CitedRagService.NotFound, answer.Text);
    }

    [Fact]
    public async Task MixedAnswerKeepsOnlyVerifiedClaims()
    {
        var fake = new { text = "Employees receive a leave loading of 17.5%.", source_ids = new[] { "leave-p9-c4" } };
        var (answer, _) = await Ask(Claims(GoodAccrual, fake), Leave, Remote);
        Assert.False(answer.Abstained);
        Assert.Single(answer.Claims);
        Assert.Equal(new[] { "unknown_source_id" }, answer.Rejected.Select(r => r.Reason));
        Assert.DoesNotContain("17.5%", answer.Text);
    }

    [Fact]
    public async Task ClaimWithoutCitationIsRejected()
    {
        var uncited = new { text = "Bonuses are paid in March.", source_ids = Array.Empty<string>() };
        var (answer, _) = await Ask(Claims(GoodAccrual, uncited), Leave, Remote);
        Assert.Equal(new[] { "no_citation" }, answer.Rejected.Select(r => r.Reason));
        Assert.Single(answer.Claims);
    }

    [Fact]
    public async Task RealIdThatDoesNotSupportTheClaimIsRejected()
    {
        var laundered = new { text = "Employees may book business class on long flights.", source_ids = new[] { "leave-p2-c1" } };
        var (answer, _) = await Ask(Claims(laundered), Leave, Remote);
        Assert.True(answer.Abstained);
        Assert.Equal(new[] { "not_supported" }, answer.Rejected.Select(r => r.Reason));
    }

    [Fact]
    public async Task ClaimWithANumberTheChunkDoesNotContainIsRejected()
    {
        var wrong = new { text = "Full-time employees accrue 25 days of annual leave per year.", source_ids = new[] { "leave-p2-c1" } };
        var (answer, _) = await Ask(Claims(wrong), Leave, Remote);
        Assert.Equal(new[] { "not_supported" }, answer.Rejected.Select(r => r.Reason));
    }

    [Fact]
    public async Task NoRetrievedEvidenceAbstainsWithoutCallingTheLlm()
    {
        var (answer, llm) = await Ask(Claims(GoodAccrual));
        Assert.True(answer.Abstained);
        Assert.Equal("no_evidence", answer.AbstainReason);
        Assert.Equal(0, llm.Calls);
    }

    [Fact]
    public async Task MalformedModelOutputAbstainsInsteadOfThrowing()
    {
        var (answer, llm) = await Ask("Sure! Employees get 20 days.", Leave, Remote);
        Assert.True(answer.Abstained);
        Assert.Equal("malformed_output", answer.AbstainReason);
        Assert.Equal(1, llm.Calls);
    }

    [Fact]
    public void ChunkIdsAreStableAndPromptListsOnlyRetrievedIds()
    {
        Assert.Equal("leave-p2-c1", Prompts.MakeChunkId("leave", 2, 1));
        Assert.Equal(Prompts.MakeChunkId("leave", 2, 1), Prompts.MakeChunkId("leave", 2, 1));
        var prompt = Prompts.Build(Question, new[] { Leave });
        Assert.Contains("[leave-p2-c1]", prompt);
        Assert.DoesNotContain("remote-p1-c1", prompt);
    }
}

import json

from cited_rag import Chunk, CitedRagService, NOT_FOUND, build_prompt, make_chunk_id

LEAVE = Chunk("leave-p2-c1", "leave-policy.pdf", 2,
              "Full-time employees accrue 20 days of annual leave per year. "
              "Unused leave may be carried over up to five days.")
REMOTE = Chunk("remote-p1-c1", "remote-work-policy.pdf", 1,
               "Employees may work remotely up to three days per week. "
               "Remote days must be agreed with a manager in advance.")
QUESTION = "How much annual leave do I get, and can I carry it over?"

GOOD_ACCRUAL = {"text": "Full-time employees accrue 20 days of annual leave per year.",
                "source_ids": ["leave-p2-c1"]}
GOOD_CARRY = {"text": "Up to five days of unused leave can be carried over.",
              "source_ids": ["leave-p2-c1"]}


class FakeRetriever:
    def __init__(self, chunks):
        self.chunks = chunks

    def retrieve(self, question):
        return self.chunks


class FakeLlm:
    def __init__(self, reply):
        self.reply = reply
        self.calls = 0

    def complete(self, prompt):
        self.calls += 1
        return self.reply


def ask(claims_or_raw, chunks=(LEAVE, REMOTE)):
    reply = claims_or_raw if isinstance(claims_or_raw, str) else json.dumps({"claims": claims_or_raw})
    llm = FakeLlm(reply)
    return CitedRagService(FakeRetriever(list(chunks)), llm).ask(QUESTION), llm


def test_correct_answer_returns_verifiable_citations():
    answer, llm = ask([GOOD_ACCRUAL, GOOD_CARRY])
    assert not answer.abstained and not answer.rejected
    citation = answer.claims[0].citations[0]
    assert (citation.source_id, citation.source, citation.page) == ("leave-p2-c1", "leave-policy.pdf", 2)
    assert citation.excerpt == "Full-time employees accrue 20 days of annual leave per year."
    assert answer.claims[1].citations[0].excerpt == "Unused leave may be carried over up to five days."
    assert llm.calls == 1


def test_fabricated_citation_id_is_rejected_and_answer_abstains():
    fake = {"text": "Full-time employees accrue 20 days of annual leave per year.",
            "source_ids": ["leave-p9-c4"]}
    answer, _ = ask([fake])
    assert answer.abstained and answer.abstain_reason == "no_verified_claims"
    assert [r.reason for r in answer.rejected] == ["unknown_source_id"]
    assert answer.text == NOT_FOUND


def test_mixed_answer_keeps_only_verified_claims():
    fake = {"text": "Employees receive a leave loading of 17.5%.", "source_ids": ["leave-p9-c4"]}
    answer, _ = ask([GOOD_ACCRUAL, fake])
    assert not answer.abstained
    assert [c.text for c in answer.claims] == [GOOD_ACCRUAL["text"]]
    assert [r.reason for r in answer.rejected] == ["unknown_source_id"]
    assert "17.5%" not in answer.text


def test_claim_without_citation_is_rejected():
    answer, _ = ask([GOOD_ACCRUAL, {"text": "Bonuses are paid in March.", "source_ids": []}])
    assert [r.reason for r in answer.rejected] == ["no_citation"]
    assert len(answer.claims) == 1


def test_real_id_that_does_not_support_the_claim_is_rejected():
    laundered = {"text": "Employees may book business class on long flights.", "source_ids": ["leave-p2-c1"]}
    answer, _ = ask([laundered])
    assert answer.abstained
    assert [r.reason for r in answer.rejected] == ["not_supported"]


def test_claim_with_a_number_the_chunk_does_not_contain_is_rejected():
    wrong = {"text": "Full-time employees accrue 25 days of annual leave per year.", "source_ids": ["leave-p2-c1"]}
    answer, _ = ask([wrong])
    assert [r.reason for r in answer.rejected] == ["not_supported"]


def test_no_retrieved_evidence_abstains_without_calling_the_llm():
    answer, llm = ask([GOOD_ACCRUAL], chunks=())
    assert answer.abstained and answer.abstain_reason == "no_evidence"
    assert llm.calls == 0


def test_malformed_model_output_abstains_instead_of_raising():
    answer, llm = ask("Sure! Employees get 20 days.")
    assert answer.abstained and answer.abstain_reason == "malformed_output"
    assert llm.calls == 1


def test_chunk_ids_are_stable_and_prompt_lists_only_retrieved_ids():
    assert make_chunk_id("leave", 2, 1) == make_chunk_id("leave", 2, 1) == "leave-p2-c1"
    prompt = build_prompt(QUESTION, [LEAVE])
    assert "[leave-p2-c1]" in prompt and "remote-p1-c1" not in prompt

Technology Choices

C#/.NET Implementation

Why choose C#: If your backend is .NET, you get first-party Microsoft support and enterprise patterns.

  • Native Azure integration — the Azure OpenAI SDK sits behind the ILlm interface, so the verifier never knows which provider produced the claims
  • Enterprise patterns — immutable records for claims and citations, dependency injection for the retriever and the model
  • Production-ready — the service maps directly onto an ASP.NET Core endpoint returning the response shape above

Python Implementation

Why choose Python: If your team writes Python, you get access to the richest AI/ML ecosystem.

  • Library ecosystem — Pydantic can validate the claim JSON, and NLI models for stronger support checks are Python-first
  • Rapid prototyping — quick iteration on the support threshold against labelled claims in a notebook
  • Community — most RAG evaluation tooling is Python-first

The Bottom Line

C#/.NET team? Use C#. Python team? Use Python. Don't fight your stack. The verifier has no provider dependency, so it ports between languages and between OpenAI and Azure OpenAI unchanged. If Azure OpenAI is the provider, check the deployment tier and current rates before budgeting, because they differ from the OpenAI list prices quoted in this article.

Engineering Trade-offs

Citation verification pays off when answers will be acted on, audited or shown to people who can't judge them, and when a wrong answer costs more than no answer. It adds a stricter prompt, a parser, a verifier with a threshold to maintain and a higher abstention rate. It reduces how often an unsupported statement reaches a user. It does not make the model correct.

When to Skip or Rethink This

  • The output is creative or conversational. There are no source claims to verify, and forced citations produce noise.
  • You need semantic guarantees from a lexical check. Negation and reversed relationships pass word overlap. Use an entailment model, a judge pass or human review.
  • You can't calibrate the threshold. An uncalibrated 0.6 is a guess, and it will either reject good claims or admit bad ones.
  • Users would rather see a draft with caveats than an abstention. Strict verification is the wrong product behaviour there.

The verifier is also only as good as retrieval. If the right chunk was never retrieved, the best outcome is a correct abstention. The next article in this series covers retrieval evaluation, which measures whether the right chunks arrive in the first place.

Key Takeaways

  • A citation nobody checks is decoration. It fails by fabricated ID, missing citation or citation laundering.
  • Give every chunk a stable ID from document, page and position, and make the model cite by that ID in a structured format.
  • The model proposes and code disposes: validity is decided by a deterministic verifier outside the model.
  • Check existence against this request's retrieved set, then check support, with numbers required to match exactly.
  • Pick the abstention policy deliberately, and return validated citations with source, page and excerpt.
  • Mock only the LLM, and assert call counts to prove abstention happens before generation.

Interview Questions

What is grounding, and how is it different from retrieval? Retrieval supplies evidence. Grounding means each claim in the answer is tied to that evidence and supported by it. A system can retrieve well and still be ungrounded.

What kinds of hallucination does citation checking catch? Fabricated source IDs and uncited claims are caught structurally. Citations that don't support the claim are caught partly by a support check. Contradictions and subtle paraphrase errors need an entailment model, a judge or a human.

What is provenance, and why use stable IDs? Provenance is the traceable path from an answer back to the exact passage and document. Stable IDs keep that path valid across requests, so logs, caches and evaluation sets stay linked to the same passage.

How do you verify evidence for a claim? Layer the checks: the claim has a citation, the cited ID is in the retrieved set, and the cited text supports the claim. Cheap deterministic checks first, then a more expensive semantic check where the risk justifies it.

When should the system abstain? When no claim survives verification, when nothing was retrieved, or when output can't be parsed. Whether to abstain on a partly verified answer depends on the cost of a misleading partial answer.

Want More Practical AI Tutorials?

Practical production AI engineering with Azure, Python and C#, published twice a week in the Real-World AI Engineering series.

Read More Articles →

Written by Jaffar Kazi, a software engineer in Sydney building AI-powered applications. Connect on LinkedIn.