Tool Calling in LLM Applications: Integrating Web Search and File Parsing
This article explains how LLM applications evolve from conversational models into task-completing agents by integrating external tools. It covers the tool-calling workflow, JSON Schema tool definitions, integration methods for web search, web page reading, file parsing, and voice interaction, the trade-offs between hosted and self-built tools, a minimal agent loop, and engineering practices for context management, reliability, security, cost, latency, observability, and rollout.
1. Background: From Models That Can Chat to Applications That Can Complete Tasks
Early LLM applications were mostly single-turn or multi-turn text Q&A. The model could answer only from its training data. It could not retrieve information after the training cutoff, nor could it read documents uploaded by users.
Real product requirements go far beyond that. Users expect an assistant to look up recent information, read links they provide, understand PDFs and spreadsheets, and give answers with traceable sources. To meet these requirements, the application must let the model call external tools and then return the tool results to the model for further reasoning.
This capability is commonly called Tool Calling or Function Calling. It is one of the core engineering patterns for building intelligent applications today.
2. How Tool Calling Works
The tool-calling flow can be divided into four steps:
- The application sends the model the names, purposes, and parameter definitions of the available tools.
- Based on the user’s question, the model decides whether a tool is needed. If so, it returns a structured call request instead of directly producing an answer.
- The application executes the tool locally or on the server and obtains the result.
- The application appends the result to the conversation as a new message. The model then generates the final answer or initiates another round of calls.
Tool definitions usually describe parameters with JSON Schema. For example:
{"name": "web_search","description": "Search public information on the internet and return a list of titles, links, and summaries","parameters": {"type": "object","properties": {"query": {"type": "string", "description": "Search keywords"}},"required": ["query"]}}
The quality of the description directly affects the model’s tool-calling accuracy. The description should explain when the tool applies and what it returns, and avoid vague wording. For example, “get data” is less clear than “search the web by keyword and return the titles and links of the top five results.”
3. Integration Methods for Core Capabilities
3.1 Web Search
Web search addresses timeliness. Before answering time-sensitive questions, the model retrieves information first and then answers based on the search results.
Three points matter during integration:
- Trigger conditions: Not every question requires search. Small talk, code explanations, and similar questions can be answered directly to reduce latency and cost. The applicable scope of search can be explained through the tool description or system prompt.
- Result size: Search results should be truncated to a reasonable length, keeping only titles, links, publication times, and key summaries. Full page content should not be inserted directly into the context.
- Citation output: Answers should indicate information sources. Cited links must come from tool results and must not be generated by the model itself; otherwise, fabricated links become likely.
3.2 Web Page Reading
The web page reading tool fetches the body content of a specified URL and converts it into plain text or Markdown that the model can read.
Several problems tend to appear at this stage:
- A page may require login or rely heavily on script rendering, resulting in empty fetch results. The application needs to detect this situation and inform the user.
- Body content may be mixed with navigation bars and ads, consuming the context window. The quality of the body-extraction algorithm or service directly affects answer quality.
- The target address may point to an intranet or local service. The application must restrict the range of accessible addresses to prevent security risks such as server-side request forgery (SSRF).
3.3 File Parsing
The goal of file parsing is to convert PDFs, Office documents, and images into content that the model can process. Parsing methods fall into two broad categories:
- Plain text extraction: Suitable for text-heavy documents. It is fast and low-cost.
- Layout-aware parsing: Preserves heading hierarchy, table structure, and image-text positions. It is suitable for complex documents such as financial reports and research papers.
The application can choose a parsing strategy based on file type. Scanned files require optical character recognition (OCR) first. Parsing results should be chunked by chapter or page number to avoid passing extremely long text all at once.
3.4 Voice Interaction
Voice interaction generally consists of two modules: automatic speech recognition (ASR) and text-to-speech (TTS), connected by a text conversation layer. It is independent of tool calling, but in real-time scenarios, latency budgets require attention. Intermediate ASR results can trigger some tool calls early to reduce user waiting time.
4. Hosted Tools vs. Self-Built Tools
Developers can choose tools hosted by the model service provider or implement tools in their own services. Each approach has its own use cases:
| Dimension | Hosted tools | Self-built tools |
|---|---|---|
| Integration cost | Low; usually only requires enabling a parameter | High; retrieval, parsing, and other services need to be integrated separately |
| Controllability | Tool behavior is determined by the provider | Data sources, filtering rules, and logs can be customized |
| Data compliance | The service nodes through which data passes need to be evaluated | Data boundaries are determined by the application’s own architecture |
| Customization needs | Limited support | Can cover internal systems and private knowledge bases |
| Operational burden | Lighter | Stability and quotas need to be maintained |
A common practice is to use a hybrid approach: general web retrieval is handled by hosted capabilities, while retrieval involving internal enterprise data is handled by self-built services. The choice should be based mainly on data sensitivity, customization depth, and the team’s operational capabilities.
5. Integration Practice: A Minimal Viable Agent Loop
The following example shows the core tool-calling loop. The code is illustrative and omits error handling and authentication details.
def run_agent(user_message, llm, tools, max_steps=5):messages = [{"role": "user", "content": user_message}]for _ in range(max_steps):reply = llm.chat(messages=messages, tools=tools)# The model did not request a tool call, so treat the reply as the final answerif not reply.tool_calls:return reply.contentmessages.append(reply.as_message())for call in reply.tool_calls:result = execute_tool(call.name, call.arguments)messages.append({"role": "tool","tool_call_id": call.id,"content": truncate(result, max_chars=4000),})raise RuntimeError("Exceeded maximum reasoning steps; check whether tool calls are stuck in a loop")
This code reflects three engineering principles:
- Set a step limit. The model may repeatedly call the same tool. A limit prevents infinite loops and runaway costs.
- Truncate tool output. Overly long returned content consumes the context and increases reasoning latency.
- Preserve call IDs. The model needs to match results to specific call requests; otherwise, mismatches occur when multiple tools run concurrently.
6. Engineering Considerations
6.1 Context Management
Multiple rounds of tool calls can quickly consume the context window. Common practices include:
- Keep only the most recent rounds of full tool results and replace earlier results with summaries.
- Chunk long documents and build an index, then recall relevant snippets on demand.
- Apply rolling summaries to conversation history, retaining user goals, confirmed facts, and unresolved issues.
6.2 Timeouts, Retries, and Degradation
External tools have unstable response times. The application should set a timeout for each tool and use exponential backoff retries for transient errors. When a tool fails, the model should be told the reason for the failure so it can answer based on available information and state that the information is incomplete.
6.3 Security Boundaries
Web pages and file content returned by tools are untrusted data. They may contain instructions that attempt to change the model’s behavior, such as “ignore all previous rules.” The application should:
- Clearly state in the system prompt that tool results are reference material only and must not be executed as instructions.
- Add human confirmation steps for execution tools that send messages or modify data.
- Restrict the access range of the web page reading tool and block intranet and local addresses.
6.4 Cost and Latency
Every tool call increases model input and response time. It is advisable to log token consumption, tool latency, and final latency per round, aggregate them by request type, and then optimize high-frequency paths. For example, cache popular search results and set short-term caching for fetched results from the same URL.
6.5 Observability
The application should log the name, argument summary, return status, and latency of each tool call. These logs are the primary basis for investigating why the model produced a given answer, and they are also the data source for evaluating tool-calling accuracy.
7. Rollout Recommendations
When starting integration, proceed in the following order:
- Identify the one or two tool capabilities the product needs most. Do not integrate all capabilities at once.
- Write clear descriptions for each tool and run regression tests with a set of representative questions.
- Implement timeouts, truncation, and logging at the tool layer before connecting the model.
- Before launch, check whether cited sources are traceable and verify behavior in prompt-injection scenarios.
- Use high-frequency call paths in the logs to decide which capabilities should be self-built and which can remain hosted.
The value of tool calling lies in giving models access to real-world information. Whether these capabilities can be delivered reliably to users depends on the design quality of tool boundaries, context management, and security policies.
