Technical Practices for Building Comprehensive Conversational Applications Using LLM APIs

    This article explores the technical practices for building fully-featured conversational applications using Large Language Model (LLM) APIs. It covers the transition from basic text interfaces to integrated architectures encompassing web search, file parsing, webpage reading, voice capabilities, and content safety. The article provides a reference architecture, implementation guidelines for context budget management and tool calling, compliance considerations, testing strategies, and risk mitigation techniques to help developers build robust and reliable AI-driven chat applications.

    1. Problem Background

    Early model interfaces only handled basic “text in, text out” operations. To create an experience close to a mature chat product, developers had to manually integrate search results, parse uploaded files, scrape webpages, manage multi-turn context, and add voice input/output and content moderation. Each module required separate development and maintenance, data formats between interfaces were inconsistent, and overall costs were high.

    Recently, an increasing number of model providers have exposed these capabilities as parameters or tools, handling tool calling and context assembly on the server side. For developers, the focus has shifted from “how to connect all modules” to “how to select capabilities based on business needs, control costs, and ensure reliability.”

    2. Core Capabilities of a Conversational Application

    A complete conversational application typically includes the following five core capabilities.

    2.1 Web Search Augmentation

    Model training data has a cutoff date and cannot access the latest information. Web search invokes a search tool before or during response generation, fetches webpage or image results, and uses them as the basis for the answer.

    Three key points for implementation:

    • Trigger Timing: Can be determined automatically by the model based on the query, or forced by business rules. For example, time-sensitive questions can default to enabling search, while pure conceptual questions can disable it to save costs.
    • Result Quality: Search results require noise reduction and deduplication, while retaining source URLs and publication times.
    • Citation Marking: The response should clearly mark information sources for user verification.

    2.2 File Input and Parsing

    Users frequently upload PDFs, Office documents, and images. Parsing methods fall into two categories:

    • Plain Text Extraction: Suitable for digital text documents; fast and cost-effective.
    • Mixed Layout Parsing: Suitable for scanned documents or those containing tables and illustrations; requires layout analysis and Optical Character Recognition (OCR).

    Parsed results must enter the context, so length limits must be considered. Overly long documents should be chunked, summarized, or have relevant paragraphs retrieved based on the query, rather than stuffing the entire content into the prompt.

    When user messages contain links, the system can scrape the page’s main text, removing irrelevant content like navigation and ads, before passing it to the model. This capability has three constraints:

    • Access Control: Restrict accessible domain ranges, prohibit internal network addresses, and prevent Server-Side Request Forgery (SSRF).
    • Timeout and Retry: If the target page responds slowly or fails to load, provide a clear prompt instead of failing silently.
    • Copyright and Privacy: Only scrape public pages and comply with the target site’s robots.txt and other conventions.

    2.4 Voice Capability Chain

    Voice interaction usually consists of three stages:

    • Speech Recognition (STT): Converts audio to text.
    • Language Model Processing: Generates a reply based on the text.
    • Speech Synthesis (TTS): Converts the reply text to audio.

    OCR for images is also frequently combined with voice capabilities. Each stage can be called independently, making it easy to replace a specific module for different scenarios (e.g., replacing only the recognition module while keeping the rest intact).

    2.5 Content Safety

    Public-facing applications must conduct risk reviews on both input and output. Common practices include:

    • Enabling server-side safety check capabilities for basic input/output moderation.
    • Adding keyword and rule filtering on the business side to cover business-specific sensitive words outside of general platform rules.
    • Returning a unified rejection message when risks are detected, and logging the event for auditing and post-mortem analysis.

    3. Reference Architecture

    It is recommended to divide the system into an Access Layer, Orchestration Layer, Capability Layer, and Storage Layer.

    1. Client (Web / Mini-Program / App)
    2. │
    3. Access Layer: Authentication, Rate Limiting, Session Management
    4. │
    5. Orchestration Layer: Intent Determination, Tool Selection, Context Assembly
    6. │
    7. ┌──────┼──────────┬───────────┬───────────┐
    8. Search File Parsing Web Reading Voice Chain Safety Check
    9. │
    10. Storage Layer: Session History, File Objects, Audit Logs

    The Orchestration Layer is the core. It determines which capabilities are required for a given request and places the outputs of each capability into the context in a unified structure. The clearer the interface between the Orchestration Layer and the model service, the easier it is to replace or expand capabilities later.

    Sample code (pseudo-code, parameter names are for illustration only; refer to the actual platform documentation):

    1. def handle_message(session, user_input, files=None):
    2. request = {
    3. "messages": session.history + [{"role": "user", "content": user_input}],
    4. "tools": {
    5. "web_search": session.config.web_search_enabled,
    6. "read_url": session.config.read_url_enabled,
    7. },
    8. "safety_check": True,
    9. }
    10. # Append attachments as text into context
    11. for f in files or []:
    12. text = extract_text(f) # Plain text extraction or layout parsing
    13. request["messages"].insert(
    14. 0, {"role": "system", "content": f"[Attachment Content]\n{text}"}
    15. )
    16. response = llm_client.chat(request)
    17. # Use fixed rejection path when safety risk is triggered
    18. if response.get("blocked"):
    19. return "Unable to provide a reply for this content. Please adjust your question."
    20. session.append(user_input, response["text"])
    21. return response["text"]

    This code embodies three principles. First, capability toggles are configuration-controlled for easy scenario-based composition. Second, attachments are uniformly converted to text and injected into the context, masking differences in file formats. Third, safety rejections have a fixed exit point, allowing the frontend to handle them uniformly.

    4. Implementation Details

    4.1 Context Budget Management

    Models have limited context lengths. Before each request, calculate the token usage of each part, including conversation history, attachment text, search results, and webpage content. If the total exceeds the limit, prioritize compressing older history while retaining recent turns and confirmed key conclusions. Attachment content can undergo relevant paragraph retrieval based on the query, injecting only the parts relevant to the question.

    4.2 Timeout and Degradation for Tool Calling

    If search or web scraping fails, the system should not interrupt the entire response. A safer approach is to degrade gracefully by answering based only on the existing context, and indicating on the UI that “the latest information could not be retrieved.” Degradation strategies should be defined in advance and included in test cases.

    4.3 External Information in Multi-step Reasoning

    In tasks requiring multi-step reasoning, the model might call search and reading tools multiple times. The Orchestration Layer should set a maximum number of calls and a total time limit to prevent infinite loops and control costs. These limits can be configured based on task types; for example, Q&A tasks might have lower limits, while research tasks might have higher ones.

    4.4 Citation and Traceability

    Every piece of external information should save its source URL, retrieval time, and summary. Citation numbers in the response must correspond one-to-one with the source list. This facilitates user verification and post-event auditing of the response basis.

    4.5 Session Data Migration

    If users want to import historical sessions, a unified data format must be defined first, including at least the role, content, timestamp, and attachment references. Once the format is clear, the logic for importing, exporting, and cross-device synchronization can remain stable.

    5. Compliance and Operations Requirements

    When providing generative services to the public, certain regulatory requirements must be met, typically including:

    1. Conducting content safety reviews and establishing sensitive information identification and manual review mechanisms.
    2. Completing necessary registration and compliance procedures for the model or service as required by local regulations.
    3. Adding identifiable AI-generated labels to generated text, images, and audio.
    4. Retaining necessary operational logs and providing public channels for user complaints and appeals.

    These requirements should be integrated into the architecture during the design phase, rather than patched in right before launch. Specific obligations depend on the current regulations in your operating region.

    6. Testing and Observability

    Before launch, it is recommended to cover four types of testing:

    • Functional Testing: Verify that outputs meet expectations under different combinations of capability toggles.
    • Boundary Testing: Cover overly long files, encrypted files, corrupted images, and inaccessible links.
    • Security Testing: Cover inducing prompts, prompt injection inputs, and sensitive topics.
    • Performance Testing: Observe Time to First Token (TTFT) and overall latency under target concurrency.

    Online monitoring should cover call success rate, tool failure rate, average latency, rejection ratio, and cost per request. When metrics are abnormal, you should be able to quickly locate the specific capability module, rather than just seeing an overall slowdown.

    7. Common Risks and Mitigation

    • Outdated Information: Mitigate risks through web search and source citation, and add prompts for time-sensitive content in the response.
    • Attachment Leaks: Encrypt attachment storage, set retention periods, and allow users to manually delete them.
    • Link Abuse: Configure domain whitelists, prohibit internal network access, and limit the number of scrapes per request.
    • Cost Overruns: Set per-session and global quotas, automatically degrading or prompting the user when exceeded.