Unified Web Search and Web Page Reading in LLM Applications: A Practical Guide

    Many LLM applications need current external information and the ability to read a user-specified page, but models cannot do that directly. This guide explains how a unified model interface can expose web search and web page reading as server-side tools: the client submits only the question, context, and tool declarations, while the server handles retrieval, page fetching, content extraction, and result return. It also covers time and location context, tool declaration principles, Python calling patterns, security boundaries, timeouts, degradation, observability, cost control, and a production validation checklist.

    Many LLM applications are good at understanding and generating content, but they do not inherently have real-time knowledge, and they cannot directly read a user-specified web page. A common solution is to combine the model with a search service and a page-parsing capability.

    A more engineering-friendly approach is to declare web_search and web_reader as server-side tools through a unified model interface. The client only submits the user question, relevant context, and tool declarations. The server handles retrieval, page fetching, content extraction, and returning tool results back to the model. This reduces client-side code and centralizes permission control, logging, and usage accounting for tool calls.

    Overall Call Flow

    A complete request typically goes through the following stages:

    1. The client submits the user question and necessary environment information.
    2. The request declares which server-side tools are allowed.
    3. The model decides whether it needs to search the web or read a page.
    4. The server executes search, page fetching, and parsing.
    5. Tool results are returned to the model.
    6. The model generates a final answer using those results.
    7. The response includes tool-call records and usage information.

    This can be abstracted as:

    1. User question
    2. ↓
    3. Client submits context and tool declarations
    4. ↓
    5. Model decides whether external information is needed
    6. ↓
    7. Server performs search or page reading
    8. ↓
    9. Tool results are returned to the model
    10. ↓
    11. Model generates the final answer
    12. ↓
    13. Client displays the answer and records call information

    Compared with traditional client-side tool calling, the main difference with server-side tools is that the client does not need to implement tool functions, parse tool arguments returned by the model, or manage state between search requests and page-fetching requests.

    Why Time and Location Context Matters

    For questions about weather, traffic, news, prices, and events, the original user question alone is often insufficient. For example, “Is it suitable to go out today?” needs at least the date, time, city, and possibly language preference.

    Therefore, an application can add a system-generated context message to the request. It can include:

    • The current date.
    • The current day of the week.
    • The user’s city or timezone.
    • The user interface language.
    • Necessary business scenario information.

    This kind of context should not rely on the model guessing, and users should not have to provide it manually every time. A more reliable approach is to generate it on the server side using the system clock, account settings, and authorized location information.

    A sample context message might look like:

    1. Current date: 2026-11-14
    2. Current day: Saturday
    3. User region: Shanghai
    4. Response language: Chinese

    It is important to note that time and geographic information are context, not facts. For real-time weather, you still need a search service or a dedicated data service to get the latest result. Context helps the model construct a correct query, but it does not replace an external data source.

    Principles for Tool Declarations

    The core purpose of tool declarations is to tell the model which external capabilities are allowed for the current request. Common capabilities include:

    • Web search: generate one or more search queries to retrieve recent public information.
    • Web page reading: open a specified URL and extract title, body text, publication time, and structured content.
    • Internal enterprise tools: knowledge-base search, order lookup, inventory lookup, and similar services.

    When designing tool declarations, follow three principles.

    1. Least Privilege

    Enable only the tools needed for the current task. If the user only asks the model to summarize text that has already been provided, there is no need to enable web search. More tools mean a larger model decision space, higher potential risk, and more call cost.

    2. Make Tool Purpose Clear

    Tool names and descriptions should accurately express what they do. Web search is for obtaining external information. Web page reading is for analyzing a specific page. Do not blur the boundary between these two capabilities.

    3. Define Failure Handling Up Front

    Search may return no results, a page may be inaccessible, or a page may require login or contain a large amount of script content. The application should define failure strategies in advance. For example:

    • If search returns no results, clearly tell the user that the information cannot be confirmed.
    • If page reading fails, answer only from search summaries.
    • If sources conflict, list the differences and ask the user to verify.
    • If real-time status cannot be confirmed, do not output a definitive conclusion.

    Python Call Example

    The following example uses a generic Python HTTP client to illustrate the engineering structure. It does not bind to a specific vendor, domain, or proprietary product.

    1. import os
    2. import requests
    3. API_KEY = os.environ["MODEL_API_KEY"]
    4. API_URL = os.environ["MODEL_API_URL"]
    5. payload = {
    6. "model": "unified-model-id",
    7. "messages": [
    8. {
    9. "role": "context",
    10. "content": "Current date: 2026-11-14; Day: Saturday; Region: Shanghai; Language: Chinese"
    11. },
    12. {
    13. "role": "user",
    14. "content": "What is the weather in Shanghai today? Is it suitable to go out? Please answer briefly."
    15. }
    16. ],
    17. "tools": [
    18. {"type": "web_search"},
    19. {"type": "web_reader"}
    20. ],
    21. "generation": {
    22. "reasoning": "disabled"
    23. }
    24. }
    25. response = requests.post(
    26. API_URL,
    27. headers={
    28. "Authorization": f"Bearer {API_KEY}",
    29. "Content-Type": "application/json"
    30. },
    31. json=payload,
    32. timeout=30
    33. )
    34. response.raise_for_status()
    35. data = response.json()
    36. print(data["output"])

    In a real project, field names should follow the official documentation of the service you are using. Just because multiple interfaces use JSON does not mean their request structures, message roles, and response fields are identical.

    If the system needs to support multiple mainstream protocols at the same time, it is useful to build an adapter layer inside the application that converts different protocols into a common internal structure. For example:

    1. class UnifiedRequest:
    2. question: str
    3. context: list
    4. enabled_tools: list
    5. metadata: dict
    6. class UnifiedResponse:
    7. answer: str
    8. tool_calls: list
    9. usage: dict
    10. request_id: str

    This prevents business code from depending directly on one protocol. When the interface style changes or a new model service is added, only the adapter layer needs to be modified, not the upper-layer business logic.

    Handling Server-Side Tool Call Records

    Even though the client does not execute tools, it is still recommended to read and save tool-call records. They help developers answer important questions:

    • Did the model actually use search?
    • What keywords were generated?
    • Did the model read a specified web page?
    • Did tool calls fail or time out?
    • How many external calls were triggered by one request?
    • Which sources were referenced in the final answer?

    The following pseudocode shows how to inspect the records:

    1. answer = response.get("output", "")
    2. tool_trace = response.get("tool_calls", [])
    3. usage = response.get("usage", {})
    4. print("Answer:", answer)
    5. for item in tool_trace:
    6. print("Tool type:", item.get("type"))
    7. print("Status:", item.get("status"))
    8. print("Query:", item.get("query"))
    9. print("URL:", item.get("url"))
    10. print("Usage:", usage)

    In production, do not expose complete tool results to end users unconditionally. Search terms, page addresses, internal identifiers, and error messages may contain private or business-sensitive information. A better approach is to write raw records into a controlled logging system, then show simplified source information to users according to permission policy.

    Search Results Are Not Facts

    Web search improves timeliness, but it does not automatically guarantee correctness. Search results can have several problems:

    • The page was published a long time ago.
    • Multiple sources are actually reposting the same original source.
    • The title and body text do not express the same thing.
    • The page content has changed, but a cached version still exists.
    • Search summaries lack context.
    • The result comes from a low-credibility website.

    Therefore, when the model generates an answer, it should try to perform the following checks:

    1. Determine whether the information is directly relevant to the question.
    2. Check publication time and applicable region.
    3. Cross-verify key conclusions across multiple sources.
    4. Distinguish facts, inferences, and recommendations.
    5. Use uncertainty language when information cannot be confirmed.

    For weather questions, for example, the model should focus on structured data such as temperature, precipitation, wind, and warnings, rather than answering only based on a page title.

    Boundaries and Security Controls for Web Page Reading

    A web page reading tool usually has to handle redirects, script rendering, encoding conversion, and main-content extraction. The application layer should also consider the following risks:

    • Malicious pages may try to induce the model to reveal system prompts.
    • Page content may be disguised as system instructions.
    • Web pages may contain large amounts of irrelevant advertising.
    • The page may require login or form submission.
    • Links may redirect to unauthorized internal addresses.
    • Page content may be too long and exceed the context limit.

    Security policies should include:

    • Restrict accessible protocols and ports.
    • Block internal network addresses, loopback addresses, and abnormal redirects.
    • Limit the length of extracted web page content.
    • Mark web content clearly as untrusted external data.
    • Prevent the model from executing sensitive operations based on instructions found in web pages.
    • Check downloaded file types and scan for viruses.
    • Audit and rate-limit user-submitted links.

    It is especially important to treat the text on a web page as data to be analyzed, not as system-level instructions. Any operation involving data deletion, money transfer, sending messages, or changing permissions must go through an independent business authorization process.

    Timeouts, Retries, and Degradation

    Web requests are more susceptible to network instability than ordinary text generation. It is recommended to set independent timeouts for search and web page reading, and to use a limited retry mechanism.

    A reasonable degradation order can be:

    1. Allow both search and web page reading in the initial request.
    2. If search times out, return only the partial information already obtained.
    3. If web page reading fails, fall back to search summaries.
    4. If all external tools are unavailable, clearly state that real-time results cannot be obtained.
    5. For non-real-time questions, fall back to the model’s existing knowledge.

    Retries should not be unlimited, because they increase latency and cost. For repeated questions, a short cache can reduce duplicate searches.

    Observability, Billing, and Cost Control

    Server-side tool calls usually generate additional usage, so the system should not only measure the length of generated text. It should also record:

    • Total number of requests.
    • Number of search calls.
    • Number of web page reading calls.
    • Input and output content volume.
    • Tool execution time.
    • Timeout and failure ratios.
    • Average cost per business scenario.

    Each request should have a unique identifier. Logs should correlate the user, session, tool calls, and final response. For high-frequency scenarios, set daily quotas, per-call limits, and concurrency limits.

    At the same time, do not force web search on every question just to make the system seem more reliable. Real-time search should depend on the question type. Weather, news, prices, and events are good candidates. Code formatting, text polishing, and summarizing already-provided material usually do not need external retrieval.

    Implementation Checklist for Production

    Before launching, verify the following:

    • Date, timezone, and region are passed correctly.
    • When tools are disabled, the model does not claim that it searched the web.
    • Search failures produce transparent messages.
    • Web page content is treated as untrusted data.
    • Access addresses and redirects are restricted.
    • Tool calls and usage information are logged.
    • Timeout, retry, and concurrency limits are set.
    • Sensitive information is masked.
    • Protocol adaptation does not affect business code.
    • Human review and issue-tracking mechanisms are in place.

    Overall, the value of server-side tools is not just reducing a few lines of client code. More importantly, it brings search, web page reading, permissions, security, audit, and cost control into the platform layer. For developers, the best practice is to separate model invocation, tool execution, and business decisions into different layers: the model is responsible for understanding and generation, the server is responsible for controlled access to external information, and the business system is responsible for final authorization and risk control. This makes it possible to add real-time information while maintaining maintainability, observability, and security.