Engineering Guide to Web Search and Tool Calling with Large Language Models
This guide explains how to build LLM applications that can search the web, read webpages, process PDFs and images, support voice interaction, and produce traceable answers. It covers capability decomposition, managed versus self-hosted tools, the tool-calling loop, retrieval and document-processing practices, citation validation, cost controls, voice evaluation, security, compliance, and a production readiness checklist.
1. Why More Capabilities Create More Engineering Work
Getting a large language model to answer a question is relatively easy. The challenge is enabling it to search the web when necessary, read webpages, parse PDF files, and turn the retrieved information into an answer with verifiable citations.
Developers traditionally need to integrate search APIs, extract webpage content, split documents, deduplicate results, track usage, and handle failures and retries. Together, these tasks create a significant engineering burden that is often underestimated during application development.
Some model providers now integrate application-level capabilities—such as web search, webpage reading, and file input—directly into their APIs. They may also provide standalone services for web crawling, OCR, speech recognition, and speech synthesis. This allows part of the toolchain to be managed by the service provider.
Whether to adopt this approach should be evaluated across four dimensions: feature coverage, cost, control, and compliance.
2. Capability Decomposition: Six Modules Behind Search-Augmented Q&A
A question-answering application that works with external information typically contains the following modules:
- Language model: Understands the question, decides whether to call a tool, and generates the final answer.
- Retrieval module: Returns candidate webpages or document passages based on a query.
- Web crawling and content extraction: Fetches pages and removes navigation elements, advertisements, and other noise.
- Document processing: Handles PDFs, Word files, images, and other formats. Scanned documents require OCR.
- Voice pipeline: Automatic speech recognition (ASR) converts speech to text, while text-to-speech (TTS) converts text back into audio.
- Citations and auditing: Records the sources supporting an answer for later verification.
This decomposition clarifies which modules can be outsourced and which should remain under the application’s control. Retrieval ranking and citation formatting directly affect answer quality, so they should generally remain in application code. There is usually no need to rebuild a general-purpose OCR engine.
3. Architecture Choices: Managed Tools or Self-Hosted Tools
The two approaches differ across several dimensions:
| Dimension | Managed tools | Self-hosted toolchain |
|---|---|---|
| Integration speed | Fast; tools can often be declared and used directly | Slower; multiple external services must be integrated |
| Control | Search sources, timeouts, and crawling policies may be restricted | Full control |
| Maintenance | Low; the provider handles much of the infrastructure | High; the team must handle anti-bot measures and changing page structures |
| Cost visibility | Usage-based billing requires independent tracking | Resource and labor costs are more explicit |
| Data boundaries | Content passes through a third-party service | Data can remain within an internal environment |
For prototypes, general-purpose Q&A, and early validation, managed tools are usually preferable because they reduce development time and validation costs.
For sensitive data, internal documents, or highly customized retrieval, self-hosting or a hybrid deployment is more appropriate. Sensitive processing can remain local while less sensitive capabilities are delegated to external services.
4. Core Workflow: The Tool-Calling Loop
The basic tool-calling pattern is a loop. The model requests a tool call, the application executes the tool, and the result is returned to the model. This continues until the model produces a final answer.
The application layer should enforce limits on the number of reasoning rounds, maintain a tool allowlist, and handle errors explicitly.
MAX_STEPS = 5 # Maximum number of reasoning roundsMAX_TOOL_CALLS = 8 # Maximum tool calls per requestdef answer(question: str) -> dict:messages = [{"role": "user", "content": question}]collected_sources = []tool_calls_used = 0for _ in range(MAX_STEPS):resp = llm.chat(messages, tools=TOOL_SCHEMAS)if not resp.tool_calls:return {"text": resp.text, "sources": collected_sources}for call in resp.tool_calls:if tool_calls_used >= MAX_TOOL_CALLS:raise RuntimeError("Tool call budget exhausted")tool_calls_used += 1result, source = run_tool(call.name,call.arguments) # Apply allowlist and type validation internallyif source:collected_sources.append(source)messages.append({"role": "tool","content": result,"tool_call_id": call.id})raise RuntimeError("Reasoning step limit exceeded")
Three implementation principles are especially important:
- Tool names and arguments must pass allowlist and type validation. The application must never execute arbitrary instructions generated by the model.
- Each call should record its duration, status, and source. This supports troubleshooting and cost accounting.
- When a budget is exceeded, the application should return an explicit error or a defined fallback result instead of failing silently.
5. Implementing Retrieval and Web Reading
The main objectives during retrieval are to improve recall while limiting noise.
- Query rewriting: Convert a conversational question into two or three groups of keywords, search them separately, and merge the results.
- Result deduplication: Merge duplicate entries using domain and title similarity.
- Freshness filtering: Restrict the publication date range for news, pricing, and policy-related questions.
Web reading requires stability and traceability:
- Set both connection and read timeouts so that a slow page does not block the entire request.
- Truncate extracted content to control the amount of text entering the context and prevent long pages from consuming the model’s useful context window.
- Save the page title, URL, and crawl time as citation metadata.
- Follow the target site’s access terms and robots directives. Do not bypass authentication or paywalls.
6. File Processing and OCR
A general file-processing workflow consists of uploading, parsing, chunking, indexing, and retrieving content when needed. Scanned documents should pass through OCR before entering the same pipeline.
Recommended chunking practices include:
- Split content by chapters or paragraphs, and preserve the heading path for each chunk, such as
Chapter 3 > 3.2 Cost Description. - Keep a small overlap between adjacent chunks to reduce semantic loss when sentences are split.
- Process tables separately. Convert them into structured text before indexing to preserve row and column relationships.
OCR output should be sampled and reviewed, with particular attention to numbers, units, dates, and formulas. For multi-page documents, record page numbers so that answers can point to precise locations.
If a passage has low recognition confidence, the answer should tell the user to verify it against the original document.
7. Citations and Answer Reliability
Reliable citations should satisfy three conditions:
- Every factual statement in the answer can be linked to a source passage.
- The user can open the source and verify the claim.
- The model does not cite information outside the retrieved results.
A common implementation is to require numbered citations such as [1] and [2] in the generated answer. The application then maps each number to a URL or document page.
Before returning the answer, the application can perform an additional validation step:
- Check that every citation number exists.
- Assess whether the cited passage corresponds to the claim through lexical or semantic matching.
- Remove unsupported sentences or mark them as requiring verification when validation fails.
8. Cost and Usage Control
Tool-enabled requests can incur both model token costs and tool usage costs. These categories should be tracked separately. Looking only at the model’s unit price can significantly underestimate total spending.
A basic per-request estimate is:
Per-request cost =(input and output tokens × model price)+ (number of tool calls × corresponding tool price)
Common cost-control measures include:
- Set daily per-user limits and per-request tool-call limits.
- Cache results for repeated queries and define an appropriate expiration period.
- Determine whether a question actually requires web access. Simple questions can be answered directly without retrieval.
- Recalculate costs regularly from production logs instead of relying only on theoretical estimates.
The gap between theoretical and actual costs often comes from retries, multi-round reasoning, and overly long webpages.
9. Evaluating the Voice Pipeline
Speech recognition and speech synthesis have a direct impact on user experience. Evaluation should cover:
- Recognition accuracy, especially for proper nouns and dialects
- End-to-end latency
- Naturalness of synthesized speech
- Concurrent request capacity
- Fallback behavior when a voice operation fails
Build a fixed test set covering quiet environments, noisy environments, different accents, and long utterances. Rerun the tests whenever the service or its parameters change.
If the voice experience does not meet the required standard, retain the text answer as a fallback and clearly inform the user that the application is operating in text mode.
10. Security and Compliance
Webpages and uploaded documents are untrusted data. They may contain text designed to persuade the model to ignore system instructions. Such content must be treated as ordinary text and must never receive permission to execute tools.
Other important considerations include:
- Define how long uploaded files are stored and provide a deletion mechanism.
- Redact personal information, such as phone numbers and government identification numbers, before writing logs.
- When quoting copyrighted material, include only the necessary excerpts and identify the source.
- For medical, financial, legal, and other high-risk domains, add appropriate disclaimers and introduce a human review step.
11. Production Readiness Checklist
- Tool allowlists, argument validation, timeout settings, and retry policies are configured.
- Usage budgets and cost-alert thresholds are defined.
- Citation-number-to-source mappings have been verified through sampling.
- Evaluation sets for voice and OCR have been established and meet the required targets.
- Logs do not contain unredacted sensitive information.
- A fallback strategy is available. If tools are unavailable, the application can still answer using existing knowledge and clearly state that the information may not be current.
