← Blog

Claude API Document Question Answering Tutorial

2026-11-16 · 5 min read · SubToAPI Team

Document question answering means feeding Claude a PDF, contract, report, or knowledge base article and letting users ask natural-language questions about its contents. The Claude API handles this well because of its large context window and strong instruction-following, but getting accurate, well-cited answers requires the right prompt structure and document handling strategy — not just dropping raw text into a chat message.

This tutorial covers two approaches: stuffing the full document into context (best for anything under ~150k tokens) and a retrieval-augmented pattern for larger corpora. You'll see working code for both, plus the prompt patterns that reduce hallucinated answers and keep responses grounded in the source text.

Approach 1: Full document in context

If your document fits comfortably in Claude's context window, this is the simplest and most accurate approach. There's no retrieval step to get wrong — Claude sees everything and answers directly from it.

The key is structuring the prompt so the model treats the document as ground truth and is explicit about what to do when the answer isn't there.

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,
    "system": "You answer questions using ONLY the document provided in the user message. If the answer is not in the document, say so explicitly. Quote the relevant sentence when possible.",
    "messages": [
      {
        "role": "user",
        "content": "<document>\n{{DOCUMENT_TEXT}}\n</document>\n\nQuestion: What is the notice period for terminating this contract?"
      }
    ]
  }'

A few things matter here:

For PDFs, extract text first (with something like pdf-parse in Node or pypdf in Python) rather than sending raw binary — Claude's Messages API works on text content, so clean extraction matters more than the API call itself.

Approach 2: Chunking and retrieval for large documents

Once you're dealing with hundreds of pages or a multi-document knowledge base, stuffing everything into one prompt gets expensive and slow, and relevant details can get buried. The standard fix is retrieval-augmented generation (RAG):

  1. Split the document into chunks — typically 500–1000 tokens, with some overlap so sentences aren't cut mid-thought.
  2. Embed each chunk using an embedding model and store the vectors (a simple in-memory array works for prototypes; use a vector DB like pgvector or Pinecone in production).
  3. Embed the user's question and retrieve the top 3–5 most similar chunks.
  4. Pass only those chunks to Claude, not the full document.
async function answerQuestion(question, chunks, embeddings) {
  const queryEmbedding = await embed(question);
  const topChunks = rankBySimilarity(queryEmbedding, embeddings, chunks, 5);

  const context = topChunks
    .map((c, i) => `<chunk id="${i}">\n${c}\n</chunk>`)
    .join("\n\n");

  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: 800,
      system:
        "Answer using only the provided chunks. Cite the chunk id you used. If none of the chunks answer the question, say so.",
      messages: [
        {
          role: "user",
          content: `${context}\n\nQuestion: ${question}`,
        },
      ],
    }),
  });

  const data = await response.json();
  return data.content[0].text;
}

This pattern scales to arbitrarily large corpora because you only ever send Claude the handful of chunks relevant to a given question, keeping latency and token costs predictable. The tradeoff is that retrieval quality now bottlenecks answer quality — if the right chunk isn't retrieved, Claude can't answer it no matter how good the prompt is. Spend time tuning chunk size and overlap before assuming the model is the problem.

Streaming answers for a better UX

Document Q&A answers can run several hundred tokens, especially with citations. Streaming the response token-by-token makes the interface feel responsive instead of making users stare at a blank screen.

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: 800,
    stream: true,
    system: "Answer using only the provided document.",
    messages: [{ role: "user", content: prompt }],
  }),
});

for await (const chunk of response.body) {
  process.stdout.write(decodeChunk(chunk));
}

Full details on event types and parsing are in the streaming docs.

Putting it behind an API

If you're building this feature into a product, you'll eventually need application-level API keys, usage tracking per customer, and a way for a small team to share access without everyone holding a personal Claude key. That's exactly what SubToAPI adds on top of your existing Claude access: generate sub_live_... keys scoped to your app, get streaming and tool use out of the box, and see per-key usage in one dashboard. Check the quickstart to get a document Q&A endpoint running in a few minutes, or see pricing for Solo, Team, and Scale plans.

Reducing hallucinated answers

Three things consistently improve groundedness in document Q&A:

Full parameter and message format details are in the Messages API docs.

questions

Can Claude read PDFs directly through the API? The Messages API works on text, so extract text from PDFs first using a library like pdf-parse or pypdf, then send the extracted text in your prompt rather than the raw file.

How large a document can I put directly in the prompt? Claude's context window supports very large documents — tens of thousands of words comfortably. Beyond that, use chunking and retrieval so you only send relevant sections per question.

How do I stop Claude from making up answers not in the document? Tell it explicitly in the system prompt to answer only from the provided text and to say when the answer isn't present, and ask it to quote or cite the source — both measurably reduce hallucinated responses.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →