CONTENTS
CHAPTER 6

Retrieval and RAG — Giving Models Knowledge

5 MIN READ

Models know a lot, but not your data: your docs, your users’ records, last week’s support tickets, today’s inventory. Retrieval-Augmented Generation (RAG) is the family of techniques for fetching relevant information and putting it in context at query time.

6.1 Why retrieval instead of retraining?

Approach Good for Bad for
Put it in the prompt Small, stable knowledge (a style guide, a few docs) Large or changing corpora
Retrieval (RAG) Large, changing, permissioned knowledge; citations Tasks needing holistic synthesis of the whole corpus
Fine-tuning Behavior, format, style, domain “feel” Injecting facts reliably (it’s lossy and goes stale)
Long context Medium corpora where you need cross-document reasoning Cost and latency per call; context rot at extreme lengths

A key rule of thumb: fine-tuning teaches behavior; retrieval supplies knowledge. Facts change; retraining every time they do is expensive and unreliable. Retrieval keeps knowledge fresh, permissioned, and citable.

6.2 The classic RAG pipeline

INDEXING (offline)
  documents → parse/clean → chunk → embed each chunk → store (vector + text + metadata)

QUERYING (online)
  user question → (rewrite query) → embed → search top-k → (rerank) → put chunks in prompt
                → model answers with citations

Every box hides decisions that significantly affect quality.

Parsing

Garbage in, garbage out. Real documents include PDFs with multi-column layouts, tables, scanned images, slide decks, and HTML full of navigation chrome. Parsing quality is often the biggest single factor in RAG quality and the most neglected. Modern approaches include layout-aware parsers and using vision-capable models to convert pages into clean markdown.

Chunking

You can’t embed a 200-page manual as one vector. It would average away all specific meaning. So you split it into chunks.

  • Fixed-size (e.g., ~500 tokens with ~50-token overlap): simple, a reasonable baseline.
  • Structure-aware: split on headings, sections, paragraphs, functions (for code). Usually better.
  • Contextual chunk headers: prepend each chunk with context such as the document title, section path, or a model-generated one-sentence summary of how the chunk fits in the document. A chunk saying “Revenue grew 3% over the previous quarter” is useless without knowing which company and quarter. Approaches like Anthropic’s “Contextual Retrieval” showed large reductions in retrieval failures this way.

Embeddings

An embedding model maps text to a vector so that semantically similar texts are close together. Choosing one:

  • Check retrieval benchmarks (e.g., the MTEB leaderboard), but test on your own data. Benchmark rankings often don’t transfer.
  • Consider dimension (storage and speed), max input length, multilingual support, and cost.
  • Re-embedding a whole corpus when you switch models is a real migration. Plan for it.

Find the k nearest vectors to the query vector. At scale this uses Approximate Nearest Neighbor (ANN) indexes like HNSW, which trade a little recall for big speed gains.

Where to store vectors: start with pgvector in Postgres. Your metadata, permissions, and vectors live together, you can filter with SQL, and you already know Postgres. Move to a dedicated vector database (Pinecone, Weaviate, Qdrant, Turbopuffer, and others) only when you have a specific scale or feature need.

6.3 Why naive RAG disappoints, and how to fix it

The demo works in an afternoon. Production quality takes months. The common failure modes and fixes:

1. Semantic search misses exact matches. Embeddings are fuzzy. Searching for error code E-4012 or SKU RN-77-B can return semantically “similar” but wrong chunks. Fix: Hybrid search. Combine vector search with keyword search (BM25), and merge results (e.g., with Reciprocal Rank Fusion). This is close to a default best practice.

2. Top-k contains the answer, but ranked 15th. Fix: Reranking. Retrieve a broad set (top 50–100), then use a cross-encoder reranker that looks at query and chunk together (more accurate than comparing two independent vectors) to choose the best 5–10.

3. User queries are vague or conversational. “What about the other one?” embeds terribly. Fix: Query rewriting. Use a model to turn the conversation into a standalone search query, or generate several query variants. HyDE (Hypothetical Document Embeddings) generates a hypothetical answer and searches with that.

4. Users see documents they shouldn’t. Fix: Permission filtering at retrieval time, using metadata filters for tenant, user, and role. Never rely on the model to “not mention” unauthorized content. If it’s in the context, assume it can leak.

5. The answer needs information scattered across many documents. (“Summarize every complaint about the checkout flow this quarter.”) Fix: Top-k retrieval is the wrong tool here. Use structured queries over metadata, map-reduce summarization, or precomputed aggregations. Some teams use knowledge graphs (GraphRAG-style approaches) for relationship-heavy questions.

6. The model ignores or misuses retrieved context. Fix: Clear prompt structure (each document in tags with source IDs), instructions to cite sources and to say “I don’t know” when the context lacks the answer, and evals that check faithfulness (Chapter 8).

6.4 Agentic retrieval: the modern shift

Classic RAG is a fixed pipeline: retrieve once, then answer. As models got better at tool use, a different pattern took over many use cases: give the model search tools and let it decide what to search, how many times, and when it has enough.

Classic RAG:   question → retrieve top-5 → answer
Agentic:       question → model searches "X" → reads results → searches "Y" →
               opens doc 3 → greps for "Z" → answers with citations

This is how coding agents navigate codebases (grep, glob, read file) instead of embedding everything, and how “deep research” products work. Advantages: multi-hop questions, self-correction when the first search fails, and no up-front decision about what’s relevant. Costs: more latency, more tokens, less predictability.

Practical guidance:

  • For high-volume, latency-sensitive, simple lookup (FAQ bots, in-app help), use classic RAG with hybrid search and reranking.
  • For complex, multi-hop, exploratory tasks, use agentic search with good tools.
  • The best systems often combine them: semantic search as a tool the agent can call, alongside keyword search and structured queries.

6.5 Don’t forget plain old databases

A big share of “RAG” questions are actually structured data questions in disguise. “How many runs did I do in October?” should not be answered by retrieving text chunks. It should be a SQL query. Give the model a tool that runs parameterized, permission-scoped queries (or a text-to-SQL tool with strict guardrails) and it will be far more accurate.

Ask of every question type: Is the answer in unstructured text, or in structured data? Route accordingly.

6.6 Evaluating retrieval

Evaluate retrieval and generation separately. When an answer is wrong, you need to know whether the right chunk was ever retrieved.

Retrieval metrics (needs a labeled set of query → relevant document pairs):

  • Recall@k: Was a relevant document in the top k? This is the most important one; if the answer wasn’t retrieved, nothing downstream can fix it.
  • Precision@k: What fraction of the top k are relevant? (Noise hurts generation.)
  • MRR / nDCG: Was the relevant result ranked near the top?

Generation metrics:

  • Faithfulness / groundedness: Is every claim supported by the retrieved context?
  • Answer correctness: Does it match the reference answer?
  • Citation accuracy: Do citations point to passages that actually support the claim?

Building the eval set: Sample real user queries (or realistic synthetic ones generated from your documents with a model), label the relevant chunks, and write reference answers. 100–200 good examples beats 10,000 sloppy ones.

Key takeaways

  • Retrieval supplies knowledge; fine-tuning shapes behavior.
  • RAG quality is decided in the unglamorous parts: parsing, chunking with context, hybrid search, reranking, and permission filtering.
  • Agentic retrieval (models using search tools iteratively) often beats fixed pipelines for complex tasks; classic RAG still wins for fast, simple lookups.
  • Many “RAG” problems are really structured-data problems. Use SQL tools.
  • Evaluate retrieval (recall@k) separately from generation (faithfulness).

Exercises

  1. Build a RAG system over a documentation set you know (React Native docs, or your company’s internal docs) with pgvector. Start naive: fixed chunks and vector search.
  2. Create 50 test questions with known source sections. Measure recall@5.
  3. Add, one at a time, measuring recall each time: structure-aware chunking, contextual chunk headers, hybrid BM25 search, and a reranker. Chart the improvement.
  4. Convert the system into an agentic version where the model has semantic_search, keyword_search, and read_section tools. Compare accuracy, latency, and cost on your 50 questions.