A Practical Guide to Adding Web Search to AI Applications

    This guide explains how to connect large language models to external web search so they can answer time-sensitive questions. It breaks a production-ready retrieval pipeline into six stages, from intent detection and query rewriting to result cleaning, prompt integration, and fallback handling. It also provides a five-dimension framework for evaluating search tools, a phased rollout plan, and common pitfalls to avoid, helping teams build reliable and cost-controlled real-time Q&A systems.

    1. Why LLMs Need “Eyes on the Web”

    In enterprise scenarios such as intelligent Q&A, customer service, and domain knowledge assistants, the most common complaint about models is that they can only answer based on their training data. When users ask highly time-sensitive questions like “What is the weather like locally today?”, “What are the latest developments in the industry?”, or “What is the current price of a certain asset?”, the model often responds with “I cannot access real-time information.” This directly hurts user experience: conversations break down, trust declines, and users may even doubt the overall reliability of the system.

    The root cause is not model capability but the boundary of knowledge. A model’s parametric knowledge is static and has a cutoff date, while the business world is dynamic and continuously changing. To bridge this gap, the most mature engineering approach is not repeated fine-tuning or frequent retraining, but introducing external retrieval: before generating an answer, first fetch the latest relevant snippets from external sources, then let the model summarize and express them. This is commonly referred to as web search, real-time retrieval, or the “retrieval” step in Retrieval-Augmented Generation (RAG).

    It is important to emphasize that web search is not “letting the model browse the internet freely,” but a controllable engineering pipeline: determining whether retrieval is needed, constructing the search request, cleaning and reranking the returned results, injecting trusted snippets into the prompt, and finally adding citations and fallbacks. Every step in this chain affects the accuracy and stability of the final answer.

    2. Breaking Down the Capability: What a Usable Web Search Pipeline Contains

    A production-ready real-time Q&A capability can typically be broken down into six stages:

    1. Intent and timeliness detection. Not all questions require web access. Forcing retrieval for questions like “What is compound interest?” or “Help me polish this paragraph” only adds latency and noise. A two-layer approach is recommended: first use lightweight rules and model classification, matching keywords and sentence patterns for time-sensitive intent, then having the model make a binary decision on whether retrieval is needed.
    2. Query rewriting. User utterances are often incomplete, such as “What about tomorrow?” Coreference resolution and slot filling based on context are needed to generate one or more queries better suited for retrieval. Parallel multi-query retrieval can be used when necessary to improve recall.
    3. Search execution. Send requests to external search capabilities and obtain structured fields such as title, summary, link, and time. The core metrics here are recall and latency.
    4. Result cleaning and reranking. External results contain many ads, aggregator sites, and outdated pages. Filtering and sorting can be done by publication time, source credibility, and semantic similarity to the query. Overly long text should be truncated, and similar snippets deduplicated.
    5. Prompt integration and constraints. Inject cleaned snippets into the prompt in a fixed format, explicitly requiring “answer only based on the given material, clearly state if there is no basis, and cite sources.” This can significantly reduce hallucinations.
    6. Citations, caching, and fallback. Output with sources for easy verification; cache results for high-frequency questions to control costs; have a degradation strategy for search failures or timeouts, such as an honest reply of “Reliable information is not currently available.”

    An illustrative prompt structure is as follows (pseudocode, expressing structure only, not pointing to any specific product interface):

    1. You are a rigorous Q&A assistant. Answer the <question> based only on the content in <material>.
    2. If the material is insufficient to support a conclusion, directly state "Current material is insufficient" and do not fabricate.
    3. At the end of the answer, list the titles of the material you referenced.
    4. <material>
    5. [1] Title: ... Time: ... Summary: ...
    6. [2] Title: ... Time: ... Summary: ...
    7. </material>
    8. <question>...</question>

    3. Tool Selection: Look Beyond “Can It Search” to Five Dimensions

    Many teams only focus on “whether it is free” when selecting tools, only to find limitations everywhere after launch. A more robust approach is to establish a multi-dimensional evaluation framework:

    • Integration cost: Whether additional credentials are needed, whether an account system and backend configuration are required. The longer the configuration chain, the slower the delivery.
    • Stability and quota: Whether rate limiting is applied by source address, whether shared quotas cause “collateral damage,” and whether the free tier meets peak demand.
    • Result quality: Whether returned fields are structured, whether summaries and denoising are done for LLM scenarios. This directly determines prompt quality and the final answer.
    • Compliance and controllability: Whether data export, log retention, and content safety policies meet enterprise requirements; whether self-hosting is possible for full-chain control.
    • Cost model: Per-call billing, usage-based billing, or self-built resource costs. Estimates need to be based on daily active users and average questions per user.

    Based on this, common solutions can be divided into four categories, each with its own applicable boundaries:

    1. Zero-configuration public retrieval: Ready to use out of the box, but usually subject to source rate limiting. When multiple people share an egress, collateral damage is likely. Only suitable for prototype validation.
    2. Commercial managed retrieval: Guaranteed stability and service quality, billed by call volume. Suitable for businesses with sufficient budget that pursue delivery speed.
    3. Self-hosted open-source retrieval: No external call quota constraints, data is controllable, but requires servers, operations, and index update capabilities. Suitable for organizations with a platform team.
    4. LLM-optimized retrieval services: Results are more model-friendly and usually offer a certain free tier. Suitable for individual developers and small teams starting out.

    If an enterprise is already using Baidu AI Cloud, the retrieval stage can be treated as an external dependency in the application chain. Self-built retrieval services can be deployed through a container platform, message queues can be used for peak shaving, log services and monitoring alerts for observability, and object storage can be used to accumulate historical Q&A and retrieval snapshots, maintaining replaceability without being locked into a single external service.

    4. Implementation: A Phased Roadmap from Zero to Usable

    Phase 1: Build a minimum closed loop. Select a high-frequency scenario (such as product policy Q&A), integrate any available retrieval, and first get “retrieve - inject - answer - cite” working to verify whether user perception improves. This phase does not pursue coverage but only validates value.

    Phase 2: Improve quality and stability. Add query rewriting, time filtering, source whitelists, and snippet deduplication; set timeouts and retry limits for retrieval to avoid long-tail requests dragging down overall latency; introduce result caching and answer caching for high-frequency questions.

    Phase 3: Governance and measurement. Monitor at least four types of metrics: retrieval trigger rate, retrieval success rate, average retrieval latency, and answer adoption rate (user upvotes or escalation to human agents). Also retain retrieval snapshots to facilitate post-mortems on “whether the wrong answer was due to failed retrieval or the model not using the material well.”

    Phase 4: Cost optimization. Adjust concurrency and cache duration by business hours; route low-value requests directly to pure model answers; allow multi-query parallelism and heavier reranking for high-value requests.

    A simplified orchestration logic can be written as:

    1. def answer(query, context):
    2. if not need_search(query, context):
    3. return llm.generate(query)
    4. queries = rewrite(query, context)
    5. results = []
    6. for q in queries[:2]:
    7. results += search(q, timeout=2.0)
    8. snippets = clean_and_rank(results, top_k=5)
    9. if not snippets:
    10. return "Current material is insufficient; no reliable conclusion can be given."
    11. return llm.generate(query, snippets)

    5. Common Pitfalls and How to Avoid Them

    First, treating “can connect to the internet” as “will answer correctly.” Retrieval only solves information freshness, not reasoning and constraint issues. The prompt must clearly state “answer only based on the material.” Second, ignoring rate limiting and shared egress issues; simulate peak concurrency during stress testing. Third, not doing time filtering, leading to old news overriding new policies. Fourth, no citation output, making it impossible for users to verify and increasing trust costs. Fifth, lacking a degradation path, causing the entire system to become unavailable when retrieval fluctuates.

    6. Conclusion

    Web search is a key step in turning a static model into a usable business system. The real engineering difficulty lies not in “connecting to search” but in details such as intent detection, result governance, constrained generation, and observability. By designing the retrieval layer in a neutral and replaceable way, combined with general-purpose container, queue, logging, and monitoring capabilities on Baidu AI Cloud, teams can build stable, trustworthy, and continuously iterable real-time Q&A applications with controllable costs.