Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 5 · Worked example · 20 min · revision 2

Asking for Citations and Validating Them

Label the retrieved passages for each request, ask for an answer as a list of claims that cite passage IDs, reject any citation outside the retrieved set with a Pydantic validator, retry once, and compare this with Claude's built-in citations on search results.

Contentsand lesson path

What you will learn

  • Produce answers that cite source IDs at the claim level and verify in code that every cited ID was actually retrieved.

Prerequisites: RAG Foundations

01. The problem

The Lumen help-centre assistant ends each answer with a list of the articles it retrieved. That list says what the model was shown, not which sentence rests on which article. When the team asked for markers such as [2] in the prose, some answers cited [4] after a request that retrieved three passages. This worked example rebuilds the answer step so that every claim can be checked:

  • each retrieved passage gets a short ID for the request, and your code keeps the map from ID to chunk;
  • the model returns structured output: a list of claims, each with the IDs of the passages that support it;
  • your code rejects a claim without a citation and any ID that was not retrieved, retries once with the errors, and falls back when the retry fails;
  • the user sees numbered sources that lead to real chunks.

Validation proves that every citation points at a passage the model was shown, not that the passage supports the claim; that is lesson 4. Finally you compare this with Claude's built-in citations.

You need Python 3.12 or later; this example was tested with Pydantic 2.14 and the anthropic package 2.9 (output_config needs version 2 or later). Steps 1 to 3 and the check in step 5 run offline against FAKE replies, so you can reproduce every output below. The real API calls need ANTHROPIC_API_KEY and ANTHROPIC_MODEL in the environment.

Terminal
mkdir cited-answers && cd cited-answers
python3 -m venv .venv
source .venv/bin/activate        # Windows (PowerShell): .venv\Scripts\Activate.ps1
python -m pip install "pydantic>=2.7,<3" "anthropic>=2.9,<3"

02. Step 1: Give each retrieved passage an ID for this request

Your retriever returns chunks with stable IDs like the ones from the chunking skill (shortened here to billing-refunds#1). In the prompt, label the hits P1, P2, P3 and keep a dictionary from label to chunk. Short labels are easy to copy exactly; the dictionary is the retrieved set the validator checks; and the mapping back to chunk IDs and titles stays in your code, where the model cannot garble it.

retrieve() is a stand-in that returns three fixed hits; in your project, call your own retriever. The <doc> format is the one from the tokens and context lab, plus an id.

Python · passages.py
"""Retrieved passages, labelled P1, P2, ... for one request."""

import textwrap
from dataclasses import dataclass


@dataclass(frozen=True)
class Hit:
    chunk_id: str  # stable ID from your chunker, e.g. "billing-refunds#1"
    title: str
    text: str


def retrieve(question: str) -> list[Hit]:
    """Stand-in for your RAG tool's retriever: three fixed hits, best first."""
    return [
        Hit("billing-refunds#1", "Refund eligibility",
            "Monthly plans can be refunded within 14 days of a charge. Annual plans"
            " can be refunded within 30 days of purchase; after that you can turn"
            " off renewal, but the current term is not refunded."),
        Hit("billing-refunds#2", "Requesting a refund",
            "To request a refund, open Settings > Billing > Invoices, choose the"
            " invoice and select Request refund. Refunds reach the original payment"
            " method within 10 business days."),
        Hit("files-limits#1", "File upload limits",
            "A single file upload can be up to 250 MB on the Business plan and up"
            " to 100 MB on the Pro plan."),
    ]


def label(hits: list[Hit]) -> dict[str, Hit]:
    """Give each hit a short label for this request: {"P1": hit, "P2": hit, ...}."""
    return {f"P{number}": hit for number, hit in enumerate(hits, start=1)}


def format_context(labelled: dict[str, Hit]) -> str:
    return "".join(
        f'<doc id="{pid}" title="{hit.title}">\n{hit.text}\n</doc>\n'
        for pid, hit in labelled.items()
    )


if __name__ == "__main__":
    labelled = label(retrieve("Can I get a refund on an annual plan?"))
    for line in format_context(labelled).splitlines():
        print(textwrap.shorten(line, width=78, placeholder=" ..."))
    print({pid: hit.chunk_id for pid, hit in labelled.items()})
Terminal
python passages.py
Expected output
<doc id="P1" title="Refund eligibility">
Monthly plans can be refunded within 14 days of a charge. Annual plans can ...
</doc>
<doc id="P2" title="Requesting a refund">
To request a refund, open Settings > Billing > Invoices, choose the ...
</doc>
<doc id="P3" title="File upload limits">
A single file upload can be up to 250 MB on the Business plan and up to ...
</doc>
{'P1': 'billing-refunds#1', 'P2': 'billing-refunds#2', 'P3': 'files-limits#1'}

The labels belong to one conversation. If a retry or a follow-up turn retrieves again, keep the labels of passages you already sent and give new passages new numbers, so that P2 never means two different passages in the same conversation.

03. Step 2: Describe a cited answer and validate it

Describe the answer as a Pydantic model, as in the validated-JSON lab of the prompt basics skill. Two rules make up the citation contract: every claim cites at least one passage, and every cited ID was sent with this request. The first rule fits a field constraint. The second depends on the request, so it cannot be written into the class; Pydantic's validation context carries per-call data into a validator instead.

Python · schema.py
"""An answer as a list of claims, each citing the passages that support it."""

from typing import Self

from pydantic import (
    BaseModel,
    ConfigDict,
    Field,
    ValidationError,
    ValidationInfo,
    model_validator,
)


class Claim(BaseModel):
    model_config = ConfigDict(extra="forbid")

    text: str = Field(min_length=1, description="One factual statement")
    sources: list[str] = Field(
        min_length=1, description="IDs of the passages that support it, e.g. P2"
    )


class CitedAnswer(BaseModel):
    model_config = ConfigDict(extra="forbid")

    claims: list[Claim] = Field(min_length=1)

    @model_validator(mode="after")
    def cited_ids_were_retrieved(self, info: ValidationInfo) -> Self:
        # No context means no retrieved set: every citation fails (fail closed).
        retrieved = (info.context or {}).get("retrieved", set())
        for number, claim in enumerate(self.claims, start=1):
            unknown = [s for s in claim.sources if s not in retrieved]
            if unknown:
                raise ValueError(f"claim {number} cites {unknown}, not retrieved")
        return self


def describe(err: ValidationError) -> str:
    """One line for all problems: where each one is and what is wrong."""
    return "; ".join(
        f"{'.'.join(map(str, e['loc'])) or 'answer'}: {e['msg']}" for e in err.errors()
    )
  • min_length=1 on sources rejects a claim with an empty citation list.
  • model_validator(mode="after") runs once every field is valid; info.context is whatever you pass as context=.
  • Without a context the retrieved set is empty and every citation fails. Failing closed means a forgotten argument shows up in your first test instead of silently accepting every ID.
  • describe() turns the errors into one line, which is what you log and what you send back to the model.

Try four replies against a request that retrieved P1 to P3:

Python · try_answers.py
from pydantic import ValidationError

from schema import CitedAnswer, describe

retrieved = {"P1", "P2", "P3"}
replies = [
    '{"claims": [{"text": "Annual plans can be refunded within 30 days.",'
    ' "sources": ["P1"]}]}',
    '{"claims": [{"text": "Refunds arrive within 10 business days.",'
    ' "sources": ["P4"]}]}',
    '{"claims": [{"text": "Refunds are reviewed within a day.", "sources": []}]}',
    '{"claims": [{"text": "Annual plans can be refunded within 30 days.",'
    ' "sources": ["billing-refunds#1"]}]}',
]
for number, reply in enumerate(replies, start=1):
    try:
        CitedAnswer.model_validate_json(reply, context={"retrieved": retrieved})
        print(number, "valid")
    except ValidationError as err:
        print(number, "invalid:", describe(err))
Terminal
python try_answers.py
Expected output
1 valid
2 invalid: answer: Value error, claim 1 cites ['P4'], not retrieved
3 invalid: claims.0.sources: List should have at least 1 item after validation, not 0
4 invalid: answer: Value error, claim 1 cites ['billing-refunds#1'], not retrieved

Reply 2 cites P4 after a request that retrieved three passages. Reply 3 has an empty citation list. Reply 4 cites a real chunk ID that was not sent with this request, which the model may have copied from an earlier turn or simply made up. Each rejection names the problem, which is what a retry needs.

04. Step 3: Ask, validate, retry once, fall back

The FAKE model below returns scripted replies, so that one run shows the three outcomes you must handle: a valid answer, a bad citation fixed on the retry, and a question that fails twice.

Python · fake_model.py
"""FAKE model for offline practice: scripted replies, not an LLM.

The first call for a question returns its first reply; a retry returns the next.
The replies imitate citation mistakes that real models make.
"""

SCRIPT = {
    "Can I get a refund on an annual plan, and how do I ask for one?": [
        '{"claims": ['
        '{"text": "Annual plans can be refunded within 30 days of purchase.",'
        ' "sources": ["P1"]},'
        '{"text": "Request it from Settings > Billing > Invoices.",'
        ' "sources": ["P2"]}]}',
    ],
    "How long does a refund take to reach my card?": [
        '{"claims": [{"text": "Refunds take up to 10 business days.",'
        ' "sources": ["P4"]}]}',
        '{"claims": [{"text": "Refunds take up to 10 business days.",'
        ' "sources": ["P2"]}]}',
    ],
    "Who checks my refund request?": [
        '{"claims": [{"text": "The billing team reviews requests within a day.",'
        ' "sources": []}]}',
        '{"claims": [{"text": "The billing team reviews requests within a day.",'
        ' "sources": ["billing-team#4"]}]}',
    ],
}


def fake_chat(system: str, messages: list[dict[str, str]]) -> str:
    replies = next(r for q, r in SCRIPT.items() if q in messages[0]["content"])
    attempt = sum(m["role"] == "assistant" for m in messages)
    return replies[min(attempt, len(replies) - 1)]
Python · cited_answer.py · part 1
"""Ask for claim-level citations, validate them, retry once, then fall back."""

import json
import textwrap
from collections.abc import Callable

from pydantic import ValidationError

from fake_model import fake_chat
from passages import Hit, format_context, label, retrieve
from schema import CitedAnswer, describe

Chat = Callable[[str, list[dict[str, str]]], str]
Labelled = dict[str, Hit]
MAX_ATTEMPTS = 2  # the first call plus one retry


class GiveUp(Exception):
    """Raised by a chat function when asking again cannot help."""


SYSTEM = (
    "You answer questions about Lumen using only the passages in <doc> tags.\n"
    "Split the answer into short claims, one fact each. Give every claim the IDs"
    " of the passages that state it, such as P2. Use only IDs shown in the"
    " passages. Leave out anything the passages do not say.\n"
    "Reply with only a JSON object that matches this JSON Schema:\n"
    + json.dumps(CitedAnswer.model_json_schema())
)


def ask(question: str, chat: Chat = fake_chat) -> tuple[CitedAnswer | None, Labelled]:
    labelled = label(retrieve(question))  # labels stay fixed for the retry
    content = f"{format_context(labelled)}\nQuestion: {question}"
    messages = [{"role": "user", "content": content}]
    for attempt in range(1, MAX_ATTEMPTS + 1):
        try:
            reply = chat(SYSTEM, messages)
        except GiveUp as err:
            print(f"  try {attempt}: gave up: {err}")
            return None, labelled
        try:
            answer = CitedAnswer.model_validate_json(
                reply, context={"retrieved": set(labelled)}
            )
            return answer, labelled
        except ValidationError as err:
            problems = describe(err)
            print(f"  try {attempt}: {problems}")
            messages += [
                {"role": "assistant", "content": reply},
                {"role": "user", "content": f"Your reply was rejected: {problems}."
                 f" Valid IDs are {', '.join(labelled)}. Send the corrected JSON."},
            ]
    return None, labelled
  • The system prompt asks for one fact per claim and for IDs taken only from the passages, and it embeds the JSON Schema. Instructions reduce mistakes; the validator catches the rest.
  • The retry message quotes the errors and lists the valid IDs. The labels stay the same, so the earlier reply and the correction refer to the same passages.
  • GiveUp lets a model adapter stop early when asking again cannot help, as in the prompt basics lab; step 4 uses it.
  • After two failures ask() returns None and leaves the fallback to the caller.

The second part renders a valid answer with numbered sources and runs three questions:

Python · cited_answer.py · part 2
def render(answer: CitedAnswer, labelled: Labelled) -> str:
    """Number sources in order of first use, so [1] is the first one cited."""
    numbers: dict[str, int] = {}
    sentences = []
    for claim in answer.claims:
        marks = "".join(
            f"[{numbers.setdefault(pid, len(numbers) + 1)}]" for pid in claim.sources
        )
        sentences.append(f"{claim.text.rstrip('.')}.{marks}")
    sources = [
        f"  [{n}] {labelled[pid].title} ({labelled[pid].chunk_id})"
        for pid, n in numbers.items()
    ]
    return "\n".join([textwrap.fill(" ".join(sentences), 76), "Sources:", *sources])


if __name__ == "__main__":
    for question in [
        "Can I get a refund on an annual plan, and how do I ask for one?",
        "How long does a refund take to reach my card?",
        "Who checks my refund request?",
    ]:
        print(question)
        answer, labelled = ask(question)
        if answer is None:
            print("  -> no cited answer: show the sources found and offer support")
        else:
            print(render(answer, labelled))
Terminal
python cited_answer.py
Expected output
Can I get a refund on an annual plan, and how do I ask for one?
Annual plans can be refunded within 30 days of purchase.[1] Request it from
Settings > Billing > Invoices.[2]
Sources:
  [1] Refund eligibility (billing-refunds#1)
  [2] Requesting a refund (billing-refunds#2)
How long does a refund take to reach my card?
  try 1: answer: Value error, claim 1 cites ['P4'], not retrieved
Refunds take up to 10 business days.[1]
Sources:
  [1] Requesting a refund (billing-refunds#2)
Who checks my refund request?
  try 1: claims.0.sources: List should have at least 1 item after validation, not 0
  try 2: answer: Value error, claim 1 cites ['billing-team#4'], not retrieved
  -> no cited answer: show the sources found and offer support

render() numbers sources in order of first use and shows each chunk ID, so a reviewer can open the exact chunk.

In the third question the claim stayed the same while its citation changed from nothing to an invented chunk ID: the model was decorating a claim, not looking up a source. The fallback shows the sources found and a route to support, never the reply with the bad citation removed, because that claim has no evidence behind it. Log rejections and fallbacks and watch their rate: a rise usually means retrieval or the prompt changed.

05. Step 4: Switch on the provider's structured-output mode

With a real model, turn on structured outputs so every complete reply parses, as in the prompt basics lab; a refusal or a reply cut off at max_tokens is the exception, handled below. The schema enforces the shape, including at least one source per claim. The retrieved-ID rule lives only in your validator, so keep validating. The adapter plugs into ask() through its chat parameter:

Python · claude_chat.py (needs ANTHROPIC_API_KEY)
"""The same loop with Claude's structured outputs. Needs ANTHROPIC_API_KEY."""

import os

import anthropic

from cited_answer import GiveUp, ask, render
from schema import CitedAnswer

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
OUTPUT_FORMAT = {
    "type": "json_schema",
    "schema": anthropic.transform_schema(CitedAnswer),
}


def claude_chat(system: str, messages: list[dict[str, str]]) -> str:
    response = client.messages.create(
        model=os.environ["ANTHROPIC_MODEL"],  # for example claude-sonnet-5-5
        max_tokens=16000,
        system=system,
        messages=messages,
        output_config={"format": OUTPUT_FORMAT},
    )
    if response.stop_reason in ("refusal", "max_tokens"):
        raise GiveUp(f"stop_reason was {response.stop_reason}")
    return "".join(block.text for block in response.content if block.type == "text")


if __name__ == "__main__":
    answer, labelled = ask("How long does a refund take to reach my card?", claude_chat)
    print(render(answer, labelled) if answer else "no cited answer")
Terminal
ANTHROPIC_MODEL=claude-sonnet-5-5 python claude_chat.py
Output with a real model (illustrative)
Refunds reach the original payment method within 10 business days.[1]
Sources:
  [1] Requesting a refund (billing-refunds#2)

A refusal or a reply cut off at max_tokens raises GiveUp, which skips a pointless retry. Other providers and local runtimes have similar structured-output modes: the provider enforces the shape of a complete reply, and your validator checks the IDs.

06. Step 5: Compare with Claude's built-in citations

Some providers attach citations for you. In Claude's Messages API you send each chunk as a search_result block with your own source string and citations enabled. The reply comes back as several text blocks; each block that draws on your content carries search_result_location citations with your source and the cited_text. document blocks work the same way. According to the Claude docs (checked in November 2026):

  • citations must be enabled on all search results in a request or on none of them;
  • the API extracts cited_text itself, so every citation points at content you sent, and cited_text does not count towards output tokens;
  • citations cannot be combined with structured outputs: a request that enables both gets a 400 error.

Check the current pages before relying on these details. The guarantee matches your validator: each citation points at a real passage. Two checks remain yours: text with no citation at all, and whether the cited text supports the claim. The function below collects cited and uncited text; here it runs on a FAKE response in the documented shape.

Python · check_citations.py
"""Turn a cited Claude response into claims and check them against the hits."""

from anthropic.types import Message

from passages import Hit, retrieve

MIN_WORDS = 6  # shorter uncited pieces are joining text such as ". To ask, "


def check_citations(response: Message, hits: list[Hit]):
    retrieved = {hit.chunk_id for hit in hits}
    cited, uncited = [], []
    for block in response.content:
        if block.type != "text":
            continue
        sources = [c.source for c in block.citations or []
                   if c.type == "search_result_location"]
        unknown = set(sources) - retrieved
        if unknown:  # cannot happen if you sent the hits; catches mapping bugs
            raise ValueError(f"citation to {sorted(unknown)}, which was not sent")
        if sources:
            cited.append((block.text.strip(), sources))
        elif len(block.text.split()) >= MIN_WORDS:
            uncited.append(block.text.strip(" ."))
    return cited, uncited


def cite(hits: list[Hit], index: int) -> dict:
    hit = hits[index]
    return {"type": "search_result_location", "source": hit.chunk_id,
            "title": hit.title, "cited_text": hit.text, "search_result_index": index,
            "start_block_index": 0, "end_block_index": 1}


if __name__ == "__main__":
    hits = retrieve("Can I get a refund on an annual plan, and how do I ask?")
    # FAKE response in the documented shape, so this runs without an API key.
    fake = Message.model_validate({
        "id": "msg_fake", "type": "message", "role": "assistant",
        "model": "fake", "stop_reason": "end_turn", "stop_sequence": None,
        "usage": {"input_tokens": 0, "output_tokens": 0},
        "content": [
            {"type": "text", "text": "Yes. "},
            {"type": "text", "citations": [cite(hits, 0)],
             "text": "Annual plans can be refunded within 30 days of purchase"},
            {"type": "text", "text": ". To ask for one, "},
            {"type": "text", "citations": [cite(hits, 1)],
             "text": "open Settings > Billing > Invoices and select Request refund"},
            {"type": "text",
             "text": ". Requests are usually approved within one working day."},
        ],
    })
    cited, uncited = check_citations(fake, hits)
    for text, sources in cited:
        print(f"{', '.join(sources):<17} <- {text}")
    for text in uncited:
        print(f"{'no citation':<17} <- {text}")
Terminal
python check_citations.py
Expected output
billing-refunds#1 <- Annual plans can be refunded within 30 days of purchase
billing-refunds#2 <- open Settings > Billing > Invoices and select Request refund
no citation       <- Requests are usually approved within one working day

The last sentence is a fabrication. With built-in citations it cannot carry a bad ID; it shows up as a text block with no citation instead. Short uncited pieces are the joining text between cited spans, which is what MIN_WORDS filters out; tune it on your own logs. The real call:

Python · claude_citations.py (needs ANTHROPIC_API_KEY)
"""Claude's built-in citations on search_result blocks. Needs ANTHROPIC_API_KEY."""

import os

import anthropic

from check_citations import check_citations
from passages import retrieve

client = anthropic.Anthropic()
question = "Can I get a refund on an annual plan, and how do I ask for one?"
hits = retrieve(question)
results = [
    {
        "type": "search_result",
        "source": hit.chunk_id,  # comes back on every citation to this result
        "title": hit.title,
        "content": [{"type": "text", "text": hit.text}],
        "citations": {"enabled": True},  # all results on, or all off
    }
    for hit in hits
]
content = [*results, {"type": "text", "text": question}]
response = client.messages.create(  # no output_config: it cannot be combined
    model=os.environ["ANTHROPIC_MODEL"],
    max_tokens=16000,
    system="Answer only from the search results. Say so if they do not answer it.",
    messages=[{"role": "user", "content": content}],
)
if response.stop_reason != "end_turn":  # a refusal or a cut-off reply
    raise SystemExit(f"no complete answer: stop_reason={response.stop_reason}")
cited, uncited = check_citations(response, hits)
for text, sources in cited:
    print(f"{', '.join(sources):<17} <- {text}")
for text in uncited:
    print(f"{'no citation':<17} <- {text}")

Which to choose? Built-in citations quote your content at no extra output cost and suit chat interfaces. A search-result citation covers whole text blocks of content, so put one sentence or bullet per block if you want finer citations. Your own claim schema works with any provider, can carry other fields (the next lesson adds a status) and makes the claim unit explicit, which lesson 4 relies on.

07. Common mistakes

08. Check your understanding

Practice check · 3 questions

Citations you can check

Questions about labelling, validating and provider citations.

Q1. A retry runs retrieval again and labels the new hits P1 to P3 in a different order from the first attempt. What goes wrong?
Q2. You send search_result blocks with citations enabled, and also set output_config.format to get a JSON reply. What happens?
Q3. Validation still fails after the retry. What should the user see?
Practice only: not graded, not saved, not evidence.

09. Apply it

Add claim-level citations to your RAG tool:

  1. Label the retrieved passages per request and keep the map from label to chunk ID.
  2. Return claims with source IDs through your provider's structured-output mode, and validate them with the retrieved set passed as validation context.
  3. Retry once with the errors, then fall back to the retrieved sources.
  4. Run your 10 in-scope questions from lesson 1 and record, per question, the cited chunk IDs, whether a retry was needed and whether it fell back.

If you use Claude, also run the same questions through the search-result route and count how many sentences come back without a citation. Keep both result files for lesson 4.

10. Review prompt

Without looking back:

  1. Why label passages per request and keep the map to chunk IDs in code?
  2. Which two rules make up the citation contract, where does each one live, and why should the validator fail closed?
  3. What does the user see when validation fails twice, and why not the reply with its bad citations removed?
  4. What do Claude's built-in citations guarantee, which two checks remain yours, and which feature cannot be combined with them?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check