Why an OpenAI → DeepSeek migration is mostly a config change
The DeepSeek API speaks the OpenAI wire format. That one fact turns most migrations from a rewrite into a configuration change: if your code already uses the official openai Python or Node SDK, you point base_url at a different host, change the model string, and ship.
The catch is that "OpenAI-compatible" is a claim about request and response shape — not a promise that every parameter, every endpoint, and every edge case behaves identically. In practice, breakages cluster in a handful of predictable places: hardcoded model identifiers, client-side token counting, renamed parameters, structured-output strictness, and assumptions about how many tool calls come back at once.
Credit where it's due: OpenAI's ecosystem is genuinely excellent — mature SDKs, JSON Schema structured outputs, strong evaluation tooling, and a broad model line. DeepSeek's advantage is different. It targets heavy reasoning and coding workloads where volume matters, its automatic context caching makes repeated prefixes cheaper, and off-peak traffic costs less. AiCredits sells DeepSeek API access to international developers who have no Chinese phone number or bank card, payable by card or PayPal. This guide is about getting there without an outage.
Step 1 — Put every provider call behind one module
The highest-leverage move happens before you touch a single prompt. Stop importing the SDK in business logic. Create one module that owns the client, and make everything else import from it. When the provider changes again in six months — and it will — you edit one file.
# llm_client.py — the only module that knows which provider you use.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
def complete(messages, model="deepseek-v4-flash", **params):
return client.chat.completions.create(
model=model,
messages=messages,
**params,
)
def text(messages, **params):
return complete(messages, **params).choices[0].message.content
if __name__ == "__main__":
print(text([{"role": "user", "content": "Say hello in exactly five words."}]))
Step 2 — Probe the surface instead of assuming parity
Compatibility varies by endpoint and by model. Before you rewrite prompts, spend two minutes confirming what actually works in your account. This script tests plain chat, JSON mode, and tool calling, and prints the model IDs your key can reach. Run it against both models — a capability that exists on one is not guaranteed on the other.
# probe.py — find out what the endpoint supports before you rewrite prompts.
import json
from llm_client import client
def probe(model):
out = {"model": model}
try:
r = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": "Reply with the single word: ok"}],
max_tokens=8,
)
out["chat"] = r.choices[0].message.content.strip()
except Exception as e:
out["chat"] = f"{type(e).__name__}: {e}"
try:
r = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": 'Return exactly {"status":"ok"} as JSON.'}],
response_format={"type": "json_object"},
max_tokens=32,
)
out["json_object"] = json.loads(r.choices[0].message.content)
except Exception as e:
out["json_object"] = f"{type(e).__name__}: {e}"
try:
r = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": "What is the weather in Lisbon?"}],
tools=[{
"type": "function",
"function": {
"name": "get_weather",
"description": "Current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}],
max_tokens=64,
)
out["tool_calls"] = bool(r.choices[0].message.tool_calls)
except Exception as e:
out["tool_calls"] = f"{type(e).__name__}: {e}"
return out
if __name__ == "__main__":
print("available models:", [m.id for m in client.models.list().data])
for m in ("deepseek-v4-flash", "deepseek-v4-pro"):
print(json.dumps(probe(m), indent=2))
| Surface | What to check | Migration risk |
|---|---|---|
| Chat completions | messages array, system role, temperature | Low — shape is identical |
| Streaming | chunk.choices[0].delta.content | Low — shape is identical |
| Tool calling | parallel calls, strict schemas, nesting depth | Medium — test your real schemas |
| JSON mode | json_object vs strict json_schema | Medium — validate output yourself |
| Token counting | client-side tokenizers drift from the server | Medium — affects context budgets |
| Embeddings | not every compatible host offers one | Verify before moving RAG |
| Vision / audio | model-dependent | Verify per model |
| Prompt caching | automatic prefix caching | Opportunity, not risk |
| Logprobs, logit_bias | uneven across compatible hosts | Low — drop or feature-detect |
Step 3 — Normalise the parameters that actually changed
Two renames and a handful of optional parameters cause most 400 errors. Newer OpenAI SDKs prefer max_completion_tokens; the compatible chat surface still expects max_tokens. Rather than sprinkling conditionals through your codebase, translate once at the boundary. Parameters that are not uniformly supported should be dropped rather than sent and rejected — but log when you drop them, so you notice if a feature you relied on disappears.
# compat.py — normalise parameters and escalate only when you have to.
from llm_client import complete
DROP = ("logit_bias", "logprobs", "top_logprobs")
def normalise(params):
p = dict(params)
# Newer OpenAI SDKs renamed this; the compatible surface still uses max_tokens.
if "max_completion_tokens" in p:
p["max_tokens"] = p.pop("max_completion_tokens")
# Uneven support across compatible hosts: drop rather than risk a 400.
for key in DROP:
p.pop(key, None)
return p
def complete_with_escalation(messages, validate, **params):
"""Cheap model first; escalate only when the answer fails your check."""
content = ""
for model in ("deepseek-v4-flash", "deepseek-v4-pro"):
resp = complete(messages, model=model, **normalise(params))
content = resp.choices[0].message.content
if validate(content):
return content, model
return content, "deepseek-v4-pro"
if __name__ == "__main__":
answer, used = complete_with_escalation(
[{"role": "user", "content": "Extract the order id: 'order AB-1043 is late'."}],
validate=lambda t: "AB-1043" in t,
temperature=0,
max_tokens=64,
)
print(used, "->", answer)
Step 4 — Keep streaming identical (one caveat)
Streaming is the part people fear most and the part that almost never breaks. The chunk shape is the same: choices[0].delta.content. The one caveat is usage reporting. If your billing or observability layer reads token counts off the final chunk, request them explicitly with stream_options={"include_usage": True} and confirm the server honours it — otherwise fall back to counting on your side.
# stream.py — the delta shape is identical; only usage reporting varies.
from llm_client import client
stream = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "Write a haiku about uptime."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
Step 5 — Replay production prompts before you move traffic
Benchmarks are marketing. Your logs are evidence. Export a few hundred real prompts from production, write a one-line assertion for each, and replay them against the new model at temperature=0. Use expect_any substring checks rather than exact-match, because wording will legitimately differ. If less than a handful fail, your prompts are portable. If a whole category fails, you have found the one prompt template that needs rewriting — cheaply, offline.
# regression.py — replay real production prompts before you move traffic.
# cases.jsonl, one JSON object per line:
# {"prompt": "The box arrived crushed.", "expect_any": ["refund", "replacement"]}
import json
from pathlib import Path
from llm_client import text
def replay(path="cases.jsonl", model="deepseek-v4-flash"):
lines = [l for l in Path(path).read_text().splitlines() if l.strip()]
cases = [json.loads(l) for l in lines]
passed = 0
for i, case in enumerate(cases, 1):
answer = text(
[{"role": "user", "content": case["prompt"]}],
model=model,
temperature=0,
max_tokens=256,
)
ok = any(t.lower() in answer.lower() for t in case["expect_any"])
passed += ok
print(f"{i:>3} {'PASS' if ok else 'FAIL'} {case['prompt'][:60]}")
print(f"\n{passed}/{len(cases)} passed on {model}")
if __name__ == "__main__":
replay()
The five things that actually break
Hardcoded model identifiers. Grep your repo for model strings in configs, fixtures, notebooks, and CI. Anything not routed through your client module is a landmine.
Client-side token counting. Local tokenizers will not match the server exactly. Every place you truncate history to fit a context budget will drift a little. Leave headroom rather than trimming to the edge.
max_tokensvsmax_completion_tokens. One host rejects the other's spelling. Normalise at the boundary.Strict JSON Schema output.
response_format={"type": "json_schema"}withstrict: trueis not universally available. If you getjson_objectonly, treat the model output as untrusted and validate with Pydantic or jsonschema before use.Assumptions about tool calls. Code that reads
message.tool_calls[0]will silently drop calls when the model returns two. Iterate the list, always.Retry logic tuned to one provider. Keep retrying on rate limits and 5xx with backoff, and keep treating 400s as non-retryable — a malformed request will never succeed on attempt two.
Where AiCredits fits
If you are migrating precisely because your OpenAI bill scales with usage and your workload is mostly reasoning and code, AiCredits is worth a look. You get an OpenAI-compatible endpoint at https://api.aicreditsapi.com/v1, two served models — deepseek-v4-flash as the fast default and deepseek-v4-pro when you need more horsepower — and straightforward signup for developers outside China, payable by card or PayPal with no Chinese phone number or bank account required.
Cost control is where it gets interesting. Prompt caching means repeated prefixes (long system prompts, fixed document context) cost less on the second call and beyond, and off-peak traffic is cheaper than peak — so batch jobs scheduled overnight are meaningfully more economical. deepseek-v4-pro costs more than deepseek-v4-flash, which is exactly why the escalation pattern above is worth building: run everything cheap, pay for the strong model only where a validator says the cheap answer was not good enough. Current rates live at aicreditsapi.com/pricing.
Teams that also want automated review of model-generated code can pair this with the AiCredits linting tools — same key, same pipeline.
Rollout and rollback
Do not do a flag day. Read the provider from an environment variable, deploy the client module behind a feature flag, and send a small slice of traffic to the new endpoint while the old one keeps serving the rest. Compare error rates, latency percentiles, and — most importantly — your own quality validators, not vibes. Rollback should be a single env-var change and a redeploy, or a flag flip if you can manage it.
Ship the client module first with the provider still unchanged. Zero behaviour change, all the refactor risk out of the way.
Run the probe and the regression replay in CI so a future SDK upgrade cannot silently break compatibility.
Shadow a percentage of live traffic, log both outputs, and diff them offline rather than in the request path.
Once parity holds for a full traffic cycle, delete the old code path — otherwise it rots.
FAQ
Yes for the core chat completions surface, including streaming and tool calling. Compatibility claims get shakier for optional parameters like logprobs and for strict JSON Schema output, which is why Step 2 probes rather than assumes.
Not with AiCredits. You sign up internationally, top up with a card or PayPal, and get an API key that works with the standard OpenAI SDK.
Start everything on deepseek-v4-flash, since it is the fast default. Add an escalation path to deepseek-v4-pro triggered by your own output validator, so you only pay the premium where quality genuinely demands it.
Usually not for ordinary chat and extraction. You will likely need changes where you depended on strict schema enforcement, on logprobs, or on the model reliably returning exactly one tool call.
Qualitatively: cache hits are cheaper than cache misses, off-peak requests cost less than peak, and deepseek-v4-pro costs more than deepseek-v4-flash. AiCredits publishes current rates at aicreditsapi.com/pricing — check there rather than trusting a stale blog post.
Yes, and you should during rollout. Keep the client module provider-agnostic, drive the choice from an env var or feature flag, and keep the old path alive until you have seen a full traffic cycle at parity.
Migration risk lives in the seams, not the models: hardcoded strings, renamed parameters, and validation you never wrote. Fix the seams first and the switch itself is a one-line change.