Portability is the entire promise of an OpenAI-compatible API. You write against one client, one request shape, one streaming format, and swapping vendors becomes an environment variable. In practice, teams attempt the swap once, watch a handful of integration tests fail, and quietly go back to hardcoding a vendor.
The gap is rarely the API shape. It is everything around it: model identifiers, tool-calling reliability, streaming edge cases, error semantics, and the assumptions baked into your retry logic. Below is what genuinely travels across gateways, what does not, and how to structure a client so a provider swap is a config change rather than a sprint.
What an OpenAI-compatible endpoint actually guarantees
The /v1/chat/completions contract is real and worth relying on. You send messages, you get back choices[0].message.content. Streaming arrives as server-sent events carrying delta objects. Tool definitions use the same JSON Schema shape. That is why the official OpenAI SDK works unchanged against a long list of gateways.
What is not portable is the semantics underneath. Two gateways can both accept response_format={'type': 'json_object'} and disagree about whether that actually constrains decoding or merely nudges the model. Both can accept tools and disagree about how reliably a call is emitted, and how well the arguments are populated. Both can return HTTP 429, but only one might include a Retry-After header. Compatibility is a spectrum, not a boolean.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
response = client.chat.completions.create(
model='deepseek-v4-flash',
messages=[
{'role': 'system', 'content': 'You are a terse code reviewer.'},
{'role': 'user', 'content': 'Name three common causes of flaky integration tests.'},
],
temperature=0.3,
max_tokens=300,
)
print(response.choices[0].message.content)
print(response.usage)
Run a compatibility smoke test before you migrate
Do not evaluate a new gateway by reading its docs. Evaluate it by running the four calls your application actually depends on. This script exercises chat, streaming, tool calling, and JSON mode against any OpenAI-compatible base URL, and it fails loudly when a surface is only half-implemented.
import json
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
MODEL = 'deepseek-v4-flash'
def check(name, fn):
try:
fn()
print(f'PASS {name}')
except Exception as exc:
print(f'FAIL {name}: {type(exc).__name__}: {exc}')
def basic_chat():
client.chat.completions.create(
model=MODEL,
messages=[{'role': 'user', 'content': 'ping'}],
max_tokens=8,
)
def streaming_deltas():
stream = client.chat.completions.create(
model=MODEL,
messages=[{'role': 'user', 'content': 'Count from one to five.'}],
stream=True,
max_tokens=32,
)
chunks = [c for c in stream if c.choices and c.choices[0].delta.content]
assert chunks, 'no content deltas received'
def tool_calling():
result = client.chat.completions.create(
model=MODEL,
messages=[{'role': 'user', 'content': 'What is the weather in Lisbon? Use the tool.'}],
tools=[{
'type': 'function',
'function': {
'name': 'get_weather',
'description': 'Get the current weather for a city',
'parameters': {
'type': 'object',
'properties': {'city': {'type': 'string'}},
'required': ['city'],
},
},
}],
max_tokens=64,
)
message = result.choices[0].message
assert message.tool_calls, 'model did not emit a tool call'
args = json.loads(message.tool_calls[0].function.arguments)
assert 'city' in args, 'tool arguments missing the expected field'
def json_mode():
result = client.chat.completions.create(
model=MODEL,
messages=[{'role': 'user', 'content': 'Return a JSON object with one key named ok set to true.'}],
response_format={'type': 'json_object'},
max_tokens=32,
)
json.loads(result.choices[0].message.content)
for name, fn in [
('basic chat', basic_chat),
('streaming deltas', streaming_deltas),
('tool calling', tool_calling),
('json mode', json_mode),
]:
check(name, fn)
Five things that break portability anyway
Model identifiers are never portable.
deepseek-v4-flashanddeepseek-v4-proare real, callable names on AiCredits, but no naming convention spans vendors. Treat the model string as configuration, never as a literal in business logic.Context and tokenization differ. A prompt that fits comfortably in one provider's window may be silently truncated by another, so validate prompt length against the target model rather than the one you developed against.
Tool-calling quality varies more than the schema. Validate
tool_calls[0].function.argumentsbefore your code trusts it, because a malformed argument string is a runtime error, not a schema violation.Streaming edge cases differ. Some gateways emit a role-only first delta, a final usage chunk, or keep-alive comments; others do not. Never assume the last chunk carries usage.
Error semantics drift. Retry on 429 and 5xx, respect
Retry-Afterwhen present, and fall back to exponential backoff when it is not offered.
Make the provider a configuration value
The cleanest portability pattern is a small registry that maps a provider name to a base URL, an environment variable holding the key, and a default model. Everything above that layer speaks only in terms of tasks and messages, never in terms of vendors.
from __future__ import annotations
import os
from dataclasses import dataclass
from openai import OpenAI
@dataclass(frozen=True)
class Endpoint:
base_url: str
api_key_env: str
default_model: str
ENDPOINTS = {
'aicredits': Endpoint(
base_url='https://api.aicreditsapi.com/v1',
api_key_env='AICREDITS_API_KEY',
default_model='deepseek-v4-flash',
),
# Any other OpenAI-compatible server you run or subscribe to.
'local': Endpoint(
base_url='http://localhost:11434/v1',
api_key_env='LOCAL_API_KEY',
default_model='whatever-your-local-server-serves',
),
}
def build_client(provider: str | None = None):
name = provider or os.environ.get('LLM_PROVIDER', 'aicredits')
endpoint = ENDPOINTS[name]
api_key = os.environ.get(endpoint.api_key_env)
if not api_key and name != 'local':
raise RuntimeError(f'Missing {endpoint.api_key_env} for provider {name!r}')
client = OpenAI(base_url=endpoint.base_url, api_key=api_key or 'not-needed')
return client, endpoint.default_model
if __name__ == '__main__':
client, model = build_client()
reply = client.chat.completions.create(
model=model,
messages=[{'role': 'user', 'content': 'Say hello in five words.'}],
)
print(reply.choices[0].message.content)
Retries and error semantics are where swaps fail
Most failed migrations are not schema failures, they are taxonomy failures. The OpenAI SDK raises APIStatusError for HTTP responses and APIConnectionError for transport problems, and the two need different handling. Retry only on codes that can plausibly succeed later, and never retry a 400 by backing off — it will fail identically four times.
import os
import time
from openai import OpenAI, APIConnectionError, APIStatusError
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
RETRYABLE = {408, 409, 429, 500, 502, 503, 504}
def complete(messages, model='deepseek-v4-flash', attempts=4, **kwargs):
last_error = None
for attempt in range(attempts):
try:
response = client.chat.completions.create(
model=model, messages=messages, **kwargs
)
return response.choices[0].message.content
except APIStatusError as exc:
last_error = exc
if exc.status_code not in RETRYABLE:
raise
except APIConnectionError as exc:
last_error = exc
time.sleep(2 ** attempt)
raise RuntimeError(f'All {attempts} attempts failed') from last_error
print(complete([{'role': 'user', 'content': 'Explain idempotency keys in one sentence.'}]))
Route by task, not by vendor
Once the provider is a config value, the interesting decision becomes model selection. Use the fast default for the high-volume, low-ambiguity work — classification, extraction, summarisation, formatting — and reserve the stronger model for tasks where a wrong answer costs more than the tokens do: refactors, architecture reviews, multi-step reasoning over your own codebase. Pro costs more than flash, and cache hits and off-peak windows cost less than either, so a task-level map keeps spend aligned with value instead of with habit.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
MODEL_BY_TASK = {
'classify': 'deepseek-v4-flash',
'extract': 'deepseek-v4-flash',
'summarize': 'deepseek-v4-flash',
'refactor': 'deepseek-v4-pro',
'architecture_review': 'deepseek-v4-pro',
}
def run_task(task: str, prompt: str) -> str:
model = MODEL_BY_TASK.get(task, 'deepseek-v4-flash')
response = client.chat.completions.create(
model=model,
messages=[{'role': 'user', 'content': prompt}],
)
return response.choices[0].message.content
print(run_task('summarize', 'Summarize the tradeoffs of eventual consistency in two sentences.'))
Compatibility surface, at a glance
| Compatibility surface | Standardised across gateways | What still leaks through |
|---|---|---|
| Chat completions (messages, temperature, max_tokens) | Yes — this is the core contract | Unsupported sampling parameters may be ignored silently |
| Streaming (stream=True, SSE deltas) | Yes — chunk shape matches | Keep-alive comments and final usage chunks vary |
| Tool and function calling | Shape matches | Argument quality and parallel-call support differ |
| Structured output (response_format) | json_object is widely supported | json_schema support and strictness differ |
| Usage and token accounting | usage object is present | Cached-token accounting and granularity differ |
| Error semantics | HTTP status codes are broadly consistent | 429 versus 503 for overload, and Retry-After presence, vary |
What this looks like in practice
If you are building outside mainland China and want DeepSeek models behind an OpenAI-compatible endpoint, AiCredits exposes deepseek-v4-flash and deepseek-v4-pro at https://api.aicreditsapi.com/v1. You top up with a card or PayPal, and you do not need a Chinese phone number or bank account to get a key — which is the practical blocker for a lot of international teams evaluating DeepSeek. Because the endpoint speaks the standard protocol, everything above works as written: the same SDK, the same streaming parser, the same tool-call validator.
Pricing is usage-based and qualitative rather than flat: flash is the cheaper default, pro costs more per token, cache hits on repeated prefixes reduce spend, and off-peak traffic is cheaper than peak. Check aicreditsapi.com/pricing for current rates before you size a budget, since published numbers move faster than blog posts do.
Swap the base URL and the model string, not the code. Everything else — retries, validation, task routing — should already be provider-agnostic before you need it to be.
Frequently asked questions
For the request and response shape, yes. For behaviour, not entirely. Expect to re-verify streaming boundaries, tool-call argument quality, JSON-mode strictness, and error codes. The smoke test above takes under a minute and surfaces all four.
No. Install the official openai package, point base_url at an OpenAI-compatible endpoint, and change the model string. The client, retry structure, and streaming loop stay the same.
Keep model identifiers in one module-level mapping from task to model, and read the provider from an environment variable at startup. Business logic should never contain a vendor string, only a task name.
Flash is the right default for classification, extraction, summarisation, and any high-volume loop where a slightly weaker answer is still acceptable. Pro costs more and is worth it for refactors, architecture review, and multi-step reasoning where a wrong answer costs more than the tokens.
Treat 429 and 5xx as retryable with exponential backoff, honour Retry-After when the response includes it, and treat 4xx client errors as permanent. Keep the retry budget in one wrapper so switching providers does not mean rewriting retry logic in every call site.
Yes, if that server exposes an OpenAI-compatible endpoint. Add it to the endpoint registry with its own base URL and a placeholder API key, then select it with the LLM_PROVIDER environment variable.