Building a Real-Time, Multimodal Conversational App with Large Language Model APIs
This practical guide explains how to connect large language models with web search, webpage retrieval, document parsing, OCR, and voice pipelines. It covers tool calling, context management, security, prompt injection protection, cost and latency optimization, evaluation, and production rollout strategies.
1. Why Conversational Apps Need Tool-Based Capabilities
Large language models have a knowledge cutoff and cannot directly access live webpages or a user’s private files. To answer time-sensitive questions or work with user-provided materials, the application layer must provide external capabilities. A common approach is to package search, webpage fetching, and file parsing as tools. The model decides whether a tool is needed, and the application returns the execution result as additional context.
This pattern is commonly known as tool use or function calling. The complete workflow has five steps:
- The application declares each tool’s name, purpose, and parameter schema to the model.
- When necessary, the model outputs a structured tool-call request.
- The application executes the actual operation locally or on the server.
- The application adds the execution result to the conversation in the required format.
- The model generates a final response based on the result.
Understanding these five steps provides the foundation for designing the capabilities discussed below.
2. Core Capabilities and Implementation Considerations
2.1 Web Search
Web search provides the model with up-to-date information. When the model determines that a question involves recent events, prices, policies, or other information that changes frequently, it can issue a search request. The application can also define rules—for example, requiring search for certain keywords—to reduce the chance that the model misses a necessary lookup.
Search results typically include a title, summary, URL, and publication time. Three implementation details are particularly important:
- Limit the number of results. Returning the first five to ten results is usually sufficient and prevents irrelevant content from consuming the context window.
- Remove duplicates. Results covering the same topic should be deduplicated.
- Filter by publication time. Outdated content should be excluded when freshness matters.
During answer generation, instruct the model to cite its sources and distinguish between facts found through search and conclusions inferred by the model. This allows users to verify the result.
2.2 Webpage Retrieval
Webpage retrieval allows the model to understand links included in user messages. The application should first identify URLs in the message and then decide whether they should be fetched.
This capability has significant security risks, so validation must happen before retrieval:
- Allow only the
HTTPandHTTPSprotocols. - Check whether the domain is within an approved range.
- Resolve the domain to an IP address.
- Reject internal-network and loopback addresses to prevent server-side request forgery (SSRF).
Fetched HTML usually contains navigation elements, advertisements, and scripts. Sending the full page directly to the model wastes tokens. Content extraction generally involves three steps:
- Remove script and style tags.
- Keep the main content area.
- Split the content by paragraphs or headings.
The application should also set a timeout and a maximum response-body size. This prevents a slow or unusually large website from blocking the entire request chain.
2.3 File Parsing
PDFs, Office documents, and images require different processing paths.
Text-based documents can usually be converted directly into plain text. Documents with complex layouts—including tables, multiple columns, or mixed text and images—require parsers that preserve layout structure. Scanned documents and photos first need optical character recognition (OCR) to convert images into text.
Parsed content should be divided into chunks. Each chunk should retain metadata such as the page number and heading hierarchy, allowing the model to provide evidence for where an answer comes from.
The upload process should include at least three validations:
- Limit file size and page count.
- Use file-header magic numbers to determine the actual file type instead of relying only on the extension.
- Apply a timeout to parsing operations so that maliciously constructed files cannot consume excessive resources.
2.4 Voice Processing
Voice interaction typically has two stages:
- Automatic speech recognition (ASR): Converts the user’s speech into text.
- Text-to-speech (TTS): Converts the model’s text output into audio.
These stages can be called independently, making it easier to replace either one with a more suitable implementation. When combined, end-to-end latency becomes a key metric. Streaming is commonly used so that transcription appears while the user is speaking and synthesized audio begins playing as it is generated. This reduces the perceived time to the first response.
Errors in speech recognition are passed directly to the model. In critical business scenarios, the application should display the transcription to the user after recognition and allow the user to confirm or edit it before further processing.
3. Context Assembly and the Tool Loop
Tool results can consume a large portion of the context window, so the way they are assembled directly affects answer quality and cost. Common strategies include:
- Sort search results by relevance and keep only the most useful items.
- Summarize long documents before adding them to the context.
- Use a sliding window for conversation history while retaining the most recent turns in full.
- Keep system instructions at the highest priority so they are not pushed out by historical content.
In multi-step reasoning scenarios, the model may issue several tool calls in sequence. A maximum loop count is therefore necessary to prevent infinite loops and uncontrolled spending. The following example shows the basic structure of a tool loop:
MAX_STEPS = 5def answer(user_msg, history, tools):messages = build_messages(history, user_msg)for _ in range(MAX_STEPS):resp = llm.chat(messages, tools=tools)if not resp.tool_calls:return resp.textfor call in resp.tool_calls:validate_args(call.name, call.arguments) # Validate arguments before executionresult = run_tool(call.name, call.arguments)messages.append(tool_result(call.id, truncate(result, limit=4000)))return "The request could not be completed within the step limit. Please narrow the scope and try again."
Three design choices in this example are especially important:
validate_argschecks the arguments before execution. Model-generated output must not be trusted unconditionally.truncatelimits the size of an individual tool result.- The loop limit guarantees that the request eventually ends.
If the model has not produced a final answer when the limit is reached, the application should return a clear message instead of failing silently.
4. Security and Compliance
Security controls should cover three layers: input, output, and tools.
Content safety checks should be deployed at both the input and output stages. When content triggers a risk policy, the application should return a consistent refusal message and record an audit log. User content in logs should be redacted to prevent sensitive information from being retained unnecessarily.
Webpages and uploaded files are untrusted data. Attackers may embed instructions in a webpage or document to induce the model to disclose information or perform unauthorized actions. This risk is known as prompt injection.
Recommended protections include:
- Clearly state in the prompt that external content is reference material only and that instructions found in it must not be executed.
- Surround external content with clear boundary markers.
- Give tools that can cause side effects—such as sending messages or modifying data—separate permissions and require explicit user confirmation.
When offering the service publicly, the operator must also meet applicable compliance obligations. These may include content safety review, algorithm or foundation-model registration requirements, and labeling of generated content. Requirements vary by jurisdiction and may change over time, so they should be confirmed with the relevant authorities before development begins. Compliance checks should also be included in the production launch checklist.
5. Cost, Latency, and Reliability
From a cost perspective, raw tool output is often the main source of token consumption. Truncating, summarizing, and denoising webpage and document content can significantly reduce the cost of each conversation. The application should also track the number of calls and average response size for each tool to identify the most resource-intensive components.
From a latency perspective, multiple sequential calls add their durations together. Independent tool calls can run in parallel—for example, searches for several keywords can be executed simultaneously. Search and webpage retrieval operations should have timeouts and a limited number of retries. If they fail, the application can fall back to an answer that does not depend on external information and clearly tell the user that live sources were unavailable.
Caching can reduce repeated requests. Results for the same search query or URL can be reused for a short period, but every cache must have an expiration time. It should also be invalidated when the underlying content changes; otherwise, the application may return stale information.
6. Evaluation and Production Rollout
An evaluation system should be established before launch. The test set should cover the following scenarios:
- Questions that require recent information.
- Questions that require source citations.
- Messages containing suspicious links.
- Very large files and scanned documents.
- Accents and noisy audio that are difficult for speech recognition.
- Clearly disallowed input.
Evaluation metrics can be divided into four categories:
- Tool-call accuracy: Whether the application calls a tool when it should and avoids calling one when it should not.
- Citation accuracy: Whether the cited sources genuinely support the conclusions.
- Refusal and false-refusal rates: Whether the safety strategy maintains an appropriate balance.
- End-to-end latency and per-conversation cost: Whether the implementation is efficient.
A staged rollout is recommended. Start by exposing the service to a small percentage of traffic, then gradually expand it after the key metrics remain stable. Whenever search strategies, prompts, or truncation thresholds are changed, rerun the test set. This helps prevent an improvement in one area from causing a regression in another.
7. Conclusion
The core engineering task in a conversational application is to connect the model to external capabilities while establishing clear boundaries at every connection point.
Web search, webpage retrieval, and file parsing address information access. Voice processing addresses the interaction format. Safety controls and compliance design address operational risk. In implementation, the most important areas are limiting the tool loop, assembling a concise context, isolating untrusted content, and conducting systematic evaluation before launch.
A well-designed system can achieve a stable balance between response quality, operating cost, latency, reliability, and compliance.
