Agent Knowledge Base and RAG: A Practical Guide

    This guide explains how a knowledge base serves as the capability foundation for AI agents and how Retrieval-Augmented Generation (RAG) connects external knowledge to the reasoning process. It walks through the five stages of building a knowledge base, parsing requirements for different file types, chunking strategies, embedding and storage principles, index structures and hybrid retrieval, as well as evaluation, access control, and operations. Engineers will find practical parameters, Python examples, and trade-off guidance for building a stable, trustworthy knowledge foundation.

    1. Why a Knowledge Base Is the Capability Foundation for Agents

    An LLM’s knowledge comes from its training corpus, which has two natural boundaries: it cannot cover information published after the knowledge cutoff, and private data such as internal documents, business rules, and historical tickets has never been part of the training set. To deliver reliable answers in real business scenarios, an agent must connect external knowledge to its reasoning process in a retrievable way. This is exactly the problem that Retrieval-Augmented Generation (RAG) solves.

    RAG is not a universal solution. It excels at factual questions with clear sources that are updated frequently, while tasks requiring long-term memory or multi-step planning still need tool calls and state management. A clear mental model is to treat the knowledge base as the agent’s long-term memory layer and tools as its hands and feet. In general-purpose technical stacks on cloud platforms such as Baidu AI Cloud, capabilities like object storage, vector retrieval, logging, and monitoring with alerting can typically be combined to form the operational foundation of a knowledge base.

    2. Overview of Knowledge Base Construction

    A usable knowledge base typically involves five stages: data ingestion, document parsing and chunking, vectorization, index construction, and retrieval with reranking. Errors at each stage are amplified downstream, so in engineering practice it is more worthwhile to invest in data quality than in model parameters.

    1. Raw documents -> Parse and clean -> Chunk -> Vectorize -> Index
    2. User question -> Query rewriting -> Vector search + keyword search -> Rerank -> Context assembly -> Generation

    3. Supported File Types and Parsing Considerations

    Different formats vary greatly in parsing difficulty and must be handled differently:

    • Plain text and lightweight markup: Clear structure and the lowest parsing cost; suitable for direct splitting by heading hierarchy.
    • Office documents: The body often mixes headings, tables, headers, and footers, so noise must be stripped before structure is extracted.
    • PDF: Two types exist, those with a selectable text layer and scanned files. Text and coordinates can be extracted from the former, while the latter must rely on optical character recognition, and recognition errors directly pollute vector semantics.
    • Tabular data: Flattening a two-dimensional structure into a single line of text causes severe semantic loss. It is recommended to chunk by row or as a small table as a whole, keeping the header as context.
    • Audio, video, and images: These must first be transcribed into text or turned into descriptions before entering the unified pipeline.

    In engineering, it is advisable to build a format-parser-quality check mapping table and manually spot-check samples that fail parsing, preventing dirty data from silently entering the index.

    4. Document Chunking Strategies

    The goal of chunking is not equal length, but making each chunk semantically self-contained and distinguishable during retrieval. Common strategies include:

    1. Fixed-length chunking: Simple to implement, but prone to cutting sentences and logic; suitable for loosely structured text.
    2. Recursive structural chunking: Splits by paragraph first, then by sentence, and finally by character, balancing length constraints with semantic completeness.
    3. Semantic/topic chunking: Determines boundaries based on changes in sentence embedding similarity, producing chunks with concentrated topics at the cost of higher computational overhead.
    4. Parent-child chunks (small chunks for retrieval, large chunks fed to the model): Small chunks ensure retrieval precision while parent chunks supply context, currently a cost-effective approach.

    The parameters usually of concern are chunk size, overlap ratio, and metadata design. Overlap mitigates information loss at boundaries and is generally set to about one tenth of the chunk length. Metadata (source, section, update time, permission labels) determines the feasibility of subsequent filtering and access control.

    1. def split_recursive(text, size=600, overlap=80):
    2. chunks, start = [], 0
    3. while start < len(text):
    4. end = min(start + size, len(text))
    5. if end < len(text): # Try to end at a sentence boundary
    6. pos = text.rfind("。", start, end)
    7. if pos > start + size // 2:
    8. end = pos + 1
    9. chunks.append(text[start:end])
    10. start = max(end - overlap, start + 1)
    11. return chunks

    5. Vectorization and Storage Principles

    Vectorization uses an embedding model to map text into a dense vector space, where semantically similar text lies closer together. Three points need attention in practice: first, documents and queries should use the same model and the same version to avoid space misalignment; second, models have an input length limit, and oversized chunks will be truncated; third, replacing the embedding model means rebuilding the entire index, so version management should be in place.

    On the storage side, data is usually divided into metadata and vectors: metadata can be placed in a relational database to support exact filtering, while vectors are handled by vector retrieval capabilities or storage services that support vector indexing. For small scale, a single-machine index is sufficient; as scale grows, sharding and replicas can be considered to balance recall, latency, and cost.

    6. Index Structures and Retrieval Flow

    The index structure determines retrieval efficiency and recall quality. Flat structures are precise but incur linear scan costs; graph-based approximate nearest neighbor structures offer fast queries and high recall but require more memory and tuning; quantization-based structures use less memory and suit very large scale, at the cost of precision loss. In engineering, selection is often a three-way trade-off among recall, latency, and memory.

    A hybrid strategy is recommended for retrieval: vector search handles semantic matching, keyword search handles exact matching of proper nouns and IDs, and after the two results are fused, reranking is applied.

    1. def retrieve(query, top_k=20, final_k=5):
    2. dense = vector_search(query, top_k) # Semantic recall
    3. sparse = keyword_search(query, top_k) # Exact recall
    4. merged = fuse(dense, sparse) # Deduplication and weighted fusion
    5. return rerank(query, merged)[:final_k] # Rerank and take the best

    7. Evaluation, Access Control, and Operations

    Evaluation should cover both retrieval and generation: the retrieval layer focuses on hit rate and top-1 relevance, while the generation layer focuses on answer accuracy, citation consistency, and reasonable refusal. It is advisable to build an evaluation set containing common questions, boundary questions, and questions with no answer in the knowledge base; the latter verifies whether the agent honestly refuses instead of fabricating.

    Access control must filter before retrieval, using access labels as query conditions rather than trimming afterward, to prevent unauthorized content from entering the context. For operations, retrieval logs and hit records should be kept, log services and monitoring alerts should be used to detect index drift and recall degradation, and an incremental rebuild mechanism should be established after document updates.

    8. Summary

    The engineering focus of a knowledge base and RAG lies in pipeline design rather than single-point tuning: parsing sets the upper bound, chunking determines semantic quality, hybrid retrieval and reranking determine accuracy, and evaluation and access control determine whether it can go live. By validating each stage layer by layer and using general-purpose cloud capabilities to support storage, retrieval, and operations, you can build a stable and trustworthy knowledge foundation for agents.