How to Build an Enterprise Knowledge Base: From Architecture to Implementation

    This article explains how enterprises can build their own knowledge base, covering why a knowledge base is more than a vector store, a five-layer architecture, data ingestion and governance, chunking and hybrid indexing, grounded generation with citations, access control and compliance, evaluation and operations, cost and performance, and a phased rollout plan. It includes practical code and configuration examples to help teams move from a demo to a production-trusted system.

    1. Define the Problem First: A Knowledge Base Is Not a Vector Store

    Many teams start a project by treating a knowledge base as “document chunking + vector retrieval.” After launch, they discover inaccurate answers, tangled permissions, and runaway costs. The essence of a self-built knowledge base is to turn unstructured and semi-structured enterprise information into a knowledge service that can be retrieved, cited, and governed. It requires at least four capabilities: data ingestion and governance, indexing and retrieval, generation and citation, and operations and evaluation. If any layer is missing, the system will struggle to run reliably in production.

    Before writing code, break the requirements into three categories:

    • Factual Q&A: policies, expense reimbursement, leave, product specifications. Accuracy and traceability matter most.
    • Process guidance: approval workflows, incident response playbooks. Complete steps and version consistency matter most.
    • Exploratory analysis: log root-cause analysis, summarizing competitor material. Broad recall and multi-turn clarification matter most.

    The question type determines the retrieval strategy, chunking granularity, and evaluation metrics. One set of parameters cannot fit all cases.

    2. Overall Architecture: A Five-Layer Design

    A sustainable architecture is usually divided into five layers, with clear contracts decoupling each layer.

    1. Ingestion layer: connects to cloud drives, code hosting, ticketing systems, databases, message queues, and other sources; handles incremental sync and deduplication.
    2. Processing layer: document parsing, layout restoration, cleaning, chunking, metadata extraction, embedding, and keyword index construction.
    3. Storage layer: object storage holds original files, a relational database holds metadata and permissions, and a search engine holds vectors and inverted indexes.
    4. Serving layer: query rewriting, hybrid retrieval, reranking, context assembly, generation, and citation annotation.
    5. Governance layer: permission checks, audit logs, monitoring and alerting, evaluation regression, and cost and quota management.

    A schematic service call flow:

    1. def answer(query, user):
    2. q = rewrite(query, history=user.session)
    3. candidates = hybrid_search(q, top_k=50, filters=acl_filter(user))
    4. top = rerank(q, candidates)[:8]
    5. ctx = assemble(top, max_tokens=6000)
    6. resp = llm.generate(q, ctx, require_citation=True)
    7. audit.log(user, q, top, resp)
    8. return resp

    acl_filter must take effect during retrieval, not after generation. Otherwise, you risk a serious privilege escalation issue where “the answer has already leaked and is merely not displayed.”

    3. Data Ingestion and Governance: The Factor That Sets the Ceiling

    In practice, the ceiling on answer quality is set by data quality; the model and retrieval only approach that ceiling. The ingestion stage must solve four problems.

    The first is parsing. Tables, headers and footers, scanned documents, and code blocks are the most common noise sources. For tables, preserve row and column structure and convert them into readable key-value descriptions. For scanned documents, apply optical character recognition (OCR) and keep confidence scores, flagging low-confidence content separately. The second is deduplication and versioning. When multiple historical versions of the same policy exist, keep the version number, effective date, and expiration date, and retrieve only the active version by default. The third is metadata. At minimum, include source system, department, classification level, owner, update time, and document type. These fields serve both as filters and as audit evidence. The fourth is incremental sync. Use content hashes for change detection to avoid the cost spikes of full rebuilds.

    1. {
    2. "doc_id": "policy_2024_03",
    3. "source": "oa",
    4. "dept": "hr",
    5. "level": "internal",
    6. "version": 7,
    7. "effective_from": "2024-03-01",
    8. "hash": "9f2c...",
    9. "acl": ["dept:hr", "role:manager"]
    10. }

    4. Chunking and Indexing: The Core Variables of Retrieval Quality

    The goal of chunking is not “uniform size” but “semantic completeness + locatability.” In practice, prioritize structured chunking: first split by heading hierarchy and paragraph boundaries, then apply a sliding window as a second pass within overly long paragraphs, keeping a certain overlap between windows so answers are not cut off. Each chunk should carry its heading path as a context prefix, for example “Travel Reimbursement > Invoice Requirements,” which significantly improves the relevance of vector recall.

    Indexing typically uses hybrid retrieval: vector retrieval excels at semantic similarity, while keyword retrieval excels at proper nouns, IDs, and abbreviations. Results from both are combined with reciprocal rank fusion and then passed to a reranking model for fine ordering. Schematic fusion logic:

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

    For strongly structured data, such as organization and personnel records or product model parameters, do not force embedding. Field filtering plus exact matching is more stable, with vector retrieval serving only as a supplementary channel.

    5. Generation and Traceability: Keeping Hallucinations in Check

    The key constraint in the generation stage is “no answer without evidence.” Three strategies can enforce this in engineering: first, explicitly instruct the prompt to answer only from the given context and provide a standard response when information is missing; second, enforce citations that label the source document and paragraph number in the output, with a front end that links back to the original text; third, set a confidence threshold, and when the top reranking score falls below it, switch to retrieval suggestions or hand off to a human instead of forcing an answer.

    A reusable prompt skeleton:

    1. Answer only from the material below; do not introduce outside knowledge.
    2. If the material is insufficient, reply "Insufficient material" and list the titles of documents to consult.
    3. Citation format: [number] Document Title · Section Path
    4. Material:
    5. [1] ...

    In addition, multi-turn conversations need query rewriting to expand “What about the hotel standard for business trips?” into “Employee business trip hotel expense reimbursement standard.” The rewritten result should keep the original question for auditing.

    6. Permissions, Security, and Compliance: The Hard Gate for Enterprise Scenarios

    Enterprise knowledge bases often involve compensation, contracts, and customer information, so permission design must come first. The recommended approach is to have a unified identity system issue identity and permissions; the knowledge base only consumes tokens and attributes, converts attributes into filter conditions at retrieval time, and enforces both row-level and document-level isolation. All Q&A must retain audit logs containing the asker, retrieved snippets, cited sources, and timestamps for later traceability. Data in transit and at rest should both be encrypted, with keys managed by a dedicated key management service rather than hard-coded in application configuration. For external model calls, disable options that use data for training, and mask or process sensitive fields locally.

    7. Evaluation and Operations: No Regression, No Iteration

    Build three layers of evaluation: an offline evaluation set covering high-frequency questions, edge cases, and historical bad cases, with metrics including recall hit rate, citation accuracy, and answer consistency; online canary testing that compares old and new strategies with small traffic; and a fixed weekly proportion of manual spot checks that feed problems back into the loop. Operations need dashboards: zero-result rate, low-confidence share, average response latency, cost per Q&A, and a list of popular unanswered questions. The popular unanswered list often points directly to missing documents and is the fastest lever for increasing the knowledge base’s value.

    8. Cost and Performance: Building a Stable Foundation with General Cloud Components

    Self-built does not mean operating everything yourself. A common approach is to hand the stateful parts to managed services: original files go to object storage, metadata to a relational database, indexes to a search service, asynchronous parsing tasks to a message queue with elastic scaling on a container platform, and logs and metrics to logging and monitoring and alerting services. In these scenarios, Baidu AI Cloud can provide general-category capabilities, such as a combination of object storage, container platform, message queue, logging service, and monitoring and alerting, so teams can gain elasticity and observability without building their own data centers.

    There are three levers for cost control: first, tiered storage and hot-cold separation, moving historical versions to infrequent-access storage; second, caching high-frequency Q&A and retrieval results; third, controlling context length and the number of reranking candidates to avoid unbounded growth in call volume.

    9. A Phased Implementation Roadmap

    • Phase 1 (2–4 weeks): pilot with a single data source and a single department, running the full loop of parsing, chunking, hybrid retrieval, citation, and auditing.
    • Phase 2 (1–2 months): integrate the permission system and incremental sync across multiple data sources, and build the evaluation set and dashboards.
    • Phase 3 (long term): expand to multiple departments and languages, introduce query rewriting, reranking, and proactive completion, and establish a knowledge operations mechanism.

    The success of a self-built knowledge base depends 80% on data governance and permission design and 20% on retrieval and generation tuning. By making the layered architecture, traceability constraints, and regression evaluation default capabilities, an enterprise knowledge base can move from “works in a demo” to “trusted in production.”