LLM API Integration in Practice: Web Search and Multimodal Capabilities

    This article explains how to build conversational applications on top of LLM APIs. It covers web search, file and URL input, speech and image recognition, and content safety checks. It also describes a practical architecture, context management, cost control, compliance considerations, and a pre-launch checklist for engineering teams.

    1. Background: From Q&A Interfaces to Conversational Applications

    Early on, most applications that integrated large language models only called a text chat interface. The model could answer only from its training data and the prompt. To reach the experience of a mature conversational product, an application needs several more capabilities: retrieving up-to-date information, understanding files users upload, reading links users send, handling voice input and output, and moderating content before launch.

    Previously, applications assembled these capabilities themselves. Developers had to call search services, parse documents, fetch web pages, and maintain context across multiple turns. When the server side moves tool calls and context assembly inside the model interface, the developer’s focus shifts. The assembly workload goes down, and the main tasks become defining capability boundaries, controlling costs, and managing risk.

    2. Core Capabilities

    When the model determines that a question requires external information, it can start a web or image search on its own. It then uses the results as the basis for its answer. Answers usually include citations so users can verify the sources.

    Three points matter most in engineering:

    • Switch policy: When the search tool is off, the model relies only on its training data, so its answers may not reflect recent events. Decide whether search should be on by default or enabled on demand, based on the business scenario.
    • Citation display: Keep source information in the response structure, and show it clearly in the interface.
    • Data trustworthiness: Search results come from external web pages. Treat them as untrusted input. Use them as reference material, not as instructions.

    2.2 Web Access in Multi-Step Reasoning

    When thinking mode is enabled, the model splits a complex question into several sub-steps. Each step may trigger a search or read a web page. These workflows take noticeably more time and tokens than single-turn Q&A. To prevent runaway behavior, set a timeout, a maximum number of search steps, and a truncation length for each result.

    2.3 File Input

    Document input generally follows one of two processing paths:

    1. Plain text extraction: Suitable for well-structured text material. It is fast and low cost.
    2. Layout-aware parsing: Suitable for documents that contain tables, charts, or scanned pages. It preserves layout information but takes longer to process.

    The parsed result is added to the conversation context. Injecting a long document in full can exceed the context window, and key information gets diluted. A common approach is to split the document into chunks and retrieve the segments relevant to the question. Another is to generate a summary first and answer from that summary.

    2.4 Web Page Reading

    When a user message contains a link, the server can recognize the link, fetch the page content, and answer using that content together with the conversation context. The application layer needs to control the following risks:

    • Limit the scope of fetching through an allowlist or permission policy. This prevents the model from being steered toward internal addresses or sensitive resources.
    • Page content may contain misleading text, such as “ignore the previous instructions.” The model should treat this text as material to analyze, not as a command to follow.
    • Set a size limit on fetched content so that very large pages do not consume excessive resources.

    2.5 Speech and Image Recognition

    Speech capabilities are usually split into separate stages. Each stage can be called on its own or combined into a pipeline:

    • Automatic Speech Recognition (ASR): Converts audio into text. It is the entry point for voice input.
    • Text-to-Speech (TTS): Converts response text into audio for voice output.
    • Optical Character Recognition (OCR): Extracts characters from images. It is often used for photo-based questions and receipt processing.

    Splitting the calls has a practical benefit. Each stage can be tested, replaced, and monitored independently. For example, if speech recognition produces errors, the problem can be traced directly to audio quality or the recognition module without investigating the entire pipeline.

    2.6 Safety Checks

    A service exposed to the public should moderate content at both the input and the output. When a risk rule is triggered, the application should return a standard refusal message and write the related record to an audit log for human review. Moderation rules need regular regression testing to confirm that both false positive and false negative rates stay within acceptable limits.

    3. Engineering Implementation

    A complete conversational application usually has the following layers:

    1. Client
    2. -> Application gateway (authentication, rate limiting)
    3. -> Session service (history storage, context trimming)
    4. -> Model API (inference, tool calls)
    5. -> Tool layer (search, web page reading, file parsing, speech processing)
    6. -> Content moderation and audit logs

    The application gateway handles identity authentication and traffic control. The session service stores message history and decides how much context to include in each request. The tool layer is split by capability, so each part can scale independently.

    3.2 Request Assembly Example

    The following code is illustrative pseudocode. The field and function names are placeholders. Check the official documentation for your platform for the actual fields.

    1. def build_request(session, user_input, attachments):
    2. # Keep only the most recent turns to control context length
    3. context = session.history[-MAX_TURNS:]
    4. # Convert files to text, then truncate before adding them to the context
    5. for file in attachments:
    6. text = extract_text(file) # Plain text or layout-aware parsing
    7. context.append({
    8. "role": "user",
    9. "content": truncate(text, MAX_FILE_CHARS),
    10. })
    11. context.append({"role": "user", "content": user_input})
    12. return {
    13. "model": MODEL_NAME,
    14. "messages": context,
    15. "tools": ["web_search", "url_reader"], # Tools enabled on demand
    16. "safety_check": True, # Enable content safety checks
    17. }

    This example reflects three principles. Conversation history needs trimming, file content needs truncation, and tools and safety checks should be configured explicitly.

    3.3 Context Management Strategies

    Context affects both cost and output quality. Common strategies include:

    • Sliding window: Keep only the last few turns. This is simple to implement, but key constraints from early in the conversation may be lost.
    • Summary compression: Periodically compress earlier conversation into a summary. Keep the user’s goals, confirmed facts, and open questions.
    • On-demand retrieval: Store conversation history and file segments in a vector index. Each request pulls only the content relevant to the current question.

    In most scenarios, a combination of a sliding window and summary compression is sufficient. On-demand retrieval is worth adding mainly for long-document Q&A or knowledge-intensive applications.

    4. Security and Compliance

    4.1 Content Safety

    Content moderation should cover inputs, outputs, and content returned by tools. The application layer should also design friendly refusal messages. It should record the category of each blocked request so that moderation rules can be improved later.

    4.2 Generative AI Regulations

    If a service offers generative AI to the public, follow the regulations of each jurisdiction where the service operates. Depending on the region, obligations may include:

    • Taking responsibility for content safety and setting up a review mechanism;
    • Completing any model registration or filing that local authorities require;
    • Adding explicit or implicit labels to AI-generated content.

    Requirements change over time. Development teams should confirm the applicable rules with legal or compliance staff during project planning, and follow the latest guidance published by the competent authorities.

    4.3 Data Privacy

    Files and conversation records uploaded by users may contain personal information or sensitive data. Clarify the following points:

    • Where data is stored and how long it is retained;
    • How data is encrypted in transit;
    • How users delete their data, and whether the deletion is complete;
    • Whether user data is used to train models, and whether the privacy policy discloses this.

    4.4 Prompt Injection Defense

    Prompt injection occurs when a user or external content tries to override system instructions. Mitigations include strictly separating system instructions from user input, tagging tool outputs with their source, and adding a confirmation step before critical actions. These measures cannot eliminate the risk entirely. Output review and least-privilege permissions must also be used as supplements.

    5. Performance and Cost Control

    Cost and latency depend mainly on three factors: whether tools are called, the length of the context, and how files are processed. In practice, the following measures help:

    1. Enable tools on demand: Turn on web search only when a question actually needs up-to-date information. This avoids adding latency to every request.
    2. Cache frequent results: Cache search results for common queries and parsed file results, with a suitable expiration time.
    3. Process files asynchronously: Move large file parsing into background tasks, and notify the frontend when it finishes. This avoids blocking the request.
    4. Set timeouts and fallbacks: When a tool call times out, fall back to answering from existing information, and tell the user the result may be incomplete.
    5. Monitor key metrics: Track time to first token, end-to-end latency, tool call success rate, refusal rate, and average token consumption per request.

    Metrics should match business goals. For example, customer service applications focus more on time to first token, while knowledge Q&A applications focus more on citation accuracy.

    6. Pre-Launch Checklist

    Before launch, confirm the following items:

    • Each capability (web search, URL reading, files, speech, moderation) has a clear switch and default value;
    • Tool results include source identifiers, and the frontend can display citations;
    • Limits are set for file size, file type, and the scope of web page fetching;
    • Moderation rules have passed regression testing, and false positive samples are recorded;
    • Logs do not contain plaintext keys or sensitive personal information;
    • Compliance items are confirmed, including required filings, AI content labeling, and the privacy policy;
    • The release is rolled out gradually, with a rollback plan in place.

    7. Summary

    Large language model applications are moving from answering questions to completing tasks. This requires organizing web search, files, web pages, speech, and safety moderation into a coherent system. Developers should focus on capability boundaries, context costs, data security, and compliance obligations. A architecture with decoupled modules, explicit configuration, and observable metrics improves the conversation experience and reduces operational and risk costs after launch.