Sub topic 9
Sending a PDF directly
This chapter assumes you can call an LLM chat API from Python, you know how to build a JSON request body, and you have read the earlier chapters on content blocks and base64 encoding. It covers the native PDF path: giving the provider the whole file and letting it read the text and the page visuals.
What "native" PDF input means
When you send a PDF natively, you do not extract text or render pages yourself. The provider does that work. A typical provider pipeline does two things for each page:
- It extracts any embedded text from the page.
- It renders the page as an image, so the model can also see charts, tables, scanned content and layout.
The model then receives both the text and the page image. This is why native input can answer questions about a chart on page 4 that has no text equivalent, and why it costs more than text extraction alone.
The PDF travels in the same message as your question. It is one more typed content block, next to the text block.
Building the request
The helper from the earlier chapter reads a file and returns its media type and base64 text. For a PDF, the media type is application/pdf. The example below uses the Anthropic Messages API, where the PDF goes in a document block.
import base64
import mimetypes
import anthropic
def load_as_base64(path):
"""Return (media_type, base64_text) for a local file."""
media_type, _ = mimetypes.guess_type(path)
if media_type is None:
raise ValueError(f"Cannot determine media type for {path}")
with open(path, "rb") as f:
data = base64.standard_b64encode(f.read()).decode("utf-8")
return media_type, data
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
media_type, data = load_as_base64("report.pdf") # media_type is application/pdf
message = client.messages.create(
model="MODEL_NAME", # replace with a model that supports PDF input
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "document",
"source": {
"type": "base64",
"media_type": "application/pdf",
"data": data,
},
},
{"type": "text", "text": "Summarize the key findings in this report."},
],
}
],
)
print(message.content[0].text)Three details matter here:
- The block type is
document, notimage. Sending a PDF in animageblock fails because PDF is not an image format. - The
media_typemust match the real bytes. A file that is not a valid PDF produces a request error even if its name ends in.pdf. - The text block comes after the document. The next chapters on prompt placement explain why putting the question after the material usually works better.
Other ways to supply the PDF
Base64 is the simplest option, but it is not the only one. Many providers accept a URL source, where the provider downloads the file. Some also accept a file ID from a file upload API, so you upload once and reference the file in many requests.
| Source | Request size | Best for | Watch out for |
|---|---|---|---|
| Base64 | Grows about 33% over the raw file | One-off requests, private files | Request body size limits |
| URL | Small | Public documents | The URL must be reachable by the provider |
| File ID | Small | Asking many questions about one file | Provider-specific retention rules |
Field names differ between providers, so check the current documentation for the exact shape. The structure is the same everywhere: a typed block that names a source and a media type.
Limits you will hit
Providers set limits on PDF input. The exact numbers change, so look them up before you design around them. Expect limits of these kinds:
- Maximum file size in megabytes, applied to the whole request, not only the PDF.
- Maximum number of pages per request.
- A cap on the total context window, since every page consumes tokens.
- Restrictions on encrypted or password-protected files, which are usually rejected.
Because base64 inflates the file by about a third, a PDF that is just under the raw file limit can still exceed the request size limit. Measure the encoded length before sending.
def check_pdf_size(path, max_request_bytes):
"""Fail early if the base64 payload would exceed the request limit."""
media_type, data = load_as_base64(path)
if media_type != "application/pdf":
raise ValueError(f"{path} is {media_type}, not a PDF")
encoded_bytes = len(data.encode("utf-8"))
if encoded_bytes > max_request_bytes:
raise ValueError(
f"Encoded PDF is {encoded_bytes} bytes; limit is {max_request_bytes}"
)
return media_type, dataPass the limit from the provider's documentation as max_request_bytes. Do not hard-code a number you read months ago.
Cost and latency
A native PDF costs more than the text it contains. Each page contributes text tokens and image tokens. A 40-page report can use tens of thousands of tokens before you write a single word of prompt. This has three consequences:
- Latency rises with page count, because the model has more input to process.
- If you ask ten questions about the same PDF, you pay for the pages ten times unless the provider offers prompt caching or file reuse.
- A long PDF leaves less room in the context window for the answer and for conversation history.
If you only need part of a document, cut it down first. A page-range split with a PDF library is cheap, and it lowers cost and noise at the same time.
import fitz # PyMuPDF
def extract_page_range(src_path, dst_path, first_page, last_page):
"""Copy pages first_page..last_page (1-based, inclusive) to a new PDF."""
with fitz.open(src_path) as src, fitz.open() as dst:
dst.insert_pdf(src, from_page=first_page - 1, to_page=last_page - 1)
dst.save(dst_path)
extract_page_range("report.pdf", "report_excerpt.pdf", 5, 12)Asking good questions about a PDF
Native input makes the model see the document, but your prompt still controls the result. A few habits help:
- Refer to pages when you can: "On the page with the revenue table, what is the total for 2023?"
- Ask for the location of each answer: "Quote the sentence and give the page number." This makes errors easier to find.
- Say what to do when the answer is missing: "If the document does not state this, reply
not stated." Without this instruction, models sometimes guess. - Keep one task per request when accuracy matters. A request that asks for a summary, a table extraction and a risk review tends to do each part worse.
Edge cases and failure modes
- Scanned PDFs. A scan has no embedded text, only page images. Native input still works because the model reads the images, but small or blurry print can be misread. Numbers are the most common casualty.
- Mixed content. If a PDF has embedded text that differs from what is drawn on the page, for example a bad OCR layer on a scan, the model may see two conflicting versions.
- Very wide tables. A table that spans a landscape page is rendered at reduced size, so tiny digits may be wrong. Rendering that page yourself at higher resolution, as covered in the next chapter, can help.
- Hidden text. Text can be invisible to a human reader but present in the extracted layer. That is a risk for prompt injection, so treat document content as data, never as instructions to the model.
- Errors from the API. Typical failures are an invalid or encrypted PDF, a payload that is too large, too many pages, or a model that does not support PDF input. Read the error message. It usually names the limit you crossed.
Summary of when native input fits
Native PDF input is a good default when the document mixes text with charts, tables or scans, and when the page count is modest. It is a poor fit for very long documents, for pure-text files where plain extraction is cheaper, and for files with strict privacy needs where you do not want to send page images to a third party. The chapter on choosing between extraction, page images and native input returns to these trade-offs.
Exercise
A 60 MB PDF is under a provider's 100 MB request limit. Why might the base64 request still be rejected, and what two steps can you take?
Show answer
Base64 makes the payload about 33% larger, so 60 MB becomes roughly 80 MB, and the JSON wrapper and the other content in the request add more. Depending on the provider's actual limits, the request can still exceed the size cap or the page limit. Measure the encoded size before sending. Then reduce the input by splitting out only the pages you need, or switch to a file upload or URL source so the body stays small.
Exercise
You send a scanned invoice as a native PDF and the model reports a total of 1,840.00, but the printed total is 1,640.00. Give two changes that make this error easier to catch or less likely.
Show answer
Ask the model to quote the line it read and give the page number, so you can compare it to the file. Render that page yourself at a higher DPI and send it as an image, so small digits are clearer. You can also ask for the line items and check that they sum to the total in code.