liveBook · Manning

Chapter 3: Grounding outputs with RAG

What you will learn in chapter 3 of Building Reliable AI Systems

This introduction explains why prompting and training alone cannot keep a chatbot current, and how RAG uses retrieved information to ground its answers.

After this chapter you will be able to

What it builds on

Section by section

Introduction

This introduction explains why prompting and training alone cannot keep a chatbot current, and how RAG uses retrieved information to ground its answers.

Key terms: basic prompting, live external data streams, application orchestrating the LLM, pretraining, fine-tune, snapshot, freshness problem, retrieval-augmented generation (RAG), real-time information retrieval, retrieved context

3.1 What is RAG?

This section explains how RAG uses retrieved information to ground LLM responses, why that helps in changing domains, and why retrieval does not guarantee reliability.

Key terms: RAG, retrieval component, external knowledge sources, grounding, hallucinations, real-time information retrieval, retraining, retrieval latency, embedding, indexing

3.2 RAG system architecture

Introduces the two main components of RAG architecture and their shared purpose in producing grounded responses.

Key terms: retrievers, generators, RAG system architecture

3.2.1 The role of the retriever

This section explains how a RAG retriever finds relevant information in external sources for a user query.

Key terms: retriever, external knowledge sources, indexed

3.2.2 The factual generators

This section explains how a RAG generator uses a user query and retrieved information to produce a relevant, factually grounded response.

Key terms: generators, retrieved information, user’s query, retrieved context

3.2.3 RAG system flow

This section traces how a RAG system turns a user query and retrieved knowledge into a context-informed response.

Key terms: user query, retriever, knowledge base, generator, retrieved context

3.2.4 Example: E-commerce shopping assistant

Uses a lamp-warranty question to show how retrieval and generation work together to produce a grounded shopping-assistant response.

Key terms: retriever, generator, retrieved warranty information, grounded, hallucinations, up-to-date, verified information, stand-alone language models

3.3 Reducing hallucinations with RAG

This section introduces how grounding RAG responses in retrieved evidence helps reduce hallucinations.

Key terms: RAG, hallucinations, retrieved evidence, parametric memory, grounding

3.3.1 Grounding the language model

This section explains how RAG grounds a response in retrieved information rather than relying only on a model’s training data.

Key terms: RAG, grounding, verified sources, training data

3.3.2 Grounding an e-commerce product query

The section contrasts a plausible but potentially wrong return-policy answer with an answer grounded in the store’s actual policy through RAG.

Key terms: RAG, retriever, generator, store credit, return policy

3.3.3 Advantages of RAG in reducing hallucinations

This section explains how RAG reduces hallucination risk by drawing on current, specific, traceable information from a shared knowledge base.

Key terms: current information, training data, adaptability, precise answers, knowledge base, generic responses, authoritative sources, credibility, trace, consistency

3.3.4 Critical applications

This section explains why grounding RAG responses in authoritative, current sources matters especially in high-stakes applications.

Key terms: RAG, grounding, authoritative sources, accountability

3.3.5 Enhancing transparency

This section explains how source references make RAG responses easier to check, while emphasizing that RAG still requires oversight.

Key terms: references, traceability, retrieval gaps, outdated or incomplete, hallucinate, oversight, guardrails, evaluation

3.4 Data preparation and reliable indexing for RAG systems

Explains how a RAG retriever prepares and indexes data so it can find relevant information quickly.

Key terms: indexing, DocumentLoaders, text splitters, chunks, embeddings, meaning of text

3.4.1 Introducing LangChain

The section introduces LangChain as a way to connect LLM application components and explains its limited role in the chapter’s initial RAG examples.

Key terms: LangChain, RAG system, external knowledge, prompt templates, helper library, text splitting, document loading, RAG pipelines

3.4.2 Structuring product catalogs

The section states why embeddings are useful when preparing a product catalog for an e-commerce chatbot.

Key terms: embeddings, user queries, product information

3.4.3 Creating the searchable vector index

This section explains how a searchable vector index makes embedded text chunks available for efficient retrieval in a RAG system.

Key terms: searchable vector index, vector store, embedded chunks, similarity

3.4.4 Implementing an index

This section explains why a FAISS index helps a chatbot retrieve relevant embedded information for its responses.

Key terms: Facebook AI Similarity Search (FAISS), FAISS index, embedded data, high-dimensional vectors

3.5 Building an effective RAG system

This section traces how a RAG system turns a user’s question into an answer informed by retrieved data.

Key terms: Question, Retrieve, Prompt, LLM, Answer, knowledge base, query processing, retrieval stage, embedding the query

3.5.1 Building an e-commerce chatbot powered by RAG

The section outlines how Clara, an e-commerce RAG chatbot, retrieves relevant information and uses it to answer a customer’s question.

Key terms: Clara, RAG pipeline, FAISS similarity search index, embedding model, matching contexts, LLM

3.5.2 Processing user queries

The section explains how embedding a customer query helps an e-commerce chatbot find relevant knowledge-base documents for its response.

Key terms: query, embedding process, product data chunks, knowledge base, relevant documents

3.5.3 Crafting an accurate response using an LLM

Shows how an e-commerce chatbot combines a customer question with retrieved manual passages in a prompt so an LLM can produce a relevant answer.

Key terms: prompt template, customer’s question, context, knowledge base, LLM

3.6 Evaluating and optimizing RAG systems

Introduces why RAG systems need evaluation and why assessing them is challenging.

Key terms: RAG systems, retrieval, generation, evaluating RAG systems

3.6.1 The role of evaluator LLMs in assessing hallucinations

This section explains how evaluator LLMs assess RAG responses for hallucination risks and how their feedback supports improvement over time.

Key terms: evaluator LLM, factual correctness, contextual appropriateness, hallucination indicators, nuanced scores, hallucination assessment at scale, feedback loop, evaluation prompts, reference examples, reference responses

3.6.2 Crafting evaluation datasets

This section explains how to build and maintain a telecom RAG chatbot evaluation dataset that exposes plausible but unsupported answers.

Key terms: evaluation data, query types, hallucination, authoritative answer sources, knowledge base, ground truth, vetted answer sources, hallucination examples, unsupported information, evaluator LLM

3.6.3 Practical metrics for RAG evaluation

The section introduces practical measures of RAG retrieval and answer quality, then distinguishes five RAGAS metrics.

Key terms: retrieval precision, answer-relevance score, factual accuracy, embeddings, cosine similarity, human-evaluation score, rubric, relevance, coherence, usefulness

3.6.4 Implementing RAGAS evaluation

Introduces a forthcoming RAGAS evaluation example using a sample test dataset, without showing the implementation.

3.6.5 Reducing hallucinations by filtering retrievals and using metadata

The section explains how filtering retrieved passages and keeping context concise helps a RAG system ground answers and reduce hallucinations.

Key terms: context window, Lost in the Middle, U-shape performance curve, semantic relevance filtering, semantic similarity threshold, metadata tags, query intent, metadata-based categorization, context length optimization, extractive summarization

3.6.6 Metadata-based filtering in a telecom chatbot

Shows how a telecom RAG chatbot can extract filters from a customer’s query and use them with BM25 retrieval to find more relevant documents.

Key terms: Best Match (BM25), keyword-based ranking, embedding-based retrieval, QueryMetadataExtractor, PromptBuilder, OpenAIGenerator, metadata fields, structured dictionary, metadata filtering, InMemoryBM25Retriever

3.6.7 Embedding chunk sizes and model choice

This section explains how testing retrieval chunk settings and embedding models, then evaluating the whole RAG system, helps improve reliability.

Key terms: chunk size, overlap, number of chunks retrieved, embedding model, evaluation datasets, individual components, integrated whole, evaluation and refinement

3.7 Advanced techniques for improving RAG

Introduces upcoming advanced RAG techniques as ways to address challenges and improve reliability, without explaining any technique.

3.7.1 Fine-tuning embeddings for in-domain relevance

Explains why RAG embeddings should be adapted to a domain and how to obtain and maintain in-domain training data.

Key terms: pretrained contextual embeddings, in-domain fine-tuning, retrieval accuracy, in-domain dataset, question-document pairs, synthetic questions, continuous embedding retraining

3.7.2 Incorporating metadata to reestablish context

This section explains how metadata can restore context lost when RAG retrieves documents in isolation.

Key terms: metadata, embedding creation, secondary filtering stage

3.7.3 Implementing hybrid retrieval

The section explains how combining retrieval techniques can improve accuracy and mentions two other ways to combine techniques for particular needs.

Key terms: hybrid retrieval, keyword search, embedding similarity, date and time filters, embeddings, cascading, query complexity

3.7.4 Enhancing queries via rephrasing and augmentation

The section distinguishes three ways to enhance a user query so retrieval can find more relevant material.

Key terms: query rephrasing, query augmentation, ensemble retrieval effect, Hypothetical Document Embeddings (HyDE), semantic search

3.7.5 Implementing query routing

Query routing classifies a query to choose a suitable index and can assign simpler queries to smaller models, improving RAG efficiency.

Key terms: query routing, query classification, indexes, smaller LLMs, more capable models, cost efficiency

3.7.6 GraphRAG: Knowledge graph-enhanced retrieval

This section explains why cross-document questions challenge standard RAG and how GraphRAG uses a knowledge graph and summaries to support corpus-wide answers.

Key terms: Standard RAG, text chunks, relationships between entities, GraphRAG, knowledge graph, entities and relationships, community summaries, hierarchical summaries, global queries

3.7.7 When to use GraphRAG vs. traditional RAG

The section explains when GraphRAG’s cross-document connections justify its indexing overhead and sketches how a Neo4j knowledge graph is populated.

Key terms: GraphRAG, indexing overhead, traditional chunk-based RAG, Neo4j, entity extraction, entities, relationships, Cypher MERGE

3.7.8 Agentic RAG: Agent-controlled retrieval

This section introduces agentic RAG as agent-controlled retrieval and illustrates how it combines multiple lookups to answer a comparison question.

Key terms: agentic RAG, AI agent, retrieval process, policy database, reviews database, synthesize

3.8 Building an RAG system for an e-commerce chatbot

Introduces an e-commerce RAG chatbot project and explains why LangChain helps assemble its retrieval and generation components.

Key terms: LangChain, higher-level abstractions, orchestration, retrieval, generation

3.8.1 Step 1: Install the required libraries

Identifies the libraries to install for the e-commerce RAG chatbot and the role each plays.

Key terms: LangChain, torch (PyTorch), transformers, sentence-transformers, datasets, faiss-cpu, similarity search, dense vectors

3.8.2 Step 2: Import libraries

3.8.3 Step 3: Load the documents

This section explains why the product dataset matters to an e-commerce chatbot and suggests a source when no private dataset is available.

Key terms: dataset, product descriptions, reviews, customer Q&As, Kaggle, Amazon Reviews

3.8.4 Step 4: Document transformers

This section explains why lengthy product descriptions are split into smaller chunks before further processing.

Key terms: document transformers, chunks, contextual information

3.8.5 Step 5: Embed text

This step explains why product descriptions are embedded and why a compact embedding model was chosen.

Key terms: embedding, vector space, semantic meaning, retrieval component, sentence-transformers/all-MiniLM-L6-v2, size and performance, semantic understanding

3.8.6 Step 6: Choose a vector store

This section chooses FAISS for similarity-based product retrieval and explains its persistence limitation.

Key terms: FAISS, vector store, similarity searches, FAISS indexes, faiss.write_index(), managed vector database, persistence

3.8.7 Step 7: Prepare the LLM model

This step selects an extractive question-answering model to identify answer spans in passages retrieved for customer queries.

Key terms: bert-base-uncased, AutoModelForQuestionAnswering, extractive question-answering, answer span, retriever

3.8.8 Step 8: Add a retriever

This section explains how the retriever brings query-relevant product information to the chatbot’s language model.

Key terms: retriever component, product information, raw data, chatbot’s language model

3.8.9 Step 9: Create a retrieval QA chain

This step combines a retriever and a QA model into a RetrievalQA chain that fetches relevant context before answering.

Key terms: retriever, question-answering (QA) model, RetrievalQA chain

3.8.10 Step 10: Test the chatbot

3.8.11 Step 11: Evaluate and prevent hallucinations with LangChain

This section shows how to assess whether an e-commerce chatbot’s answers are supported by retrieved documents and suggests ways to reduce unsupported answers.

Key terms: hallucination_score, response tokens, retrieved source documents, grounding quality, test queries, ground-truth answers, product knowledge base, retrieval process, embedding models, similarity search

3.8.12 Challenges and adaptations of the chatbot

The section identifies practical challenges for an e-commerce RAG chatbot and emphasizes that reliable production use requires continued attention after implementation.

Key terms: Data quality, diverse queries, Response accuracy and relevance, index, Scalability, Feedback mechanism, customer interactions, RAG, dynamic information retrieval, chunking strategies

3.9 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 2: Generating trustworthy responses with prompt engineering Chapter 4: Embeddings and vector search →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.