Jangid RAG Zero-to-Hero Pipeline
Build a fully functional Retrieval-Augmented Generation system — from naive to modular — that grounds LLM answers in your own documents and eliminates hallucination.
// TL;DR
The Jangid RAG Zero-to-Hero Pipeline is a framework for building Retrieval-Augmented Generation systems in three tiers — Naive, Advanced, and Modular — that ground LLM answers in your own documents and eliminate hallucination. It covers paragraph-aware chunking with overlap, TF-IDF vectorisation, FAISS indexing, pre-retrieval query rewriting, post-retrieval reranking, routing, and query fusion with Reciprocal Rank Fusion. Use it whenever an LLM must answer questions about private, proprietary, or time-sensitive documents it wasn't trained on, or when hallucination and outdated knowledge are unacceptable risks — like legal contracts, internal policies, or support knowledge bases.
// When should you use the Jangid RAG Zero-to-Hero Pipeline?
Use this skill whenever an LLM needs to answer questions about private, proprietary, or time-sensitive documents it was not trained on, or when LLM hallucination and outdated knowledge are unacceptable risks.
// What do you need before building a RAG pipeline?
- Source Document(s)required
The raw text file(s) or corpus the system will retrieve from (e.g. a product manual, legal contract, story, knowledge base). - User Queryrequired
The natural-language question the end user wants answered. - LLM API Accessrequired
An API key and endpoint for an LLM (e.g. Groq, OpenAI). Free-tier keys are sufficient for prototyping. - Target RAG Tier
Which tier to build: Naive RAG, Advanced RAG, or Modular RAG.
// What are the core principles behind a solid RAG system?
Chunking Over Full-Document Injection
Never inject a whole document into the prompt. That wastes tokens and is 'the worst way to do RAG.' Always split the document into smaller chunks first, then retrieve only the relevant ones.
Chunk-Vector-Index Loop
The core RAG idea is: chunk the document → convert chunks to vectors → index the vectors → convert the user query to a vector → retrieve the K nearest-neighbor chunks → build a new prompt → send to the LLM. Nothing more, nothing less, at the naive level.
Overlap for Context Continuity
When splitting into chunks, carry forward the last N characters of the previous chunk (the 'overlap size') so that mid-sentence breaks do not destroy meaning. Without overlap, the retriever sees fragments like 'mysterious circumstances' with no knowledge of what 'circumstances' refers to.
Word-Boundary Respect
Never let a chunk cut in the middle of a word. After computing the overlap start position, walk backward character-by-character until you land on a space. This prevents garbage tokens like 'LIC' (a cut of 'public') from corrupting the vector space.
Pre-Retrieval Query Rewriting
Before searching the index, hand the raw user query to the LLM and ask it to rewrite the query for optimal chunk retrieval. This is the defining upgrade from Naive RAG to Advanced RAG and costs only one extra LLM call.
Post-Retrieval Reranking
After retrieving chunks, send them back to the LLM and ask it to reorder them from most to least relevant and discard irrelevant noise. Only the filtered, reranked context goes into the final answer prompt.
Routing Decision
In Modular RAG, before any retrieval, ask the LLM whether the question can be answered from its pre-trained knowledge ('chat') or requires document lookup ('doc'). This prevents unnecessary retrieval for general knowledge questions.
Query Fusion (Multi-Query Strategy)
Instead of one retrieval pass, generate three to five diverse reformulations of the user query, run a vector search for each, collect all retrieved chunks, and rerank the combined pool using the Reciprocal Rank Fusion (RRF) formula. This uncovers both explicit and implicit relevant passages that a single query would miss.
Prompt Precision
The answer prompt must instruct the LLM to 'answer the question using only the provided context' and to respond with 'I don't know' if the answer is absent. Vague prompts produce hallucinated answers even when good context is available.
// How do you build a RAG pipeline step by step?
- 1
Load and inspect the source document
Read the raw text file. Print its total character length to understand scale. A 12 k-character document is representative. Confirm the document is plain text before proceeding.
- 2
Split the document into paragraph-aware chunks with overlap
First split on newline characters to get natural paragraphs; strip empty lines. Then merge paragraphs into chunks up to your chosen chunk_size (e.g. 200 characters). Carry an overlap_size (e.g. 50 characters) of the previous chunk into each new chunk. After computing the overlap start index, walk backward to the nearest space to avoid mid-word cuts. Expect roughly 10–30% more chunks than a naive fixed-slice approach due to overlap.
- 3
Vectorise chunks with TF-IDF
Instantiate a TF-IDF Vectorizer with stop_words='english' so common words (the, is, a) are downweighted and unique keywords receive higher weight. Fit-transform the chunk list to get a compressed sparse matrix, then convert to a dense float32 NumPy array. TF = term frequency within a chunk; IDF = inverse document frequency that boosts rare, meaningful terms.
- 4
Normalise vectors and build a FAISS flat index
L2-normalise each chunk vector using the formula: x_norm = x / sqrt(sum(x^2)). Create a FAISS IndexFlatIP (inner product) index with the vector dimension. Add all normalised chunk vectors to the index. This creates the 'virtual 3D space' where proximity equals semantic similarity.
- 5
Transform the user query into a vector and retrieve top-K chunks
Vectorise the query string using the same fitted TF-IDF vectorizer (transform only, never re-fit). Convert to float32 dense array. Call index.search(query_vector, K) where K=3–5. The returned indices map back to your chunk list. These are the 'relevant chunks' — the nearest neighbors in vector space.
- 6
Build the answer prompt and call the LLM
System instruction: 'You are a helpful question-answering assistant. Answer the question using only the provided context. If the answer is not present in the context, respond with I don't know.' Append the retrieved chunks as context and the user's original question. Send to the LLM API. This completes Naive RAG.
- 7
[Advanced RAG] Rewrite the query before retrieval (Pre-Retrieval)
Before step 5, send the user query to the LLM with the instruction: 'Rewrite this query for the pre-retrieval stage of a RAG pipeline to find the most relevant chunks. Return only the rewritten query.' Use the rewritten query — not the original — for the vector search in step 5.
- 8
[Advanced RAG] Rerank retrieved chunks after retrieval (Post-Retrieval)
After step 5, number the retrieved chunks (0, 1, 2 …) and send them to the LLM with the instruction: 'Select only the relevant facts from the chunks below to answer the question. Order from most relevant to least relevant. Ignore irrelevant noise.' Use the LLM's reordered, filtered output as the context for step 6.
- 9
[Modular RAG] Add a Routing decision before retrieval
Before step 7, send the query to the LLM with the instruction: 'Check whether you need to look up the Spider-Man document for this question. Return "chat" if the LLM can answer from general knowledge, or "doc" if document retrieval is required.' Only proceed to retrieval if the response is 'doc'. For 'chat', answer directly from the LLM.
- 10
[Modular RAG] Apply Query Fusion (multi-query strategy)
Instead of one query, ask the LLM: 'Generate three diverse search queries based on this user question. Return them one per line, no numbering.' Append the original query to form a multi-query list. Run the vector search for each query independently. Collect all retrieved chunks into a combined pool. Apply the Reciprocal Rank Fusion (RRF) formula to score and sort the pool: score(chunk) = sum over queries of 1/(rank_in_that_query + k), where k is a smoothing constant (commonly 60). Take the top-K chunks from the fused ranking as the final context.
- 11
Encapsulate each RAG tier into a reusable class
NaiveRAG class: load_document, chunk, vectorize, build_index, retrieve, generate. AdvancedRAG inherits NaiveRAG and adds rewrite_query and rerank_context methods. ModularRAG inherits AdvancedRAG and adds route and generate_queries (fusion) methods. Expose a single .ask(query) method that runs the full pipeline and returns: original_query, rewritten_query, retrieved_context, refined_context, answer.
// What are real-world examples of this RAG pipeline in action?
A legal team has a 50-page contract and wants to answer 'What are the termination clauses?' without feeding the entire document to the LLM.
Load the contract text. Chunk into 200-character paragraph-aware chunks with 50-character overlap and word-boundary correction. TF-IDF vectorise and FAISS-index the chunks. At query time, run Pre-Retrieval rewriting ('rewrite for retrieval: termination clauses and conditions'), retrieve top-3 chunks, Post-Retrieval rerank to filter boilerplate, then generate the answer with the 'answer only from context, else say I don't know' prompt.
A customer support bot needs to answer both general product questions (answerable from LLM training) and specific policy questions (only in internal docs).
Apply Modular RAG Routing: for each incoming question, ask the LLM 'chat or doc?' General questions like 'What is a return policy in general?' get answered directly. Policy-specific questions like 'What is our 90-day return window?' trigger document retrieval. Use Query Fusion on the doc path to generate multiple search angles (e.g. 'return window duration', 'refund timeframe policy', 'days allowed for return') and RRF-rerank the combined chunk pool before generating the final answer.
// What mistakes should you avoid when building RAG?
- Injecting the whole document into the prompt — this is 'the worst way to do RAG' and wastes tokens without improving relevance.
- Chunking by fixed character slices without paragraph awareness — this produces meaningless mid-sentence fragments like 'mysterious o us' that corrupt retrieval.
- Cutting chunks mid-word — creates garbage tokens (e.g. 'LIC' from 'public') that distort TF-IDF vectors. Always walk back to a space boundary.
- Re-fitting the TF-IDF vectorizer on the query — the vectorizer must only be fit on chunks and then used to transform the query. Re-fitting destroys the shared vocabulary.
- Forgetting to cast vectors to float32 — FAISS requires float32; passing other dtypes raises cryptic errors.
- Using a vague answer prompt — without explicit 'answer only from context / say I don't know' instructions, the LLM will hallucinate even when good chunks are retrieved.
- Skipping the overlap step — without overlap, the first token of a chunk has no surrounding context and the retriever cannot understand it.
- Hardcoding chunk indices without checking chunk list length — index-out-of-range errors occur when the chunk count changes after improving the chunking strategy.
- Exposing API keys in shared notebooks — use environment variables or secret managers, not inline strings.
// What are the key RAG terms you need to know?
- Naive RAG
- The baseline RAG tier: chunk document → vectorise → index → retrieve top-K chunks by query similarity → build prompt → LLM answer. No query optimisation, no reranking.
- Advanced RAG
- Extends Naive RAG by adding Pre-Retrieval (query rewriting) before the vector search and Post-Retrieval (reranking and filtering) after it.
- Modular RAG
- The most capable tier, treating each RAG component (routing, retrieval, rewriting, reranking, fusion, generation) as a swappable module that can be combined, repeated, or skipped depending on the query.
- Pre-Retrieval
- The stage before vector search where the user's raw query is rewritten or expanded by the LLM to better match relevant chunk vocabulary.
- Post-Retrieval
- The stage after vector search where retrieved chunks are reranked from most to least relevant and irrelevant noise is discarded before the final prompt is built.
- Chunk
- A short sub-segment of a document (e.g. 200 characters) created during indexing. The atomic unit of retrieval in a RAG system.
- Overlap Size
- The number of characters carried from the end of the previous chunk into the start of the next chunk, preserving cross-boundary context.
- Word-Boundary Correction
- Walking the overlap start index backward character-by-character until a space is found, preventing chunks from beginning mid-word.
- TF-IDF Vectorizer
- A vectorisation method combining Term Frequency (how often a word appears in a chunk) and Inverse Document Frequency (how rare the word is across all chunks). Rare, meaningful keywords receive higher weight; common stop words are suppressed.
- FAISS Flat Index (IndexFlatIP)
- A vector index that stores all chunk vectors and performs exact inner-product (cosine) similarity search. Equivalent to a searchable '3D space' of chunks.
- K Nearest Neighbors (top-K)
- The K chunk vectors closest to the query vector in the FAISS index — the 'relevant chunks' returned by retrieval.
- Routing
- A Modular RAG gate where the LLM decides whether a query requires document lookup ('doc') or can be answered from general knowledge ('chat'), preventing unnecessary retrieval.
- Query Fusion
- A Modular RAG strategy that expands one user query into multiple diverse sub-queries, runs independent vector searches for each, and merges the results using Reciprocal Rank Fusion.
- Multi-Query Strategy
- The process within Query Fusion of generating three to five semantically varied reformulations of the original query to cover different retrieval angles.
- Reciprocal Rank Fusion (RRF)
- The scoring formula used in Query Fusion: score(chunk) = sum of 1/(rank_in_query + k) across all queries. Chunks that rank highly in multiple query results receive the highest fused scores.
- Sparse Matrix
- The memory-efficient output of TF-IDF vectorisation that stores only non-zero values. Must be converted to a dense float32 NumPy array before FAISS indexing.
// FREQUENTLY ASKED QUESTIONS
What is Retrieval-Augmented Generation (RAG)?
RAG is a technique that grounds LLM answers in your own documents by chunking the document, converting chunks to vectors, indexing them, retrieving the most relevant chunks for a query, and injecting only those chunks into the prompt. This eliminates hallucination and lets the LLM answer questions about private or time-sensitive content it was never trained on.
What is the difference between Naive, Advanced, and Modular RAG?
Naive RAG chunks, vectorises, indexes, retrieves top-K chunks, and generates an answer — nothing more. Advanced RAG adds pre-retrieval query rewriting and post-retrieval reranking. Modular RAG treats every component as a swappable module, adding a routing gate that decides whether retrieval is even needed and query fusion that runs multiple reformulated searches merged with Reciprocal Rank Fusion.
How do I build a basic RAG system from scratch?
Load your document, split it into paragraph-aware chunks with overlap and word-boundary correction, vectorise the chunks with TF-IDF, normalise them and build a FAISS IndexFlatIP, transform the user query with the same vectoriser, retrieve the top-3 to top-5 nearest chunks, then build a prompt instructing the LLM to answer using only that context. That completes Naive RAG.
How do I stop my RAG system from hallucinating?
Use a precise answer prompt: instruct the LLM to 'answer the question using only the provided context' and to respond with 'I don't know' if the answer isn't present. Vague prompts cause hallucination even when good chunks are retrieved. Combine this with proper chunking, overlap, and reranking so the right context actually reaches the model.
How does RAG compare to just pasting the whole document into ChatGPT?
Pasting the whole document wastes tokens and is called 'the worst way to do RAG.' RAG retrieves only the relevant chunks, so it scales to large corpora, costs fewer tokens, and keeps the LLM focused on pertinent context. Full-document injection breaks on long documents and buries the answer in noise, reducing accuracy.
When should I use RAG instead of fine-tuning?
Use RAG when an LLM needs to answer questions about private, proprietary, or frequently-changing documents, or when hallucination is an unacceptable risk. RAG updates instantly — just re-index new documents — whereas fine-tuning requires retraining. Fine-tuning changes behaviour and style; RAG injects factual, up-to-date knowledge without touching model weights.
What is query fusion in RAG?
Query fusion is a Modular RAG strategy that expands one user query into three to five diverse reformulations, runs an independent vector search for each, collects all retrieved chunks into a combined pool, and reranks them using Reciprocal Rank Fusion (RRF). This uncovers both explicit and implicit relevant passages a single query would miss.
What results can I expect from an Advanced RAG pipeline?
Expect more relevant retrieval and fewer hallucinations than Naive RAG, at the cost of two extra LLM calls per query. Pre-retrieval rewriting aligns the query vocabulary with your chunks, and post-retrieval reranking filters boilerplate noise before generation. Answers become more grounded, with cleaner context and better handling of ambiguous or poorly-phrased user questions.
Why do I need overlap between chunks in RAG?
Overlap carries the last N characters of the previous chunk into the next so mid-sentence breaks don't destroy meaning. Without it, a retriever sees fragments like 'mysterious circumstances' with no knowledge of what 'circumstances' refers to. Overlap preserves cross-boundary context and makes each chunk independently understandable during retrieval.
What is routing in Modular RAG?
Routing is a gate where the LLM decides whether a query needs document lookup ('doc') or can be answered from general knowledge ('chat') before any retrieval runs. This prevents wasteful retrieval for general-knowledge questions, saving tokens and latency while reserving document search for questions that genuinely require your private content.
Do I need a paid LLM API to build a RAG system?
No — free-tier API keys from providers like Groq or OpenAI are sufficient for prototyping a RAG pipeline. You need an API key and endpoint, a source document, and a user query. TF-IDF vectorisation and FAISS indexing run locally without any paid service, so you can build and test the full pipeline at no cost.