Building Agent Knowledge Bases and RAG Retrieval: A Complete Guide
This article explains how to build a knowledge base for AI agents and how retrieval-augmented generation (RAG) works end to end. It covers data ingestion and parsing, chunking strategies, hybrid index structures, incremental updates, the key control points that determine RAG quality, and how to evaluate and debug the pipeline. It also outlines a practical deployment approach using cloud services.
Building Agent Knowledge Bases and RAG Retrieval: A Complete Guide
1. Why Agent Applications Depend on Knowledge Bases and RAG
When building agent applications, the model itself only provides reasoning and generation. What actually determines whether the application is usable is whether it can get the right information at the right moment. Stuffing private documents, business rules, and historical tickets directly into the prompt works in the short term, but it quickly runs into three hard constraints: a limited context window, key information being diluted inside long text, and no way for content updates to take effect immediately.
The value of retrieval-augmented generation (RAG) is that it externalizes memory: source material is first processed into a searchable knowledge base, then a small number of highly relevant fragments are retrieved dynamically per question and handed to the model to compose an answer. This yields three benefits. First, knowledge becomes updatable: change the document and you change the behavior. Second, answers become traceable: every conclusion can point back to the source text. Third, access can be controlled: the retrieval layer can filter what is visible based on the user’s identity.
It is worth stressing that RAG is not a one-off project but a pipeline. No single-point optimization (swapping in a better embedding model, for example) can compensate for defects in upstream parsing and chunking. The more reliable engineering approach is to treat knowledge base construction as data engineering, and to manage retrieval quality as a measurable, regression-testable metric.
2. How to Build the Knowledge Base: From Raw Files to Retrievable Units
2.1 Data Ingestion and Parsing
The first loss in a knowledge base happens at the parsing stage. Misaligned tables, headers and footers leaking into body text, and scanned documents with no text layer will all distort every downstream step. In practice: keep the mapping between original files and parse results; extract tables structurally so they are not flattened into meaningless strings; apply optical character recognition to scanned content and retain confidence scores, flagging low-confidence fragments separately.
2.2 Chunking Strategy: Granularity Sets the Retrieval Ceiling
The goal of chunking is not equal length but semantic completeness. Common approaches include recursive splitting by heading hierarchy, splitting aligned to paragraph and sentence boundaries, and attaching metadata such as the document title and section path to each fragment. Chunks that are too large introduce noise and raise cost; chunks that are too small lose context and leave the model unable to resolve references. A common engineering pattern is parent-child chunks: retrieval matches the child chunk, and the parent chunk is filled back in for the model, balancing precision and context.
# Example: recursive chunking with metadata and parent-child chunksdef split_with_meta(doc, parent_len=1200, child_len=300):parents = recursive_split(doc.text, parent_len) # split by heading/paragraph firstfor p in parents:p.meta = {"title": doc.title, "path": doc.section_path}for c in recursive_split(p.text, child_len):yield {"text": c, "parent": p.text, "meta": p.meta}
2.3 Index Structure and the Retrieval Flow
The index structure has to match the shape of the queries. Dense vector indexes are good at semantic similarity but insensitive to proper nouns, IDs, and clause numbers; keyword inverted indexes are good at exact matches but struggle with paraphrasing. The mainstream approach is therefore to run both: generate vector and keyword indexes at write time, then recall in parallel at query time and fuse the rankings.
A typical retrieval flow is: query rewriting (resolving references, splitting multi-intent questions) → multi-path recall (vector + keyword, with metadata filtering when needed) → fusion and deduplication → reranking → context assembly → generation with citation labeling. If the business is latency-sensitive, limit reranking to a small candidate set and control cost with “widen on coarse recall, narrow on fine ranking.”
2.4 Updates, Incrementality, and Consistency
Documents change continuously, so the index must support incremental writes and invalidation cleanup. A good practice is to compute a content fingerprint for each chunk and skip rebuilding when the fingerprint is unchanged; deletions and canary releases should take effect atomically to avoid a situation where a new answer cites an old chunk. When multiple versions coexist, filtering by version number and effective time in the retrieval layer is far cheaper than correcting mistakes after the fact.
3. Key Control Points for RAG Quality
- Query understanding: normalizing colloquial questions and expanding them into multiple queries can significantly improve recall coverage.
- Permissions and compliance: enforce access control at the retrieval stage rather than the generation stage, so unauthorized content never enters the context.
- Empty-result handling: when recall returns nothing or overall similarity is low, explicitly decline or hand off to a human instead of letting the model improvise.
- Citations and verifiability: attach source fragment identifiers to output conclusions so the business side can spot-check and assign accountability.
- Cost control: cache high-frequency questions, compress context length, and choose the model tier per scenario.
4. Evaluation and Tuning: Making Retrieval Quality Regression-Testable
Without evaluation, RAG can only be tuned by feel. Build a small labeled dataset and measure the retrieval layer and the generation layer separately: for retrieval, look at hit rate and ranking quality; for generation, look at answer correctness, completeness, and citation consistency. After each change to chunk granularity, recall count, or reranking strategy, run a regression pass to avoid fixing one scenario and breaking three others.
When debugging, work down the chain from the top: first check whether parsing dropped characters, then whether chunking broke semantic units, then whether recall missed key fragments, and only then suspect the generation prompt. In practice, the root cause of most “the model is making things up” problems lies before retrieval.
5. Implementation Recommendations
To stand up a knowledge base quickly and keep operating it, you can build on the general cloud capabilities offered by Baidu AI Cloud: object storage to hold raw documents and index snapshots, a container platform to run parsing and retrieval services, a message queue to decouple incremental updates, and logging plus monitoring and alerting to observe recall rate, latency, and failure rate. This turns the knowledge base from a one-time import into infrastructure that keeps iterating, which is what gives an agent application the conditions it needs for a stable launch.
