API-ifying Large Language Model Applications: A Technical Guide to Replicating Conversational Products

    This article explains how to turn a full-featured conversational AI product into composable APIs. It breaks down the six capability layers of a chat application, covers protocol compatibility across Chat Completions, Responses, and Messages, and walks through web search, URL reading, file parsing, OCR, ASR/TTS, safety moderation, and cost governance. You will learn the trade-offs between platform-managed tools and self-built pipelines, plus a layered architecture for a stable, compliant deployment.

    1. From Monolithic Applications to Composable Capabilities: Why Conversational Products Are Going API-First

    Over the past year, the capability boundaries of conversational AI products have expanded rapidly. What started as plain text Q&A has grown to include web search, web page content extraction, document parsing, image text recognition (OCR), speech input and playback, and content safety moderation. Early on, these capabilities were mostly bundled inside the end-user application. If developers wanted to replicate a similar experience, they had to integrate a search service, crawlers and content extraction components, an OCR engine, speech recognition and synthesis services, and sensitive-word libraries—multiple heterogeneous systems with long engineering chains, many failure points, and high tuning costs.

    A clear trend has recently emerged in the industry: capabilities that were once hard-wired inside applications are being broken out one by one into standard APIs and exposed through a unified protocol. The technical significance goes beyond “writing less code.” It pushes complex multi-tool orchestration down to the server side, so developers only need to declare the tools they require in a request, and the platform handles retrieval, fetching, context assembly, and result backfilling. For developers, this compresses a pipeline that used to take weeks to wire together into a single API call.

    It is worth emphasizing that these capabilities are not unique to any single vendor; mainstream cloud providers and platforms across the industry are all advancing similar capability openings. This article therefore does not discuss any specific product. Instead, it abstracts a general technical paradigm to help you implement it on any model service compatible with the OpenAI or Anthropic protocols.

    2. Capability Breakdown: The Atomic Capabilities of a Complete Conversational Product

    To replicate a mature conversational application, start by building a capability inventory. It can usually be split into six layers:

    1. Inference layer: responsible for intent understanding, multi-turn context management, tool-call decisions, and final response generation.
    2. Retrieval layer: web search, addressing the timeliness of model knowledge and fact verification.
    3. Reading layer: given a URL, fetch the page and extract the main content, turning external information into clean text that can enter the context.
    4. File layer: upload PDFs, Word, Excel, plain text, and more, then parse, chunk, and trim overly long content.
    5. Multimodal layer: image OCR, speech-to-text (ASR), and text-to-speech (TTS).
    6. Governance layer: input and output safety moderation, sensitive content blocking, log auditing, and quota management.

    The key insight is that these six layers are not peers in engineering terms. The inference layer is the orchestration hub, while the other five typically appear at the protocol level as “tools” or “standalone endpoints.” Their invocation timing, failure-retry strategies, and billing models are completely different, and mixing them together in the design is a major source of rework later.

    3. Protocol Compatibility: One Codebase for Multiple Interface Styles

    The current mainstream approach is to support three interface styles simultaneously: Chat Completions, Responses, and Messages. The first two carry multi-turn conversations in a messages array, while the latter separates the system prompt into a top-level field. The engineering recommendation is to build an adapter layer that converts your internally unified conversation model into the target protocol:

    1. # Illustration: internal unified message -> target protocol
    2. def to_messages(internal, protocol="chat"):
    3. if protocol == "messages": # system as a separate field
    4. return {"system": internal["system"],
    5. "messages": internal["turns"]}
    6. return {"messages": [{"role": "system",
    7. "content": internal["system"]}] + internal["turns"]}

    The model identifier is typically a single string across different providers’ protocols, so switching providers only changes configuration, not business code. Tool declarations use the industry-standard JSON Schema to describe the function name, purpose, and parameter structure, and the model decides whether to call based on that.

    Web capabilities are generally exposed as two tools: one performs keyword search and returns a result list, and one fetches the main content of a specified link. The invocation pattern is as follows:

    1. resp = client.chat.completions.create(
    2. model="deepseek-flash",
    3. messages=[{"role": "user", "content": "Help me look up the latest industry data"}],
    4. tools=[{"type": "deepseek_web_search"},
    5. {"type": "deepseek_read_url"}]
    6. )

    After the server completes retrieval and fetching, it backfills the results as tool messages, and the model then generates an answer based on this content. Compared with a self-built four-stage pipeline of “search API + crawler + content cleaning + chunking,” this pattern has a clear latency advantage because it eliminates multiple network round trips and local cleaning overhead.

    But its shortcoming must be stated objectively: reduced controllability. You cannot customize ranking factors, regional and language preferences, or result deduplication strategies, and it is hard to further structure the fetched content. For strongly compliant, highly customized scenarios, it is still recommended to keep self-built retrieval as a fallback, forming a dual channel of “platform retrieval first, self-built retrieval as degradation.”

    5. File Input and OCR: Engineering Essentials for Long-Document Processing

    The typical file pipeline is: upload to obtain a file identifier → reference that identifier in the conversation request → the server parses it and injects it into the context. In practice, the pitfalls concentrate in three areas:

    • Overly long truncation: an entire book cannot fit into the context, so you need to chunk by token budget and use a summary index for coarse filtering.
    • Layout restoration: tables and multi-column layouts are the main killers of parsing accuracy, and an OCR channel is needed as a fallback when necessary.
    • Failure visibility: parsing failures must explicitly return an error code rather than silently returning empty content, otherwise the model will “confidently make things up.”

    6. Voice Pipeline: Implementation Details for ASR and TTS

    Speech input is usually billed by audio duration, output is billed by characters, and there are often tiered discounts. In engineering terms, note the following: the sample rate and encoding format must match the target service; long audio should be segmented and recognized incrementally to improve first-token latency; TTS needs to cache high-frequency fixed scripts to avoid repeated billing; and a text fallback channel must be provided to ensure usability in noisy environments.

    7. Safety Moderation and Cost Governance

    The governance layer is best built as a symmetric structure: intercept injection attacks and violating requests on the input side, and intercept leaks and inappropriate content on the output side. On the cost side, build a four-dimensional dashboard—track the three billing bases of per-token, per-call, and per-duration separately—and set tenant-level quotas and circuit-breaker thresholds to prevent a single point of failure from causing the bill to spiral out of control.

    8. Architecture Recommendations and Conclusion

    The recommended layered architecture is: an access layer for protocol adaptation and authentication, an orchestration layer for tool decisions and degradation, a capability layer that encapsulates retrieval, files, voice, and moderation, and an observability layer that uniformly collects logs, metrics, and distributed tracing. If the whole system runs on general cloud products such as Baidu AI Cloud’s container platform, object storage, log service, and monitoring and alerting, you can further simplify elastic scaling and audit compliance work.

    In summary, API-ifying conversational products trades “integration complexity” for “loss of controllability.” The rational strategy is to use platform built-in tools to quickly obtain a usable experience, use self-built pipelines to hold the line on compliance and customization, and backstop stability with robust observability and degradation mechanisms.