← Blog

Claude API RAG Pipeline Integration Example

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

What a Claude RAG pipeline actually looks like

Retrieval-Augmented Generation (RAG) with Claude means you fetch relevant documents from your own data store, inject them into the prompt, and let Claude generate an answer grounded in that content instead of relying purely on what it learned during training. The core pattern is the same regardless of vector database or framework: embed → retrieve → construct prompt → call Claude → return answer with sources.

This article walks through a concrete integration example — from chunking documents to streaming the final answer — using plain HTTP calls so you can adapt it to any stack (Node.js, Python, Go) without being locked into a specific RAG framework. We'll also cover the parts most tutorials skip: context window budgeting, citation formatting, and what to do when retrieval returns noisy or irrelevant chunks.

Step 1: Chunk and embed your documents

Before Claude ever sees a request, you need a retrieval layer. This part doesn't involve Claude at all — it's standard embedding infrastructure:

  1. Split source documents into chunks (300–800 tokens works well for most technical content).
  2. Generate embeddings for each chunk using any embedding model.
  3. Store vectors in a vector database (Pinecone, Weaviate, pgvector, Qdrant — the choice doesn't affect the Claude integration pattern).
  4. At query time, embed the user's question and retrieve the top-k most similar chunks.
// pseudocode for retrieval step
const queryEmbedding = await embed(userQuestion);
const matches = await vectorDB.query({
  vector: queryEmbedding,
  topK: 5,
  includeMetadata: true,
});
const contextChunks = matches.map(m => m.metadata.text);

Step 2: Build the prompt with retrieved context

The most common mistake in Claude RAG integrations is dumping raw retrieved text into the prompt with no structure. Claude performs noticeably better when context is clearly delimited and the instructions explicitly tell it how to use (and not use) the retrieved material.

const systemPrompt = `You are a support assistant. Answer the user's question
using ONLY the context provided below. If the context doesn't contain
enough information to answer, say so explicitly. Cite the source number
for every claim you make.`;

const contextBlock = contextChunks
  .map((chunk, i) => `[${i + 1}] ${chunk}`)
  .join('\n\n');

const userMessage = `Context:\n${contextBlock}\n\nQuestion: ${userQuestion}`;

This structure does two things: it reduces hallucination by scoping the model's answer to the retrieved text, and it makes citations trivial because each chunk already has a numbered reference.

Step 3: Call Claude with the constructed prompt

Once the prompt is built, the call to Claude is a standard messages request. If you're calling Claude directly through Anthropic, you manage your own API key and rate limits. If you're routing traffic through an application layer — for example when multiple services or team members need access without sharing a raw provider key — a wrapper like SubToAPI gives you an sub_live_... application key with usage metadata per key, which is useful when a RAG pipeline is shared across several internal tools.

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4",
    "max_tokens": 1024,
    "system": "'"$systemPrompt"'",
    "messages": [
      {"role": "user", "content": "'"$userMessage"'"}
    ]
  }'

See the quickstart and messages docs for the full request schema if you're setting this up for the first time.

Step 4: Stream the response for a responsive UI

RAG answers can take a few seconds to generate, especially with longer context windows. Streaming the response token-by-token keeps the UI responsive instead of showing a blank loading state. The streaming contract works the same as a normal chat completion — set "stream": true and consume server-sent events on the client. Full details are in the streaming docs.

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',
    max_tokens: 1024,
    stream: true,
    system: systemPrompt,
    messages: [{ role: 'user', content: userMessage }],
  }),
});

const reader = response.body.getReader();
// process stream chunks and append to UI as they arrive

Step 5: Handle context window budgeting

A common failure mode in RAG pipelines is retrieving too many chunks and blowing past the model's effective context window, or diluting relevant content with noise. Practical rules:

Step 6: Add tool use for dynamic retrieval

Static retrieval (embed once, fetch top-k, done) works for straightforward Q&A. For more complex pipelines — multi-hop questions, or cases where Claude needs to decide whether to search again with a refined query — tool use lets Claude call your retrieval function directly as part of the conversation instead of you pre-fetching everything upfront.

{
  "name": "search_documents",
  "description": "Search the knowledge base for relevant passages",
  "input_schema": {
    "type": "object",
    "properties": {
      "query": { "type": "string" }
    },
    "required": ["query"]
  }
}

Claude can call this tool mid-conversation if the initial context isn't sufficient, then incorporate the new results into its final answer. See the tools docs for the full tool-use request and response cycle.

Production checklist

questions

Do I need a special Claude model for RAG, or does any model work? Any current Claude model handles RAG-style prompts. Larger models follow "answer only from context" instructions more reliably, which matters more than raw capability for grounded Q&A.

How many retrieved chunks should I inject into the prompt? Start with 3–5 chunks and measure answer quality. More chunks rarely help and increase both latency and cost; re-ranking before injection usually beats simply increasing the count.

Can Claude call my retrieval system directly instead of me pre-fetching context? Yes — using tool use, you can expose a search function as a tool and let Claude decide when to call it, which works well for multi-step or ambiguous queries. See the tools documentation for the request format.

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 →