Building an AI Agent Knowledge Base and RAG Retrieval: A Complete Guide
This article explains how to build a knowledge base for AI agents and how Retrieval-Augmented Generation (RAG) retrieval works end to end. It covers why a knowledge base acts as the factual foundation for agents, the four stages of the knowledge pipeline, supported file types and parsing principles, document chunking strategies, embedding and storage fundamentals, index structures and the retrieval workflow, and layered evaluation and tuning methods. Readers will gain a practical understanding of each stage and the key constraints that keep retrieval accurate.
1. Why a Knowledge Base Is the Factual Foundation of an AI Agent
A large language model’s knowledge boundary is defined by its training corpus, which has two inherent limitations. First, it lags behind in timeliness and cannot perceive business rules added after the model is deployed. Second, it lacks private data: internal documents, ticket records, and product manuals will never appear in public corpora. The core idea of Retrieval-Augmented Generation (RAG) is to retrieve relevant fragments from external knowledge sources during inference, then inject them into the prompt as context so the model can “answer with the book open.”
In agent scenarios, the value of RAG is amplified further. Agents typically require multi-turn planning and tool calls. If every turn relies on model memory, errors accumulate along the chain. Assigning factual judgments to knowledge base retrieval and leaving reasoning and orchestration to the model is a design based on separation of responsibilities. From an engineering perspective, the knowledge base can be treated as the agent’s long-term memory layer, complementing short-term conversation context.
2. Overview of Knowledge Base Construction
Building a usable knowledge pipeline typically involves four stages: data ingestion and parsing, chunking and structuring, embedding and storage, and indexing and retrieval. These four stages form a pipeline, and any roughness at one stage propagates downstream.
Raw files -> Parse & clean -> Chunk -> Embed -> Vector store / inverted index -> Retrieval fusion -> Rerank -> Context injection
It is important to emphasize that a knowledge base is not a one-time project. Documents are updated, deprecated, and added, so incremental synchronization and version management are required; otherwise, retrieval results will drift away from the actual business state.
3. Supported File Types
Enterprise knowledge sources are highly heterogeneous, so the ingestion layer needs to handle them in tiers based on “parsing difficulty.”
- Plain text and lightweight markup: TXT, Markdown, code files, and similar formats have clear structures and can be chunked directly by paragraph or heading level.
- Office documents: PDF, Word, PPT, and Excel. PDFs come in text-layer and scanned forms, and the latter requires OCR to extract text. Tables and multi-column layouts can easily break reading order and require layout analysis to restore.
- Rich text and web pages: HTML and on-site pages require stripping noise such as navigation and footers while preserving the main body.
- Structured data: database tables, logs, and JSON returned by APIs. This content is not suitable for direct embedding. A more reliable approach is to extract it into field-based descriptive text or route it through a Text-to-SQL tool path.
- Audio and video: transcribe to text first before ingestion, since transcription quality directly determines the upper limit of retrieval.
The general principle at the parsing stage is “fidelity first”: preserve locating information such as heading levels, page numbers, and section numbers to leave anchors for later source citation.
4. Document Chunking Strategies
The goal of chunking is not equal length, but making each chunk semantically self-contained and sized to fit the model’s context budget.
Common strategies include fixed-length chunking (simple to implement but prone to cutting semantics), recursive chunking by punctuation and paragraphs (the most common in engineering), chunking by heading level (suitable for standardized documents), sliding-window chunking (keeping overlap between adjacent chunks to mitigate boundary information loss), and parent-child chunking (small chunks for retrieval, large chunks for providing context).
In practice, it is recommended to introduce three configurable parameters: chunk size, overlap ratio, and separator priority. An illustrative configuration is shown below:
chunk_config = {"chunk_size": 500, # Target length per chunk; adjust for document density"overlap": 50, # Overlapping tokens to mitigate boundary truncation"separators": ["\n## ", "\n\n", "\n", "。", ""],"keep_metadata": ["title", "page", "section", "updated_at"],}
For “atomic structures” such as tables, code blocks, and formulas, cross-chunk splitting should be prohibited. When necessary, make them standalone chunks with additional context notes.
5. Embedding and Storage Fundamentals
The essence of embedding is mapping text into a high-dimensional semantic space so that semantically similar fragments are closer in that space. A common similarity measure is cosine similarity. Choosing an embedding model requires weighing three factors: Chinese semantic performance, vector dimension (which affects storage and retrieval cost), and maximum input length (which determines the chunk size limit).
A key constraint is that ingestion and querying must use the same embedding model and the same preprocessing logic; otherwise, the vector spaces are not comparable and retrieval fails overall. When upgrading the model, perform a full rebuild rather than mixing versions.
On the storage side, two paths usually run in parallel: a vector index handles semantic recall, and an inverted index handles exact keyword matching. Queries with low semantics but high precision requirements, such as business terms, model numbers, and error codes, often perform poorly with pure vector retrieval and need a keyword channel as a fallback.
6. Index Structures and the Retrieval Workflow
The index structure determines retrieval recall speed and precision. Exact retrieval is a linear scan, which is infeasible with large data volumes. Approximate nearest neighbor indexes use graph structures or quantization compression to trade controllable precision loss for order-of-magnitude performance gains, making them a common choice in production.
A complete retrieval typically includes the following steps:
- Query rewriting: resolve references and omissions using conversation history, and split into multiple sub-queries when necessary.
- Hybrid recall: the vector channel and keyword channel retrieve candidate sets in parallel.
- Fusion and ranking: normalize and merge multi-channel results, then apply a rerank model for fine ranking.
- Filtering and trimming: filter by permissions, time, and document status, and control the token budget of injected context.
- Context injection and citation: number the fragments in the prompt and require the model to annotate sources for easy manual verification.
If an enterprise already uses common cloud infrastructure such as object storage, container platforms, log services, and monitoring and alerting, it can host raw documents, index services, and retrieval quality metrics separately, forming an observable and traceable closed loop.
7. Evaluation and Tuning
Tuning cannot rely on intuition; it requires a small-scale evaluation set covering single-hop factual queries, multi-hop reasoning, and negation and boundary questions. Core metrics include recall rate, hit rate, answer faithfulness, and citation accuracy. When “retrieval succeeds but the answer is wrong,” the problem usually lies in the prompt and context organization. When “nothing is retrieved at all,” go back to the chunking and embedding stages to investigate. This layered localization approach is more efficient than globally retuning parameters.
