Building LLM Applications with Web Search, File Parsing, and Voice APIs
This article explains how developers can extend LLM applications beyond text generation by integrating web search, web page reading, file parsing, speech recognition, speech synthesis, and OCR. It covers single-round and multi-step retrieval, input handling and content safety, a three-layer agent architecture with its orchestration loop, cost estimation, engineering practices, and testing approaches.
1. Background: From Model Calls to Application Capabilities
Most developers who first integrated large language models used only the text generation API. To build a complete intelligent assistant, they also had to build their own search, document parsing, and speech transcription modules. Each module required separate selection, integration, and maintenance.
As providers began exposing these common capabilities as APIs, application development shifted its focus from building components to orchestrating capabilities.
This shift has two direct effects. First, an assistant’s core functions can be assembled from a few standard APIs, which shortens development time. Second, the cost structure has expanded from token-based billing alone to “model fees plus tool call fees.” Understanding both points is a prerequisite for evaluating whether a solution is feasible.
2. Core Capabilities
2.1 Web Search: Two Retrieval Strategies
When a model needs external information, it typically works in one of two ways.
- Single-round retrieval: The model determines that a question requires external information and issues one search request. It then generates an answer from the results and attaches citations. This approach suits time-sensitive questions and fact checking. It responds quickly and costs less per call.
- Multi-step retrieval: During reasoning, the model issues several search requests, revising its query terms based on intermediate results until it has enough information. This approach suits complex questions that require synthesizing multiple sources. It is more accurate but takes longer and requires more calls.
The two strategies differ mainly in latency and cost. Engineers should decide whether to enable multi-step reasoning based on question type, rather than enabling it for every request. One practical approach is to use single-round retrieval for simple questions and switch to a multi-step process when a question involves comparison, summarization, or multiple conditions.
2.2 Web Page Reading: From Links to Context
User messages often contain links. The system needs to handle three tasks: identifying the links, fetching the page content, and cleaning the content before adding it to the context.
The fetching stage must handle redirects, request timeouts, pages that depend on script rendering, and pages that require login. Each of these cases should return a clear failure result instead of leaving the model waiting indefinitely.
The cleaning stage removes navigation bars, advertisements, and scripts, keeping only the title and body text. It also records the original URL and fetch time so the answer can cite the source. Page content is often long, and inserting it directly into the context can fill the context window. Common approaches include splitting the text into paragraphs and selecting the relevant ones, or generating a summary before adding it to the context.
2.3 File Input: Parsing Workflow
File processing can be divided into three layers.
- Type identification: Determine the format by combining the file header and the file extension. Relying on the extension alone can be misleading, for example with a renamed executable or a corrupted document.
- Content extraction: Plain text files can be read directly. Document files require extracting the text while preserving the structure of paragraphs, lists, and tables as much as possible. Documents with complex layouts also need layout analysis to distinguish headings, body text, headers and footers, and multi-column content.
- Mixed text and images: Text in scanned documents and images must be recognized through OCR. Charts require position information and captions before the model can interpret their meaning.
Before the extracted content is added to the context, it should be split by page or section, with page numbers labeled. This lets the model cite the source accurately in its answer, and it lets users trace the answer back to the original document.
2.4 Speech and Recognition Capabilities
Speech-related capabilities typically include the following three types.
- Automatic speech recognition (ASR): Converts audio into text. Key considerations include sample rate, number of audio channels, silence-based segmentation, and timestamp output.
- Text-to-speech (TTS): Converts text into audio. Key considerations include voice, speaking rate, pauses, and how numbers, dates, and proper nouns are pronounced.
- Optical character recognition (OCR): Converts images or scanned documents into text. Key considerations include skew correction, layout reconstruction, and preservation of table structure.
These capabilities can be chained together into a pipeline or called individually. A complete voice assistant pipeline looks like this:
Voice input -> Speech recognition -> Orchestration and model inference -> Speech synthesis -> Voice output
The value of calling each capability separately lies in replaceability. If only one stage of an existing workflow needs an upgrade, such as the speech recognition module, the entire pipeline does not need to be rebuilt.
Example code is shown below. The function names are for illustration only.
def voice_assistant_turn(audio_in):text = asr(audio_in) # Speech recognitionanswer = run_agent(text) # Orchestration layer: model and tools work togetherreturn tts(answer.text) # Text-to-speech
2.5 Content Safety
Applications serving end users need content safety mechanisms, typically at three checkpoints.
- Input moderation: Block policy-violating questions and detect injected content that attempts to override system instructions.
- Output moderation: Check generated content. When a risk is detected, return a standard refusal message.
- External content moderation: Fetched web pages and uploaded files may also contain malicious instructions or policy-violating material. Filter this content before it enters the context.
Services offered to the public may also carry compliance obligations, such as content safety review, model registration, and labeling of generated content, where applicable. These requirements depend on the laws of each jurisdiction, so teams should confirm them with legal counsel before launch.
3. Architecture Design
The orchestration layer decides when to call which tool. A three-layer structure is recommended.
- Access layer: Handles session management, identity authentication, and request rate limiting.
- Orchestration layer: Maintains conversation context, parses tool call requests from the model, executes them, and returns the results to the model.
- Tool layer: Adapters for search, web page fetching, file parsing, and speech services. Each adapter manages timeouts, retries, and logging in a consistent way.
The core logic of the orchestration loop is shown below:
def run_agent(user_msg, tools, model, max_steps=5):context = [user_msg]for step in range(max_steps):resp = model.generate(context, tools=tools.schemas())if not resp.tool_calls:return resp # No tool needed, return the reply directlyfor call in resp.tool_calls:result = tools.execute(call.name, call.args, timeout=10)context.append(result.as_message())raise RuntimeError("Exceeded the maximum number of tool-call steps")
This code has three design points. First, max_steps limits the number of loop iterations, which prevents an infinite loop if the model keeps calling tools. Second, every tool call has a timeout, so a single slow request cannot stall the entire pipeline. Third, tool results should be compressed before being added to the context, keeping only the fields relevant to the question. This saves context space.
4. Cost Accounting
The total cost can be expressed as follows:
Total cost = Model token fees + Sum of (number of calls for each tool × unit price for that tool)
Tool fees are usually metered by number of calls or amount of processing, for example per thousand requests, per page, or per minute of audio. Metering units vary widely across providers. For this reason, prices should not be hard-coded. Instead, read them from the provider’s current pricing schedule and reconcile them regularly.
An example cost estimation function is shown below:
def estimate_cost(tokens_in, tokens_out, tool_counts, prices):model_cost = tokens_in * prices["in_per_token"] + tokens_out * prices["out_per_token"]tool_cost = sum(n * prices[name] for name, n in tool_counts.items())return model_cost + tool_cost
Common cost optimization methods include the following.
- Cache search and fetch results: Reuse results when the same query recurs within a short period.
- Limit multi-step reasoning: Set a maximum number of tool calls for each type of request.
- Summarize web pages and files before adding them to the context: This reduces the number of tokens entering the context.
- Enable tools only when needed: Activate a capability only when the question actually requires external information.
5. Engineering Practices
- Source tracking: Attach a source URL and retrieval time to every conclusion drawn from external content, so it can be verified and audited.
- Timeouts and graceful degradation: When a tool fails, tell the model the reason for the failure. The model should then answer without relying on external information and state that the information could not be retrieved.
- Idempotency and caching: Read requests can be retried safely. Write requests need idempotency keys to prevent duplicate execution.
- Observability: Record the latency, status code, response size, and cost of each tool call, and set alerts for anomalies.
- Privacy protection: Uploaded files and voice recordings often contain personal information. Define a clear retention period, avoid long-term storage by default, and explain how the data is used in the user-facing interface.
6. Testing Methods
Tests should cover typical scenarios and edge cases for each capability.
- Search: Build test sets that include time-sensitive information, contradictory sources, and queries with no results. Check whether the model correctly flags uncertainty.
- Web page reading: Cover redirects, timeouts, dynamically rendered pages, and pages that require login.
- File parsing: Cover scanned documents and multi-column layouts
