Frequently Asked Questions About Jangid RAG Zero-to-Hero Pipeline
22 answers covering everything from basics to advanced usage.
// Basics
What does the chunk-vector-index loop actually do?
The chunk-vector-index loop is the core of RAG: 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, and send it to the LLM. At the naive level, that's the entire pipeline — nothing more, nothing less.
What is TF-IDF and why use it for vectorising chunks?
TF-IDF combines Term Frequency (how often a word appears in a chunk) with Inverse Document Frequency (how rare the word is across all chunks). Rare, meaningful keywords get higher weight and common stop words are suppressed. It's a lightweight, local vectorisation method that needs no embedding model, making it ideal for prototyping a RAG pipeline.
What is a FAISS Flat Index and what does IndexFlatIP mean?
A FAISS Flat Index stores all chunk vectors and performs exact similarity search — think of it as a searchable 3D space of chunks where proximity equals semantic similarity. IndexFlatIP uses inner-product search; when vectors are L2-normalised first, inner product equals cosine similarity, giving you reliable nearest-neighbor retrieval.
What exactly does the answer prompt need to contain?
The answer prompt must include a system instruction like: '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 or reranked chunks as context plus the user's original question. This precision prevents hallucination even when context is imperfect.
// How To
How do I split a document into paragraph-aware chunks?
First split on newline characters to get natural paragraphs and strip empty lines. Then merge paragraphs into chunks up to your chunk_size (e.g. 200 characters), carrying an overlap_size (e.g. 50 characters) of the previous chunk into each new one. After computing the overlap start index, walk backward to the nearest space to avoid mid-word cuts.
How do I add pre-retrieval query rewriting to my RAG system?
Before the vector search, 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 FAISS search. This single extra LLM call is the defining upgrade from Naive to Advanced RAG.
How do I rerank retrieved chunks after retrieval?
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 the final answer prompt instead of the raw retrieved chunks.
How do I implement query fusion with Reciprocal Rank Fusion?
Ask the LLM to generate three diverse search queries from the user question, then add the original query to the list. Run an independent FAISS search for each, collect all retrieved chunks into a pool, and score each chunk with RRF: score = sum over queries of 1/(rank_in_that_query + k), where k is commonly 60. Sort the pool by score and take the top-K as final context.
// Troubleshooting
Why does my RAG system return index-out-of-range errors?
This usually happens when you hardcode chunk indices without checking the chunk list length. After improving your chunking strategy, the chunk count changes, so any hardcoded index can exceed the new list size. Always validate against len(chunks) and map retrieved FAISS indices back dynamically rather than assuming fixed positions.
Why is FAISS throwing cryptic errors when I add my vectors?
FAISS requires float32 vectors. If you pass a different dtype — like float64 from a default NumPy conversion — you'll get cryptic errors. Always cast your dense vectors to float32 before adding them to the index or searching. This applies to both chunk vectors and the query vector.
Why does retrieval break after I re-fit the TF-IDF vectorizer on the query?
Re-fitting the vectorizer on the query destroys the shared vocabulary. The vectorizer must be fit only on your chunks, then used to transform the query with transform(), never fit_transform(). Re-fitting creates a different vocabulary and vector space, so the query vector becomes incomparable to your indexed chunk vectors and retrieval returns garbage.
Why does my retriever return meaningless fragments?
Meaningless fragments like 'mysterious o us' come from fixed character-slice chunking without paragraph awareness, or from cutting chunks mid-word. Switch to paragraph-aware chunking, add overlap for cross-boundary context, and walk back to the nearest space boundary so you never produce garbage tokens like 'LIC' from 'public' that corrupt your TF-IDF vectors.
// Comparisons
How does Advanced RAG compare to Naive RAG?
Naive RAG does a single straight-through pass: chunk, vectorise, index, retrieve, answer. Advanced RAG wraps that with two extra LLM calls — pre-retrieval query rewriting to align the query with chunk vocabulary, and post-retrieval reranking to filter noise. The result is more relevant context and fewer hallucinations, at the cost of slightly more latency and tokens.
How does query fusion compare to a single retrieval pass?
A single retrieval pass only surfaces chunks matching the one phrasing of the query, missing implicit or alternate-vocabulary matches. Query fusion runs three to five diverse reformulations, pools all results, and reranks with RRF so chunks that rank highly across multiple queries rise to the top. It uncovers both explicit and implicit relevant passages a single query would miss.
How does TF-IDF retrieval compare to dense embedding retrieval?
TF-IDF is a sparse, keyword-based method that's fast, local, and free — ideal for prototyping and keyword-heavy documents. Dense embeddings capture semantic meaning beyond exact words but require an embedding model or API. This pipeline uses TF-IDF for simplicity; you can swap in embeddings later since Modular RAG treats vectorisation as a replaceable component.
How does the routing decision compare to always retrieving?
Always retrieving wastes tokens and latency on general-knowledge questions the LLM can already answer. The routing decision asks the LLM 'chat or doc?' first, so only questions requiring your private content trigger retrieval. This keeps the pipeline efficient and avoids injecting irrelevant document chunks into questions that don't need them.
// Advanced
How should I structure my code to support all three RAG tiers?
Build a NaiveRAG class with load_document, chunk, vectorize, build_index, retrieve, and generate methods. Have AdvancedRAG inherit from it and add rewrite_query and rerank_context. Have ModularRAG inherit from AdvancedRAG and add route and generate_queries for fusion. Expose a single .ask(query) method that returns the original query, rewritten query, retrieved context, refined context, and answer.
What chunk_size and overlap_size should I use?
A chunk_size of around 200 characters with a 50-character overlap works well for representative documents like a 12k-character text. Overlap typically produces 10–30% more chunks than naive fixed-slicing. Larger chunks capture more context but dilute relevance; smaller chunks sharpen retrieval but risk losing meaning. Tune based on your document structure and query specificity.
What value of k should I use in the RRF formula?
A smoothing constant of k=60 is the common default in Reciprocal Rank Fusion. It controls how much weight top ranks receive versus lower ranks — larger k flattens the differences between ranks, smaller k sharply favours top-ranked chunks. Start with 60 and adjust only if your fused rankings over- or under-emphasise consistently top-ranked passages.
Can I combine routing and query fusion in the same pipeline?
Yes — that's the strength of Modular RAG. Route first to decide 'chat or doc.' On the doc path, apply query fusion to generate multiple search angles, run parallel vector searches, and RRF-rerank the pool before generation. Each module is swappable, repeatable, or skippable depending on the query, so you can compose them freely.
How do I secure my API keys in a RAG notebook?
Never hardcode API keys as inline strings in shared notebooks. Use environment variables or a secret manager to load keys at runtime. Exposing keys in shared code risks quota theft and billing abuse. Load them via os.environ or a .env file excluded from version control, keeping credentials out of your source.
Why L2-normalise vectors before building the FAISS index?
L2-normalisation (x_norm = x / sqrt(sum(x^2))) makes inner-product search equivalent to cosine similarity in FAISS IndexFlatIP. Without normalisation, longer vectors dominate the inner product regardless of semantic relevance. Normalising both chunk and query vectors ensures retrieval measures true directional similarity, giving you reliable nearest-neighbor results.