Building Knowledge Bases and RAG for AI Agents

    This article explains how retrieval-augmented generation supports AI agents when model knowledge is not the same as current, permissioned enterprise knowledge. It covers document intake, a shared document model, cleaning, chunking, embeddings and storage, indexing and retrieval, safe agent integration, evaluation, and a practical rollout path.

    1. Why knowledge bases matter for agent applications

    In agent applications, a large language model interprets user intent, organizes language, and plans tasks. What the model already knows is not the same as the knowledge an organization can use today. Internal policies, operating manuals, business rules, and project documents change often, have restricted access, and are written inconsistently. Relying only on the model’s prior knowledge makes it hard to keep answers accurate, timely, and within access rules.

    Retrieval-augmented generation (RAG) combines external knowledge retrieval with model generation. The system first retrieves materials related to the user’s question, then passes those materials to the model as context and asks it to answer from that evidence rather than only from information stored in its parameters.

    A typical flow is:

    User question → query processing → knowledge retrieval → candidate selection → context assembly → model generation → citations and result checks.

    This approach does not make answers correct by default. Parsing errors, chunks that break meaning, missed key clauses, or a model that ignores the evidence can all produce wrong answers. A knowledge base should be treated as a verifiable data-processing pipeline, not as “upload files and start Q&A.”

    For an agent, knowledge retrieval is usually a callable capability. The agent can decide, based on the task, whether to retrieve, whether to issue a follow-up query, and whether to combine retrieval with other business operations. Permission checks and access to sensitive data cannot be left to the model’s own judgment. The application service must enforce those controls deterministically.

    2. File intake: accepting a format is not the same as understanding the content

    2.1 Plan parsing by content characteristics

    Enterprise knowledge sources can be grouped by data characteristics:

    • Plain text and markup: easy to extract, but heading levels, lists, and paragraph boundaries should be preserved.
    • Office documents: may include tables, comments, headers, footers, and revision marks. Decide which of these count as official knowledge.
    • Fixed-layout documents: extracted text may not follow reading order. Multi-column layouts, footnotes, and tables that span pages are especially error-prone.
    • Scans and images: usually need text recognition, plus handling of recognition confidence, layout structure, and character errors.
    • Structured data: table records, business fields, and database results. Decide whether to convert them to text based on query needs.
    • Exported web content: remove navigation, ads, repeated menus, and similar noise, and keep the body structure where possible.

    The fact that a system can accept a file type does not mean it can parse everything inside correctly. A file extension only describes the container, not content quality. Two fixed-layout documents may look the same, yet one may contain extractable text and the other only page images.

    Before intake, check whether the file is damaged or encrypted, whether it contains hidden content, and whether parsing produces garbled text, abnormal blank space, or a broken reading order. For critical policies and high-risk business materials, sample the results for human review.

    2.2 Use a shared document data model

    After sources enter the knowledge base, they should be converted to a common internal representation. A document record typically needs the body text, a source identifier, document version, update time, business category, access scope, and page or section location when needed.

    Metadata is not optional decoration. It is a basis for retrieval and governance. For example:

    • Document version distinguishes current policy from historical policy.
    • Effective dates support questions about a specific time range.
    • Department or tenant identifiers separate access scopes.
    • Page numbers and section paths support citations that can be checked.
    • Source records help locate parsing errors or update failures.

    If this information is lost at import, later retrieval of related text may still fail to show whether the text is valid, whether the user may access it, or which original location the answer should cite.

    2.3 Clean text without changing business meaning

    Cleaning usually means removing repeated headers and footers, repairing broken lines, normalizing whitespace, and deleting meaningless control characters. Cleaning must not change facts just to make the text look tidy.

    Amounts and units, time ranges, exception conditions, and negation words must be kept. Numbering may be how clauses refer to each other and should not be deleted casually. For tables that cross pages, restore the relationship between headers and data rows instead of joining cell text into a continuous string with no context.

    For suspected recognition errors, keep the original material and the processing record. Content that cannot be recovered reliably should be marked for review, not guessed automatically.

    3. Document chunking: balance semantic completeness and retrieval precision

    3.1 Why chunking is needed

    Embedding an entire document tends to compress many topics into one representation and weakens matches for local questions. Putting the whole document into the generation context can also exceed the length budget or add a large amount of irrelevant information.

    The goal of chunking is a fragment with a clear topic that still keeps the conditions, definitions, and context needed to answer. A good fragment should be understandable on its own and still traceable to the source.

    3.2 Common methods and where they fit

    Fixed-length chunking is simple and suits text with little structure. It can cut through sentences, formulas, or clauses, so it usually needs to respect natural paragraph boundaries.

    Structure-based chunking uses sections, headings, paragraphs, and lists. For manuals and policy documents, it often preserves semantic relationships better.

    Semantic chunking looks for boundaries where the topic changes between neighboring passages. It suits long continuous narrative, but it needs extra computation and judgment, and it still must be checked so that information required for one question is not split apart.

    Parent-child organization uses smaller fragments for retrieval, then expands a hit to its parent paragraph or section. That can balance precise location with fuller context, but the expansion must be limited so one hit does not pull in too much unrelated content.

    In practice, combine methods: split by structure first, subdivide paragraphs that are too long, and apply special rules to tables, Q&A items, and procedure steps.

    3.3 There is no single best chunk size

    Fragments that are too short may keep a conclusion and drop the conditions that apply. Fragments that are too long may mix several topics, reduce retrieval discrimination, and consume context space.

    Chunk length should be set together with document type, typical questions, embedding-model capacity, and the generation model’s context budget. Text length should not be treated as a simple character count, because languages and symbol combinations can be measured differently inside a model.

    Moderate overlap between neighboring fragments can reduce loss at boundaries. Too much overlap raises storage cost and makes retrieval results highly repetitive. A safer default is to keep complete paragraphs, then add context through section paths, parent-fragment links, and controlled expansion.

    For example, if “who it applies to,” “application conditions,” and “exceptions” together decide whether a process can be used, they should not be split only because a length threshold was reached.

    4. Embeddings and storage: make semantic search manageable

    4.1 How vector representations work

    An embedding model maps text into a high-dimensional numeric space so that semantically similar content is closer under a chosen similarity measure. At query time, the user question is also converted to a vector and compared with fragment vectors.

    Common measures include cosine similarity, inner product, and Euclidean distance. The choice must match how the embedding model was trained, whether vectors are normalized, and how the index is implemented. These pieces should not be swapped arbitrarily.

    Vector search handles questions that are worded differently but mean something similar. It does not reliably handle every exact match. Contract numbers, clause numbers, dates, and amounts often need keyword search or structured filters as well.

    Each knowledge fragment needs a stable identifier that can be tied to its location in the source, the document version, and the access policy. A vector is only a retrieval representation. It does not replace the original content.

    A general organization is:

    Document record → fragment record → vector index record.

    The file itself, fragment text, business metadata, and vectors can live in separate stores, but the links must remain traceable. The system can then fetch the body from a retrieval result, build a citation, and remove the matching index entries when a document is deleted or updated.

    4.3 Changing the embedding model requires a new evaluation

    Query vectors and document vectors in the same knowledge base must use a compatible embedding method. Vectors from different models are not in a directly comparable semantic space just because they have the same dimension.

    Switching embedding models usually means regenerating document vectors and rebuilding the index, then checking retrieval quality. Old and new indexes should be managed separately, with an explicit version switch so queries are not mixed.

    Also record the embedding version, chunking-rule version, and content version. When quality drops, that record helps show whether the cause is a data change, a processing-rule change, or a model change.

    5. Indexing and retrieval: from recalled candidates to usable evidence

    5.1 Separate semantic indexes from keyword indexes

    A vector index finds semantically close fragments. A keyword index matches explicit terms. For knowledge-base Q&A, the two usually complement each other.

    Exact vector search compares the query vector with every candidate. Results are controllable, but cost rises as the data grows. Approximate nearest-neighbor indexes use graph structure, partitions, or compression to lower retrieval cost, and they may sacrifice some recall. Choose the index structure from data scale, latency budget, update frequency, and quality requirements, not from query speed alone.

    Hybrid retrieval can collect semantic candidates and keyword candidates separately, then combine them with rank fusion or a scoring strategy that has been validated. Raw scores from different retrieval methods are not necessarily on the same scale and should not be added directly.

    5.2 Query processing must not change the original intent

    A user question may use abbreviations, references, or information omitted across turns. Query processing can fill in needed context, detect time conditions and business scope, or split a complex question into sub-questions.

    Rewrites should keep the original question and should not treat model guesses as conditions the user has confirmed. If the user only asks “what materials are required to apply,” the system should confirm the application type first rather than assume a particular process.

    In multi-turn dialogue, history should be filtered for relevance so earlier topics are not pulled into the current retrieval by mistake.

    5.3 Filtering, reranking, and deduplication have different jobs

    Metadata filters limit the search scope, for example to a valid version, a business category, or what the user is allowed to see. Permission conditions must apply before evidence enters the generation context. When the system can do so, filter at retrieval time, and still verify reliably before evidence is returned.

    Reranking compares how well each fragment matches the question and moves better material forward. It does not replace permission checks and cannot repair errors in the source documents.

    Deduplication reduces repeated paragraphs, overlapping fragments, and same-source content that would otherwise fill the context. Similar documents that differ in specific clauses must not be dropped only because the text looks alike. Version and source still have to be checked.

    5.4 Context assembly decides what the model sees

    Before candidates reach the model, organize them by relevance, validity, and how they complement each other. Each fragment should carry the source, version, and location information that is needed.

    When context length is limited, do not simply take the top-ranked segments. Prefer coverage of the conditions the answer depends on. If the question involves a process, eligibility, and exceptions, the evidence should cover those dimensions where possible.

    If evidence is insufficient, conflicts, or only a historical version was found, the system should state the limitation, ask for more information, or hand off to human confirmation. It should not force a definite conclusion.

    6. Security and lifecycle management in agent integration

    6.1 Separate retrieval capability from execution authority

    Knowledge retrieval supplies factual grounding. Business execution changes external state. They are not the same thing. A knowledge fragment that describes a step does not mean the agent is authorized to perform that step.

    Retrieval results are external data and must not be treated as high-priority instructions. If a document says things like “ignore existing rules” or “send sensitive materials,” the system should treat that text as content to analyze, not as something to execute automatically. Sensitive operations need their own permission checks, parameter checks, and human confirmation where required.

    6.2 Updates should be traceable and reversible

    A knowledge update usually involves parsing, chunking, embedding, and index writes. A failure at any step can mix old and new content.

    A safer pattern is to build a version that is not yet published, finish quality checks, and then switch the retrieval entry point to the new version. Incremental updates can use content fingerprints to find what changed, but deletions, permission changes, and expired documents must be handled as well. Adding new data alone is not enough.

    Caches should also account for knowledge version and access scope. Otherwise a user may receive an answer based on an old policy, or a cached result from another access scope.

    7. Evaluation and troubleshooting: base improvements on evidence

    7.1 Evaluate in layers, not only by whether the answer reads well

    At the retrieval layer, check whether the top candidates cover the correct evidence, where key fragments rank, and how much irrelevant content appears. At the generation layer, check whether the answer is accurate, faithful to the evidence, supported by its citations, and complete about important limits.

    Also test these cases:

    • Questions that can be answered normally
    • The same question in different wording
    • Questions with exact conditions such as numbers and dates
    • Questions the knowledge base cannot answer
    • Conflicts across multiple versions
    • Questions the user is not allowed to access
    • Documents that contain misleading instructions

    For high-risk work, one overall accuracy number is not enough to call the system usable. Check critical facts, refusal behavior, and permission boundaries separately.

    7.2 Locate failures along the pipeline

    When an answer is wrong, check in order:

    1. Whether the source material is correct and currently valid
    2. Whether parsing dropped tables, footnotes, or key passages
    3. Whether chunking broke the link between conditions and conclusions
    4. Whether the query was rewritten incorrectly
    5. Whether retrieval recalled the right evidence
    6. Whether reranking pushed key fragments down
    7. Whether context was cut off by length limits
    8. Whether the model generated content that left the evidence

    Layered checks avoid blaming every failure on the generation model. If the correct evidence was never recalled, changing the answer prompt repeatedly will not fix the root cause.

    8. Implementation advice: close a small loop before expanding

    Start with a business area that has a clear boundary, higher-quality documents, and relatively stable question types. Build a loop of intake, evidence retrieval, answer generation, human evaluation, and fixes.

    Validate parsing and permissions before tuning chunking and retrieval. Make single-turn Q&A reliable before adding multi-turn planning and automatic execution. As scale grows, hybrid retrieval, candidate reranking, incremental updates, and monitoring alerts can be added, but each change should be measured on the same evaluation set for both benefit and side effects.

    The point of a knowledge base is not one index type or one chunk-size setting. It is that the path from source files to an agent’s answer stays explainable, traceable, and verifiable. RAG becomes a sound engineering base for agent applications only when data quality, retrieval, access control, and generation constraints work together.