AI Agentic Handbook
Volume II

Retrieval-Augmented Generation

Giving a model the right knowledge at answer time — chunking, retrieval, ranking, production.

Sections

Interview questions answered at staff level

01

RAG Fundamentals

Why RAG exists, when not to build it, and what happens inside a query.

10 questions
02

Chunking & Embeddings

The least glamorous section and the one that decides your ceiling.

10 questions
03

Retrieval & Ranking

Dense vs sparse, hybrid, rerankers, top-k and the vocabulary interviewers check for.

10 questions
04

Production RAG Systems

Multi-tenancy, security, caching, monitoring and incidents — judgment under constraint.

10 questions

Read first

Blog posts for this volume, easiest first

RAG in plain English: letting the AI look it up

Why a model that sounds like it knows everything still needs to check, and how retrieval-augmented generation makes it read before it answers.

Your first RAG pipeline in pure Python

Chunk, vectorise, rank and build a cited prompt in ~150 lines of standard-library Python, test it with pytest, then swap in a real Embedding model and LLM without touching the rest.

Hybrid search and reranking: a field guide

Dense and sparse retrieval fail in opposite ways. How Reciprocal Rank Fusion combines them in 15 lines, where ColBERT and SPLADE fit, and what a Cross-encoder costs per 100 candidates on CPU and GPU.

Talking a team out of RAG (when it is the wrong tool)

RAG is a default, not a requirement. When long context with prompt caching or text-to-SQL is the better design, what it costs and how fast it is with numbers, how per-document permissions change the answer, and the written threshold that flips the decision.

From toy RAG to a real one: embeddings, a vector store and an LLM

Take the stdlib pipeline from the first RAG post and swap in a real Embedding model, a persistent vector store and an LLM, with pinned versions, timeouts, retries, batching and tests.

Anatomy of a production RAG system

Every box between the user's question and a cited answer, with a latency and cost budget per stage, who owns it, and the one metric that tells you it is broken.

Choose your chunk size by measurement, not folklore

A reproducible method: build a small golden set on a public corpus, sweep chunk sizes, and read recall@k, evidence coverage and context cost off one table.

Key terms

58 pages with diagrams and quizzes

EmbeddingBudding

A list of numbers that stands for the meaning of a piece of text, arranged so that similar meanings land close together.

Vector spaceBudding

The space embeddings live in, where 'close together' means 'similar in meaning'.

EncoderMid

A model that reads text and turns it into meaning-numbers, instead of writing a reply.

Bi-encoderMid

Turns the question and each document into vectors separately, then compares them. Fast enough to search millions.

Cross-encoderMid

Reads the question and one document together and scores the match. Much sharper than comparing vectors, far too slow to run over everything.

Cosine similarityBudding

A score from −1 to 1 for how closely two embeddings point the same way: the usual way to ask 'are these two texts about the same thing?'

Dot productBudding

Multiply two lists of numbers position by position and add it all up. The cheapest way to ask 'do these two texts mean the same thing?'

Embedding dimensionalityMid

How many numbers are in each embedding — 384, 768, 1024, 3072. Storage, speed and cost grow with it in a straight line. Quality does not.

Symmetric vs asymmetric embeddingsMid

Symmetric search matches like with like (ticket to ticket). Asymmetric search matches a short question to the long passage that answers it.

Instruction prefix (query: / passage:)Mid

A tiny label such as 'query: ' or 'passage: ' stuck in front of text before embedding it, telling the model which role this text is playing.

Matryoshka embeddingsSenior

Embeddings trained so the first few hundred numbers work on their own: cut 3072 down to 256 and keep most of the quality.

MTEB leaderboardMid

The big public scoreboard for embedding models. Perfect for picking three to try; your own test set decides the winner.

Fine-tuning an embedding modelSenior

Training an embedding model a bit further on your own question-and-passage pairs, so your field's jargon finally lands near its meaning.

ChunkingBudding

Cutting documents into passages small enough to search and hand to a model. Usually a few hundred tokens, cut where the document itself breaks.

Chunk overlapBudding

Repeating the tail of one chunk at the start of the next, so an idea cut in half still appears whole somewhere.

Structural & semantic chunkingMid

Cutting where the topic changes rather than every N words, spotted by a drop in similarity between neighbouring sentences.

Parent-document retrievalMid

Search small chunks so the match is precise, then hand the model the bigger section around them. Retrieve small, return big.

Contextual enrichment (breadcrumbs)Senior

Adding a short model-written note to each chunk saying where it came from, before it is stored. Anthropic measured 35–67% fewer retrieval misses.

Layout-aware parsingMid

Pulling text out of PDFs and scans with reading order, headings, tables and figures intact — so everything downstream has structure to work with.

OCR (optical character recognition)Budding

Turning pictures of text — scans, photos, faxes — into text a computer can actually read. Mistakes here spread into everything downstream.

Ingestion pipelineMid

The machinery that collects your documents, parses, chunks, embeds and indexes them — and keeps the index honest as sources change and vanish.

Document registrySenior

The record book for ingestion: one row per source document — where it came from, its version, its status, who may see it, which chunks it made.

Content hashingMid

A fingerprint of a document's text. Same text, same fingerprint — so you can skip unchanged files, spot duplicates and retry safely.

Change data capture (CDC)Senior

Change data capture: reading a database's own change log so your search index follows every insert, update and delete within seconds.

TombstoneSenior

A little note saying 'this was deleted', travelling through the system so every copy and index learns to drop it.

BackfillSenior

Rebuilding the whole index the new way — new model, new chunker, new fields — beside the live one, then switching over once it checks out.

Chunk metadataBudding

The labels stored next to each chunk — customer, permissions, source, date, page — used for filtering, access control and citations.

Sparse retrievalBudding

Good old keyword search: find the documents containing the words you typed. Fast, easy to explain, and still unbeatable for IDs, codes and names.

BM25Budding

The keyword scoring formula behind most search engines: rare words count more, repeats count less and less, long documents don't win by being long.

SPLADESenior

Keyword search with a brain: a model writes the weighted word list, and adds related words the text never used.

Dense retrievalBudding

Search by meaning: turn the question and every passage into number-lists, and return the passages whose numbers sit closest.

Hybrid searchMid

Run keyword search and meaning search side by side, then merge the two lists — each one covers what the other misses.

Semantic search vs similarity searchBudding

Search that goes after what you meant rather than the words you typed. Usually embeddings, plus a reranker to tidy up the top.

Approximate nearest neighbour (ANN)Mid

Approximate nearest neighbour search: find vectors close to your query without checking them all. Give up a sliver of accuracy, gain huge speed.

HNSWSenior

The most common way to index vectors in memory: a layered map of 'who is near whom', walked greedily from the top down.

IVF (inverted file index)Senior

Sort the vectors into buckets, then only search the buckets nearest your question. Cheap to build, easy to split across machines.

Product quantization (PQ)Staff

Squash each vector into a handful of bytes by describing it with 'standard pieces' from a learned catalogue. 3,072 bytes become 64.

Scalar & binary quantizationMid

Storing each number in an embedding with fewer bits — 16-bit, 8-bit, even 1-bit — to cut memory 2–32×, with a re-check pass to win the accuracy back.

ANN recall (efSearch, nprobe)Senior

How many of the genuinely closest vectors your fast index actually returned. Measured against slow exact search, not against human opinion.

Metadata filtering (pre, post, filtered ANN)Mid

Restricting a search to items whose fields match conditions — this customer, this language, after 2024 — without quietly wrecking recall.

Candidate generation & the retrieval funnelMid

The cheap first pass that cuts millions of items down to a few hundred, so something slower and smarter can order them properly.

Top-k (retrieval k vs context k)Budding

How many results a stage returns. Early stages want lots (100+); the few you hand the model want to be few (5–10).

Query rewritingMid

Turning the user's messy message into a proper search query: resolving 'it', expanding jargon, dropping the small talk.

Query decompositionSenior

Breaking a question that is really three questions into parts, searching for each, then answering from all the evidence together.

HyDE (hypothetical document embeddings)Senior

Have the model write a pretend answer first, then search with that instead of the question — because answers look like documents, and questions don't.

Intent classification & routingMid

Working out what kind of request just arrived, so it can be sent down the right path: document search, database query, tool call, or a polite 'no'.

Vector databaseMid

A store built to search embeddings quickly, with filters, updates, deletes and backups. Often Postgres with pgvector is already enough.

Sharding & partitioningSenior

Splitting an index across machines so each holds a slice. Buys you size and write throughput — not a faster single query.

ReplicationSenior

Keeping copies of each shard on several machines, so you survive a failure and can answer more queries at once.

RerankerMid

A slower, sharper model that re-scores the top 50–200 candidates, so only the best 5–10 ever reach the model writing the answer.

Reciprocal Rank Fusion (RRF)Mid

A merge trick for two result lists: score each document by its position in each list, not by the raw numbers. No calibration needed.

Weighted score fusionSenior

Combining retriever scores rather than ranks: rescale each list to a common range, then blend them with a weight you tune.

Context assemblyMid

Turning ranked chunks into an actual prompt: drop duplicates, fit the token budget, order them, label them so they can be cited.

Lost in the middleSenior

Models used to overlook facts buried in the middle of a long prompt. Finding one fact is largely fixed; joining several across a long text still isn't.

Grounding & groundedness checksBudding

Making the model answer from the sources you handed it rather than from memory — and then checking that it actually did.

Attribution & citationsMid

Linking each claim in an answer to the exact passage that backs it — and measuring whether those citations are right and complete.

Abstention & relevance thresholdsMid

Letting the system say 'I don't know' on purpose when the evidence isn't there, instead of guessing beautifully.

Semantic cacheSenior

Reusing a stored answer when a new question means roughly the same as an old one. Cheap and fast, with a real risk attached.