Ask about a PDF
A conversation that reads a PDF once and answers follow-up questions about it. The model reads the file itself, so there is no text extraction and no index.
use freyja::{Agent, Client, EndpointPreset, InputContent, Message, Retry, Role};
let client = Client::from_env(EndpointPreset::Anthropic)?;
let agent = Agent::new(Retry::new(client, |wait| tokio::time::sleep(wait)))
.system("Answer only from the attached document. When it does not say, answer: not stated.");
let mut chat = agent.conversation(Vec::new());
let pdf = std::fs::read("contract.pdf")?;
let first = chat
.send(Message::new(
Role::User,
[
InputContent::file(pdf, "application/pdf"),
InputContent::Text("What is the notice period?".into()),
],
))
.await?;
println!("{}", first.answer);
let second = chat.send("Does it say who pays for repairs?").await?;
println!("{}", second.answer);
println!("{} of {} input tokens read from cache", second.usage.cached_input_tokens, second.usage.input_tokens);
The PDF goes in once, on the first turn, and the conversation keeps it in the transcript. Every later question is sent with it, so the model can answer from the whole document each time.
That resend is what prompt caching pays for. Anthropic caches the transcript on every turn, so the follow-up reads the PDF back at a tenth of the input price. On a one-page PDF the second question read 1,657 of its 1,677 input tokens from cache. OpenAI and Gemini cache on their own. See Prompt caching.
Retry repeats a call the provider failed with an overload or a rate limit, so a busy moment does not end the conversation. The system prompt keeps answers to the document, and "not stated" gives the model something to say other than a guess.
Vec::new() keeps the conversation in memory. Use JsonlStorage::open(path) to keep it across restarts, as in Long conversations.
When to index instead
Send the file when the questions are about one document and it fits the model's context: a contract, a report, a paper. A long PDF costs about 1,600 tokens a page on every turn, even when cached reads make each one cheap.
Index the text instead when the answers are spread across many documents, or when one is too long to send whole. Search then sends only the few passages a question needs. See Load documents into an index.
PDF is the type every provider reads. See Files for the others.