Building an AI Agent Knowledge Base and RAG Pipeline: A Practical Guide
This guide walks through the full lifecycle of building a knowledge base and retrieval-augmented generation (RAG) pipeline for AI agents, covering the six-stage chain from data ingestion to retrieval and reranking, supported file formats, document chunking strategies, embedding and storage design, index structures, multi-path retrieval, and layered quality evaluation. It also clarifies what RAG can and cannot solve, and why every stage needs its own observability metrics.
Building an AI Agent Knowledge Base and RAG Pipeline: A Practical Guide
In agent application development, the model itself only provides reasoning and generation capabilities. What really determines whether an answer “understands the business” is whether external knowledge can be retrieved stably and accurately, then injected into the context. Retrieval-augmented generation (RAG) is the engineering paradigm that carries this responsibility: it converts unstructured documents into searchable vectors and indexes, recalls relevant fragments when a user asks a question, and hands them to the model to organize an answer. The sections below break down the build process layer by layer, following the knowledge base lifecycle: construction, chunking strategies, embedding and storage, and the retrieval flow.
1. The Overall Knowledge Base Pipeline and Its Boundaries
A maintainable knowledge base pipeline typically has six stages: data ingestion → parsing and cleaning → chunking → embedding → index writing → retrieval and reranking. If any stage degrades, the final answer quality drops noticeably, and the failure symptoms often look similar (irrelevant answers, mismatched facts). That is why each stage needs its own observability metrics rather than judging everything by the final answer alone.
The boundaries need to be clear first: RAG is good at solving “missing knowledge” and “outdated knowledge,” but not “complex reasoning” or “permission isolation.” The former relies on prompt orchestration and tool calls; the latter requires metadata filtering at the retrieval layer. Leaving permission handling to the generation stage is the most common security pitfall in practice.
2. Supported File Types
The ingestion layer has to deal with fragmented formats. By parsing difficulty, they fall into three tiers:
- Plain text (txt, md, csv, code files): parsed losslessly and ready for cleaning directly.
- Formatted documents (pdf, docx, pptx): require handling columns, headers and footers, tables, and text inside images; parsing quality depends on whether layout structure information is preserved.
- Web pages and structured exports (html, xml, json): tags and scripts must be stripped, while heading hierarchy is kept as a chunking cue.
The engineering recommendation is to abstract the “parser” into a replaceable component and maintain separate output validation for each format: page-to-character ratio, blank page ratio, and garbled text rate. Parsing anomalies must be intercepted before ingestion; otherwise the noise gets embedded and pollutes recall results over the long term.
3. Document Chunking Strategies
The goal of chunking is not “equal length” but making each fragment semantically self-contained and distinguishable during retrieval.
- Structure-first chunking: use headings, sections, and clauses as boundaries, and keep the “parent section” as metadata. This offers the best cost-performance ratio.
- Overlapping window chunking: split at a fixed length within structural boundaries with a certain overlap ratio, so an answer that happens to span a boundary is not cut off.
- Semantic chunking: split at points where sentence similarity shifts abruptly. It works well but is computationally expensive, making it suitable for high-density knowledge such as manuals.
- Parent-child chunking: small chunks for precise recall, large chunks for context, balancing hit rate and information completeness.
Illustrative implementation (pseudocode):
def split_document(blocks, max_len=500, overlap=80):chunks, buf = [], ""for b in blocks: # blocks already carry hierarchy and page metadataif len(buf) + len(b.text) > max_len and buf:chunks.append(make_chunk(buf, b.meta))buf = buf[-overlap:]buf += b.textif buf:chunks.append(make_chunk(buf, b.meta))return chunks
Do not evaluate chunking by feel. Fix a set of question-answer pairs and measure the proportion of cases where “the fragment containing the answer is fully included.” This metric localizes problems better than final accuracy.
4. Embedding and Storage Principles
Embedding maps text into a high-dimensional dense space where semantically similar fragments sit closer together. Three factors matter when choosing a model: Chinese semantic performance, the balance between vector dimension and storage cost, and adaptability to the business vocabulary. The same knowledge base must use the same model and the same version; a model upgrade means rebuilding the entire index, so a rebuild window and a canary strategy need to be reserved.
The storage side usually combines three general capabilities: object storage keeps original documents and intermediate parsing artifacts for traceability and re-parsing; a vector search service or database holds vectors and metadata; relational storage maintains document versions, chunking records, and permission labels. Metadata design must be finalized before ingestion, because it directly determines whether filtered retrieval is possible later.
5. Index Structure and Retrieval Flow
The index structure determines recall efficiency. For small datasets, an approximate nearest neighbor graph structure or a quantization compression scheme is enough; as data grows, sharding and replicas are needed, along with a tradeoff between recall rate and latency. Production retrieval is generally a multi-path fusion: vector recall handles semantic similarity, keyword recall handles exact matching of proper nouns and IDs, and the two result sets are merged and deduplicated.
Then comes reranking and assembly: a cross-encoder first scores candidate fragments precisely, metadata filters (time, department, document type) narrow the scope, and the context is finally trimmed to budget. The complete flow can be summarized as:
query → rewrite/expand → vector recall + keyword recall→ metadata filtering → deduplication → reranking → context assembly → generation → citation tracing
6. Quality Evaluation and Continuous Iteration
Going live is not the endpoint. A three-layer evaluation is recommended: at the retrieval layer, look at hit rate and recall fragment coverage; at the generation layer, look at answer correctness and citation consistency; at the business layer, look at human adoption rate and follow-up question rate. Online feedback should flow back as new question-answer pairs, driving iteration of chunking parameters and prompt templates.
Under Baidu AI Cloud’s general cloud product portfolio, this pipeline can be assembled from standard capabilities such as object storage, vector search, container platforms, and log monitoring and alerting, avoiding tight coupling with any single component. The core principle: every stage must be observable, replaceable, and rollback-capable, so the knowledge base can evolve with the business over the long term instead of gradually decaying.
