Why swapping providers hurts more than it should
Provider lock-in rarely lives in the API. It lives in the forty places in your codebase where somebody called a vendor SDK directly, hardcoded a model ID as a string literal, read response.choices[0].message.content, and moved on. The day a better model shows up — or a provider changes its limits, terms, or availability — every one of those call sites becomes a migration project.
The adapter pattern fixes the shape of that problem, not the models. You define one small interface that your application owns, then write thin translation classes behind it. Switching providers becomes a configuration change; switching model tiers becomes a one-word argument. Everything below is runnable Python you can drop into a project today.
The adapter pattern in three rules
One interface. Application code calls
complete(messages, ...)and nothing else. No vendor SDK imports outside the adapters package.Adapters translate, they do not think. An adapter converts messages, model tiers, responses, and errors. Prompts, retries, and business logic stay in your app.
No provider types cross the boundary. If a raw
ChatCompletionobject escapes into your service layer, you no longer have an adapter — you have a wrapper with extra steps.
Step 1 — define the interface your app owns
Keep it deliberately boring. Two dataclasses and one abstract method cover the vast majority of text workloads, and they are the only thing your tests need to fake.
# llm_core.py
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
@dataclass
class Message:
role: str # system | user | assistant
content: str
@dataclass
class Completion:
text: str
model: str
input_tokens: int
output_tokens: int
raw: dict = field(default_factory=dict, repr=False)
class LLMAdapter(ABC):
'The only LLM surface your application code is allowed to touch.'
@abstractmethod
def complete(
self,
messages: list[Message],
*,
model: str | None = None,
temperature: float = 0.7,
max_tokens: int = 800,
) -> Completion:
raise NotImplementedError
Step 2 — write the DeepSeek adapter
AiCredits serves an OpenAI-compatible endpoint, so the DeepSeek adapter is mostly plumbing: point the official openai client at the AiCredits base URL, resolve a model, normalize the response. Use deepseek-v4-flash as the everyday default and route genuinely hard tasks to deepseek-v4-pro, which costs more per call but reasons further — that tradeoff is the whole reason to keep tiers in the adapter instead of in call sites.
The tier map is the important line. Your application should ask for fast or strong, never for a vendor model ID. That single indirection is what lets you re-point a workload later without touching a code review.
# aicredits_adapter.py
import os
from openai import OpenAI
from llm_core import Completion, LLMAdapter, Message
class AiCreditsAdapter(LLMAdapter):
BASE_URL = 'https://api.aicreditsapi.com/v1'
# The app asks for a tier; the adapter decides which model that means.
TIERS = {
'fast': 'deepseek-v4-flash',
'strong': 'deepseek-v4-pro',
}
def __init__(self, model: str = 'deepseek-v4-flash', api_key: str | None = None):
self.default_model = model
self.client = OpenAI(
base_url=self.BASE_URL,
api_key=api_key or os.environ['AICREDITS_API_KEY'],
)
def complete(self, messages, *, model=None, temperature=0.7, max_tokens=800):
requested = model or self.default_model
resolved = self.TIERS.get(requested, requested)
resp = self.client.chat.completions.create(
model=resolved,
messages=[{'role': m.role, 'content': m.content} for m in messages],
temperature=temperature,
max_tokens=max_tokens,
)
choice = resp.choices[0]
usage = getattr(resp, 'usage', None)
return Completion(
text=choice.message.content or '',
model=resp.model,
input_tokens=getattr(usage, 'prompt_tokens', 0) if usage else 0,
output_tokens=getattr(usage, 'completion_tokens', 0) if usage else 0,
raw=resp.model_dump(),
)
if __name__ == '__main__':
llm = AiCreditsAdapter()
result = llm.complete(
[Message('user', 'Summarize the adapter pattern in two sentences.')],
model='fast',
)
print(result.text)
print(f'{result.model}: {result.input_tokens} in / {result.output_tokens} out')
Step 3 — choose the provider at configuration time
Now the switch is an environment variable. Add a second entry to PROVIDERS, point it at another adapter, and every call site follows automatically. A second OpenAI-compatible vendor can often reuse the same base class with a different base_url and model map; a vendor with a native SDK gets its own class that implements complete() and does the translation there.
# registry.py
import os
from aicredits_adapter import AiCreditsAdapter
from llm_core import LLMAdapter
def _aicredits() -> LLMAdapter:
return AiCreditsAdapter(model=os.getenv('LLM_MODEL', 'deepseek-v4-flash'))
PROVIDERS = {
'aicredits': _aicredits,
# 'second-provider': lambda: OtherAdapter(base_url=..., model_map=...),
}
def get_llm(name: str | None = None) -> LLMAdapter:
key = (name or os.getenv('LLM_PROVIDER', 'aicredits')).lower()
if key not in PROVIDERS:
raise ValueError(f'Unknown provider {key!r}; known: {sorted(PROVIDERS)}')
return PROVIDERS[key]()
# Call site — unchanged forever:
# llm = get_llm()
# answer = llm.complete([Message('user', prompt)], model='strong')
What actually breaks when you switch
The interface stays stable; the semantics underneath do not. These are the differences that bite in practice, and where each one belongs.
| Concept | Where it breaks | Where to fix it |
|---|---|---|
| Model choice | Model IDs differ per vendor and change over time | Map app tiers (fast / strong) to IDs inside the adapter |
| Token accounting | Usage field names and availability vary | Normalize to input_tokens / output_tokens on Completion |
| Finish reasons | Truncation and stop conditions are reported differently | Map to an enum: stop, length, tool_call, other |
| System prompts | Some APIs take system as a separate top-level parameter | Fold it into the messages list inside the adapter |
| Streaming | Incremental chunk shapes differ between SDKs | Expose a stream() method that yields normalized text deltas |
| Errors | Status codes and error bodies vary | Translate into RetryableError / FatalError at the adapter edge |
Where adapters leak — and what to do about it
Streaming and tool calling. Add
stream()andtools=to the interface early, even as stubs. Retrofitting them after ten call sites exist is the rewrite you were trying to avoid.Structured output. Keep JSON schemas in app code and let the adapter own parsing and repair; schema enforcement is not uniform across providers.
Prompt caching. Treat cache hits as an optimization you observe in usage stats, never as behavior your logic depends on. Off-peak requests and cache hits are cheaper, but that is a budgeting detail, not a contract.
Cost control. Log normalized token counts per call site and review them weekly. Current rates live at aicreditsapi.com/pricing — check them there rather than hardcoding assumptions into your docs.
A practical migration checklist
Grep for the vendor SDK import. Every hit outside your adapters directory is a leak to fix.
Replace model string literals with tier names (
fast,strong).Write one golden-prompt test that runs against every registered adapter and asserts response shape, not exact wording.
Log
model, input tokens, output tokens, and latency on every call before you switch, so you have a baseline to compare afterwards.Keep a second provider registered and exercise it monthly — an untested fallback is not a fallback.
If switching providers takes more than changing an environment variable, the abstraction is in the wrong place.
Frequently asked questions
For a 200-line script, yes. For anything with more than a handful of call sites, no — you are already paying the switching cost, just in a different currency. The interface file above is about twenty-five lines.
Yes. AiCredits exposes an OpenAI-compatible API, so you set base_url to https://api.aicreditsapi.com/v1 and keep the same client, streaming, and error types. Only the model names differ: deepseek-v4-flash and deepseek-v4-pro.
Pass model='strong' (or the full model ID) for that call. Pro costs more per call than flash, so reserve it for the requests where flash visibly fails — long reasoning chains, tricky refactors, dense summarization.
Yes. Mirror the interface with an AsyncLLMAdapter built on AsyncOpenAI and the same normalization logic. Keep one interface per style so call sites stay explicit about whether they block.
Some, and that is the point: features with no cross-vendor equivalent should sit behind an optional capability flag (for example supports_tools) rather than being forced into the base interface for everyone.