LLM API Protocol Compatibility and Smooth Migration: A Practical Guide
This article explains how to reduce the cost of switching LLM providers through configuration-driven integration, protocol compatibility assessment, and a three-layer architecture for configuration, adaptation, and business logic. It compares common HTTP API and native SDK integration forms, lists key migration feasibility questions, and provides a Python adapter example that keeps business code independent of the underlying provider. It also introduces a functional alignment checklist beginning with streaming output.
1. Background
In the lifecycle of an AI application, changing model providers is often more frequent than expected. Price adjustments, model capability iterations, regional compliance requirements, and fluctuations in service stability can all prompt teams to consider switching. If business code is deeply bound to one provider’s request format, every switch requires changing the call chain, retesting, and releasing a new version, and migration costs quickly accumulate.
The core goal of the integration layer is therefore to make provider switching a configuration change rather than an engineering rework.
2. Three Forms of API Protocol Compatibility
Common approaches to model service integration in the industry fall into three categories.
Chat-completion-style HTTP APIs
The request body usually contains the model name, a message list withroleandcontentfields, and sampling parameters such as temperature. The response contains structured candidate results. Many providers offer endpoints compatible with this structure, so client code can be reused by changing only the base URL and key.Messages-style HTTP APIs
The structure is similar to the previous category, but the position of the system prompt, the types of content blocks, and the organization of tool-calling fields differ. AI coding tools that use these APIs usually specify the endpoint address and authentication token through environment variables.Provider-native SDKs
Native SDKs can expose provider-specific advanced parameters, such as reasoning process output, web retrieval, and structured output constraints. The advantage is full functionality; the disadvantage is that code becomes tied to a single vendor.
Understanding the differences among these three forms helps determine whether a migration only requires configuration changes or also requires adapter code changes.
3. Migration Feasibility Assessment
Before switching, it is advisable to answer the following four questions.
- Which API form is currently used for calls?
- Does the business depend on any parameter or response field that is unique to a provider?
- Are tool calling, streaming output, and multimodal input implemented in the target service?
- Are the authentication method, quotas, and rate-limiting policies after the switch acceptable?
If all answers are yes, usually only configuration changes are needed. If provider-specific parameters are involved, they must be mapped in the adapter layer, or a fallback path must be retained for that feature.
“Compatibility” only means that request formats can be aligned; it does not mean that behavior is completely identical. Even when the same tool-calling protocol is used, different models may still differ in how they interpret parameters, handle long context, and adhere to output formats. Passing the protocol layer does not mean passing the quality layer.
4. Three-Layer Architecture: Configuration, Adaptation, and Business
It is recommended to split model calls into three layers.
The first layer is the configuration layer. The base URL, model name, key, timeout, and retry count are all read from environment variables or a configuration center. No hardcoded provider constants should appear in business code.
The second layer is the adapter layer. It provides a unified call interface externally. Internally, it converts business requests into the request format of the target service and normalizes response results into internal data structures.
The third layer is the business layer. Business logic depends only on internal interfaces and is unaware of the underlying provider.
This layering means that switching providers affects only the configuration layer and the adapter layer, while test cases for the business layer can remain unchanged.
The following example demonstrates the basic idea of the adapter layer using a generic HTTP client.
import osfrom dataclasses import dataclassimport requests@dataclassclass LLMConfig:base_url: strapi_key: strmodel: strtimeout: float = 60.0@classmethoddef from_env(cls) -> "LLMConfig":return cls(base_url=os.environ["LLM_BASE_URL"],api_key=os.environ["LLM_API_KEY"],model=os.environ.get("LLM_MODEL", "default-model"),)class ChatAdapter:"""Unified chat interface that hides differences between underlying providers."""def __init__(self, config: LLMConfig):self.config = configself.session = requests.Session()self.session.headers.update({"Authorization": f"Bearer {config.api_key}","Content-Type": "application/json",})def chat(self, messages: list[dict], temperature: float = 0.2) -> str:payload = {"model": self.config.model,"messages": messages,"temperature": temperature,}resp = self.session.post(f"{self.config.base_url.rstrip('/')}/chat/completions",json=payload,timeout=self.config.timeout,)resp.raise_for_status()data = resp.json()return data["choices"][0]["message"]["content"]
In the code, the key is injected through environment variables and is not written into the source. The business layer calls only ChatAdapter.chat; when switching services, only LLM_BASE_URL, LLM_API_KEY, and LLM_MODEL need to be changed.
If the target API uses another structure, only the request assembly and result parsing in the chat method need to be replaced, while the external interface remains unchanged.
5. Functional Alignment Checklist
During migration, verify the following capabilities one by one.
- Streaming output:
