Blog · · 8 min read
Gate RAG citations on this turn's retrieval registry

A product RAG agent that invents footnote IDs or streams source chips for passages that were never retrieved hands users a receipt that lies. Free-text "cite your sources" prompts fail that bar, and provider annotations still leave gaps: Anthropic's Citations docs guarantee pointers into documents you supplied, while OpenAI Community reports show Responses API file_citation markers bind to files rather than chunks. This guide shows how to mint a per-turn retrieval registry, choose a generation path, validate every ID before UI render, and refuse unsupported claims so RAG citations become checkable product behavior.
The delivery contract in one page
Treat citations as a pipeline, not a prompt line:
- Retrieve with the same authorization and tenant filters the product already uses for knowledge search.
- Register every returned chunk as
{chunk_id, source_url, title, text, heading_path, retrieved_at}. - Generate with one deliberate path: provider-native citations, structured claim objects with
supporting_chunk_ids, or prompt markers that only name registry IDs. - Validate before any chip renders: every cited ID must belong to this turn's registry; optional span or faithfulness checks reject unsupported claims.
- Stream chips from validated citations only (
citations_deltaor annotation events mapped through the registry). - Refuse or regenerate when retrieval is empty, IDs are unknown, or support checks fail.
- Eval coverage (factual sentences with a citation), validity (markers resolve), and faithfulness (cited text supports the claim), as LLM Best Practices recommends.
The citation-attribution pattern states the binding rule plainly: every claim must resolve to a retrieved-source id from this turn's registry, and unknown IDs must be rejected before delivery. The hallucinated-citations anti-pattern is what you get when free-text footnotes ship unverified.
Why invented RAG citations happen
Three mechanisms create the failure.
Prompt-only footnotes invent authority. Models trained on academic and legal text produce plausible IDs, titles, and URLs that never appeared in retrieval. The anti-pattern catalog names this directly: whatever the model writes is shipped as-is until a user clicks and finds nothing.
Provider annotations are incomplete product contracts. Anthropic's native citations parse pointers into your documents and keep cited_text off the output-token bill, which is the right default when you can feed retrieved chunks as document or search_result blocks (Citations, Search results). OpenAI Responses file_search returns file_citation annotations with file_id, filename, and a character index into the answer (File search). Multiple implementers migrating from Assistants report those annotations no longer identify the retrieved chunk, only the file, so a product that used to show the supporting passage loses that UX unless it rebuilds the mapping (community thread).
Valid pointers still mis-support claims. Anthropic's own comparison notes that native citations improve pointer reliability versus prompt quotes, while whether the cited span supports the claim remains an evaluation problem. A chip that opens the wrong paragraph is still a product defect.
Practitioner reports describe the same failure. One engineer wrote that a fake citation is worse than none because it is a receipt that lies (X post). Another product reports deterministic guardrails that reject fake citations at a high accuracy floor (X post). Treat those as author reports, and make the registry gate a product invariant.
Build the per-turn retrieval registry
Before the model writes a sentence, freeze the evidence set for this turn.
RetrievalRegistry
turn_id: string
tenant_id: string
query: string
chunks: map[chunk_id -> {
source_url, title, heading_path,
text, score, retrieved_at
}]
empty: boolean
Rules:
- Mint
chunk_idvalues that are non-sequential and hard to guess (UUIDs or hashed content keys), so fabricated[4]style markers fail the membership check easily. - Store deep links in metadata (
source_url#heading-anchor, page range, line range) so chips open the passage, not the document home page. - Keep the registry server-side for the turn. Never let the client invent IDs that the model "confirms."
- If retrieval returns nothing, set
empty=trueand skip generation paths that emit citations. Show an explicit no-source state. BotDojo's citation store is one productized form of the same idea: tools mint numeric citation IDs, and the agent may only reference those IDs.
Wire retrieval through the product's existing knowledge path so tenant filters and authorization stay identical to non-cited answers. A citation pipeline that searches a wider corpus than the agent is allowed to read creates a new leak channel.
Choose the generation path before the schema
Path A: Provider-native citations (Claude)
Return retrieved chunks as search_result blocks inside the tool result, or as top-level user content, with citations: { enabled: true } on every result. Anthropic requires all-or-nothing citation settings in a request and, inside one tool_result, forbids mixing search_result with other block types (Search results). Prefer multiple small text blocks inside each result when you want finer chip granularity.
Claude native citations and structured outputs cannot share one request, so pick the citation path before you design the answer schema. Enabling citations on documents or search results together with output_config.format (or the deprecated output_format) returns a 400 error (Citations). Decide at design time: either stream interleaved citation blocks, or emit a JSON schema of claims with chunk IDs and validate offline. Products that assume "structured answers plus native citations" will discover the conflict in production.
Streaming: handle citations_delta beside text deltas and buffer chips until the citation object is complete. Map search_result_index and block ranges back through your registry so the UI shows your product title and deep link, not only the model-facing source string.
Path B: Structured claims with supporting_chunk_ids
When you need a JSON schema (grading, CRM writeback, multi-claim cards), force:
{
"claims": [
{
"text": "...",
"supporting_chunk_ids": ["c_8f3a…"]
}
],
"uncited_meta": "optional short bridge text only"
}
Validate every supporting_chunk_ids entry against the registry. Drop or regenerate claims with unknown IDs. This is the path Anthropic forces when structured outputs win over native citations, and it matches the citation-attribution structured-output option.
Path C: Prompt markers with hard validation
For models without native citations, label context as [chunk_id] text… and require inline markers only from that set. After generation, strip any marker absent from the registry before render. Never leave stripping as a best-effort log line.
Validate before stream, then check support
Gate order matters:
- Membership: cited ID ∈ this turn's registry.
- Presence: cited text or span exists in the registered chunk (for native
cited_text, confirm it is a substring or accepted block slice). - Support: the claim is entailed by the cited span (deterministic overlap for short factual claims; sampled judge for harder cases), as both Anthropic guidance and LLM Best Practices separate pointer validity from faithfulness.
OpenAI Responses file_citation annotations identify a file, not the retrieved chunk, so product agents still need a chunk registry for passage chips. Even when you include: ["file_search_call.results"], the annotation does not carry a chunk key (File search; community reports). Product agents that want passage chips must keep their own chunk registry (or reconstruct the best-matching result text) and refuse to show a chip that cannot resolve to a passage. File-level footnotes are a degraded mode, not feature parity with Assistants-era chunk citations.
A valid citation pointer is not a faithful claim; run a support check after ID validation or you will stream accurate links to the wrong sentence. Do not make the chip user-visible until that support check passes, or mark the claim as unverified and regenerate.
Empty retrieval policy: do not ask the model for citations. Return a fixed empty-state message and a "show what was searched" affordance for operators. Log refusals; a spike usually means retrieval or filters changed, not a model personality shift.
Stream chips users can verify
Render each validated citation as a chip: title - heading - last_updated. On hover, show the cited span the model saw. On click, open the deep link. Keep citations beside the claim, not only in a footer dump.
For streaming UIs:
- Buffer text until accompanying citations for that span validate.
- Never optimistic-render a chip from a partial ID.
- If regeneration removes a claim, remove its chips in the same frame.
BotDojo's markdown footnote plus "Show Sources" panel shows one two-surface UX (inline markers and a sources drawer). Markers still have to resolve to the session citation store (BotDojo Citations).
Handle failure and recovery
| Failure | Product behavior |
|---|---|
| Empty retrieval | No-source state; no citation path; log refusal |
| Unknown citation ID | Strip claim or regenerate; never render chip |
| Native citations + structured outputs requested | Reject config at deploy time; route to Path B |
| File-level annotation without chunk map | Show file title only with "passage unavailable", or suppress chip |
| Support check fails | Regenerate once with the supporting chunk highlighted; then refuse the claim |
| Mixed citation enablement in one Claude request | Fail the request; Anthropic rejects mixed settings |
Partial answers are allowed: fewer verified claims beat a fluent paragraph of invented footnotes.
Verify the solution
Ship these drills before enabling chips in production:
- Inject a model output that cites
[missing-id]; assert zero chips and a regenerate or strip. - Enable Claude citations and structured outputs together in a staging client; assert the API error is caught at config validation, not at runtime for end users.
- On OpenAI file_search, assert every user-visible passage chip resolves through included results or your registry, not only
file_id. - Mutate a claim so the cited span no longer supports it; assert the support gate blocks the chip.
- Force empty retrieval; assert the empty-state copy and no free-text footnotes.
- Track release metrics: coverage, validity, faithfulness. A relevance lift that drops faithfulness is a regression (LLM Best Practices).
Common mistakes
- Prompting for citations without a registry. This recreates the hallucinated-citations anti-pattern.
- Treating provider annotations as the finished product. Claude still needs a support check; OpenAI file citations still need a chunk map for passage UX.
- Designing JSON answer schemas and native Claude citations as one path. The API forbids that combination.
- Counting message-level "sources used" as claim-level citations. Listing retrieved docs in a footer does not bind each sentence.
- Client-side ID inventing. If the browser can add a chip ID, the model is no longer the only forgery source.
What to do next
Pick one live product agent that already retrieves from your knowledge base. Add a server-side per-turn registry on that path, choose Path A or Path B deliberately, and block chip render until membership and support checks pass. Run the six drills above on staging before flipping the UI flag. If you build agents on Make Your Agent, start from your existing grounded retrieval results and add the registry gate at the answer boundary rather than inventing a second search path.