LLM API Tool Integration in Practice: Building a Web-Connected Conversational App

    This article explains how to integrate multiple tool APIs into an LLM-powered conversational application. It covers web search, web page reading, file parsing, speech processing, and content safety, along with system architecture, implementation steps, cost and latency control, security and compliance considerations, common troubleshooting scenarios, and a staged rollout plan.

    From Single-Turn Q&A to a Complete Application

    Large language models can only answer from training data. They cannot access live information, private user files, or arbitrary web pages. Early implementations often required developers to manually gather search results, parse documents, transcribe audio, and pack all that material into prompts. This approach was expensive to build and difficult to maintain.

    The mainstream approach today is tool use, also called function calling. The developer declares available tools to the model. The model decides whether to call a tool, which tool to call, and what arguments to pass. The application layer executes the tool and returns the result to the model, which then produces the final answer. This mechanism lets the model search, read, reason, and respond within the same conversation.

    Common Capabilities

    Web search gives the model access to recent information. Two scenarios are common. In direct retrieval, the model decides that real-time data is needed, performs a single search, and includes references in its answer. In multi-step retrieval, the model searches repeatedly during reasoning, compares results, and fills missing information. Multi-step retrieval has higher latency and is better for complex questions; direct retrieval suits factual Q&A.

    Web Page Reading

    User messages often contain links. The application must detect the links, fetch the page content, remove navigation bars, ads, and scripts, truncate the text to a reasonable length, and pass it to the model. Fetching should handle timeouts, redirects, encoding errors, and pages that cannot be parsed because they depend on dynamic rendering.

    File Parsing

    File parsing covers PDFs, office documents, and images. Plain text extraction works for text-based documents and is fast and low-cost. Layout parsing is useful for documents with tables, charts, or mixed text and images because it preserves structural information. Scanned documents and photos need optical character recognition (OCR) before text can be extracted.

    Speech

    Speech recognition converts user audio into text, and speech synthesis converts the answer back into audio. They can be used independently or combined into a speech dialogue loop. Real-time speech is latency-sensitive, so streaming processing should be used instead of waiting for the entire audio segment to finish.

    Content Safety

    Content safety checks model input and output for basic risk. When a risk is detected, the application should return a uniform refusal message and log the event for later auditing.

    System Architecture

    A maintainable conversational application usually contains these layers:

    • Frontend: collects user input, files, and audio; displays streaming output and citations.
    • Application service layer: manages session state, permissions, rate limits, and logs.
    • Model interface layer: wraps model calls and handles retries and timeouts.
    • Tool execution layer: implements search, web page reading, file parsing, speech processing, and other tools, with unified argument validation.
    • External resources: search services, object storage, message queues, and other common infrastructure.

    The core logic is a loop: the model returns a tool-call request, the application executes the tool, the result is appended to the conversation context, and this repeats until the model gives a final answer.

    1. def chat_turn(messages, tools, max_rounds=5):
    2. for _ in range(max_rounds):
    3. resp = model.create(messages=messages, tools=tools)
    4. if not resp.tool_calls:
    5. return resp.text
    6. for call in resp.tool_calls:
    7. result = run_tool(call.name, call.arguments)
    8. messages.append(tool_result_message(call.id, truncate(result)))
    9. return "The request exceeded the tool-call limit. Please narrow the scope and retry."

    The max_rounds limit prevents invalid tool-call loops. The truncate step controls context length so cost and latency do not grow out of control.

    Implementation Steps

    1. Define the feature boundary. List the capabilities the application needs, such as web Q&A only, or also file analysis and voice input. More features mean a larger security surface and higher cost.

    2. Define tool descriptions. Each tool needs a name, a purpose description, and a parameter structure. Be specific. For example, state that the tool is for retrieving recent information, not for general knowledge questions. Vague descriptions can cause the model to call the wrong tool.

    3. Add execution-layer protections:

      • Set a timeout and maximum retry count for each tool.
      • Block internal and local addresses in web page reading to prevent server-side request forgery.
      • Limit bytes fetched per request and file size.
      • Apply rate limiting and caching to external calls, reusing results for identical queries within a short window.
    4. Manage context. Web page content and document text can be long. Summarize the content or keep only the paragraphs relevant to the question. Preserve metadata about sources so citations can be shown in the answer.

    5. Design citation display. Factual statements in the answer should correspond to source links, and the frontend should let users view the original source. This reduces misunderstanding about model output.

    6. Build a test set. Cover pure knowledge questions, questions requiring real-time information, messages with links, scanned files and tabular documents, very long web pages, malicious web content, and noisy voice samples. After changing tool descriptions or prompts, replay the test set and compare the results.

    Cost and Performance

    Cost in a tool-enabled application usually comes from two sources: token consumption for model calls and per-call charges from tool invocations. Track them separately, otherwise it is difficult to identify where cost is coming from.

    Common ways to reduce cost include:

    • Enable tools only when needed instead of running a search for every question.
    • Limit the truncation length for web page text and file content.
    • Cache parsing results for popular queries and duplicate files.
    • Send simple tasks to a lighter model and reserve stronger models for complex reasoning.

    For performance, multi-step retrieval can significantly increase latency. Set a total time budget. If the budget is exceeded, return the available results and note that the information may be incomplete. Streaming output improves the user’s waiting experience.

    Security and Compliance

    For applications exposed to external users, security and compliance should be prerequisites for launch.

    1. Content safety: enable input and output moderation, log hits, and use a consistent refusal message.
    2. Prompt injection protection: web content, files, and speech transcripts are untrusted data. Treat them as material, not as instructions. For example, if a web page contains text like “ignore previous instructions,” the model should not follow it.
    3. Data privacy: define how long user-uploaded files are retained, provide a deletion mechanism, and redact personal information from logs.
    4. Compliance obligations: follow local regulations and confirm whether model registration, content moderation, or labeling AI-generated content is required.

    Troubleshooting

    • Outdated answers: check whether the search tool was actually triggered and whether the timestamp of the search result was passed to the model correctly.
    • Inaccurate citations: verify the mapping between citation numbers and the source list, and prevent the model from inventing links.
    • Empty web page fetch: this is often caused by script-based dynamic rendering or access restrictions. Use a more suitable fetching method, or ask the user to paste the text.
    • Garbled file parsing: distinguish text-based documents from scanned documents. Scanned files need OCR, and encoding problems need separate handling.
    • Tool-call loops: check whether tool error messages are clear. If errors are vague, the model is more likely to retry repeatedly.

    Rollout Recommendations

    A practical rollout order is: implement web Q&A and citation display first to validate the core experience; then add web page reading and file parsing; finally add voice interaction and more complex multi-step reasoning. At each stage, include cost monitoring, safety review, and regression tests so the application remains maintainable as features expand.