RAG Knowledge Bases: How to Reduce LLM Hallucinations
Learn how to build a dedicated knowledge base with retrieval-augmented generation (RAG), from document loading and text chunking to vector retrieval and answer generation. This article explains how retrieval quality, grounding prompts, abstention, source citations, and ongoing evaluation help reduce hallucinations and make answers more verifiable.
1. Why Build a Dedicated Knowledge Base?
Large language models (LLMs) draw on knowledge learned during training, which creates two inherent limitations:
- Missing private data: Internal documents, product manuals, policies, and procedures that were never included in the training data are unavailable to the model.
- Outdated knowledge: Models do not automatically learn about new data or industry developments after training.
When asked about a private domain, a model may generate a plausible but incorrect answer based on similar patterns in its training data instead of admitting that it does not know. This is a hallucination: content presented confidently without sufficient factual grounding.
Retrieval-augmented generation (RAG) addresses this problem by retrieving relevant document passages from an external knowledge base before generating an answer. These passages are added to the prompt context, giving the model evidence to work from and reducing the likelihood of unsupported answers.
2. The RAG Pipeline
A complete RAG system has four main stages:
- Document loading: Convert data in different formats into standardized document objects.
- Text chunking: Split long documents into coherent passages suitable for retrieval.
- Embedding and storage: Convert passages into semantic vectors and store them in a vector database.
- Retrieval and generation: Retrieve passages relevant to the user’s question and pass them to the LLM to generate an answer.
The following sections examine each stage.
3. Document Loading: Standardizing Data Ingestion
Document loaders convert PDFs, web pages, spreadsheets, audio and video transcripts, and other sources into standard document objects containing text and metadata.
Metadata typically includes the source filename, page number, and section heading. This information provides the foundation for tracing answers back to their sources.
Loaders generally support two categories of data sources:
- Public sources: Public web pages, video platform captions, and social media content.
- Private sources: Internal knowledge bases, collaborative notes, design documents, and code repositories.
The following illustrative example shows PDF loading:
# Example using a PDF loader from an LLM application frameworkfrom document_loaders import PyPDFLoaderloader = PyPDFLoader("docs/machine_learning_lecture.pdf")pages = loader.load()# Total number of pageslen(pages) # For example, 22# Inspect the first page's content and metadatapage = pages[0]print(page.metadata) # Includes source, page number, and other metadataprint(page.content[:500]) # First 500 characters of page text
In this example, each PDF page becomes a separate document object with its own text and metadata. Preserve this metadata so the system can identify supporting sources in its answers. Source attribution lets users verify responses and is an important part of reducing hallucinations.
4. Text Chunking: Choosing the Right Granularity
Loaded documents need to be split for two reasons: embedding models have input-length limits, and chunk size affects retrieval quality. Large chunks can make retrieval less precise, while small chunks may lose necessary context.
Common strategies include:
- Fixed-size chunks with overlap: For example, use 500-character chunks with a 50-character overlap between adjacent chunks to reduce context loss at boundaries.
- Separator-based splitting: Prefer natural boundaries such as paragraphs, headings, and line breaks, then split further if a passage remains too long.
- Preserving document structure: Carry section headings and page numbers into each chunk’s metadata.
Chunk size is a trade-off between retrieval precision and contextual completeness. Tune it using an evaluation set of real business questions rather than choosing parameters arbitrarily.
5. Embeddings and Retrieval: Finding Relevant Content
An embedding model converts each chunk into a semantic vector, which is stored in a vector database. The database can be a cloud-based vector search service or a self-hosted solution.
At query time, the user’s question is also converted into a vector. Similarity calculations then identify the most relevant chunks.
Key practices for improving retrieval quality include:
- Hybrid retrieval: Combine semantic vector search with keyword search to support both meaning-based matching and exact terminology.
- Reranking: Retrieve a larger candidate set, such as 20 chunks, then use a cross-encoder to select a smaller, more relevant set, such as five chunks.
- Similarity-score filtering: Set a minimum score and exclude chunks below that threshold from the generation context.
6. Engineering Controls for Reducing Hallucinations
Retrieval alone is not enough. Even with relevant passages in the context, a model may still generate unsupported content. The following controls help keep answers grounded.
1. Set Explicit Grounding Instructions
The system prompt should require the model to answer only from the supplied context and clearly state when the available material is insufficient.
For example:
Answer the user's question strictly using the reference material below.Do not use information outside the reference material.If the reference material is insufficient to answer the question, state:"The available material does not provide enough information to answer this question."Do not guess.Reference material:{retrieved_chunks}User question:{question}
2. Prefer Abstention to Incorrect Answers
For knowledge-base applications, the cost of saying “I don’t know” is generally lower than the cost of fabricating an answer. When evidence is insufficient, the system should favor abstention over unsupported claims, even if that means declining to answer more often.
3. Cite Supporting Sources
Require answers to cite the chunk identifiers or sources they rely on, such as a filename and page number. This allows users to check the evidence and encourages the model to generate responses grounded in the retrieved material.
4. Add a Validation Layer
Validate generated answers against the retrieved passages. Check their semantic consistency, and if the answer diverges too far from the evidence, replace it with an abstention response or route it for human review.
5. Evaluate and Iterate Continuously
Build a test set containing:
- Questions answerable from the knowledge base.
- Questions outside the knowledge base’s coverage.
- Leading questions that encourage unsupported answers.
Regularly measure hallucination and abstention rates to detect regressions as models or knowledge-base data change.
7. Conclusion
A dedicated RAG knowledge base gives an LLM evidence on which to base its answers. Document loading standardizes data ingestion; chunking and embeddings make the content retrievable at an appropriate level of detail; and grounding instructions, abstention, and citations constrain the generation stage.
The engineering priority should be verifiable answers and the ability to abstain, not an answer to every question. A knowledge-base assistant that acknowledges when it lacks evidence is more trustworthy than one that always produces a confident response.
