Practical RAG: Hallucination Mitigation and Retrieval Cost Optimization
Retrieval-Augmented Generation (RAG) leverages external knowledge to answer questions, but it does not automatically guarantee accuracy. This article explores practical RAG engineering, focusing on mitigating hallucinations and optimizing retrieval costs. It covers building a reliable knowledge foundation, query rewriting, synergizing real-time search with static knowledge bases, graph-enhanced retrieval, healthcare-specific RAG applications, and layered hallucination control to help developers build trustworthy enterprise knowledge services.
1. Rethinking RAG: Evidence-Driven Answers, Not Just Search
Retrieval-Augmented Generation (RAG) is a technique that retrieves relevant information from external knowledge sources before generating an answer, providing this information as context to a large language model (LLM). It enables systems to utilize private, updated, and traceable knowledge, but it cannot automatically guarantee correct answers.
A common misconception is that simply retrieving a document prevents the LLM from hallucinating. In reality, errors can occur at multiple stages:
- Document parsing breaks the semantic relationships of tables, headings, or footnotes.
- Query expressions do not match the terminology in the knowledge base.
- Retrieval hits a relevant topic but misses the critical evidence needed to answer.
- The context contains conflicting or outdated information.
- The model extrapolates a local conclusion into an unsupported general claim.
Therefore, the engineering goal of RAG should not merely be “returning a plausible paragraph,” but rather “answering questions based on verifiable evidence within explicit permissions, timeframes, and knowledge boundaries.”
A relatively complete processing chain can be represented as:
User Question -> Intent Recognition -> Query Processing -> Retrieval Routing -> Evidence Recall -> Reranking and Conflict Checking -> Constrained Generation -> Citation Verification
Any stage in this chain can become a bottleneck. Optimization requires identifying the problem first, rather than simply increasing the context length or switching the generation model.
2. Build a Reliable Knowledge Foundation Before Tuning Retrieval Algorithms
2.1 Document Parsing Should Preserve Structure, Not Just Extract Text
Enterprise documents often contain body text, tables, images, formulas, and attachments. Converting them uniformly into continuous text loses significant information.
For instance, a medical research table’s “sample size,” “intervention method,” “observation period,” and “outcome metrics” rely on row-column relationships for correct interpretation. If only numbers and text are retained, the model might concatenate data from different studies.
The parsing stage should at least preserve:
- Document ID, version, release time, and source.
- Section paths, heading hierarchies, and page numbers.
- Row and column headers, units, and footnotes of tables.
- Image captions and their associated body text.
- The position of text snippets within the original document.
- Access permissions and business ownership.
For image-based documents, OCR and visual understanding can be combined, but the extraction results should still retain original page locations. The output of vision models is an interpretation and should not be treated by default as a verified fact.
2.2 Chunking Should Center on Semantic Integrity
Fixed-length chunking is simple to implement but easily separates definitions from their constraints. For example, a paragraph might specify an applicable scope, followed by a list of exceptions. If these two parts are divided into different chunks, the retrieval system might only recall the first half.
A more robust strategy is to use headings, paragraphs, tables, or business items as boundaries, performing secondary splitting only when chunks are too long. Short chunks can retain parent section information, and table chunks should carry necessary headers and units.
It is necessary to distinguish between two granularities:
- Index granularity: Facilitates precise matching with user queries.
- Evidence granularity: Sufficient to support a complete explanation.
The system can first retrieve smaller chunks and then expand to parent sections or adjacent paragraphs, but expansion must be constrained by length budgets and relevance. A longer context does not mean a more reliable answer.
2.3 Permission Filtering Must Occur Before Evidence Reaches the Model
Content in a knowledge base often has departmental, project, or user-level access restrictions. Permission control cannot be executed only at the UI presentation stage; otherwise, unauthorized information may have already entered the model’s context.
In practice, permission conditions should be integrated into retrieval filters and maintained consistently during reranking, cache reuse, and citation presentation. Shared caches must also account for user permission scopes to prevent evidence leakage between different users.
3. Query Rewriting: Completing Expression Without Altering User Intent
User queries are often short, colloquial, and context-dependent. For example, “Is this plan still usable now?” lacks the object, timeframe, and evaluation criteria.
The role of query rewriting is to transform implicit information into retrieval-friendly expressions, not to fabricate premises for the user.
3.1 Split Query Processing into Distinct Tasks
The following tasks can be performed separately:
- Coreference resolution: Determining what “this plan” refers to based on conversation history.
- Terminology standardization: Mapping abbreviations and aliases to unified concepts.
- Condition extraction: Identifying time, region, version, and applicable demographics.
- Question decomposition: Splitting complex questions into multiple retrievable sub-questions.
- Retrieval expansion: Supplementing synonymous expressions and related concepts.
These tasks should ideally produce structured intermediate results rather than just a single long query. Structured results are easier to inspect, log, and debug.
For instance, if a user asks, “Are there better outcomes for elderly patients using this treatment?”, the system must first confirm the treatment method, the comparative method, and the specific metrics for “better.” If critical conditions are missing, it can ask the user or explicitly state the assumptions used for retrieval, but it must not silently fill in the gaps.
3.2 Retain Both Original and Rewritten Queries
Relying entirely on rewritten results can cause semantic drift. A rewriting model might change “Are there risks?” to “How to reduce risks?”, thereby altering the nature of the question.
A more reliable approach is to use the original query, the standardized query, and a few expanded queries in parallel. Merge candidate results, deduplicate them, and then perform unified reranking. The number of expansions should be budget-constrained to avoid introducing a large number of topically relevant but practically irrelevant candidate chunks.
3.3 Validate Rewriting with Retrieval Performance
A fluent rewritten text does not necessarily mean better retrieval performance. It is necessary to observe:
- Whether critical evidence enters the candidate set more easily.
- Whether negative words, time limits, or version conditions are omitted.
- Whether business assumptions not present in the original question are introduced.
- Whether the extra latency from multiple queries is justified.
For high-risk scenarios, it is recommended to save the original question, the rewriting result, and the final retrieval conditions used to facilitate tracking error sources.
4. Synergizing Real-Time Search with Static Knowledge Bases
Static knowledge bases are suitable for answering policies, product manuals, and long-term stable professional knowledge, but they cannot naturally cover real-time changing information.
For questions like “Is there a warning today?” or “Have recent policies changed?”, the system should first determine their time sensitivity before deciding whether to invoke real-time external retrieval.
4.1 Establish Retrieval Routing Instead of Always Searching the Internet
Routing can integrate the following signals:
- Whether the query contains temporal expressions like “today,” “recently,” or “latest.”
- Whether the question’s subject belongs to high-frequency changing information.
- Whether the local data’s update time meets the requirement.
- Whether the user explicitly requests external sources.
- Whether sending the query content to external systems is permitted.
When dealing with internal contracts, customer data, or personal health information, privacy and permission checks must be performed first. One cannot directly send the complete question externally just to supplement information.
4.2 External Retrieval Results Require Source and Time Verification
Search result summaries are merely clues and may not directly support conclusions. For critical facts, the complete source content should be obtained whenever possible, verifying the publication time, update time, applicable scope, and source reliability.
When internal documents conflict with external materials, simply adopting the more recently published content is unwise. For example, internal policies might still be the officially enforced regulations for the organization, while external materials might only be industry suggestions.
The answer should distinguish between “current internal rules,” “public external information,” and “unconfirmed changes,” avoiding mixing materials of different validity levels into a single conclusion.
5. Graph-Enhanced Retrieval: When Is It Worth It?
Traditional RAG primarily recalls chunks through text similarity. Graph-enhanced retrieval further organizes entities, concepts, and relationships, making it suitable for questions requiring cross-chunk evidence connection.
For example, if a user asks, “Which business processes will be affected by this policy adjustment?”, the answer might involve policy clauses, responsibility divisions, process nodes, and exception approval conditions. Simply retrieving a similar paragraph is often insufficient; a relationship graph can help locate associated objects.
However, graph structures are not inherently superior to text retrieval. For simple factual queries, the cost of graph construction and maintenance may outweigh the benefits.
5.1 Where Do Graph Construction Costs Come From?
Common costs include:
- Extracting entities and relationships from text.
- Unifying synonymous names and eliminating duplicate entities.
- Identifying cross-document relationships.
- Generating local or global summaries.
- Handling document updates, deletions, and version changes.
- Saving the original evidence corresponding to relationships.
If complex extraction is performed on all chunks, even if a large number of chunks only contain repetitive introductions, formatting instructions, or table of contents, it will consume resources. The key to reducing costs is minimizing low-value processing, not simply cutting down model input length.
5.2 Filtering Chunks by Concept Importance
Low-cost methods can first identify candidate concepts, then evaluate whether a chunk is worth entering the graph construction pipeline.
An illustrative scoring formula is:
S(c) = αK(c) + βB(c) + γU(c) + δQ(c) − λD(c)
Where:
- K(c): Key concept information contained in the chunk.
- B(c): Potential bridging value connecting different topics.
- U(c): Business importance.
- Q(c): Source and parsing quality.
- D(c): Degree of duplication with existing materials.
These metrics and their weights are specific system design choices, not universal standard parameters. In practice, a validation set should be used to check whether the scoring truly retains critical evidence.
High concept frequency does not equate to high importance. Rare anomalies, prohibition conditions, and safety limits might appear only once but are crucial for business decisions. Therefore, the filtering mechanism should set protective rules for such content.
5.3 Filtering Affects Only Graph Processing, Not the Original Knowledge
A two-tier structure is recommended:
- All qualified documents enter the basic text index.
- High-value chunks enter entity-relationship extraction and graph indexing.
This way, graph-enhanced queries can utilize structural relationships, while ordinary factual queries can still access text not processed by the graph.
To avoid missing key connections, limited adjacent context expansion can be performed around high-scoring chunks, and a portion of sampled chunks can be retained to check filtering bias. If queries repeatedly hit important materials not graphified, they can be added to the subsequent incremental construction queue.
5.4 Relationships in the Graph Must Be Traceable
Relationship extraction models can produce errors. Therefore, the existence of an edge in the graph should not be directly interpreted as a confirmed fact.
Every important relationship should save its source chunk, document version, and validity period. For conflicting relationships, their sources can be recorded concurrently rather than forcibly merged.
Graph retrieval provides a path for organizing evidence, but the final answer should still return to the original text for verification.
6. RAG in Healthcare: Classification, Standardization, and Structured Combination
Medical knowledge features complex terminology, strict applicable conditions, and frequent evidence updates. General similarity retrieval easily finds “topically related” materials but not necessarily “conditionally matched” materials.
For instance, differences in study subjects’ age, disease stage, comorbidities, treatment dosage, and observation period may mean conclusions cannot be directly transferred.
6.1 Classify First, Then Retrieve
The system can first determine whether a question belongs to disease explanation, drug information, research evidence, guideline queries, or process instructions. Different categories use different retrieval conditions and answer templates.
Classification results should not become an immutable single route. For cross-category questions, multiple candidate categories can be retained to prevent systematic missed retrievals caused by front-end classification errors.
6.2 Terminology Standardization Requires Context
The same disease or treatment concept might have an official name, an abbreviation, and a colloquial term. Standardization helps improve recall but should not forcibly merge approximate concepts from different contexts.
The system should retain the original expression, the standardized concept, and the mapping basis. For polysemous abbreviations, judgment should be made based on department, disease, and context; if still uncertain, the user should be asked for clarification.
6.3 Constrain Evidence Matching with Research Question Structures
For clinical research questions, retrieval conditions can be organized around the study population, interventions, comparators, and outcome measures (PICO), supplementing with study design and follow-up period information as needed.
The value of this structured approach lies in establishing a matching sieve: first confirming whether the research conditions match, then discussing whether the results support the conclusion.
Answers should clearly distinguish between research observations, applicable scopes, and evidence limitations. If stating an evidence level, it should be based on explicit evaluation criteria, not solely on the model’s linguistic judgment. Medical RAG especially needs to demonstrate the applicable boundaries of information and should not package retrieval results as definitive personal treatment recommendations.
7. Integrating Document Parsing with Multi-Turn Research Processes
For questions requiring the synthesis of multiple documents, a single retrieval may be insufficient to form a complete answer. A multi-turn process of “planning - retrieval - verification - supplementary retrieval” can be adopted:
- Break down the question into sub-conclusions that need to be proven.
- Find corresponding evidence for each sub-conclusion.
- Check for missing conditions and conflicting information.
- Append retrieval for identified gaps.
- Summarize verified conclusions and unresolved issues.
The premise of this process is still reliable document parsing. If table units or footnotes are lost during ingestion, multi-turn retrieval merely repeatedly processes erroneous materials.
Stop conditions must also be set, such as reaching a query budget, having evidence for main sub-questions, or new retrievals no longer providing effective information. An automated research process without stop conditions may increase costs without improving answer quality.
8. Hallucination Mitigation: From Single Prompts to Layered Control
8.1 Pre-Generation: Ensure Sufficient and Relevant Evidence
Reranking should focus on whether the chunk actually answers the question, not just keyword similarity. It should also check time, version, applicable subjects, and source conflicts.
The “sufficient evidence” here should not be determined solely by a similarity score; it can be judged comprehensively based on question type, key condition coverage, and source quality.
8.2 During Generation: Define Evidence Boundaries
Generation instructions should require the model to:
- State verifiable facts only based on provided evidence.
- Separate original facts from analytical inferences.
- Not fabricate answers for missing conditions.
- Explain sources separately for conflicting information.
- Explicitly ask supplementary questions or refuse to answer when information is insufficient.
The retrieved materials themselves should also be treated as untrusted input. Operational instructions appearing in documents cannot override system rules, especially triggering sensitive operations or bypassing permissions.
8.3 Post-Generation: Verify the “Conclusion-Evidence” Relationship
The presence of a citation does not mean it is correct. After answering, check whether every important conclusion is supported by the corresponding chunk, paying special attention to numbers, dates, comparative relationships, and negative conditions.
For high-risk content, factual claims in the answer can be extracted item by item, followed by checking their evidence support status. Using another model for verification can help, but model cross-checking should not be treated as a definitive guarantee; key fields should ideally combine rule validation with manual spot checks.
9. Deciding Further Investment via Layered Evaluation
Whether RAG is worth doing depends on whether the knowledge has clear value and whether the system can provide reliable answers at an acceptable cost, not on whether a complex architecture is used.
It is recommended to establish at least the following evaluation layers:
| Layer | Primary Focus |
|---|---|
| Data Layer | Parsing completeness, version correctness, permission consistency |
| Retrieval Layer | Critical evidence recall, condition matching, noise ratio |
| Generation Layer | Factual correctness, evidence support degree, answer completeness |
| Security Layer | Unauthorized leakage, sensitive information exfiltration, malicious instruction interference |
| Operations Layer | Response time, processing cost, failure rate, and update latency |
For concept filtering schemes, full-scale graph construction, filtered graph construction, and basic text retrieval should be compared simultaneously. Besides total cost, the effects on cross-document questions, low-frequency concept questions, and exception condition questions should also be observed.
If an optimization reduces processing volume but significantly damages evidence recall in critical scenarios, it cannot be deemed a success solely based on cost reduction.
10. Recommended Engineering Implementation Sequence
A more reliable implementation approach is to incrementally add capabilities:
Phase 1: Establish high-quality document parsing, permission filtering, basic retrieval, and traceable citations. Confirm that the knowledge base covers real questions.
Phase 2: Introduce query standardization, multi-path recall, reranking, and refusal to answer when evidence is insufficient. Prioritize resolving high-frequency errors.
Phase 3: Add controlled external retrieval for time-sensitive questions, and introduce structured fields and specialized evaluations for industry scenarios.
Phase 4: Introduce graph-enhanced retrieval only when there is a genuine need for cross-document relational reasoning, controlling costs through concept filtering, incremental updates, and evidence backtracking.
Ultimately, a mature RAG system should simultaneously answer three questions: Why were these materials retrieved? Why can these materials support the conclusion? Under what conditions is this conclusion no longer valid? Only by implementing these three questions into data, processes, and evaluations can RAG evolve from a demonstrative Q&A feature into a trustworthy enterprise knowledge service.
