Claude API RAG Pipeline: LangChain Tutorial
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
- An Anthropic API key (or a SubToAPI key if you're routing through a hosted proxy — more on that below)
- An embeddings provider (OpenAI, Voyage AI, or a local model — Claude does not have a native embeddings endpoint)
- A vector store (Chroma is used here for simplicity; FAISS, Pinecone, and Weaviate work the same way with LangChain)
langchain,langchain-anthropic, andlangchain-communityinstalled
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
- Retrieving too much context. Dumping 20 chunks into every prompt increases cost and can actually hurt accuracy by burying the relevant passage. Tune
kdown before tuning the prompt. - No overlap between chunks. Zero overlap means answers that span a chunk boundary get cut in half. Keep at least 50–100 characters of overlap.
- Treating RAG as a fix for outdated training data only. RAG is also the right tool when your data is private, changes frequently, or is too large to fit in a single context window — not just for freshness.
- Skipping evaluation. Log the retrieved chunks alongside the generated answer during testing. If the answer is wrong, you need to know whether retrieval or generation failed.
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.