Building an Enterprise Knowledge Base: Technical Approach and Practice

    This article walks through the technical path for building an enterprise knowledge base, explaining why a vector database alone is not enough. It covers a five-layer architecture, reliable data ingestion, parsing and chunking, hybrid retrieval with reranking, grounded generation with refusal, permission enforcement at index time, evaluation, cost and operations, and a phased rollout plan.

    1. Define the Goal First: A Knowledge Base Is Not a Vector Database

    Many teams treat the knowledge base as a single vector retrieval component at project kickoff, then find the answers unusable after launch. The root cause is mistaking storage for knowledge. A usable enterprise knowledge base must solve four things at once: where knowledge comes from, how it is correctly understood, how it is accurately retrieved, and how it is safely delivered.

    Three questions can lock down the scope during the planning stage:

    • Who is it for: customer service agents, R&D engineers, or company-wide policy Q&A? Different audiences have very different tolerance for accuracy and freshness.
    • What form do answers take: retrieval-style Q&A with source citations, or analytical Q&A that synthesizes across multiple documents? The latter demands higher quality in chunking and recall.
    • How costly is a failure: a wrong policy answer is a user experience issue, while a wrong answer involving amounts, compliance, or production operations is an incident and requires stricter fallback strategies.

    Once these three points are clear, decide on the technology stack and investment scale, and avoid chasing an all-encompassing solution from the start.

    2. Overall Architecture: A Five-Layer Design

    A clear layered structure is recommended, with each layer holding a single responsibility and independently replaceable:

    1. Data ingestion layer: connects to internal document systems, ticketing systems, code repositories, and databases, handling incremental sync and change capture.
    2. Processing and indexing layer: document parsing, cleaning, chunking, vectorization, and index writes; this is the decisive stage for quality.
    3. Retrieval layer: vector retrieval, keyword retrieval, and metadata filtering run in parallel, followed by fusion ranking.
    4. Generation and orchestration layer: prompt assembly, context trimming, citation backfilling, and refusal decisions.
    5. Governance layer: permissions, auditing, monitoring, evaluation, and cost.

    The key value of layering is replaceability. When retrieval quality is poor, you should be able to adjust only the chunking and fusion strategy instead of rebuilding the whole system.

    3. Data Ingestion: Making Sync Reliable Engineering

    The most common hidden failure in a knowledge base is out-of-sync data: a document has been updated, but the index still holds the old version. Three things need to be in place.

    First, unique identifiers and versions. Every document and every chunk needs a stable ID and version number; on update, write the new version first and then switch over, so retrieval never hits a half-updated state.

    Second, incremental capture. Prefer pulling increments via change logs or timestamp cursors rather than rebuilding the full set on a timer; full rebuilds should be the fallback, scheduled during off-peak hours.

    Finally, deletion propagation. Deletions at the source must sync to the index, otherwise revoked policy clauses will be recalled, which is a serious problem in compliance scenarios. A soft-delete flag plus periodic physical cleanup works.

    Illustrative incremental sync logic:

    1. def sync_once(connector, index, state):
    2. cursor = state.get("cursor")
    3. for doc in connector.fetch_changes(since=cursor):
    4. if doc.deleted:
    5. index.soft_delete(doc.id)
    6. continue
    7. chunks = pipeline.process(doc) # parse + clean + chunk
    8. index.upsert(doc.id, doc.version, chunks)
    9. cursor = max(cursor, doc.updated_at)
    10. state["cursor"] = cursor

    4. Parsing and Chunking: The Stage That Sets the Ceiling

    Parsing quality determines the ceiling of the knowledge base. Multi-column layouts, tables, headers and footers, and scanned pages in PDFs all become noise sources. Practical recommendations:

    • Route documents by type; send table-heavy documents through structured parsing that preserves row and column semantics instead of degrading them to plain text.
    • Preserve structural information by writing heading levels into metadata, so each chunk knows its position in the document.
    • Scanned documents must go through OCR followed by manual spot checks; recognition errors directly contaminate answers.

    For chunking, fixed-length splitting is simple to implement but severs semantics badly. A safer approach is “structure first, length as fallback”: split along natural boundaries such as headings and paragraphs, then split oversized parts again with an overlapping window, typically 10%–20% overlap, so cross-boundary semantics are not lost.

    1. def split_by_structure(doc, max_len=800, overlap=120):
    2. sections = doc.split_by_heading()
    3. out = []
    4. for sec in sections:
    5. if len(sec.text) <= max_len:
    6. out.append(sec)
    7. else:
    8. out.extend(sliding_window(sec.text, max_len, overlap))
    9. return out

    Each chunk should carry metadata: source system, document ID, version, effective time, visibility scope, and heading path. All of these fields are used later for permission filtering and citation display, and backfilling them afterwards is extremely costly.

    5. Retrieval Design: Hybrid Retrieval Beats Vector Alone

    Relying on vector retrieval alone loses points on two types of problems: exact matching of proper nouns, IDs, and model numbers, and recall of long-tail low-frequency terms. A mature approach runs three paths in parallel:

    • Vector retrieval: handles semantically similar content expressed differently.
    • Keyword retrieval: handles exact hits on IDs, abbreviations, and proper nouns.
    • Metadata filtering: trims the candidate set up front by department, time, or document type.

    Results from the three paths are merged via weighted fusion or a unified ranking model. For fusion, reciprocal rank fusion gets you started quickly without training:

    1. def rrf(results, k=60):
    2. scores = {}
    3. for ranked in results:
    4. for rank, item in enumerate(ranked):
    5. scores[item.id] = scores.get(item.id, 0) + 1 / (k + rank + 1)
    6. return sorted(scores.items(), key=lambda x: -x[1])

    Reranking is mandatory after recall. First recall a relatively large candidate set (for example, dozens of items), then use a finer relevance model to select the top few for generation. This two-stage “coarse recall + fine ranking” structure is usually more cost-effective than simply increasing top-k.

    6. Generation and Orchestration: Traceable Answers and Explicit Refusal

    The core of the generation layer is not wording but constraints. Three hard requirements:

    First, mandatory citations. Every conclusion in an answer must trace back to a specific chunk, with the source title and link shown in the frontend so users can verify.

    Second, explicit refusal. When the highest relevance score falls below a threshold, return “no supporting evidence found” rather than letting the model improvise. The threshold must be calibrated with real business questions, not set by intuition.

    Third, context budget. The context window is limited, so truncate by rerank score and prefer chunks that are structurally complete, avoiding stitching fragments of one document together and creating semantic conflicts.

    Illustrative orchestration:

    1. def answer(query, index, rerank, llm, threshold=0.35):
    2. candidates = index.hybrid_search(query, top_n=40)
    3. top = rerank(query, candidates)[:6]
    4. if not top or top[0].score < threshold:
    5. return {"text": "No supporting evidence found in the knowledge base", "refs": []}
    6. prompt = build_prompt(query, top)
    7. return {"text": llm(prompt), "refs": [t.doc_id for t in top]}

    7. Permissions and Security: Up Front, Not Bolted On

    Enterprise knowledge bases often hold sensitive information, so permission design must be completed at the indexing stage rather than filtering after retrieval. The recommended practice is to write visibility scope into chunk metadata and enforce it as a mandatory filter during recall, ensuring content the user cannot access never enters the candidate set. Recalling first and filtering later tends to produce a hidden defect: the candidate set is filled with authorized content, and unauthorized users end up without the results they should get.

    Also required: encryption in transit and at rest, access audit logs, masking of sensitive fields before ingestion, and controls on outbound distribution of generated content.

    8. Evaluation: No Evaluation, No Optimization

    A three-layer evaluation system is recommended:

    • Offline evaluation set: business experts label 100–300 real questions with key points for standard answers; run regression regularly and track recall hit rate and answer accuracy.
    • Online metrics: no-result rate, citation click-through rate, thumbs-down rate, and average response latency.
    • Regression gate: any change to chunking parameters, prompts, or model versions must pass the offline evaluation before release.

    The evaluation set is one of the most important assets of a knowledge base. Put it under version control and keep expanding it, especially by feeding online failure cases back in as evaluation samples.

    9. Cost and Operations: Look at the Whole Bill

    The cost of a self-built solution is more than compute. The full bill includes compute for document parsing and vectorization, storage and memory for the vector index, inference for retrieval and generation, scheduling and retries for sync jobs, and ongoing evaluation and manual labeling effort.

    Optimizations in order of cost-effectiveness: start with caching (results for high-frequency questions, embeddings), then shrink the candidate set, then tier storage for cold data, and only then consider changing model sizes. Observability should cover sync lag, index size, retrieval latency distribution, no-result rate, and cost per Q&A, with alerts on anomalies.

    10. Suggested Rollout Path

    • Phase 1 (2–4 weeks): pick a scenario with clear boundaries and well-formed documents, connect ingestion, parsing, retrieval, and citations, and first achieve “grounded and no fabrication.”
    • Phase 2 (1–2 months): add permission filtering, auditing, the evaluation set, and refusal strategies, and expand document coverage.
    • Phase 3 (ongoing): establish a failure-case feedback loop, iterate on chunking and reranking strategies, and gradually extend to multiple scenarios and knowledge sources.

    For teams that want to lower the barrier to self-building, the general cloud capabilities offered by Baidu AI Cloud can carry infrastructure such as vector retrieval, object storage, containerized deployment, and log monitoring and alerting, letting you focus on parsing quality, retrieval strategy, and the evaluation system, which are what truly determine results. The deciding factor in a self-built knowledge base is never technology selection, but whether data governance and the evaluation loop are solid.