A Practical Architecture for Intelligent Apps: Web Search and Document Parsing

    This article explains how intelligent applications move beyond simple Q&A by combining web search, page reading, file parsing, multi-step retrieval, and voice. It covers the tool-calling loop, build-versus-hosted trade-offs, context and cost control, security, and a staged rollout plan.

    A General Architecture for Intelligent Apps: Web Search and File Parsing in Practice

    1. From answering questions to getting work done

    Early large-language-model apps were essentially one-shot Q&A. A user typed a question, and the model generated text from knowledge learned during training. That pattern has two hard limits. First, training data has a cutoff, so the model cannot know events that happened later. Second, the model cannot see the user’s private files or read web pages.

    A mature intelligent app often looks like a single input box. Behind it, the system may run intent detection, query generation, page fetching, document parsing, result filtering, and answer generation in sequence. Those steps should be invisible to users. For developers, each step is an engineering concern that needs design, monitoring, and fallbacks.

    2. Five core capabilities

    Search supplies the model with up-to-date information. A typical flow is: the model generates search queries from the question, calls a search service, receives titles, snippets, and links, then decides which results deserve a deeper read. Engineering work includes query quality, deduplication, recency filters, and source credibility. Citing sources in the answer helps users verify claims and reduces the risk of fabricated content.

    2.2 Page reading

    Search results usually provide only snippets. Full detail requires reading the original page. A page-reading module fetches the page, strips noise such as navigation and ads, extracts the body, and compresses it to a usable length. It must handle encoding differences, dynamically rendered pages, redirects, and timeouts. If a user message already contains a URL, the system should detect and read that page automatically.

    2.3 File parsing

    Users often upload PDFs, office documents, and images. Parsing typically has two goals. One is extracting plain text, which works for simple documents. The other is preserving layout: tables, figure captions, and body text in reading order, which matters for financial reports, papers, and scans. Parse quality directly affects answer accuracy, so it is useful to keep intermediate parse artifacts for debugging.

    2.4 Multi-step reasoning and retrieval

    Hard questions often cannot be solved with a single search. The model may look up background first, then revise queries from new information, then synthesize multiple sources. The system should allow multiple tool rounds while capping the number of steps so the model does not loop uselessly.

    2.5 Voice interaction

    Voice combines speech recognition and speech synthesis. Transcripts enter the dialogue flow; answer text is synthesized and played. Latency is the key metric. Streaming text so speech can start while generation continues is usually required.

    3. The basic tool-calling loop

    Regardless of stack, most intelligent apps follow the same loop: the model decides whether it needs a tool, the tool runs, results are written back into context, and the model continues until it produces a final answer.

    1. MAX_STEPS = 6
    2. def run_agent(user_message, history, tools, llm):
    3. messages = history + [{"role": "user", "content": user_message}]
    4. for _ in range(MAX_STEPS):
    5. reply = llm.chat(messages, tools=tools)
    6. if not reply.tool_calls:
    7. return reply.text
    8. for call in reply.tool_calls:
    9. result = execute_tool(call.name, call.arguments)
    10. messages.append(tool_result_message(call.id, result))
    11. raise RuntimeError("Exceeded max reasoning steps; please narrow the question")

    The snippet omits many details but highlights three points. First, the loop must terminate, or cost and latency will explode. Second, tool results should be standardized, including errors and timeout flags, so the model can understand failures. Third, tool output should be length-limited. An untrimmed web page can consume a large share of context and crowd out other information.

    4. Build versus hosted

    For each capability, decide whether to implement it yourself or use a hosted service. Compare along these dimensions:

    Dimension Self-built Hosted
    Time to ship Slower; each integration is custom Faster; often a configuration switch
    Control High; every stage can be customized Bounded by the vendor’s capabilities
    Data compliance Data stays in your environment Requires review of transfer and retention policies
    Cost visibility You must instrument usage Usually usage-based; needs monitoring
    Replaceability Components can be swapped Migration requires rewriting adapters

    A practical rule: keep core business logic and sensitive data processing in-house; evaluate hosted options first for generic capabilities such as search, parsing, and speech. In either case, wrap external capabilities behind a single adapter layer so the application does not depend on one vendor’s API details.

    5. Context and cost control

    The context window is finite. Tool results, chat history, and system instructions all consume space. Common practices include:

    1. Rolling summaries of history, keeping only the last few turns verbatim.
    2. Chunking web and file content and selecting segments by relevance.
    3. Keeping citation metadata so sources remain traceable even if the body is truncated.
    1. def fit_budget(chunks, max_tokens, count_tokens):
    2. selected, used = [], 0
    3. for chunk in sorted(chunks, key=lambda c: c.score, reverse=True):
    4. cost = count_tokens(chunk.text)
    5. if used + cost > max_tokens:
    6. continue
    7. selected.append(chunk)
    8. used += cost
    9. return selected

    The function picks chunks by relevance score until the token budget is reached. Production systems also need original order among chunks and merging of duplicates.

    6. Security and compliance

    Intelligent apps introduce new attack surfaces.

    • Prompt injection: Web pages or files may contain text that tries to make the model take unintended actions. Treat all external content as data, not instructions, and restrict high-risk operations at the system layer.
    • SSRF: When fetching URLs automatically, validate the protocol, block private networks and loopback, and limit redirects.
    • Data isolation: Store uploaded files per user, set retention periods, and support deletion.
    • Output audit: Log tool inputs and outputs so incorrect answers can be traced later.

    7. A staged rollout

    Advance in four phases.

    Phase 1: Ship a minimal loop of chat plus a single tool, such as web search, and verify the calling loop and citation display.

    Phase 2: Add page reading and context budgeting to manage cost and quality on long text.

    Phase 3: Add file parsing and multi-step retrieval, with sampling checks on parse results.

    Phase 4: Build evaluation. Metrics should include answer accuracy, citation correctness, average latency, tool-call failure rate, and cost per request. Whenever you change models or parameters, run the same eval set so you do not judge quality by gut feel.

    The hard part of intelligent apps has shifted from “can we call a model” to “can we organize external capabilities.” Design search, reading, and parsing clearly, then add explicit boundaries and ongoing monitoring, and a simple chat UI can reliably complete complex tasks.