Share E-Book
Scan to open this page

Scan with your phone to open this page

Author: Jia Huang

Rating No ratings yet

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.

AI Reading Assistant

Whole-book reading guide from stratified index samples; jump to passages in the text

AI guide
【One-Line Pitch】 A code-first, dialogue-driven engineering manual that takes you from raw document ingestion to production-grade RAG systems, explaining not just how to build retrieval pipelines but why they fail and how to fix them—ideal for developers who already know the basics and want real architectural depth. 【Book Arc】 - **Opening (~0%–10%)**: Establishes the RAG stack's foundation with data import—loading text, JSON, CSV, web pages, and PDFs using LangChain loaders like TextLoader, WebBaseLoader, and PyPDFLoader, plus advanced parsing with Unstructured and Marker tools. - **Early (~10%–23%)**: Dives into document parsing and layout understanding—using PyMuPDF for coordinate visualization, UnstructuredLoader for structured element extraction (titles, tables, images), and techniques like ParentID to group related content across pages. - **Early (~23%–32%)**: Covers chunking strategies in depth—why chunk size impacts retrieval accuracy and generation quality, with practical tools like CharacterTextSplitter, RecursiveCharacterTextSplitter (including language-aware splitting for code), and format/layout-based approaches for Markdown, HTML, and PDFs. - **Middle (~32%–48%)**: Explores embeddings and vector storage—how embedding models encode semantic meaning, model selection trade-offs (cost, speed, privacy), similarity computation with sentence-transformers, and vector database features like metadata filtering (using Milvus as an example). - **Middle (~48%–60%)**: Introduces hybrid retrieval fundamentals—sparse vectors like BM25 for exact keyword matching, dense vectors for semantic search, and how they complement each other, plus caching strategies for embedding computation. - **Late (~60%–100%)**: Moves to advanced topics—post-retrieval processing, response generation, evaluation frameworks (RAGAS, TruLens, DeepEval, Phoenix), and complex paradigms including GraphRAG, Agentic RAG, and Modular RAG. 【Key Takeaways】 - **Data ingestion is the foundation of RAG quality** (Early): Choosing the right loader per format—CSVLoader for tables, WebBaseLoader with BeautifulSoup for web pages, PyPDFLoader for simple text, UnstructuredLoader for complex layouts—determines what your system can retrieve. Use BeautifulSoup's SoupStrainer to filter out navigation noise from web pages. - **Layout-aware parsing beats raw text extraction** (Early): For PDFs, tools like Marker convert to Markdown preserving structure, while UnstructuredLoader returns Document objects with rich metadata (coordinates, categories) that enable fine-grained segmentation by paragraphs, headings, or tables. Visualizing layout with PyMuPDF helps debug parsing issues. - **Chunking strategy directly impacts answer quality** (Early): Chunk size must balance context window limits against semantic completeness—too small loses context, too large dilutes relevance. RecursiveCharacterTextSplitter preserves sentence/paragraph integrity by progressively splitting on separators, and language-aware splitting (e.g., Python code by class/def) is essential for code documents. - **Metadata is a retrieval superpower** (Early): Beyond semantic search, metadata fields (timestamps, categories, difficulty levels) enable conditional filtering—as shown with Milvus expressions like `type == "BOSS battle" and difficulty == "Hard"`—dramatically improving result relevance. - **Embedding model choice is a trade-off, not a quest for "best"** (Middle): OpenAI models perform well, but privacy, cost, and speed constraints often force local open-source alternatives. The key is balancing options—sentence-transformers like paraphrase-MiniLM-L6-v2 work for similarity tasks, while jina-embeddings-v3 handles 89 languages for cross-lingual clustering. - **Sparse and dense retrieval are complementary, not competing** (Middle): BM25's sparse vectors excel at exact keyword matching with IDF weighting, while dense vectors capture semantic meaning—hybrid systems combine both to handle diverse query types. Embedding caching (e.g., CacheBackedEmbeddings with LocalFileStore) avoids redundant computation. - **Evaluation is non-negotiable for production RAG** (Late): Frameworks like RAGAS, TruLens (with RAG TRIAD), DeepEval, and Phoenix provide structured ways to measure retrieval and generation quality—without them, you're guessing at system performance. 【Reading Tips】 - **Skim the code-heavy sections in Chapters 1–2** if you're already comfortable with LangChain loaders and splitters—focus instead on the "why" explanations (e.g., why chunk size matters, why token count can't be used pre-embedding). - **Deep-read the PDF parsing sections** (Marker, UnstructuredLoader, PyMuPDF visualization)—these are the most nuanced and least-covered topics in typical RAG tutorials, and the coordinate-based layout debugging is genuinely valuable. - **Pay attention to the dialogue format** between Alex, Lewis, and the engineer—it surfaces practical questions (like privacy constraints on embedding models) that pure technical docs miss. - **Treat Chapter 3's embedding selection as a decision framework**, not a model catalog—the trade-off discussion (cost/speed/privacy) is more reusable than any specific model name. - **Skip ahead to evaluation frameworks (Chapter 9) early** if you're building for production—knowing how you'll measure success shapes ingestion and chunking choices from the start. 【Coverage Limits】 This guide covers the book's first half in detail (ingestion through hybrid retrieval fundamentals) but only summarizes the later chapters on evaluation and advanced paradigms, as the excerpts provide limited material on those sections.
Page 9
Table of Contents Importing table data in CSV format 26 Importing data using CSVLoader • 26 Comparing CSVLoader and UnstructuredCSVLoader • 29 Crawling and p...
View in text
Excerpt 2
sually represents the main content section of the webpage, mainly comprising the core information of the article or page, and does not include navigation bar...
View in text
Excerpt 3
lf.health = 100 self.stamina = 100 self.state = "IDLE" self.attack_patterns = { "NORMAL": 10, "SPECIAL": 30, "ULTIMATE": 50 } def update(self, delta_time): s...
View in text
Excerpt 4
iple languages, the jina-embeddings-v3 model is especially enhanced for processing long contexts, supporting inputs up to 8192 tokens, making it highly suita...
View in text
Excerpt 5
rom 65 309 (HP: 2291) Qdrant 326 4 Yes From 9 281 (HP: 820) Chroma Unknown Unknown Yes Self-hosted free Self-hosted free Elastic- 700~100 5~10 Self-hosted fr...
View in text
Excerpt 6
self._load_metadata() def _load_metadata(self): """Load image metadata""" with open(self.metadata_path, 'r', encoding='utf-8') as f: data = json.load(f) for...
View in text
Excerpt 7
but can also filter for the most recently published videos. Limitations of Self-query retriever However, the performance of the Self-query retriever is not s...
View in text
Excerpt 8
ion processes (Decoupling chunks used for retrieval/chunks used for synthesis, where “Synthesis” refers to text generation, sometimes called composition, tha...
View in text
Tags
AI categories
Artificial IntelligenceAIPython
ISBN: 1835888666
Publisher: Packt Publishing
Publish Year: 2026
Language: English
Pages: 492
File Format: PDF
File Size: 18.0 MB
Text Preview (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.

Generating text preview…