Claude can answer questions about your documents and point to the exact sentence, page or chunk behind every claim. That feature is called Citations, and it is built into the Messages API at no extra fee.
In this tutorial I show you how to turn it on in Python for plain text, PDFs, custom chunks and RAG search results. You will also see how to read each citation format, stream citations live and keep costs low.
- Turn it on: add
"citations": {"enabled": True}to eachdocumentorsearch_resultblock. No beta header is needed. - Four citation types:
char_location(plain text),page_location(PDF),content_block_location(custom content) andsearch_result_location(RAG results). - Cost: normal token prices. The quoted
cited_textdoes not count toward output tokens. - Big gotcha: citations plus structured outputs (
output_config.format) returns a 400 error. - Models: every active Claude model, including Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.2.
What the Claude Citations API Does
Normally, Claude answers in one block of text. With citations on, the API splits the answer into several text blocks. Each block that uses your source carries a citations list with the exact quoted text and where it came from.
The API parses these pointers itself. So every citation is guaranteed to point at a real place in the documents you sent, which is very hard to get from prompt tricks alone.
Use it when:
- Support bots: answers must link back to a help article or policy.
- Legal and finance: reviewers need page numbers for every claim.
- RAG apps: you already retrieve chunks and want Claude to say which chunk it used.
- Research tools: you want clickable highlights in a UI.
Note: Citations has been in the API since early 2025. As of 3 December 2026 the docs list it as stable on the Claude API, Amazon Bedrock, Claude Platform on AWS, Google Cloud and Microsoft Foundry. It is not available inside Managed Agents sessions.
Prerequisites and Setup
You need Python 3.10 or newer, a Claude API key and the official anthropic SDK. I checked every example against anthropic 2.16.0 (the current PyPI release) and API version 2026-10-21.
- Get an API key. Create one in the Claude Console under API keys. My guide on how to get a Claude API key walks through it.
- Install the SDK. Run
pip install -U anthropicinside a virtual environment. - Set the key as an environment variable. On macOS or Linux run
export ANTHROPIC_API_KEY="sk-ant-...". On Windows PowerShell use$env:ANTHROPIC_API_KEY="sk-ant-...". Never paste the key into your code. - Pick a model. I use
claude-opus-5-5for most examples,claude-sonnet-5-5for PDFs andclaude-haiku-5-5for cheap high-volume work. - Add
"citations": {"enabled": True}to every document in the request. It is all or nothing: you cannot mix cited and uncited documents in one request.
New to the SDK? Start with my Claude API Python tutorial, then come back here.
Example 1: Cite a Plain Text Document
Plain text is the simplest source. The API splits it into sentences, and each citation gives a 0-indexed character range. The helper below prints the answer with numbered markers and a sources list, and it works for every citation type in this guide.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
POLICY = (
"Refunds are available within 30 days of purchase. "
"Digital downloads cannot be refunded once opened. "
"Shipping fees are not refundable."
)
def print_with_citations(response):
refs = []
answer = ""
for block in response.content:
if block.type != "text":
continue # skip thinking blocks
answer += block.text
for c in block.citations or []:
refs.append(c)
answer += f" [{len(refs)}]"
print(answer)
print("Sources:")
for i, c in enumerate(refs, start=1):
if c.type == "char_location":
where = f"chars {c.start_char_index}-{c.end_char_index}"
elif c.type == "page_location":
where = f"page {c.start_page_number}"
elif c.type == "content_block_location":
where = f"block {c.start_block_index}"
elif c.type == "search_result_location":
where = c.source
else:
where = c.type
print(f'[{i}] "{c.cited_text.strip()}" ({where})')
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=2048,
messages=[
{
"role": "user",
"content": [
{
"type": "document",
"source": {
"type": "text",
"media_type": "text/plain",
"data": POLICY,
},
"title": "Refund Policy",
"context": "Official store policy, updated 2026.",
"citations": {"enabled": True},
},
{"type": "text", "text": "Can I get my shipping fee back?"},
],
}
],
)
print_with_citations(response)
A typical output looks like this:
No, shipping fees are not refundable [1]
Sources:
[1] "Shipping fees are not refundable." (chars 101-134)
Notice the title and context fields. Claude reads them, but it never cites them. Put metadata such as dates, owners or a JSON string in context, because title has a length limit.
Tip: Always loop over response.content and check block.type == "text". Opus 5.5 always thinks, so the content list can also hold thinking blocks.
Example 2: Cite Pages in a PDF
For PDFs, the API extracts the text, splits it into sentences and returns 1-indexed page numbers. You can send the PDF as base64, as a public URL ("type": "url") or as a Files API file_id.
import base64
from pathlib import Path
import anthropic
client = anthropic.Anthropic()
# Option A: inline base64
pdf_b64 = base64.standard_b64encode(Path("report.pdf").read_bytes()).decode()
pdf_source = {"type": "base64", "media_type": "application/pdf", "data": pdf_b64}
# Option B: upload once with the Files API, reuse the file_id
# uploaded = client.files.upload(file=Path("report.pdf"))
# pdf_source = {"type": "file", "file_id": uploaded.id}
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=4096,
messages=[
{
"role": "user",
"content": [
{
"type": "document",
"source": pdf_source,
"title": "Annual Report 2026",
"citations": {"enabled": True},
},
{"type": "text", "text": "What were the three biggest risks? Cite pages."},
],
}
],
)
for block in response.content:
if block.type == "text":
print(block.text, end="")
for c in block.citations or []:
# end_page_number is exclusive, so subtract 1 for the last page
print(f" [p.{c.start_page_number}-{c.end_page_number - 1}]", end="")
print()
The end page is exclusive. A citation with start_page_number: 5 and end_page_number: 6 means page 5 only. That is why the code subtracts 1.
Warning: Claude cannot cite images. A scanned PDF with no text layer will get answers but no page citations. Run OCR first, or send the text as a plain text document.
If you plan to ask many questions about the same PDF, upload it once. My Claude Files API tutorial covers uploads, listing and deleting files.
Example 3: Custom Content for Your Own Chunks
Sometimes sentence splitting is wrong for your data. Think of transcripts, bullet lists or table rows. A custom content document lets you pass a list of text blocks. Each block is one citable unit, and the API does no extra chunking.
import anthropic
client = anthropic.Anthropic()
transcript = [
"[00:01] Priya: We will ship version 2 on 15 January.",
"[00:14] Tom: QA needs one more week for the payments flow.",
"[00:30] Priya: Fine, move the launch to 22 January.",
]
response = client.messages.create(
model="claude-haiku-5-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "document",
"source": {
"type": "content",
"content": [{"type": "text", "text": line} for line in transcript],
},
"title": "Launch meeting transcript",
"citations": {"enabled": True},
},
{"type": "text", "text": "What is the final launch date and why?"},
],
}
],
)
for block in response.content:
if block.type == "text":
print(block.text, end="")
for c in block.citations or []:
print(f" (line {c.start_block_index})", end="")
print()
Citations come back as content_block_location with 0-indexed start_block_index and an exclusive end_block_index. If one line is cited, you get start 2 and end 3.
Search Result Blocks for RAG
If you already run a retrieval step, the search_result block is the best fit. Each result carries a source (a URL or any stable ID like kb://article-1234), a title and a list of text blocks. Claude then cites your results the same way it cites web search results.
Method 1: Pass results directly in the user message
Use this when your app fetches the chunks before calling Claude. It is the simplest RAG pattern.
import anthropic
client = anthropic.Anthropic()
def search_kb(query):
# Replace with your vector DB or keyword search.
hits = [
{"url": "kb://billing/refunds", "title": "Refund rules",
"chunks": ["Refunds are issued within 5 business days.",
"Annual plans get a prorated refund."]},
{"url": "kb://billing/invoices", "title": "Invoices",
"chunks": ["Invoices are emailed on the 1st of each month."]},
]
return [
{
"type": "search_result",
"source": h["url"],
"title": h["title"],
"content": [{"type": "text", "text": t} for t in h["chunks"]],
"citations": {"enabled": True},
}
for h in hits
]
question = "How fast are refunds and do annual plans get money back?"
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=2048,
messages=[
{
"role": "user",
"content": search_kb(question) + [{"type": "text", "text": question}],
}
],
)
for block in response.content:
if block.type == "text":
print(block.text, end="")
for c in block.citations or []:
print(f" [{c.title}: {c.source}]", end="")
print()
Method 2: Return results from a tool
Use this when Claude should decide what to search for. Your tool returns a list of search_result blocks inside the tool_result. If you are new to tools, read my Claude tool use tutorial first.
import anthropic
client = anthropic.Anthropic()
kb_tool = {
"name": "search_knowledge_base",
"description": "Search the help center. Use it for any product question.",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"],
},
}
messages = [{"role": "user", "content": "How do I export my invoices?"}]
first = client.messages.create(
model="claude-opus-5-5",
max_tokens=2048,
tools=[kb_tool],
tool_choice={"type": "auto"}, # forced tool_choice returns 400 on Opus 5.5
messages=messages,
)
tool_use = next((b for b in first.content if b.type == "tool_use"), None)
if tool_use:
results = [
{
"type": "search_result",
"source": "https://help.example.com/invoices/export",
"title": "Export invoices",
"content": [{"type": "text", "text": "Go to Billing, then Invoices, then click Export CSV."}],
"citations": {"enabled": True},
}
]
messages.append({"role": "assistant", "content": first.content})
messages.append({
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": tool_use.id, "content": results}],
})
final = client.messages.create(
model="claude-opus-5-5", max_tokens=2048, tools=[kb_tool], messages=messages
)
for block in final.content:
if block.type == "text":
print(block.text, [c.source for c in block.citations or []])
Note: The official docs example forces the tool with tool_choice on claude-opus-5. Forced tool_choice (any or tool) returns a 400 on Opus 5.5, Sonnet 5.5 and Fable 5.2, so I use auto plus a clear tool description.
Rules to remember for search results:
- Off by default: citations on search results are disabled unless you set
enabledto true. - All or nothing: every search result in a request must use the same citation setting.
- Tool results are strict: if one block in a
tool_resultis asearch_result, all of them must be. - Text only: no images inside the
contentarray. - Whole blocks: Claude cites whole text blocks, never part of one. Split long chunks for finer citations.
- Web search mix: if the web search tool is in the same request, citations must be on for all search results.
Citation Formats Explained
Every citation has a type and a cited_text. The location fields change by source type. Here is the full map, taken from the docs and the SDK types.
| Citation type | Comes from | Location fields | Indexing |
|---|---|---|---|
char_location |
Plain text document | start_char_index, end_char_index |
0-indexed, end exclusive |
page_location |
PDF document | start_page_number, end_page_number |
1-indexed, end exclusive |
content_block_location |
Custom content document | start_block_index, end_block_index |
0-indexed, end exclusive |
search_result_location |
search_result block |
source, title, search_result_index, block indices |
0-indexed, end exclusive |
web_search_result_location |
Built-in web search tool | url, title, encrypted_index |
Opaque index |

char_location citation (checked 3 Dec 2026).Document citations also include document_index and document_title. The document_index counts every document block in the request, across all messages, starting at 0. The search_result_index works the same way for search results.
Streaming Citations
With streaming, citations arrive as a citations_delta inside content_block_delta events. Each delta holds one citation for the current text block. The Python SDK wraps this as a simple "citation" event, so you do not have to parse raw events.
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=4096,
messages=[
{
"role": "user",
"content": [
{
"type": "document",
"source": {"type": "text", "media_type": "text/plain",
"data": "The grass is green. The sky is blue."},
"title": "Colors",
"citations": {"enabled": True},
},
{"type": "text", "text": "What color is the sky?"},
],
}
],
) as stream:
for event in stream:
if event.type == "text":
print(event.text, end="", flush=True)
elif event.type == "citation":
print(f' [source: "{event.citation.cited_text.strip()}"]', end="")
final = stream.get_final_message()
print()
print("Input tokens:", final.usage.input_tokens, "Output tokens:", final.usage.output_tokens)
The SDK event also has a snapshot field with every citation collected so far for that block. Call stream.get_final_message() at the end to get the same structure as a normal response.
curl Example
Here is the same idea with raw HTTP and a search result block. It is handy for testing from a terminal.
curl https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2026-10-21" \
-d '{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"messages": [{
"role": "user",
"content": [
{
"type": "search_result",
"source": "kb://billing/refunds",
"title": "Refund rules",
"content": [{"type": "text", "text": "Refunds are issued within 5 business days."}],
"citations": {"enabled": true}
},
{"type": "text", "text": "How long do refunds take?"}
]
}]
}'
Token Costs and a Worked Example
Citations has no separate fee. You pay normal input and output token prices. Turning it on adds a few input tokens for a system prompt and document chunking, but the quoted cited_text is free on output, and free again when you send it back in later turns.
| Model | Input / MTok | Output / MTok | Cache read / MTok | Batch (input / output) |
|---|---|---|---|---|
| Claude Fable 5.2 | $8 | $40 | $0.20 | $4 / $20 |
| Claude Opus 5.5 | $4 | $20 | $0.20 | $2 / $10 |
| Claude Sonnet 5.5 | $2 | $10 | $0.10 | $1 / $5 |
| Claude Haiku 5.5 (prompts up to 100K) | $0.10 | $0.50 | $0.01 | $0.05 / $0.25 |
Worked example: a 20-page PDF report. The PDF docs say each page uses about 1,500 to 3,000 text tokens, plus up to 1,568 image tokens per page. Say the request totals 60,000 input tokens and Claude writes a 1,000-token cited answer.
- Opus 5.5: 60,000 x $4/M = $0.24, plus 1,000 x $20/M = $0.02. Total $0.26.
- Sonnet 5.5: $0.12 + $0.01 = $0.13.
- Haiku 5.5: $0.006 + $0.0005 = about $0.0065.
- Opus 5.5 with the PDF cached: 60,000 x $0.20/M = $0.012, plus $0.02 output = about $0.03 per follow-up question.
Tip: You can put cache_control: {"type": "ephemeral"} on a document or search result block. The citation blocks themselves are not cached, but the source text is. See my prompt caching guide and the full Claude API pricing breakdown.
Limits and Compatibility
| Item | Limit or rule |
|---|---|
| Max request size | 128 MB on the first-party Claude API (raised on 28 Oct 2026; other platforms vary) |
| PDF pages per request | 600 (100 when the context window is under 1M tokens) |
| PDF format | Standard PDF, no password or encryption |
| Citable content | Text only. No citations from images or image-only PDF pages |
| Other file types | Convert .docx or .xlsx to plain text. .csv and .md can go in as text/plain |
| Mixing settings | All documents (or all search results) in a request must share one citation setting |
| Structured outputs | Not compatible. Returns a 400 error |
| Prompt caching, token counting, batches | Compatible |
| Managed Agents | Document citations not available. Search results only inside tool results |
| Data handling | ZDR eligible (except Covered Models) and HIPAA eligible |
Need JSON with sources? The docs suggest asking for one field: value line per field, then reading each line’s citations in code. Prompts that demand “JSON only” still work, but they may return few or no citations. For true schema output, use my structured outputs guide in a separate call.
Citations API vs Asking the Model to Cite
You could just write “quote your sources” in the prompt. Here is why the built-in feature usually wins.
| Point | Citations API | Prompt-based quoting |
|---|---|---|
| Pointer validity | Guaranteed to point into your documents | Quotes can be wrong or invented |
| Location data | Char, page or block indices, ready for UI highlights | You must search for the quote yourself |
| Output cost | Quoted text is free | You pay for every quoted word |
| Quality | Anthropic says it cites more relevant quotes | Depends on your prompt |
| JSON output | Not with structured outputs | Works with any format |
| Setup | One flag per document | Prompt tuning plus parsing code |
At launch, Anthropic reported up to 15% better recall accuracy than custom setups in its internal tests. Customer Endex said source hallucinations fell from 10% to 0%.
Troubleshooting: Common Problems and Fixes
| Problem or error | Cause | Fix |
|---|---|---|
400 invalid_request_error with citations and output_config.format |
Citations are not compatible with structured outputs | Remove output_config.format (or the old output_format), or split into two calls |
| 400 error about mixed citation settings | Some documents or search results have citations on and some off | Set enabled the same on every block |
400 tool_choice: type "tool" and "any" are not supported for this model. |
Forced tool use on Opus 5.5, Sonnet 5.5 or Fable 5.2 | Use {"type": "auto"} and name the tool in the prompt |
| Validation error on a tool result | A tool_result mixes search_result with other block types |
Put extra text inside a search result’s content instead |
| Answer has no citations | Prompt asked for JSON only, or the PDF is a scan | Ask a plain question. OCR scanned PDFs first |
AttributeError on block.citations |
You read a thinking or tool_use block |
Check block.type == "text" first |
| 413 or request too large | Payload over the size limit | Upload with the Files API or split the PDF |
| 429 or 529 | Rate limit or overload | Back off and retry. See my 429 and 529 fix guide |
Note: Only the structured outputs and forced tool_choice messages above are quoted from the official docs. For the others, the exact error wording can vary, so check the message field in the error body.
Frequently Asked Questions
Is the Claude Citations API free?
There is no extra fee. You pay standard token prices, and the quoted cited_text does not count toward output tokens.
Which Claude models support citations?
All active models, including Fable 5.2, Opus 5.5, Sonnet 5.5, Haiku 5.5 and Haiku 4.5. No beta header is required.
Can I use citations with structured outputs or JSON mode?
No. Sending output_config.format with citations enabled returns a 400 error. Ask for field: value lines instead and parse them.
Can Claude cite images or scanned PDFs?
No. Claude can only cite text. A scanned PDF with no text layer needs OCR before citations will work.
What is the difference between a custom content document and a search result?
Both cite whole text blocks. A search result also carries a source URL or ID and returns it in each citation, which makes it the better choice for RAG.
Do citations work with streaming?
Yes. Each citation arrives as a citations_delta, and the Python SDK exposes it as a "citation" event.
Can I cache documents that have citations enabled?
Yes. Add cache_control to the document or search result block. The source text is cached, which makes follow-up questions much cheaper.



