liveBook · Manning

Chapter 5: Building knowledge bases with RAG

What you will learn in chapter 5 of Build an AI Agent (From Scratch)

Introduces knowledge bases with RAG as the next context-engineering enhancement to the basic agent and previews the chapter’s focus on vector and structure-based search.

After this chapter you will be able to

What it builds on

Section by section

Introduction

Introduces knowledge bases with RAG as the next context-engineering enhancement to the basic agent and previews the chapter’s focus on vector and structure-based search.

5.1 The problem of using internal data

This section explains why agents need to find relevant information in private data and place it in context when web search cannot answer a question.

Key terms: web search, internal data sources, relevant, context

5.1.1 A simple case: Single file

For a small attached file, the agent can read the whole file into the LLM’s context to answer a question about its contents.

Key terms: file-reading tool, context, context windows

5.1.2 Multiple files

This section explains why answering a question from a multi-file archive calls for structure-based exploration instead of reading every file.

Key terms: structure based, context, filenames, folder names

5.1.3 Large or extensive data

This section explains why large files and extensive document collections require selective retrieval rather than structure-based exploration alone.

Key terms: structure-based exploration, context, selectively retrieves, vector search, keyword search

5.2 Types of search methods

Introduces the retrieval–augmentation–generation flow and explains why different search needs call for different methods.

Key terms: RAG, retrieval, augmentation, generation, knowledge base, exact word matching, semantically similar content, traversing relationships, file structure

5.2.1 Keyword search

This section explains how keyword search ranks documents, when exact matching works well, and why it misses synonyms.

Key terms: keyword search, TF-IDF, term frequency, inverse document frequency, BM25, exact words or phrases, synonyms, similar expressions, synonym dictionary

5.2.2 Vector search

This section explains how vector search retrieves text by semantic similarity, why it handles natural-language queries, and when keyword search remains preferable.

Key terms: embedding model, embedding, vector space, query vector, cosine similarity, Euclidean distance, natural-language questions, semantic search, context-aware, keyword search

5.2.3 Graph search

This section explains how graph search answers relationship-based questions and why building a useful graph remains challenging.

Key terms: graph search, nodes, entities, edges, relationships, graph traversal, multistep relationship queries, code-dependency analysis, unstructured text, entity extraction

5.2.4 Structure-based search

This section explains how agents can search systematically organized files by following their structure, and why hybrid search combines exact and semantic matching.

Key terms: structure-based search, tree, grep, filenames, folder structures, hybrid search, keyword search, vector search, normalized, weighted average

5.3 Practicing vector search

Introduces the basic idea behind vector search before the chapter’s hands-on implementation.

Key terms: vector search, vectors, distances, semantic similarity

5.3.1 Embedding: Converting text to vectors

This section explains how embeddings represent text as vectors and uses cosine similarity to show why vector search can find related text without exact word matches.

Key terms: embedding, vector space, semantic relationships, text-embedding-3-small, embedding vector, NumPy array, cosine similarity, keyword search, vector search

5.3.2 Chunking: Dividing long text into search units

Explains why documents are split into searchable chunks, how chunk size affects retrieval, and how overlap preserves context in fixed-length chunking.

Key terms: embedding, vector, chunks, chunk size, context information, search accuracy, fixed-length chunking, overlap, chunk boundaries, chunk_size

5.3.3 Implementing vector search

This section implements vector search by ranking embedded chunks against an embedded query and demonstrates that it can find relevant text without exact keyword matches.

Key terms: query vector, chunk vectors, cosine_similarity, argsort()[::-1], top_k, similarity score, semantic search, embeddings, keyword search

5.3.4 Why vector databases are necessary

This section explains why searching every embedding becomes impractical at scale and how vector databases address that problem, then contrasts several database options.

Key terms: chunks, O(n), vector databases, approximate nearest neighbor (ANN), embeddings, metadata-based filtering, Chroma, Pinecone, Qdrant, Milvus

5.3.5 Exercise: Finding relevant information from web search results

This exercise uses vector search to select relevant passages from web search results and shows how doing so reduces the context sent to an LLM.

Key terms: include_raw_content=True, fixed_length_chunking, get_embeddings, vector_search, vector search, semantic-matching capability, token count, context, savings rate, Tavily

5.4 Structure-based search

Introduces structure-based search as a way for an agent to find answers among files extracted from an archive.

Key terms: structure-based search, filesystem, filenames

5.4.1 Preparing the GAIA dataset

This subsection prepares GAIA questions and their attached files for structure-based search, including a repeatable working folder for each problem.

Key terms: GAIA dataset, attachments, load_dataset(), snapshot_download(), local_dir, cache, working folder, initial state, file_name, working directory

5.4.2 Implementing filesystem tools

This section explains filesystem tools that let an agent extract attachments, inspect files, and read text or media in formats suited to each file.

Key terms: unzip_file, list_files, zipfile, read_file, start_line, end_line, pandas, Markdown tables, read_media_file, PDF handler

5.4.3 Connecting tools to the agent

This section connects filesystem tools to the agent so it can explore files, including extracted zip archives, over multiple steps.

Key terms: @tool decorator, filesystem tools, web search tools, max_steps

5.4.4 Solving GAIA zip file problems

This section shows how an agent solves a GAIA problem by exploring a zip attachment, reading its files, and matching job requirements to applicants.

Key terms: unzip_file, list_files, read_media_file, read_file, filenames, extensions, format cues

5.5 Extending agents with callbacks

This section introduces callbacks as a way to extend an agent for deployment needs without changing its core code.

Key terms: callback pattern, core code, user approval, compress search results

5.5.1 The need for agent extension

This section explains how callbacks let developers extend an agent at specific points in its execution without changing its core logic.

Key terms: callbacks, extension points, agent’s core logic, before_llm_callback, after_llm_callback, before_tool_callback, after_tool_callback, after_run_callback

5.5.2 Implementing tool callbacks

This section adds callbacks to the Agent so code can intercept tool calls before execution or replace results afterward.

Key terms: before_tool_callback, after_tool_callback, ToolResult, Early Exit pattern, before_tool_callbacks, after_tool_callbacks, inspect.isawaitable()

5.5.3 Human-in-the-loop tool-execution approval

This section shows how an approval callback lets an agent run safe tools immediately while pausing before sensitive tool calls.

Key terms: human-in-the-loop (HITL), dangerous tools, safe tools, approval callback, act(), None, tool result, rejection message

5.5.4 Compressing search results

Shows how an after-tool callback automatically compresses long web search results and how it can coexist with a before-tool approval callback without changing the agent’s core logic.

Key terms: after_tool_callback, search_web, chunking, vector search, ToolResult, _extract_search_query, ExecutionContext, ToolCall, tool_call_id, query

5.6 Summary

The chapter summary connects the scale of internal data to appropriate search methods, reviews two retrieval approaches, and shows how callbacks extend agents without changing core logic.

Where this is used later

Concepts explained in this chapter

← Chapter 4: Implementing a basic ReAct agent Chapter 6: Adding memory to your agent →

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.