← Blog

Claude API Knowledge Base RAG Setup Guide

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

What "RAG Setup" Actually Means Here

If you're searching for "Claude API knowledge base RAG setup," you're probably trying to get Claude to answer questions using your own documents — internal wikis, product docs, support tickets, contracts — instead of relying only on what it learned during training. RAG (Retrieval-Augmented Generation) is the pattern for doing that: you store your documents as searchable vectors, retrieve the most relevant chunks for a given question, and inject those chunks into the prompt you send to Claude.

There's no special "RAG mode" in the Claude API itself. You're combining three independent pieces — a chunking/embedding pipeline, a vector store, and a standard Claude completion call — into one request flow. This guide walks through each piece concretely, with working code, so you can go from zero to a functioning knowledge base assistant.

The Architecture at a Glance

A working RAG setup has five stages:

  1. Ingest — pull raw text from your source documents.
  2. Chunk — split text into retrievable pieces (usually 300–800 tokens).
  3. Embed — convert each chunk into a vector using an embedding model.
  4. Store — index vectors in a vector database for similarity search.
  5. Retrieve + generate — at query time, embed the question, find the closest chunks, and pass them to Claude as context.

None of this requires a special framework. A few hundred lines of plain code will get you a solid v1.

Step 1: Chunk Your Documents

Chunk size matters more than most people expect. Chunks that are too large waste context and dilute relevance; chunks that are too small lose coherence. A good default is 400–600 tokens per chunk with 10–15% overlap between adjacent chunks so you don't cut sentences mid-thought at retrieval boundaries.

function chunkText(text, maxTokens = 500, overlap = 60) {
  const words = text.split(/\s+/);
  const chunks = [];
  let start = 0;
  while (start < words.length) {
    const end = Math.min(start + maxTokens, words.length);
    chunks.push(words.slice(start, end).join(" "));
    start += maxTokens - overlap;
  }
  return chunks;
}

Keep track of source metadata (filename, section title, page number) alongside each chunk — you'll need it later for citations.

Step 2: Generate Embeddings

Claude's API does not provide an embeddings endpoint, so you'll pair it with a dedicated embedding model (open-source options like all-MiniLM, or hosted ones from an embeddings provider). Embed every chunk once during ingestion, and embed the user's question once per query.

async function embed(texts) {
  const res = await fetch("https://api.your-embedding-provider.com/v1/embeddings", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ input: texts, model: "embedding-model-v1" })
  });
  const data = await res.json();
  return data.data.map(d => d.embedding);
}

Step 3: Store and Index Vectors

Any vector database works here — Postgres with pgvector, a managed service, or an in-memory index for small datasets. For a knowledge base under a few thousand chunks, even a flat in-memory cosine similarity search is fast enough and avoids extra infrastructure.

create table kb_chunks (
  id serial primary key,
  content text,
  source text,
  embedding vector(384)
);

create index on kb_chunks using hnsw (embedding vector_cosine_ops);

Step 4: Retrieve Relevant Chunks at Query Time

When a user asks a question, embed the query and run a similarity search to pull the top-k chunks (typically 3–8, depending on how dense your content is).

select content, source
from kb_chunks
order by embedding <=> $1
limit 5;

Resist the urge to retrieve too many chunks "to be safe." More retrieved text means more tokens spent, slower responses, and a higher chance Claude gets distracted by irrelevant context.

Step 5: Build the Prompt and Call Claude

This is where the Claude API call happens. Put retrieved chunks in the system prompt or as a clearly labeled context block in the user message, and instruct Claude to answer only from that context — this is the step that actually turns "a chatbot with some text" into "a grounded knowledge base assistant."

If you're routing requests through SubToAPI, the call looks like any other Messages request — the only difference is you're building the content field from your retrieved chunks instead of the raw user question:

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4",
    "max_tokens": 800,
    "system": "Answer only using the provided context. If the answer is not in the context, say you do not know.",
    "messages": [
      {
        "role": "user",
        "content": "Context:\n[chunk 1]\n[chunk 2]\n[chunk 3]\n\nQuestion: How do I reset a user'\''s API key?"
      }
    ]
  }'

SubToAPI sits in front of your existing Claude access and exposes it as a standard HTTPS API with a sub_live_... key, so this part of the pipeline doesn't require separate Anthropic account setup per environment — see the quickstart and Messages API reference for the full request format.

Step 6: Handle Citations and Context Limits

For internal tools, returning the source of each chunk alongside the answer builds trust and makes debugging retrieval quality much easier:

const context = chunks.map((c, i) => `[${i+1}] (${c.source}) ${c.content}`).join("\n\n");

Ask Claude to cite chunk numbers in its answer, then map those back to your source metadata on the client side. Watch your total prompt size — if you're retrieving long chunks or many of them, check your request against the payload limits before it fails in production.

Production Considerations

A few things that matter once this moves past a prototype:

Choosing a Vector Database

For most teams the decision comes down to operational simplicity: pgvector if you already run Postgres, a managed vector service if you want zero infrastructure, or an in-memory index if your knowledge base is small and static. Don't over-architect this early — a flat index with a few thousand chunks performs fine, and migrating later is straightforward since the embeddings and chunking logic don't change.

questions

Does Claude have a built-in RAG or embeddings feature? No. Claude's API handles the generation step only. You need a separate embedding model and vector store; Claude receives the retrieved text as part of the prompt.

How many chunks should I retrieve per query? Start with 3–5 chunks of 400–600 tokens each. Measure answer quality, then adjust — more chunks isn't automatically better and increases token cost and latency.

Can I use RAG with streaming responses? Yes. Retrieval happens before the API call; once you've built the prompt with retrieved context, you can stream the completion normally. See streaming for implementation details.

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 →