Building a Private Knowledge Base: Fixing LLM Hallucinations and Irrelevant Answers

    This article explains why large language models hallucinate or bypass retrieved knowledge in enterprise settings, and how Retrieval-Augmented Generation (RAG) addresses the gap between generation and factual grounding. It breaks down the four key stages of a RAG pipeline—document loading and parsing, semantic chunking, embedding and indexing, and constrained generation—along with common failure points at each stage. It then covers core engineering techniques for suppressing hallucinations, including strict prompts with refusal behavior, citation traceability, retrieval quality safeguards, and context budget control. Finally, it outlines an evaluation and iteration approach using offline test sets and production monitoring to keep the knowledge base reliable over time.

    1. Background: Why LLMs Fabricate and Overstep

    Large language models offer strong general-purpose reasoning and generation, but their knowledge is frozen at the cutoff of their training data. For internal enterprise documents or business data created after training, the model is effectively unaware of the content. When users push a question anyway, the model tends to “fill in” a plausible but incorrect answer based on probability distributions—the so-called hallucination.

    Enterprise knowledge base scenarios also involve a second, more subtle problem: the model bypasses the retrieved knowledge snippets and answers directly from parametric memory. Both problems stem from the same root: there is no strong constraint between generation capability and the source of facts. Retrieval-Augmented Generation (RAG) mitigates this by introducing external data sources, but a poorly engineered pipeline still cannot eliminate it.

    2. Pipeline Breakdown: Four Key RAG Stages and Common Defects

    2.1 Document Loading and Parsing

    Data formats vary widely across sources—PDF, Word, web pages, and tables each behave differently. The loader’s job is to normalize heterogeneous data into standard document objects that carry the content body and metadata (such as page number, section, and source path). A common defect is losing layout structure during parsing, which misaligns tables and scrambles heading hierarchy, causing retrieval to miss the mark downstream.

    Illustrative code:

    1. from langchain.document_loaders import PyPDFLoader
    2. loader = PyPDFLoader("docs/report.pdf")
    3. pages = loader.load() # returns a list of document objects, one per page
    4. print(len(pages)) # total number of pages
    5. print(pages[0].page_content[:500])
    6. print(pages[0].metadata) # metadata such as source and page number

    2.2 Semantic Chunking

    Chunk granularity directly determines recall quality. Chunks that are too small lose semantic completeness; chunks that are too large introduce noise and exceed the context window. In practice, split along semantic paragraphs and add an overlap window of a certain proportion so that cross-paragraph references are not cut off. Metadata must be passed through with every chunk, since it is the basis for later traceability.

    2.3 Embedding and Indexing

    Chunks are encoded into vectors and written to a vector index; at query time, the user question is encoded and used for approximate nearest neighbor search over the index. Three points matter here: whether the embedding model matches the document language; whether the index type matches the data scale; and whether a hybrid strategy combining keyword search and vector search is used, to balance exact matching of proper nouns with semantic generalization.

    2.4 Generation and Constraints

    The retrieved snippets are assembled into a prompt that instructs the model to “answer only based on the given material.” This is the final gate for suppressing hallucinations, and the step most often overlooked in engineering implementations.

    3. Core Engineering Techniques for Suppressing Hallucinations

    3.1 Strongly Constrained Prompts and Refusal

    The prompt must state three rules explicitly: use only the provided context; when the context is insufficient, explicitly state that the question cannot be answered; and tag each conclusion with a citation number. Refusal is not a failure—it is a sign of reliability.

    1. You are an enterprise knowledge assistant. Follow these rules:
    2. 1. Answer only from the content in <context>; do not use external memory;
    3. 2. If <context> cannot support an answer, reply "Not mentioned in the material";
    4. 3. After each conclusion, tag the source snippet with [number].
    5. <context>{{retrieved_chunks}}</context>
    6. Question: {{question}}

    3.2 Citation Traceability and Verifiability

    Attach the source document and page number to every answer so users can jump to verify it in one click. Verifiability significantly narrows the model’s room for free improvisation, and makes it easier to pinpoint whether the error came from retrieval or generation.

    3.3 Retrieval Quality Safeguards

    Set a similarity threshold and discard candidates below it; rerank the retrieved results to move the most relevant snippets to the front; and build a question-answer cache for high-frequency questions to reduce instability caused by pipeline jitter.

    3.4 Context Budget and Noise Control

    The context window is a scarce resource. Truncate by relevance, cap the number of injected snippets, and avoid diluting attention with irrelevant content—one of the common triggers that leads the model to bypass the knowledge base.

    4. Evaluation and Continuous Iteration

    Build an offline evaluation set covering three question types—factual, multi-hop, and no-answer—and measure recall hit rate, answer accuracy, and refusal accuracy for each. In production, collect the real distribution of questions through logging services and monitoring alerts, and periodically feed them back to refine chunking strategies and prompt templates. Data and index updates can use incremental sync, with object storage retaining the original documents to ensure traceability and rebuildability.

    5. Conclusion

    Eliminating hallucinations is not the result of a single trick, but of coordination across the full chain: parsing, chunking, retrieval, constraints, and evaluation. Binding the source of facts tightly to the generation process—letting the model answer when evidence is sufficient and honestly refuse when it is missing—is the real prerequisite for a usable enterprise knowledge base.