← Blog

Claude API RAG Pipeline: LangChain Tutorial

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

Building a RAG pipeline with Claude and LangChain

Retrieval-augmented generation (RAG) lets Claude answer questions using your own documents instead of relying only on what it learned during training. The pattern is: split your documents into chunks, embed them, store the embeddings in a vector database, retrieve the most relevant chunks for a given question, and pass those chunks to Claude as context alongside the user's prompt.

LangChain gives you the plumbing for all of that — document loaders, text splitters, vector store integrations, and chains that wire retrieval and generation together — while Claude handles the actual reasoning and answer generation. This tutorial walks through a working pipeline end to end: loading documents, chunking, embedding, retrieving, and generating answers with Claude through the Anthropic API.

What you need before starting

pip install langchain langchain-anthropic langchain-community chromadb

Step 1: Load and split your documents

LangChain's text splitters handle chunking so you don't retrieve whole documents when only a paragraph is relevant.

from langchain_community.document_loaders import TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter

loader = TextLoader("docs/product_handbook.txt")
documents = loader.load()

splitter = RecursiveCharacterTextSplitter(
    chunk_size=800,
    chunk_overlap=100
)
chunks = splitter.split_documents(documents)

Chunk size is a tradeoff: smaller chunks retrieve more precisely but lose surrounding context; larger chunks carry more context but dilute relevance scoring. 500–1000 characters with 10–15% overlap is a reasonable starting point for most technical documentation.

Step 2: Embed and store the chunks

from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma

embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = Chroma.from_documents(
    documents=chunks,
    embedding=embeddings,
    persist_directory="./chroma_db"
)

Claude itself has no embeddings API, so you need a separate embeddings model. This is a common point of confusion for people moving from a single-vendor setup to Claude — the generation and the retrieval layers are two different services, and that's expected.

Step 3: Set up the retriever

retriever = vectorstore.as_retriever(
    search_kwargs={"k": 4}
)

k=4 retrieves the four most similar chunks per query. Start here and tune based on how dense your source material is — legal or technical docs often benefit from k=6 or higher.

Step 4: Wire retrieval into a Claude chain

from langchain_anthropic import ChatAnthropic
from langchain.chains import RetrievalQA

llm = ChatAnthropic(
    model="claude-opus-4-20250514",
    anthropic_api_key="YOUR_API_KEY",
    temperature=0
)

qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=retriever,
    return_source_documents=True
)

result = qa_chain.invoke({"query": "What is the refund policy for annual plans?"})
print(result["result"])

temperature=0 keeps answers grounded in retrieved text rather than creative. The "stuff" chain type pushes all retrieved chunks into one prompt — fine for k=4-6 chunks, but switch to "map_reduce" if you're retrieving dozens of chunks that would otherwise blow past the context window.

Step 5: Control the prompt template

The default RetrievalQA prompt is generic. For production use, pass a custom prompt that tells Claude explicitly how to handle missing information:

from langchain.prompts import PromptTemplate

template = """Use the following context to answer the question.
If the answer isn't in the context, say you don't know — do not guess.

Context:
{context}

Question: {question}

Answer:"""

prompt = PromptTemplate(
    template=template,
    input_variables=["context", "question"]
)

qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=retriever,
    chain_type_kwargs={"prompt": prompt}
)

This single instruction — explicitly allowing "I don't know" — is the biggest lever against hallucinated answers in RAG systems. Without it, models tend to fabricate plausible-sounding content when retrieval comes up empty.

Streaming the response

For a chat-style UI, stream the generation rather than waiting for the full answer:

for chunk in llm.stream("Summarize the refund policy based on retrieved context."):
    print(chunk.content, end="", flush=True)

If you're building this on top of a hosted Claude endpoint rather than calling Anthropic directly, the same streaming pattern works against SubToAPI — see /docs/streaming for request format.

Where SubToAPI fits in

LangChain's ChatAnthropic class only needs a base URL and an API key — it doesn't care which backend serves the requests. If you're running Claude access through SubToAPI (useful for teams that want usage metadata, per-key limits, and a single dashboard instead of raw Anthropic console access), you point the client at https://api.subtoapi.app/v1 and use a sub_live_... key instead of a raw Anthropic key. The request and response shapes match the Messages API, so the RAG chain above needs no structural changes — see /docs/messages and /docs/quickstart for the exact request format. Plans start at €9/month with a free trial at /signup, and pricing details are at /pricing.

Common pitfalls

FAQ

Does Claude have a built-in embeddings model for RAG?

No. Anthropic doesn't offer an embeddings endpoint, so RAG pipelines using Claude need a separate embeddings provider such as OpenAI's text-embedding-3-small, Voyage AI, or a self-hosted model, paired with a vector store like Chroma, FAISS, or Pinecone.

Why use LangChain instead of calling the Claude API directly for RAG?

LangChain handles document loading, chunking, retriever abstraction, and chain composition so you're not reimplementing that plumbing. You can absolutely build RAG by hand with raw API calls — LangChain just removes boilerplate when you're combining multiple vector stores, loaders, or retrieval strategies.

How much context should I retrieve per query?

Start with 4–6 chunks of 500–1000 characters each and measure answer quality. If answers miss relevant details, increase k; if answers seem distracted by irrelevant text, decrease it or tighten chunk size.

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 →