Leanpub Header

Skip to main content

Topics

Retrieval-Augmented Generation

From chunking and embeddings to reranking and grounded answers, retrieval-augmented generation as told through the free samples of the Leanpub books about building it.

Created from the free samples of 13 Leanpub books and the descriptions and tables of contents of 5 more, with every source cited.

Retrieval-augmented generation (RAG) is a way of building applications on a language model in which the system first looks up documents relevant to a question and then gives them to the model, as part of the prompt, to answer from. One of the sources states the whole idea in a sentence: relevant passages are retrieved from an external knowledge source and included as context when the model generates its answer.[1] The model's own knowledge is fixed in its weights when training ends, so it cannot see new, private or specialised information, and when asked about what it does not know it tends to produce fluent text that is wrong.[1] Retrieval addresses this at the moment of answering and leaves the model unchanged.

The technique has become a standard pattern for systems that answer questions about an organisation's own documents, in customer support, legal research, clinical guidelines and internal documentation.[4] The books about it have moved on from showing that it works. Several open with the same observation, that a demonstration over a few clean documents is easy and that the difficulty begins with real data, where most failures are failures of retrieval and not of the model.[2] All of the books used here were published in 2026.

This article covers how a RAG system is put together, embeddings and vector search, hybrid search and reranking, the choice between retrieval and fine-tuning, hallucination and grounding, the architectures that go beyond the basic recipe, running retrieval on one's own hardware, and evaluation and operation. Its sources are the free samples of 13 Leanpub books and the public descriptions and tables of contents of 5 more. Where a sample says something, it is cited; where a book has no sample, it is cited only for what its description and contents list say, and the note in the Sources list says so. Prompt engineering has its own article.

Where to start

A reader who wants to understand a RAG system without building one can begin with Understanding Modern LLM Systems (2026), described as a 67-page guide with no mathematics and no code that follows one question through a complete system, for people in sales, product, compliance and security review and for engineers from outside machine learning.[14]

For an engineer who will build one, the general treatment is The Art and Science of RAG (2026), which assumes comfort with code and basic machine-learning concepts but no experience of retrieval, embeddings or vector databases, and explains each component before any framework that wraps it.[1] Production RAG and GenAI Systems (2026) is described as covering the same ground without favouring a vendor or framework.[15] A developer on the Microsoft stack has Production-Grade RAG with C# and .NET (2026), which asks only for C# and one web API built with it, and opens with a four-page vocabulary of the field.[3] Developers who would sooner meet retrieval inside an ordinary web application have Django 6.1 with Python 3.14 (2026), one of whose six projects is described as a knowledge base that answers questions from the reader's own documents.[11]

Other sources come second. Embeddings and Reranking in Retrieval-Augmented Generation (2026) is for practitioners taking a working prototype to production, and its chapters on chunking, embedding models and reranking can be read independently.[2] Mastering Qdrant for RAG Applications (2026) and Vector Search Inside Out (2026) go deep into one vector database and one index algorithm respectively,[4][16] Building Hallucination-Resistant RAG and AI Agents (2026) is addressed to engineers already responsible for a production system,[5] and Beyond "Chunk and Pray" (2026) is described as being for those whose systems a compliance team, auditor or regulator may examine.[8]

History

Neither half of the technique was new when it was named. Information retrieval had been studied for decades, and for most of that time it meant keyword search: algorithms such as TF-IDF and BM25 scored documents by how often the query's words appeared in them, and search engines and enterprise knowledge bases ran on that approach.[4] Text generation from a sequence-to-sequence model was the other established half.[2]

The term comes from a 2020 research paper, which joined a generator to a dense retriever working over an index of Wikipedia passages and trained the two together for open-domain question answering.[2] The paper showed that this did better than a model relying on its parameters alone.[1] Present practice differs from that design in most details. The generator is a general model used as it comes, not one trained with its retriever; the corpus is whatever an organisation holds; and the pipeline is modular, with each component replaceable as better ones appear.[2] What made the pattern ordinary was the arrival of models with longer context windows that follow instructions about the text they are given.[1]

Two later dates recur in the sources. One book places the point at which RAG became a discipline in late 2024, when a model developer reported that prefixing each chunk with a sentence of generated context before embedding it cut retrieval failures by about half, and by two thirds with reranking.[3] Another dates practical local retrieval to 2024 to 2026, when open embedding models reached the quality of commercial ones and running a language model on a personal machine became a one-line command.[6]

How a RAG system works

A RAG system has two phases with different characters. Ingestion turns raw documents into a searchable index, once per document; query time retrieves from that index and generates an answer, once per question.[2] One source compresses the whole flow into nine verbs: load, normalise, chunk, embed, index, retrieve, rerank, assemble, generate.[2]

Ingestion and chunking

Documents arrive as PDFs, word-processor files, web pages, code and email, and each format needs its own parsing: a PDF's columns, headers and tables have to be disentangled, and a web page's navigation stripped.[2] The text is then normalised, a step with a cost on either side, since cleaning too hard destroys things like version numbers and identifiers and cleaning too little leaves noise.[2]

Chunking splits each document into pieces that are embedded and retrieved separately. A chunk should make sense on its own, be small enough to share the context window with others, and follow the structure of the document.[2] The decision is made once and affects every later query, and the sources treat it as the most consequential and least examined choice in the design; one calls it the first tuning knob.[2][3] The methods on offer run from fixed-size and sentence-based splitting through sliding windows and hierarchical parent-and-child schemes to splitting by meaning, and one book notes that recent empirical studies have overturned some assumptions about the last of these.[2]

Query time

When a question arrives it is cleaned, sometimes rewritten or expanded, and embedded with the same model as the documents; the index returns a ranked list of candidate chunks, which may be filtered by metadata such as document type, date or the asker's permissions.[2] The best of these are assembled into a prompt with the system's instructions, the question and an indication of where each passage came from, and the model writes the answer.[2]

The design separates two jobs. The generator does not need to memorise facts, and the retriever does not need to write. The same source gives the corresponding weakness: every component is necessary, and the pipeline fails at its weakest one. If the retrieved context is irrelevant the model invents or declines, and if the model ignores the context the machinery was pointless.[2] The relation between retrieval quality and answer quality is described as a threshold and not a slope. Below a certain level the system fails altogether, which is why an improvement such as reranking can appear to do nothing on a system that already retrieves well and change everything on one that does not.[2] A book on one vector database puts the same point bluntly: a mediocre model with excellent retrieval often gives acceptable answers, and an excellent model with bad retrieval does not.[4]

Keyword search fails when the question and the document use different words for one thing. The example in one sample is a doctor searching for chest pain during exercise when the relevant document speaks of exertional angina.[4] An embedding model answers this by converting a text into a fixed-length list of numbers, a vector, arranged so that texts with similar meanings lie close together; the same sample measures a high similarity between those two phrases although they share no word.[4]

Embedding models

An embedding model is not a generative model, though the two share an architecture and are distributed through the same channels: it returns a vector and cannot write a sentence. A RAG system pairs one of each.[7] Early word embeddings gave a word the same vector wherever it appeared, so that the bank of a river and the bank that holds an account were indistinguishable; current models are contextual, and are trained by contrasting pairs of texts that mean the same thing against pairs chosen at random.[7] Many are also given a short task prefix, so that a query and a document to be retrieved are encoded differently.[7]

Closeness is usually measured by cosine similarity, the angle between two vectors, which for vectors normalised to unit length gives the same ranking as the dot product and as Euclidean distance.[7] EmbeddingGemma 2, the one source given to a single embedding model, describes vectors that can be cut to a shorter length to save storage, and records the detail that a truncated vector has to be normalised again or retrieval quality falls.[7] The same book says of its own subject that its results are competitive, not dominant, and a book on local search argues that the difference between good embedding models now matters less than the difference between having search and not having it.[7][6]

Indexes and vector databases

Comparing a query with every stored vector is exact and scales linearly: with a million vectors of 768 dimensions it costs hundreds of millions of operations per query.[4] Approximate nearest-neighbour indexes give up a little accuracy for a very large gain in speed. The samples list locality-sensitive hashing, inverted-file indexes that search only the most promising clusters, product quantisation, which compresses vectors, and HNSW, a layered graph whose upper levels make long jumps and whose lowest level searches locally, and which is the usual default.[4] Vector Search Inside Out is about that one algorithm; its description promises to build it up from nothing and then to measure each of its settings on real data, including why fixed settings lose recall as a collection grows.[16]

A vector database wraps such an index in what production needs. Mastering Qdrant for RAG Applications argues for a purpose-built one on four grounds: metadata filters applied during the graph search and not after it, a structured payload stored with each vector, persistence, replication and monitoring that a search library lacks, and dense and sparse vectors in one collection.[4] Other sources keep the vectors in a system they already run. Redis for AI Applications: Building Fast, Intelligent Systems (2026) uses an in-memory data store as cache, vector index and full-text search at once, and opens with a support question that is first checked against a semantic cache of earlier answers before any retrieval or model call is made.[9] The two Django books use the pgvector extension to PostgreSQL,[11][10] as does the retrieval chapter of Data Voyage (2026).[12]

Hybrid search and reranking

Semantic search did not retire keyword search. Exact matching still does better for rare terms, identifiers and exact phrases, and the sources agree that the strongest systems run both and merge the two result lists, commonly by reciprocal rank fusion.[2][6] The author of a document management system makes the same remark of his own archive, that neither kind of search is enough alone.[10] The .NET book's vocabulary lists hybrid search as its default retriever.[3]

Reranking is a second pass over the candidates. The embedding model used for retrieval encodes the query and each document separately, which is what makes it fast enough to index a corpus but loses fine detail; a cross-encoder reads the query and a candidate together and scores the pair more accurately, at a cost that confines it to a short list, typically 50 to 200 candidates.[2] The book that gives reranking two chapters calls it the cheapest large improvement available to a retrieval system,[2] and the .NET book calls it the production default of 2026.[3]

Retrieval, fine-tuning and long context

Retrieval is one of several ways to give a model knowledge it was not trained on. Fine-tuning continues a model's training on domain data and changes its weights; RAG changes nothing in the model and supplies the knowledge when the question is asked.[2] The sources draw the line in the same place. Fine-tuning suits what is implicit or behavioural, such as a style, a format or a domain's way of reasoning, and retrieval suits what is explicit, factual, frequently changing or in need of a citation.[2] Fine-tuning on documents is described as expensive, slow to update and liable to disturb what the model could already do,[1] and one sample names the common mistake of fine-tuning on documents that change every week.[2] Many production systems use both, a tuned model for the reasoning and retrieval for the facts, and the advice for the undecided is to begin with retrieval, because a retrieval system is cheaper to change than a model.[2]

A long context window is the other alternative, and the sources do not treat it as a replacement. One notes that even with very large windows there are practical limits on how much can be placed in a single prompt with coherent results.[9]

Hallucination and grounding

RAG is usually justified by hallucination, and the sources are careful about what it does and does not achieve. Grounding means anchoring an answer to retrieved documents, so that a claim can be traced to its source; the .NET book's vocabulary adds that RAG reduces hallucination and does not eliminate it.[3]

Building Hallucination-Resistant RAG and AI Agents gives the fullest account. It defines a hallucination relative to the evidence the system had, not relative to the truth: a claim the retrieved documents do not support is one even when it happens to be correct, and a model that faithfully repeats a wrong date from its knowledge base has made a factual error but has not hallucinated.[5] It separates contradicting the supplied evidence from adding to it, and counts answering when the evidence is insufficient as a distinct failure, of abstention.[5] Its premise is that hallucination cannot be removed, because a model predicts plausible text and common training and evaluation methods reward a guess over an admission of ignorance, so the work is to constrain it in layers: better sources, better retrieval, constrained generation, independent verification, and declining to answer.[5] Each layer adds latency and cost, and the book advises matching the layers to the risk, a medical records system needing far more than a writing assistant.[5]

Beyond chunk, embed and retrieve

The basic recipe has acquired a family of variants, and the vocabulary in Production-Grade RAG with C# and .NET is a compact list of them. In agentic RAG the model decides what to retrieve and when; one technique generates a hypothetical answer and searches with that; another issues several versions of the query and fuses the results; corrective designs grade what was retrieved and fall back to another source when nothing passes; and vectorless retrieval navigates a document's structure of articles, sections and clauses with no embeddings at all.[3] Graph-based designs build a knowledge graph from the corpus, in a version that indexes eagerly and a later one that defers the work to query time at a small fraction of the indexing cost.[3]

Beyond "Chunk and Pray" takes the strongest position against the basic recipe. Its description argues that similarity is not relevance and that retrieved prose is not evidence, and its contents develop an alternative in which a question is translated into structured triples, bound to a verified knowledge graph and answered from asserted facts with their provenance, figures being recalled exactly and vector retrieval kept only as a flagged fallback.[8] The running example is a financial report, and the design includes abstaining when verification fails.[8]

Local and private retrieval

The documents an organisation most wants to search are often those it is least free to send elsewhere. Local AI Search Engine (2026) builds the whole pipeline on the reader's own hardware and gives the reasons as privacy, cost, dependence on a vendor and latency, with a law firm's privileged case files as the example.[6] It also declines to oversell the choice: the sample counts hardware, electricity and engineering time as real costs, includes a hardware table from a processor-only minimum upward, and reports an analysis in which hosted embedding services remain cheaper below a few million tokens a day.[6]

Building a Document Management System (2026) takes a middle course. Its search and classification run locally, only the question-answering assistant calls an outside model, and no document is sent without consent given for that document; without consent the system still searches and simply writes no answers.[10] In a regulated setting the question becomes one of governance: AI for Financial Risk, Compliance and Regulatory Reporting (2026) devotes a chapter to RAG for regulatory intelligence within a banking platform,[18] and Understanding Modern LLM Systems is described as retracing its pipeline to show where confidential data is exposed at each stop.[14]

Evaluation and operation

A RAG system is measured in two places. Retrieval has the long-established metrics of search, such as recall and precision in the top results and rank-sensitive scores; the answer has newer ones, among them faithfulness, the degree to which it is supported by the retrieved context, and the relevance of the context and of the answer.[2][3] Production-Grade RAG with C# and .NET runs a set of 100 reference questions as a gate on every change to the code,[3] and Failure-First AI Agents (2026), an early-access book, is described as turning quality goals into executable evaluations and release gates, with a chapter on retrieval, grounding and citation quality.[17]

Operation brings its own subjects. Retrieval quality decays as content changes or embedding models are replaced, which the .NET book calls embedding drift;[3] indexes have to be updated incrementally as documents are added, changed and deleted;[6] and access control has to hold at retrieval, so that a user is never shown a passage from a document they may not read.[2] The security chapters listed across the sources name prompt injection, poisoned documents and leakage of personal data,[2][1] and regulation appears as an engineering requirement, in audit logging and in a deletion path that reaches every store holding a person's data.[3] The AI Engineer Bootcamp in a Book (2026) is described as treating all of this as ordinary software engineering, with retrieval as one layer of a system that also needs an API, a database, authentication and tests.[13]

Questions about Retrieval-Augmented Generation

Which RAG book should I start with?

The Art and Science of RAG is the general treatment for engineers, assuming code and basic machine-learning concepts but no experience of retrieval or vector databases.[1] A reader who wants the concepts without code can begin with Understanding Modern LLM Systems, described as a 67-page guide that follows one question through a complete system.[14]

What is retrieval-augmented generation?

It is a design in which relevant passages are retrieved from an external knowledge source and included as context when a language model generates its answer.[1] The model itself is not changed, and the knowledge base can be updated without retraining it.[2]

Should I use RAG or fine-tuning?

Retrieval suits knowledge that is explicit, factual, frequently changing or in need of a citation, and fine-tuning suits what is implicit or behavioural, such as style or a domain's way of reasoning.[2] Many production systems combine the two, and the advice for the undecided is to begin with retrieval because it is cheaper to change.[2]

Does RAG stop a model from hallucinating?

No. It reduces hallucination and does not eliminate it.[3] The fullest source on the subject treats it as something to constrain in layers, through better sources, better retrieval, constrained generation, independent verification and declining to answer.[5]

Keyword search scores documents by the query's words and fails when the question and the document use different words for the same thing; vector search compares embeddings, in which texts of similar meaning lie close together.[4] Keyword search remains better for rare terms and identifiers, so the strongest systems run both and merge the results.[2]

Can a RAG system run without sending documents to a cloud service?

Yes. Local AI Search Engine builds the whole pipeline, from parsing to answer generation, on the reader's own hardware.[6] Its sample also counts the hardware and engineering time that this costs and reports that hosted embedding services remain cheaper at low volumes.[6]

Sources

Every source is a Leanpub book or course. The note after each says which part of it was read; where no sample was available, only the public description and table of contents were used.

  1. 1.
    The Art and Science of RAG, Steve Publications: Understanding, Designing, and Deploying Retrieval-Augmented Generation Systems Free sample: chapter 1 (why models need retrieval, RAG in one sentence, the plan of the book) and the opening of chapter 2 on how models store knowledge. 2026. Free sample: PDF · EPUB
  2. 2.
    Embeddings and Reranking in Retrieval-Augmented Generation, Steve Publications: Building Production-Grade Search Systems with Dense Retrieval and Neural Reranking Free sample: the introduction and most of chapter 1 (the retrieve-then-generate architecture, why retrieval quality decides answer quality, the full data flow, RAG against fine-tuning). 2026. Free sample: PDF · EPUB
  3. 3.
    Production-Grade RAG with C# and .NET, Rachid DAHIR: Building Retrieval-Augmented Generation Systems with C#, the Microsoft Agent Framework, and Azure Free sample: the preface, the reading guide, a four-page vocabulary of RAG terms and the contents list; no chapter text. 2026. Free sample: PDF
  4. 4.
    Mastering Qdrant for RAG Applications, Steve Publications: Building Production Vector Search Systems with the Open-Source Vector Database Free sample: the introduction and chapter 1 (keyword against semantic search, embeddings, nearest-neighbour algorithms, why a purpose-built vector database). 2026. Free sample: PDF · EPUB
  5. 5.
    Building Hallucination-Resistant RAG and AI Agents, Steve Publications: A Complete Guide to Reliable, Evidence-Grounded AI Systems Free sample: the introduction and the opening of chapter 1 (hallucination defined relative to evidence, its types and why it cannot be removed). 2026. Free sample: PDF · EPUB
  6. 6.
    Local AI Search Engine, Steve Publications: Building Intelligent Document Retrieval Systems from Scratch Free sample: the introduction and chapter 1 (the case for local search, the system's design goals, hardware requirements and costs). 2026. Free sample: PDF · EPUB
  7. 7.
    EmbeddingGemma 2, Steve Publications: A Technical Guide to Google's Embedding Model for Semantic Search and RAG Free sample: the introduction and chapter 1 (what an embedding is, contextual embeddings and their training, similarity measures, embedding against generative models). 2026. Free sample: PDF · EPUB
  8. 8.
    Beyond "Chunk and Pray", Agus Sudjianto and Wing Yan Lau: Building Trustworthy RAG with Geometric Knowledge Graphs Free sample: the title pages and the detailed contents list only, with no chapter text; cited for its description and contents. 2026. Free sample: PDF
  9. 9.
    Redis for AI Applications: Building Fast, Intelligent Systems, Steve Publications: A Practical Guide to Caching, Vector Search, RAG, LLM Integration, and Production Deployment with Python Free sample: the introduction (a support query traced through cache, retrieval and model; what the data store offers) and chapter 1 on running it locally; the retrieval chapters are not in it. 2026. Free sample: PDF · EPUB
  10. 10.
    Building a Document Management System, Franky Bonanno: with Django 6.1, HTMX and pgvector Free sample: chapter 1 on what a document management system must do and the opening of chapter 2 on the stack; the search and assistant chapters are not in it. 2026. Free sample: PDF
  11. 11.
    Django 6.1 with Python 3.14, Franky Bonanno: From your first project to production: complete web applications with PostgreSQL, semantic search with pgvector, and dynamic interfaces with HTMX Free sample: the prologue and chapter 1 on Python 3.14; nothing on retrieval, which is cited from the description. 2026. Free sample: PDF · EPUB
  12. 12.
    Data Voyage, Irfan Ali: Building Real AI Systems from Data to Deployment Free sample: the contents list, author's note, preface and acknowledgements; no chapter text. 2026. Free sample: PDF
  13. 13.
    The AI Engineer Bootcamp in a Book, AhmedAdawy: Build the Foundations Free sample: a contents list and chapter 1 on AI engineering as system building; retrieval is cited from the description. 2026. Free sample: PDF
  14. 14.
    Understanding Modern LLM Systems, koe: A Field Guide to RAG, Agents, and Beyond No sample: from the description and its chapter list. 2026.
  15. 15.
    Production RAG and GenAI Systems, Arvind Kumar No sample: from the description. 2026.
  16. 16.
    Vector Search Inside Out, Ritesh Modi No sample: from the description. 2026.
  17. 17.
    Failure-First AI Agents, storymaker: A Practical Field Guide to Evaluating RAG, Tool Use, Memory, and Multi-Agent Systems No sample: from the description and table of contents. 2026.
  18. 18.
    AI for Financial Risk, Compliance and Regulatory Reporting, Sreedhara Reddy Kotha: Production Systems and Architecture for Modern Banking No sample: from the description and table of contents. 2026.

Further reading

Other books in the library on the same ground, not cited above.

  • The Prompting Playbook, Steve Publications: A Definitive Guide to Mastering Human–AI Communication with Large Language Models A general reference on prompting language models, with one chapter on RAG and prompt design for it. 2026. Free sample: PDF · EPUB
  • Building AI Agents with Ollama, Steve Publications: Design, Deploy, and Scale Reliable Local AI Systems On building agents that run on local hardware, with a chapter on retrieval and vector search. 2026. Free sample: PDF · EPUB
  • The Agentic AI CourseCourse, Dr. Ryan Rad: From Language Models to Multi-Agent Systems A twenty-lesson course on agentic systems, from model fundamentals to multi-agent orchestration. 2026.

This is an article created from the free samples of 13 Leanpub books and the descriptions and tables of contents of 5 more. We're building these articles to provide you, the Leanpub reader, with a good jumping-off point to discover more Leanpub books that are interesting and relevant to you. We never use material which is paid-only when building these articles: we only use material which is already free on Leanpub. However, Leanpub authors can opt out from inclusion in articles from their book settings page.

Updated November 2026.

In the Leanpub store: 33 books · 2 courses in the Retrieval Augmented Generation category · also filed under Vector Database

All topics