Overview

6 Retrieval Augmented Generation (RAG)

Retrieval Augmented Generation (RAG) combines semantic retrieval with large language model generation to ground answers in factual, up-to-date sources and curb hallucinations. This chapter shows how to turn plain search into conversational, personalized assistance by uniting encoders (for retrieval) and decoders (for fluent responses). It walks through two end-to-end applications: upgrading the Travelle hotel search into a recommendation assistant and building a research agent that synthesizes insights from academic papers with clear source attribution. It also compares industrial and open-source LLMs and demonstrates using a unified gateway to experiment with multiple models and balance cost, quality, and reliability.

Under the hood, the RAG pipeline spans query processing, embeddings, a vector-backed knowledge base, retrieval, prompt construction, and guided generation. The chapter emphasizes why long documents must be chunked: fixed context windows and information dilution make single-shot embeddings ineffective. It introduces practical chunking strategies—fixed-size, sentence/paragraph, semantic, and especially recursive splitting with overlaps—to preserve meaning while fitting model limits. For production-scale retrieval, it replaces FAISS with a vector database, highlighting Qdrant for efficient similarity search, robust metadata filtering (for example, city-scoped hotel queries), hybrid search, and scalable operations. With structured prompts and streaming, raw ranked results become coherent narratives tailored to the user’s intent.

Because RAG quality depends on both what is retrieved and what is generated, the chapter establishes an evaluation toolkit. Retrieval is assessed with precision@K, recall, MRR, NDCG, and context relevance, while generation is judged on faithfulness to sources, answer relevancy, context adherence, and completeness. The RAGAS framework provides a reference-free, LLM-assisted suite of core metrics and a composite score, complemented by techniques like LLM-as-judge, synthetic test sets, and production-aligned testing. By the end, readers have built two complete RAG systems, understand the necessity and methods of chunking, know when and how to adopt vector databases, can select appropriate LLMs, and have a clear path to measuring and improving reliability as they move toward enterprise- and agentic-grade RAG.

Architecture of a Retrieval Augmented Generation (RAG) system showcasing the integration of retrieval and generative components for enhanced natural language processing tasks.
OpenRouter.ai landing page, allowing access to potentially any LLM Endpoint
Computational Cost of Context Window Expansion
Comparison of LLM Text Chunking Strategies
Metrics for Evaluating Retrieval Engine
Metrics for Evaluating LLM Generation
RAGAS Core Metric extensively covers LLM Grounding and Response (Source)

Summary

  • Retrieval Augmented Generation combines semantic search capabilities with language model generation to eliminate hallucinations and provide accurate, contextually relevant responses grounded in factual information, representing a fundamental shift from standalone LLMs to knowledge-grounded AI systems.
  • Context window limitations in embedding models (8,192 tokens for Nomic Embed) require recursive chunking techniques that break down large documents into semantically coherent segments while preserving context through overlap, enabling effective processing of research papers and comprehensive hotel descriptions without losing critical information.
  • OpenRouter's unified API enables seamless integration of multiple language models with retrieval results, producing coherent, well-cited responses that synthesize information from multiple sources while maintaining factual accuracy and providing flexibility in model selection for different use cases.
  • Production-ready vector databases like Qdrant provide essential capabilities over experimental FAISS setups, including persistent storage, concurrent access, and optimized retrieval algorithms necessary for enterprise-scale RAG applications that require reliability and performance at scale.
  • RAG's versatility spans diverse domains from personalized travel recommendations (Travelle hotel search) to academic literature analysis (research paper agents), demonstrating consistent accuracy and source attribution capabilities across different content types and user requirements.
  • Dense vector representations through models like Nomic Embedding enable sophisticated semantic understanding, while metadata filtering capabilities allow targeted searches (city-specific hotels, year-filtered papers) that significantly improve retrieval precision and computational efficiency.
  • Systematic RAG evaluation through frameworks like RAGAS requires measuring both retrieval quality and generation accuracy using metrics including faithfulness, context precision, context recall, and answer relevancy to ensure production system reliability and continuous improvement.

FAQ

What is Retrieval Augmented Generation (RAG) and why is it important?RAG combines a retriever (semantic search over external knowledge) with a generator (LLM) so answers are grounded in factual, retrieved context. This reduces hallucinations, brings in up-to-date, domain-specific information, and produces responses that are both accurate and well-articulated. It shifts systems from keyword search to conversational, evidence-backed answers.
How does a RAG pipeline work end-to-end?A typical flow is: (1) Process the user query and embed it, (2) Retrieve top-k relevant chunks from a knowledge base via a vector index/database, (3) Construct a prompt that includes the original query and the retrieved context, (4) Generate an answer with an LLM that attends to the supplied context, often with citations, and (5) Optionally stream the output and return both the answer and sources.
How does RAG reduce hallucinations in LLMs?By retrieving evidence first and feeding it to the LLM, RAG constrains the model to generate from verified context rather than relying solely on its parametric memory. Clear prompt instructions to “answer based only on the provided context” and to cite sources further improve factuality and transparency.
Why do we need to chunk documents, and which chunking strategies work best?Embedding models have fixed context windows and long texts cause information dilution and truncation. Chunking creates focused, retrievable segments that fit the window and improve precision. Useful strategies include: fixed-size (simple but may split meaning), sentence-based or paragraph-based (preserve boundaries), recursive splitting (tries larger natural separators first, then smaller, with overlap), and semantic chunking (topic-aware, more compute-heavy).
When should I use a vector database instead of FAISS, and what does Qdrant add?Use a vector database for production needs like scale, reliability, and metadata filtering. Qdrant adds filterable HNSW for fast similarity with rich filters, hybrid search (sparse + dense), multi-vector search, sharding/partitioning, and quantization/offloading for cost-performance. FAISS is great for prototypes or single-machine setups; vector DBs shine with large, evolving datasets and operational requirements.
What is hybrid search and how does metadata filtering improve RAG relevance?Hybrid search blends semantic vectors with lexical/sparse signals and metadata filters. Pre-filtering (e.g., locality = “Istanbul”) shrinks the candidate set before similarity search, improving precision and speed while ensuring geographic or policy constraints are respected. This yields more relevant, diverse, and efficient retrieval for the LLM to use.
What is OpenRouter and why use it in a RAG system?OpenRouter provides a unified API to multiple LLMs (e.g., GPT-4, Claude, Mistral), enabling model switching, fallbacks, and cost optimization without major code changes. It helps teams test models, balance performance and price, and ensure reliability in production via automatic fallbacks.
How do I evaluate a RAG system effectively?Evaluate both retrieval and generation: - Retrieval: Precision@K, Recall, MRR, NDCG, Context Relevance. - Generation: Faithfulness (grounded in context), Answer Relevancy (to the query), Context Adherence (no extra claims), Completeness. RAGAS offers a reference-free suite (context precision/recall, faithfulness, answer relevancy) and a composite score. Advanced practices include LLM-as-judge, synthetic test data, and production-aligned testing.
What did the Travelle hotel search example demonstrate?It showed how semantic search over hotel reviews plus an LLM yields personalized, conversational recommendations with citations instead of raw ranked lists. Starting with FAISS in a single city (Paris), the system then scaled via Qdrant to support multi-city retrieval with metadata filters and hybrid search for higher relevance and efficiency.
What did the research-paper RAG example show, and what were the key steps?It demonstrated scholarly RAG with precise retrieval and proper source attribution. Key steps: acquire abstracts (Kaggle), recursively chunk with overlap, embed (e.g., Nomic), store chunks in Qdrant, query via semantic similarity, and generate answers with OpenRouter while citing authors/titles/venues. Chunking was critical to avoid context overflow and to retrieve the exact, technical segments needed.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build an Advanced RAG Application (From Scratch) ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build an Advanced RAG Application (From Scratch) ebook for free