Ankit KanojiyaIntermediate
Evergreen guide by Ankit Kanojiya · Intermediate · AI / ML
Retrieval-Augmented Generation (RAG), Explained
How to ground an LLM in your own data by retrieving relevant passages at query time and feeding them into the prompt. Covers embeddings, vector search, chunking, and evaluation.
- RAG
- Embeddings
- Vector Search
- Retrieval
- LLM
- Chunking
A base LLM only knows what was in its training data, which is frozen at some cutoff date and does not include your private documents. Retrieval-Augmented Generation (RAG) closes that gap by fetching relevant text at query time and placing it in the prompt, so the model can answer from current, specific sources instead of memory. It is the most common way to build a question-answering feature over a private knowledge base.
The core pipeline
RAG has two phases. First, an offline indexing phase prepares your data. Second, an online query phase runs for each user question.
Indexing:
- Split documents into chunks.
- Convert each chunk into an embedding, a vector of numbers that captures meaning.
- Store the vectors in a vector database alongside the original text.
Querying:
- Embed the user's question with the same model.
- Find the chunks whose vectors are most similar to the question.
- Insert those chunks into the prompt and ask the model to answer using them.
Answer the question using only the context below.
If the context does not contain the answer, say you do not know.
Context:
{retrieved_chunks}
Question: {user_question}
Embeddings and similarity
An embedding model maps text to a point in a high-dimensional space where similar meanings land near each other. Similarity is usually measured with cosine similarity, which compares the angle between two vectors. Retrieval returns the top-k nearest chunks, where k is a small number like 3 to 8.
The question and the documents must be embedded with the same model, since vectors from different models are not comparable.
Chunking strategy matters
How you split documents has a large effect on quality.
- Chunks that are too large dilute relevance and waste context tokens.
- Chunks that are too small lose the surrounding context needed to make sense.
- A common starting point is a few hundred tokens per chunk with some overlap between neighbors so a sentence split across a boundary is not lost.
Respect document structure where possible. Splitting on headings, paragraphs, or code blocks usually beats splitting on a fixed character count.
Improving retrieval quality
Plain vector search is a baseline, not a ceiling. Several techniques routinely help:
- Hybrid search combines vector similarity with keyword search, which catches exact terms, product codes, and names that embeddings sometimes miss.
- Reranking runs a second, more accurate model over the top candidates to reorder them before they enter the prompt.
- Metadata filtering restricts search to the right subset, such as a single customer, product version, or date range.
- Query rewriting expands or clarifies a terse question before retrieval.
Keep the model honest
RAG reduces hallucination but does not eliminate it. Two habits help:
- Instruct the model to answer only from the provided context and to admit when the answer is absent.
- Return citations by tracking which chunk each answer came from, so users can verify and so you can debug bad answers.
Grounding also fails when retrieval fails. If the right chunk never makes it into the prompt, the model cannot use it, and a confident wrong answer may follow. Many RAG problems are retrieval problems wearing a generation costume.
Evaluating a RAG system
Measure the two stages separately.
- Retrieval: for a set of test questions, does the correct chunk appear in the top-k results? Metrics like recall at k quantify this.
- Generation: given the right context, is the final answer faithful to it and complete? This is often scored by a human or by another model acting as a judge.
Separating the metrics tells you where to invest. If retrieval recall is low, better chunking or hybrid search helps. If retrieval is good but answers are wrong, the prompt or the generation model is the problem.
When RAG is the right tool
RAG fits when answers must come from a specific, changing, or private corpus, such as internal docs, support articles, or product catalogs. It is cheaper and faster to update than retraining a model, since adding knowledge means adding documents to the index. For teaching a model a new skill or style rather than new facts, other approaches fit better, which the next article compares directly.