Practical Application of Integrating Search and Tool Calling in LLM APIs
This article explores the practice of integrating search and tool calling into Large Language Model (LLM) APIs. It covers how server-side orchestration reduces integration costs, breaks down six common capabilities and their applicable scenarios, explains the underlying workflow, and provides a code example for a web search-enabled application. It also discusses cost, performance, security, and compliance considerations, while offering architectural recommendations and a deployment checklist.
1. Background: The Declining Integration Cost of Intelligent Applications
In the past, to build an intelligent application with web-based Q&A capabilities, developers usually had to complete multiple steps independently: connecting to search services, parsing web pages and documents, calling speech recognition and synthesis, and then stitching the results returned by various tools into a context understandable by the model. Each step involved authentication, timeout retries, format conversion, and error handling. The engineering effort often exceeded the model invocation itself.
A recent change is that some model services have begun to incorporate common external capabilities on the server side. Developers can enable corresponding features via parameter switches, while tool calling, result backfilling, and context stitching are handled by the server. This model shifts “orchestration” from the application layer to the platform layer, allowing developers to focus on product logic and user experience.
To understand this shift, it is necessary to distinguish between two concepts. Model capability refers to the model’s inherent understanding, reasoning, and generation. Tool capability refers to actions the model performs via external systems, such as retrieving information, reading web pages, parsing files, and converting speech. Only when combined can the model answer time-sensitive questions, process user-uploaded materials, and provide conclusions based on traceable sources.
2. Capability Breakdown: Six Common Capabilities and Scenarios
2.1 Web Search
Web search allows the model to retrieve public web pages or images before answering and to attach sources to the response. It is suitable for time-sensitive queries such as news, policies, pricing, and version information.
Two points require attention during use. First, the quality of retrieval results depends on how the query is generated; the model typically rewrites the user’s question into a search query. Second, the credibility of the answer depends on whether the sources are cited. The application layer should display citation links and retrieval timestamps so users can verify them.
2.2 Multi-step Retrieval in Deep Reasoning
In scenarios that support reasoning modes, the model can repeatedly retrieve and read links during multi-step reasoning, and then revise its judgment based on new results. This capability is suitable for multi-hop questions, such as needing to first confirm the date of an event and then looking up policies relevant to that time.
The trade-off is increased latency and cost. Each round of retrieval adds an external call, so expenses must be managed through maximum retrieval rounds, concurrency control, and caching strategies.
2.3 File Parsing
A typical file parsing workflow includes format identification, plain text extraction, layout and image content processing, chunking, and context injection. For scanned documents and images, OCR is required first to obtain text; for documents with mixed text and graphics, the title hierarchy and table structure must be preserved, otherwise the model will struggle to understand paragraph relationships.
# Pseudocode: Basic pipeline for file parsing, function implementation depends on the chosen parsing tooldef ingest_document(path: str) -> list[str]:fmt = detect_format(path) # Identify formats like PDF, Office documents, images, etc.if fmt == "image":text = run_ocr(path) # Convert image content to textelse:text = extract_text(path) # Extract plain text, preserving titles and table structuresreturn split_into_chunks(text, max_tokens=800) # Chunk the text to control context length
2.4 URL Reading
URL reading refers to the model identifying web addresses in user messages, scraping the page, and answering based on the context. Key engineering steps include removing navigation bars, ads, and scripts to retain only the main content; summarizing or segmenting overly long pages; and recording the scraping time to avoid treating expired content as current fact.
Additionally, applications must comply with the access terms of target sites and must not bypass logins or paywalls to scrape content.
2.5 Standalone Tool Interfaces
Beyond capabilities embedded in model conversations, platforms may also provide search, web scraping, OCR, speech recognition, and speech synthesis as standalone interfaces. The advantage of standalone interfaces is that they can be combined. For example, speech input can first be converted to text via speech recognition, then passed to the model for Q&A, and finally output as audio via speech synthesis.
When combining these, the input and output formats of each step should be clearly defined, and error propagation should be handled between steps. If speech recognition fails, subsequent steps should return a prompt immediately instead of passing empty text to the model.
2.6 Input and Output Safety Validation
Safety validation parameters can perform basic risk control checks on the model’s input and output. When a risk is detected, the interface returns a refusal flag, and the application displays a fallback message accordingly. Services facing external users should enable this capability by default and distinguish between “normal refusal” and “system errors” in both the frontend and logs.
3. Workflow: How Server-Side Orchestration Operates
A request involving tool calls typically goes through the following steps:
- Receive the request and parse the tool switches and reasoning mode parameters.
- The model determines whether the current question requires external information and generates tool call instructions.
- The server executes the tool calls to retrieve search results, web content, or parsed text.
- The server backfills the results into the context in a structured manner based on their sources.
- The model generates an answer based on the backfilled content and cites sources.
- The output is returned to the caller after passing a safety review.
For application developers, three things need attention: whether sources are traceable, whether the total latency of a single request is acceptable, and whether there is a fallback path if a tool fails. For example, if a search times out, the system can fall back to an answer based solely on the model’s knowledge, explicitly informing the user that the response has not been verified in real time.
4. Integration Example: Building an Application with Web Search
The following code illustrates the basic structure of the application layer. This is pseudocode, and parameter names and return structures should be based on the official documentation of the service used.
# Pseudocode: The application layer only organizes messages and switches; tool execution is handled by the serverdef answer_with_sources(client, question: str):messages = [{"role": "system", "content": "You are a rigorous Q&A assistant; answers must cite sources."},{"role": "user", "content": question},]response = client.chat(messages=messages,tools=["web_search"], # Enable web search; tool name is illustrativesafety_check=True, # Enable safety check; tool and parameter names are illustrative)if response.refused: # Returns a refusal flag when a risk is hitreturn "This question cannot be answered temporarily. Please try rephrasing it.", []return response.text, response.citations
The application layer should also handle the following issues:
- Render
citationsas a clickable list of sources and display the retrieval time. - Provide clear prompts for empty or timed-out results to prevent the model from fabricating content without evidence.
- Record the number of tool calls and the time consumed for each request for cost analysis and troubleshooting.
5. Cost and Performance Considerations
5.1 Cost Composition
When expanding capabilities using tools, the total cost usually consists of two parts: the token fees for the model’s input and output, and the tool calling fees. Tool fees may be calculated per call or based on the volume of data processed, subject to the official pricing table.
The cost per request can be estimated using the following formula:
Cost per request = Input tokens × Input unit price + Output tokens × Output unit price + Σ (Number of calls for the i-th tool × Unit price of that tool)
Estimates should be based on the distribution of real traffic rather than a single example. The number of tool calls in deep retrieval scenarios can fluctuate significantly, so a margin should be reserved.
5.2 Latency Control
Multi-step retrieval accumulates latency incrementally. Common control methods include:
- Setting a maximum number of tool call rounds, after which the model answers based on existing information.
- Caching results for hot queries with a reasonable expiration time.
- Executing parallel scraping tasks concurrently rather than waiting serially.
- Summarizing long documents before feeding them into the model to reduce context length.
5.3 Context Management
Content returned by tools can be very long. If all of it is directly appended to the context, it will squeeze the model’s effective reasoning space and increase costs. The recommended approach is to first filter segments by relevance, keeping only the parts directly related to the question, and noting the source location in the answer.
6. Security, Compliance, and Content Governance
When providing services to external users, governance work must run through the entire process of design, development, and operations.
- Safety Validation: Enable input and output review, design unified fallback messages for refusal scenarios, and retain audit logs for review.
- Compliance Obligations: Fulfill content safety reviews, generative content labeling, and relevant model registrations or filings in accordance with local regulatory requirements. Specific requirements are subject to the regulations issued by the competent authorities.
- Source Traceability: Retain citation links, retrieval times, and summary texts to facilitate user verification and to help discover and correct misinformation.
- Privacy Protection: Clearly define the storage period for user-uploaded files, desensitize sensitive information, grant access based on the principle of least privilege, and avoid logging original file content.
- Copyright and Site Rules: Comply with the access terms and copyright agreements of target sites when scraping web pages, and limit cited content to the necessary scope.
7. Architectural Recommendations and Deployment Checklist
In terms of engineering implementation, it is recommended to divide the system into five layers:
- Access Layer: Responsible for authentication, rate limiting, and request validation.
- Orchestration Layer: Responsible for deciding when to call tools and how to organize the context.
- Tool Layer: Encapsulates external capabilities such as search, scraping, parsing, and speech, with unified timeouts and error formats.
- Storage Layer: Saves sessions, cached results, and uploaded files, with defined expiration policies.
- Audit Layer: Records tool calls, safety blocks, and cost data to support troubleshooting and compliance audits.
Before going live, you can check the following items:
- Are timeout and retry limits set for each tool?
- Is there a clear fallback response path when a tool fails?
- Can citations in the response be clicked and accessed, with retrieval times noted?
- Is safety validation enabled, and are refusal messages unified?
- Is cost monitoring broken down by tool type?
- Are the storage period and deletion mechanism for user files clearly defined?
- Have all compliance obligations been confirmed item by item?
8. Conclusion
Incorporating capabilities such as search, parsing, and speech into server-side orchestration lowers the integration barrier for intelligent applications. Developers still need to balance cost, latency, source traceability, and security compliance. Designing each step of the tool calling process clearly and retaining observable data is the foundation for building reliable intelligent applications.
