Claude API Document QA System Tutorial
What you'll build
This tutorial shows you how to build a document question-answering system using the Claude API — a tool where users upload PDFs, docs, or text files and ask questions in plain English, getting accurate answers grounded in the source material. This is one of the most common production use cases for Claude: internal knowledge bases, support documentation search, contract analysis, and research assistants all follow the same core pattern.
The architecture has four parts: chunking your documents into retrievable pieces, retrieval of the most relevant chunks for a given question, prompt construction that feeds those chunks to Claude with clear instructions, and answer generation with citations back to the source. None of this requires fine-tuning — Claude's large context window and instruction-following make retrieval-augmented generation (RAG) straightforward to implement without a heavy ML pipeline.
Step 1: Chunk your documents
Long documents need to be split into smaller pieces before they can be searched. A chunk size of 500-1000 tokens with slight overlap (50-100 tokens) works well for most text — large enough to preserve context, small enough to stay relevant.
function chunkText(text, chunkSize = 800, overlap = 100) {
const words = text.split(/\s+/);
const chunks = [];
let i = 0;
while (i < words.length) {
const chunk = words.slice(i, i + chunkSize).join(" ");
chunks.push(chunk);
i += chunkSize - overlap;
}
return chunks;
}
For PDFs, extract text first with a library like pdf-parse before chunking. Keep metadata with each chunk — document name, page number, section heading — so you can cite sources later.
Step 2: Retrieve relevant chunks
You have two reasonable options depending on scale:
Embeddings + vector search. Generate embeddings for each chunk and store them in a vector database (pgvector, Pinecone, or even an in-memory array for small datasets). At query time, embed the question and find the closest chunks by cosine similarity.
Keyword/BM25 search. For smaller document sets (under a few hundred pages), simple keyword matching or a library like lunr.js is often good enough and avoids the complexity of running an embeddings pipeline.
A simple in-memory cosine similarity retriever:
function cosineSimilarity(a, b) {
let dot = 0, normA = 0, normB = 0;
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}
function retrieveTopChunks(queryEmbedding, chunkEmbeddings, chunks, topK = 5) {
const scored = chunks.map((chunk, i) => ({
chunk,
score: cosineSimilarity(queryEmbedding, chunkEmbeddings[i]),
}));
return scored.sort((a, b) => b.score - a.score).slice(0, topK);
}
Start simple. You can always swap in a dedicated vector store later without changing the Claude integration.
Step 3: Build the prompt
This is where most document Q&A systems succeed or fail. The key is to instruct Claude to answer only from the provided context, cite which chunk the answer came from, and explicitly say when the answer isn't in the documents.
function buildPrompt(question, retrievedChunks) {
const context = retrievedChunks
.map((r, i) => `[Source ${i + 1}: ${r.chunk.metadata.doc}]\n${r.chunk.text}`)
.join("\n\n---\n\n");
return `You are a document assistant. Answer the question using only the context below.
If the answer isn't in the context, say "I don't have that information in the provided documents."
Always cite the source number(s) you used, like [Source 1].
Context:
${context}
Question: ${question}`;
}
Step 4: Call the Claude API
Once you have your prompt, send it to Claude. If you're running this through SubToAPI, the request looks exactly like the standard Messages API — you're just pointing at a different base URL with your sub_live_ key instead of managing Claude access directly.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "PROMPT_WITH_CONTEXT_HERE"}
]
}'
For a chat-style document assistant where users ask follow-up questions, stream the response so the UI feels responsive instead of waiting for the full answer. See the streaming docs for the event format.
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,
stream: true,
messages: [{ role: "user", content: prompt }],
}),
});
Full request/response shapes for non-streaming calls are in the Messages API reference.
Step 5: Handle multi-document and follow-up questions
Real document Q&A systems need to handle two tricky cases:
- Multiple documents with overlapping content. Include the document name in each chunk's metadata and instruct Claude to disambiguate ("According to Document A... while Document B states..."). Don't silently merge conflicting sources.
- Conversational follow-ups. Keep the retrieved context plus the conversation history in the messages array across turns, but re-run retrieval for each new question — the relevant chunks for a follow-up are often different from the original question.
const messages = [
{ role: "user", content: buildPrompt(question1, retrieve(question1)) },
{ role: "assistant", content: answer1 },
{ role: "user", content: buildPrompt(question2, retrieve(question2)) },
];
Why wrap this behind an API
Once your retrieval logic is working, the Claude calls themselves are the easy part — but if you're shipping this inside a product with multiple team members or usage tiers, you still need API keys, usage tracking per user, and a way to control spend. Building that from scratch means handling key rotation, rate limits, and billing logic yourself. SubToAPI turns your Claude access into a standard HTTPS API with scoped application keys, streaming, and usage metadata out of the box, so you can focus on the chunking and retrieval logic instead of API plumbing. Check the pricing page or start with the quickstart guide.
Should I use embeddings or just send the whole document to Claude?
If your documents fit comfortably in Claude's context window and you're not dealing with hundreds of files, skipping retrieval and sending the full text directly is simpler and often more accurate. Use chunking and retrieval when document volume grows too large for a single context window or when you need sub-second responses across a large corpus.
How do I stop Claude from hallucinating answers not in the documents?
Explicit prompt instructions matter most: tell Claude to answer only from provided context and to say clearly when information is missing. Lowering temperature toward 0 and requiring source citations in the output also reduces fabricated answers, since Claude has to point to specific text it used.
Can I build this without a vector database?
Yes. For document sets under a few hundred pages, keyword search or an in-memory array with cosine similarity (as shown above) performs well and is far simpler to operate than a managed vector store. Add a dedicated vector database only once retrieval quality or latency becomes a measurable problem.