How to Build a RAG Pipeline with LangChain (Step by Step)
A practical, step-by-step guide to building a RAG pipeline with LangChain: loading, chunking, embeddings, a vector store, retrieval, reranking, generation and evaluation.

What Is a RAG Pipeline?
A RAG (retrieval-augmented generation) pipeline lets a language model answer questions using your own data. Instead of hoping the model memorized the right facts, you search your documents for the passages that matter, put them in the prompt, and ask the model to answer from them.
LLMs don't know your private data. Fine-tuning is expensive and slow to update. RAG injects relevant context into the prompt at runtime, so updating the knowledge is as simple as re-indexing a document. It's the difference between a generic answer and a business-specific one.
Every RAG pipeline has the same two halves. Indexing runs ahead of time: load documents, split them into chunks, turn each chunk into an embedding and store it. Querying runs on every request: embed the question, retrieve similar chunks, optionally rerank them, then generate an answer grounded in those chunks.
- Indexing: load → chunk → embed → store
- Querying: embed question → retrieve → rerank → generate → cite sources
When to Use RAG (and When Not To)
RAG is the right tool when the answer lives in documents you control and changes over time: product docs, support tickets, internal wikis, contracts, research notes. It also gives you citations, which makes answers auditable.
It is the wrong tool when the task is about behaviour rather than knowledge. If you want the model to write in a specific style or follow a strict output format, prompting or fine-tuning is a better fit. And if your whole knowledge base fits comfortably in the model's context window and rarely changes, you may not need retrieval at all.
Step 1: Load and Clean Your Documents
LangChain ships document loaders for PDFs, web pages, Notion, Google Drive, databases and more. Whatever the source, the goal is the same: plain text plus metadata (source URL, title, section, last-updated date). Keep that metadata. You will use it later for filtering and for citations.
Clean before you chunk. Strip navigation menus, cookie banners, repeated headers and footers, and page numbers. Garbage in the index shows up as garbage in the answers, and no amount of clever retrieval fixes it.
Step 2: Chunk the Text
The trick isn't the retrieval; it's the chunking strategy. Chunks that are too small lose context. Chunks that are too large dilute the match and waste prompt space. I use LangChain's RecursiveCharacterTextSplitter with meaningful overlap, so context isn't severed mid-sentence.
The recursive splitter tries to break on paragraphs first, then sentences, then words, which keeps related ideas together. A common starting point is around 500–1,000 characters per chunk with 10–20% overlap. Tune it by looking at real retrieved chunks, not by guessing.
For structured documents, split on structure. Markdown and HTML splitters can keep a heading attached to the text under it, which makes each chunk self-explanatory when it shows up in a prompt.
Step 3: Create Embeddings
An embedding model turns each chunk into a vector, so that chunks with similar meaning end up close together. I use OpenAI's text-embedding-3-small: it is cheap, fast and good enough for most retrieval work.
Two rules matter more than the model you pick. Use the same embedding model for indexing and for queries. And when you change models, re-embed everything, because vectors from different models are not comparable.
Step 4: Store Vectors in a Vector Database
I use Pinecone for vector storage because it is managed and scales without babysitting. For prototypes, an in-memory or local store such as FAISS or Chroma is enough. If you already run Postgres, pgvector keeps everything in one database.
Store the metadata next to every vector. Filters such as 'only documents from this product' or 'only pages updated this year' are often the cheapest way to improve relevance.
Step 5: Retrieve the Right Chunks
At query time, embed the user's question with the same model and fetch the top matches, typically 10–20 candidates. LangChain wraps any vector store as a retriever, so the rest of the chain doesn't care which database sits underneath.
Pure vector search misses exact terms such as product codes, error messages and names. Hybrid search, combining keyword (BM25) and vector results, fixes most of those misses and is worth adding early.
Step 6: Rerank Before You Generate
Vector similarity isn't always semantic relevance. I add a cross-encoder reranker step (using Cohere) to sort the retrieved chunks before feeding them to the LLM. A reranker reads the question and each chunk together, so it judges relevance far better than distance between two vectors.
The pattern is retrieve wide, rerank narrow: fetch 20 candidates, rerank, and keep the best 3–5. This dramatically reduces hallucinations, because the model sees fewer irrelevant passages it might be tempted to use.
Step 7: Generate a Grounded Answer
Build the prompt from three parts: clear instructions, the reranked chunks with their sources, and the user's question. Tell the model to answer only from the provided context, to cite the source for each claim, and to say 'I don't know' when the context doesn't contain the answer.
Return the sources with the answer. Users trust answers they can check, and citations make debugging much faster when something goes wrong.
- Instructions: answer only from the context, cite sources, admit when you don't know
- Context: the top 3–5 reranked chunks, each with its title and URL
- Question: the user's original wording
Step 8: Evaluate and Improve
Build a small test set before you tune anything: 30–50 real questions with the answer and the source document you expect. Check two things separately. Did retrieval bring back the right chunk? Did the model answer correctly from it? Most RAG problems are retrieval problems, and you can only see that if you measure the two halves on their own.
Then change one thing at a time: chunk size, overlap, top-k, hybrid search, reranker, prompt. Keep the change only if the test set improves.
Common RAG Mistakes
Most broken RAG pipelines fail in the same few ways. Fixing these usually beats switching to a bigger model.
- Chunking by a fixed character count and cutting sentences or tables in half
- Dropping metadata, so you can't filter results or cite sources
- Sending 20 raw chunks to the model instead of reranking to the best few
- Mixing embedding models between indexing and queries
- Never re-indexing, so answers drift out of date
- Tuning without a test set, so you can't tell whether a change helped
Frequently Asked Questions
How do you build a RAG pipeline?
Index your documents (load, chunk, embed, store in a vector database), then at query time embed the question, retrieve the most similar chunks, rerank them, and pass the best few to an LLM with instructions to answer only from that context and cite sources.
What is the best chunk size for RAG?
There is no universal number. Around 500–1,000 characters with 10–20% overlap is a common starting point; tune it against a test set of real questions and inspect the chunks that come back.
Do I need LangChain to build RAG?
No. You can call an embedding API, a vector database and an LLM directly. LangChain saves time with ready-made loaders, splitters and retrievers, and makes it easy to swap components.
Which vector database should I use for RAG?
Pinecone if you want a managed service, pgvector if you already use Postgres, and FAISS or Chroma for local prototypes. The chunking and reranking choices usually matter more than the database.
Is RAG better than fine-tuning?
For knowledge that changes, yes: you update the index instead of retraining, and you get citations. Fine-tuning is better for teaching style, tone or output format.
Keep reading
All guides →
Vector Databases for RAG: Pinecone vs pgvector vs Chroma
Pinecone vs pgvector vs Chroma for RAG: hosting, scaling, filtering, hybrid search and ops burden compared, with notes on FAISS, Qdrant and Weaviate.

RAG vs Fine-Tuning: Which One Do You Need?
RAG vs fine-tuning, explained for builders: what each one does, the cost, latency and freshness trade-offs, and a simple checklist to pick the right one.

15 n8n Workflow Examples You Can Build Today
15 practical n8n workflows for alerts, data sync, AI, DevOps and content. Each one lists the trigger, the main nodes and the gotcha that bites first.