Single-vendor risk in AI APIs rarely arrives as a dramatic shutdown. It looks like a Tuesday morning where a model you depend on starts returning differently formatted output, or your requests get throttled at the exact hour your traffic peaks, or a payment method gets flagged and every key in your app stops working at once.
The reflex is to sign up for three providers and call it a strategy. That usually produces three SDKs, three prompt dialects, and no real failover path. What actually works is narrower: one interface you own, two or three routes behind it, and a written rule for when each route gets used.
What single-vendor risk actually looks like
Model retirement or silent behavior change — a version you pinned gets deprecated, or its defaults shift under you.
Capacity cliffs — you get rate limited precisely when your product is busiest.
Regional or network failure — the API is healthy, but the path to it isn't, from your region or your users'.
Account and billing risk — a card declines, a verification check stalls, or a policy review freezes access with no notice.
Commercial change — pricing structure, rate-limit tiers, or data-retention terms move in a direction your product can't absorb.
SDK churn — a client library breaks on upgrade and drags your release schedule with it.
Layer 1: one interface you own
Every major provider now exposes an OpenAI-compatible chat completions shape, which means the abstraction you need is small. Keep routes — base URL, key, model name — in configuration, and never import a vendor SDK inside business logic.
AiCredits serves DeepSeek v4 models behind an OpenAI-compatible endpoint, so adding it as a route is a base_url and an api_key swap rather than a rewrite. Routes should be data, not architecture.
The router below tries your primary route first, retries only errors that genuinely warrant a retry, and moves to the next route on auth or malformed-request failures. Set FALLBACK_API_KEY, FALLBACK_BASE_URL and FALLBACK_MODEL only if you have a second route; the script runs fine without them.
import os
import time
import random
from openai import (
OpenAI,
APIConnectionError,
APITimeoutError,
RateLimitError,
InternalServerError,
)
RETRYABLE = (APIConnectionError, APITimeoutError, RateLimitError, InternalServerError)
ATTEMPTS_PER_ROUTE = 2
def build_routes():
routes = []
primary_key = os.environ.get("AICREDITS_API_KEY")
if primary_key:
routes.append({
"name": "aicredits",
"model": "deepseek-v4-flash",
"client": OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key=primary_key,
timeout=30.0,
max_retries=0, # we own the retry loop
),
})
if os.environ.get("FALLBACK_API_KEY"):
routes.append({
"name": "fallback",
"model": os.environ["FALLBACK_MODEL"],
"client": OpenAI(
base_url=os.environ["FALLBACK_BASE_URL"],
api_key=os.environ["FALLBACK_API_KEY"],
timeout=30.0,
max_retries=0,
),
})
if not routes:
raise SystemExit("Set AICREDITS_API_KEY to run this example.")
return routes
ROUTES = build_routes()
def ask(prompt, escalate=False):
last_error = None
for route in ROUTES:
model = route["model"]
if escalate and route["name"] == "aicredits":
model = "deepseek-v4-pro"
for attempt in range(ATTEMPTS_PER_ROUTE):
try:
response = route["client"].chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
)
text = response.choices[0].message.content
print(f"[answered by {route['name']} / {model}]")
return text
except RETRYABLE as exc:
last_error = exc
time.sleep(min(2 ** attempt + random.random(), 8.0))
except Exception as exc:
# Non-retryable (bad request, auth, policy): try the next route.
last_error = exc
break
raise RuntimeError(f"all routes failed: {last_error}")
if __name__ == "__main__":
print(ask("Explain vendor lock-in in two sentences."))
That one printed line — which provider and model answered — is what tells you weeks later whether your failover path is real or theoretical.
Layer 2: tier by capability, not by headcount
Two routes only help if they do different jobs. A workable split: a fast tier for the bulk of traffic (classification, field extraction, summarization, first-pass code review) and an escalation tier for problems that fail the cheap pass.
On the DeepSeek v4 line, that maps to deepseek-v4-flash as the fast default and deepseek-v4-pro when you need stronger reasoning. Pro costs more than flash, so gate it behind a rule rather than a hunch: escalate when the flash response fails a schema check, when input exceeds a length you've measured as unreliable, or when the task is explicitly flagged high-stakes.
The same split doubles as vendor-risk insurance. If fast-tier behavior shifts on one provider, you move that tier to another route without touching the escalation path.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key=os.environ["AICREDITS_API_KEY"],
)
# Stable text first: long, unchanging instructions. Volatile text last: the diff.
# Keeping the prefix byte-identical across calls gives you cache hits, which
# cost less than fresh input on the same model.
REVIEWER_RULES = """
You review Python diffs. Report only real defects: resource leaks,
unhandled exceptions, mutable default arguments, off-by-one errors,
and unsafe deserialization. For each finding output one line:
FILE:LINE | severity | problem | minimal fix. No praise, no summary.
""".strip()
def review(diff, escalate=False):
model = "deepseek-v4-pro" if escalate else "deepseek-v4-flash"
response = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": REVIEWER_RULES},
{"role": "user", "content": f"<diff>\n{diff}\n</diff>"},
],
temperature=0.1,
)
usage = response.usage
print(
f"model={model} "
f"prompt_tokens={usage.prompt_tokens} "
f"completion_tokens={usage.completion_tokens}"
)
return response.choices[0].message.content
if __name__ == "__main__":
sample = "def parse(items=[]):\n items.append(1)\n return items\n"
print(review(sample))
Layer 3: failover policy you can defend
Most multi-provider plans quietly fall apart here, because the retry logic is too eager. Retry connection errors, timeouts, rate limits, and 5xx responses. Do not retry 400s, 401s, or 403s against a second provider — a malformed or unauthorized request fails everywhere, and you may be billed for the attempt.
Set the client timeout shorter than your own request deadline so one stalled provider doesn't consume your whole budget. Add jitter to backoff. Circuit-break a route after a run of consecutive failures and probe it on a timer rather than hammering it.
And log provider plus model on every request. Without that, "which vendor failed?" becomes an argument instead of a query.
| Policy | What it does | Best for | Watch out for |
|---|---|---|---|
| Failover-only | Primary handles everything; backup used on error | Small teams, cost-sensitive workloads | The backup stays cold and untested |
| Tiered escalation | Cheap model first, stronger model on failure or difficulty | High-volume extraction, review, classification | Drifts without an explicit escalation rule |
| Weighted split | Sends a slice of traffic to each route | Comparing quality, smoothing quota limits | Doubles your evaluation surface |
| Dual-run (shadow) | Sends live requests to both, serves one, compares | High-stakes output, migration prep | Extra spend on shadowed traffic |
| Aggregator-only | One key routes across many models | Prototyping, long-tail model access | Your routing rules and uptime are someone else's |
Where aggregators fit — and where they don't
Aggregators like OpenRouter are genuinely good at what they do: one key, one balance, and a wide catalog that includes models you'd never get approved for individually. For prototyping and long-tail coverage, that breadth is hard to beat.
The tradeoff is that an aggregator is still one account, one auth path, and one set of routing decisions that aren't yours. It reduces model risk while leaving provider risk intact. First-party platforms have the deepest surrounding tooling, and if your team already lives in OpenAI's ecosystem, that familiarity has real value you shouldn't throw away.
The pragmatic stack is two paths into the same interface: one you already trust, plus a direct route you control. AiCredits is built for that second slot — DeepSeek v4 credits for international developers, payable by card or PayPal with no Chinese phone number or bank account needed, behind the OpenAI-compatible endpoint you're already calling.
A second provider you've never failed over to isn't redundancy. It's a config file.
A checklist you can finish this week
Move every base URL, key, and model name into environment variables.
Set timeout and max_retries=0 on each client; own the retry loop yourself.
Log provider, model, and token usage on every call.
Write your escalation rule in one sentence and commit it next to the code.
Break the primary key in staging and confirm the fallback actually answers.
Keep prompts provider-agnostic; avoid provider-only parameters in shared paths.
Re-run a fixed evaluation set after any model or route change.
Treat pricing as a routing input, not a price list
Multi-provider also means multi-pricing-shape. What matters is the shape: off-peak requests cost less than peak, cache hits cost less than fresh input, and the stronger tier costs more than the fast one — so your escalation rule is also a spending rule. Compare routes on those axes instead of a single headline rate; current DeepSeek credit rates are listed at aicreditsapi.com/pricing.
If you'd rather not spend tokens on a first pass at all, AiCredits' code linting tools catch a chunk of mechanical defects before any model sees the diff.
FAQ
Not for scale — for continuity. A single route means a single outage, billing problem, or deprecation notice sits between you and downtime. The cost of a second route is one environment variable and a few lines of failover code.
Not on the happy path. The router calls the primary directly and only pays extra time when the primary fails. Keep the abstraction thin: no queue, no extra service hop, no serialization you don't need.
Only fail over on errors that mean no work was done — connection failures, timeouts before a response, 429s, and 5xx. Never silently re-send a request that already streamed a partial answer; make the caller's retry decision explicit instead.
Yes. AiCredits serves deepseek-v4-flash and deepseek-v4-pro at https://api.aicreditsapi.com/v1, so the same client, message format, and streaming code you use elsewhere works unchanged.