Notas / 13
Point any OpenAI SDK at Modelry in two lines
Repointing an OpenAI client at another endpoint is sold as a one-line change, and it is — until the first request comes back with a body shape you did not expect. This is the two lines that actually change, the same client in Python, Node and curl, and the five responses that account for most first-day failures: a stale OPENAI_BASE_URL that overrides your code, a model id that does not exist, a 402 with two different meanings, a 429 that tells you when to come back, and a stream whose last event has no choices. Every error body below is copied from what the gateway returns, so you can match it against your logs.
Two lines, and only two
An OpenAI-compatible endpoint changes the host and the key. The path stays /v1/chat/completions, the request body is the same JSON, and the response is the same object. If your client works against OpenAI, it works here after two values change:
base_url = "https://api.tokenaimodels.com/v1"
api_key = "your key"
Two things are worth knowing before you paste them anywhere. First, the host is the api. subdomain. Our documentation describes the apex domain as CDN-served and the api. host as the direct connection, so long-running streams belong on api. — that is a statement about our own setup, not a benchmark. Second, the key goes in an Authorization: Bearer header. We read that header and nothing else, so a client that sends only x-api-key (the Anthropic convention) authenticates against nothing and gets a 401 that looks like a bad key.
Which model ids exist
Do not guess, and do not copy a model id from a blog post — including this one. Ask the endpoint:
curl -s https://api.tokenaimodels.com/v1/models \
-H "Authorization: Bearer $MODELRY_KEY" | jq -r '.data[].id'
The list contains only models with a live upstream channel, which is why it is the authority rather than the price table. Each entry carries the context window, the output ceiling and the current rate:
{
"object": "list",
"data": [
{
"id": "deepseek-chat",
"object": "model",
"owned_by": "modelry",
"context_length": 1000000,
"max_output_tokens": 384000,
"pricing": {
"currency": "usd",
"unit": "per_1m_tokens",
"offpeak": { "input": 0.25, "cached_input": 0.006, "output": 1.45 },
"peak": { "input": 0.5, "cached_input": 0.012, "output": 2.9 },
"peak_hours_utc": ["01:00-04:00", "06:00-10:00"],
"peak_days": "Mon-Fri"
}
}
]
}
Those numbers are illustrative of the field layout; the response is the number, and /pricing is where the rates are explained. Fetch it instead of trusting a copy.
Python, unchanged
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.tokenaimodels.com/v1",
api_key=os.environ["MODELRY_KEY"],
timeout=180.0, # read timeout, not just connect
max_retries=0, # see failure #1 before you paper over it
)
resp = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": "List three causes of a truncated SSE stream."}],
max_tokens=400,
)
print(resp.choices[0].message.content)
print(resp.usage) # prompt_tokens, completion_tokens, cached tokens
Nothing else changes: no new import, no adapter class, no response wrapper.
Node and TypeScript
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.tokenaimodels.com/v1",
apiKey: process.env.MODELRY_KEY!,
timeout: 120_000,
maxRetries: 0,
});
const resp = await client.chat.completions.create({
model: "deepseek-chat",
messages: [{ role: "user", content: "One sentence on prompt caching." }],
max_tokens: 200,
});
Note the property is baseURL with a capital URL in SDK v4, and the SDK also reads OPENAI_BASE_URL from the environment — which is the next failure on this list.
curl, when you want the raw bytes
curl -sS https://api.tokenaimodels.com/v1/chat/completions \
-H "Authorization: Bearer $MODELRY_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"deepseek-chat","messages":[{"role":"user","content":"hi"}],"max_tokens":20}'
Failure 1: a stale environment variable wins over your code
Both official SDKs read OPENAI_BASE_URL and OPENAI_API_KEY from the environment when the constructor does not receive them. A leftover export OPENAI_BASE_URL=https://api.openai.com/v1 in a shell profile, a Dockerfile ENV, or a CI secret silently wins: your key travels to the wrong service, and the 401 blames the key.
import os
print("OPENAI_BASE_URL =", os.environ.get("OPENAI_BASE_URL", "<unset>"))
print("key present =", bool(os.environ.get("MODELRY_KEY")))
Run that before anything else when a client "works locally but not in CI". Pass both values explicitly and the class of bug disappears.
Failure 2: the model id does not exist
Our 404 is explicit about where to look:
HTTP/1.1 404 Not Found
{"error":{"message":"Model 'deepseek-v4' does not exist. GET /v1/models for the list.","type":"invalid_request_error","code":"model_not_found"}}
The envelope is always {"error":{"message","type","code"}}. type is the class, code is the specific reason, and they are not always the same string — code is what you branch on.
Failure 3: a 402 that means two different things
A 402 is a pre-authorisation failure, not a rate limit and not a plan limit, and there are two variants:
HTTP/1.1 402 Payment Required
{"error":{"message":"Insufficient balance. Top up to continue.","type":"insufficient_quota","code":"insufficient_balance"}}
{"error":{"message":"Key quota exhausted.","type":"insufficient_quota","code":"insufficient_quota"}}
insufficient_balance is the account; insufficient_quota is this key's own cap. Both are fixed by a human or a dashboard, so retrying is pointless — but note that the request is pre-authorised before it reaches a model, sized from the body you sent and your max_tokens. A large max_tokens on a nearly empty balance is therefore rejected even if the answer would have been cheap. Lower max_tokens to get under the line.
Failure 4: a 429 that tells you when to come back
HTTP/1.1 429 Too Many Requests
retry-after: 37
{"error":{"message":"Rate limit exceeded.","type":"rate_limit_error","code":"rate_limit_exceeded"}}
The window is a fixed minute, not a rolling one, and retry-after carries the seconds left in the current window. Honour the header: exponential backoff with jitter, applied to a fixed window, retries into the same wall on purpose. The limiter is per key, so two keys double the ceiling — which is also why client-side retry storms are worth avoiding rather than tuning.
Failure 5: the last stream event has no choices
With stream_options: {"include_usage": true} the final event before [DONE] carries usage and an empty choices array. Code written against examples that put usage on the last content chunk indexes event.choices[0] unconditionally and dies with IndexError: list index out of range — after printing the whole answer, which makes the traceback look like a first-byte problem.
for event in stream:
if not event.choices: # usage-only event
usage = event.usage
continue
piece = event.choices[0].delta.content
if not piece:
continue
Guard the empty case, and treat the reported usage as authoritative: settle your own accounting against it, not against an estimate.
A five-minute check worth keeping
Four requests in CI, against a fixed model id rather than a floating alias, catch nearly all of this class of breakage: a non-streaming call that returns 200 and non-empty content; the same call with stream: true that returns more than one chunk; GET /v1/models containing the id you hardcoded; and a request with a deliberately wrong key that must return 401 with type: authentication_error. When one fails after an upgrade, diff the raw body before touching the SDK — the envelope is stable, the optional fields inside it are not.
Create a key at /signup, point the client at https://api.tokenaimodels.com/v1, and the first of these four checks will tell you whether you are talking to the right service. Rates for every model live on /pricing; the full reference is in /docs.
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.