How to Build Modular RAG From Scratch
For ML engineers and developers · Based on Jangid RAG Zero-to-Hero Pipeline
// TL;DR
ML engineers can use the Jangid RAG Zero-to-Hero Pipeline to build a RAG system in three inheritable tiers without heavyweight frameworks. Start with Naive RAG — paragraph-aware chunking, TF-IDF vectorisation, L2-normalised FAISS IndexFlatIP, top-K retrieval, grounded generation. Layer Advanced RAG's pre-retrieval query rewriting and post-retrieval reranking on top. Finish with Modular RAG's routing gate and query fusion using Reciprocal Rank Fusion. Each tier is a class that inherits the last, exposing a single .ask() method. Use it to understand RAG internals before reaching for abstracted libraries.
How do you structure a RAG pipeline into clean, inheritable tiers?
Build three classes with an inheritance chain. `NaiveRAG` owns the fundamentals: `load_document`, `chunk`, `vectorize`, `build_index`, `retrieve`, and `generate`. `AdvancedRAG(NaiveRAG)` adds `rewrite_query` and `rerank_context`. `ModularRAG(AdvancedRAG)` adds `route` and `generate_queries` for fusion. Each tier exposes a single `.ask(query)` method that runs the full pipeline and returns the original query, rewritten query, retrieved context, refined context, and answer. This mirrors the complexity progression and keeps every stage testable in isolation.
How do you implement retrieval correctly with TF-IDF and FAISS?
Instantiate a TF-IDF vectorizer with `stop_words='english'` so common words are downweighted. Fit-transform the chunk list to get a sparse matrix, then convert to a dense float32 NumPy array — FAISS requires float32 or you'll hit cryptic errors. L2-normalise each vector (`x / sqrt(sum(x^2))`) so inner-product search in `IndexFlatIP` equals cosine similarity. Build the index with the vector dimension and add all normalised vectors. At query time, transform the query with the same fitted vectorizer — never `fit_transform`, which destroys the shared vocabulary — cast to float32, and call `index.search(query_vector, K)` with K=3–5.
How do you add Advanced and Modular capabilities without rewriting everything?
Because each tier inherits the last, you extend rather than rewrite. In `AdvancedRAG`, `rewrite_query` sends the raw query to the LLM: 'Rewrite this query for the pre-retrieval stage of a RAG pipeline. Return only the rewritten query.' Then `rerank_context` numbers retrieved chunks and asks the LLM to order them most-to-least relevant and discard noise. In `ModularRAG`, `route` asks the LLM 'chat or doc?' to gate retrieval, and `generate_queries` produces three diverse reformulations for query fusion. Pool the per-query results and score with RRF: `score = sum over queries of 1/(rank_in_query + 60)`, then take the top-K fused chunks.
What are the subtle bugs that break RAG pipelines?
Five recurring traps: re-fitting the TF-IDF vectorizer on the query (destroys vocabulary alignment); forgetting float32 casts (FAISS errors); hardcoding chunk indices without checking `len(chunks)` (index-out-of-range after you improve chunking); skipping overlap (first tokens lack context); and cutting chunks mid-word (garbage tokens like 'LIC' from 'public' distort vectors). Always walk the overlap start index backward to the nearest space. And never inject the whole document into the prompt — chunk and retrieve.
How do you know your pipeline is actually working?
Because `.ask()` returns intermediate state — original query, rewritten query, retrieved context, refined context, and answer — you can inspect every stage. Compare retrieved versus refined context to verify reranking is filtering noise. Check the rewritten query makes retrieval sense. Confirm routing sends general questions to 'chat'. This observability is the reason to hand-build before adopting abstracted frameworks: you see exactly where relevance is won or lost.
Next step
Implement `NaiveRAG` first against a representative 12k-character document and validate retrieval quality on known questions. Then subclass to `AdvancedRAG` and measure whether rewriting and reranking improve relevance. Finally build `ModularRAG` with routing and RRF fusion. Keep API keys in environment variables, and benchmark each tier before deciding how much complexity your use case justifies.
// FREQUENTLY ASKED QUESTIONS
Why must I use transform instead of fit_transform on the query?
The TF-IDF vectorizer must be fit only on your chunks to establish a shared vocabulary. Calling fit_transform on the query re-fits a new vocabulary, producing a query vector that's incomparable to your indexed chunk vectors — retrieval then returns garbage. Always use transform() on the query so it maps into the same vector space as the chunks.
Why does FAISS require float32 and how do I convert?
FAISS only accepts float32 arrays; other dtypes raise cryptic errors. After TF-IDF produces a sparse matrix, convert it to a dense array and cast with .astype('float32'). Do the same for the query vector before calling index.search. This applies to both the vectors you add to the index and every query vector you search with.
Should I hand-build this or use a framework like LangChain?
Hand-build first to understand RAG internals — chunking, vectorisation, FAISS search, routing, and RRF fusion — then decide if a framework's abstractions justify their opacity. This pipeline's inheritable NaiveRAG → AdvancedRAG → ModularRAG structure gives you full observability into every stage via the .ask() return values, which frameworks often hide. Build for comprehension, then abstract where it pays off.