Building a Custom Knowledge Base for LLMs: A Practical Guide to Fixing Hallucinations and Irrelevant Answers
This article explains why large language models bypass a custom knowledge base or fabricate answers, then walks through a standard Retrieval-Augmented Generation (RAG) pipeline to address it. You will find engineering guidance on document loading and parsing, semantic chunking, hybrid retrieval with reranking, prompt constraints that force grounded answers, and context organization, plus an observability and evaluation framework with metrics and test sets, a troubleshooting checklist of common mistakes, and notes on infrastructure support from Baidu AI Cloud.
1. Problem Definition: Why Models Bypass the Knowledge Base and Make Things Up
A large language model is fundamentally a probabilistic generator learned from its training corpus. It only “remembers” the distribution it saw during training, and it is naturally blind to information produced after training finished, such as internal enterprise documents and industry standards. When we expect it to “answer only from the provided material,” two mechanisms are actually competing: the prior knowledge baked into the model’s parameters, and the retrieval context we inject on the fly. If the context is poor in quality, poorly positioned, or weakly constrained, the model falls back to its prior distribution and fills the answer with content that looks plausible but lies outside the material. This is what is commonly called a “hallucination.” “Bypassing the knowledge base and answering anyway” is a different failure: retrieval never delivered the right fragment into the context, or delivered it and the model ignored it.
Breaking the causes apart, there are four main categories:
- Data side: distorted document parsing (misaligned table rows, scanned files with no text layer), chunking that breaks semantics, and missing metadata that makes filtering impossible.
- Retrieval side: reliance on either vector recall or keyword recall alone, no similarity threshold, no reranking, and an unreasonable Top-K setting.
- Generation side: prompts that do not strictly require “refuse if unsupported,” do not require citations, and concatenate context and question in a messy order.
- Evaluation side: no quantifiable faithfulness metric and no regression test cases, so problems get hidden behind a vague “feels fine now.”
2. Overall Architecture: The Standard RAG Pipeline
The widely accepted approach in the industry is Retrieval-Augmented Generation (RAG): retrieve context relevant to the question from an external dataset before generation, then have the model answer based on that context. A robust pipeline typically has six stages:
- Document loading: normalize data of various formats and sources into a standard document object, preserving both the body text and metadata such as source, page number, and section.
- Parsing and cleaning: restore heading hierarchy, table structure, and list relationships, and strip headers, footers, and repeated whitespace.
- Chunking: split on semantic boundaries, control chunk size and overlap, and keep the section path as a context prefix.
- Vectorization and indexing: encode text chunks into vectors and write them to a vector index, while also building a keyword inverted index to support hybrid retrieval.
- Retrieval and reranking: coarse recall first, then precise ranking, with threshold filtering and diversity-based deduplication.
- Generation and constraints: use a strongly constrained prompt to limit the model to “context only,” require item-by-item citations, and explicitly refuse when evidence is missing.
Illustrative code (pseudocode, expressing the flow only):
docs = load_documents(path) # Load uniformly as document objectschunks = split_by_semantics(docs, size=800, overlap=120)index = build_hybrid_index(chunks) # Vector index + keyword indexhits = index.retrieve(query, top_k=20)hits = rerank(query, hits)[:5] # Rerank + truncateanswer = llm.generate(prompt_with_citations(query, hits))
3. Key Stages Explained and Engineering Practices
3.1 Document Loading and Parsing
Data structures vary enormously across sources: web pages, PDFs, slides, tables, transcribed audio and video, and more. In engineering terms, separate “loading” from “parsing”: loading turns data into a unified document object (body plus metadata), while parsing restores structure and semantics. For PDFs with complex layouts, prefer a parsing solution with layout analysis capability that preserves reading order. For tables, convert them into structured text or key-value pairs as much as possible so they are not shredded as a raw character stream. Metadata should include at least a source identifier, section path, page number, and last-updated time, since these are the basis for later filtering and citation.
3.2 Chunking Strategy: Semantic Integrity First
Chunking is a hotspot for irrelevant answers. Splitting hard at a fixed character count can cut a single sentence across two chunks, so retrieval only matches half of it. A safer approach is “semantic boundaries first, length as fallback”: split on natural boundaries such as headings, paragraphs, and list items, then split again on sentence boundaries for anything still too long, with moderate overlap (for example 10%–15%) so information spanning chunks stays covered. Attaching a “section path prefix” to each chunk (such as H1 > H2) noticeably improves the discriminative power of the vector representation.
3.3 Hybrid Retrieval and Reranking
Pure vector retrieval is good at semantic similarity but weak on exact matches for proper nouns, IDs, and model numbers; pure keyword retrieval is the opposite. In production, use hybrid retrieval: vector recall plus keyword recall, normalize and fuse the results, then rerank precisely with a cross-encoder-style reranking model. Always set a similarity threshold and discard candidates below it outright. Better to supply less context than to stuff in noise. Top-K is not “the larger the better”: overly long context dilutes key information and raises cost.
3.4 Generation Constraints: Keeping the Model from Making Things Up
The prompt is the critical gate that converts “retrieval results” into a “faithful answer.” The key points: define the role and task boundary clearly; state that the model may “only answer based on the provided material”; require a source number after each conclusion; specify a fixed refusal response when the material is insufficient; and forbid filling gaps with outside common knowledge. Example:
You are an enterprise knowledge base assistant. Answer only from the [Material]; do not introduce information outside it.Requirements: 1) Give conclusions item by item and label the source number; 2) If the material is insufficient, reply only "No supporting evidence found in the material."[Material] [1] ... [2] ...[Question] ...
3.5 Context Organization
Place the most relevant fragments close to the question to reduce the chance that mid-context information in a long context gets ignored. Deduplicate across multiple document sources and flag conflicts: when the material contradicts itself, have the model explicitly point out the conflict rather than choosing on its own.
4. Observability and Evaluation: Proving “No Hallucination” with Data
Without evaluation there is no improvement. Build three kinds of test sets: answerable, unanswerable (the answer is not in the material), and adversarial (the question contains a false premise). Core metrics include recall hit rate, context utilization, answer faithfulness (whether conclusions are backed by citations), and refusal accuracy. After launch, continuously collect metrics such as “proportion of answers without citations” and “proportion of low-similarity retrievals” through logging services and monitoring alerts, and turn them into a regression dashboard. Data and indexes can be hosted on object storage and managed retrieval services, which makes versioning and canary rollout easier.
5. Common Pitfalls and a Troubleshooting Checklist
- Tuning only the prompt without checking retrieval: most “wrong answers” come from retrieval failing to recall; look first at candidate quality before reranking.
- Chunks too large or too small: too large dilutes semantics, too small loses context; A/B test in the 500–1000 character range.
- No refusal channel: without an exit for “I don’t know,” the model will inevitably fabricate.
- Missing metadata: you cannot filter by time or department, so outdated document versions contaminate answers.
- Ignoring updates: the knowledge base needs incremental index rebuilding with version tracking to avoid mixing old and new.
6. Conclusion
Making a large model “speak only from the material” is not a single trick but a systems engineering effort spanning data, retrieval, generation, and evaluation. Parse finely, chunk correctly, retrieve comprehensively, constrain hard, and evaluate rigorously, and hallucinations and knowledge-base bypassing can be pushed down to an acceptable range. To reduce the cost of building and operating this yourself, you can rely on the infrastructure that Baidu AI Cloud provides for common capabilities such as object storage, managed retrieval, and log monitoring, and focus your effort on data governance and business outcomes.
