LLM API-Powered Intelligent Applications with Web Retrieval: Architecture, Orchestration, and Security
This article explains how to use LLM APIs to build an intelligent assistant that can search the web, read web pages, and parse uploaded files. It walks through the end-to-end question-answering flow, the main engineering challenges, a layered architecture, a controlled tool-calling loop, citation and file-handling practices, security controls, and a systematic testing approach.
1. From a Chat Box to an Intelligent Assistant
Early LLM applications were mostly single-turn or multi-turn text conversations, and the model answered only from its training data. As user expectations have risen, more products have placed web retrieval, file understanding, and web page reading into the same chat interface. Users only need to enter a request, and the system automatically decides when to search, when to read materials, and how to organize the results into an answer.
This experience looks simple, but behind it is a long tool-calling chain. For developers, understanding this chain is key to judging whether they can build a similar application themselves.
2. A Complete Question-Answering Execution Process
Take “compare the conclusions of two technical reports” as an example. The system usually goes through the following steps:
- Parse the user message and identify whether it contains web links or attachments.
- The model decides whether external information is needed. If so, it generates search terms and calls the search tool.
- It reads candidate pages from the search results, extracts the main text, and removes noise such as navigation and ads.
- It combines the newly obtained materials with the conversation history and sends them back to the model for further reasoning.
- The model outputs an answer with cited sources.
Each step can fail. Search results may be empty, pages may require login, and file parsing may produce garbled text. A mature system needs fallback strategies for each step to avoid interrupting the entire answer.
3. Main Challenges for Developers
- High tool integration cost: Search, web scraping, and document parsing usually come from different services, with different interface formats, authentication methods, and rate-limit rules.
- Difficult call-order control: In multi-step reasoning, the model may repeatedly search for the same question or give a conclusion too early when materials are insufficient.
- Context expansion: Web page text and document content are long. Direct concatenation can exceed the context window and dilute key information.
- Inconsistent source credibility: Web page quality varies, and some pages may contain text that tries to change model behavior.
- Compliance and security: Both user input and model output need basic risk review. When a risk is detected, there must be clear refusal and logging mechanisms.
4. Layered Architecture Design
It is recommended to split the system into five layers, each with a single responsibility, making replacement and testing easier.
- Model layer: Wraps the chat completion API and handles timeouts, retries, and model switching in a unified way.
- Tool layer: Each tool provides a unified parameter description and return structure, such as search, web page reading, and file parsing.
- Orchestration layer: Controls the reasoning loop, maximum steps, tool call order, and context management.
- Safety layer: Validates and filters input, tool return content, and final output.
- Application layer: Handles session storage, history import, interface display, and citation rendering.
The benefit of this division is that when replacing the retrieval service, only the tool layer implementation needs to change, while the orchestration logic and interface remain unchanged.
5. Implementation Points for the Orchestration Loop
The core is a controlled loop. The model decides whether to call a tool, and tool results are written back into the message list until the model gives a final answer or the step limit is reached.
def run_assistant(user_query, history, llm, tools, max_steps=6):messages = history + [{"role": "user", "content": user_query}]for _ in range(max_steps):reply = llm.chat(messages=messages, tools=tools.schemas())if not reply.tool_calls:return reply.contentmessages.append(reply.as_message())for call in reply.tool_calls:output = tools.execute(call.name, call.arguments)messages.append({"role": "tool","tool_call_id": call.id,"content": truncate(output, max_chars=4000),})raise RuntimeError("Reasoning steps exceeded the limit; please narrow the question scope")
There are three points to note during implementation. First, a step limit must be set; otherwise, the model may fall into repeated searching. Second, tool return content needs to be truncated or summarized to avoid a single result filling the context. Third, exceptions should be converted into structured error information and returned to the model, so the model has a chance to continue in another way.
6. Web Retrieval and Citations
Retrieval capability is usually provided as a tool. The model generates search terms based on the question, and the system returns fields such as title, link, snippet, and publication time. Developers can refer to the following design:
- Search only when the model determines it is truly necessary, avoiding wasted calls on common-knowledge questions.
- Save the link, title, fetch time, and original text snippet for each result so that every claim in the answer can be traced back to a source.
- Deduplicate the same source and prioritize authoritative sites and more recent content.
Citation format should remain consistent, for example, by marking a number at the end of a paragraph and listing sources at the end of the article. Readers can use this to verify information, and the team can audit the quality of model output.
7. File Parsing Strategies
Users upload many types of files, including text documents, spreadsheets, presentations, and scanned images. Parsing usually falls into two categories:
- Plain text extraction: Suitable for well-structured electronic documents, with fast speed and low cost.
- Mixed text-and-image parsing: Suitable for documents containing charts, formulas, or scans, and requires preserving layout structure and image descriptions.
Parsing results should be split by section, and page or position information should be recorded for each chunk. When answering, the model can cite specific paragraphs instead of restating the entire file. For large files, it is recommended to parse asynchronously in the background and show progress in the front end to avoid long-blocking requests.
8. Web Page Reading and Link Detection
When a user message contains a link, the system needs to identify the link first and then fetch the page content. This step carries obvious security risks, and the following principles should be followed in the design:
- Validate the protocol and domain, allowing only HTTP and HTTPS.
- After resolving the domain, check the IP address and reject access to internal addresses and local loopback addresses to prevent server-side request forgery.
- Set timeouts and response body size limits to prevent malicious pages from consuming resources.
- When extracting the main text, remove scripts, styles, and navigation areas, keeping only text relevant to the question.
Fetched page content is data and should not be executed as instructions. Even if a page contains text such as “ignore previous requirements,” the system should treat it as ordinary text and mark it in the prompt as untrusted external content.
9. Content Safety Checks
Safety checks can be placed in two locations: before user input enters the model, and before model output is returned to the user. The basic flow is as follows:
- Classify input risk. When a high-risk category is detected, directly return a refusal message.
- Apply the same check to model output to avoid generating prohibited content.
- When a risk is detected, record the request identifier, detected category, and time for later auditing.
Validation rules should be tied to business policy. An education product and a developer-facing tool may handle the same type of content differently. Rules need to be regularly tested against real samples to control false-positive rates.
10. Testing and Evaluation
Testing an intelligent assistant cannot rely only on whether a single answer is correct. It also needs to cover the following dimensions:
- Whether tool calls are triggered in the correct scenarios, including searching when search is needed and not searching when a direct answer is sufficient.
- Whether cited sources actually exist and are consistent with the answer content.
- Whether the system can give a reasonable response to exceptions such as empty results, timeouts, and garbled files.
- Whether the system can continue to follow its original instructions when facing malicious web pages and injected text.
It is recommended to build a fixed evaluation set, run regression tests whenever the model or tools are changed, and record latency, call counts, and success rate. These metrics can help the team determine whether an optimization is truly effective.
11. Conclusion
The core of building an intelligent application with search, reading, and file-understanding capabilities is to make the model’s reasoning ability work stably with external tools. Developers need to focus on the controllability of the orchestration loop, context conciseness, source traceability, and the definition of security boundaries. By implementing the layered architecture step by step and iterating continuously through systematic testing, teams can build a usable intelligent assistant with a relatively low trial-and-error cost.
