Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
Four documented ways to put your data in front of Claude: a PDF document block, a file uploaded once and sent by file_id, search_result blocks from your own retrieval, and citations on every claim. Then mixed formats in one request, and how to read a 400 or 413 when a file is refused.
What you will learn
- Send a PDF to Claude as a document block, inline as base64 or by file_id
- Upload a file once with the Files API and pick the right block for each file type
- Return your own retrieval hits as search_result blocks and read the citations that come back
- Diagnose a 400 or 413 from an ingestion request by reading the status, then the file's metadata
Before you start
- The Claude Messages API: your first call
- Claude tool use: tool_use and tool_result
- Basic Python
A support agent answers questions from the shop's returns policy. The policy is a PDF. Sometimes it's a handful of snippets from your own search. And a customer who asks "can I return a sale item?" deserves to see where the answer came from.
Three problems show up in a first version: the same PDF is sent again with every request, retrieved snippets are pasted in as plain text, and the answers come back with no source. The result is slow, costly and hard to trust. The Claude docs describe one option for each problem: PDF support, the Files API, search results and citations. This article walks through all four in a small SupportDesk project, then follows a claims agent that sends three file types in one request and learns to read the error when a file is refused.
Answering from a handbook
Picture a colleague who has to answer from a handbook. You can get the book in front of them in four ways:
- Hand over a photocopy, every time. That's sending the PDF inline.
- Put the book in a locker once and hand out the locker number. That's the Files API, and the number is the
file_id. - Ask a librarian, who brings back only the matching pages. Those are search results.
- Ask the colleague to flag the page they read. That's citations.
Same handbook, four ways in. You choose by where the book lives, and whether the customer must see the page.
Four ways to get data in
| Option | What you send | Use it when |
|---|---|---|
| PDF support | A document block with a base64 or URL source | One PDF, one request. Claude reads the text and the page images. |
| Files API | Upload once (up to 500 MB a file), then a document block with a file source and the file_id | The same file goes into many requests |
| Search results | search_result blocks: a source, a title and the content | Your own retrieval returns snippets |
| Citations | "citations": {"enabled": true} on the block | Each claim must point back to its source |
The first two move files. The third moves snippets. The fourth adds the source to the answer.
blocks.py: three content blocks
Everything reaches Claude as a content block in the user message. The project builds the three blocks in one small file:
"""Three ways to hand Claude your data. Each function returns one content block."""
import base64
import pathlib
TITLE = "Returns policy"
def pdf_inline(path):
raw = pathlib.Path(path).read_bytes()
data = base64.standard_b64encode(raw).decode()
return {"type": "document", "title": TITLE,
"source": {"type": "base64",
"media_type": "application/pdf",
"data": data},
"citations": {"enabled": True}}
def pdf_by_id(file_id):
return {"type": "document", "title": TITLE,
"source": {"type": "file", "file_id": file_id},
"citations": {"enabled": True}}
def search_result(source, title, text):
return {"type": "search_result", "source": source,
"title": title,
"content": [{"type": "text", "text": text}],
"citations": {"enabled": True}}
pdf_inline: the source type isbase64, so the bytes ride along in the request.pdf_by_id: the source type isfile, and only the id travels.search_result: a source, a title, and the content as text blocks.- Every block switches citations on.
feed.py: where the data goes in
The data feed uploads once, asks by id, and runs a search tool. Here are the parts that matter (the full file is in the project):
def upload(client, path):
with open(path, "rb") as f:
up = client.files.upload(file=(NAME, f, "application/pdf"))
return up.id
def ask_by_id(client, file_id, question):
doc = blocks.pdf_by_id(file_id)
return ask(client, [doc, {"type": "text", "text": question}])
def search_policies(query):
words = set(query.lower().split())
hits = [k for k in KB if words & set(k[2].lower().split())]
return [blocks.search_result(*k) for k in hits]
def ask_with_search(client, question):
msgs = [{"role": "user", "content": question}]
r = ask_tools(client, msgs)
use = next(b for b in r.content if b.type == "tool_use")
results = search_policies(use.input["query"])
msgs += [{"role": "assistant", "content": r.content},
{"role": "user", "content": [{
"type": "tool_result",
"tool_use_id": use.id,
"content": results}]}]
return ask_tools(client, msgs)
def citations(r):
"""Every citation on every text block."""
return [(b.text, c) for b in r.content if b.type == "text"
for c in (b.citations or [])]
Three things to notice:
uploadruns once and hands back a file id. Later requests build the document from that id and nothing else. The Files API lives atclient.filesin the current SDK.- For search, Claude first asks for your tool. Your own retrieval runs, and the hits go back inside the
tool_resultassearch_resultblocks, not as pasted text. (The tool round trip itself is covered in Claude tool use: tool_use and tool_result.) - When the answer arrives, the citations are read off each text block.
What each request carried
The project runs against a stand-in: the real Anthropic SDK talks to an httpx mock transport that answers like the Messages and Files APIs. The replies are scripted, but the request sizes are measured from the real request bodies of a small two-page demo PDF.
inline PDF request 1728 bytes | page_location p.1
upload request 1261 bytes | file_test_0001
file_id request 264 bytes | page_location p.2
search result request 903 bytes | search_result_location kb://sale-items
2 results sent, 1 cited: Sale items
citations + structured output -> 400 invalid_request_error
Reading the run line by line:
- The inline PDF answer cites page 1, with a
page_locationcitation. - The upload prints a file id, once.
- By file id, the request shrinks from 1728 to 264 bytes, and the answer cites page 2.
- Two search results were sent, and the answer cited one of them by its source,
kb://sale-items. - The last line: citations plus a structured output format is a 400. You have to choose one of the two.
A citation points back
A cited answer comes back as text blocks, and each block carries a list of citations. A PDF citation holds the cited text, the document title, and a start and end page. The end page is exclusive, so start_page_number: 2, end_page_number: 3 means page 2. The cited text doesn't count toward output tokens.
The citation type follows the source you sent:
| Source | Citation type |
|---|---|
| Plain text document | char_location |
| PDF document | page_location |
| Custom content document | content_block_location |
search_result block | search_result_location |
That's how the run could print p.2 for the PDF and kb://sale-items for the search hit: the answer carries where each claim came from. For the wider question of what a citation proves in a retrieval app, see Citations and abstention in RAG.
Mixed formats: the file type picks the block
Now a second use case from the follow-up lecture. A claims agent reviews damage claims. Each claim comes with a policy PDF, a photo of the box and a notes file, and they must travel together in one request.
Think of a parcel depot. You leave a parcel once and get a ticket (the file id). Later you show the ticket, not the parcel. Each kind of parcel has its own counter, and a parcel can be refused at the desk: wrong counter, or too heavy.
| File | MIME type | Input block | Watch for |
|---|---|---|---|
application/pdf | document | No password; up to 600 pages on current models | |
| Plain text | text/plain | document | Upload it as text/plain |
| Image | jpeg, png, gif, webp | image | All four take the same block |
| Word, Excel | .docx, .xlsx | none | Convert to text or PDF first |
| Other data files | other types | none | Goes to the code execution tool as a container upload |
The project's blocks.py turns that table into one function, and refuses an unknown type before any request is sent:
"""Pick the input block for a file, by its type. Each function returns a block."""
import base64
import pathlib
IMAGES = ("image/jpeg", "image/png", "image/gif", "image/webp")
DOCS = ("application/pdf", "text/plain")
def block_type(mime):
if mime in IMAGES:
return "image"
if mime in DOCS:
return "document"
raise ValueError(f"{mime}: convert to text or PDF first")
def by_id(file_id, mime):
return {"type": block_type(mime),
"source": {"type": "file", "file_id": file_id}}
def inline(path, mime):
raw = pathlib.Path(path).read_bytes()
data = base64.standard_b64encode(raw).decode()
source = {"type": "base64", "media_type": mime, "data": data}
return {"type": block_type(mime), "source": source}
def as_text(label, text):
return {"type": "text", "text": f"{label}:\n{text}"}
Image blocks and the base64 options are covered in more depth in images, PDFs and thinking blocks. Here the point is the rule: the block type has to match the file's MIME type, whether you send bytes or an id.
ingest.py: upload once, diagnose a refusal
The intake uploads each file once, puts many files in one request by id, and names the fault when a request fails:
def ask_mixed(client, files, question):
content = [blocks.by_id(fid, mime) for fid, mime in files]
content.append({"type": "text", "text": question})
return ask(client, content)
def diagnose(client, content, err):
"""Name the fault from the status code and the file's own metadata."""
if err.status_code == 413:
return "size limit: send the big file by file id"
for b in content:
src = b.get("source", {})
if src.get("type") != "file":
continue
mime = client.files.retrieve_metadata(src["file_id"]).mime_type
try:
want = blocks.block_type(mime)
except ValueError:
return "unsupported format: convert to text or PDF first"
if want != b["type"]:
return f"wrong block type: {want} block needed for {mime}"
return "no file fault found"
The method is the same every time: read the status first. A 413 means size. Otherwise read the file's own metadata to learn its real type, and compare it with the block you sent.
The run uploads three files, sends one mixed request, then builds three faulty requests on purpose (again against the stand-in, whose size cap is set to 50,000 bytes so a 413 fits on a laptop):
upload returns_policy.pdf application/pdf file_test_0001
upload damaged_box.png image/png file_test_0002
upload agent_notes.txt text/plain file_test_0003
by file id request 360 bytes | document image document text
inline request 2385 bytes | document image document text
fault 1: 400 invalid_request_error
wrong block type: image block needed for image/png
fault 2: 400 invalid_request_error
unsupported format: convert to text or PDF first
fault 3: 413 request_too_large
size limit: send the big file by file id
fixed: docx as a text block -> end_turn
fixed: big scan by file id -> end_turn
Three file types travel in one request: a document, an image, another document and the text question. By id, that request is 360 bytes; inline, the same files make it 2385. Then the three faults:
| Symptom | Cause | Fix |
|---|---|---|
| 400, wrong block type | An image file sent in a document block | Match the block to the file type |
| 400, unsupported format | A Word file sent in a document block | Convert to text or PDF, or send the text as a text block |
| 413, request too large | A big scan sent inline as base64 | Upload once and send the file id |
Retrying the same request won't help with any of these. Each one is fixed by changing the request.
Common mistakes
- Trusting a file id typed by a user. Files are shared across the workspace, so any key there can read any file. Keep the map from user to file on your own server.
- Citations together with a structured output format. The API answers with a 400, as the run showed. Pick one.
- Expecting citations from a scanned PDF. With no extractable text, there's nothing to cite.
- Mixed citation settings across search results. All
search_resultblocks in one request must use the same setting. - Pasting retrieved snippets as plain text. Send them as
search_resultblocks, so the answer can cite them. - Resending the whole PDF on every turn. Upload it once and send the id.
Quick recap
| The case | The input |
|---|---|
| A photo of a cracked box | image block |
| The signed policy, a PDF | document block |
| Agent notes in a text file | document block, text/plain |
| The same PDF in every request | Upload once, send the file_id |
| A customer letter in Word | Convert it, then a text block |
| Snippets from your own search | search_result blocks in the tool_result |
| The customer must see the source | citations: {enabled: true} |
Choose the way in by where the data lives, and keep the source on every claim.
Try it yourself
Add a fourth policy article to KB in feed.py, for example one about gift cards, and ask "Can I return a gift card?". Which search_result blocks does search_policies send, and which source should the citation point to?
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.