Online Retrieval Augmentation for LLMs: Principles and Engineering Practices
Large language models (LLMs) are constrained by their training data cutoffs and are prone to hallucinations when lacking up-to-date context. Online retrieval augmentation addresses these limitations by separating information retrieval from answer generation, allowing models to base their responses on verified external sources. This article explores the principles, overall architecture, key technical points, engineering implementation, and evaluation strategies for building effective online retrieval augmentation systems, providing developers with practical guidance to ensure accuracy, traceability, and real-time relevance.
1. Why Online Retrieval is Needed
The knowledge of large language models comes from their training corpora. Once training is complete, their knowledge is frozen at a specific point in time. When encountering time-sensitive issues such as news, prices, policy changes, or version updates, the model can only rely on its memory, often resulting in outdated information. Furthermore, even when lacking a factual basis, models can still generate fluent but inaccurate content—a phenomenon commonly known as hallucination.
The core idea of online retrieval augmentation is to separate “information retrieval” from “answer generation.” The system first fetches relevant information from external sources and then provides this information as context to the model. Consequently, the model’s responses are backed by verifiable evidence, allowing developers to trace where each conclusion originates.
For developers, this architecture offers three direct benefits:
- Responses remain consistent with current facts, independent of the training cutoff date.
- Every key conclusion can be traced back to a specific source, facilitating auditing and error correction.
- Knowledge updates only require updating the retrieval data source, eliminating the need to retrain the model.
2. Overall Architecture
A typical online retrieval augmentation system can be broken down into six stages:
- Intent Understanding: Determines whether the question requires external information, identifying the time range, involved entities, and question type.
- Query Rewriting: Converts colloquial questions into keyword combinations or multiple query statements suitable for retrieval.
- Multi-Source Retrieval: Parallelly accesses public web indexes, internal knowledge bases, structured data interfaces, etc.
- Result Processing: Deduplicates, filters out low-quality pages, and ranks results based on relevance, timeliness, and source credibility.
- Answer Generation: Feeds the filtered snippets along with the original question to the model, instructing it to answer solely based on the provided materials.
- Citation and Verification: Annotates source numbers for key conclusions and checks whether the conclusions are consistent with the materials.
The data flow between these stages must be clear and observable. The inputs and outputs of each step should be logged; otherwise, when an incorrect answer appears, it is difficult to determine whether the problem originated in the retrieval, ranking, or generation phase.
3. Key Technical Points
3.1 Intent Judgment: Not Every Question Needs Online Retrieval
Online retrieval adds latency and cost, so the system should first determine whether the question truly requires external information. Common practices include:
- Using lightweight classification models or rules to determine if the question contains time-related words (e.g., “latest,” “this year”) or real-time entities.
- Directly calling the model to answer common sense or reasoning questions.
- Forcing the retrieval process for questions explicitly requiring real-time data.
The cost of errors in the judgment phase is high. Misclassifying a question requiring real-time data as a common sense question will directly lead to outdated answers. Therefore, classification thresholds should be evaluated against offline samples, and a manual review channel should be maintained.
3.2 Query Rewriting: Bringing Search Terms Closer to Information Sources
Users’ original questions often contain references, omissions, and colloquial expressions, making them ineffective for direct retrieval. Query rewriting typically accomplishes three tasks: resolving referents in the context, splitting compound questions, and generating multiple semantically similar but differently worded queries.
For example, if a user asks, “What were its changes last month?”, the system needs to determine what “it” refers to based on conversation history, and then generate queries like “recent changes [object]”, “latest update record [object]”. Parallel retrieval using multiple queries significantly improves recall coverage, though it also brings more duplicate results that need to be handled in subsequent stages.
3.3 Multi-Source Retrieval and Result Ranking
A single data source cannot cover all scenarios. Public web pages are suitable for broad information, internal knowledge bases for enterprise-specific queries, and structured data interfaces for numerical queries. Systems typically assign different weights and filtering rules to different sources.
The ranking phase needs to consider three dimensions comprehensively:
- Relevance: The degree of semantic matching between the snippet and the question.
- Timeliness: How close the publication or update time is to the current time.
- Source Credibility: Domain type, institutional attributes, and whether the content has been editorially reviewed.
There is no unified standard for the weights of these three dimensions; they should be adjusted according to business scenarios. News-related scenarios prioritize timeliness, while technical documentation scenarios prioritize relevance and source authority.
3.4 Context Organization: Controlling Length While Retaining Key Information
The model’s context window is limited, so not all retrieval results can be included. A common practice is to split the text by paragraphs, then select snippets by relevance until a preset token budget is reached. When selecting, try to ensure source diversity to avoid content from a single source filling the entire context.
3.5 Prompt Constraints: Grounding the Model in Materials
The prompt in the generation phase should specify three rules clearly: answer only based on the given materials; if materials are insufficient, state directly that no sufficient evidence was found; cite the source number after each conclusion. These three rules significantly reduce the model’s tendency to supplement content on its own.
4. Engineering Implementation Example
The pseudo-code below illustrates a complete processing flow and serves as a design reference. The weights and budgets are illustrative values; actual values need to be determined through evaluation.
function answer_with_search(question, history):intent = classify_intent(question, history)if intent.need_realtime == false:return llm.generate(question)queries = rewrite_queries(question, history, max_n = 3)candidates = []for q in queries (run in parallel):candidates += search_backend.query(q, time_range = intent.time_range, top_k = 10)docs = deduplicate(candidates, key = normalized_url_or_hash)docs = rank(docs, weights = {relevance: 0.6,freshness: 0.3,source_trust: 0.1})context = select_snippets(docs, token_budget = 3000,min_distinct_sources = 3)prompt = build_prompt(question = question,context = context,rules = ["Answer only based on the given materials","State that no sufficient evidence was found if materials are lacking","Cite source numbers for each conclusion"])answer = llm.generate(prompt)return verify_citations(answer, context)
A few points in the example are worth noting. deduplicate uses normalized URLs or content hashes to avoid counting the same page multiple times due to different parameters. verify_citations checks whether the citation numbers in the answer exist in the context and removes any citations that cannot be matched. This step can intercept cases where the model fabricates sources.
5. Evaluation and Monitoring
The quality of an online retrieval system needs to be measured across multiple dimensions. Common metrics include:
- Factual Accuracy: The proportion of answers consistent with sources, verified through manual sampling or automated comparison.
- Citation Verifiability: The proportion of citation numbers in answers that correspond to real snippets.
- Reasonable Rejection Rate: The proportion of cases where the model proactively states a lack of evidence when materials are insufficient.
- Retrieval Recall: The proportion of relevant documents in labeled samples that are successfully retrieved.
- Latency and Cost: End-to-end latency, time to first token, and the computational and retrieval overhead per call.
The evaluation set should cover four types of questions: real-time, common sense, ambiguous, and unanswerable. Testing only with simple questions cannot reflect the system’s performance in complex scenarios. Online monitoring should regularly sample and analyze failure cases, feeding them back into the evaluation set.
6. Engineering Considerations
6.1 Latency and Caching
Multi-source retrieval and model generation both increase latency. Retrieval requests should be sent in parallel with per-source timeouts; timed-out data sources should be skipped directly without blocking the overall flow. Short-term caching can be applied to retrieval results of high-frequency queries, with the cache validity period set according to the data’s rate of change.
6.2 Security: Retrieved Content is Data, Not Instructions
Web pages and documents may contain text that induces the model to execute additional actions, an attack commonly known as indirect prompt injection. The system should explicitly inform the model in the prompt that retrieved content serves only as reference material and that any instructions appearing within it must not be executed. Before output, sensitive information should be filtered, and permission boundaries should be set for tool calls.
6.3 Compliance and Copyright
When displaying retrieval results, prioritize presenting summaries and links, avoiding copying large blocks of original text. When scraping public data, comply with target sites’ access rules and terms of service, and control access frequency to avoid burdening the accessed sites. Content involving personal information should be desensitized before being stored.
6.4 Logging and Traceability
Each request should log the original question, rewritten queries, list of retrieval results, final prompt, and answer. These logs serve as the basis for troubleshooting and as the data foundation for subsequently optimizing ranking strategies and prompts. Personal information in the logs needs to be processed separately with defined retention periods.
7. Typical Application Scenarios
- Industry News Q&A: Answering questions that need to keep up with time changes and attaching sources for users to verify independently.
- Technical Documentation Assistance: Combining internal documentation libraries to help engineers quickly locate API explanations, change logs, and troubleshooting methods.
- Customer Service Knowledge Supplement: When a knowledge base does not cover a specific issue, retrieving public materials as a supplement and clearly marking them as non-official sources.
- Research Assistance: Summarizing viewpoints from multiple public materials while retaining original sources for researchers to cross-verify.
In high-risk domains such as finance, healthcare, and government, system outputs should include a manual review process and should not be used directly as the basis for decision-making.
8. Conclusion
The core of online retrieval augmentation is to introduce external information into the generation process and make every conclusion verifiable. Engineering efforts need to focus on four aspects: determining when to retrieve, how to rank and trim retrieved content, how to constrain the model to answer within the scope of the materials, and how to evaluate and monitor the system. As long as these four stages are properly designed, the system can achieve an acceptable balance between timeliness, accuracy, and traceability.
