Building a Web-Connected Q&A Application with LLM APIs
Learn how to combine LLM APIs with web search, URL reading, document parsing, and safety checks to build a web-connected Q&A application. This guide covers tool orchestration, a layered reference architecture, citation handling, file processing, and practical controls for cost, latency, traceability, and compliance.
1. Beyond the Model: What an Application Needs
A large language model on its own generates text from its training data. When users ask for current information, upload contracts or reports, or provide web links, the model needs external tools to produce reliable answers.
Traditionally, developers had to integrate search, web scraping, document parsing, and speech processing separately. Each component came with its own integration requirements, timeout policies, and billing rules, increasing maintenance overhead. A more recent approach is for model services to expose these capabilities through standardized parameters or tools. Developers enable the relevant capabilities, and the model decides when to use them.
The central challenge is therefore shifting from whether a capability can be integrated to three practical questions:
- How should the capabilities be combined?
- How can costs be controlled?
- How can outputs remain traceable and meet compliance requirements?
2. Five Core Capabilities and Their Design Considerations
2.1 Web Search
In non-reasoning mode, the model determines whether a user’s question requires retrieval. If it does, the model performs a web or image search and includes source citations in its answer.
Key design considerations:
- Keep citations consistent. Citation numbers in the answer must correspond to entries in the source list so users can verify claims.
- Preserve publication dates. For time-sensitive topics such as news, policies, and prices, the interface should show the time period covered by the information.
- Require retrieval when freshness matters. For questions that explicitly require current information, system instructions can require a search rather than allowing the model to answer from memory.
2.2 Multi-Step Retrieval in Reasoning Mode
In reasoning mode, a model can search and read links across multiple steps before synthesizing an answer. This approach suits complex tasks, such as comparing public financial reports from several companies or tracing revisions to a policy.
Key design considerations:
- Limit retrieval rounds per request. Repeated searches can cause latency and costs to grow without producing a better answer.
- Log the retrieval path. Record search queries, returned pages, and page-reading durations to help diagnose incorrect answers.
- Set an overall request timeout. If the request times out, return the findings already available and clearly state that the information is incomplete.
2.3 File Input
File input can support PDFs, Office documents, and images. Processing may involve plain-text extraction or layout-aware parsing that handles text and visual elements together.
Plain-text extraction works well for documents dominated by structured text. Layout-aware parsing is more suitable for scanned documents, reports with charts, and table-heavy materials.
Key design considerations:
- Choose parsing methods by file type. Do not apply the most resource-intensive parsing method to every file.
- Manage long parsing results. Split or truncate extracted content before adding it to the model context. Preserve source page numbers for citations.
- Set file limits. Define maximum file sizes and page counts, and explain limit violations in the interface.
2.4 URL Reading
When URL reading is enabled, the model can identify web addresses in user messages, retrieve page content, and use it alongside the conversation context.
Key design considerations:
- Retrieve only publicly accessible pages. If a page requires authentication or payment, explain the restriction rather than attempting to bypass it.
- Respect crawling restrictions. Follow the target site’s robots.txt directives and rate limits, and enforce a delay between requests to the same domain.
- Treat page content as untrusted input. Instructions embedded in a page, such as “ignore previous instructions,” must be treated as ordinary text and must not change system behavior.
2.5 Safety Checks
When a service’s safety-check parameter is enabled, the service performs basic screening of inputs and outputs. If a risk is detected, the API returns a refusal indicator.
Key design considerations:
- Handle refusals explicitly. The interface should recognize refusal indicators and display a consistent, user-friendly message rather than a blank response or raw error code.
- Review flagged events. Log safety triggers and periodically review samples to refine application-level keyword filters and rules.
- Retain application-level moderation. Provider-side safety checks are a baseline safeguard, not a replacement for the application operator’s own content moderation responsibilities.
3. Combining Integrated Capabilities and Standalone Tools
Applications do not have to enable every capability through a single conversation API. They can also call search, web retrieval, OCR, speech recognition, and speech synthesis as standalone tools.
The two approaches involve different trade-offs:
| Approach | Advantages | Limitations | Suitable use cases |
|---|---|---|---|
| Integrated capabilities | Faster integration and less configuration | Less control over intermediate steps | General-purpose Q&A and assistant applications |
| Standalone tools | Customizable workflows and easier auditing | Higher development and maintenance overhead | Fixed workflows such as receipt processing and compliance reviews |
Common combinations include:
- Voice Q&A: Convert speech to text, send the text to the model—with web search if needed—and convert the response back to speech.
- Document Q&A: Parse files, split the extracted text into chunks, retrieve relevant chunks using vector or keyword search, and have the model answer from those passages.
- Web page summarization: Retrieve a URL, clean the page content, remove navigation and advertising, and generate a summary.
- Structured receipt extraction: Extract text with OCR, use the model to map it to structured fields, and validate the results against business rules.
4. Reference Architecture
A layered architecture separates responsibilities and makes individual components easier to replace or extend:
[Client: Web / Mobile / Mini App]|[Access Layer: Authentication, Rate Limiting, Request Logs]|[Orchestration Layer: Session Management, Tool Routing,Timeouts and Retries]|+------------+-------------+-------------+-------------+| | | | |[Model API] [Search Tools] [Web Retrieval] [File Parsing/OCR] [Speech I/O]|[Safety and Compliance Layer: Input/Output Screening,Refusal Handling, AI Content Labeling]|[Storage Layer: Conversation History, File Cache, Usage Statistics]
The orchestration layer is the core of this architecture. It determines whether to enable tools for a request, the order in which tools are called, the fallback path after a failure, and how the final response is assembled.
Centralizing these decisions prevents workflow logic from becoming scattered across the application. It also provides a single place to update integrations when changing models or tools.
5. Key Implementation Steps
5.1 Configure Tool Parameters
The following example illustrates the configuration approach. It is not a provider-specific API contract; consult the relevant API documentation for actual parameter names and supported values.
# Illustrative code: demonstrates the configuration approach onlyrequest = {"model": "<model-name>","messages": messages, # Conversation history maintained by orchestration"thinking": {"enabled": False}, # Whether to enable reasoning mode"tools": [{"type": "web_search"}, # Web search{"type": "url_reader"}, # URL reading],"safety_check": True, # Input/output safety screening}
Two principles are important here.
First, enable only the tools a workflow actually needs. Unnecessary tool calls add cost and latency.
Second, make tool configuration a scenario-based policy. For example, ordinary Q&A can run with reasoning mode disabled, while complex analysis can enable it.
5.2 Parse and Display Source Citations
Citations are essential to making answers verifiable. The orchestration layer should map citation numbers in the model’s response to the corresponding source entries and render them consistently.
def render_answer(answer_text: str, citations: list[dict]) -> str:"""Combine the answer and its sources into user-readable text."""if not citations:return answer_textlines = [answer_text, "", "Sources:"]for idx, item in enumerate(citations, start=1):title = item.get("title", "Untitled page")url = item.get("url", "")lines.append(f"[{idx}] {title} {url}")return "\n".join(lines)
This simple renderer assumes that the source list is already ordered to match the citation numbers in the answer.
The interface should also display each source’s publication date. If a source predates the period relevant to the question, show a warning so users can assess whether the information is sufficiently current.
5.3 Process Uploaded Files
A practical file-processing workflow has four stages: validation, parsing, chunking, and storage.
from dataclasses import dataclassMAX_FILE_MB = 20 # Application-defined file size limitMAX_CHUNK_CHARS = 2000 # Maximum characters per chunk@dataclassclass Chunk:text: strpage: int # Preserve page numbers for later citationsdef validate_file(size_mb: float, file_type: str) -> None:if size_mb > MAX_FILE_MB:raise ValueError(f"File exceeds the {MAX_FILE_MB} MB limit")if file_type not in {"pdf", "docx", "pptx", "png", "jpg"}:raise ValueError("This file type is not currently supported")def split_into_chunks(pages: list[str]) -> list[Chunk]:chunks = []for page_no, page_text in enumerate(pages, start=1):for start in range(0, len(page_text), MAX_CHUNK_CHARS):chunks.append(Chunk(page_text[start:start + MAX_CHUNK_CHARS], page_no))return chunks
Scanned documents and images require OCR before text processing. When recognition confidence is low, prompt users to verify the extracted content.
5.4 Identify Links in User Messages
Link detection should take place in the orchestration layer so the application can decide whether to trigger web retrieval. A regular expression can identify common HTTP and HTTPS addresses in user messages.
