Building Web-Connected Q&A and Multimodal Applications with LLM APIs

    This article explains how to build an LLM application that combines web search, file parsing, link reading, deep reasoning, and voice interaction through a unified API. It covers the capability breakdown, a reference architecture, design trade-offs, cost and failure handling, voice pipelines, security and compliance, and a pre-launch testing checklist.

    1. Background and Problem Definition

    LLM applications are moving beyond single-turn text Q&A toward experiences that combine multiple capabilities. Users expect an application to retrieve up-to-date information from the web, read attachments, understand links to web pages, and support voice interaction. The application must also meet content safety requirements.

    In the past, developers had to assemble several services themselves: search, document parsing, optical character recognition (OCR), speech recognition (ASR), speech synthesis (TTS), and content moderation. Each step required its own handling of authentication, timeouts, format conversion, and context management. The longer the chain, the more points of failure it has.

    When a unified interface moves these capabilities to the server side, the server handles tool calls and context assembly automatically, and the client-side engineering effort drops noticeably. However, this raises new design questions: which decisions belong to the server, which must the client control, how to locate the cause of an error when one occurs, and how to control costs. This article addresses these questions.

    2. Capability Breakdown: From Features to Architecture

    Before designing the system, split the capabilities into modules that can be observed and controlled independently. A typical multimodal conversation system can be divided into six categories.

    1. Web search: The model determines from the question whether external information is needed, starts a search on its own, and generates an answer with citations based on the search results.
    2. File input: PDFs, office documents (text, spreadsheets, and presentations), and images are converted into text through text extraction or layout parsing, then added to the conversation context.
    3. Link reading: The system detects URLs in user messages, fetches the main content of each page, and provides it to the model for answering.
    4. Deep reasoning: The model interleaves search and reading across multiple reasoning steps. This suits questions that require synthesizing information from multiple sources.
    5. Voice capabilities: OCR recognizes text in images, ASR converts speech to text, and TTS converts text to speech. Each can be called on its own or combined into a complete pipeline.
    6. Safety checks: Inputs and outputs are moderated. When a risk is detected, the system returns a refusal flag, and the client decides how to display it.

    A reference architecture for combining these modules looks like this:

    1. Client (text / files / voice / links)
    2. │
    3. ▼
    4. Access gateway (authentication, rate limiting, request logging)
    5. │
    6. ▼
    7. Conversation orchestration layer
    8. ├─ Tool switches: web search / link reading / file parsing / deep reasoning
    9. ├─ Voice pipeline: OCR / ASR / TTS
    10. └─ Safety checks: input moderation → model inference → output moderation
    11. │
    12. ▼
    13. Response rendering (body text, citations, refusal flags, audio stream)

    The orchestration layer is the key component. It determines which tools are available for each request, defines the fallback strategy when a step fails, and decides which logs to keep. Even when the underlying capabilities are provided centrally by the server, the orchestration layer still needs to be implemented on the business side.

    3. Design Decisions Before Integration

    3.1 Trade-offs Between Self-Built Orchestration and a Unified Interface

    Each approach suits different scenarios. The table below compares them across several dimensions.

    Dimension Self-built multi-service orchestration Unified interface with server-side tools
    Development cost High, since each service must be integrated separately Low, integrated once
    Control granularity Fine-grained, every step can be customized Moderate, depends on server-side behavior
    Troubleshooting Clear per-stage separation, but the chain is long More black-box behavior, relies on logs and timeout settings
    Data flow Each step can be precisely controlled Requires clarity on the server’s data processing scope
    Maintenance burden Continuous investment as services are upgraded Mainly follows changes in the interface version

    For small teams or rapid validation, a unified interface is usually the better fit. For systems with strict requirements on data flow, latency, or cost, you can keep self-built orchestration and use unified capabilities only for some steps.

    3.2 Enabling Tools On Demand

    Each tool adds request latency and cost. For example, web search introduces external network latency, link reading may fail on pages rendered dynamically, and deep reasoning increases the number of inference steps. For this reason, enable tools based on the business scenario rather than turning all of them on by default.

    One practical approach is to route requests by question type: disable web search for pure knowledge questions, enable it for time-sensitive information, and enable file parsing when the user attaches a file.

    3.3 Managing Context Length

    Text extracted from files can be very long. Adding all of it to the context takes up space for useful information and increases cost. Common approaches include:

    • Split content by page or paragraph, and select only the chunks relevant to the question;
    • For very long documents, generate a summary first, then answer the user’s question based on that summary;
    • For tabular content, preserve the structure so that row and column relationships are not lost.

    3.4 Failure Fallbacks

    Any external capability can fail. Search timeouts, inaccessible links, and low-confidence speech recognition are all common. The answer should clearly tell the user whether the information is complete, rather than presenting a definitive conclusion without evidence. For example, “The link could not be accessed. The following answer is based only on the available context” is more reliable than presenting a guess.

    4. Example: Wrapping a Q&A Client with Safety Checks

    The code below is an illustrative pseudo-implementation that shows the structure of a client wrapper. The field names and function names are placeholders. For actual development, follow the official documentation of the service you use.

    1. import time
    2. ALLOWED_TOOLS = {"web_search", "read_url", "file_parse"}
    3. def call_with_retry(body: dict, timeout: float, max_retries: int = 2) -> dict:
    4. """Retry timeouts a limited number of times with exponential backoff. Raise all other exceptions immediately."""
    5. for attempt in range(max_retries + 1):
    6. try:
    7. return llm_client.post(body, timeout=timeout) # Placeholder: the actual HTTP call
    8. except TimeoutError:
    9. if attempt == max_retries:
    10. raise
    11. time.sleep(2 ** attempt)
    12. def ask(user_id: str, text: str, tools: set[str], files: list[str] | None = None) -> dict:
    13. unknown = tools - ALLOWED_TOOLS
    14. if unknown:
    15. raise ValueError(f"Unregistered tools: {unknown}")
    16. body = {
    17. "user_id": user_id, # Used for auditing and rate limiting. Should not contain sensitive personal information.
    18. "input": text,
    19. "tools": sorted(tools),
    20. "safety_check": True, # Must be enabled for external users.
    21. }
    22. if files:
    23. body["files"] = [upload_file(f) for f in files] # Placeholder: file upload function
    24. resp = call_with_retry(body, timeout=30)
    25. if resp.get("refused"):
    26. return {"status": "refused", "answer": "This request did not pass the content safety review."}
    27. return {
    28. "status": "ok",
    29. "answer": resp["output"],
    30. "citations": resp.get("citations", []), # Citation sources, for display in the frontend
    31. }

    This code applies several engineering principles.

    First, a tool allowlist. Only registered tools can be called, which prevents configuration errors or external input from introducing unknown capabilities.

    Second, safety parameters are enabled by default. Services open to the public must have content safety checks turned on. This should not be an option that callers can disable.

    Third, separate timeout handling from retries. Only timeouts are retried, a limited number of times with backoff. Retrying parameter errors or authentication failures is pointless and only multiplies bad requests.

    Fourth, structured results. Refusals, normal answers, and citations are returned separately, so the frontend can display each one differently.

    5. Combining Voice Capabilities into a Pipeline

    Voice capabilities usually appear as a multi-step pipeline. Take “ask a question by taking a photo and hear the answer read aloud” as an example. The flow is as follows:

    1. Run the image through OCR to extract the text and layout information;
    2. Combine the recognized text with the user’s spoken question (converted to text by ASR) as context;
    3. The model generates a text answer;
    4. Convert the text to audio with TTS and return it to the client for playback.
    1. def voice_qa(image_bytes: bytes, audio_bytes: bytes) -> bytes:
    2. ocr_text = ocr_recognize(image_bytes) # Placeholder: image text recognition
    3. question = asr_transcribe(audio_bytes) # Placeholder: speech-to-text
    4. prompt = f"Image content: {ocr_text}\nUser question: {question}"
    5. answer = ask("anonymous", prompt, tools=set()).get("answer", "")
    6. return tts_synthesize(answer) # Placeholder: text-to-speech

    Two points need attention when combining steps into a pipeline.

    First, latency accumulates across steps. Each step may take from a few hundred milliseconds to several seconds, so the overall experience depends on the slowest step. TTS can start playing audio while the rest of the text is still being generated, which reduces the user’s wait time.

    Second, errors propagate along the pipeline. OCR errors directly affect the model’s reasoning, so keep confidence scores in the intermediate results and ask the user to confirm when confidence is low.

    6. Security and Compliance

    6.1 Two-Way Content Moderation

    Input moderation prevents policy-violating questions from reaching the model. Output moderation prevents policy-violating content generated by the model from being shown to the user directly. Without both, risks remain open. Treat a refusal flag as a normal business state and record it in the audit log. Do not display it as a system error.

    6.2 Trust Boundaries for External Content

    Web page content, file content, and speech transcription results are all untrusted data. They may contain text that tries to make the model ignore its original instructions, which is known as prompt injection. In practice:

    • Clearly separate “instructions” from “reference material” in the prompt, and use reference material only as a source of facts;
    • Allowlist executable tool calls and restrict their permissions;
    • Require user confirmation for critical actions, such as sending messages or modifying data. Do not let the model execute these actions directly.

    Allowing the service to fetch arbitrary URLs can lead to server-side request forgery (SSRF), where the server is made to access internal addresses or metadata services. Resolve the domain name before fetching, reject internal, loopback, and reserved addresses, and limit the number of redirects and the size of response bodies.

    6.4 Data and Compliance Obligations

    When providing services to external users, consider the following:

    • Complete any filing or registration required by the regulations in the jurisdictions where the service operates for generative AI services;
    • Label generated content as required by applicable rules so that users can distinguish human-created content from AI-generated content;
    • Define how long uploaded files are stored and what they are used for, and avoid logging original sensitive content;
    • Describe the scope of external capabilities and the data flows in the privacy policy.

    7. Testing and Pre-Launch Checklist

    Before launch, test each capability module separately rather than relying only on a single end-to-end demo.

    Functional correctness

    • Web Q&A: Sample answers to check whether each citation matches the claim it supports, and whether any answer cites a source that does not exist.
    • File parsing: Test text-based PDFs, scanned documents, multi-column layouts, and office documents with tables. Record the rates of parsing failures and out-of-order content.
    • Link reading: Cover both static pages and pages that depend on script rendering. Measure the fetch failure rate, and confirm that the fallback message appears correctly when a fetch fails.

    Performance and cost

    • Measure time to first token and end-to-end latency separately, and break them down by tool type to identify bottlenecks.
    • Track costs by the number of tool calls, and set usage limits per user and per day.

    Security and compliance

    • Verify that both input moderation and output moderation trigger and return refusal flags.
    • Test with web pages and files that contain prompt injection content, and confirm