Building AI Applications with Web Search and File Parsing

    This article explains how to build AI applications that search the web, parse uploaded files, and read web pages. It covers why a plain model API is not enough, the four layers of an AI application, the core capabilities of web search, file parsing, and web reading, a sample tool-calling loop, context and cost control, security and compliance, quality evaluation, and rollout recommendations.

    1. Background: From Chatting to Getting Things Done

    Over the past few years, the way people use large language models has changed. Early products mainly offered question answering, where the model relied only on what it learned during training. As requirements grew, users wanted models to look up current information, read uploaded materials, open links to verify details, and provide conclusions with sources. This capability is usually called “tool augmentation.” In essence, the model calls external capabilities on demand while generating a response, then integrates the results into its reasoning.

    For developers, the challenge is not calling the model once. The challenge is keeping the whole pipeline stable. Questions include where search results come from, how web pages are fetched, how PDFs and images are converted to text, how context is assembled across multiple tool calls, and how failures are handled.

    2. Why a Model API Alone Is Not Enough

    Connecting only to a model API usually raises four problems.

    1. Knowledge freshness: Model training data has a cutoff date. Questions about recent events, prices, or policies require real-time retrieval.
    2. Unstructured input: Uploaded PDFs, scanned documents, and slide decks contain tables, formulas, and images. Passing a file directly as a string loses its layout.
    3. External page retrieval: User messages often include URLs. The system must fetch each page, remove navigation and ads, extract the main text, and handle timeouts, redirects, and access restrictions.
    4. State management in multistep reasoning: The model may search first, read two articles, find conflicting information, and then search again. The result of each step must be added back to the context in the correct order.

    These problems are engineering problems, and they are largely independent of the model’s own capabilities. Handing them to a shared server-side capability reduces the cost of rebuilding the same infrastructure for each application.

    3. Capability Layers: Model, Tools, and Orchestration

    A complete AI application usually has four layers.

    • Model layer: Understands user intent, plans steps, and generates the final answer.
    • Tool layer: Provides search, parsing, fetching, and similar capabilities. Each tool needs clear input and output definitions.
    • Orchestration layer: Decides when to call which tool, writes tool results back into the context, and limits the number of loops.
    • Interaction layer: Handles the user interface, streaming output, citation cards, and conversation history.

    Developers can build the tool layer themselves or use managed capabilities from a provider. The two approaches differ as follows.

    Dimension Self-built tools Managed tools
    Integration cost Search, parsing, and fetching services must each be integrated separately Enabled through parameters or declarative configuration
    Data path Fully controlled by the developer Compliance requirements must be assessed when data passes through a third party
    Customization High. Data sources and algorithms can be chosen freely Limited by the provider’s service scope
    Operational burden Dependencies, quotas, and failover must be maintained Infrastructure operations are handled by the provider

    When choosing between them, prioritize data compliance, latency requirements, and depth of customization, not only integration speed.

    4. Core Capabilities

    The key to web search is the trigger strategy. A model does not need to search for every request. For common-knowledge questions, searching only adds latency and cost. Good practices include:

    • Describing applicable scenarios in the tool description, for example, “call this tool when the question involves recent information or requires source evidence”;
    • Requiring the model, in the system prompt, to cite sources for factual claims;
    • Deduplicating results, filtering by recency, and scoring domain credibility.

    Citations in an answer should include the title, source site, and access time so users can verify them.

    4.2 File Parsing

    File parsing falls into two types. Plain text extraction suits text-heavy documents such as contracts and reports. It is fast and inexpensive. Layout parsing preserves heading hierarchy, table structure, and image positions. It suits financial statements, academic papers, and scanned documents. Developers should choose a parsing mode based on the document type, and limit file size and page count before upload to avoid timeouts.

    4.3 Web Reading

    Web reading typically includes these steps: identify URLs in the message, validate the protocol and domain, fetch the HTML, extract the main text, truncate overly long content, and submit the result to the model along with the conversation context. The quality of text extraction directly determines answer accuracy. Save the original URL and the fetch time so that every conclusion can be traced back to its source.

    4.4 Retrieval Loops in Multistep Reasoning

    When deep reasoning is enabled, the model may run several rounds of “search, read, and reason again.” The orchestration layer needs a maximum number of rounds, a timeout for each round, and a total token budget to prevent runaway loops.

    5. Sample Implementation: A Tool-Calling Loop

    The pseudocode below shows a general tool-calling loop. It does not depend on any specific platform. It only describes the control logic.

    1. messages = [user_input]
    2. tools = [search_web, read_url, parse_file]
    3. for step in range(MAX_STEPS):
    4. response = model.generate(messages, tools=tools)
    5. if response.has_no_tool_calls():
    6. return response.text # The model has produced the final answer
    7. for call in response.tool_calls:
    8. check_permission(call.name, call.arguments)
    9. result = run_tool(call.name, call.arguments, timeout=TIMEOUT)
    10. messages.append(tool_result(call.id, truncate(result)))
    11. raise MaxStepsExceeded()

    Three points matter in this implementation. First, validate all tool arguments. Never trust a URL or file path generated by the model without checking it. Second, truncate tool results and label each one with its source. Third, the loop needs a clear termination condition.

    6. Context Management and Cost Control

    Tool results are often large. A long web page or a multi-page PDF can consume tens of thousands of tokens. If all of them stay in context, latency and cost rise noticeably. Common practices include:

    1. Summarizing tool results and keeping only the paragraphs relevant to the question;
    2. Clearing older intermediate results in chronological order while keeping citation metadata;
    3. Setting a budget cap for each session, and asking the user to narrow the question when the cap is reached;
    4. Caching repeated queries so the same URL is not fetched again within its validity period.

    7. Security and Compliance

    Introducing external content increases security risk.

    • Prompt injection: Web pages or files may contain embedded instructions that try to make the model leak information or perform unauthorized actions. Treat tool output as data, not as instructions, and restrict which actions the system can execute.
    • Source policies: Set allowlists or blocklists for fetch targets, and filter out non-compliant content and low-credibility sources.
    • User privacy: Define how long uploaded files are stored, let users delete them, and keep sensitive information out of logs.
    • Copyright: When quoting content, keep the source attribution, limit the length of excerpts, and do not use excerpts as a substitute for the original work.

    8. Quality Evaluation and Fallbacks

    Building an evaluation set is essential. Draw 100 to several hundred samples from real user questions, covering questions that need no retrieval, questions that need retrieval, questions that require file parsing, and questions that include URLs. Track citation accuracy, factual accuracy, average latency, cost per request, and failure rate.

    Plan fallback strategies for failure cases as well. When a search returns no results, tell the user clearly. When a page fails to load, ask the user to paste the text directly. When parsing fails, fall back to plain text extraction.

    9. Rollout Recommendations

    1. Start with a minimal working loop. Implement one tool first, such as web search, and verify citation quality before adding file parsing and web reading.
    2. Keep prompts, tool descriptions, and the evaluation set under version control so that every change can be compared.
    3. Record structured logs for each tool call, and redact user content.
    4. Review failure samples regularly. Separate model issues, tool issues, and orchestration issues, and optimize each one on its own.

    The reliability of an AI application depends on how completely its engineering details are handled.