Choosing and Integrating LLM APIs: A Practical Engineering Guide for Developers in China
Selecting an LLM API provider involves more than writing integration code—it requires evaluating network accessibility, payment options, model coverage, compliance, and cost structure. This guide walks through four common integration paths, the design of a unified access layer, stability engineering with timeouts and retries, token-based cost estimation, data compliance considerations, and a pre-launch checklist to help teams ship reliable LLM-powered services.
Choosing and Integrating LLM APIs: A Practical Engineering Guide for Developers in China
Clarify Your Selection Criteria First
The hard part of LLM API integration usually isn’t the code—it’s the upfront selection decision. Developers often face a trade-off between ease of access and model coverage: the simpler the integration path, the fewer models may be available; the broader the model coverage, the higher the demands on networking, payment, and compliance.
When evaluating an integration option, consider at least these six dimensions:
- Network accessibility: Can the service endpoints be reached reliably, and is latency within acceptable bounds?
- Payment and invoicing: Are commonly used payment methods supported, and can the provider issue invoices your finance team requires?
- Model coverage: Does the service include the model types your business needs, such as general-purpose chat, code generation, multimodal understanding, or embedding models?
- Stability and rate limits: Are availability metrics transparent, and do concurrency and rate limits handle your traffic peaks?
- Data compliance: Does user data pass through overseas nodes, and does the setup satisfy industry regulations and personal data protection requirements?
- Cost structure: Are billing units, pricing tiers, and usage reporting clear enough for budget management?
There is no single best answer across these dimensions. The same team will weight them differently during prototyping versus production launch.
Four Common Integration Paths
1. Direct Integration with the Model Provider
Connecting directly to the model provider’s official API gives you the most primitive interface and the earliest access to new features and model versions. The downsides are equally clear: account registration, payment settlement, and network access all need to be handled independently, and corporate procurement and reimbursement processes may be complicated. This path is common for teams with international operations or the relevant qualifications already in place.
2. Aggregation Gateways and Unified Proxy Services
These services provide a single access point on top of multiple model providers, so your application code integrates with one API and can switch between models. The value lies in reducing multi-vendor adaptation costs; the trade-off is an additional dependency. Before committing, verify the provider’s credentials, data retention policies, failover capability, and actual service-level commitments—and document the data flows in your internal security review.
3. Cloud Provider LLM Platforms
Domestic cloud platforms—such as Baidu AI Cloud’s LLM service platform—typically offer in-country deployment nodes, enterprise account systems, invoicing and corporate settlement, plus enterprise features like permission management and audit logs. For compliance-sensitive industries such as finance, government, and healthcare, this path is easier to get approved internally.
4. Self-Hosted Open-Source Models
Deploying open-source models on owned or rented compute means your team handles inference serving, scaling, and monitoring. Data stays fully under your control, and unit costs can be lower at high concurrency—but you need expertise in GPU resource management, model optimization, and operations. For small teams, initial labor costs often exceed what API calls would cost.
Designing a Unified Access Layer
Whichever path you choose, add a unified access layer between your application code and the model services. Its responsibilities include: abstracting away provider-specific API differences, centralizing key management, handling timeouts and retries consistently, logging usage, and failing over to backup models when the primary service is down.
Most chat-style APIs use HTTP and JSON. The request body contains a model name and an array of messages organized by roles such as system, user, and assistant. Streaming output is implemented via chunked transfer or server-sent events, allowing the frontend to render responses incrementally and reduce perceived latency.
Here is illustrative pseudocode showing the basic structure of an access layer:
function callLLM(userInput, modelName):baseUrl = readEnvVar("LLM_BASE_URL")apiKey = readEnvVar("LLM_API_KEY")headers = {"Authorization": "Bearer " + apiKey,"Content-Type": "application/json"}body = {"model": modelName,"messages": [{"role": "system", "content": "You are a professional technical assistant"},{"role": "user", "content": userInput}],"temperature": 0.2}response = sendPost(baseUrl + chatCompletionPath, headers, body, timeout=30s)return response.content
The endpoint paths, parameter names, and model names in the example must be replaced with the actual definitions in your chosen provider’s documentation. Parameter names vary across platforms—always defer to the official documentation.
Stability Engineering: Timeouts, Retries, and Fallbacks
LLM calls have highly variable latency, and occasional timeouts and rate limiting are normal—so stability design must come first.
Timeout settings. Set connection and read timeouts separately. For non-streaming requests, estimate the read timeout based on expected output length; for streaming requests, watch the time-to-first-token and idle gaps without data.
Conditional retries. Only retry retryable errors: network connection failures, request timeouts, rate-limit responses, and transient server errors. Do not retry parameter errors, authentication failures, or content policy violations. Use exponential backoff with random jitter so a burst of retries doesn’t hit the service simultaneously.
function retryWithBackoff(userInput, modelName, maxAttempts=3):waitTime = 1sfor attempt in 1..maxAttempts:try:return callLLM(userInput, modelName)catch RetryableError:if attempt == maxAttempts: throwsleep(waitTime + randomJitter())waitTime = waitTime * 2
Concurrency and rate limiting. Use a token bucket or semaphore on the client side to control concurrency, and configure queues according to the provider’s published rate limits. Keep batch offline jobs on a separate queue from online requests so offline work doesn’t starve online traffic.
Fallback chains. For critical business flows, configure an ordered list of backup models. When the primary model is unavailable or times out, automatically switch to a comparable backup model and log the switch event. Output quality may differ after fallback, so the product layer should either surface this to users or apply rules to decide whether to accept the result.
Cost Estimation and Usage Control
Most LLM services bill by token, with input and output priced separately and significant price differences across models. Break your budget estimation into these steps:
- Measure the average input and output token counts of typical requests.
- Estimate daily input and output totals from average daily traffic and a peak factor.
- Apply the official unit prices of your chosen model to compute monthly cost.
- Add headroom, and account for retries, fallbacks, and test-environment calls separately.
A rough formula:
Monthly cost = daily requests × 30 × (avg input tokens ÷ 1000 × input price+ avg output tokens ÷ 1000 × output price)
Prices change as providers adjust them—before launch, rely on the current official pricing page rather than numbers from older articles.
Engineering-wise, also do the following: assign separate API keys per business line and environment so usage can be attributed per project; set usage alert thresholds; and truncate or summarize overly long inputs to cap costs.
Data Compliance and Security
LLM integration involves sending user input to external services, so compliance risks must be addressed at the design stage.
- Data classification: Identify whether inputs contain personal information, trade secrets, or regulated data, and mask or substitute sensitive fields before sending.
- Cross-border assessment: If service nodes are located overseas, determine—based on your business type—whether cross-border data transfer assessments or filings are required, and consult your legal team.
- Log governance: Do not log full user inputs or model outputs, and never log API keys. If retention is necessary, encrypt the data and set retention periods.
- Key management: Inject keys via environment variables or a dedicated secrets management service; never hardcode them in the repository. Rotate keys regularly and revoke access promptly when staff leave.
- Least privilege: Assign call permissions per project and role rather than sharing a single high-privilege key across all services.
Decision Reference by Scenario
The table below summarizes common tendencies by business scenario:
| Business Scenario | Preferred Path | Key Considerations |
|---|---|---|
| Rapid prototyping, comparing multiple models | Aggregation gateway or unified access layer | Provider credentials, data retention policy |
| Compliance-heavy domains (finance, government) | Domestic cloud platform or private deployment | In-country nodes, audit and permission systems |
| Highly sensitive data, full control required | Self-hosted open-source models | GPU resources, ops capability |
| High-concurrency production services | Multi-vendor redundancy plus unified access layer | Rate limits, failover, cost |
Model selection is not a one-time decision. Review model quality, cost, and stability data quarterly, and adjust your path based on actual metrics.
Pre-Launch Checklist
Before going live, confirm each of the following:
- API keys removed from code and isolated across environments.
- Timeouts, retry counts, and backoff policy configured, applying only to retryable errors.
- Concurrency limits aligned with the provider’s rate limits.
- Backup models configured and failover rehearsed.
- Usage tracking and cost alerts wired into monitoring.
- Log masking rules verified—no sensitive data in output.
- Cross-border data and personal information assessments completed and archived.
- Load test results meet expected peaks, with error rates and latency within acceptable ranges.
LLM API integration is an ongoing effort. Clear selection criteria set the boundaries early; solid stability and cost control carry you through the middle; and continuous optimization driven by monitoring data keeps model capabilities reliably serving your business.
