Notes
All notes

RAGs (AI Engg #10)

A customer asks your assistant: “Does the Pro plan include SSO?” The model was trained months ago and has never seen your pricing page. Left alone it will invent an answer. With Retrieval-Augmented Generation, you first fetch the pricing page, hand the model the exact paragraph, and ask it to answer from that. Now the answer is current, and it can cite where it came from.

RAG is the single most important pattern in applied AI, and it is deceptively simple until it is not. This chapter builds it end to end: chunking, indexing, retrieval, reranking, generation, and evaluation. You will see the whole pipeline in code, then learn how LangChain, LlamaIndex, Haystack, and RAGFlow change the picture as it grows — and when a fine-tune beats RAG.

The idea

\[ P(y \mid q) = \sum_{d \in \mathrm{top}_k} P(d \mid q)\, P(y \mid q, d) \]

You cannot compute that sum exactly; in practice you retrieve a small set of documents \(d\) and condition the model on them. RAG is a system: the answer is only as good as the union of its stages. That is why “RAG doesn’t work” almost always means “one stage is weak,” not “the model is weak.”

The RAG pipeline is index-time and query-time:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.0cm, minimum height=0.68cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (l) at (-4.4,0) {load};
  \node[b, fill=blue!10] (c) at (-2.2,0) {chunk};
  \node[b, fill=blue!10] (e) at (0,0) {embed};
  \node[b, fill=orange!15] (r) at (2.2,0) {retrieve};
  \node[b, fill=green!12] (g) at (4.4,0) {generate};
  \draw[a] (l) -- (c); \draw[a] (c) -- (e); \draw[a] (e) -- (r); \draw[a] (r) -- (g);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (-2.2,-0.5) {offline};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (3.3,-0.5) {online};
\end{tikzpicture}

Chunking: the decision that decides everything

You cannot embed a 60-page handbook as one vector — the meaning averages out and no query matches. So you split into chunks, and each chunk becomes a retrievable unit. Chunking choices dominate recall.

Rules that work in practice:

# structure-aware chunking with overlap, keeping heading context
def chunk(text, title, size=600, overlap=90):
    words, chunks, i = text.split(), [], 0
    while i < len(words):
        body = " ".join(words[i:i + size])
        chunks.append({"text": f"{title}\n\n{body}",
                       "meta": {"title": title, "start": i}})
        i += size - overlap
    return chunks
# production: split by headings first, then by size within each section

A complete RAG in one script

No framework. This is the whole idea, and you should build it once by hand before reaching for abstraction.

from openai import OpenAI
from sentence_transformers import SentenceTransformer
import chromadb

client = OpenAI()
embed = SentenceTransformer("all-MiniLM-L6-v2")
db = chromadb.Client()
col = db.create_collection("kb", metadata={"hnsw:space": "cosine"})

# --- index time ---
docs = ["Pro plan includes SSO and audit logs.",
        "Free plan is limited to 3 seats.",
        "Refunds are accepted within 30 days."]
col.add(ids=[str(i) for i in range(len(docs))], documents=docs,
        embeddings=embed.encode(docs, normalize_embeddings=True).tolist(),
        metadatas=[{"tenant": "acme"}] * len(docs))

# --- query time ---
def answer(q, tenant="acme", k=3):
    qv = embed.encode([q], normalize_embeddings=True).tolist()
    hits = col.query(query_embeddings=qv, n_results=k, where={"tenant": tenant})
    ctx = "\n".join(f"[{i+1}] {d}" for i, d in enumerate(hits["documents"][0]))
    sys = ("Answer ONLY from the context. Cite sources like [1].\n"
           "If the context does not contain the answer, reply exactly: not found.")
    r = client.chat.completions.create(
        model="gpt-4o-mini", temperature=0,
        messages=[{"role": "system", "content": sys},
                  {"role": "user", "content": f"Context:\n{ctx}\n\nQuestion: {q}"}])
    return r.choices[0].message.content

print(answer("Does Pro include SSO?"))   # "Yes, the Pro plan includes SSO [1]."
print(answer("Do you support Mars?"))    # "not found."

Every clause in that system prompt earns its place: ONLY from context prevents mixing in training knowledge; cite [1] makes it checkable; not found gives the model a legitimate way out, which is the difference between a trustworthy assistant and a confident liar.

Beyond naive RAG

If you stopped at Section 3 you would have a useful demo and a fragile product. The production upgrades, in rough order of ROI:

  1. Hybrid retrieval — dense + BM25 for keywords (Chapter 9).
  2. Reranking — retrieve top-50, cross-encode, keep top-5.
  3. Query rewriting — expand a terse user query into a fuller one, or generate multiple queries and merge results.
  4. Metadata filtering — scope by tenant, language, date, permissions.
  5. Parent-child chunks — retrieve a small chunk for precision, but pass its larger parent section to the LLM for context.
  6. Contextual compression — strip retrieved chunks down to the sentences that matter before prompting.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=1.75cm, minimum height=0.66cm, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (q) at (-3.6,0) {rewrite};
  \node[b, fill=cyan!15] (h) at (-1.6,0) {hybrid};
  \node[b, fill=orange!15] (r) at (0.5,0) {rerank};
  \node[b, fill=green!12] (c) at (2.6,0) {compress};
  \node[b, fill=yellow!22] (g) at (4.4,0) {generate};
  \draw[a] (q) -- (h); \draw[a] (h) -- (r); \draw[a] (r) -- (c); \draw[a] (c) -- (g);
\end{tikzpicture}

Retrieval strategies compared

Naive RAG retrieves with one dense-vector lookup. Production retrieval is a choice per query shape. The four families:

\[ \mathrm{score}(q, d) = \sum_{t \in q} \mathrm{IDF}(t)\, \frac{\mathrm{tf}(t,d)\,(k_1+1)}{\mathrm{tf}(t,d) + k_1\,(1-b+b\,|d|/\mathrm{avgdl})} \]

Strategy Matches on Wins when Fails when Cost
BM25 exact terms codes, names, keywords paraphrase, synonyms ~free
Dense meaning natural questions, paraphrase negation, completeness, lookalikes embedding + ANN
Hybrid + RRF both almost everything (default) both, merged
Cross-encoder rerank full pair reading precision on top-50 as first-pass over thousands \(O(\mathrm{candidates})\) model calls
Reasoning (PageIndex, Ch. 17) structure long structured docs, “list all…” millions of short docs LLM tree walk
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=1.9cm, minimum height=0.66cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (q) at (-3.3,1.0) {query};
  \node[b, fill=cyan!15] (bm) at (-3.3,-0.9) {BM25 top-50};
  \node[b, fill=blue!10] (de) at (0,-0.9) {dense top-50};
  \node[b, fill=orange!16] (fu) at (-1.65,-2.1) {fuse (RRF)};
  \node[b, fill=green!12] (re) at (1.65,-2.1) {rerank top-5};
  \draw[a] (q) -- (bm); \draw[a] (q) -- (de);
  \draw[a] (bm) -- (fu); \draw[a] (de) -- (fu);
  \draw[a] (fu) -- (re);
\end{tikzpicture}
# hybrid + rerank: wide cheap recall, narrow expensive precision
def retrieve(q, bm25, vec, reranker, k1=50, k2=5):
    pool = reciprocal_rank_fusion(bm25.search(q, k1), vec.search(q, k1))
    return reranker.rerank(q, pool)[:k2]  # cross-encoder reads (q, doc) pairs
# route structured/completeness queries to the tree index (Chapter 17)
# if wants_all_clauses(q): return page_index.reasoned_search(q)

Rule of thumb: BM25 for the exact, dense for the paraphrased, hybrid as the default, rerank when precision pays, reasoning when structure decides. If recall is still low, fix chunking and filters before swapping strategies — the retriever can only rank what the index kept separable.

RAG vs fine-tuning (again, with a test)

You need Use Why
Fresh or private facts RAG retrieved at runtime, citable
Exact citations RAG the evidence is in the prompt
A specific tone/format fine-tune behavior, not knowledge
Lower latency on a narrow task fine-tune a small model no retrieval round-trip
Both facts and style both common in mature systems

A useful test: if the knowledge changes weekly, it cannot be fine-tuned (you would retrain constantly). If the knowledge is stable but the style is wrong, fine-tuning is the lever. Most teams need RAG, not fine-tuning, and reach for the latter too early.

Frameworks: when hand-rolled stops scaling

Hand-rolling is the right way to learn and often the right thing to ship. Frameworks earn their place when the pipeline branches:

# LangChain sketch — the same pipeline, assembled from components
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
from langchain_core.prompts import ChatPromptTemplate

store = Chroma(embedding_function=OpenAIEmbeddings(), persist_directory="./db")
retriever = store.as_retriever(search_kwargs={"k": 5})
chain = ({"context": retriever | (lambda docs: "\n".join(d.page_content for d in docs)),
          "q": lambda x: x["q"]} | ChatPromptTemplate.from_template(
              "Answer only from:\n{context}\n\nQ: {q}") | ChatOpenAI(model="gpt-4o-mini"))
print(chain.invoke({"q": "Does Pro include SSO?"}))

The framework version is shorter but hides the stages. Start hand-rolled; adopt a framework when branching, tracing, and integrations outweigh the clarity cost — not before.

Evaluating RAG (the part people skip)

You cannot improve what you do not measure, and RAG has two failure surfaces. Measure both with (query, expected_docs, expected_answer) triples:

Tools: RAGAS and DeepEval implement faithfulness, answer-relevance, and context-precision scores; a model-as-judge plus deterministic checks (does the cited page actually contain the claim?) covers the rest. Run these on every change to chunks, model, embeddings, or prompt. Chapter 13 goes deeper.

# RAGAS-style eval (conceptual)
# from ragas import evaluate
# from ragas.metrics import faithfulness, answer_relevancy, context_precision
# result = evaluate(dataset, metrics=[faithfulness, answer_relevancy, context_precision])

Pitfalls

QQuestionSelf-check

Where does RAG most often fail: retrieval or generation? What is the cheapest first upgrade?

ASolution

Retrieval, by a wide margin. The cheapest first upgrades are better chunking and hybrid retrieval with reranking — they raise recall before you touch the prompt. Always verify the needed evidence was in context before rewriting the system message.

Next: AI Agents (AI Engg #11) — when the model must act, not just answer.