API reference
One endpoint for DeepSeek and other frontier Chinese models. Point any official SDK at the base URL below, authenticate with a Modelry key, and switch models by changing one string.
Overview
Modelry is a managed inference API platform. You send OpenAI Chat Completions requests to one base URL; we route each request to the model provider, meter the token counts the provider reports, and debit your usage credits. We are your contracting party and your single point of support — the model providers are our suppliers, not your vendors, and you have no direct claim against them.
What that gives you:
- One integration. Same request and response schema as OpenAI, so existing SDKs and frameworks work after you change the base URL, the key and the model id.
- One error format. Provider-specific payloads are normalised into OpenAI's
{"error":{"message","type","code"}}shape, so your retry logic only has to understand one contract. - Usage credits, metered per request. No subscription required. Every call is pre-authorised against your balance and settled against the provider's reported usage.
- Failover before the first token. If a provider channel fails while nothing has been produced, the request is retried on the next channel for the same model. Your model is never silently swapped for a cheaper one.
This page is the full reference. If you want a five-minute integration, read Quickstart and Errors. The rest is what you need when something breaks in production.
Quickstart
- Create an account. Sign up at /signup and verify the email address. Signup credit is issued on verification; calling the API from an unverified account returns
403 email_unverified. - Create a key. Dashboard → API keys → New key. The plaintext is shown once — only a SHA-256 hash is stored, so a lost key cannot be recovered. Rotate instead of hunting.
- Call the API. Export the key as
MODELRY_API_KEYand run any snippet below.
curl https://api.tokenaimodels.com/v1/chat/completions \
-H "Authorization: Bearer $MODELRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-chat",
"messages": [
{"role": "system", "content": "You are a terse assistant."},
{"role": "user", "content": "Explain what an API gateway does in one sentence."}
],
"max_tokens": 300,
"temperature": 0.7
}'A successful call returns HTTP 200 with choices[0].message.content and a usage block. The three failures you will actually hit on day one: 401 (key wrong or revoked), 402 (balance cannot cover the pre-authorisation), 404 (model id not in the catalogue — call GET /v1/models).
What we ask for. We do not ask you for identity documents to open an account. Any identity or fraud checks required for a payment are carried out by Creem, our merchant of record, at its checkout.
Authentication
Every request carries a bearer token. Keys are account-scoped, not project-scoped: one account can hold many keys, and each key can be restricted independently.
- Key format:
sk-live-followed by 32 URL-safe characters. The first 12 characters are stored as an identifier so you can tell keys apart in the dashboard. - Revocation takes effect within 20 seconds. Successful authentications are cached briefly, so a revoked key can still work for up to 20 seconds. Build for that window instead of assuming instant cutoff.
- Per-key controls: allowed model list, RPM override, spend cap, and expiry date. A key with an allow-list rejects other models with
403 permission_error. - Rotation: create the new key, deploy it, confirm traffic, then revoke the old one. The 20-second cache makes overlapping keys safe.
- Never ship a key in a client. Mobile apps and browser bundles are extractable. Proxy through your own backend and keep the key server-side.
Keys are scoped to your account balance, not to a project. If you need per-customer cost isolation, issue one key per customer with a spend cap rather than one shared key.
Base URL & endpoints
Use https://api.tokenaimodels.com/v1 — the api subdomain, not the apex domain. The apex host is served through a CDN that may buffer responses; the API host is a direct connection and guarantees token-by-token streaming.
Not implemented
The surface is deliberately small. These OpenAI endpoints do not exist here and return 404 — plan around them rather than discovering them in production:
Need embeddings or an Anthropic-shaped API? Tell us — routing is per model, and the roadmap follows demand.
Models
Model ids are stable strings. Capacity, context length and price can differ between them, so treat the table below as the contract and GET /v1/models as the live view.
USD per 1M tokens. Upper figure = off-peak, lower line = peak.
What each model is for
- deepseek-chat — the default. Lowest cost per token, long context. Reasoning is disabled by default (see Reasoning models); thousands of chat, RAG and code-completion workloads run here.
- deepseek-reasoner — the reasoning tier. It thinks before it answers, costs roughly four to five times more per token, and is worth it only for hard multi-step problems, maths, and gnarly refactors.
GET /v1/models only returns models that currently have a live upstream channel. A model listed here but absent from that response has no capacity right now; calling it returns 503 no_channel.
USD per 1M tokens. Upper figure = off-peak, lower line = peak.
What each model is for
- deepseek-chat — the default. Lowest cost per token, long context. Reasoning is disabled by default (see Reasoning models); thousands of chat, RAG and code-completion workloads run here.
- deepseek-reasoner — the reasoning tier. It thinks before it answers, costs roughly four to five times more per token, and is worth it only for hard multi-step problems, maths, and gnarly refactors.
GET /v1/models only returns models that currently have a live upstream channel. A model listed here but absent from that response has no capacity right now; calling it returns 503 no_channel.
Create a completion
POST /v1/chat/completions follows the OpenAI schema. Unknown fields are forwarded to the upstream provider verbatim, so provider-specific parameters usually work — if the provider rejects one, its 400 is returned to you.
deepseek-chat and you get 384,000. Send a bad model and you get 404 instead.Response
Standard Chat Completions object: id, object, created, model, choices[], usage. Every response also carries an x-request-id header; quote it in support requests — it is the key we use to trace a request through the gateway.
Message formats
Messages use OpenAI's role model. Three roles are generally useful: system, user, assistant; tool appears only after a tool call.
Text only, for now
Image, audio and file parts are not accepted by the current upstream models. A content array containing an image part is forwarded and rejected with a 400 from the provider. If you need vision, keep that workload on a provider that supports it.
Context and truncation
There is no server-side conversation memory: you send the whole history each time, and you are billed for the whole history each time. When the history exceeds the model context, the provider returns a 400 — we do not silently truncate, because silent truncation produces answers that look right and are wrong.
Streaming
Set stream: true to receive server-sent events over a single HTTP response. Chunks are OpenAI-shaped; the stream ends with data: [DONE].
stream = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": "Write two haiku about latency."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)- Usage arrives in the last content chunk. We inject
stream_options:{"include_usage":true}, so the final data event before[DONE]carries ausageblock and an emptychoicesarray. Code that assumeschoices[0]always exists will throw on that last event — guard it. - Keep-alive is silence. We do not send comment lines. Set client idle timeouts well above your expected time-to-first-token; long reasoning requests can go quiet for tens of seconds before the first delta.
- No buffering proxies. If you put your own CDN or nginx in front, disable response buffering (
proxy_buffering off), otherwise tokens arrive in bursts. - Retry only before the first token. Once output has started, a retry would duplicate text. Treat a mid-stream disconnect as a failed request and charge it against your own budget.
Reasoning models
deepseek-reasoner produces a reasoning trace before the answer. We preserve it rather than stripping it, because it is often the most useful part of the response when debugging an agent.
resp = client.chat.completions.create(
model="deepseek-reasoner",
messages=[{"role": "user", "content": "Prove that the square root of 2 is irrational."}],
max_tokens=8000,
extra_body={"reasoning_effort": "medium"},
)
choice = resp.choices[0].message
# reasoning trace, when the provider returns it
print((choice.model_extra or {}).get("reasoning_content", ""))
print(choice.content)- Where it lives. The trace is returned as
reasoning_contentalongsidecontentand streams asdelta.reasoning_content. The OpenAI SDKs do not type that field — read it from the raw object (Python:model_extra; Node: cast toany). - Budget.
max_tokenscovers thinking plus answer. A hard question with a 2,000-token budget can spend everything on reasoning and return an empty answer. Give reasoner calls at least 4,000, and checkfinish_reason === "length". - Effort. We default
reasoning_efforttomedium. Going tohighraises both latency and cost; going tolowis often enough for classification and extraction. Ondeepseek-reasonerthe medium default adds a fixed input overhead of about 80 tokens to every request, independent of your prompt length; passinglowremoves it. A value you send overrides ours — the merge order is our per-model defaults, then your body, then the fields we pin. - Cost. Reasoner tokens are priced four to five times higher than
deepseek-chat. Route by task difficulty instead of defaulting everything to the expensive model.
deepseek-chat ships with thinking switched off. If you want the fast model to reason, pass thinking:{"type":"enabled"} yourself — and expect both the bill and the time-to-first-token to rise.
Tool calling
Function calling follows the OpenAI contract: you declare tools, the model returns tool_calls, you execute them, then send results back as tool messages. Availability depends on the model; the DeepSeek tiers support it.
{
"model": "deepseek-chat",
"messages": [{"role": "user", "content": "What is the weather in Osaka right now?"}],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
}
],
"tool_choice": "auto"
}
# assistant reply (no content, one tool call)
{
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call_abc123",
"type": "function",
"function": {"name": "get_weather", "arguments": "{\"city\":\"Osaka\"}"}
}]
},
"finish_reason": "tool_calls"
}]
}
# then append the tool result and call again
{"role": "tool", "tool_call_id": "call_abc123", "content": "{\"temp_c\":14,\"sky\":\"clear\"}"}- The loop is yours: the model never executes a function. Append the assistant message containing
tool_calls, then onetoolmessage per call, then call the API again. finish_reason: "tool_calls"means the turn ended waiting for a result, not that it failed.- Streaming tool calls arrive as fragments: accumulate
delta.tool_calls[i].function.argumentsby index and parse the JSON once at the end. Parsing each fragment is the most common integration bug here. - Tool schemas are billed as input tokens. Large schemas sent on every turn are a real cost; trim descriptions or move stable definitions into the system prompt so they can be cached.
Structured output
JSON mode is available through response_format:{"type":"json_object"}. JSON Schema mode is not implemented.
resp = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "Reply with JSON only."},
{"role": "user", "content": "Extract the order record number and total as JSON: OR-2026-0042, USD 128.40"},
],
response_format={"type": "json_object"},
)
print(resp.choices[0].message.content) # {"order_record":"OR-2026-0042","total":128.4}- The provider requires the word JSON in the prompt when JSON mode is on. A request without it can be rejected or produce prose.
- JSON mode guarantees parseable JSON, not a schema. Validate the object on your side; missing keys are a normal outcome.
- For strict shapes, put the schema in the system prompt and validate with a library such as zod or pydantic, then retry once on validation failure.
Prompt caching
DeepSeek tiers cache prompt prefixes automatically — there is no cache API to call and nothing to configure. When a prefix hits, those tokens bill at the cached-input rate instead of the input rate, which is roughly 30 times cheaper on deepseek-chat.
- How you observe it.
usage.prompt_cache_hit_tokens(orusage.prompt_tokens_details.cached_tokens, depending on the provider) tells you how many prompt tokens were served from cache. We accept either field and bill accordingly. - What makes a hit. A stable prefix: same system prompt, same tool schemas, same document ordering. Changing the first bytes invalidates everything after them.
- The classic mistake. Putting a timestamp, request id, user name or random few-shot example at the top of the prompt. Move volatile content to the end and cache hits jump from 0% to most of the prompt.
- Chat is cache-hostile. A conversation that grows at the end keeps a stable prefix and caches well; one that rewrites history does not.
Pricing
Prices are per 1M tokens in US dollars and split three ways: uncached input, cached input, output. Input and output are priced separately because they cost us separately.
Two rates for the same model. deepseek-chat-lite runs the exact same DeepSeek-V4.1-Flash weights with the same 1M context as deepseek-chat, at a lower price. Same endpoint, same request shape, same metering — pick it for higher-volume, lower-cost workloads.
Peak and off-peak. Model providers raise prices during their peak windows. We pass that through in full: on the DeepSeek tiers, peak is exactly twice the off-peak rate. The rate applied is the one in effect when your request arrives at the gateway, not when the stream finishes.
The local columns use fixed offsets — EST (UTC−5) and CET (UTC+1) — and do not follow daylight saving: during EDT and CEST the local clock reads one hour later than shown.
How a charge is computed
cost = uncached_input × in + cached_input × cached + output × out, each term divided by 1M and the total rounded up to one micro-dollar ($0.000001). No per-request fee, no minimum, no rounding to cents.
Worked example
deepseek-chat, off-peak, 12,000 prompt tokens of which 8,000 hit cache, 800 output tokens:
- 4,000 uncached input × $0.25 / 1M = $0.001000
- 8,000 cached input × $0.006 / 1M = $0.000048
- 800 output × $1.45 / 1M = $0.001160
- Total $0.002208 — debited as 2,208 micro-dollars.
The same request inside a peak window costs $0.004416. That 100% swing is why the pre-authorisation, not the price list, is what protects you from surprise balances.
Usage & metering
Billing has three steps per request. Knowing them explains every number you see in the dashboard.
- Pre-authorise. Before contacting the provider we estimate the cost from the prompt size and your
max_tokens, add a 15% cushion, and freeze that amount. Ifbalance − frozenis smaller, the request fails with402 insufficient_balanceand never reaches the provider. - Forward and meter. The request runs against the selected channel, and the provider's
usageis the authority. Cache-hit tokens are billed at the cached rate. - Settle. The freeze is released and the actual cost is debited in one transaction, writing a ledger row and a usage row. Freezing more than the final cost is normal; the difference is returned automatically.
Estimated rows are flagged in dashboard → usage so you can audit them. If a model habitually reports estimated, tell us — it means the provider stopped returning usage and we should be reading a different field.
Frozen amounts are never left behind: an orphan sweep runs on a schedule and releases any hold whose process died mid-request.
Statements & tax
Every payment — top-up — appears on dashboard → statements with a reference number. The invoice itself is issued and emailed by Creem, the merchant of record, and is also available in the Creem customer portal; it carries the seller registration details your finance team needs for a filing. Amounts are in USD.
- Tax and who handles it. Payment is handled by Creem (Armitage Labs OÜ, Estonia), the merchant of record. You buy from Creem, not from us. Any VAT or sales tax is calculated from the billing address you enter at the Creem checkout, and Creem charges, collects and remits it. EU business customers enter a VAT identification number on that same checkout page; with a valid number Creem charges no VAT and you account for it under reverse charge. Creem emails a payment confirmation and an invoice, and both are also available in the Creem customer portal. Refunds and credit notes come from Creem too.
- What this dashboard is not. The statements page in this dashboard is our own record of payments and credit adjustments, kept for your reconciliation. It is not a tax invoice and not a receipt, and it does not replace the invoice Creem issues.
- Business plan. The plan includes an invoice issued by Creem, our merchant of record, together with an availability target of 99.9% per calendar month. That is a target, not a service-credit commitment: contractual credits exist only where we have signed an SLA with you. If procurement needs a purchase order reference, contact us before signing up.
- Books. Ledger entries for every credit and debit are visible in the dashboard, so you can reconcile spend against your own accounting without asking us for a statement.
Errors
Errors use OpenAI's envelope: {"error":{"message":"...","type":"...","code":"..."}}. Branch on status first, then code where it is more specific.
The model field in a response body carries the upstream model name (for example deepseek-flash), not the id you sent. Sending it back returns the 404 above; always use an id from GET /v1/models.
Concurrency limit on non-streaming requests
Non-streaming calls are held open for the whole generation, so they are capped separately: when the number of them already in flight reaches the instance ceiling, further non-streaming requests return 503 server_error with code: "concurrency_limit" and a Retry-After: 2 header.
HTTP/1.1 503 Service Unavailable
retry-after: 2
{"error":{"message":"Server busy. Retry shortly, or set stream=true to avoid buffering.","type":"server_error","code":"concurrency_limit"}}- The pre-authorisation for that request is released before the error is returned, so a rejection does not freeze your balance.
stream: truerequests are not subject to this ceiling. Switching to streaming is the fix that does not depend on waiting.- The ceiling is per instance, not per key: during a busy minute it can fire for a request that is well inside its own rate limit. Treat it as load, not as a fault in the request.
- Two seconds is the shortest interval worth retrying, not a promise that capacity is free by then. If it repeats, reduce the number of concurrent non-streaming calls you issue rather than retrying harder.
Client-side mapping
Upstream 4xx responses are passed through with the provider's message, except authentication failures from a provider, which are returned as 502 upstream_error because they are our problem, not yours.
Retry policy we recommend
- Retry: 429, 502, 503. Do not retry: 400, 401, 402, 403, 404, 451.
- Exponential backoff with jitter: 500 ms, 1 s, 2 s, 4 s, capped at 30 s, maximum three attempts.
- 429 responses carry
Retry-Afterin seconds (the remainder of the current one-minute window). Honour it, then apply jitter — several clients waking at the same instant will simply re-trigger the limit. - Never retry after streaming has begun — you will duplicate output and pay twice for overlapping tokens.
- Log
x-request-idwith every failure. It is the only handle that lets us trace a request through the gateway and the provider.
Rate limits
Limits are per key, enforced in fixed one-minute windows (the counter resets on the minute, not on a rolling basis). They exist to keep one runaway client from consuming shared upstream capacity.
Per-model limits are applied at the gateway and adjusted as capacity grows; we do not publish a fixed number.
- No hard token-per-minute cap. Throughput is bounded by upstream capacity instead; a burst of very large requests can queue or fail with 502 even under the RPM limit.
- 429 means slow down now. The limiter counts requests, not tokens, so one client hammering a key starves every other client on that key.
- Concurrency advice. Keep CONCURRENCY × (average latency in seconds) × 60 below your RPM. Ten concurrent requests at 3 s latency is 200 RPM-equivalent — that overruns a Starter key.
- Queue, don't retry-storm. A client-side queue with a token bucket is far more effective under load than aggressive retries.
Limits & timeouts
Long-running reasoning requests are the usual timeout victim: a single call can run for minutes. If your workload regularly exceeds 280 seconds, use streaming (which keeps the connection alive) and give the client a generous idle timeout.
We do not truncate oversized prompts. If the request exceeds the model context, the provider rejects it and you get a 400 with the provider's message — cheaper for you than a silently mangled answer.
Availability & failover
The routing layer supports several upstream channels per model — different provider keys or regions — ordered by priority, then recent failure count, then weight. As of today each model is served by a single upstream channel, so that ordering is not exercised; the rules below are what runs the moment a second channel is added.
- Selection: channels are ordered by priority, then by recent failure count, then by weight.
- Failover window: a request moves to the next channel only while nothing has been produced. Once the first token is sent, the response is committed.
- Not every error fails over. 429 and 5xx fail over; other 4xx do not, because the request itself is wrong and every channel would reject it.
- Health: a channel degrades after three consecutive failures and is taken out of rotation after six; two consecutive successes bring it back.
- No cross-model fallback. We will not answer a
deepseek-reasonerrequest withdeepseek-chat. If the model has no capacity you get503 no_channel, and the decision stays yours.
A 502 after retries across all channels means the model itself is down upstream. Check the provider's status page before opening a ticket — but quote your x-request-id either way.
Content policy
Requests are screened before they reach the model. We scan only the text of user messages — system prompts are not scanned, because your safety instructions are not a request to the model and treating them as one produces false positives (and accusations we would rather avoid).
- A rejection is
403 content_policy_violationwith codeaup_violation. Warnings include the strike count in the message. - Only a content hash is stored for each event — never your text. Reviewers see patterns, not prompts.
- False positive? Use the appeal form (three submissions per account per day) and include the
x-request-id. A human reviews it. - Refusals from the model itself (as opposed to our filter) are not policy violations and never count as strikes.
Data handling
- Prompts and completions are not persisted. They transit the gateway in memory to reach the provider and are not written to the database or to disk.
- What is stored: model id, token counts, cost, latency, status, key id, request id. That is the minimum needed to bill you and to debug a request you report.
- Who sees your prompt: the model provider, because inference happens there. No third party beyond that, and we do not use your content for training.
- Retention: usage metadata is kept for 13 months; ledger and order records for 7 years because tax law requires it; account data is deleted within 30 days of account closure, except where retention is legally required. Moderation events keep a content hash only.
- Sub-processors: Stripe for payments, Resend for transactional email, a VPS provider for hosting, and the model provider for inference. Each receives only what its function needs; the current list is maintained in the Privacy Policy.
- International transfers: account and usage data are processed in our hosting region; inference requests are processed by the model provider, which may be in another country. For personal data originating in the EEA or UK we rely on standard contractual clauses, and a data processing addendum is available on request.
- Your rights: access, correction, export and deletion requests go to
support@tokenaimodels.comand are answered within 30 days.
Regional availability
The service is not offered to customers located in mainland China, nor to persons or entities in jurisdictions subject to comprehensive sanctions. This is a contractual restriction first: by using the API you confirm you are not located in, resident in, or acting on behalf of an entity in, those places. See the Acceptable Use Policy.
- Where the platform can determine the request region — from a CDN country header or edge geolocation — a blocked region receives HTTP 451 with a plain-text body before the request reaches a model. Where the region cannot be determined, the contractual restriction above still applies and is enforceable under the Terms.
- Region signals are imperfect: VPNs, corporate egress proxies and cloud regions all misreport location. A 451 you believe is wrong should be raised with support, not routed around.
- Relaying our API to end users in a blocked region — for example wrapping it in your own service for Chinese customers — is a breach of the Terms and grounds for immediate termination, regardless of where your servers sit.
- Payments from sanctioned or high-fraud regions are refused at checkout independently of API access.
Compliance & legal
This section is the short version of the documents that actually bind you: the Terms of Service, the Acceptable Use Policy (which forms part of the Terms), the Privacy Policy and the Refund Policy. Where this page and those documents disagree, the legal documents prevail.
Who you are contracting with
Modelry is a trading name. The invoice for a credit purchase is issued by Creem, our merchant of record, in its own name. The operator of Modelry is named in our Terms of Service, which sets out who your counterparty is. Model providers are our suppliers: we are your counterparty for the service and you have no direct contractual relationship with them.
Eligibility
- You must be at least 18 and able to enter a binding contract.
- Business accounts must be authorised by the organisation they represent.
- One account per legal entity unless agreed otherwise. Sharing a key across unrelated parties is a breach, not a shortcut.
Sanctions and export controls
- The service is not offered to persons or entities subject to sanctions administered by OFAC, the EU, the UK or the UN, or to anyone acting on their behalf.
- Government, military, intelligence and defence-contractor use requires prior written approval and is declined by default. Signups from
.gov,.miland.eduaddresses are rejected automatically at registration, even where the individual account looks civilian. - Autonomous weapons, direct control of critical infrastructure, and law-enforcement decisions without human review are prohibited outright, in every jurisdiction, with or without approval.
- You are responsible for your own export-control position: where you are, what you build, and whether your end users may lawfully receive the output.
Consumer rights (EU, UK and similar)
If you buy as a consumer you normally have 14 days to withdraw from a distance contract. Digital services work differently: when you ask us to begin supplying immediately, you acknowledge that the withdrawal right is lost once supply starts — which is what happens when credits are first consumed. Nothing here removes rights that mandatory consumer law gives you, and the Refund Policy lists the cases in which we refund in full regardless.
Your responsibility for outputs
Model output can be wrong, incomplete or biased, and it is not professional advice. You are responsible for validating it before relying on it, for the lawfulness of your prompts, and for telling your own users that they are interacting with an AI system. Regulated uses — medical, legal, financial, employment, housing, credit — need human review and, where the law requires it, a licensed professional in the loop.
Trademarks and affiliation
Model and company names on this site — including DeepSeek and Qwen — are the trademarks of their respective owners and are used only to describe which model serves a request. Modelry is not affiliated with, endorsed by, sponsored by or certified by any model provider, and availability of a model does not imply any partnership.
Data protection
For content you send to a model we act as processor; for account, billing and usage data we act as controller. Sub-processors are listed in the Privacy Policy. A data processing addendum, including standard contractual clauses for transfers out of the EEA or UK, is available before you send personal data — ask support and it is provided for signature. Data subject requests: support@tokenaimodels.com, answered within 30 days.
Changes and deprecation
We may add, change or withdraw a model. Withdrawing a model that a paying account depends on is announced at least 30 days ahead by email to account owners, except where a provider withdraws it with less notice — in which case we tell you as soon as we know. Price changes apply prospectively only and never to credits already purchased.
Building on the API
Building a product on top of the API is expected and encouraged: your customers talk to your service, and you carry the relationship with them. Providing raw API access to third parties — issuing keys that let them call us directly under your account — requires a written agreement first. See the Acceptable Use Policy.
Desktop & chat apps
Any client with a custom OpenAI-compatible provider works. Fill in the base URL, the key and the model id; the rest is the client's defaults.
A wrong base URL is the single most common setup failure: some clients append/v1themselves, others do not. If you get a 404 on/v1/v1/chat/completions, drop the suffix from the field.
SDKs & frameworks
Official OpenAI SDKs work unchanged. So do the popular wrappers — point them at the base URL and they treat us like OpenAI.
from langchain_openai import ChatOpenAI
import os
llm = ChatOpenAI(
model="deepseek-chat",
base_url="https://api.tokenaimodels.com/v1",
api_key=os.environ["MODELRY_API_KEY"],
temperature=0.3,
)
print(llm.invoke("Name three tradeoffs of server-side rendering.").content)Notes that save an afternoon: LangChain fans out to /v1/embeddings if you use a vector store — keep embeddings on another provider. LlamaIndex needs OpenAILike with is_chat_model=True. The Vercel AI SDK's streamText works as-is because our SSE format matches OpenAI's.
Migrating to Modelry
From OpenAI
Everything else — the SDK, the retry wrapper, the streaming parser — stays. Two behaviour differences to check: error code values are ours (mapped to OpenAI names), and rate limits are enforced in fixed one-minute windows per key rather than OpenAI's per-account scheme.
From DeepSeek direct
Same models, one fewer vendor to manage, per-key quotas and one order record. What you give up: the provider's console-level controls and any provider-specific endpoints beyond Chat Completions.
Production checklist
- Point at
api.tokenaimodels.com, not the apex domain, or streaming will arrive in bursts. - Put the key in an environment variable or secret manager. Never in a client bundle.
- Set
max_tokensexplicitly. The 4,096 default is fine for chat and wrong for long-form generation. - Handle the final SSE event: empty
choices, populatedusage, then[DONE]. - Retry only 429/502/503, with exponential backoff and jitter, and never after the first token.
- Keep a request-level queue so concurrency × latency stays inside your RPM.
- Log
x-request-id, model, token counts and status for every call — it is your only audit trail. - Watch
usage.prompt_cache_hit_tokenson your main workload; a stable prompt prefix can cut input cost by an order of magnitude. - Alert on 402 as well as 5xx. Running dry mid-day is a page, not a log line.
- Route by difficulty:
deepseek-chatby default,deepseek-reasoneronly when the task justifies four to five times the price.
FAQ
Why is my content empty, with a huge token count?
Reasoning was on. On deepseek-chat we disable it by default, but if you pass thinking:{"type":"enabled"} yourself, the thinking budget eats max_tokens and can leave nothing for the answer. Check finish_reason and raise max_tokens.
402 with a positive balance — why?
The balance must cover the *pre-authorisation*, not the eventual cost. A request with max_tokens: 384000 on deepseek-reasoner freezes several dollars before it starts. Lower max_tokens or top up.
Does switching models change anything else?
Only the model id. Same endpoint, same key, same billing; prices and limits differ per model.
Can I get an OpenAI-compatible /v1/embeddings?
Not today. Use another provider for vectors and pass the resulting context to us as text.
Is my data used for training?
No. We do not persist prompt content at all; see Data handling.
What happens if my balance hits zero mid-stream?
The in-flight request completes and settles; the next request fails with 402. We do not cut a stream in half.
Do you support Anthropic-style /v1/messages?
No. Chat Completions only. Anthropic SDKs cannot be pointed here without an adapter such as LiteLLM.
How do I report a billing discrepancy?
Open the request in usage, copy its x-request-id, and contact support from the dashboard with that id. Every ledger entry is reconcilable against a usage row.
Can I use this for a government or defence project?
Not without prior written approval. Government, military, intelligence and defence-contractor use is declined by default — see Compliance & legal. Approval, where granted, comes with conditions on data handling and end use.
Can I build a product on top of the API and charge my customers?
You can build a product on top of it and charge for that product. Issuing raw keys so third parties call us directly under your account needs a written agreement. The distinction is who the end user's counterparty is.
Can I use it from mainland China?
No. The service is not offered to customers located in mainland China, and relaying it to end users there breaches the Terms. See Regional availability.
Still stuck
Contact support from the dashboard with the x-request-id of a failing call, the model id and the timestamp. For moderation disputes use the appeal form; for limit increases, message us from the Business plan page.
Modelry API v1 · reference last updated 2026 · prices and limits are shown live on the pricing page.