Building an Agent Knowledge Base and How RAG Works
This article explains why a knowledge base defines the capability boundary of an AI agent and walks through the four key stages of building one: file type support, document chunking, embedding and storage, and index structure with the retrieval pipeline. It also covers stage-by-stage evaluation metrics and common pitfalls, showing how to turn RAG into an observable, repeatable data pipeline that keeps agent answers accurate as data changes.
Building an Agent Knowledge Base and How RAG Works
1. Why a Knowledge Base Defines an Agent’s Capability Boundary
A large language model learns from its training corpus, which leaves two natural gaps. First, it cannot cover information published after its knowledge cutoff. Second, enterprise private data—policy documents, product manuals, support ticket records—is simply not part of the training distribution. Retrieval-Augmented Generation (RAG) addresses this by fetching relevant content before inference and assembling it into the context, so the model can answer with the material in front of it.
RAG is not a universal patch, though. It is good at problems that are factual, traceable, and updated frequently; it is not a substitute for the model’s own reasoning and coding ability. So the starting point for building a knowledge base is not picking a tool, but first defining which questions must go through the retrieval path.
2. How to Build the Knowledge Base: Four Key Stages
2.1 Supported File Types
In engineering practice, inputs usually fall into three categories:
- Structured data: tables, logs, database exports—better served by field queries than vector retrieval;
- Semi-structured data: documents with heading hierarchies, lists with attributes—structure information can be preserved;
- Unstructured data: body paragraphs, scanned files, text inside images.
Scanned files and images require an extra text recognition step. For tables, splitting them directly breaks row and column semantics; a safer approach is to convert them into natural-language descriptions of “header plus row” before ingestion. In general-purpose capabilities on cloud platforms such as Baidu AI Cloud, object storage is commonly used to hold the original files, while log services and monitoring alerts track the failure rate and latency of ingestion jobs.
2.2 Document Chunking Strategy
Chunking determines the smallest semantic unit that can be retrieved, and it has the biggest impact on results. Common strategies:
- Fixed-length chunking: simple to implement, but prone to cutting in the middle of a sentence;
- Overlapping chunking: adjacent chunks share some content, mitigating information loss at boundaries;
- Structure-aware chunking: split along headings, paragraphs, and list boundaries for the most complete semantics;
- Parent-child chunks (retrieve small blocks, feed large blocks to the model): balances retrieval precision with context completeness.
Illustrative implementation:
def split_by_structure(text, max_len=800, overlap=80):blocks, buf = [], ""for para in text.split("\n\n"):if len(buf) + len(para) > max_len and buf:blocks.append(buf)buf = buf[-overlap:] + paraelse:buf += "\n\n" + paraif buf.strip():blocks.append(buf)return [b.strip() for b in blocks]
In practice, attach metadata to every chunk: source file, section path, last updated time, and permission labels. This metadata is the basis for later filtering and access control.
2.3 How Embedding and Storage Work
Embedding maps text into a high-dimensional semantic space where semantically similar text sits closer together. Three things matter when choosing a model: Chinese semantic performance, vector dimension (which affects storage and retrieval cost), and maximum input length (which caps the chunk size).
On the storage side, separate two needs. Vectors need an approximate nearest neighbor index in exchange for query speed. Original text and metadata are better kept in a relational or document store, used to assemble the final context and apply conditional filters. The two data paths are linked by a unique identifier.
Batch ingestion should be a re-entrant pipeline: deduplicate by file fingerprint, retry failures, and when a version is updated, delete the old vectors before writing the new ones—otherwise multiple versions of the same paragraph pollute retrieval.
2.4 Index Structure and the Retrieval Flow
Mainstream indexes fall into exact indexes (brute-force comparison, fine for small datasets) and approximate indexes (partitioning, graph structures, trading a little recall for throughput). The choice should depend on data scale and latency budget, not on chasing whatever is “more advanced.”
The full retrieval chain:
- Query rewriting: resolve references, break down multi-intent questions;
- Hybrid recall: vector retrieval handles semantic similarity, keyword retrieval handles proper nouns and part numbers;
- Metadata filtering: narrow the scope by time, department, and permissions;
- Reranking: score the candidate set with a finer relevance model;
- Context assembly: deduplicate, compress, and label sources;
- Generation and citation: require the model to give a source for each statement.
3. Evaluation and Common Pitfalls
Evaluate stage by stage to locate problems: in recall, look at hit rate and coverage; in ranking, look at top-1 relevance; in generation, look at faithfulness (whether the answer relies only on retrieved content) and citation accuracy.
Frequent pitfalls include: chunks that are too large, letting irrelevant content crowd the context; missing permission filters, leading to out-of-scope answers; relying on vector retrieval alone, which fails on queries about model numbers and part numbers; and indexes that are not synced after documents are updated, producing stale answers.
4. Summary
The engineering essence of a knowledge base and RAG is a controllable data pipeline: input adaptation determines information fidelity, chunking determines semantic completeness, embedding and indexing determine recall efficiency, and reranking and citation determine answer credibility. Make each stage an observable, repeatable, and evaluable module, and only then can an agent’s answer quality improve steadily and keep evolving as the data updates.
