07.5 Citations and Attribution
An answer that says "the refund window is 30 days" is only half a product. The other half is letting the person who reads it check that claim against the source — and letting you check it when a user reports a wrong answer. This lesson covers the whole citation stack for RAG: why you cite, the four levels of attribution, prompt-based citations you build yourself, the citation features each provider ships as of November 2026 (Anthropic document and search-result citations, OpenAI file-search and web-search annotations, Gemini grounding metadata and File Search citations, OpenRouter's web plugin), how to verify citations cheaply and expensively, how to present them in a UI without breaking copyright or streaming, and how attribution extends beyond plain text to images, audio and code.
What you'll learn
- Why citations matter (trust, verification, legal defensibility, debugging) and the four levels of attribution: document, passage, quote and claim
- The difference between faithful citations produced during generation and post-hoc citations attached afterwards — and why post-hoc citations are decoration until verified
- Prompt-based citations end to end: numbered markers, quote-then-answer prompts, structured evidence fields, and mapping markers back to chunks, pages and URLs through the provenance metadata from lesson 05.8
- Every provider's citation feature as of November 2026: exact API shapes, citation granularity, what each returns, pricing effects, and incompatibilities (notably Anthropic citations vs structured outputs)
- How to verify citations: reference checks, quote containment, entailment and LLM-judge checks, citation precision and recall, and repair strategies
- How to present citations: inline markers, hover cards, source lists, deep links with page anchors and text fragments, and the streaming rules that keep markers honest
docs_qa/cite.py: the module's citation layer — Pydantic models, a pure-local verifier with real output, and a Markdown renderer
What you don't need
- API keys. Everything except the provider samples runs locally; the provider samples are labelled illustrative and show response shapes copied from official documentation.
- The retrieval pipeline itself — you have lesson 07.1 for that, and the
Retriever/Hitcontract from lesson 06.10. - A law degree. The copyright and licensing discussion is engineering guidance, not legal advice.
Setup
The citation layer needs Pydantic; the provider samples need the provider SDKs. If you haven't created the module project yet, run uv init rag --bare --python 3.13 && cd rag first (see lesson 03.1, Part 4), then:
uv add openai anthropic google-genai pydantic python-dotenv
# or: pip install openai anthropic google-genai pydantic python-dotenvThese commands install the newest release of each package. The samples were checked against openai 3.42.1, anthropic 2.4.0, google-genai 2.34.0 and pydantic 2.14.3 as of November 2026; a newer major version may change names or response shapes, so check the library's changelog if a call does not match. The .env file holds OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY and OPENROUTER_API_KEY as in earlier modules. docs_qa/cite.py (Part 4) needs only pydantic — no keys, no network.
What you must be able to do after this lesson#
- Explain what a citation is for
- Build prompt-based citations
- Use a provider's native citation feature
- Verify that a citation supports the claim
- Present citations clearly to users
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "The answer needs sources." | Part 1 |
| "Can we show which page that came from?" | 1.2 The levels of attribution |
| "Just ask the model to cite its sources." | Part 2 and 4.1 What 'verified' means |
| "Claude has a citations feature — should we use it?" | 3.2 Anthropic and 3.7 Choosing |
| "OpenAI's file search gives citations for free." | 3.3 OpenAI |
"Gemini returns grounding_metadata." |
3.4 Gemini |
| "The citations looked right but the answer was wrong." | 1.4 What a citation does not prove and Part 4 |
| "Our citations break when we stream." | 5.5 Citations in streaming responses |
| "How do we cite a table, an image, an audio timestamp?" | Part 6 |
| "What does citation precision/recall mean?" | 4.3 Citation precision and recall |
Part 1: What a citation is for#
1.1 Why cite at all#
Four audiences need citations, and they need different things:
| Audience | What they need | What breaks without it |
|---|---|---|
| The end user | Trust and a way to check | They can't tell a grounded answer from a fluent hallucination (02.10); adoption stalls |
| You, debugging | A trace from claim → chunk → parse | "The bot quoted the wrong refund window" becomes archaeology instead of a bug report — 05.8 Part 8 shows the lineage chain |
| Legal / compliance | Defensibility: what was said, based on what, when | You can't show the answer was supported by a document you were authorised to use |
| Product / eval | A measurable quality signal | You can't compute citation precision or catch unsupported claims systematically (07.9 owns the full eval suite) |
1.2 The levels of attribution#
"Cite your sources" hides four different jobs. Know which level you're building:
| Level | What it identifies | Example | Cost to produce | Who provides it |
|---|---|---|---|---|
| Document-level | Which file/document | "Employee Handbook, Returns Policy" | Trivial — you already have doc_id on every Hit |
You, from retrieval metadata |
| Passage-level | Which chunk/section/page within it | "§ Returns, p. 41" | Small — needs section_path, page_start from 05.8 |
You, from chunk metadata |
| Quote-level | The exact verbatim text span | "within 30 days of delivery" (chars 120–148) |
Medium — the model must copy text exactly, or the provider must return spans | Model quote, or provider citation APIs |
| Claim-level | Which sentence/claim each source supports | "the 30-day claim ← chunk A; the 18-week claim ← chunk B" | Highest — requires per-claim binding, ideally during generation | Structured output or provider citations |
The trap: document-level citations are cheap and nearly useless for verification. Telling a user "this came from the 40-page handbook" doesn't let them check the claim. Quote- and claim-level attribution is what makes an answer verifiable; passage-level is the practical sweet spot for UI (a page jump plus a highlighted snippet).
1.3 Faithful vs post-hoc citation#
There are two ways citations get attached, and they are not interchangeable:
- Faithful (inline) citation — the citation is produced during generation, bound to the claim as it's written. The model decides "this sentence is supported by chunk 2" while writing the sentence. Provider citation features and structured evidence fields do this.
- Post-hoc citation — the answer is generated first, then a second pass (another model call, or a heuristic) attaches sources afterwards. Cheaper to bolt on, and the source list can look perfectly plausible while being wrong: the second pass never saw which evidence the first pass actually used.
1.4 What a citation does not prove#
A citation is a pointer with a promise, not proof. Specifically, a citation does not establish:
- That the source is correct. The chunk may itself be stale, wrong, or superseded (07.2 covers freshness filters).
- That the claim follows from the quote. "Not returnable after 30 days" and "returnable within 30 days" share almost all their words. Only an entailment check (4.4) can catch this.
- That the model read the citation. Providers' citation features are model-generated too; they fail like any generation. Verify before trusting.
- That the user may see the source. Access control was applied at retrieval time (06.6); a citation must never leak the existence of a document the user can't access — see 07.11 for the security rules.
Part 2: Prompt-based citations (build it yourself)#
This is the portable approach: it works on every provider, every model, and every retrieval stack, because it's just prompt + parsing. Lesson 07.4 owns the grounding prompt itself; this part adds the citation contract on top.
2.1 The numbered-marker convention#
Context assembly labels the chunks it sends, and the label becomes the citation handle. This course uses two label styles: 07.1's ContextItem.label numbers chunks positionally — "[1]", "[2]", … in rank order — while 04.6 teaches stable document IDs (<document id="KB-118">, cited as [KB-118]). This lesson uses the positional [n] convention: marker n resolves to sources[n-1], the n-th chunk actually sent. The contract is then:
- The model writes the answer with
[n]markers inline, wherenis the number of the chunk supporting that claim. - Your code keeps the ordered
sourceslist it sent, so markernresolves tosources[n-1]→ aHit→ itsmetadata→ aSourceRef. - Verification (Part 4) checks that the marker exists, the chunk was really retrieved, and the evidence quote appears in it.
flowchart LR
Q[User question] --> R[Retriever.search]
R --> H["Hits: text + metadata<br/>(chunk_id, doc_id, page…)"]
H --> C["Context builder:<br/>number chunks [1]..[k]"]
C --> L["LLM call<br/>(grounding + citation prompt)"]
L --> A["Answer text<br/>with [n] markers"]
A --> P["cite.py: parse → verify → render"]
P --> U[UI: inline markers + source list]
P -.->|bad citation| V["repair: regenerate / drop / flag"]2.2 The citation prompt#
Two prompt shapes cover most needs. Both are in the prompt gallery in full.
Variant A — markers only (cheapest). The model cites by chunk number; you trust the binding implicitly and verify afterwards. Fewest output tokens, weakest guarantee: the model can mark a claim with a chunk that doesn't support it, and you only find out in verification.
Variant B — quote-then-answer. The model must quote the supporting text before or alongside the claim. The quote is checkable by string match (4.2); a fabricated quote fails loudly. Costs more output tokens and occasionally makes answers choppy.
Variant C — structured evidence (strongest, needs 03.4). The model returns {answer, citations: [{marker, quote, chunk_id}]} under schema constraints. Best parseability, but see 2.4 for the provider caveat — on Anthropic, structured output and citations can't be combined, so you either use markers-in-text or Anthropic's own citation blocks.
2.3 From marker to source: the join#
The join is where provenance metadata earns its keep. Each Hit from the Retriever carries metadata — the flattened ChunkMeta/DocumentMeta fields from 05.8: chunk_id, doc_id, title, section_path, page_start/page_end, source_uri, effective_date. Context assembly numbers the chunks it actually sends; the citation resolver maps n → Hit → SourceRef:
# cite.py's SourceRef mirrors those metadata fields. Build it once per
# request from the Hits that made it into context:
def source_ref_for(hit) -> SourceRef:
m = hit.metadata
return SourceRef(
chunk_id=m.get("chunk_id", hit.id),
doc_id=m.get("doc_id", ""),
title=m.get("title") or m.get("doc_title", "Untitled"),
section_path=m.get("section_path", []),
page_start=m.get("page_start"),
page_end=m.get("page_end"),
source_uri=m.get("source_uri", ""),
effective_date=m.get("effective_date"),
version=m.get("version"),
)If a chunk lacks page/section metadata, the citation degrades gracefully to document-level — still useful, just less checkable. That degradation is a data problem from Module 05, not a citation problem: fix it at ingestion (05.8), not by guessing at display time.
2.4 Structured evidence fields#
When you want machine-checkable citations rather than markers in prose, put the citation in the schema:
class WireCitation(BaseModel):
marker: int
quote: str # verbatim span expected inside the chunk
chunk_id: str
class CitedOutput(BaseModel):
answer: str # prose, markers optional
citations: list[WireCitation]This is 03.4's schema-constrained output applied to citations: the shape is guaranteed, the content still needs Part 4's checks. These are the wire models — what the model returns. Your code converts them into docs_qa/cite.py's verified CitedAnswer/ClaimCitation/ClaimEvidence/SourceRef models (defined in full at 4.2): claim spans are computed by code, not trusted from the model, and the names are deliberately distinct from 07.1's Answer/Citation and 07.4's Evidence/GroundedAnswer so the consolidated docs_qa package can't collide on import.
2.5 Failure modes of prompt-based citations#
| Failure | What it looks like | Fix |
|---|---|---|
| Invented marker | [7] when only 5 chunks were sent |
marker_in_range check (n_sources=len(sources)); regenerate once, then drop the claim |
| Wrong chunk | Real marker, real chunk, claim not supported | Entailment/quote verification (Part 4) |
| Citation dump | One marker at the end "covering" five claims | Prompt rule: one marker per claim; claim-coverage metric catches it |
| Marker drift in streaming | Marker rendered before its target text finished streaming | Buffer citations; render markers at block end (5.5) |
| Literal-marker collision | Source text contains [1]; parser can't tell model markers from document text |
Unusual marker glyph; escape brackets at ingestion |
| Renumbering bug | Context builder drops a chunk after numbering | Number last, after trimming/dedup; assert contiguity |
| Post-edit invalidation | You edit the answer text; claim_start/claim_end now point at wrong spans |
Recompute spans after any text mutation, or store quotes not offsets |
Part 3: Provider-native citation features#
Every major provider now ships some citation mechanism. They differ in a way that matters: what triggers the citation (a document you send vs the provider's own retrieval tool vs the open web), what granularity comes back (file, page, character range, block range, URL span), and what it costs. The document-block citation API surface — how to send a PDF with citations.enabled and read page_location/char_location back — was covered in 03.6, 4.9; this part covers what changes when you use those features for RAG, plus the retrieval-tool citations that only exist inside provider-managed search.
3.1 The three mechanisms#
| Mechanism | Who retrieves | What gets cited | Providers (Nov 2026) |
|---|---|---|---|
| Document citations | You send the documents; the model cites spans inside them | Your own corpus, at sentence/block/page granularity | Anthropic (document blocks, search_result blocks); OpenAI/Gemini/OpenRouter only through their file-attachment citations (partial — see below) |
| Retrieval-tool citations | The provider's own store/tool retrieves; the model cites what it got | The provider-hosted corpus | OpenAI file_search, Gemini File Search, Anthropic via search_result blocks you fill from your retriever |
| Web citations | The provider searches the live web | Public URLs | All four (OpenAI web_search, Anthropic web_search tool, Gemini google_search, OpenRouter openrouter:web_search server tool) |
The key architectural fact: of the four providers' documented citation surfaces, only Anthropic's lets you attach citations to documents you retrieved and formatted yourself — via search_result blocks. OpenAI and Gemini's file citations ride on their retrieval tools, which means their citation granularity is whatever their chunker produces, and the retrieved text is theirs to see, not yours (07.7 covers that trade-off).
3.2 Anthropic: document citations and search-result blocks#
Anthropic has the richest citation surface for self-managed RAG. Two ways in:
A. Document blocks with citations.enabled. Send each source as a document block. Three source types, three citation location types:
| Source type | Location type | Indices |
|---|---|---|
| Plain text | char_location |
start_char_index/end_char_index, 0-based, end exclusive |
| PDF (text-extractable) | page_location |
start_page_number/end_page_number, 1-based, end exclusive |
| Custom content (your chunks as content blocks) | content_block_location |
start_block_index/end_block_index into your content array, 0-based, end exclusive |
Plain text and PDFs are auto-chunked into sentences; custom content documents do no further chunking — your blocks are the citable units. For RAG, that means one custom-content document per retrieved chunk gives you exact chunk-level citations for free. Scanned PDFs without extractable text are not citable (no image citations yet). Every citation carries cited_text — the exact quoted span — which "does not count toward output tokens", and isn't billed as input when replayed in later turns. document_index is 0-based across all document blocks in the request (every message); document_title (and source/title on search_result citations) carries your metadata into the citation, while context is a hint to the model and is not echoed back.
B. search_result blocks — built for RAG. Instead of document blocks, pass each retrieved result as:
{
"type": "search_result",
"source": "kb://handbook/returns-policy", # any stable string: URL or internal ID
"title": "Returns Policy — Employee Handbook",
"content": [{"type": "text", "text": chunk_text}],
"citations": {"enabled": True},
}Citations come back as search_result_location objects carrying source, title, cited_text, search_result_index, start_block_index/end_block_index — i.e. the citation resolves to your source string and your content blocks, which map straight onto chunk_id and Hit metadata. source accepts "any stable string… a URL, or an internal identifier such as kb://article-1234" — use your canonical document ID here and the deep-link problem from 05.8, 8.2 mostly disappears.
The rules that will bite you:
- All-or-nothing. Every
document/search_resultblock in a request must agree oncitations.enabled, or the API errors. - No structured outputs.
citations.enabled+output_config.format(or the deprecatedoutput_format) → 400. For JSON-shaped answers with citations, Anthropic's documented workaround is line-oriented output ("field: value" lines where each value's text block carries its own citations) — see their citations guide. - Compatible with prompt caching, token counting and batch processing.
- Streaming: citations arrive as
citations_deltaevents insidecontent_block_delta, one citation per delta, attached to the currenttextblock (03.3, 6.4). - Web search tool:
web_searchserver tool returnsweb_search_resultitems (url,title,encrypted_content,page_age) and citations of typeweb_search_result_location(url,title,encrypted_index,cited_text— capped at ~150 characters, so web citations are snippet-level, not full-quote level). Priced at $10 per 1,000 searches plus token costs for retrieved content; each search counts as one use regardless of result count, and errored searches aren't billed. Citations are always on for web search. - Models: all active Claude models support citations (the docs' supported-models list as of 11 November 2026 runs from
claude-sonnet-4-5andclaude-haiku-4-5throughclaude-fable-5-2andclaude-mythos-5-2).
# s3_2_anthropic_search_results.py — a search_result block per retrieved chunk.
# Requires: anthropic, keys in .env. Output illustrative.
import os
from dotenv import load_dotenv
import anthropic
load_dotenv()
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
# `retrieved_hits` is what your Retriever returned this turn (docs_qa/
# retrieval.py); keep the SAME order — search_result_index in citations
# indexes into this list.
retrieved_hits = [] # replace with: retriever.search(question, k=5)
def as_search_result(hit):
m = hit.metadata
return {
"type": "search_result",
"source": m.get("source_uri") or f"kb://{m.get('doc_id')}",
"title": m.get("title", "Untitled"),
"content": [{"type": "text", "text": hit.text}],
"citations": {"enabled": True},
}
response = client.messages.create(
model="claude-haiku-5-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
*[as_search_result(h) for h in retrieved_hits], # your Hits
{"type": "text",
"text": "What is the parental leave entitlement? Answer with citations."},
],
}],
)
# Response: text blocks; cited spans carry `citations` lists.
for block in response.content:
if block.type == "text":
print(block.text)
for c in getattr(block, "citations", None) or []:
# c.type == "search_result_location"
print(f" cited: {c.cited_text!r} -> {c.source} "
f"blocks {c.start_block_index}:{c.end_block_index}")Primary carers receive 18 weeks of fully paid leave [citations on the
following spans].
cited: '18 weeks of fully paid leave' -> https://handbook.acme.internal/policies/leave blocks 0:1C. The same blocks, returned by a tool (agentic RAG). search_result blocks do not have to sit in the user turn. Anthropic's search-results page documents two delivery routes — "from tool calls" (your custom tool returns them, so the model decides when and what to search) and "as top-level content" (the pre-fetched pattern above) — and says Claude cites the results automatically when citations are enabled, with no special prompting. The tool route is how you combine this lesson with the tool loop of Module 08A: the model asks for a search, your retriever runs, and the tool_result carries the blocks. The same rules apply (the same citations.enabled setting on every block in the request, text-only content, no structured outputs). Checked against the official page in November 2026; the sketch below mirrors its shape:
# s3_2c_anthropic_tool_search_results.py — search_result blocks inside a tool_result.
# Requires: anthropic, keys in .env. ILLUSTRATIVE: not run here.
from dotenv import load_dotenv
import anthropic
load_dotenv()
client = anthropic.Anthropic()
SEARCH_TOOL = {
"name": "search_knowledge_base",
"description": "Search the company knowledge base and return matching passages.",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string", "description": "The search query"}},
"required": ["query"],
},
}
def search_knowledge_base(query: str) -> list[dict]:
"""Run YOUR retriever and return search_result blocks (see as_search_result above)."""
hits = [] # replace with: retriever.search(query, k=5)
return [{
"type": "search_result",
"source": h.metadata.get("source_uri") or f"kb://{h.metadata.get('doc_id')}",
"title": h.metadata.get("title", "Untitled"),
"content": [{"type": "text", "text": h.text}],
"citations": {"enabled": True},
} for h in hits]
messages = [{"role": "user", "content": "What is the parental leave entitlement?"}]
first = client.messages.create(model="claude-haiku-5-5", max_tokens=1024,
tools=[SEARCH_TOOL], messages=messages)
tool_use = next((b for b in first.content if b.type == "tool_use"), None)
if tool_use is not None:
messages += [
{"role": "assistant", "content": first.content},
{"role": "user", "content": [{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": search_knowledge_base(tool_use.input["query"]),
}]},
]
final = client.messages.create(model="claude-haiku-5-5", max_tokens=1024,
tools=[SEARCH_TOOL], messages=messages)
for block in final.content:
if block.type == "text":
print(block.text)
for c in getattr(block, "citations", None) or []:
print(f" cited: {c.cited_text!r} -> {c.source}")Two design points. First, the retrieval query is now written by the model, so the query-understanding work of 07.3 moves into the tool description and the tool's own logic; keep k modest inside the tool because every round trip is a full-price request. Second, citations come back in the final answer's text blocks exactly as in route B, so evidence_from_anthropic in cite.py (4.2) handles both routes unchanged.
3.3 OpenAI: file-search and web-search annotations#
OpenAI's citations live on annotations attached to output_text content, and they come in two flavours:
file_citation — from the file_search tool (Responses API). Shape:
{"type": "file_citation", "index": 992, "file_id": "file-…", "filename": "handbook.pdf"}Read that carefully: index is the position in the output text where the citation attaches (a character offset in practice — verify on non-ASCII answers); file_id+filename identify the file, not the chunk, page or passage. OpenAI's file search does not return page numbers or quoted spans in the annotation. To recover what was cited you must ask for it: include: ["file_search_call.results"] populates the file_search_call output item's results array, each row carrying file_id, filename, text (the retrieved chunk text), score (0–1) and attributes (your vector-store metadata — put chunk_id/page there at ingestion and the join works). The tool itself takes vector_store_ids, max_num_results, ranking_options (ranker — "auto" or "default-2024-11-15" on the Responses API reference as of 11 November 2026; the retrieval guide's prose example names an older dated ranker, "default-2024-08-21", that the typed lists no longer show — plus score_threshold 0–1 and hybrid_search weights) and filters — 07.7 covers the store side.
url_citation — from the web_search tool:
{"type": "url_citation", "start_index": 2606, "end_index": 2758,
"url": "https://…", "title": "…"}start_index/end_index delimit the cited span in the answer text — true span-level web citation. web_search_call output items carry the action (search with queries, or open_page/find_in_page on reasoning models). The annotation union also includes container_file_citation and file_path types for container-file/agentic file workflows — out of scope here; evidence_from_openai (4.2) returns None for anything but file_citation.
Pricing (as of November 2026, pricing page): file search $2.50 per 1,000 tool calls plus storage $0.10/GB/day (1 GB free); web search $10 per 1,000 calls plus search-content tokens billed at model rates. File-search tool-call pricing applies to the Responses API only.
# s3_3_openai_annotations.py — file_search + reading annotations back.
# Requires: openai. Output illustrative.
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.responses.create(
model="gpt-6-luna",
tools=[{"type": "file_search",
"vector_store_ids": ["<vector_store_id>"],
"max_num_results": 5}],
include=["file_search_call.results"], # the retrieved chunks, for your join
input="What is the parental leave entitlement?",
)
for item in response.output:
if item.type == "file_search_call":
for r in item.results or []:
# r.attributes carries whatever metadata you stored per file/chunk
print("retrieved:", r.filename, r.score, r.attributes)
if item.type == "message":
for part in item.content:
if part.type == "output_text":
text = part.text
for ann in part.annotations or []:
if ann.type == "file_citation":
# file-level citation: resolve via results by file_id
print(f"cite @{ann.index}: {ann.filename} ({ann.file_id})")
elif ann.type == "url_citation":
span = text[ann.start_index:ann.end_index]
print(f"cite @{ann.start_index}-{ann.end_index}: {ann.url} <- {span!r}")3.4 Gemini: grounding metadata and File Search citations#
Gemini has two different citation surfaces, one per API:
generate_content (primary per module convention). With the file_search tool (types.Tool(file_search=types.FileSearch(file_search_store_names=[...], metadata_filter=...)) — the two fields Google's File Search page shows as of November 2026; check the SDK's types.FileSearch reference for any result-count option rather than assuming one), citations arrive in response.candidates[0].grounding_metadata:
grounding_chunks[]— one per retrieved chunk;retrieved_contextcarriestitle,text(the chunk text itself),file_search_store,page_number(a single int, for paged docs like PDFs),media_id(for image-derived chunks), and yourcustom_metadata(a list ofkeyplusstring_valueornumeric_valueentries).grounding_supports[]— binds answer spans to chunks:segment(start_index/end_index/textof the answer),grounding_chunk_indices(which chunks support it),confidence_scores(0–1),rendered_parts. ⚠️ The segment indices are UTF-8 byte offsets into a single content part —segment.part_indexsays which part, measured from the start of that part, not fromresponse.text. Slicingtext[start:end]as characters is wrong for non-ASCII answers and for multi-part responses.
That's claim-level grounding with the retrieved text included — the strongest self-serve citation payload of the four providers. Google Search grounding on the same API returns grounding_metadata with web_search_queries, grounding_chunks[].web (uri, title) and grounding_supports in the same shape.
Interactions API. The newer API returns typed annotations on text content blocks instead: file_citation objects with file_name, document_uri, source, page_number, media_id, custom_metadata, and start_index/end_index — documented as byte offsets into the response text (measure carefully: bytes ≠ characters for non-ASCII). Web grounding returns url_citation annotations (url, title, start_index, end_index) plus google_search_call/google_search_result steps; a place_citation type exists for Google Maps results.
Pricing (as of November 2026): File Search charges embeddings at indexing time, storage is free, query-time embeddings are free, and retrieved document tokens bill as ordinary context tokens. Grounding with Google Search on Gemini 3+ models bills per executed search query — $14 per 1,000 requests after 5,000 free per month shared across Gemini 3+ models, with a default 1,500 requests/day cap on the paid tier.
# s3_4_gemini_grounding.py — File Search + reading grounding_metadata.
# Requires: google-genai. Output illustrative.
import os
from dotenv import load_dotenv
from google import genai
from google.genai import types
load_dotenv()
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
response = client.models.generate_content(
model="gemini-3.8-flash",
contents="What is the parental leave entitlement?",
config=types.GenerateContentConfig(
tools=[types.Tool(file_search=types.FileSearch(
file_search_store_names=["fileSearchStores/your-store"]))],
),
)
cands = response.candidates or []
gm = cands[0].grounding_metadata if cands else None
parts = (cands[0].content.parts if cands and cands[0].content else []) or []
if gm and gm.grounding_supports:
for support in gm.grounding_supports:
seg = support.segment
# segment indices are UTF-8 BYTE offsets into ONE content part
# (seg.part_index; 0 for the usual single-part answer) — decode
# the byte slice, don't slice the str as characters
pi = getattr(seg, "part_index", 0) or 0
ptext = (getattr(parts[pi], "text", "") if pi < len(parts)
else "") or (response.text or "")
span = ptext.encode("utf-8")[seg.start_index:seg.end_index].decode("utf-8", "replace")
for idx in support.grounding_chunk_indices:
rc = getattr(gm.grounding_chunks[idx], "retrieved_context", None)
if rc is None:
continue
print(f"claim bytes {seg.start_index}:{seg.end_index} <- "
f"{rc.title} page={getattr(rc, 'page_number', None)} "
f"conf={support.confidence_scores}")
print(f" span: {span!r}")3.5 OpenRouter and everyone else#
OpenRouter has no RAG store of its own — file search / vector stores are a provider-side feature it doesn't broker (07.7 covers the build-vs-buy detail). What it does standardise is web citations: the openrouter:web_search server tool (the older web plugin and the :online model suffix are deprecated in its favour, as of November 2026; see 07.7, 2.5) returns Chat-Completions-style annotations on the assistant message:
{"type": "url_citation",
"url_citation": {"url": "…", "title": "…", "content": "…excerpts…",
"start_index": 100, "end_index": 200}}content carries Exa highlights (extractive excerpts) when the Exa engine is used. Engine choice matters for cost and behaviour: auto (the default: the provider's native search when it has one, otherwise Exa), native (the provider's own search, for example Anthropic, Google, OpenAI and SpaceXAI models), exa, firecrawl, parallel, perplexity — per-engine pricing is on the web search server-tool page. Domain filters (allowed_domains/excluded_domains) behave differently per engine (Google's native search supports neither; OpenAI's honours only allowed_domains), so check the compatibility notes before relying on them. For file citations, OpenRouter passes through whatever the routed provider emits; on parsed PDFs it "may include a file_citation annotation" but "parsing a file alone does not guarantee a citation" (03.6, 4.9).
3.6 The comparison table#
| Anthropic | OpenAI | Gemini | OpenRouter | |
|---|---|---|---|---|
| Your own retrieved docs | ✅ document + search_result blocks |
❌ (file search cites its store only) | ❌ (File Search cites its store only) | ⚠️ parsed-file file_citation, partial |
| Citation granularity (own docs) | sentence / block / page / char | file only (+results text you join yourself) |
chunk (+page_number, media_id, custom metadata) |
file only |
| Quoted text returned | cited_text always |
no (recover via file_search_call.results) |
chunk text + segment indices |
content excerpts (web only) |
| Span binding | per text block | char index / start_index–end_index |
grounding_supports segments / byte offsets |
start_index–end_index |
| Structured output | ❌ 400 with citations | ✅ (annotations orthogonal) | ⚠️ reported gaps with response_json_schema |
depends on endpoint |
| Streaming | citations_delta |
annotation.added events |
grounding at candidate level / annotation deltas (Interactions) | chunk annotations |
| Cost | citations ≈ free (cited_text unbilled); web search $10/1k |
file search $2.50/1k calls + storage; web $10/1k | File Search: storage+query embeddings free; Google grounding $14/1k queries (3+) | per-engine web pricing; native = provider passthrough |
| Caching | compatible | annotations survive; check store/include |
compatible | per endpoint |
3.7 Choosing a citation strategy#
| Your situation | Best fit |
|---|---|
| Own vector store (Modules 05–06 pipeline), need page/section precision, multi-provider portability | Prompt markers + cite.py verification — works everywhere, verifiable |
| Claude-only product, want provider-verified span citations with zero parsing code | search_result blocks — source = your canonical ID, cited_text free |
| OpenAI shop already paying for file search | file_citation annotations + file_search_call.results — join via attributes.chunk_id |
| Gemini shop with a File Search store | grounding_metadata — richest payload (text + pages + confidence) |
| Answers must cite the live web | Provider web-search tools / OpenRouter's openrouter:web_search server tool — but verify: web citations decay and pages change |
| Regulated/high-assurance: citations must be proven, not trusted | Provider citations plus your own verifier — native citations reduce fabrication but don't eliminate it |
| Structured JSON answers required | Markers-in-text or line-oriented citations; Anthropic native citations are off the table (400) |
The honest summary: provider citations buy you binding fidelity; they don't buy you truth. They reduce invented-marker and wrong-span failures, but the claim-to-evidence relation still needs verification for anything high-stakes. Budget for Part 4 regardless of which row you pick.
Part 4: Verifying citations#
4.1 What "verified" means#
Verification is a ladder of checks, cheapest first. Stop at the rung your risk level demands:
| Rung | Check | Catches | Cost |
|---|---|---|---|
| 1. Reference validity | Marker number is within the sent source range (marker_in_range); chunk_id was actually retrieved this turn; claim span is in bounds |
Invented markers, citations to chunks never retrieved | Free (pure Python) |
| 2. Quote containment | The cited quote appears (normalised) in the chunk text | Fabricated or paraphrased "quotes" | Free |
| 3. Entailment | The quoted passage actually supports the claim — "30 days for a refund" ≠ "not returnable after 30 days" | Plausible-but-wrong attribution, the hardest failure | An NLI model or an LLM judge per citation |
| 4. Answer faithfulness | Every claim in the answer is covered by some citation | Uncited claims hiding between cited ones | Judge over the whole answer — 07.9 owns this metric family |
Rungs 1–2 are deterministic and belong in docs_qa/cite.py below. Rungs 3–4 need a model; run them on a small model (02.9 for the cheap/fast defaults) and sample them in production — verifying every citation of every answer doubles your LLM bill.
4.2 cite.py: models and the pure-local verifier#
docs_qa/cite.py is the module's citation layer. Four Pydantic models carry the data — SourceRef (where a citation points, mirroring the ChunkMeta/DocumentMeta fields from 05.8), ClaimEvidence (the quoted span), ClaimCitation (marker + claim span + evidence) and CitedAnswer (text + citations) — plus functions to parse [n] markers, verify, score, render, bridge 07.4's [passage-id] output, and adapt provider citations. (The names are deliberately not Answer/Citation/Evidence: 07.1's types.py and 07.4's generate.py already own those names with different fields — when 07.11 consolidates the package, identical names would collide on import.) It imports only pydantic and the standard library; the demo below is real output.
# docs_qa/cite.py — the citation layer. Full file at the end of this lesson.
# Key excerpts:
def norm(s: str) -> str:
"""Fold differences that don't change meaning: unicode form, curly
quotes/dashes, whitespace runs, case."""
s = unicodedata.normalize("NFKC", s)
s = s.translate(_QUOTES)
return _WS.sub(" ", s).strip().lower()
# Canonical positional markers only — [007] stays literal text rather
# than silently merging with [7] (it then fails marker_in_text).
_MARKER = re.compile(r"\[(0|[1-9]\d{0,2})\]")
def verify_citations(answer: CitedAnswer, chunks: dict[str, str],
known_chunk_ids: set[str] | None = None,
n_sources: int | None = None) -> list[Check]:
"""Rungs 1-2: marker_in_text, marker_in_range, claim_span_valid,
marker_inside_claim, evidence_chunk_known, quote_found — one Check
per citation per rule. n_sources = chunks actually sent to the model."""The verifier's core check — quote containment — is deliberately dumb:
found = norm(ev.quote) in norm(chunks[ev.chunk_id])Normalise before comparing because models reflow whitespace and straighten quotes constantly; a raw in check fails on "line1\nline2" vs "line1 line2". What it cannot catch is a real quote that doesn't support the claim — that's rung 3.
Demo — real output (fixture corpus: returns policy, parental leave, VPN error codes; ran locally, pydantic only). The script is demo.py, shown in full below:
=== marker positions ===
[(74, 77, 1), (136, 139, 2), (205, 208, 3)]
=== verification ===
[ok] [1] marker_in_text: marker present
[ok] [1] marker_in_range: marker 1 within 1..3 sent sources
[ok] [1] claim_span_valid: [0:77] of 209 chars
[ok] [1] marker_inside_claim: marker inside claim span
[ok] [1] evidence_chunk_known: chunk chk_ret_01… in context
[ok] [1] quote_found: quote located in chunk
… (same six checks pass for markers 2 and 3)
citation precision: 1.00
claim coverage: 1.00
=== failure case ===
[ok] [9] marker_in_text: marker present
[FAIL] [9] marker_in_range: marker 9 outside 1..3 sent sources
[ok] [9] claim_span_valid: [210:246] of 246 chars
[ok] [9] marker_inside_claim: marker inside claim span
[ok] [9] evidence_chunk_known: chunk chk_ret_01… in context
[ok] [9] quote_found: quote located in chunk
citation precision: 0.75The failure case appended "Returns are allowed for 60 days [9]" — an invented marker carrying a real quote ("return unused items within 30 days of delivery", which exists in chk_ret_01). Rung 1's marker_in_range caught it even though the quote verified: [9] was never one of the three sources sent. Note what none of this needed: an LLM, a network call, or a provider.
demo.py — save it in your project root next to docs_qa/ and run python demo.py (it needs only pydantic, no keys):
# demo.py — run cite.py end to end on a fixture. Pure local, real output.
import sys
sys.path.insert(0, "docs_qa")
from cite import (CitedAnswer, ClaimCitation, ClaimEvidence, SourceRef,
cited_answer_from_grounded, citation_precision,
claim_coverage, marker_positions, norm, render_markdown,
verify_citations)
# --- the corpus this turn retrieved (chunk_id -> text) -------------------
CHUNKS = {
"chk_ret_01": ("Returns policy: employees may return unused items within "
"30 days of delivery for a full refund to the original "
"payment method. After 30 days, store credit is issued "
"instead. Damaged items are not returnable."),
"chk_par_02": ("Parental leave: primary carers receive 18 weeks of fully "
"paid leave, usable within the first year after birth or "
"placement. Secondary carers receive 4 weeks."),
"chk_vpn_03": ("VPN error codes: ERR_VPN_104 means the tunnel timed out "
"during handshake; restart the client and retry. "
"ERR_VPN_201 indicates certificate expiry."),
}
SOURCES = {
"chk_ret_01": SourceRef(
chunk_id="chk_ret_01", doc_id="doc_ret", title="Employee Handbook",
section_path=["Policies", "Returns"], page_start=41, page_end=41,
source_uri="https://handbook.acme.internal/policies/returns",
snippet="Employees may return unused items within 30 days…"),
"chk_par_02": SourceRef(
chunk_id="chk_par_02", doc_id="doc_par", title="Leave Policy",
section_path=["Leave", "Parental"], page_start=7, page_end=8,
source_uri="https://handbook.acme.internal/policies/leave",
snippet="Primary carers receive 18 weeks of fully paid leave…"),
"chk_vpn_03": SourceRef(
chunk_id="chk_vpn_03", doc_id="doc_vpn", title="IT Help Centre",
section_path=["VPN", "Error codes"],
source_uri="https://help.acme.internal/vpn/errors",
snippet="ERR_VPN_104 means the tunnel timed out…"),
}
# --- an answer as the model might produce it ------------------------------
TEXT = ("Unused items can be returned within 30 days of delivery for a "
"full refund [1]. Primary carers get 18 weeks of fully paid "
"parental leave [2]. If the VPN drops with ERR_VPN_104, restart "
"the client and retry [3].")
def span_of(text, start_phrase, end_phrase):
"""char offsets covering start_phrase..end_phrase inclusive of marker."""
s = text.index(start_phrase)
e = text.index(end_phrase, s) + len(end_phrase)
return s, e
answer = CitedAnswer(text=TEXT, citations=[
ClaimCitation(marker=1, claim_start=0,
claim_end=span_of(TEXT, "Unused items", "[1]")[1],
evidence=[ClaimEvidence(
quote="return unused items within 30 days of delivery",
chunk_id="chk_ret_01")]),
ClaimCitation(marker=2,
claim_start=span_of(TEXT, "Primary carers", "[2]")[0],
claim_end=span_of(TEXT, "Primary carers", "[2]")[1],
evidence=[ClaimEvidence(
quote="18 weeks of fully paid leave",
chunk_id="chk_par_02")]),
ClaimCitation(marker=3,
claim_start=span_of(TEXT, "If the VPN", "[3]")[0],
claim_end=span_of(TEXT, "If the VPN", "[3]")[1],
evidence=[ClaimEvidence(
quote="ERR_VPN_104 means the tunnel timed out during handshake",
chunk_id="chk_vpn_03")]),
])
print("=== marker positions ===")
print(marker_positions(TEXT))
print()
print("=== verification ===")
# n_sources = the 3 chunks actually sent to the model, in [1]..[3] order
checks = verify_citations(answer, CHUNKS, known_chunk_ids=set(CHUNKS),
n_sources=len(CHUNKS))
for c in checks:
print(f" [{'ok' if c.ok else 'FAIL'}] [{c.citation}] {c.name}: {c.detail}")
print(f"citation precision: {citation_precision(checks):.2f}")
print(f"claim coverage: {claim_coverage(answer):.2f}")
print()
print("=== rendered ===")
print(render_markdown(answer, SOURCES))
print()
# --- the failure case: an invented marker carrying a REAL quote ------------
# [9] was never sent (only 3 sources), but its quote genuinely exists in
# chk_ret_01 — so quote_found passes and marker_in_range is what catches it.
print("=== failure case ===")
bad = CitedAnswer(text=TEXT + " Returns are allowed for 60 days [9].",
citations=answer.citations + [
ClaimCitation(
marker=9, claim_start=len(TEXT) + 1,
claim_end=len(TEXT) + len(
" Returns are allowed for 60 days [9]."),
evidence=[ClaimEvidence(
quote="return unused items within 30 days of delivery",
chunk_id="chk_ret_01")]),
])
checks2 = verify_citations(bad, CHUNKS, known_chunk_ids=set(CHUNKS),
n_sources=len(CHUNKS))
for c in checks2:
if c.citation == 9 or not c.ok:
print(f" [{'ok' if c.ok else 'FAIL'}] [{c.citation}] {c.name}: {c.detail}")
print(f"citation precision: {citation_precision(checks2):.2f}")
print()
# --- the bridge: 07.4's generate.py emits [passage-id] markers -------------
print("=== bridge from 07.4 generate.py output ===")
class FakeEvidence:
def __init__(self, passage_id, quote):
self.passage_id = passage_id
self.quote = quote
class FakeGrounded:
answer = ("Primary carers get 16 weeks of leave [handbook-005], "
"usable in the first year [handbook-005].")
evidence = [FakeEvidence("handbook-005",
"16 weeks for the primary caregiver")]
bridged = cited_answer_from_grounded(FakeGrounded,
["handbook-005", "handbook-001"])
print("rewritten text:", bridged.text)
for cit in bridged.citations:
print(f" marker={cit.marker} span=[{cit.claim_start}:{cit.claim_end}] "
f"evidence={[(e.quote[:30], e.chunk_id) for e in cit.evidence]}")
checks3 = verify_citations(
bridged,
{"handbook-005": "Parental leave: 16 weeks for the primary caregiver "
"and 6 weeks for the secondary caregiver, usable "
"within the first year."},
n_sources=2)
for c in checks3:
if not c.ok:
print(f" [{'ok' if c.ok else 'FAIL'}] [{c.citation}] {c.name}: {c.detail}")
print(f"citation precision: {citation_precision(checks3):.2f}")Its last section shows the bridge in action — real output:
=== bridge from 07.4 generate.py output ===
rewritten text: Primary carers get 16 weeks of leave [1], usable in the first year [1].
marker=1 span=[0:71] evidence=[('16 weeks for the primary careg', 'handbook-005')]
citation precision: 1.00[handbook-005] became [1] — its position in the passage list you sent — the two occurrences in one sentence collapsed to a single ClaimCitation, and the structured evidence bound to it by passage position. cited_answer_from_grounded is what lets you keep 07.4's stable-id prompting and this lesson's verifiable positional contract; unknown ids are renumbered past n_sources so marker_in_range fails them loudly.
The provider adapters at the bottom of cite.py (evidence_from_anthropic, evidence_from_openai, evidence_from_hit) normalise native citations into the same ClaimEvidence shape, so the verifier is provider-agnostic — with one honest caveat each: Anthropic's search_result_location citations carry no document_index (the chunk identity lives in source, which your chunk_id_for callback maps), OpenAI's file_citation carries no quote or chunk (you join file_id → attributes.chunk_id via file_search_call.results and supply the quote yourself), and evidence_from_hit returns an empty quote on purpose so quote_found fails closed rather than passing vacuously — which is exactly why include: ["file_search_call.results"] matters.
4.3 Citation precision and recall#
Following the ALCE benchmark's framing (Gao et al. 2023): a citation is correct only if the cited passage supports the statement it is attached to.
- Citation precision = verified citations ÷ all citations.
cite.py'scitation_precision()computes it over rungs 1–2, grouped perClaimCitationobject — so two claims that legitimately share marker[1]score independently rather than merging into one check; swap in the entailment judge for the strict version. - Citation recall (a.k.a. citation coverage) = claims carrying a supporting citation ÷ all claims.
claim_coverage()approximates it by sentence: split the answer on sentence boundaries, count sentences containing a marker. It's crude — a claim split across two sentences needs both halves cited, and a sentence can hold two claims — but it's the free version. The judge-based version is a 07.9 metric.
Measure both on your eval set (06.10's harness pattern, one level up). A system with precision 0.9 and recall 0.4 is very different from 0.6/0.9: the first cites carefully but misses claims; the second sprinkles markers everywhere. Which is worse depends on your users — for compliance, low recall is the dangerous one.
4.4 The expensive checks: entailment and LLM-judge#
Quote containment proves the words exist; entailment proves they mean the claim. Two options:
NLI model. A natural-language-inference model scores (premise=quote, hypothesis=claim) → entailment/neutral/contradiction. Cheap per call, runs locally, but NLI models are tuned on short sentence pairs and get flaky on long, numeric or tabular claims. Good enough for a first pass; measure its agreement with human labels before trusting it (the Cohen's-kappa pattern from 06.10, 2.6 applies directly).
LLM judge. One small-model call per citation (or batched per answer):
You are checking whether a source passage supports a claim.
CLAIM: {claim_text}
QUOTE: {evidence.quote}
SOURCE CHUNK: {chunk_text[:2000]}
Answer with JSON only:
{"verdict": "supported" | "unsupported" | "contradicted",
"reason": "<one sentence>"}
Rules:
- "supported" requires the QUOTE (not just the chunk) to state or directly
imply the CLAIM. Numbers must match exactly.
- If the claim adds information not in the quote, answer "unsupported".
- If the quote states the opposite, answer "contradicted".Cost control: judge only citations that passed rungs 1–2 and were shown to a user or fed into an eval; sample 5–10% in production logs. Use a different model family than the answerer where possible — a model grading its own citations is a mild conflict of interest (same caveat as LLM-judge design in 07.9 and Module 10A).
4.5 Repair strategies#
When verification fails, you have four moves, in increasing order of user-visible damage:
| Strategy | When | What the user sees |
|---|---|---|
| Regenerate | Transient slips (invented marker, missing quote) | Normal answer, one extra LLM call — feed the failed checks back as errors, the 03.4 validate-and-retry pattern |
| Drop the claim | One claim unsupported, rest fine | Answer minus that sentence, or "…and other details I can't verify" — prefer surgical removal over a wrong citation |
| Flag | Can't tell if wrong, or policy requires honesty | Answer + visible "unverified" marker on that claim |
| Abstain that part | The unsupported claim was the point | "I can't confirm X from the available documents" — the abstention machinery from 07.4 |
Never silently keep a failed citation. A citation that fails verification and stays on screen is worse than no citation: it converts a hallucination into an apparently authoritative hallucination.
Part 5: Presenting citations#
5.1 UI patterns#
| Pattern | What the user sees | Best for | Cost |
|---|---|---|---|
Inline numeral [1] |
Superscript/link number after the claim | Dense prose answers, chat | Cheapest; needs a source list |
| Hover/focus card | Number → floating card with title, snippet, link | Web UIs, when users verify often | Medium (frontend work) |
| Source list footer | Numbered list under the answer: title, section, page, link, snippet | Always — pair with any inline pattern | Trivial |
| Highlighted passage | Quote shown inline or in card, highlighted in the source | Legal/compliance, "show me the words" | Needs quote-level evidence |
| Side panel / split view | Answer left, cited document right with the span highlighted | Research tools, long documents | Highest; needs deep links + viewer |
Whichever you pick, the rendered output must answer three questions without a click: which source, which part of it, and is it allowed to show me this. render_markdown() in cite.py produces the portable baseline — markers in the text plus a numbered source list with title, page range, section path, URI and a ~200-char snippet (the snippet discipline from 05.8, 8.1).
5.2 Deep links and locators#
A citation becomes actionable when it links to the exact spot. The URL is source_uri + locator, per 05.8, 8.2 — store the canonical ID (source_id), rebuild the URL at render time, never store pre-built links:
| Source type | Locator | Example |
|---|---|---|
| Your docs site | fragment you control | /handbook/returns#eligibility |
| PDF / file store | page param | …/policy.pdf?page=41 |
| Web page | text fragment | …/article#:~:text=within%2030%20days |
| Audio/video | timestamp | …/episode?t=123 |
| Code | line range + commit | …/blob/<sha>/file.py#L40-L52 |
Two traps: text fragments are fragile — #:~:text= requires the exact string to still exist on the page; when the source is your document store, prefer page/section anchors and keep the quoted text for highlight lookup. And page numbers are only as good as the parser — a page_start that came from a mis-parsed PDF (05.2) produces confident wrong links; spot-check locators when you change parsers.
5.3 Edge cases#
- Multiple chunks, one document. Collapse citations to the same
doc_idinto one source entry listing each locator ("pp. 41, 43") — five footnotes to the same handbook page reads as noise. - Tables and figures. A quote can't capture a table cell. Cite the chunk containing the table and name it in the citation metadata (
"Table 3, p. 12"); for figures/images, cite the caption or themedia_id(Gemini returns one for image-derived chunks — 3.4). Rule of thumb: cite the container, describe the cell. - Structured data. When the answer comes from rows (SQL results, API fields), the honest citation is the query + filters + row id, not a quote. "Invoice INV-2042, line 3" beats a fabricated paragraph quote.
- Empty/degenerate evidence. A citation whose
quoteis empty or shorter than ~15 chars verifies trivially — treat sub-sentence quotes as document-level at best.
5.4 Quote length, copyright and PII#
- Quote length. Show enough to verify, not enough to republish. A snippet of ~200 chars (the 05.8 convention) previews without becoming a copy of the source.
cited_texton Anthropic is unbilled but still displayed — the same discipline applies. - Copyright/licensing. Quoting short spans for verification is normal engineering practice; wholesale reproduction of paywalled or licensed content in your UI is a licensing question, not an engineering one — this is not legal advice; check the licence of the corpus you're serving (05.1 covers source permissions).
- PII in snippets. A citation preview can leak personal data from a chunk the asker shouldn't fully see — the same allow-list discipline as logs (03.10, 05.8 Part 10). Snippets are display-only; never feed them back into prompts.
5.5 Citations in streaming responses#
Streaming breaks naive citation rendering in two ways: markers can arrive before the text they point at finishes, and citation payloads arrive as separate events after (or interleaved with) the text.
The safe pattern, consistent with 03.3, 6.4: stream the prose, buffer the citations, resolve at block end. Concretely:
- Anthropic: collect
citations_deltaevents per text block; the block'scitationslist is complete atcontent_block_stop. - OpenAI Responses:
response.output_text.annotation.addedevents carry each annotation; indices are stable, so you can render[n]markers once the annotated span has fully streamed. - Gemini
generate_content:grounding_metadataattaches to the completed candidate — citations resolve at end of stream, not incrementally. - Gemini Interactions / OpenRouter: annotation deltas arrive inline; apply the same buffer-and-resolve rule.
Never render a citation marker pointing at text that isn't fully on screen, and never renumber markers mid-stream — a reader who saw [2] must not watch it become [3]. If your UI numbers sources dynamically, assign numbers when the source list is final (end of stream), and keep the in-text glyphs stable by binding them to source identity, not position.
Part 6: Attribution beyond text#
Reference
The citation machinery generalises; only the locator changes.
| Modality | What the citation points at | Status (Nov 2026) |
|---|---|---|
| Images / page images | The image itself or its region | Gemini File Search returns media_id for image-derived chunks (downloadable via file_search_stores.download_media); Anthropic has no image citations — scanned PDFs aren't citable; Module 09 owns vision pipelines |
| Audio / video | Timestamp range + speaker | Chunk-level start_ms/end_ms/speaker fields from 05.8, 2.4; render as ?t=123 deep links; preview Module 09 |
| Code | Repo + commit + line range | Cite file.py#L40-L52 at a pinned commit — a line range without a commit rots immediately; treat the quoted code as evidence, not prose |
| Structured data | Row/query identity | "Result row inv_2042.l3 from the invoices query" — see 5.3 |
| Web pages | URL + optional text fragment | url_citation annotations give you url+title+span; add #:~:text= only if you control link stability |
The invariant across all of them: a citation is (source identity) + (locator) + (evidence span) + (the claim it supports). Whatever the modality, cite.py's SourceRef/ClaimEvidence/ClaimCitation shape carries it — page_start becomes start_ms, source_uri becomes the repo URL, quote becomes the code span.
The docs_qa package so far#
This lesson adds cite.py to the package the module is building. Files from sibling lessons (retrieval.py, generate.py, query.py, conversation.py) come from their own lessons; cite.py consumes their outputs — Hits from the Retriever contract and GroundedAnswer objects from the generator — through the small adapter functions shown above (cited_answer_from_grounded for 07.4's [passage-id] markers, evidence_from_* for provider citations).
docs_qa/
├── cite.py # this lesson: ClaimCitation/SourceRef/ClaimEvidence
│ # models, marker parsing, pure-local verification,
│ # precision/coverage metrics, Markdown rendering,
│ # provider-citation adapters
├── retrieval.py # 07.2/07.7 — Retriever implementations
├── generate.py # 07.4 — context assembly + grounded generation
└── … # grows each lesson; consolidated in 07.11docs_qa/cite.py in full:
# docs_qa/cite.py — citations for the docs_qa RAG app.
# Requires: pydantic (everything else is the standard library)
#
# Sits between the model's answer and the UI:
# answer text + [n] markers -> ClaimCitation objects (span + evidence + source)
# -> verification (does the evidence really support the claim?)
# -> rendering (inline markers + a source list a person can check)
#
# Provider-native citations (Anthropic citations, OpenAI annotations, Gemini
# grounding metadata) are normalised into the same ClaimEvidence/SourceRef
# shapes by the adapters at the bottom, so the verifier and renderer never
# care which provider produced them. Names are deliberately ClaimCitation /
# ClaimEvidence / CitedAnswer: 07.1's types.py already owns Answer/Citation
# and 07.4's generate.py owns Evidence/GroundedAnswer — see the lesson.
from __future__ import annotations
import re
import unicodedata
from dataclasses import dataclass
from pydantic import BaseModel, Field
class SourceRef(BaseModel):
"""Where a citation points. Fields mirror ChunkMeta/DocumentMeta
(lesson 05.8): enough to answer 'what, where, which version, may I see it'
without joining back to a documents table."""
chunk_id: str
doc_id: str
title: str
section_path: list[str] = Field(default_factory=list)
page_start: int | None = None
page_end: int | None = None
source_uri: str = ""
effective_date: str | None = None # freshness: which policy version
version: str | None = None # document/version stamp, if any
snippet: str = "" # display-only preview, filled at render time
class ClaimEvidence(BaseModel):
"""The exact passage the model claims supports a claim. `quote` is the
verbatim text expected inside the source chunk — this is what the
string-match verifier checks. `span_start`/`span_end` locate the quote
inside the source, but the UNIT depends on the provider: char offsets
for Anthropic char_location, block/page indices otherwise — treat them
as opaque locators, not slice offsets, unless you know the unit."""
quote: str
chunk_id: str
span_start: int | None = None
span_end: int | None = None
class ClaimCitation(BaseModel):
"""One [n] marker in the answer bound to the claim it supports and the
evidence behind it. claim_start/claim_end are char offsets into
CitedAnswer.text covering the claim *including* its marker."""
marker: int
claim_start: int
claim_end: int
evidence: list[ClaimEvidence] = Field(min_length=1)
class CitedAnswer(BaseModel):
text: str
citations: list[ClaimCitation] = Field(default_factory=list)
_WS = re.compile(r"\s+")
_QUOTES = str.maketrans({"“": '"', "”": '"', "‘": "'", "’": "'",
"–": "-", "—": "-"})
def norm(s: str) -> str:
"""Fold the differences that don't change meaning: unicode form,
curly quotes/dashes, whitespace runs, case."""
s = unicodedata.normalize("NFKC", s)
s = s.translate(_QUOTES)
return _WS.sub(" ", s).strip().lower()
# Canonical positional markers only: [0] is rejected by marker_in_range,
# and zero-padded forms like [007] do NOT match — they stay literal text
# and the citation fails marker_in_text rather than silently merging
# with [7].
_MARKER = re.compile(r"\[(0|[1-9]\d{0,2})\]")
# Stable-id markers, as 07.4's generate.py emits them: [handbook-005].
_ID_MARKER = re.compile(r"\[([a-z0-9][\w.-]*)\]")
_SENT_END = re.compile(r"(?<=[.!?])\s+")
def marker_positions(text: str) -> list[tuple[int, int, int]]:
"""[(start, end, marker_number)] for every [n] in the answer text."""
return [(m.start(), m.end(), int(m.group(1)))
for m in _MARKER.finditer(text)]
def cited_markers(text: str) -> set[int]:
return {n for _, _, n in marker_positions(text)}
def _sentence_span(text: str, pos: int) -> tuple[int, int]:
"""(start, end) of the sentence containing char offset `pos`. Used to
derive claim spans for markers the model didn't annotate itself."""
start = 0
for m in _SENT_END.finditer(text):
if m.end() <= pos:
start = m.end()
else:
break
nxt = _SENT_END.search(text, pos)
return start, nxt.start() if nxt else len(text)
@dataclass
class Check:
citation: int # marker number, or -1 for answer-level checks
name: str
ok: bool
detail: str = ""
cid: int = -1 # which ClaimCitation object (ordinal); -1 = n/a
def verify_citations(answer: CitedAnswer,
chunks: dict[str, str],
known_chunk_ids: set[str] | None = None,
n_sources: int | None = None) -> list[Check]:
"""The cheap, deterministic checks. `chunks` maps chunk_id -> chunk text
(what the retriever returned this turn); `known_chunk_ids` optionally
restricts to the chunks actually placed in context — pass it and a
citation pointing at a chunk that was never retrieved fails loudly.
`n_sources` is the number of chunks sent to the model (the size of the
ordered sources list the [n] markers index into); pass it and
`marker_in_range` fails any marker outside 1..n_sources.
What this CANNOT check: whether the quote actually entails the claim.
'Returns are allowed within 30 days' is in the chunk, but so is
'Returns are NOT allowed within 30 days' in a negated policy. That needs
the entailment check in 4.4 — an LLM judge or an NLI model."""
known = known_chunk_ids if known_chunk_ids is not None else set(chunks)
checks: list[Check] = []
markers_in_text = cited_markers(answer.text)
for ci, cit in enumerate(answer.citations):
m = cit.marker
# the marker must actually appear in the answer text
checks.append(Check(m, "marker_in_text", m in markers_in_text,
"marker present" if m in markers_in_text
else "marker missing from answer text",
cid=ci))
# and it must be one of the sources actually sent this turn
if n_sources is not None:
in_range = 1 <= m <= n_sources
checks.append(Check(m, "marker_in_range", in_range,
f"marker {m} {'within' if in_range else 'outside'} "
f"1..{n_sources} sent sources", cid=ci))
# the claim span must be sane and contain its own marker
span_ok = 0 <= cit.claim_start < cit.claim_end <= len(answer.text)
checks.append(Check(m, "claim_span_valid", span_ok,
f"[{cit.claim_start}:{cit.claim_end}] of "
f"{len(answer.text)} chars", cid=ci))
if span_ok:
inside = any(s >= cit.claim_start and e <= cit.claim_end
and n == m for s, e, n in marker_positions(answer.text))
checks.append(Check(m, "marker_inside_claim", inside,
"marker inside claim span" if inside
else "no [n] marker inside the claim span",
cid=ci))
# every evidence chunk must be one the retriever actually returned
for ev in cit.evidence:
checks.append(Check(m, "evidence_chunk_known",
ev.chunk_id in known,
f"chunk {ev.chunk_id[:12]}… "
f"{'in context' if ev.chunk_id in known else 'NOT retrieved this turn'}",
cid=ci))
# and the quote must appear in that chunk's text
if ev.chunk_id in chunks:
nq = norm(ev.quote)
found = bool(nq) and nq in norm(chunks[ev.chunk_id])
checks.append(Check(m, "quote_found", found,
"quote located in chunk" if found
else "quote NOT found in chunk text",
cid=ci))
else:
checks.append(Check(m, "quote_found", False,
"skipped: chunk text unavailable",
cid=ci))
return checks
def citation_precision(checks: list[Check]) -> float:
"""Share of citation OBJECTS whose evidence fully verifies (rungs 1-2).
Grouped by citation identity (`cid`), not marker number: two claims may
legitimately share marker [1] and must score independently."""
by_cit: dict[tuple[str, int], list[Check]] = {}
for c in checks:
key = ("c", c.cid) if c.cid >= 0 else ("m", c.citation)
by_cit.setdefault(key, []).append(c)
if not by_cit:
return 0.0
good = sum(1 for cs in by_cit.values() if all(c.ok for c in cs))
return good / len(by_cit)
def claim_coverage(answer: CitedAnswer) -> float:
"""Citation recall, approximated: split the answer into sentences and
measure what share carry at least one [n] marker. Crude — a claim split
across two sentences needs both halves cited — but it's the number you
can compute without an LLM judge. Module 07.9 builds the real version."""
sentences = [s for s in re.split(r"(?<=[.!?])\s+", answer.text.strip()) if s]
if not sentences:
return 0.0
cited = sum(1 for s in sentences if _MARKER.search(s))
return cited / len(sentences)
def cited_answer_from_grounded(gen, passage_ids: list[str],
chunk_id_for=None) -> CitedAnswer:
"""Convert lesson 07.4's generator output into this lesson's model.
generate.py sends <passage id="..."> blocks; the model cites stable ids
as [handbook-005] and may return structured evidence:[{passage_id,
quote}]. cite.py verifies positional [n] markers bound to the ordered
source list — this adapter renumbers each known id to its 1-based
position in `passage_ids` (the order the passages were sent), rewrites
the markers in the text, and binds evidence by passage position.
`chunk_id_for(pid)` maps a passage id to your chunk_id (default: the
passage id itself — generate.py's ids ARE the chunk ids).
Claim spans are derived per marker occurrence (the sentence holding
it). Markers whose id isn't in `passage_ids`, and markers with no
matching evidence entry, are kept — they fail verification loudly
(marker_in_range / quote_found) instead of being silently dropped."""
if isinstance(gen, str):
text, gen_evidence = gen, []
else:
text = getattr(gen, "answer", "") or getattr(gen, "text", "") or ""
gen_evidence = getattr(gen, "evidence", None) or []
pos = {pid: i + 1 for i, pid in enumerate(passage_ids)}
pid_for_pos = {v: k for k, v in pos.items()}
overflow: dict[str, int] = {}
def _renumber(m: re.Match) -> str:
pid = m.group(1)
if pid in pos:
return f"[{pos[pid]}]"
if pid not in overflow:
overflow[pid] = len(passage_ids) + 1 + len(overflow)
return f"[{overflow[pid]}]"
new_text = _ID_MARKER.sub(_renumber, text)
def _field(ev, name: str):
return ev.get(name) if isinstance(ev, dict) else getattr(ev, name, None)
ev_by_marker: dict[int, list[ClaimEvidence]] = {}
for ev in gen_evidence:
pid = _field(ev, "passage_id")
n = pos.get(pid) if pid else None
if n is None:
continue # evidence for a passage never sent — nothing to bind
cid = chunk_id_for(pid) if chunk_id_for else pid
ev_by_marker.setdefault(n, []).append(
ClaimEvidence(quote=_field(ev, "quote") or "", chunk_id=cid))
citations: list[ClaimCitation] = []
seen_spans: set[tuple[int, int, int]] = set()
for m in _MARKER.finditer(new_text):
n = int(m.group(1))
s, e = _sentence_span(new_text, m.start())
e = max(e, m.end())
if (n, s, e) in seen_spans:
continue
seen_spans.add((n, s, e))
evidences = ev_by_marker.get(n)
if not evidences:
pid = pid_for_pos.get(n)
cid = (chunk_id_for(pid) if chunk_id_for and pid else pid) or ""
evidences = [ClaimEvidence(quote="", chunk_id=cid or "")]
citations.append(ClaimCitation(marker=n, claim_start=s,
claim_end=e, evidence=evidences))
return CitedAnswer(text=new_text, citations=citations)
def render_markdown(answer: CitedAnswer, sources: dict[str, SourceRef]) -> str:
"""Answer text (markers intact) + a numbered source list. `sources` maps
chunk_id -> SourceRef, built once per request from retrieved Hits.
One entry per (marker, chunk_id): a claim backed by two chunks lists
both, and the same document cited via two chunks appears twice — the
reader sees every source, not just the first."""
out = [answer.text.strip(), "", "**Sources**", ""]
seen: set[tuple[int, str]] = set()
entries: list[tuple[int, SourceRef]] = []
for cit in sorted(answer.citations, key=lambda c: c.marker):
for ev in cit.evidence:
ref = sources.get(ev.chunk_id)
if ref and (cit.marker, ev.chunk_id) not in seen:
seen.add((cit.marker, ev.chunk_id))
entries.append((cit.marker, ref))
for n, ref in entries:
loc = ""
if ref.page_start:
loc = f" — p. {ref.page_start}" + (
f"–{ref.page_end}" if ref.page_end and ref.page_end != ref.page_start else "")
fresh = ""
if ref.effective_date:
fresh += f" — effective {ref.effective_date}"
if ref.version:
fresh += f" (v{ref.version})"
section = " / ".join(ref.section_path) if ref.section_path else ""
out.append(f"[{n}] {ref.title}{loc}{fresh}"
+ (f" — {section}" if section else ""))
if ref.source_uri:
out.append(f" {ref.source_uri}")
if ref.snippet:
out.append(f" > {ref.snippet}")
return "\n".join(out)
def evidence_from_hit(hit) -> ClaimEvidence | None:
"""Best-effort ClaimEvidence from a retrieved Hit (06.10 contract).
⚠️ `quote` is intentionally EMPTY: the retriever hands you the whole
chunk, not the span supporting a claim, and a chunk-prefix 'quote'
would make `quote_found` pass vacuously — precision would read 1.00
regardless of content. Fill `quote` with the real verbatim span (from
the model's evidence or your own extraction) before verifying; until
then `quote_found` fails closed."""
meta = getattr(hit, "metadata", {}) or {}
chunk_id = meta.get("chunk_id") or getattr(hit, "id", "")
if not chunk_id:
return None
return ClaimEvidence(quote="", chunk_id=chunk_id)
def evidence_from_anthropic(citation: dict,
chunk_id_for=None) -> ClaimEvidence | None:
"""Anthropic citation -> ClaimEvidence. `cited_text` is the exact
quoted span, so `quote_found` works verbatim.
The citation `type` decides what the span indexes into:
char_location / page_location / content_block_location ->
document_index into the document blocks you sent;
search_result_location -> `source` (your stable string) plus
start/end_block_index into that result's content blocks;
web_search_result_location -> a URL, not a corpus chunk -> None.
`chunk_id_for(citation) -> str` maps provider citations onto your
chunk ids (document_index -> the chunk you sent, source -> chunk_id).
Without it the raw provider ids are used — they only verify if
`chunks`/`known_chunk_ids` are keyed the same way."""
if not isinstance(citation, dict):
return None
ctype = citation.get("type")
if ctype == "web_search_result_location":
return None
quote = citation.get("cited_text") or ""
# explicit `is not None`: index 0 is a legitimate position
start = citation.get("start_char_index")
if start is None:
start = citation.get("start_block_index")
end = citation.get("end_char_index")
if end is None:
end = citation.get("end_block_index")
if ctype == "search_result_location":
chunk_id = citation.get("source") or ""
else:
doc_index = citation.get("document_index")
chunk_id = f"doc_block_{doc_index}"
if chunk_id_for is not None:
mapped = chunk_id_for(citation)
if mapped:
chunk_id = mapped
return ClaimEvidence(quote=quote, chunk_id=chunk_id,
span_start=start, span_end=end)
def evidence_from_openai(annotation: dict,
results: list | None = None,
quote: str = "") -> ClaimEvidence | None:
"""OpenAI annotation -> ClaimEvidence.
`file_citation` is file-level — {type, index, file_id, filename}: no
quote, no chunk. Pass the `file_search_call.results` rows (the
`include: ["file_search_call.results"]` payload) so file_id joins to
the retrieved chunk via `attributes.chunk_id`, and pass `quote`
yourself — the annotation doesn't say which span was used. Until both
are filled, `evidence_chunk_known`/`quote_found` fail closed.
`url_citation`, `container_file_citation` and `file_path` point at the
web or container files, not corpus chunks -> None."""
if not isinstance(annotation, dict):
return None
if annotation.get("type") != "file_citation":
return None
chunk_id = ""
if results:
for r in results:
if getattr(r, "file_id", None) == annotation.get("file_id"):
attrs = getattr(r, "attributes", None) or {}
chunk_id = ((attrs.get("chunk_id") if isinstance(attrs, dict)
else getattr(attrs, "chunk_id", None))
or getattr(r, "file_id", "") or "")
break
if not chunk_id:
chunk_id = annotation.get("file_id", "")
return ClaimEvidence(quote=quote, chunk_id=chunk_id)Decision table#
| Question | Answer |
|---|---|
| Do we need citations at all? | If users must trust or verify answers, or wrong answers have cost — yes. If it's an internal draft tool, markers-only is fine. |
| Prompt markers or provider citations? | Markers + cite.py when you own retrieval and need portability/verification. Provider citations when you want binding fidelity and accept their granularity. |
| Which provider feature? | Anthropic search_result blocks for self-managed RAG; OpenAI file_search/web_search annotations if you're on its store/tools; Gemini grounding_metadata/file_citation if you use its stores; OpenRouter's openrouter:web_search server tool for web citations across models. |
| Structured output + citations? | Anthropic: impossible together (400) — use markers or line-format. Others: annotations are orthogonal to response_format, but verify per model. |
| How much verification? | Rungs 1–2 always (free). Rung 3 (entailment) for customer-facing or compliance answers. Rung 4 in eval/CI, sampled in prod. |
| Streaming? | Buffer citations; resolve markers at block/stream end; never renumber mid-stream. |
Prompt gallery#
P1 — markers-only citation prompt (cheapest; pair with cite.py verification):
Answer the question using ONLY the numbered sources below. After each claim
that comes from a source, add its number in square brackets, e.g. [2].
Rules:
- One marker per claim. If a sentence combines claims from two sources,
cite both: [1][3].
- Never cite a source that doesn't contain the information.
- If the sources don't contain the answer, say "I don't have that in the
available documents" — do not use outside knowledge.
- Today's date is {today}.
QUESTION: {question}
SOURCES:
[1] {chunk_1_title} — {chunk_1_text}
[2] {chunk_2_title} — {chunk_2_text}
...P2 — quote-then-answer (stronger; the quote is string-match verifiable):
Answer using only the numbered sources. For each claim:
1. First write QUOTE: the exact words from the source that support it.
2. Then write the claim followed by its marker, e.g. CLAIM [2].
Rules:
- QUOTE must be copied verbatim — do not paraphrase inside QUOTE.
- Keep quotes under 30 words.
- If no source supports a claim, omit the claim entirely.
QUESTION: {question}
SOURCES: (same numbered format as P1)P3 — structured evidence (schema-constrained; the CitedAnswer model from 2.4):
Return JSON matching the schema. In `answer`, write the response prose with
[n] markers inline. In `citations`, for each marker include the verbatim
`quote` from the chunk and its `chunk_id`. Every marker in `answer` must
appear in `citations`, and vice versa.P4 — entailment judge (rung-3 verification, 4.4):
You are checking whether a source passage supports a claim.
CLAIM: {claim_text}
QUOTE: {evidence.quote}
SOURCE CHUNK: {chunk_text[:2000]}
Answer with JSON only:
{"verdict": "supported" | "unsupported" | "contradicted",
"reason": "<one sentence>"}Failure gallery#
| Anti-pattern | Why it fails | Do instead |
|---|---|---|
| Trusting provider citations blindly | They are model-generated; wrong spans happen | Run rungs 1–2 verification on everything shown to users |
| Post-hoc citation pass with no verification | Fluent, plausible, wrong attributions | Verify or don't show |
[n] markers colliding with document text |
Parser can't distinguish; injection vector | Unusual marker glyph + escape at ingestion |
| Numbering chunks before trimming | Model cites [7], you send 5 |
Number after the final context is fixed; assert contiguity |
| Showing snippets with PII | Preview leaks data the asker can't see | Allow-list snippet fields; treat as untrusted display text |
| Rendering citation markers mid-stream | Marker points at text not yet on screen; renumbering confusion | Buffer; resolve at block end |
| Deep links built at ingest time | URLs rot when sites reorganise | Store canonical ID + source_uri + ingested_at; rebuild at render (05.8, 8.2) |
| One citation per answer | "Citation dump" at the end covers nothing checkably | One marker per claim; measure claim_coverage |
| Citing a superseded document version | User checks the current policy, sees a different answer | Freshness filters at retrieval + effective_date/version in the citation (07.2) |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A citation proves the answer is correct." | It proves a pointer exists. Correctness needs entailment checks and good retrieval; the source itself can be wrong or stale. |
| "Provider citations are verified by the provider." | They're model-generated spans — better binding than markers, still fallible. Anthropic's docs claim "better citation reliability" vs prompting, not correctness. |
| "Post-hoc citations are fine if they look right." | They're decoration until verified — a second model guessing which source went with which claim. |
| "Citations and structured output work together everywhere." | On Anthropic they're mutually exclusive (400 error). On Gemini there are reported gaps with response_json_schema + grounding. Check per provider. |
| "Quoting more text makes citations safer." | Longer quotes increase copyright/PII exposure and UI noise; ~200-char snippets verify fine. |
| "If the quote is in the chunk, the claim is supported." | Containment ≠ entailment. Negations and numbers break it — that's rung 3. |
| "Citations slow nothing down." | Provider web/file-search tools bill per call ($2.50–$10/1k); verification judges add a model call per citation if you run them all. |
| "You can cite scanned PDFs." | Anthropic: no — PDFs need extractable text; image citations don't exist yet. Gemini File Search can cite media_id for image-derived chunks. |
Key takeaways#
- Citations operate at four levels — document, passage, quote, claim. Passage+quote is the practical sweet spot; claim-level is what makes answers verifiable.
- Faithful (inline) citations beat post-hoc ones; post-hoc citations are decoration until verified.
- Prompt-based citations are portable:
[n]markers + the orderedsourceslist +cite.pyverification works on every provider. - Provider citations differ in kind: Anthropic cites your documents/search-results at sentence/block/page granularity with free
cited_textbut no structured output; OpenAI annotates file-level (file_citation) and URL-span (url_citation) citations on its own tools; Gemini returns the richest payload (grounding_metadatawith chunk text, page numbers, confidence); OpenRouter standardises weburl_citations across engines. - Verify before showing: marker validity + quote containment are free; entailment needs a judge; citation precision/recall belong on your eval set.
- Stream safely: buffer citations, resolve markers at block end, never renumber mid-stream.
- Beyond text: the same (source, locator, span, claim) shape carries images (
media_id), audio (start_ms), code (commit + line range) and structured rows.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Citation | A pointer binding a claim in the answer to evidence in a source |
| Attribution | The general act of crediting sources; citations are its claim-level form |
| Faithful citation | A citation produced during generation, bound to the claim as written |
| Post-hoc citation | A citation attached after the answer was generated |
| Claim-level attribution | Binding each individual claim to its supporting source(s) |
| Quote-level attribution | Citing the exact verbatim text span supporting a claim |
[n] marker convention |
Numbering retrieved chunks and citing them inline as [n] |
search_result block |
Anthropic content block for passing your retrieved results with built-in citation support |
search_result_location |
Anthropic citation type resolving to a search_result block's source and content blocks |
file_citation |
OpenAI annotation identifying the file an answer span came from (no page/chunk) |
url_citation |
OpenAI/Gemini/OpenRouter annotation binding an answer span to a web URL |
grounding_metadata |
Gemini's citation payload: chunks + supports binding answer spans to retrieved context |
grounding_supports / grounding_chunk_indices |
Gemini structures mapping answer segments to supporting chunks |
citations_delta |
Anthropic streaming event carrying one citation at a time |
| Citation precision | Verified citations ÷ all citations |
| Citation recall / coverage | Claims carrying a supporting citation ÷ all claims |
| Entailment check | Verifying the quote actually supports the claim (NLI model or LLM judge) |
| Claim span | Char offsets in the answer text covering a claim and its marker |
| SourceRef | cite.py model: everything needed to display and link a source |
| ClaimEvidence | cite.py model: the quoted span expected inside a chunk |
| ClaimCitation | cite.py model: one [n] marker bound to a claim span + evidence list |
| CitedAnswer | cite.py model: answer text + its ClaimCitations |
| ALCE | Princeton benchmark for automatic evaluation of LLM citations (EMNLP 2023) |
Exercises#
- Markers to sources: extend the
demo.pyfixture so two citations point at the samedoc_idwith differentchunk_ids; confirmrender_markdownemits one source entry per (marker, chunk) pair and decide how you'd collapse them to one document entry (§5.3's rule). - Verifier edge cases: add a citation whose
quoteis""(empty), one whoseclaim_start > claim_end, and one whose marker is[0]. Predict which checks fail, runverify_citations, and explain each result. - Normalisation: craft a chunk containing a curly-quoted phrase and a line break mid-sentence; write a
quotethat differs only in whitespace/quote style and confirmnorm()makesquote_foundpass. - Precision/recall by hand: take an answer with 4 claims where 3 are cited and 1 citation fails
quote_found. Computecitation_precisionandclaim_coverageby hand, then check the code agrees. - Provider shapes: write
evidence_from_gemini(grounding_metadata)that convertsgrounding_supports+grounding_chunksintoClaimEvidence/ClaimCitationobjects. Which fields map toquote,chunk_id,span_start/span_end— and why are the segment indices bytes, not characters? - The 60-day trap: the failure-case demo catches an invented marker (
marker_in_range). Now craft a citation where the marker is in range and the quote is real but the claim inverts it ("returns are NOT allowed after 30 days" citing the 30-day-allowed chunk). Which rung catches it? Write the judge prompt input for it. - Streaming rule: given Anthropic's
citations_deltaevents, sketch the accumulator state needed to attach citations to the right text block — what do you store per block, and when do you render? - Deep links: for a PDF source with
page_start=41and a quote, build three candidate deep links (page param, text fragment, canonical-ID rebuild) and argue which survives a site reorganisation.
Hints. (2) An empty quote fails quote_found (the verifier fails closed rather than passing vacuously); claim_start > claim_end fails claim_span_valid; marker [0] fails marker_in_range, because the valid range is 1..n_sources — expect other checks on the same citation to fail too if your spans do not enclose the marker, since each rule is reported separately. (4) Three citations exist for the cited claims and one fails, so precision is 2 ÷ 3 ≈ 0.67; three of four claims carry a marker, so coverage is 3 ÷ 4 = 0.75. (5) The quote comes from the chunk text in grounding_chunks[idx].retrieved_context.text or the answer segment; chunk_id from your custom_metadata or title; the indices are UTF-8 byte offsets into one content part, so decode the byte slice. (6) Rung 3 (entailment); the judge input is the claim, the quote and the chunk, filled into prompt P4 below. (7) Store, per text block index, the accumulated text and a list of citation payloads; render when content_block_stop arrives for that block.
Check yourself#
- What are the four levels of attribution, and which is the practical sweet spot for UI verification?Document, passage, quote, claim. Passage+quote is the sweet spot: enough to verify, cheap to produce.
- Why are post-hoc citations "decoration until verified"?Because a second pass guesses the binding after the fact; it can produce fluent, specific, wrong attributions that look authoritative.
- What does a citation not prove, even when everything checks out?That the source is correct/current, that the claim follows from the quote, that the model actually used it, and that the user may see it.
- On Anthropic, what are the two ways to get citations on your own retrieved documents, and what citation type does each return?
documentblocks (page_location/char_location/content_block_location) andsearch_resultblocks (search_result_locationwith yoursourcestring). - Why can't you combine Anthropic citations with
output_config.format, and what's the documented workaround?They're incompatible — citations interleave blocks with text, conflicting with strict JSON schema → 400. Workaround: line-oriented "field: value" output where each value's block carries citations. - What does OpenAI's
file_citationannotation contain, and what do you needinclude: ["file_search_call.results"]for?type,index(position in the output text — char offset in practice),file_id,filename— file-level only.file_search_call.resultsgives the retrieved chunktext/score/attributesto join against. - Which Gemini structure binds answer text spans to retrieved chunks, and what extra fields do its chunks carry?
grounding_metadata.grounding_supports(segment byte-offset indices +grounding_chunk_indices+ confidence) overgrounding_chunks[].retrieved_context(title, text,page_number,media_id, custom metadata). - What is OpenRouter's
url_citationshape, and which engines power its web search tool?{type: "url_citation", url_citation: {url, title, content, start_index, end_index}}on the messageannotations. Engines: auto (native when the provider has it, otherwise Exa), native (for example Anthropic, Google, OpenAI, SpaceXAI), exa, firecrawl, parallel, perplexity. - Name the four verification rungs and which are free.Reference validity, quote containment (free, deterministic); entailment/NLI or LLM judge; whole-answer faithfulness (model calls).
- Why does quote containment fail to catch "not returnable after 30 days" citing the 30-day-allowed chunk?The quote exists verbatim in the chunk — containment passes — but the claim inverts its meaning. Only entailment catches it.
- What are citation precision and recall, and which is dangerous for compliance?Precision = verified ÷ all citations; recall/coverage = cited claims ÷ all claims. Low recall is dangerous for compliance: unsupported claims go uncited.
- What is the safe streaming pattern for citations, and why is mid-stream renumbering bad?Stream prose, buffer citation events, resolve markers at block/stream end. Renumbering mid-stream makes a marker a reader saw change meaning.
- How would you cite an audio answer segment, a code snippet, and a table cell differently?Audio:
start_ms/end_ms+?t=link. Code: repo + commit +#L40-L52. Table: cite the containing chunk and name the table/"Table 3, p.12" in metadata — a quote can't capture a cell.
Further resources#
- Anthropic, Citations and Search results: document/search-result citation shapes,
cited_textbilling, the structured-output incompatibility, streaming deltas. - Anthropic, Web search tool and Pricing:
web_search_result_locationcitations, $10/1k searches. - OpenAI, File search guide, Web search guide and Pricing:
file_citation/url_citationannotations,file_search_call.results, tool pricing, the inline-citation display requirement. - Google, File search, Grounding with Google Search and the Interactions API reference:
grounding_metadata,file_citation/url_citation/place_citationannotations, File Search and grounding pricing. - OpenRouter, Web search server tool:
url_citationannotations, engines, domain filters, per-engine pricing. - ALCE — Enabling LLMs to Generate Text with Citations (Gao, Yen, Yu, Chen; EMNLP 2023): the citation-quality benchmark and its precision/recall framing; code and data.
- CSS Text Fragments (
#:~:text=) (MDN): the text-fragment link syntax for deep-linking to quoted passages.
← 07.4 — Grounded Generation: Prompts, Context Assembly and Abstention | Module 07 overview | 07.6 — Conversational RAG →