← Blog

Claude API RAG Pipeline Tutorial: Build It Step by Step

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

Retrieval-augmented generation (RAG) lets Claude answer questions using your own data instead of relying only on what it learned during training. This guide walks through building a working RAG pipeline with the Claude API: how to chunk and embed documents, retrieve relevant context, and send that context to Claude in a way that produces grounded, citeable answers.

If you're searching for a Claude API RAG pipeline tutorial, you're probably trying to solve one of two problems: Claude doesn't know about your internal docs, product data, or recent events, or you want to reduce hallucinations by forcing responses to be based on retrieved facts. RAG solves both by separating "finding information" (retrieval) from "generating a response" (the LLM call). Below is a complete, minimal pipeline you can adapt.

What a RAG Pipeline Actually Does

A RAG pipeline has four stages:

  1. Ingest — split your documents into chunks.
  2. Embed — convert each chunk into a vector using an embedding model.
  3. Retrieve — at query time, find the chunks most similar to the user's question.
  4. Generate — pass the retrieved chunks plus the question to Claude and get an answer grounded in that context.

Claude handles step 4. Steps 1–3 are infrastructure you build yourself (or with a vector database). Let's go through each stage.

Step 1: Chunk Your Documents

Chunk size matters more than people expect. Chunks that are too large dilute relevance; chunks that are too small lose context. A reasonable starting point is 300–500 tokens per chunk with ~50 token overlap between consecutive chunks so you don't cut sentences off mid-idea.

function chunkText(text, chunkSize = 1500, overlap = 200) {
  const chunks = [];
  let start = 0;
  while (start < text.length) {
    const end = start + chunkSize;
    chunks.push(text.slice(start, end));
    start = end - overlap;
  }
  return chunks;
}

This is character-based, not token-based, but it's good enough to get started. For production, swap in a proper tokenizer so chunk boundaries align with actual token counts.

Step 2: Generate Embeddings

Embed each chunk with any embedding model you have access to (OpenAI, Cohere, Voyage, or a local model). Store the vector alongside the chunk text and some metadata (source document, page number, URL) so you can cite sources later.

async function embedChunks(chunks, embedFn) {
  const results = [];
  for (const chunk of chunks) {
    const vector = await embedFn(chunk);
    results.push({ text: chunk, vector });
  }
  return results;
}

Store these in a vector database — Pinecone, Weaviate, pgvector, or even an in-memory array for small datasets. The embedding model and Claude are independent; nothing about RAG requires using the same vendor for both.

Step 3: Retrieve Relevant Chunks

At query time, embed the user's question and compute similarity (cosine similarity is standard) against your stored vectors. Return the top-k matches, usually 3–8 chunks depending on how much context you can afford to send.

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 retrieveTopK(queryVector, store, k = 5) {
  return store
    .map(item => ({ ...item, score: cosineSimilarity(queryVector, item.vector) }))
    .sort((a, b) => b.score - a.score)
    .slice(0, k);
}

A common mistake is retrieving too many chunks "just in case." More context doesn't reliably improve answer quality — it increases cost and gives Claude more irrelevant text to sift through. Tune k empirically against your actual queries.

Step 4: Send Context to Claude

This is where the Claude API call happens. Build a system prompt that instructs Claude to answer only from the provided context and to say so explicitly when the context doesn't contain the answer.

const context = retrieveTopK(queryVector, store, 5)
  .map((c, i) => `[${i + 1}] ${c.text}`)
  .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",
    system: "Answer the user's question using only the context below. If the context doesn't contain the answer, say you don't have enough information. Cite sources by their bracketed number.",
    messages: [
      { role: "user", content: `Context:\n${context}\n\nQuestion: ${userQuestion}` }
    ],
    max_tokens: 1024
  })
});

const data = await response.json();
console.log(data.content[0].text);

This structure — strict system instructions plus bracketed source citations — is what keeps RAG answers grounded instead of letting Claude fall back on general knowledge when the retrieved context is thin.

If you're running this through SubToAPI, you get the same /v1/messages endpoint with your sub_live_ key, plus usage metadata per request so you can track exactly how many tokens your RAG pipeline consumes across retrieval-heavy queries. See /docs/messages for the full request format and /docs/quickstart if you're setting this up for the first time.

Handling Long Documents and Streaming

If your retrieved context is large or you're building a chat-style interface, stream the response instead of waiting for the full completion. This matters especially in RAG apps where generation can take a few seconds once you've stuffed several chunks into the prompt. SubToAPI supports streaming on the same endpoint — details at /docs/streaming.

Common Pitfalls

questions

Do I need a vector database to build a RAG pipeline with Claude? Not for small datasets — an in-memory array with cosine similarity works fine for a few thousand chunks. For production scale, use a dedicated vector database like Pinecone or pgvector.

Can Claude generate embeddings itself? No, Claude is a generation model, not an embedding model. You need a separate embedding model (OpenAI, Voyage, Cohere, or open-source) for the retrieval step.

How many retrieved chunks should I send to Claude per query? Start with 3–8 chunks and tune based on answer quality and cost. More chunks isn't automatically better — irrelevant context can dilute the answer.

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 →