Share E-Book

RAG from First Principles - Engineering retrieval-augmented generation systems with Python, LangChain, and LlamaIndex (Jia Huang)(Z-Library)

Author Jia Huang

artificial intelligence
Language English

A rigorous, code-first guide to RAG engineering by a bestselling AI author. Master data ingestion, chunking, embeddings, vector storage, hybrid retrieval, reranking, and evaluation from the ground up. Key Features Engineer RAG systems layer by layer, from ingestion to evaluation Master hybrid retrieval, reranking, and index optimization strategies Learn through a dialogue-driven, code-first teaching style used by 10,000+ of students Book Description Most developers can spin up a RAG pipeline in an afternoon using LangChain or LlamaIndex. Far fewer understand why retrieval fails or how to fix it. This book is for those who want to go deeper. RAG From First Principles dismantles the retrieval-augmented generation stack layer by layer, explaining how documents are ingested and parsed, why chunking strategy directly impacts answer quality, how embedding models encode meaning, what happens inside a vector database, and how sparse and dense retrieval interact in a hybrid system. Written by Jia Huang, a research engineer and bestselling AI author, it brings both research depth and production experience to one of AI's most critical engineering disciplines. Structured as a progressive dialogue between a seasoned engineer and two students, the book surfaces the questions practitioners actually ask. Each chapter builds on the last, covering topics from data import and chunking to embedding selection, index design, hybrid search, and post-retrieval processing, before moving on to response generation, evaluation, and advanced paradigms including GraphRAG, Agentic RAG, and Modular RAG. By the end, you'll have the architectural understanding to optimize, debug, and extend your RAG systems with confidence.

Format PDF
Size 18.0 MB
10
Views
0
Downloads
0.00
Total Donations
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
RAG from First Principles Engineering retrieval-augmented generation systems with Python, LangChain, and LlamaIndex Jia Huang
Page 3
RAG from First Principles Copyright © 2026 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing, nor its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. This book was written by Jia Huang. Generative AI tools were used only to assist with ideation, phrasing, and diagram drafts, and all technical content and code were created, verified, and tested by the author and Packt’s editorial team. Packt does not accept AI-generated content that replaces expert authorship. Portfolio Director: Gebin George Relationship Lead: Akash Sharma Project Manager: Prajakta Naik Content Engineer: Afzal Shaikh Technical Editor: Sumant Jadhav/Rahul Limbachiya Indexer: Rekha Nair Production Designer: Prashant Ghare/Shankar Kalbhor Growth Lead: Akash Sharma First published: May 2026 Production reference: 1290526 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul’s Square Birmingham B3 1RB, UK ISBN 978-1-83588-866-7 www.packtpub.com
Page 4
Contributors About the author Jia Huang is a Lead Research Engineer at A*STAR (Agency for Science, Technology and Research), Singapore, where his work focuses on NLP, large language models, and applied AI engineering. With over twenty years of experience leading large-scale AI and data projects across government, finance, healthcare, and e-commerce, he brings an unusually practical lens to technically rigorous subjects. In recent years, his research has primarily focused on NLP pre-trained large models and FinTech applications. He is the author of six bestselling technical books, including Hands-on AI Agent Development for Large Model Applications, selected as one of JD Best Books of 2024, and GPT: How Large Models Are Built, named CSDN’s Most Influential IT Book of 2023. His online RAG engineering course has been completed by over 10,000 students.
Page 5
About the reviewer Naresh Dulam is a visionary technology leader with deep expertise in data analytics, cloud computing, and artificial intelligence. With a career spanning influential roles across Health- care, Telecom, and financial sectors, he has led transformative analytical platforms that deliver sustainable and impactful solutions to address evolving industry needs. As a forward-thinking innovator, Naresh combines technical expertise with a passion for knowledge-sharing, mentoring aspiring professionals, and fostering ethical practices. His commitment to driving innovation and creating meaningful impact is matched by his vision of inspiring the next generation of technol- ogists. Beyond his professional achievements, Naresh enjoys exploring nature on adventurous expeditions and empowering others to achieve their full potential.
Page 6
Subscribe for a free ebook New frameworks, evolving architectures, research drops, production breakdowns – AI_Distilled filters the noise into a weekly briefing for engineers and researchers working hands-on with LLMs and generative AI systems. Subscribe now and receive a free eBook, along with weekly insights that help you stay focused and informed. Subscribe at https://packt.link/8Oz6Y or scan the QR code below.
Page 7
(This page has no text content)
Page 8
Table of Contents Preface xix Free benefits with your book xxiv Chapter 1: Data Import 1 Does the parsing process depend on file type? 2 Reading simple text with a DataLoader 3 Using LangChain to read TXT files and generate document objects • 4 Data loaders in LangChain • 5 Using LangChain to read all files in a directory • 7 Using LlamaIndex to read all documents in a directory • 10 Connect learner with LlamaHub and read database entries • 12 Reading various types of documents with the unstructured tool • 13 Parsing specific elements with the JSON loader 15 Reading text from images 19 Reading text using UnstructuredLoader • 19 Reading text using UnstructuredImageLoader • 19 Reading text from a PPT • 20 Using large models for holistic image-text parsing • 22 Wukong title • 25 Body • 25 Image content • 25 Prologue title • 25 Body • 25 Image content • 25 Adaptations from Journey to the West • 26 Body • 26 Image content • 26
Page 9
Table of Contentsviii Importing table data in CSV format 26 Importing data using CSVLoader • 26 Comparing CSVLoader and UnstructuredCSVLoader • 29 Crawling and parsing web documents 30 Parse web pages with WebBaseLoader • 31 Granular webpage parsing with UnstructuredLoader • 33 Understanding the cultural and story background of Black Myth: Wukong 35 Markdown file titles and structure 36 Why Markdown? • 36 Implementing UnstructuredMarkdownLoader • 37 Text formats, layout recognition, and table parsing in PDF files 39 Using loading tools for PDF files • 40 Simple text extraction with PyPDFLoader • 42 Using the Marker tool to convert PDF documents to Markdown format • 43 Structured parsing with UnstructuredLoader • 49 Visualizing layout with PyMuPDF and coordinate information • 56 Using UnstructuredLoader to parse tables in PDF pages • 60 Integrating content under the same title using ParentID • 63 Summary 65 Get this book’s PDF version and more 66 Chapter 2: Text Chunking 67 Why chunking is very important 68 Context window limits the maximum chunk length 69 Impact of chunk size on retrieval accuracy • 71 Impact of chunk size on generation quality • 73 How small can the chunk size be while still retaining enough context? • 73 Different chunking strategies 74 Visualize chunking with the ChunkViz tool • 75 Chunking by a fixed number of characters • 76 The CharacterTextSplitter tool in LangChain • 76
Page 10
Table of Contents ix Setting chunk size parameters in LlamaIndex • 79 Recursive chunking • 79 Chunking based on specific formats • 81 Chunking based on document structure or semantics • 83 Using the unstructured tool for document structure-based chunking 83 Using LlamaIndex SemanticSplitterNodeParser for semantic chunking 85 Advanced indexing techniques related to chunking 86 Sentence splitting with sliding window • 87 Mixed generation of parent and child text blocks during chunking • 88 Creating metadata for text chunks during chunking • 90 Workflow of HyDE technology 92 Forming hierarchical indices during chunking • 92 Document embedded object technology for complex data structures • 94 Summary 95 Subscribe for a free eBook 96 Chapter 3: Information Embedding 97 Embedding is the encoding of external information 97 Measuring similarity between vectors 101 From early word embedding models to large model embeddings 102 Early word embedding models • 102 Contextual word embedding models • 103 Sentence embedding models and the SentenceTransformers framework • 104 Computing semantic similarity between two sentences • 107 Multilingual embedding models • 108 Embedding models for different data types • 108 Image, audio, and video embedding models • 108 Joint image and text embedding models • 109 Graph and knowledge graph embedding models • 110 Embedding models in the era of large language models • 111
Page 11
(This page has no text content)
Page 12
Table of Contents xi Mainstream vector databases 160 Selection and evaluation of vector databases 163 Vector database selection • 164 Index and search settings in vector databases 167 Milvus vector operation example • 167 Preparing the sample dataset • 168 Creating a Milvus collection and index • 169 Example: Inserting and querying monster data with vector search • 171 Choosing the appropriate index type 173 FLAT (Exact brute-force search) • 174 IVF_FLAT (Inverted file index + Exact search) • 175 IVF_PQ (Inverted file index + Product quantization) • 177 ScaNN • 178 HNSW • 179 HNSW_SQ, HNSW_PQ, and HNSW_PRQ • 180 SPARSE_INVERTED_INDEX • 181 BIN_FLAT and BIN_IVF_FLAT • 182 Disk index and GPU index • 182 Selecting the appropriate metric 183 Commonly used metrics for dense floating-point vectors • 185 The metric used in search must match the index • 188 Search and query: Two retrieval methods 192 Using Milvus for hybrid search 193 Floating point vectors, sparse floating point vectors, and binary vectors • 194 Hybrid retrieval strategy implementation • 196 Building a hybrid retrieval system using Milvus • 197 Vector databases and multimodal retrieval 203 Using the visualized BGE model for multimodal retrieval • 204 Loading the visualized BGE model • 205 Creating the image dataset • 206 Generating image embeddings • 207
Page 13
Table of Contentsxii Storing image vectors in Milvus • 208 Creating a multimodal search function • 209 Executing a sample image search query • 210 Visualizing the search results • 211 Using ResNet-34 to extract image features and perform retrieval 213 Extracting image features with ResNet-34 • 214 Storing scene features in Milvus • 214 Searching for similar scenes • 216 Data maintenance and vector storage CRUD operations in RAG systems 217 Data flow maintenance and management in RAG systems • 217 Vector insert, delete, and update operations in Milvus • 218 Inserting vector entities • 219 Upserting vector entities • 219 Deleting vector entities • 220 Collection operations in vector databases • 221 Viewing collection information • 221 Load collection into memory • 221 Release memory resources • 222 Deleting a collection • 222 Summary 222 Chapter 5: Pre-Retrieval Processing 223 Why pre-retrieval processing matters 223 Techniques included in pre-retrieval processing 224 Query construction: Asking questions in natural language 225 Text-to-SQL: Transforming natural language into SQL 226 Why Text-to-SQL matters in RAG • 226 Traditional Text-to-SQL implementation • 227 Text-to-SQL in the deep learning era • 228 Large language model-based Text-to-SQL implementation • 229 Example: Building a simple Text-to-SQL workflow • 229
Page 14
Table of Contents xiii Solution combining agent, SQL data function, and tool calls • 234 How to understand metadata extraction • 235 What are data functions • 235 Two-turn conversational query process • 238 Text-to-cypher: From natural language to graph database queries 243 Understanding graph databases • 243 Core components of a graph database • 244 Why graph databases matter in RAG • 244 Basic Cypher syntax • 246 Text-to-Cypher workflow • 246 Example: Generating a Cypher query from natural language • 247 SQL query vs Cypher query • 248 Self-query retriever automatically generating metadata filter conditions from queries 249 Metadata fields for video retrieval • 249 Combining vector retrieval and metadata filtering • 250 Installing required libraries • 252 Loading documents with metadata • 252 Building the self-query retriever • 253 Configure metadata fields for the retriever • 254 Limitations of Self-query retriever • 257 Query translation: Better explaining user questions 257 Query rewriting: Reformulating the original question into an appropriate form • 258 Guiding large language models to rewrite queries via prompts • 258 Optimizing queries with RePhraseQueryRetriever • 259 Query decomposition: Breaking down queries into multiple subproblems • 260 Using MultiQueryRetriever • 261 Query clarification: Step-by-step refinement and clarification of user questions • 264 Query expansion using HyDE to generate hypothetical documents • 269 Query routing finding the right data source 273 Logical routing determining the path of the query • 274
Page 15
Table of Contentsxiv Example: Routing to different data sources • 275 Semantic routing: Selecting relevant prompts • 276 Example: Routing to prompt templates • 276 Summary • 277 Get this book’s PDF version and more 279 Chapter 6: Index Optimization 281 From small to large node-sentence sliding window and parent-child text chunks 282 Node-sentence sliding window retrieval • 283 Parent-child text chunk retrieval • 287 From summary to detail: building summary-to-detail indexes with IndexNode and RecursiveRetriever 291 Implementation of the Summary-to-Detail strategy in LlamaIndex • 292 Hierarchical merging HierarchicalNodeParser and RAPTOR 296 Creating hierarchical indexes with HierarchicalNodeParser • 297 Using RAPTOR to recursively generate multi-level indexes • 301 Forward/backward linking connecting related nodes by forward/backward extension 304 Hybrid retrieval improving retrieval accuracy and expanding coverage 309 Combining BM25 and semantic retrieval with ensemble retriever • 309 Using MultiVectorRetriever to implement multi-representation indexing • 316 Hybrid querying and query routing • 319 Summary 319 Subscribe for a free eBook 320 Chapter 7: Retrieval Post-Processing 321 Common retrieval post-processing techniques 323 Reranking • 323 RRF re-ranking • 323 How should I understand the smoothing parameter? • 325 Cross-encoder re-ranking • 331 ColBERT re-ranking • 334
Page 16
Table of Contents xv Cohere re-ranking and Jina re-ranking • 339 Introduction to Jina reranker v2 • 341 Applications and capabilities • 341 Performance and efficiency • 342 Integration and access • 342 RankGPT and RankLLM • 342 Time-weighted re-ranking • 344 Difference between LangChain and LlamaIndex recency weighting 347 Compression 348 Contextual compression retrievers • 348 Compressing prompts with LLMLingua • 351 How to use LLMLingua to compress prompts • 353 RECOMP method • 355 Sentence embedding optimizer • 355 Remembering long context through prompt caching 357 Correction 358 Summary 369 Get this book’s PDF version and more 371 Chapter 8: Response Generation 373 Improving LLM output quality by refining prompts 374 Guiding generation results with templates and examples • 375 Enhancing the diversity and comprehensiveness of generation • 377 Introducing fact-checking mechanisms to enhance factual accuracy • 378 Controlling output format through output parsing • 378 LangChain output parsing mechanisms • 379 LlamaIndex output parsing mechanisms • 379 Basic parsing mode • 382 Structured parsing mode • 382 OpenAI’s JSON mode and structured output • 384 Pydantic parsing • 385
Page 17
Table of Contentsxvi Function call parsing • 388 Improving output quality through model choice • 389 Methods of integrating retrieved results into the generation process • 391 Input layer integration • 392 Output layer integration • 393 Intermediate layer integration • 393 Self-RAG generation • 394 RRR dynamic generation optimization • 396 Summary 398 Subscribe for a free eBook 398 Chapter 9: System Evaluation 399 Evaluation system for RAG systems 401 Evaluation dataset for RAG • 402 Retrieval evaluation and response evaluation • 403 RAG TRIAD – holistic evaluation • 404 Retrieval evaluation metrics • 405 Precision • 406 Recall • 406 F1 score • 407 Mean reciprocal rank • 407 Mean average precision • 408 P@K • 409 Document precision, page precision, and positional document precision • 409 Positional document precision • 411 Response evaluation metrics • 412 N-gram overlap-based metrics • 412 Metrics based on semantic similarity • 415 Metrics based on faithfulness or groundedness • 417
Page 18
(This page has no text content)
Page 19
(This page has no text content)
Page 20
Preface Retrieval-augmented generation (RAG) has rapidly become one of the most important ap- proaches for building reliable and intelligent AI systems. By combining large language models with external knowledge retrieval, RAG enables applications to generate responses that are more accurate, contextual, and grounded in enterprise data. In this book, you will explore the com- plete RAG pipeline from first principles, beginning with the foundations of embeddings, vector storage, and vector databases, before moving into advanced retrieval optimization and response generation strategies. The book explains not only how RAG systems work conceptually, but also how they are implemented in practical, production-ready environments. You will first learn how vector representations are created and managed, including how em- beddings are stored, indexed, and retrieved efficiently using vector databases such as Milvus and frameworks like LlamaIndex. The book explains the architecture of vector storage systems, indexing methods such as FLAT and IVF, and the trade-offs involved in similarity search and large- scale retrieval. From there, you will discover pre-retrieval processing techniques, including query construction, query translation, Text-to-SQL workflows, metadata filtering, and query routing, enabling natural language questions to interact seamlessly with structured and unstructured data sources. Once the retrieval foundations are established, the book focuses on improving retrieval quali- ty through index optimization strategies. You will learn how to design more accurate retrieval pipelines using sentence-window retrieval, parent-child chunking, hierarchical indexing, and context-expansion techniques with both LlamaIndex and LangChain. These chapters empha- size practical engineering decisions that improve retrieval precision while preserving sufficient context for generation. Through detailed code examples and architectural explanations, you will understand how to balance chunk granularity, contextual recall, and scalability when building high-quality RAG applications.
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
Back to List