Engineering Practices for LLM API Integration and Invocation

    This article presents a general engineering methodology for integrating large language model (LLM) inference into business systems in a way that is controllable, observable, and scalable. It covers architectural layering, credential and secret management, request construction and prompt versioning, streaming output and time-to-first-token, concurrency, rate limiting and retry strategies, cost control and capacity planning, observability and quality evaluation, fault tolerance and compliance, and a final deployment checklist. The guidance applies to any platform that exposes inference APIs, including the relevant general-purpose capabilities on Baidu AI Cloud.

    1. Why a Successful Call Is Only the Starting Point

    Many teams feel a rush of satisfaction the first time they get a response from an LLM: a few lines of code deliver text generation, summarization, classification, and question answering that used to require substantial engineering effort. But in real production environments, there is a long way from one successful call to a stable online service. How are credentials managed? How are timeouts set? How is output streamed back? How do you avoid being overwhelmed by rate limits as concurrency grows? How is the monthly invocation cost accounted for? How does the system degrade when errors occur? These are the core questions that determine whether a project can run sustainably.

    Rather than discussing whether a particular tool is good, this article frames the topic as a general engineering problem: how to integrate LLM inference into a business system in a controllable, observable, and scalable way. This methodology applies to any platform that provides inference APIs, including the relevant general-purpose capabilities on Baidu AI Cloud.

    2. Architectural Layering Before Integration

    A mature LLM application can usually be split into four layers, decoupled from each other through clear contracts:

    1. Access layer: handles authentication, parameter validation, rate limiting, and auditing, shielding the system from untrusted external input.
    2. Orchestration layer: manages prompt templates, context assembly, multi-turn conversation state, tool invocation, and flow branching.
    3. Model invocation layer: encapsulates request construction, retries, timeouts, and stream parsing, and exposes a unified interface upward.
    4. Data and observability layer: logging services, monitoring and alerting, metrics collection, and cost and quality evaluation.

    The value of layering is that when a model capability needs to be replaced or gradually rolled out, the change is confined to the invocation layer, and business code requires no modification.

    1. Business request -> Access layer (auth/rate limit) -> Orchestration layer (templates/context)
    2. -> Invocation layer (retry/timeout/streaming) -> Inference service
    3. -> Observability layer (logs/metrics/cost)

    3. Credential and Secret Management

    Credential leakage is the most common and most serious security issue in LLM integration. There is only one basic principle: secrets must never appear in clients or code repositories.

    • Secrets are held centrally by the backend; the frontend communicates only with your own services.
    • Use the key management or environment variable injection provided by the cloud platform, and avoid hardcoding.
    • Establish a rotation mechanism and a least-privilege policy, with separate credentials per business line.
    • Mask authentication fields in logs to prevent secondary leakage through the logging service.
    1. import os
    2. # Credentials are injected by the deployment environment, never committed to the repository
    3. API_KEY = os.environ["LLM_API_KEY"]
    4. BASE_URL = os.environ["LLM_ENDPOINT"] # delivered by the configuration center

    4. Request Construction and Prompt Engineering

    A request body typically contains common fields such as the model identifier, message list, temperature, maximum generation length, and stop sequences. From an engineering standpoint, version management of prompts deserves more attention:

    • Treat prompts as code assets, put them under version control, and annotate the reason for each change.
    • Separate system instructions from user input so that user input cannot override system constraints.
    • Truncate and filter user input to prevent prompt injection attacks.
    • For structured output scenarios, explicitly define the output format and validate it on the parsing side with a fallback.
    1. def build_messages(system_prompt, user_input, history=None):
    2. messages = [{"role": "system", "content": system_prompt}]
    3. for turn in (history or [])[-6:]: # limit context length
    4. messages.append(turn)
    5. messages.append({"role": "user", "content": user_input[:4000]})
    6. return messages

    5. Streaming Output and Time to First Token

    For conversational products, the experience bottleneck is often not total latency but time to first token. Streaming responses let users see feedback within a few hundred milliseconds, significantly improving perceived performance. Key implementation points:

    • The invocation layer reads response chunks incrementally and pushes them to the frontend segment by segment.
    • Use a message queue or a long-lived connection channel to decouple generation from consumption, avoiding long occupation of request threads.
    • On the frontend, keep placeholders and auto-scrolling during incremental rendering, and handle incomplete character truncation.
    • If the business only needs the final result (such as classification or tagging), disable streaming to reduce complexity.
    1. for chunk in client.stream(messages):
    2. delta = chunk.get("content", "")
    3. if delta:
    4. yield delta # pushed to the client by the upper layer over a long-lived connection

    6. Concurrency, Rate Limiting, and Retry Strategy

    Inference service throughput is a finite resource, and the client must constrain itself proactively. A recommended combination:

    • Client-side rate limiting: use a token bucket to control requests per second and concurrency.
    • Exponential backoff retries: retry only on timeouts, rate limits, and server errors; do not retry parameter errors.
    • Circuit breaking: fail fast when the error rate exceeds a threshold to avoid cascading failures.
    • Queue-based peak shaving: put non-real-time tasks into a message queue and let consumers process them at a steady rate within quota.
    1. import random, time
    2. def call_with_retry(fn, max_attempts=3):
    3. for attempt in range(max_attempts):
    4. try:
    5. return fn()
    6. except TransientError:
    7. if attempt == max_attempts - 1:
    8. raise
    9. time.sleep(2 ** attempt + random.random())

    7. Cost Control and Capacity Planning

    Under usage-based billing, cost overruns usually come from three types of waste: overly long context, duplicate requests, and ineffective retries. Practical measures include:

    • Context trimming and summary compression, keeping only necessary history.
    • Result caching, with semantic or exact caches for high-frequency repeated questions.
    • Tiered routing, sending simple tasks to smaller models and escalating complex tasks.
    • Usage dashboards by business line and by API, with budget thresholds set through monitoring and alerting.

    For capacity planning, it is recommended to first run a small-traffic canary to measure the request volume that can be handled per unit of time, then estimate peak quota and queuing strategy accordingly, rather than passively scaling up only after rate limit errors appear.

    8. Observability and Quality Evaluation

    LLM output is non-deterministic, so the traditional monitoring approach of “a successful request means a correct result” no longer applies. Three categories of metrics need to be added:

    1. Performance metrics: time to first token, end-to-end latency, success rate, and rate limit ratio.
    2. Cost metrics: invocation count, input and output length distribution, and cost per business unit.
    3. Quality metrics: format compliance rate, manual sampling pass rate, and negative user feedback rate.

    On the engineering side, logs across the invocation path can be collected centrally into a logging service and combined with monitoring and alerting to form a closed loop. On the quality side, build an offline evaluation set and run regression validation before changing prompts or model versions, avoiding the situation where “changing one prompt sentence causes overall online quality to drop.”

    9. Fault Tolerance, Degradation, and Compliance

    Any external dependency will fail, so a fallback must be designed in advance:

    • Consolidate timeout and exception handling, and return readable fallback messages to users.
    • Prepare a rule engine or templated answers as a degradation option for critical paths.
    • Perform two-way review of input and output on the content safety side, and retain audit records.
    • Define a data retention policy, and mask sensitive data before it enters the inference path.

    10. Deployment Checklist

    • Are secrets fully backend-managed and rotation-capable?
    • Are prompts versioned and injection-resistant?
    • Are streaming and time-to-first-token monitoring enabled?
    • Are rate limiting, retries, and circuit breaking all in place?
    • Is there a cost dashboard with budget alerts?
    • Is there an offline evaluation set and a degradation plan?
    • Do logs and monitoring cover the full path and are they masked?

    When these elements are implemented layer by layer, LLM capability turns from a “demo that runs” into infrastructure that can be operated sustainably. For the actual implementation, you can use general-purpose capabilities such as the container platform, message queue, logging service, and monitoring and alerting provided by Baidu AI Cloud to carry these elements, allowing you to focus your effort on business orchestration and quality refinement.