Connecting Large Language Models to the Web: Server-Side Tool Calling and Cost Management
This guide explains how to add web access to large language model applications through server-side tool execution. It compares client-side and server-side workflows, covers request construction and response parsing, and outlines practical approaches to usage tracking, cost estimation, reliability, security, and launch readiness.
1. Why Large Language Models Need Web Access
Large language models have a training data cutoff and cannot directly access real-time information. Questions about weather, stock prices, news, and product documentation often require the model to retrieve information from external sources before answering.
A common approach is to provide two types of tools:
- A search tool that returns summaries of relevant web pages for a set of keywords.
- A retrieval tool that fetches the content of a URL and converts the page into text.
Web access improves both the timeliness and verifiability of responses. When the model provides a conclusion, it can also include source links, allowing developers and users to assess the reliability of the answer.
2. Two Tool Execution Models
Before adding web access, decide who will execute the tools. There are two common models.
1. Client-Side Execution
The application declares function definitions in the request. The model then returns an instruction to call a specific function with specific parameters. The application parses that instruction, calls a search service or fetches a web page, and sends the result back to the model as a new message.
This loop may continue for multiple rounds. Developers must manage state, handle errors, and limit the number of iterations.
2. Server-Side Execution
The model service handles both tool invocation and execution. The client only declares which tools are enabled. The service performs the search or page retrieval, organizes the results, and generates the final response.
The client receives the complete answer along with the tool invocation records returned by the service.
The two models involve different trade-offs:
| Dimension | Client-Side Execution | Server-Side Execution |
|---|---|---|
| Development effort | Requires an invocation loop and result forwarding | Only requires tool declaration and result parsing |
| Control | Search sources and crawling rules can be fully customized | Depends on the provider’s search and retrieval strategies |
| Latency | Multiple round trips can add latency | Usually reduces client-side round trips |
| Troubleshooting | The call chain is local and easier to debug with breakpoints | Troubleshooting depends on the returned invocation records |
Client-side execution is a better fit when a business needs its own knowledge base or strict control over the allowed data domain. Server-side execution has a lower integration cost when the goal is to quickly add general-purpose web-based question answering.
3. The Basic Server-Side Tool Calling Workflow
In a server-side execution model, a request generally follows this lifecycle:
- The client sends conversation messages and tool declarations.
- The model determines whether external information is needed and, if necessary, generates search terms or target URLs.
- The service performs the search or retrieves web pages, then passes the raw results to the model.
- The model combines the information and generates an answer.
- The response includes the answer, tool invocation records, and usage statistics.
Developers should pay particular attention to the fifth step. The answer affects the user experience, the invocation records provide traceability, and the usage statistics support cost accounting. All three should be stored completely.
4. Request Construction and Example Code
The following example shows the basic request structure. Exact field names, tool type identifiers, and model names depend on the service being used. The placeholders in this example must not be used directly in production.
import os# Read the key from an environment variable; do not write it into code or logsapi_key = os.environ["LLM_API_KEY"]request = {"model": "<model identifier>","messages": [# Put time, location, and language context in the system message# to help the model understand the query{"role": "system", "content": "Current time: 2026-11-14, Saturday; location: Shanghai; output language: Chinese"},{"role": "user", "content": "What is the weather like in Shanghai today? Is it suitable for going out? Please answer briefly."},],# Declare the server-side tools to enable. The client does not# implement the actual tool execution logic."tools": [{"type": "<web search tool type>"},{"type": "<web retrieval tool type>"},],# Enable or disable optional settings such as reasoning# according to the provider's documentation"options": {"reasoning": "disabled"},}
Several implementation details are important:
- Provide context upfront. The model cannot automatically know the current time or location. Including this information in the messages reduces ambiguity in generated search queries.
- Manage keys securely. Store API keys in environment variables or a secrets management service. Do not hard-code them in a repository.
- Keep tool declarations minimal. Enable only the tools required by the application. More tools can increase uncertainty around both billing and latency.
5. Parsing Responses and Preserving Invocation Records
A response generally contains two types of information: the answer text and the server-side tool invocation records. The following practices are recommended:
- Store the answer and records separately. Use the answer for display and the records for auditing and troubleshooting.
- Log invocation actions. Preserve search queries, target URLs, and invocation types so that the basis of an answer can be reviewed.
- Handle empty results. If a search fails or a page cannot be accessed, the model may produce a cautious response. The application should detect this situation and notify the user in the interface.
An illustrative parsing function is shown below:
def extract_answer(response: dict) -> dict:answer = response["choices"][0]["message"]["content"]tool_logs = response.get("server_tool_calls", [])sources = []for step in tool_logs:for call in step.get("calls", []):action = call.get("action", {})# Record the search query or URL for later reviewsources.append({"kind": call.get("kind"),"query_or_url": action.get("queries") or action.get("url"),})return {"answer": answer, "sources": sources}
6. Usage and Cost Estimation
Server-side tools are commonly billed according to two categories:
- The number of input and output tokens processed by the model.
- The number of tool calls or the amount of time spent processing them.
Some services may also use different prices for different time periods, such as peak and off-peak hours.
A basic estimate can be expressed as:
Cost per request = input tokens × input price + output tokens × output price + search calls × price per search call + page retrievals × price per retrieval
When implementing cost accounting, keep the following points in mind:
- Use the official pricing information. Prices may change, and promotional or limited-time rates may expire. Avoid hard-coding prices in application logic.
- Track actual usage. Read tool invocation counts from the usage fields in the response instead of relying only on local estimates.
- Set budget alerts. Track costs daily or monthly. Send notifications or apply rate limits when spending exceeds a threshold.
- Separate testing and production. Use separate keys for test traffic so that experimental usage can be accounted for independently.
7. Engineering Practices: Timeouts, Caching, and Fallbacks
Web access introduces external dependencies, so reliability requires dedicated design.
- Set timeouts. Apply an overall request limit. Page retrieval latency can vary considerably. After a timeout, return a fallback answer without web results and explain the reason.
- Cache results. For questions with short-lived validity, such as weather and exchange rates, cache results at the application layer with an appropriate expiration time. Historical facts can generally use a longer cache period.
- Use a retry strategy. Apply exponential backoff to retryable errors to avoid repeated requests and unexpected charges. Before implementing retries, confirm whether the provider charges for failed requests.
- Apply rate limits. Limit request frequency per user at the gateway layer to prevent abnormal traffic from causing uncontrolled costs.
8. Security and Content Compliance
Web-enabled applications bring external page content into the model context. This creates several risks that must be addressed:
- Prompt injection. Web pages may contain text designed to change the model’s behavior. The system prompt should clearly state that page content is reference material, not an instruction.
- Data leakage. Do not include sensitive user information in search queries. Queries should contain only the minimum information necessary to complete the task.
- Source reliability. For high-risk domains such as healthcare, law, and finance, include sources with the answer and remind users to verify the information independently.
- Copyright and compliance. When displaying retrieved content, follow the target website’s terms of use and identify the source.
9. Pre-Launch Checklist
Before releasing the feature, verify each of the following items:
- The tool execution model has been selected based on business requirements, and the rationale has been documented.
- Keys are stored in environment variables or a secrets management service, and logs contain no keys.
- Only necessary tools are enabled in requests.
- Response parsing covers successful, empty-result, and failure cases.
- Invocation records are persisted for later review.
- A cost estimation model has been established, with budget alerts configured.
- Timeout, retry, rate-limiting, and fallback strategies have been tested.
- The system prompt includes protections against prompt injection from web content.
- End-to-end testing has been completed with test traffic, and the results have been recorded.
Conclusion
Adding web access to a large language model application starts with choosing the right tool execution model. The integration should then cover request construction, response parsing, usage tracking, cost management, and reliability engineering.
Server-side execution can significantly reduce development effort, but it must be supported by complete invocation logging and cost monitoring. Before launch, teams should validate the entire workflow end to end and continue adjusting the implementation based on actual usage.
