Build a Claude API Document Question Answering App
A document question answering app lets users upload a PDF, contract, report, or knowledge base article and ask natural-language questions about its content instead of searching or reading manually. You build it by sending the document text (or relevant chunks of it) to Claude along with the user's question, and letting the model answer strictly from that context.
This article walks through the actual architecture: how to get document text into the model, how to handle documents too large for a single context window, how to structure the prompt so Claude answers accurately instead of hallucinating, and how to wire it all up with working code.
The core pattern
At its simplest, document Q&A is three steps:
- Extract text from the source document (PDF, DOCX, HTML, plain text).
- Send that text plus the user's question to Claude in a single prompt.
- Return Claude's answer, ideally with a citation of where in the document it came from.
For short documents (a few pages), you can pass the full text directly. For anything longer — contracts, manuals, research papers — you need a chunking or retrieval step before the API call, because even Claude's large context window has limits and stuffing an entire 200-page PDF into every request is slow and expensive.
Step 1: extract and prepare the text
Use a PDF/text extraction library (pdf-parse, pdfplumber, or similar) to pull raw text out of the uploaded file. Clean it up: strip headers/footers, collapse excessive whitespace, and keep page or section markers if you want to cite them later.
import pdf from "pdf-parse";
import fs from "fs";
async function extractText(filePath) {
const buffer = fs.readFileSync(filePath);
const data = await pdf(buffer);
return data.text;
}
Step 2: chunk long documents
If the document fits comfortably within context (roughly under 20–30 pages of dense text), skip chunking entirely and send it whole — this is simpler and avoids retrieval errors. For longer documents, split into overlapping chunks (e.g. 1,000–1,500 tokens with 100-token overlap) and store them with an identifier (page number, section title).
function chunkText(text, size = 4000, overlap = 400) {
const chunks = [];
for (let i = 0; i < text.length; i += size - overlap) {
chunks.push(text.slice(i, i + size));
}
return chunks;
}
For retrieval, embed each chunk and the user's question, then select the top-N most similar chunks to include in the prompt. This is a lightweight RAG approach — you don't need a full vector database for small apps; an in-memory cosine-similarity search over a few hundred chunks works fine.
Step 3: build the prompt
The quality of document Q&A depends heavily on prompt structure. Be explicit that Claude should only answer from the provided text and should say so when the answer isn't present — this prevents confident-sounding hallucinations.
const systemPrompt = `You are a document assistant. Answer the user's question
using only the document excerpts provided below. If the answer is not
present in the excerpts, say "I couldn't find that in the document."
Cite the section or page number when possible.`;
const userPrompt = `Document excerpts:
${relevantChunks.join("\n---\n")}
Question: ${question}`;
Step 4: call the API
Here's a working request against SubToAPI's /messages endpoint, which forwards to your Claude access through a standard API key:
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
system: systemPrompt,
messages: [{ role: "user", content: userPrompt }],
}),
});
const data = await response.json();
console.log(data.content[0].text);
If you're new to the API shape, the quickstart and messages docs cover request/response formats in full, and the same sub_live_... key works across your entire app without touching provider-specific credentials.
Handling multi-document and follow-up questions
Real document Q&A apps rarely stop at one question. Two things matter for usability:
- Conversation continuity. Keep the message history (previous questions and answers) in the
messagesarray so follow-ups like "what about clause 4?" resolve correctly without re-explaining context. - Streaming responses. For longer answers, stream tokens back to the UI instead of waiting for the full response. This matters a lot for perceived speed when answering questions about dense legal or technical text. See streaming docs for the event format.
const stream = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
stream: true,
system: systemPrompt,
messages: conversationHistory,
}),
});
Adding structured extraction with tools
If your app needs more than freeform answers — say, pulling structured fields like dates, amounts, or parties from a contract — define a tool schema and have Claude return JSON instead of prose. This is useful for building searchable metadata alongside the Q&A interface. The tools docs explain how to define a schema and parse the tool-call response reliably.
Why route this through an API gateway
Document Q&A apps tend to run a lot of requests per document (initial parse, multiple questions, follow-ups), often from more than one developer or environment. Running everything through SubToAPI gives you per-application keys instead of shared raw credentials, usage metadata so you can see which documents or features are driving cost, and team seats if more than one person is building against the same Claude access. Setup takes a few minutes — sign up, generate a key, and point your existing fetch/curl calls at api.subtoapi.app.
Common pitfalls to avoid
- Sending the whole document on every follow-up question. Cache extracted text and only re-send relevant chunks, not the full document, on each turn.
- No "I don't know" instruction. Without it, Claude will sometimes extrapolate beyond the document rather than admitting the answer isn't there.
- Ignoring document structure. Preserving page numbers and headings in your chunks makes citations possible and builds user trust in the answers.
- Treating OCR’d scans as clean text. Scanned PDFs need OCR cleanup before chunking, or answers degrade significantly.
questions
Do I need a vector database to build document Q&A with Claude? No, not for small-to-medium apps. Short documents can be sent whole; longer ones can use a simple in-memory similarity search over chunks before falling back to a dedicated vector store if scale demands it.
How do I stop Claude from making up answers not in the document? Use an explicit system prompt instructing it to answer only from the provided excerpts and to say when information isn't present — this single instruction removes most hallucination issues.
Can I build this without managing Anthropic API keys directly? Yes. Services like SubToAPI issue standard sub_live_... keys that proxy to your existing Claude access, so your app code, streaming, and tool calls work the same way without handling provider credentials directly.