Building an Enterprise Knowledge Base: Fixing LLM Hallucinations and Irrelevant Answers
This article explains why large language models hallucinate or ignore a knowledge base, breaks down the standard Retrieval-Augmented Generation (RAG) pipeline, and presents an engineering approach to make answers evidence-grounded. It covers document loading and semantic chunking, hybrid retrieval with reranking, constrained prompting, refusal thresholds, and regression evaluation, along with common pitfalls to avoid.
1. Background: Why LLMs Answer Confidently When They Don’t Know
A large language model’s knowledge is bounded by its training corpus. Proprietary internal documents and business data created after the training cutoff are simply not part of it. When a question falls outside that knowledge, the model tends to “complete” a plausible-sounding answer from its probability distribution. That is hallucination. A more damaging variant occurs when the correct content does exist in the knowledge base, yet the model bypasses the retrieved results and answers from memory, producing irrelevant responses.
Both problems share the same root cause: the model does not treat externally retrieved evidence as the only trusted source. The fix is not more parameter tuning. It requires governing both the data pipeline and the constraint mechanisms.
2. The Basic RAG Pipeline
The widely adopted approach is Retrieval-Augmented Generation: retrieve context fragments relevant to the question from an external dataset, then pass those fragments together with the question to the model. A practical pipeline has six stages:
- Document loading: normalize data from different formats and sources into a standard document object containing the body text and associated metadata.
- Document splitting: split along semantic boundaries into coherent fragments, controlling fragment length and overlap.
- Embedding and indexing: convert fragments into vector representations and write them to a vector search service; structured data can go through keyword search separately.
- Query rewriting: normalize the user’s original question and expand it along multiple paths to improve recall.
- Hybrid retrieval and reranking: run vector recall and keyword recall in parallel, then score and order candidate fragments with a reranking model.
- Constrained generation: use the highly relevant fragments as the sole factual basis and require the model to return an answer with citations.
Illustrative code (pseudocode, structure only):
docs = load_documents(path) # Load into a unified document objectchunks = split_by_semantics(docs, size=500, overlap=50)index = build_index(embed(chunks)) # Build the vector indexdef answer(q):hits = rerank(vector_search(q) + keyword_search(q))context = concat([h.text for h in hits[:5]])return llm.generate(prompt=q, evidence=context, must_cite=True)
3. Root Causes of Hallucination and Knowledge Base Bypass
- Poor splitting: a complete conclusion is cut across two fragments, retrieval captures only half of it, and the model has to fill in the rest.
- Missing recall: pure vector search is insensitive to proprietary terms, IDs, and abbreviations, so the correct fragment never enters the candidate set.
- Drowned context: too many low-relevance fragments dilute the key evidence and shift the model’s attention.
- Unconstrained prompts: without an explicit instruction to answer only from the provided material, the model defaults to its parametric memory.
- No refusal mechanism: generation still runs when retrieval confidence is low, sharply increasing the chance of hallucination.
- No traceability check: answers carry no citation anchors, so errors cannot be located or regression-tested.
4. Engineering the Fix
4.1 Data Layer: Loading and Splitting
The document loader normalizes data from PDFs, web pages, tables, and internal systems into a standard document object, storing body text and metadata separately. Metadata should retain at least the source, section, last-updated time, and permission tags, laying the groundwork for later filtering and traceability. Splitting should follow heading hierarchy and paragraph semantics rather than a fixed character count. For tabular structured data, preserve row-column relationships, and when necessary convert each row into a natural-language sentence before indexing.
4.2 Retrieval Layer: Hybrid Recall and Reranking
Any single retrieval method has blind spots. Vector search excels at semantic similarity; keyword search excels at exact matches on IDs and proprietary terms. Merge both result sets and let a reranking model order them precisely, keeping only three to five highly relevant fragments. Also attach metadata filters to the retrieval request (time range, department, document type) to exclude irrelevant corpus up front.
4.3 Generation Layer: Strongly Constrained Prompts
The prompt must explicitly state the role, the evidence boundary, and the output format. The core points: answer only from the provided evidence; when evidence is insufficient, state clearly that the material does not mention it; tag each conclusion with the fragment ID; no speculation and no supplementation from external knowledge.
You are an enterprise knowledge base assistant. Answer only from the [Evidence].If the evidence is insufficient to support a conclusion, reply only: Not mentioned in the material.Output format: conclusion + [fragment ID].[Evidence] {context}[Question] {question}
4.4 Fallback Layer: Refusal and Confidence Thresholds
Set a retrieval score threshold. Below it, route to a refusal or a human handoff instead of letting the model improvise. The refusal rate should be one of the core monitoring metrics, observed alongside accuracy, so coverage is never gained at the expense of trustworthiness.
4.5 Evaluation Layer: A Regression-Testable Evaluation Set
Build a human-labeled evaluation set with reference answers covering three question types: single-hop facts, multi-hop reasoning, and unanswerable questions. Measure recall hit rate, answer accuracy, and correct refusal rate separately. After every change to the splitting strategy or the prompt, run a regression pass and let the data show whether the change actually helped. On the production side, connect logging and monitoring alerts, and sample-review answers without citations and low-scoring retrieval requests.
5. Common Pitfalls
- Assuming a larger model removes hallucination: constraints and the evidence chain are what matter.
- Stuffing in as many fragments as possible: noise significantly degrades generation quality.
- Using vector search only: proprietary-term scenarios require a keyword channel.
- Ignoring permissions: the knowledge base needs metadata-based access control to prevent unauthorized recall.
- Treating launch as the finish line: the knowledge base needs continuous updates and periodic regression evaluation.
6. Summary
Suppressing hallucination comes down to turning evidence into a hard constraint: semantic splitting keeps fragments complete, hybrid retrieval ensures sufficient recall, prompts and thresholds keep the model in bounds, and traceability plus evaluation make problems discoverable and fixable. To lower the cost of building and operating the system, enterprises can assemble an elastic pipeline on general-purpose cloud capabilities such as object storage, container platforms, vector search, and log monitoring, and focus their effort on corpus governance and the evaluation system. That is the long-term moat for trustworthy knowledge base question answering.
