Notas / 08
Moving off OpenRouter: an eight-point checklist
Both endpoints speak the OpenAI wire format, so the migration looks like a base URL change and a new key. It is not: model identifiers differ, OpenRouter-specific body fields and headers are meaningless or harmful elsewhere, and features you relied on — per-generation stats, credit queries, provider routing hints — may simply not exist. This article is the checklist that catches those differences before your traffic does. It ships a single script that runs eight checks against any candidate endpoint and prints a pass/fail table, then explains what to do with each failure, including the three mistakes that break migrations in practice.
What actually changes
Four categories, and only the first is obvious. Identity: base URL, key format, and the model string. Schema: most of the payload is standard; a few provider-specific parameters exist and behaviour differs when they are wrong. Auxiliary endpoints: /models, /embeddings, /responses, per-generation statistics, credit balance — support varies wildly. Operational semantics: rate limits, retry hints, error codes, and whether the endpoint streams at all through the hostname you chose.
OpenRouter's model ids are namespaced, typically vendor/model with optional suffixes. A compatible gateway normally uses plain ids such as deepseek-chat, and the platform this article targets publishes exactly three. Carrying an old id across gives you 404 model_not_found on the first request — a clean, immediate failure, which is why model discovery should be your very first check.
The eight checks
#!/usr/bin/env python3
"""gateway_smoke.py — eight checks to run against a candidate endpoint before cutover."""
import json, os, sys, time, urllib.error, urllib.request
BASE = os.environ.get("BASE_URL", "https://api.tokenaimodels.com/v1").rstrip("/")
KEY = os.environ["MODELRY_API_KEY"]
MODEL = os.environ.get("MODEL", "deepseek-chat")
results: list[tuple[str, bool, str]] = []
def post(path: str, payload: dict, headers: dict | None = None):
body = json.dumps(payload).encode()
req = urllib.request.Request(BASE + path, data=body, method="POST")
req.add_header("Authorization", "Bearer " + KEY)
req.add_header("Content-Type", "application/json")
for k, v in (headers or {}).items():
req.add_header(k, v)
t0 = time.monotonic()
try:
resp = urllib.request.urlopen(req, timeout=180)
return resp, time.monotonic() - t0, None
except urllib.error.HTTPError as exc:
return exc, time.monotonic() - t0, exc
def check(name: str, ok: bool, detail: str = "") -> None:
results.append((name, ok, detail))
def get(path: str):
req = urllib.request.Request(BASE + path)
req.add_header("Authorization", "Bearer " + KEY)
return urllib.request.urlopen(req, timeout=60)
# 1. model discovery
try:
catalogue = json.loads(get("/models").read())
ids = [m.get("id") for m in catalogue.get("data", [])]
check("1 models list", MODEL in ids, f"{MODEL} in {ids}")
except Exception as exc:
check("1 models list", False, str(exc))
# 2. blocking completion with usage
resp, dt, err = post("/chat/completions", {
"model": MODEL,
"messages": [{"role": "user", "content": "Reply with the single word: ok"}],
"max_tokens": 16,
})
if err is None:
data = json.loads(resp.read())
usage = data.get("usage") or {}
check("2 completion + usage", bool(usage.get("total_tokens")),
f"{dt:.2f}s usage={usage}")
else:
check("2 completion + usage", False, f"HTTP {err.code}")
# 3. streaming: chunk count and time to first token
try:
resp, dt, err = post("/chat/completions", {
"model": MODEL,
"messages": [{"role": "user", "content": "Count from 1 to 40."}],
"stream": True, "max_tokens": 300,
})
chunks, ttft, usage_seen = 0, None, False
t0 = time.monotonic()
for raw in resp:
line = raw.decode("utf-8", "replace").strip()
if not line.startswith("data:"):
continue
payload = line[5:].strip()
if payload == "[DONE]":
break
obj = json.loads(payload)
if obj.get("usage"):
usage_seen = True
if obj.get("choices"):
chunks += 1
ttft = ttft or time.monotonic() - t0
check("3 streaming", chunks >= 5, f"chunks={chunks} ttft={ttft or 0:.2f}s")
check("4 usage in stream", usage_seen, "usage event with empty choices")
except Exception as exc:
check("3 streaming", False, str(exc))
check("4 usage in stream", False, "skipped")
# 5. tool calling
try:
resp, dt, err = post("/chat/completions", {
"model": MODEL,
"messages": [{"role": "user", "content": "Weather in Osaka?"}],
"tools": [{"type": "function", "function": {
"name": "get_weather", "description": "Current weather",
"parameters": {"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]}}}],
"tool_choice": "auto", "max_tokens": 200,
})
if err is None:
choice = json.loads(resp.read())["choices"][0]
calls = choice["message"].get("tool_calls") or []
parsed = json.loads(calls[0]["function"]["arguments"]) if calls else {}
check("5 tool calls", choice["finish_reason"] == "tool_calls" and bool(parsed),
f"finish={choice['finish_reason']} args={parsed}")
else:
check("5 tool calls", False, f"HTTP {err.code}")
except Exception as exc:
check("5 tool calls", False, str(exc))
# 6. JSON mode
try:
resp, dt, err = post("/chat/completions", {
"model": MODEL,
"messages": [{"role": "system", "content": "Reply with JSON only."},
{"role": "user", "content": "Return {\"ok\": true}"}],
"response_format": {"type": "json_object"}, "max_tokens": 64,
})
if err is None:
content = json.loads(resp.read())["choices"][0]["message"]["content"]
json.loads(content)
check("6 json_object", True, content[:40])
else:
check("6 json_object", False, f"HTTP {err.code}")
except Exception as exc:
check("6 json_object", False, str(exc))
# 7. error envelope on an unknown model
resp, dt, err = post("/chat/completions", {
"model": "no-such-model", "messages": [{"role": "user", "content": "hi"}]})
if err is not None:
try:
body = json.loads(err.read())
shaped = "error" in body and "message" in body["error"]
except Exception:
shaped = False
check("7 error envelope", shaped and err.code == 404, f"HTTP {err.code} shape_ok={shaped}")
else:
check("7 error envelope", False, "unknown model accepted")
# 8. request id header
resp, dt, err = post("/chat/completions", {
"model": MODEL, "messages": [{"role": "user", "content": "ok"}], "max_tokens": 8})
rid = resp.headers.get("x-request-id") if resp is not None else None
check("8 x-request-id", bool(rid), str(rid))
width = max(len(n) for n, _, _ in results)
failed = 0
for name, ok, detail in results:
failed += 0 if ok else 1
print(f"{name:<{width}} {'PASS' if ok else 'FAIL'} {detail}")
print(f"\n{failed} failure(s)")
sys.exit(1 if failed else 0)
Run it as BASE_URL=https://candidate.example/v1 MODELRY_API_KEY=sk-live-... python3 gateway_smoke.py. It exits non-zero on any FAIL, which makes it usable as a CI gate and as an acceptance test before you flip DNS or an environment variable.
Failure 1: an OpenRouter model id carried across
deepseek/deepseek-chat, deepseek/deepseek-chat:free, anthropic/claude-3.5-sonnet — none of these resolve on a platform that sells two DeepSeek tiers under plain ids. The error is 404 invalid_request_error with code model_not_found, and the fix is to read GET /v1/models at boot and fail fast if your configured id is absent. Do not hardcode a translation table: the catalogue is the contract, and a model listed in documentation but missing from /v1/models currently has no capacity, so the only safe assertion is against the live response.
Failure 2: provider-routing fields forwarded into a 400
OpenRouter accepts body fields and headers that carry routing intent — provider preference, transforms, fallbacks, and the attribution headers used for its leaderboards. A gateway that forwards unknown body fields verbatim to the upstream provider will hand that payload to DeepSeek, which rejects it with a 400 whose message names the offending field. Two habits prevent it: keep provider-specific parameters in one configuration object so they can be deleted in a single place, and treat any 400 on a field you did not knowingly send as a migration artefact rather than a model problem.
Failure 3: depending on an endpoint that is not there
Per-generation statistics, a credits-balance query, an embeddings route, /models/{id} lookups, and the responses API are all common OpenRouter-adjacent surface that a smaller gateway may not implement. Check before you cut over, not after. The platform used here documents its exclusions explicitly — no /embeddings, no /responses, no images, audio, files, batches or assistants, no /models/{id} (filter the list instead), no Anthropic-shaped /messages. If your app calls one of those, it needs a plan: keep a second vendor for embeddings, or move that path to a service that offers it. A 404 in production is an outage, even when the 404 is documented.
What to watch when you speak to a gateway instead of OpenAI
Three gateway-specific properties decide how much work "compatibility" really is. Error normalisation: 429, 502 and 503 are retryable, 400, 401, 402, 403, 404 and 451 are not, and a prepaid gateway adds 402 codes that no OpenAI client maps by default — branch on status first, then code. Failover semantics: where a second channel is configured, a request that fails before the first token may be retried on another channel for the same model, and the model is never silently swapped for a different one, so a 503 no_channel is an honest capacity answer rather than a reason to fall back to a different model in your own code. Billing model: charges are pre-authorised against a prepaid balance and settled against the provider's reported usage, which means a request can fail with 402 for reasons of *estimate* rather than price, and a stream interrupted after output started is billed at an estimate. Read the usage log rather than inferring it from the response body.
Start the checklist at https://tokenaimodels.com — run gateway_smoke.py against https://api.tokenaimodels.com/v1 before you point production at it, and keep it in CI so the next endpoint change is a test result instead of an incident.
A Modelry opera uma plataforma que serve modelos DeepSeek atrás de um único endpoint HTTP, com créditos pré-pagos e impostos tratados pelo merchant of record no checkout, além de uma política de retenção de dados documentada. Comece com $0.50 de crédito de teste: criar uma chave.