AI Systems: RAG

With a video: giving LLMs your data via embeddings, vector search, and retrieval-augmented generation.

Intermediate8 min read
Language
Theme

EP 01: RAG kya hai?

DocumentschunkChunksembedVector DBpgvector/PineconeQuestionembed + searchTop-k chunksLLMGrounded answerQuality lives in chunking + embeddings; always cite sources
Key idea at a glance

The problem, stated properly

An LLM knows only what was in its training data: nothing about your company docs, nothing after its cutoff, and it will confidently invent answers when it does not know. Retrieval-Augmented Generation fixes this with a simple move: before the model answers, fetch the relevant pieces of your data and paste them into the prompt. The model then answers from real text instead of from memory. The idea is one sentence; making it actually work in production is chunking, embeddings, vector search, reranking, and evaluation, each with its own failure modes.

The pipeline, both halves

Offline (indexing), done once per document set and on every update:

  1. Ingest + clean: pull docs from Drive/Notion/Confluence/web. Strip boilerplate, extract text from PDFs (tables and multi-column layouts are where extraction quietly destroys quality).
  2. Chunk: split into pieces of ~200-500 tokens with 10-20% overlap. Chunking is the highest-leverage decision in the whole system: too big and embeddings blur unrelated ideas together; too small and every chunk lacks the context to be useful. Split on semantic boundaries (headings, paragraphs), never mid-sentence, and store metadata (source, title, section, date) with every chunk.
  3. Embed: each chunk passes through an embedding model (OpenAI text-embedding-3, Cohere, open-source BGE/E5) producing a vector of ~768-3072 floats. Similar meanings land at nearby points.
  4. Index: vectors go into a vector DB (pgvector, Pinecone, Weaviate, Qdrant, FAISS) with an ANN index like HNSW that finds approximate nearest neighbors in milliseconds over millions of vectors.

Online (answering), per question:

  1. Embed the user's question with the same model.
  2. ANN search returns the top ~20-50 candidate chunks; keyword (BM25) search in parallel catches exact terms vectors miss, like part numbers and error codes. Merge the two result sets (hybrid search).
  3. Rerank: a cross-encoder model rescores the candidates against the actual question (expensive but accurate) and keeps the top 3-8.
  4. Stuff the survivors into the prompt with instructions to answer only from the context and cite sources.
  5. The LLM generates the answer; citations map back to chunk metadata so users can verify.

Why vector search is fast: ANN in one paragraph

Comparing a query vector against 100 million stored vectors one by one (exact search) costs ~100M dot products per query: seconds, not milliseconds. HNSW (Hierarchical Navigable Small World) builds a multi-layer graph over the vectors, where each node links to its nearest neighbors; search greedily walks the graph from a sparse top layer down to dense bottom layers, landing near the true neighbors after ~log N hops. You trade a small recall loss (you might miss 2-5% of true neighbors) for 1000x speed, which is the correct trade in almost every system.

Real numbers to design with

  • Corpus: 1M docs x ~10 chunks each = 10M vectors x 1536 dims x 4 bytes is about 60 GB, plus HNSW graph overhead (~1.5-2x). Fits on one beefy node or a small shard set.
  • Latency budget: embedding the query ~50-100 ms (API call), ANN search ~5-20 ms, rerank 50 candidates ~50-200 ms, LLM generation 1-5 s (streaming hides most of it). Retrieval adds well under 500 ms; the LLM is the slow part.
  • Cost shape: indexing a million docs is a one-time batch cost; every query pays one embedding call + one LLM call with a fattened prompt. Prompt tokens from retrieval are usually the dominant recurring cost, which is why reranking down to 3-8 chunks matters.

Failure modes (this is where interviews are won)

  • Retrieval miss: the answer is in the corpus but the right chunk never made the top-k, so the model hallucinates anyway. Fixes: hybrid search, query rewriting/expansion (an LLM rewrites the vague question into 2-3 specific searches), higher recall + rerank.
  • Chunk boundary decapitation: the answer spans a split ("The limit is... [chunk ends] 5 requests per second [next chunk]"). Overlap and section-aware splitting exist because of this.
  • Distractor pollution: top-k contains 3 relevant chunks and 5 confidently-irrelevant ones, and the model happily weaves all of them in. Reranking and lower k are the fix.
  • Stale index: the doc changed last week, the embedding is from last quarter. Index freshness (webhook-driven re-embedding on doc update) is a production requirement, not a nicety.
  • "The model ignored the context": long prompts bury the relevant chunk in the middle, and models have a real lost-in-the-middle weakness. Put the best chunks first and last, keep total context lean.
  • Multimodal reality: your PDFs are 40% tables and figures that text extraction mangles. Table-aware extraction or multimodal embeddings, or accept wrong answers on tabular questions.

Tradeoffs worth naming

  • RAG vs fine-tuning: fine-tuning teaches the model how to talk (style, format, domain vocabulary); RAG gives it what to know (facts that change). Fine-tuning cannot keep up with facts that change weekly and hallucinates when asked about them anyway. Most production systems use RAG for knowledge and fine-tuning only for behavior, if at all.
  • RAG vs long-context models: "just paste everything into a 1M-token window" works for one-off analysis of a small doc set, but at 1M docs it is impossible, and even at small scale it costs 100x more per query and degrades accuracy (lost-in-the-middle). Long context complements RAG; it does not replace it.
  • Dedicated vector DB vs pgvector: under ~10M vectors, pgvector inside your existing Postgres removes an entire system to operate. Beyond that, or when you need advanced filtering at high QPS, a dedicated store earns its complexity.

Common interview traps

  • Describing RAG as "search, then answer" without the offline/online split, chunking strategy, or reranking.
  • Claiming embeddings understand exact keywords. They capture semantic similarity; "ERR_429_THROTTLE" needs BM25, not cosine similarity.
  • No evaluation story. Production RAG is measured: retrieval recall (does the right chunk make top-k?), answer faithfulness (does the answer stick to the retrieved text?), both tracked over a golden question set.
  • Ignoring citations and permissions. Enterprise RAG must retrieve only what the asking user is allowed to see, which means ACL metadata on every chunk and filtering at query time.

Interview Q&A

Q: Users complain the system answers questions the docs definitely cover. Walk me through debugging.
A: Split the pipeline and test each stage alone. First, retrieval: run the failing question, look at the top-20 chunks. If the right chunk is missing, it is a recall problem: check chunking (was the answer split or in a mangled table?), try hybrid search and query rewriting. If the right chunk is retrieved, it is a generation problem: check whether reranking buried it, whether the prompt is too long, and whether the model instructions let it say "I don't know" instead of forcing an answer. Every RAG bug is exactly one of these two, and the discipline is never tweaking prompts before measuring retrieval recall.

Q: How do you keep answers faithful and reduce hallucination?
A: Four compounding defenses: retrieve well (most hallucinations are retrieval misses in disguise), instruct the model to answer only from the provided context and to say "not covered" when it is not, require citations per claim so unfaithful answers are visible, and evaluate faithfulness on a golden set with an LLM-judge or human review before every prompt/model change ships. None of these is sufficient alone; together they get faithfulness into the high 90s.

Key takeaways

Interview pointer

The full RAG discussion is in the video: watch it before your next AI interview.