Engineering Practices for Integrating Web Search, Web Page Reading, and File Parsing into LLM APIs
This article covers the engineering practices for adding external capabilities—web search, web page reading, file parsing, and content safety—to LLM-powered conversational applications. It explains how to let the model decide when to search, how to fetch and extract web content safely (including SSRF prevention), how to parse different file types, how to manage multi-step tool-call loops, and what to check before going live.
1. Why Conversational Applications Need External Capabilities
An LLM’s training data has a cutoff date, and the model cannot directly read a user’s private files or live web pages. To give timely, verifiable answers, developers must bring retrieval, reading, and parsing capabilities into the model’s context. A common industry pattern is: the model understands user intent and composes the answer, while external tools supply the factual material, connected through a structured tool-calling protocol.
Separating these capabilities makes the system design clearer. This article covers four areas—web search, web page reading, file parsing, and content safety—and explains the engineering essentials and common pitfalls of each.
2. Web Search: Letting the Model Decide When to Search
A typical web search flow has five steps:
- The application sends the user’s question together with descriptions of the available tools to the model;
- The model determines whether the question depends on up-to-date information and, if so, generates search keywords;
- The server executes the search and returns structured results such as titles, snippets, and links;
- The results are appended to the context, and the model composes an answer based on them;
- Source citations are preserved in the answer so users can verify it.
The key decision point is “whether to search.” Developers usually constrain the model’s behavior through tool descriptions—for example, specifying which kinds of questions require retrieval and the maximum number of results per call. Note that search results come from external web pages and may be inaccurate or contain misleading text. The system should treat retrieval results as material to be verified, not as instructions to execute. For numbers, dates, and conclusions in the answer, display source links in the frontend and add secondary verification where necessary.
3. Web Page Reading: Safe Fetching and Content Extraction
User messages often include web links. The application must do three things: identify the link, fetch the content safely, and extract the main text. Safety is the most easily overlooked part. If the server accesses user-supplied URLs without restrictions, attackers can use this to probe internal network services—a risk commonly known as Server-Side Request Forgery (SSRF).
The following example shows the basic idea of protocol and address validation:
import ipaddressimport socketfrom urllib.parse import urlparsedef is_safe_url(url: str) -> bool:parsed = urlparse(url)if parsed.scheme not in ("http", "https") or not parsed.hostname:return Falsetry:infos = socket.getaddrinfo(parsed.hostname, None)except socket.gaierror:return Falsefor info in infos:ip = ipaddress.ip_address(info[4][0])if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:return Falsereturn True
This code is only the first layer of defense. When making the actual request, you should pin the already-resolved IP address to avoid DNS rebinding attacks, where validation resolves to a public address but the real connection is switched to an internal one. You should also set timeouts, a maximum response size, and a limit on redirect counts.
Content extraction also requires engineering work. Navigation bars, ads, scripts, and stylesheets consume large numbers of tokens while carrying almost no useful information. A common approach is to first apply a main-content extraction algorithm, then convert the result to Markdown or plain text. If the page is too long, truncate it according to the token budget, or generate section-level summaries before passing them to the model.
4. File Parsing: Choosing a Processing Path by File Type
Users upload files in many formats, each requiring different handling. The table below shows recommended processing paths for common formats:
| File type | Recommended approach | Key considerations |
|---|---|---|
| PDF with a text layer | Extract text directly, preserving page numbers and heading hierarchy | Multi-column layouts can scramble reading order |
| Scanned PDFs and images | OCR, or have a vision model generate descriptions | Recognition errors directly affect answers; prompt users to verify |
| Office documents | Convert based on paragraph, heading, and table structure | Convert tables into a readable format to preserve row-column relationships |
| Documents with mixed text and images | Separate text and images, then reorganize by position | Keep image captions aligned with the corresponding body text |
Once file content is added to the context, it consumes a large number of tokens. When a document exceeds the model’s context limit, a common solution is to split the text into chunks, then use vector or keyword retrieval to find the segments relevant to the question, placing only those segments in the prompt. This approach is commonly known as Retrieval-Augmented Generation (RAG).
Chunking strategy also affects quality. Chunks that are too small lose context; chunks that are too large introduce irrelevant information. In practice, splitting at heading or paragraph boundaries works well, and each chunk should retain its section and page number so the model can provide locatable citations in its answers.
5. The Tool-Calling Loop in Multi-Step Reasoning
In reasoning modes or complex tasks, the model may need to call tools multiple times: search first, then read a specific web page, and finally answer based on both. The application must maintain a tool-calling loop until the model no longer requests tools.
def run_agent(client, messages, tools, max_steps=5):for _ in range(max_steps):reply = client.chat(messages=messages, tools=tools)if not reply.tool_calls:return reply.textfor call in reply.tool_calls:result = execute_tool(call.name, call.arguments)messages.append({"role": "tool","tool_call_id": call.id,"content": result,})raise RuntimeError("Tool call step limit exceeded")
The loop needs several constraints. A step limit prevents the model from falling into repeated calls; a per-call timeout prevents external services from slowing down the overall response; and token consumption per round should be tracked cumulatively for cost control. Content returned by tools should be truncated in length and labeled as external data, so the model does not treat text within it as system instructions.
6. Content Safety and Compliance Obligations
Content safety is a fundamental requirement when offering services to the public. The usual approach is bidirectional moderation of inputs and outputs: input moderation blocks clearly non-compliant questions, and output moderation prevents the model from generating inappropriate content. If the platform provides safety-check parameters, enable them directly; otherwise, integrate an independent content moderation service.
When a risk is detected, the application should return a standardized refusal message without exposing specific moderation rules, which could otherwise be used to repeatedly probe the boundaries. Blocked requests should also be logged to facilitate later analysis of false-positive rates.
On the compliance side, jurisdictions generally impose obligations on generative AI services offered to the public, such as content safety review, service registration, and labeling of AI-generated content. The specific requirements depend on the latest regulations of the relevant authorities in your target market, and each item should be confirmed by legal or compliance staff before launch.
Privacy protection matters as well. Conversation records and uploaded files should be retained on a minimal basis with clearly defined retention periods, and deleted data should be purged accordingly. Logs should never contain plaintext API keys or complete personally sensitive information.
7. Pre-Launch Checklist
Before going live, verify the following items one by one:
- Tool calling: step limits, per-call timeouts, and failure retry policies are in place;
- Web page reading: protocols are restricted, internal addresses are blocked, and redirect and size limits are configured;
- File parsing: OCR accuracy for scanned documents has been validated, and chunked retrieval is implemented for over-long documents;
- Source display: key conclusions in answers can be traced back to specific sources;
- Safety moderation: both inputs and outputs are moderated, and refusal messages are standardized without revealing rules;
- Compliance materials: registration, content labeling, and moderation workflows have been confirmed;
- Key management: API keys are stored in environment variables or a key management service, never committed to code repositories;
- Cost monitoring: token consumption is tracked per user and per feature, with usage alerts configured.
After completing these checks, the application can gradually expand its rollout to a controlled group of users, and you can adjust tool descriptions, chunking strategies, and safety thresholds based on monitoring data.
