← Blog

Claude API RAG Tutorial: Build Retrieval-Augmented Generation

2026-11-13 · 6 min read · SubToAPI Team

What this tutorial covers

If you're searching for a Claude API retrieval augmented generation tutorial, you want to know how to feed Claude relevant external documents at query time so it answers questions using your data instead of hallucinating from training memory. This article walks through the actual mechanics: splitting documents into chunks, generating embeddings, retrieving the most relevant chunks for a given query, and injecting them into a Claude prompt in a way the model can use reliably.

RAG is not a Claude-specific feature — it's an architecture pattern you build around any LLM API. Claude doesn't search your documents automatically; you retrieve the relevant text yourself and pass it in the request. This guide builds that pipeline step by step, with working code, so you understand what's actually happening before you reach for a framework.

The RAG pipeline in four stages

A working RAG system has four moving parts:

  1. Chunking — splitting source documents into pieces small enough to embed and retrieve individually
  2. Embedding — converting each chunk into a vector that represents its meaning
  3. Retrieval — finding the chunks most similar to the user's query at request time
  4. Generation — passing the retrieved chunks to Claude as context and asking it to answer using them

Get chunking and retrieval wrong and no amount of prompt engineering fixes it. Claude can only answer well if the right text actually makes it into the context window.

Step 1: Chunk your documents

Chunk size matters more than most tutorials admit. Too large, and retrieval pulls in noise alongside the relevant sentence. Too small, and you lose surrounding context the model needs to interpret a fact correctly.

A reasonable starting point for prose documents is 300–500 tokens per chunk with a small overlap (50–100 tokens) so sentences aren't cut mid-thought:

function chunkText(text, chunkSize = 400, overlap = 80) {
  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 structured content (FAQs, API docs, support tickets) chunk by natural boundaries — one chunk per Q&A pair or per section — instead of a fixed word count. Structure-aware chunking almost always outperforms naive splitting.

Step 2: Generate embeddings

Each chunk needs a vector embedding so you can compare it mathematically to a query. Claude's API doesn't provide an embeddings endpoint, so you'll use a dedicated embedding model (OpenAI's text-embedding-3-small, Voyage AI, or a local model like bge-small) purely for this step. Store the vector alongside the chunk text and its source metadata:

async function embed(text) {
  const res = await fetch("https://api.openai.com/v1/embeddings", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
    },
    body: JSON.stringify({
      model: "text-embedding-3-small",
      input: text,
    }),
  });
  const data = await res.json();
  return data.data[0].embedding;
}

Store { id, text, embedding, source } objects in a vector database (Pinecone, Weaviate, pgvector, or even an in-memory array for a prototype).

Step 3: Retrieve relevant chunks

At query time, embed the user's question and compare it to every stored chunk using cosine similarity. Return the top-k matches:

function cosineSimilarity(a, b) {
  const dot = a.reduce((sum, v, i) => sum + v * b[i], 0);
  const magA = Math.sqrt(a.reduce((s, v) => s + v * v, 0));
  const magB = Math.sqrt(b.reduce((s, v) => s + v * v, 0));
  return dot / (magA * magB);
}

async function retrieve(query, chunks, topK = 4) {
  const queryEmbedding = await embed(query);
  return chunks
    .map((c) => ({ ...c, score: cosineSimilarity(queryEmbedding, c.embedding) }))
    .sort((a, b) => b.score - a.score)
    .slice(0, topK);
}

Four chunks is a sensible default. More context isn't always better — irrelevant chunks dilute the signal and increase cost without improving accuracy.

Step 4: Build the Claude prompt

This is where the API call happens. Put retrieved chunks in the system prompt or as the first part of the user message, clearly labeled, and instruct Claude to answer only from the provided context:

async function askWithContext(query, retrievedChunks) {
  const context = retrievedChunks
    .map((c, i) => `[${i + 1}] ${c.text}`)
    .join("\n\n");

  const response = await fetch("https://api.subtoapi.app/v1/messages", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.SUBTOAPI_KEY}`,
    },
    body: JSON.stringify({
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      system:
        "Answer the user's question using only the context below. If the context doesn't contain the answer, say so explicitly. Cite sources using [1], [2] etc.",
      messages: [
        { role: "user", content: `Context:\n${context}\n\nQuestion: ${query}` },
      ],
    }),
  });

  return response.json();
}

We're using SubToAPI here because it exposes Claude through a standard HTTPS endpoint with an application API key (sub_live_...), which makes it simple to call from a backend without juggling a direct Anthropic subscription. Usage and token counts are tracked per key automatically, which matters for RAG apps where every request includes a retrieved-context payload that can vary a lot in size. See the quickstart and messages docs for the full request format.

Handling cost and context size

Retrieved context adds tokens to every request, and that's where RAG costs creep up. A few practical controls:

If you're running RAG across a team, routing every request through a shared gateway also makes it easier to track which app or environment is driving retrieval costs — check pricing if you're evaluating that for a production setup.

Common mistakes

Not telling Claude what to do when context is insufficient. Without an explicit instruction, the model will sometimes fill gaps with general knowledge, which defeats the point of RAG. Always include a fallback instruction like "say you don't have enough information."

Retrieving too much context "just to be safe." This increases both cost and the chance Claude gets distracted by irrelevant chunks. Tune topK empirically against real queries, not instinct.

Re-embedding on every request instead of caching. Document embeddings should be computed once at ingestion time and stored. Only the user's query needs to be embedded live.

Getting started

Try the pipeline above with a small document set first — a handful of markdown files or FAQ entries is enough to validate chunking and retrieval quality before scaling to a full vector database. Once retrieval is solid, swapping in Claude for generation is a single API call. Sign up for a free trial to test the generation step against your own retrieved context.

Questions

Does Claude have a built-in RAG or search feature? No. Claude's API answers based on whatever text you include in the prompt. You're responsible for retrieving relevant chunks yourself and passing them in as context.

What's the best chunk size for RAG with Claude? 300–500 tokens per chunk with 50–100 tokens of overlap works well for prose. For structured content, chunk by natural boundaries like sections or Q&A pairs instead of a fixed size.

Can I build RAG without a vector database? Yes, for small document sets. An in-memory array with cosine similarity, like the example above, works fine for prototypes or datasets under a few thousand chunks. Move to a dedicated vector database once retrieval latency or data volume grows.

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 →