Search Tutorials
--Ads--Citations and Source Attribution
Make every claim traceable to a source chunk, with prompt-based and API-native citations.
Citations turn a RAG answer from "trust me" into "check for yourself". They let users verify claims, open the original document and judge how current the source is, and they make wrong answers easier to spot and debug. This lesson shows two ways to get citations: prompt-based citation markers that you validate, and the API's built-in citations feature, which returns the exact cited text.
Approach 1: Prompt-based citation markers
Number the sources and ask the model to put source IDs in square brackets after each statement. This is simple and works with any prompt format.
import re
from rag_helpers import ask
def answer_with_markers(question: str, hits: list[dict]) -> tuple[str, list[dict]]:
sources = "\n".join(f'<source id="{i}" title="{h["title"]}">\n{h["text"]}\n</source>'
for i, h in enumerate(hits, start=1))
answer = ask(f"<sources>\n{sources}\n</sources>\n\n"
"Answer using only the sources. After each sentence that uses a source, add its "
"id in square brackets, like [1] or [1][3]. If the sources do not answer the "
f"question, say so without citations.\n\nQuestion: {question}")
cited_ids = sorted({int(n) for n in re.findall(r"\[(\d+)\]", answer)})
invalid = [n for n in cited_ids if not 1 <= n <= len(hits)]
if invalid:
answer = re.sub(r"\[(%s)\]" % "|".join(map(str, invalid)), "", answer) # drop bad ids
references = [{"id": n, **hits[n - 1]} for n in cited_ids if 1 <= n <= len(hits)]
return answer, references
answer, refs = answer_with_markers("How much is the home internet allowance?", hits)
print(answer)
for r in refs:
print(f"[{r['id']}] {r['title']}")
Employees who work remotely can claim up to 1,500 rupees per month for home internet [1].
[1] Zentrix Labs Remote Work Policy
Markers tell you which source supports a sentence, but not which part of it, and nothing guarantees that the source really says what the sentence claims. Groundedness checking (Module 12) closes that gap.
Approach 2: The API's built-in citations
The Claude API can cite sources natively. Pass each retrieved chunk as a document content block with citations enabled. The response is split into text blocks, and each block that relies on a source carries a list of citations containing the exact quoted text and its location in the document. Because the cited text is extracted from your documents rather than generated, the quotes are guaranteed to be real.
import anthropic
client = anthropic.Anthropic()
def answer_with_citations(question: str, hits: list[dict]):
documents = [
{
"type": "document",
"source": {"type": "text", "media_type": "text/plain", "data": h["text"]},
"title": h["title"],
"context": f"Source file: {h['source']}", # metadata the model can read, never cited
"citations": {"enabled": True},
}
for h in hits
]
return client.messages.create(
model="claude-opus-5-5",
max_tokens=2000,
output_config={"effort": "low"},
messages=[{"role": "user", "content": documents + [
{"type": "text", "text": f"Answer using these documents. If they do not answer "
f"the question, say so.\n\nQuestion: {question}"}]}],
)
def render(response) -> str:
"""Turn text blocks and their citations into an answer with numbered footnotes."""
body, footnotes = [], []
for block in response.content:
if block.type != "text":
continue
body.append(block.text)
for c in block.citations or []:
footnotes.append(f'[{len(footnotes) + 1}] {c.document_title}: "{c.cited_text.strip()}"')
body.append(f"[{len(footnotes)}]")
return "".join(body) + "\n\n" + "\n".join(footnotes)
print(render(answer_with_citations("Can I carry over unused leave?", hits)))
Yes. You can carry over up to 5 unused days of paid leave to the next calendar year[1].
[1] Zentrix Labs Leave Policy: "Unused leave of up to 5 days can be carried over to the next calendar year."
Notes on built-in citations:
- Plain-text documents are cited by character range (
start_char_indexandend_char_index), and PDFs by page range, so you can highlight the passage in your UI. - For pre-chunked content, a
contentdocument source with one text block per chunk makes the model cite whole chunks (content_block_location). - Enable citations on all documents in a request or on none.
- Citations cannot be combined with structured JSON output (
output_config.format) in the same request.
Displaying citations well
- Link each citation to the source document, at the page or section, wherever possible.
- Show the date or version of each cited source.
- Show the cited quote on hover or expansion, so users can check without leaving the answer.
- Treat answers without citations as a signal: either the model is saying "not found", or something went wrong.
Key takeaways
- Citations make answers verifiable and failures debuggable.
- Prompt-based markers are simple; validate that cited IDs exist.
- Built-in API citations return exact quotes and locations extracted from your documents.
- Link citations to the source location and show source dates.