Integrating Web Search and Tool Calling into LLM Applications: Common Practices

    This article describes common practices for adding external capabilities such as web search and tool calling to large language model (LLM) applications. It compares client-side and server-side tool calling, reviews core capabilities including web search, URL reading, file/OCR, speech, and content moderation, and outlines integration steps, cost control, quality assurance, security, and a launch checklist.

    1. Background: Why LLMs Need External Capabilities

    LLM training data has a cutoff date, so models cannot directly obtain real-time information such as weather, news, or stock prices. Users also frequently upload web links, PDF files, scanned documents, or audio, which go beyond the scope of plain text reasoning.

    In the past, teams often had to build an external capability chain themselves: search service integration, web crawling, body-text extraction, document parsing, OCR, speech recognition and synthesis, plus result stitching and error handling. Each module had its own interface, rate limits, and failure modes, resulting in high maintenance costs.

    In recent years, more service providers have built these capabilities into model interfaces as “tool declarations.” Developers enable the corresponding tools in a request, and the server handles retrieval, reading, and context stitching. The application only needs to handle the final result. Understanding the boundaries of this model is a prerequisite for deciding whether to adopt it.

    2. Two Tool-Calling Modes

    Tool calling generally falls into two categories, with clear differences in control and complexity.

    1. Client-side tool calling

    The model returns a function name and parameters to be executed. The application executes the function itself, sends the result back to the model as a new message, and the model then generates the final answer. This process may loop for multiple rounds.

    • Advantages: Every step is controllable; it can connect to internal enterprise systems and is easy to audit and customize.
    • Disadvantages: You need to write the call loop, timeout retry, parameter validation, and result truncation logic.

    2. Server-side built-in tools

    The request only declares the tool type. The model completes the call on the server side and returns the final answer, optionally with call records.

    • Advantages: Short integration path; no need to maintain tool execution code.
    • Disadvantages: Tool parameters, ranking strategies, and result formats are determined by the service provider, leaving limited room for customization.

    When choosing between them, consider the following dimensions:

    Dimension Client-side tool calling Server-side built-in tools
    Controllability High Medium
    Integration cost Relatively high Relatively low
    End-to-end latency Depends on your own chain Depends on server-side scheduling
    Auditability Fully autonomous Depends on call records
    Cost transparency Can be counted per item Need to check billing details

    During prototype validation, server-side built-in tools can quickly confirm business value. After entering the scale-up phase, if there are strict requirements for data sources, filtering rules, or audit trails, you should move to client-side tool calling or use a combination of both.

    3. Core Capabilities

    Web search. A search typically includes keyword generation, result recall, ranking, and summary filtering. Developers need to pay attention to result timeliness and source credibility, and keep source links in the answer.

    Web page reading. Raw web pages contain navigation, ads, and scripts. The quality of body-text extraction directly affects answer accuracy. Long pages need to be truncated or segmented; otherwise they consume the context window and increase input token usage.

    File input and OCR. Text-based files usually have their content extracted directly; images and scanned documents require OCR first. OCR accuracy is affected by resolution, skew angle, and fonts. Key fields such as amounts and dates should be validated a second time.

    Speech input and output. Speech-to-text focuses on sample rate, number of channels, and audio duration; text-to-speech focuses on voice, speaking rate, and first-packet latency for streaming output. Speech billing is generally based on duration, so long recordings should be split before processing.

    Content safety moderation. Moderation should cover both user input and model output. For scenarios that access external web pages, additional protection against prompt injection is needed, such as text hidden in a page that says “ignore previous instructions.”

    4. Integration Workflow

    Step 1: Manage credentials. API keys should be stored in environment variables or a secret management service, not written into code repositories or logs. Use different keys for different environments (development, testing, production), and set quota alerts.

    Step 2: Declare capabilities. List the tool types to enable in the request. Enable only the tools required by the business and follow the principle of least privilege.

    Step 3: Inject context. LLMs cannot perceive the current time and location. If a user asks “today” or “nearby,” inject the current date, time zone, region, and language into the system message to prevent the model from relying on outdated information in its training data.

    Step 4: Parse results. Read the final answer and save server-side call records, including search queries, source links, and call latency, for troubleshooting and frontend citation display.

    Step 5: Handle failures. Common failures include timeouts, rate limiting, empty results, and inaccessible web pages. The application needs a degradation strategy, such as returning “No reliable information was retrieved at this time” instead of letting the model answer without evidence.

    The following sample code illustrates the request structure. The class names, field names, and service address are placeholders. Actual parameter names should follow the official documentation of the selected service.

    1. client = LLMClient(api_key=env("LLM_API_KEY"), base_url=SERVICE_URL)
    2. response = client.chat_completion(
    3. model="general-chat-model",
    4. messages=[
    5. {"role": "system",
    6. "content": "Current time: 2026-11-14 Saturday, location: Shanghai, language: Chinese"},
    7. {"role": "user",
    8. "content": "What is the weather in Shanghai today? Is it suitable to go out? Please answer briefly"}
    9. ],
    10. tools=[{"type": "web_search"}, {"type": "read_url"}],
    11. thinking=False,
    12. timeout_seconds=30
    13. )
    14. answer = response.final_answer
    15. for call in response.tool_call_records:
    16. audit_log.write(call.name, call.query, call.source_urls, call.latency_ms)

    Three points in the code are worth noting: credentials come from environment variables; time and location are injected through the system message; and call records are fully written to the audit log.

    5. Cost Calculation and Control

    The total cost of a request usually consists of the following parts:

    Total cost = input tokens × input unit price + output tokens × output unit price + tool call count × per-call tool fee + speech duration × speech unit price

    Among these, tool call count is the variable most likely to get out of control. The model may search and read web pages multiple times in a single request, so the following measures are recommended:

    • Limit the maximum number of tool calls per request.
    • Cache results for identical queries for a short period, such as ten minutes.
    • Truncate web page body text to a fixed length to avoid long pages driving up input tokens.
    • Schedule batch tasks separately for peak and off-peak periods, and reconcile costs according to billing rules.
    • Summarize costs daily and break them down by feature module to identify high-consumption scenarios.

    6. Quality Assurance

    Traceability. Each factual statement in the answer should map to a source link. The frontend can display citation markers so users can verify the information.

    Timeliness. For questions that are highly time-sensitive, such as weather, prices, and policies, ensure that the publication time of search results is within an acceptable range and note the information date in the answer.

    Hallucination control. In the system prompt, require the model to “answer only based on retrieval results” and allow it to answer “cannot confirm.” When retrieval is empty, the application should directly return fallback copy.

    Offline evaluation. Build an evaluation set of about one hundred samples covering real-time information, multi-source comparison, file parsing, and speech transcription. After every change to prompts, tool configuration, or model version, rerun the evaluation and compare accuracy, citation completeness, and average latency.

    7. Security and Compliance

    Prompt injection protection. Web pages, files, and speech transcripts are all untrusted data. The system should clearly tell the model that this content is only material, not instructions, and that any text asking it to change behavior should be ignored.

    Data minimization. Before uploading files, desensitize them by removing sensitive fields such as ID numbers, phone numbers, and bank card numbers. Keep only necessary fields in logs and set a retention period.

    Two-way moderation coverage. Input moderation blocks violating requests, and output moderation blocks inappropriate content. Both should record the reason for blocking to support review and rule adjustment.

    Permission isolation. Different business lines should use independent keys and limit available tools according to the principle of least privilege. If a key is leaked, it should be revocable quickly without affecting other business lines.

    8. Launch Checklist

    1. Keys are stored in a secret management service, with no plaintext keys in code or logs.
    2. The tool list contains only business-required items.
    3. Time, location, and language are injected through the system message.
    4. Tool call count has an upper limit, and timeout and retry policies are defined.
    5. Answers include source links, and fallback copy is available when retrieval is empty.
    6. Web page and file content has prompt injection protection.
    7. Input and output moderation is enabled, and blocked events can be queried.
    8. Costs are counted by request, feature, and date, with budget alerts configured.
    9. The offline evaluation set passes the defined thresholds before release.

    After completing the checklist above, the prototype can enter a limited canary rollout. During this phase, focus on citation accuracy, average response time, and per-request cost before deciding whether to expand traffic.