Skip to main content

RAG WTH Is it?

Retrieval Augmented Generation - Yet another acronym the ML researchers have slapped onto something so simple.

  • You have a large pre-trained model
  • You have data lying in your documents, PDFs, CSV files
  • How would you extend these models to infer insights from this data?

Or in simpler terms, how can you make LLMs answer questions about your employee agreement, your blog posts, or the data that is super private to your company?

We can achieve it by performing 3 steps

  1. Retrieval
  2. Augmentation
  3. Generation

Get it? Hence the name. Very innovative.


Ok…Ok.. wait…this is what every article in every major AI company is telling you.

I can go two routes from here

  1. Explain to you how to do it. Again plenty of articles exist. I highly recommend this video
  2. Explain some cool stuff I learned along the way

This post started as route 2 and, two years later, I’ve filled in the parts I skipped: why RAG exists in the first place, when not to use it, how the pieces fit together, and the retrieval tricks that matter more than the prompt.

Why does RAG exist? LLM failure modes

I find it easier to remember RAG as a list of things an LLM does badly, and what retrieval does about each.

LLM failure modeWhat goes wrongHow RAG helps
Frozen knowledgeA model only knows what was in its training data. Anything newer, like your policy updated last week, is invisible to it.Retrieve the current document at question time. Update the index, not the model.
No access to private dataYour employee agreement, tickets and internal wiki were never in the training set.Index them and retrieve the relevant parts.
HallucinationDeep-learning text generators are prone to hallucinate unintended text (Ji et al.’s survey on the topic). When the model doesn’t know, it can still produce a fluent answer.Ground the answer in retrieved passages and tell the model to say “I don’t know” when the context doesn’t contain the answer. This reduces the problem; it does not eliminate it.
No sourcesYou can’t tell where a claim came from.You know which chunks went into the prompt, so you can show citations.
Context limitsYou can’t paste a whole company wiki into every prompt.Retrieve only the few chunks that matter.

The idea is older than the current hype. The original RAG paper (Lewis et al., 2020, NeurIPS) combined a pre-trained seq2seq model (parametric memory) with a dense vector index of Wikipedia (non-parametric memory), and reported that RAG generated more specific, diverse and factual text than a parametric-only baseline.

RAG vs fine-tuning vs long context

Three ways to get your data in front of a model. They solve different problems, so the real question is which one you need.

RAGFine-tuningLong context (stuff it all in the prompt)
Best forFacts and documents that change; answers with citationsChanging behaviour: tone, format, a narrow taskSmall, bounded corpora; one-off analysis of a single large document
Updating knowledgeRe-index the changed documentsRetrainPaste the new text
Cost per queryLow prompt size, plus a retrieval stepTraining has an upfront cost, and updating means retrainingPays for every token on every call
Main riskBad retrieval means bad answersModels struggle to absorb new facts this wayThe model may not use everything you give it

What the research says:

  • RAG vs fine-tuning for knowledge. Ovadia et al. compared the two for injecting knowledge into LLMs and found that fine-tuning gave some improvement but RAG consistently outperformed it, for both knowledge seen in training and entirely new knowledge. They also found LLMs struggle to learn new facts through unsupervised fine-tuning. This is a study of knowledge injection; it does not say fine-tuning is useless, only that it is the wrong tool for “teach the model my documents”.
  • RAG vs long context. Li et al. benchmarked RAG against long-context LLMs (EMNLP 2024 industry track) and found that, with enough resources, long-context models achieved higher average performance, while RAG’s much lower cost remained a distinct advantage. Their hybrid, Self-Route, sends each query to RAG or long context based on the model’s own self-reflection.
  • Long context isn’t a free lunch. Liu et al.’s Lost in the Middle found that performance is often highest when the relevant information is at the beginning or end of the input, and drops when it sits in the middle, even for models built for long contexts.
  • The “just put it all in the prompt” threshold. Anthropic’s Contextual Retrieval write-up says that if your knowledge base is smaller than 200,000 tokens (about 500 pages), you can include the whole thing in the prompt and skip RAG, with prompt caching making it faster and cheaper. Context windows keep growing, so check the current limit and pricing for the model you use.

My rule of thumb: small and static, stuff the prompt. Large or changing, retrieve. Need a particular style or format, fine-tune. And they combine: a fine-tuned model can sit on top of a RAG pipeline.

The components of a RAG system

  1. Loader / parser: gets text out of PDFs, HTML, CSVs, tickets. This step quietly decides your quality ceiling: if a table comes out as soup, no retriever can fix it.
  2. Chunker: splits documents into pieces small enough to embed and retrieve.
  3. Embedding model: turns each chunk (and later each query) into a vector.
  4. Index / vector store: stores vectors, and often the original text and metadata, for fast nearest-neighbour search. Often paired with a keyword (BM25) index.
  5. Retriever: takes the question and returns the top candidates. May include query rewriting, filters and fusion.
  6. Reranker (optional but worth it): re-scores the candidates more carefully.
  7. Prompt builder and generator: puts the best chunks into the prompt and asks the LLM to answer from them.
  8. Evaluation and monitoring: tells you whether any of this is working (more on that at the end).

Building it: the mechanics

Here is a small end-to-end retriever you can read in one sitting. It chunks text with overlap, builds a dense index and a BM25 index, fuses the two rankings, and builds a grounded prompt. Swap the final print for a call to whichever LLM you use.

# pip install rank_bm25 sentence-transformers numpy
import numpy as np
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer

def chunk(text: str, size: int = 120, overlap: int = 30) -> list[str]:
    """Split into overlapping windows of `size` words."""
    words = text.split()
    step = size - overlap
    return [" ".join(words[i:i + size]) for i in range(0, max(len(words) - overlap, 1), step)]

def build_index(chunks, model):
    vectors = model.encode(chunks, normalize_embeddings=True)   # dense index
    bm25 = BM25Okapi([c.lower().split() for c in chunks])       # keyword index
    return vectors, bm25

def dense_rank(query, vectors, model, k=20):
    scores = vectors @ model.encode([query], normalize_embeddings=True)[0]  # cosine similarity
    return list(np.argsort(-scores)[:k])

def bm25_rank(query, bm25, k=20):
    return list(np.argsort(-bm25.get_scores(query.lower().split()))[:k])

def rrf(rankings, k=60):
    """Reciprocal rank fusion: score = sum of 1 / (k + rank) across rankings."""
    scores = {}
    for ranking in rankings:
        for rank, doc_id in enumerate(ranking, start=1):
            scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)

def retrieve(query, chunks, vectors, bm25, model, top=3):
    fused = rrf([dense_rank(query, vectors, model), bm25_rank(query, bm25)])
    return [chunks[i] for i in fused[:top]]

def build_prompt(query, contexts):
    context = "\n\n".join(f"[{i + 1}] {c}" for i, c in enumerate(contexts))
    return ("Answer using only the context below. If the answer is not there, say you don't know.\n\n"
            f"Context:\n{context}\n\nQuestion: {query}\nAnswer (cite sources like [1]):")

# --- usage ---
model = SentenceTransformer("all-MiniLM-L6-v2")
chunks = chunk(open("employee_handbook.txt").read())
vectors, bm25 = build_index(chunks, model)

question = "How many days of paid leave do I get?"
print(build_prompt(question, retrieve(question, chunks, vectors, bm25, model)))

Two things to notice. Retrieval and generation are separate steps, so you can debug retrieval on its own by printing what came back before any LLM sees it. And the prompt tells the model to refuse when the context doesn’t answer the question, which matters because RAG reduces hallucination but doesn’t switch it off.

Retrieval techniques beyond multi-query and HyDE

These two are the ones I picked up first, and I’m keeping them here:

Multi-query

Given a question, 3 other questions of a similar nature are generated and the consolidated result is sent back.

HyDE

Takes LLM to a party. Given a question, HyDE generates a hypothetical answer and then uses it to search the document you have. The paper (Gao et al., 2022) calls it Hypothetical Document Embeddings: the generated document may contain inaccuracies, but it captures the relevant patterns, and the embedding of it is used to find real documents that are close to it.

Both rewrite the query. In practice, a lot of the quality comes from other places. Here they are, roughly in the order I’d try them:

1. Chunking strategy

How you split decides what can be retrieved at all. Anthropic notes that chunk size, boundaries and overlap all affect retrieval performance, with chunks typically no more than a few hundred tokens. Common strategies:

  • Fixed-size with overlap: simple and predictable (what the code above does). It can cut a sentence or a table in half.
  • Structure-aware: split on headings, paragraphs and sentences first, and only fall back to a character count when a section is too big. Good for docs and Markdown.
  • Semantic chunking: split where the topic changes, using embedding similarity between neighbouring sentences. More expensive, and I’d compare it against the simple version before adopting it.
  • Small-to-big (parent-document): embed small pieces for precise matching, but hand the LLM the larger surrounding passage. LlamaIndex’s production RAG guide calls this decoupling retrieval chunks from synthesis chunks.

2. Hybrid search (keyword + vector)

Embeddings are good at meaning and bad at exact strings: error codes, product SKUs, names, version numbers. BM25 is the opposite. Run both in parallel and merge. Anthropic’s write-up describes the same pattern, noting that it helps with exact terms like error codes that embeddings alone may miss.

The usual merge is reciprocal rank fusion (RRF): each document gets 1 / (k + rank) from every list it appears in, and you sort by the sum. It needs no score normalisation, because it only looks at ranks, which is the point when BM25 scores and cosine similarities live on different scales. It comes from Cormack, Clarke and Büttcher (SIGIR 2009), who report that it consistently yields better results than any individual system they combined. Elasticsearch’s RRF docs use the same formula with a default rank constant of 60, and Cormack’s paper says k = 60 was fixed in a pilot study and near-optimal, though the exact value is not critical.

3. Reranking

Retrieval is a wide net; reranking is a closer look. A bi-encoder embeds the query and each document separately, so document vectors can be precomputed, which is why it scales. A cross-encoder reads the query and document together, which is more accurate but too slow to run over a whole corpus. Sentence-Transformers’ retrieve and re-rank guide recommends exactly that split: retrieve around 100 candidates cheaply, then rerank only those.

from sentence_transformers import CrossEncoder

reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
candidates = retrieve(question, chunks, vectors, bm25, model, top=20)
scores = reranker.predict([(question, c) for c in candidates])
best = [c for _, c in sorted(zip(scores, candidates), reverse=True)][:3]

4. Contextual retrieval

A chunk like “the company’s revenue grew by 3% over the previous quarter” is useless on its own: which company, which quarter? Anthropic’s approach is to have an LLM prepend a short, chunk-specific context (usually 50 to 100 tokens) to each chunk before embedding it and before building the BM25 index. On their evaluation, the top-20 retrieval failure rate fell from 5.7% to 3.7% with contextual embeddings, to 2.9% when also using contextual BM25, and to 1.9% when additionally reranking the top 150 chunks down to 20. Those are Anthropic’s own benchmark numbers on their chosen datasets, so test on your data before you believe them.

5. Metadata filters and structure

If the user asks about “the 2025 leave policy”, don’t make the embedding model figure out the year. Store metadata (document type, date, product, team, access level) with each chunk and filter before similarity search. LlamaIndex’s guide covers this under structured retrieval for large document sets. It is also where you enforce “this user may not see HR documents”.

6. Measure, don’t vibe-check

Change one thing, then measure. Ragas is a reference-free evaluation framework whose metrics cover the retrieval component (does the retriever find relevant, focused context?), how faithfully the LLM uses the retrieved passages, and the quality of the generated output. Whatever tool you use, build a small set of real questions with the chunks that should answer them. Check retrieval and generation separately, because “the answer was wrong” has two very different fixes.

Take Diversion into the World of Monitoring

It all started with the video and LangChain. People hate LangChain for its abstraction. But I loved the level of tracing it supports.

Guess who else also does it

  • Sentry
  • Arize UI

For a RAG system, tracing is how you answer “what did the retriever actually hand to the model for this question?”, which is the first thing to look at when an answer is wrong.