How to Build a Web-Connected Q&A Application with LLM APIs
This article explains how to build a production-ready, web-connected Q&A application using large language model APIs. It covers the four-layer application architecture, core capabilities such as web search, URL reading, file parsing, OCR and speech services, the token-plus-tool-call cost model, an orchestration code example, and engineering best practices for citations, timeouts, logging, context management, and compliance, ending with a practical implementation checklist.
1. Background: From Single-Turn Chat to Capability Composition
Early LLM APIs offered simple text-in, text-out interfaces. Models could only answer from training data—they couldn’t access real-time information or read user-uploaded files. As tool use and retrieval-augmented generation (RAG) matured, model APIs began integrating external capabilities into the reasoning process. Models can now decide when to search, when to read a web page, and how to incorporate retrieved results into their answers.
For developers, this means the core of an application becomes a “model plus tools” composition. A complete chat product typically consists of four layers:
- Interaction layer: message rendering, multi-turn sessions, streaming output, and file attachments;
- Orchestration layer: deciding when to call the model, when to call tools, and how to assemble context;
- Capability layer: model inference, retrieval, web scraping, file parsing, and speech/image processing;
- Governance layer: content safety moderation, access control, audit logging, and usage tracking.
Understanding the boundaries between these four layers matters more than simply calling any single API.
2. Breaking Down the Core Capabilities
2.1 Web Search
Web search lets the model access public web pages or image libraries before answering. There are typically two engineering patterns.
The first is direct retrieval in non-thinking mode. The model decides whether a search is needed, issues one or more queries if so, and generates an answer based on the results. This mode has low latency and suits time-sensitive queries—news, prices, weather, and similar scenarios.
The second is multi-step retrieval in thinking mode. During reasoning, the model can decompose the question, search multiple times, compare sources, and then synthesize an answer. It is more accurate but slower and more expensive, making it suitable for complex research or questions requiring cross-validation.
In either mode, answers should include citations. Citations let users verify information and help developers diagnose whether the model misread retrieval results.
2.2 URL Reading and Web Scraping
When a user message contains a URL, the application needs to decide whether to fetch that page. Fetched content usually requires cleaning: strip navigation, ads, and scripts; keep the main body; and control length to avoid exceeding the context window.
Web scraping also requires attention to:
- The target site’s access rules—respect robots.txt and terms of service;
- Request timeouts and retry policies, so a single slow site doesn’t stall the entire session;
- Allowlists or blocklists for sensitive targets such as internal network and loopback addresses, to prevent server-side request forgery (SSRF);
- Caching of fetched results to reduce duplicate requests and costs.
2.3 File Parsing
File input typically supports PDFs, Office documents, and images. There are two parsing approaches.
Plain text extraction suits simply structured documents—it’s fast and cheap. Layout-aware parsing preserves tables, image positions, and page structure, making it appropriate for financial reports, academic papers, and scanned documents.
Two points matter for parsed output. First, long documents should be chunked before entering the context, with page numbers or section markers preserved so the model can cite them. Second, parsing failures should be surfaced clearly to the user, rather than letting the model fabricate an answer from empty content.
2.4 OCR, Speech Recognition, and Speech Synthesis
OCR converts text in images into machine-readable text and commonly complements file parsing. Speech recognition transcribes audio into text; speech synthesis converts text back into audio. Combined, these enable interactions like “snap a photo and ask” or voice conversations.
Key metrics for these capabilities include recognition accuracy, end-to-end latency, and audio format compatibility. Test with a real sample set before launch—don’t rely on demo performance.
2.5 Safety Checks
Safety checks cover both input and output. Input checks identify policy-violating, adversarial, or injection-style content; output checks prevent the model from generating illegal or inappropriate information. When a risk is detected, the system should return a standardized refusal indicator and log the event.
Note that safety checks are only baseline risk control—they cannot replace business-level review mechanisms.
3. Cost Model: Tokens and Tool Calls Are Billed Separately
Most capability-based APIs use a “model token fees plus tool call fees” pricing structure. The former is calculated from input and output token counts; the latter from call counts, retrieval counts, page counts, audio duration, or document page counts.
Cost can be estimated with the following formula:
Total cost = input tokens × input unit price + output tokens × output unit price + Σ (tool call count × tool unit price)
Refer to the provider’s pricing page for actual rates. Before launch, run load tests with typical requests, measure the average number of tool calls per session, and then project monthly costs. Common optimization techniques include:
- Capping the maximum number of retrievals per session;
- Caching results for high-frequency questions;
- Gating deep retrieval capabilities by user tier;
- Summarizing or filtering long documents into chunks before sending them to the model.
4. Architecture Sketch of a Generic Chat Application
The following code illustrates the orchestration logic. Tool names and parameters are illustrative—refer to your platform’s documentation for specifics.
def handle_message(user_msg, history, options):tools = []if options.get("web_search"):tools.append(web_search_tool) # web search toolif options.get("read_url") and contains_url(user_msg):tools.append(read_url_tool) # URL reading toolmessages = build_context(history, user_msg, max_tokens=8000)if options.get("safety_check"):verdict = moderate_input(user_msg)if verdict.blocked:return {"refused": True, "reason": verdict.code}response = llm_client.chat(messages=messages, tools=tools, stream=True)for chunk in response:if chunk.is_tool_call:result = run_tool(chunk.name, chunk.arguments) # execute tool and feed result backresponse = llm_client.continue_with(result)yield chunk.textlog_usage(user_id=options["user_id"], tokens=response.usage, tools=response.tool_calls)
Three points stand out in this structure. First, tools are registered on demand to avoid adding irrelevant capabilities that inflate context and cost. Second, input passes safety checks before reaching the model. Third, every call logs usage, which supports billing and auditing later.
5. Engineering Best Practices
5.1 Citations and Trustworthiness
Require the model to cite sources in its answers and display source links in the frontend. When retrieval results are insufficient, guide the model to state “unable to confirm” rather than fabricate an answer. The backend can validate citation links and filter out dead URLs.
5.2 Timeouts, Retries, and Degradation
Tool calls may fail or time out. Set an independent timeout for each tool and use exponential backoff for retries. If retrieval fails, the system can fall back to answering from the model’s own knowledge while informing the user that the result was not verified against real-time sources.
5.3 Logging and Privacy
Logs should not record complete sensitive user information. Mask fields such as phone numbers, ID numbers, and bank card numbers; retain only necessary metadata for attachments. Set retention periods for access logs and restrict internal staff access to them.
5.4 Context Management
Long sessions exhaust the context window quickly. A common approach is to keep the most recent turns verbatim and compress earlier content into summaries. File content should be retrieved on demand rather than sent in full every turn.
6. Compliance and Safety Obligations
When offering generative AI services to external users, you must fulfill applicable legal obligations. These typically include:
- Enabling and continuously maintaining content safety moderation for both input and output;
- Completing any required registration or filing of the model or service under local regulations;
- Labeling AI-generated text, images, and audio so users can identify them;
- Publishing clear terms of service and a privacy policy explaining data collection, use, and retention periods;
- Establishing channels for complaints and reports, and handling violating content promptly.
Compliance work should be incorporated during product design, not patched in right before launch.
7. Implementation Checklist
When building a similar application, proceed in this order:
- Define the business scenario and determine which questions require real-time information versus the model’s own knowledge;
- Select the necessary capability set—start with web search and file parsing;
- Implement the orchestration layer, making tool registration, safety checks, and usage logging independent modules;
- Test accuracy, latency, and cost with a real sample set, and set default parameters;
- Complete safety and compliance configuration before opening to external users;
- After launch, continuously monitor call volume, failure rates, and user feedback, and iterate.
Finally, a usable chat interface is only part of the product. Session management, permission systems, operational tooling, and reliability engineering equally determine whether the product can run long term. API capabilities provide the intelligence; a complete product still demands solid engineering investment.
