v1Mis à jour le 2026-11-17

Référence de l'API

Un seul endpoint pour les modèles DeepSeek. Pointez un client qui parle le format OpenAI chat-completions vers l'URL de base ci-dessous, authentifiez-vous avec une clé Modelry, et changez de modèle en modifiant une seule chaîne.

Cette documentation est en anglais.

URL de basehttps://api.tokenaimodels.com/v1
AuthentificationAuthorization: Bearer sk-live-...
ProtocoleOpenAI Chat Completions (SSE streaming)
Modèlesdeepseek-chat · deepseek-chat-lite · deepseek-reasoner
Facturationcrédits d'usage, mesurés par requête

Vue d'ensemble

Vous cherchez le chemin le plus court plutôt que la référence complète ? Premier appel en cinq minutes — une clé, un curl, une vraie réponse. Revenez ici quand quelque chose demande explication.

Modelry est une plateforme d'API d'inférence gérée. Vous envoyez des requêtes OpenAI Chat Completions à une seule URL de base ; nous routons chaque requête vers le fournisseur du modèle, mesurons les comptes de tokens que le fournisseur déclare et débitons vos crédits d'usage. Nous sommes votre cocontractant et votre point de support unique — les fournisseurs de modèles sont nos fournisseurs, pas vos vendeurs, et vous n'avez aucune créance directe contre eux.

Ce que cela vous apporte :

  • Une seule intégration. Même schéma de requête et de réponse qu'OpenAI, donc les SDK et frameworks existants fonctionnent après changement de l'URL de base, de la clé et de l'identifiant de modèle.
  • Un seul format d'erreur. Les charges utiles propres à chaque fournisseur sont normalisées dans la forme {"error":{"message","type","code"}} d'OpenAI, pour que votre logique de nouvelle tentative n'ait qu'un contrat à comprendre.
  • Des crédits d'usage, mesurés par requête. Aucun abonnement requis. Chaque appel est pré-autorisé sur votre solde puis réglé d'après l'usage déclaré par le fournisseur.
  • Aujourd'hui, un seul canal sert tous les modèles de cet endpoint. S'il tombe, la requête échoue et le montant pré-autorisé est libéré. Votre modèle n'est jamais remplacé en silence par un modèle moins cher.

Cette page est la référence complète. Pour une intégration en cinq minutes, lisez Démarrage rapide et Erreurs. Le reste sert quand quelque chose casse en production.

Démarrage rapide

  1. Créez un compte. Inscrivez-vous sur /signup et vérifiez l'adresse e-mail. Le crédit d'inscription est émis à la vérification ; appeler l'API depuis un compte non vérifié renvoie 403 email_unverified.
  2. Créez une clé. Tableau de bord → Clés d'API → Nouvelle clé. Le texte en clair n'est affiché qu'une fois — seul un hachage SHA-256 est stocké, donc une clé perdue ne peut pas être récupérée. Faites une rotation plutôt que de la chercher.
  3. Appelez l'API. Exportez la clé dans MODELRY_API_KEY et exécutez l'un des extraits ci-dessous.
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
  }'

Un appel réussi renvoie HTTP 200 avec choices[0].message.content et un bloc usage. Les trois échecs que vous rencontrerez vraiment le premier jour : 401 (clé erronée ou révoquée), 402 (le solde ne couvre pas la pré-autorisation), 404 (identifiant de modèle absent du catalogue — appelez GET /v1/models).

Ce que nous demandons. Nous ne demandons aucun justificatif d'identité pour ouvrir un compte. Les contrôles d'identité ou de fraude exigés pour un paiement sont effectués par Creem, notre Merchant of Record, sur sa page de paiement.

Authentification

Chaque requête porte un jeton bearer. Les clés sont rattachées au compte, pas au projet : un compte peut détenir plusieurs clés, et chaque clé peut être restreinte indépendamment.

En-têteValeur
AuthorizationBearer sk-live-... (obligatoire)
Content-Typeapplication/json (obligatoire pour POST)
  • Format de clé : sk-live- suivi de 32 caractères compatibles URL. Les 12 premiers caractères sont stockés comme identifiant, pour distinguer les clés dans le tableau de bord.
  • La révocation prend effet en 20 secondes. Les authentifications réussies sont brièvement mises en cache, donc une clé révoquée peut encore fonctionner jusqu'à 20 secondes. Concevez pour cette fenêtre plutôt que de supposer une coupure instantanée.
  • Contrôles par clé : liste de modèles autorisés, dérogation de RPM, plafond de dépense et date d'expiration. Une clé dotée d'une liste d'autorisation rejette les autres modèles avec 403 permission_error.
  • Rotation : créez la nouvelle clé, déployez-la, confirmez le trafic, puis révoquez l'ancienne. Le cache de 20 secondes rend le chevauchement des clés sans risque.
  • Ne livrez jamais une clé dans un client. Les applications mobiles et les bundles navigateur sont extractibles. Passez par votre propre backend et gardez la clé côté serveur.
Les clés portent sur le solde de votre compte, pas sur un projet. Si vous avez besoin d'isoler les coûts par client, émettez une clé par client avec un plafond de dépense plutôt qu'une clé partagée.

URL de base et endpoints

Utilisez https://api.tokenaimodels.com/v1 — le sous-domaine api, pas le domaine racine. L'hôte racine passe par un CDN qui peut mettre les réponses en tampon ; l'hôte API est une connexion directe et garantit un streaming token par token.

MéthodeCheminObjet
POST/v1/chat/completionsCréer une complétion de chat. Renvoie du JSON, ou des événements serveur lorsque stream vaut true.
GET/v1/modelsLister les modèles disponibles pour votre compte avec la longueur de contexte, la limite de sortie et les prix actuels.

Non implémenté

La surface est volontairement réduite. Ces endpoints OpenAI n'existent pas ici et renvoient 404 — anticipez-les plutôt que de les découvrir en production :

EndpointStatut
/v1/embeddingsnon disponible
/v1/responsesnon disponible (utilisez /v1/chat/completions)
/v1/images/generationsnon disponible
/v1/audio/*non disponible
/v1/files, /v1/batchesnon disponible
/v1/assistants, /v1/threadsnon disponible
/v1/models/{id}non disponible (filtrez la réponse de liste)
Anthropic /v1/messagesnon disponible

Besoin d'embeddings ou d'une API au format Anthropic ? Dites-le-nous — le routage est par modèle et la feuille de route suit la demande.

Modèles

Les identifiants de modèle sont des chaînes stables. La capacité, la longueur de contexte et le prix peuvent différer : traitez le tableau ci-dessous comme le contrat et GET /v1/models comme la vue en direct.

USD pour 1 M de tokens. Chiffre supérieur = heures creuses, ligne inférieure = pointe.

À quoi sert chaque modèle

  • deepseek-chat — le modèle par défaut. Coût par token le plus bas, contexte long. Le raisonnement est désactivé par défaut (voir Modèles de raisonnement) ; des milliers de charges de chat, de RAG et de complétion de code tournent ici.
  • deepseek-reasoner — l'offre de raisonnement. Il réfléchit avant de répondre, coûte environ quatre à cinq fois plus par token, et ne se justifie que pour les problèmes difficiles à plusieurs étapes, les mathématiques et les refactorings délicats.

GET /v1/models ne renvoie que les modèles disposant actuellement d'un canal amont actif. Un modèle listé ici mais absent de cette réponse n'a pas de capacité en ce moment ; l'appeler renvoie 503 no_channel.

Identifiant de modèleContexteSortie maxEntréeEntrée en cacheSortie
deepseek-chat
General chat and writing
1,000,000384,000$0.250
peak $0.500
$0.006
peak $0.012
$1.45
peak $2.90
deepseek-chat-lite
Same model, lower rate
1,000,000384,000$0.200
peak $0.400
$0.006
peak $0.012
$0.850
peak $1.70
deepseek-reasoner
Deep reasoning for hard multi-step problems and refactors
1,000,000384,000$1.10
peak $2.20
$0.044
peak $0.088
$4.75
peak $9.50

Créer une complétion

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.

FieldTypeNotes
modelstringRequired. One of the ids in Models.
messagesarrayRequired, at least one message. See Message formats.
streambooleanDefault false. true returns server-sent events.
max_tokensintegerDefault 4,096. Clamped to the model maximum (384,000 for DeepSeek tiers). For reasoner models this budget covers thinking plus answer.
temperaturenumber0–2. Default is the provider's.
top_pnumberNucleus sampling. Use one of temperature or top_p, not both.
stopstring | arrayUp to four stop sequences.
seedintegerBest-effort determinism where the provider supports it.
frequency_penalty / presence_penaltynumber-2 to 2, provider support varies.
toolsarrayFunction definitions. See Tool calling.
tool_choicestring | objectauto | none | required, or a named function.
response_formatobject{"type":"json_object"} only. No json_schema.
userstringOpaque end-user id, forwarded for provider-side abuse signals.
reasoning_effortstringlow | medium | high. Default medium on deepseek-reasoner.
thinkingobjectDeepSeek-style switch. We send {"type":"disabled"} to deepseek-chat by default; pass your own value to override.

Maximum output is clamped, not rejected: ask for 900,000 tokens on 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.

Formats de message

Messages use OpenAI's role model. Three roles are generally useful: system, user, assistant; tool appears only after a tool call.

RoleContentNotes
systemstringInstructions and persona. Put stable text first — it improves prompt-cache hits.
userstring or content arrayYour request. Content array form: [{"type":"text","text":"..."}].
assistantstring or nullPrior turns. With tool calls, content may be null and tool_calls set.
toolstringResult of a tool call. Requires tool_call_id matching the assistant 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 a usage block and an empty choices array. Code that assumes choices[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.

Modèles de raisonnement

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_content alongside content and streams as delta.reasoning_content. The OpenAI SDKs do not type that field — read it from the raw object (Python: model_extra; Node: cast to any).
  • Budget. max_tokens covers 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 check finish_reason === "length".
  • Effort. We default reasoning_effort to medium. Going to high raises both latency and cost; going to low is often enough for classification and extraction. On deepseek-reasoner the medium default adds a fixed input overhead of about 80 tokens to every request, independent of your prompt length; passing low removes 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.

Appels d'outils

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 one tool message 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.arguments by 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.

Sortie structurée

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.

Cache de prompt

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 (or usage.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.

Tarifs

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.

WindowUTCChina (UTC+8)Central Europe (UTC+1)US Eastern (UTC-5)
Peak 1Mon–Fri 01:00–04:00Mon–Fri 09:00–12:00Mon–Fri 02:00–05:00Sun–Thu 20:00–23:00
Peak 2Mon–Fri 06:00–10:00Mon–Fri 14:00–18:00Mon–Fri 07:00–11:00Mon–Fri 01:00–05:00
Off-peakeverything else, all weekendeverything elseeverything elseeverything else

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.

We do not round in our favour: settlement uses the provider's own counts, and the only rounding is a single ceiling to the nearest micro-dollar.

Usage et mesure

Billing has three steps per request. Knowing them explains every number you see in the dashboard.

SituationWhat you are chargedStatus in usage log
Successful requestActual cost from provider usageok
Provider omits usageThe pre-authorised estimatesettled_estimated
Failure before any outputNothing — the freeze is released—
Stream interrupted after output startedEstimate, because no usage arrivedsettled_estimated
Request blocked by content policyNothing—

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.

Relevés et taxes

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.

Erreurs

Errors use OpenAI's envelope: {"error":{"message":"...","type":"...","code":"..."}}. Branch on status first, then code where it is more specific.

StatustypeWhen it happensWhat to do
400invalid_request_errorBody is not JSON, or messages is missing/emptyFix the request; retrying will not help
401authentication_errorKey missing, malformed, revoked, or wrong environmentCheck the header; rotate the key
402insufficient_quota (insufficient_balance)Balance cannot cover the pre-authorisationTop up or lower max_tokens
402insufficient_quota (quota_*)Key spend cap reachedRaise the cap on the key
403permission_error (email_unverified)Account email not verifiedVerify, then retry
403permission_errorAccount suspended, or model not allowed on this keyCheck dashboard, or remove the allow-list
403content_policy_violation (aup_violation)Request tripped the content policyRephrase; see Content policy; appeal if wrong
404invalid_request_error (model_not_found)Unknown model idCall GET /v1/models
429rate_limit_errorPer-key RPM exceededBack off exponentially
451(plain text)Region not servedSee Regional availability
502upstream_errorEvery channel failed, or the provider is unreachableRetry with backoff
503upstream_error (no_channel)No live channel for that modelRetry later, or use another model
503server_error (concurrency_limit)Non-streaming requests in flight hit the instance ceilingHonour Retry-After (2s), or set stream=true

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: true requests 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-After in 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-id with every failure. It is the only handle that lets us trace a request through the gateway and the provider.

Limites de débit

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.

PlanRequests per minute (RPM)Notes
Free10Enough to evaluate, not to serve traffic
Starter$20/mo → 60Single production service
Pro$100/mo → 300Several services or a small team
Business$500/mo → 1,500Higher limits on request
Per keyoverrides the planSet an RPM on the key to isolate a workload

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. 10 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.

Need more? Business plan customers can request a limit increase; tell us your expected RPM and token mix so the channel pool behind your model is sized for it.

Limites et délais

LimitValue
Request timeout at the gateway280 seconds, then the connection is closed
max_tokens default4,096
max_tokens ceilingper model — see GET /v1/models
Context windowper model — see GET /v1/models
Messages per requestno artificial cap — bounded by context
Stop sequences4
Tools per requestprovider-dependent, typically 128
Concurrent requestsbounded by RPM, not by a separate connector limit

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.

Disponibilité

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-reasoner request with deepseek-chat. If the model has no capacity you get 503 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.

Politique de contenu

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).

TierCoversAction
1 — hard lineSexual content involving minors; weapon and explosive synthesis; bioweapon enhancementRequest rejected. First two occurrences are warnings; the third suspends the account for 7 days, then it self-clears.
2 — high riskMalware and credential stealers; phishing kits; doxxing and personal-data huntingRequest rejected and logged. 10 rejections on one key revokes that key.
3 — grey zoneAdult content, medical-advice-shaped questionsAllowed through, logged for human review.
  • A rejection is 403 content_policy_violation with code aup_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.

Traitement des données

  • 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.com and are answered within 30 days.

Do not send secrets you would not send to any third-party inference API. We do not log payloads, but the provider receives them by design.

Disponibilité régionale

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.

Conformité et mentions légales

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, .mil and .edu addresses 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.

Compliance questions with a procurement questionnaire attached are welcome. We will answer in writing, including the parts where our answer is "not covered" — a clear gap is more useful to your legal team than a confident paragraph.

Applications de bureau et de chat

Tout client acceptant un fournisseur personnalisé au format OpenAI fonctionne. Renseignez l'URL de base, la clé et l'identifiant de modèle ; le reste correspond aux valeurs par défaut du client.

ApplicationOù le modifierNotes
CursorRéglages → Modèles → Clé d'API OpenAI + Remplacer l'URL de baseAjoutez deepseek-chat comme modèle personnalisé
Cline / Roo Code (VS Code)Fournisseur d'API : « OpenAI Compatible »Définir l'URL de base par profil de fournisseur
Continueconfig.json → models[].provider: openaiDéfinir apiBase et model
Open WebUIAdmin → Réglages → Connexions → OpenAIL'URL doit se terminer par /v1 ; ajoutez les modèles à la main
LibreChatlibrechat.yaml → endpoints personnaliséstitleConvo et liste des modèles
Cherry StudioRéglages → Fournisseurs → OpenAI → Hôte de l'APIL'hôte est l'URL de base /v1
ChatBoxRéglages → Fournisseur de modèle → API OpenAI compatibleAjoutez l'identifiant de modèle à la main
NextChatRéglages → Endpoint personnaliséActivez les noms de modèles personnalisés
LobeChatRéglages du fournisseur → OpenAI → URL du proxyCertaines versions exigent le suffixe /v1
SillyTavernChat Completion → Compatible OpenAILe streaming fonctionne ; gardez l'hôte api sur le sous-domaine api
DifyFournisseur de modèle → Compatible API OpenAILe nom du modèle doit correspondre exactement à /v1/models
n8nIdentifiant OpenAI → URL de baseUtilisez le nœud HTTP Request pour le streaming
Une URL de base erronée est l'erreur de configuration la plus fréquente : certains clients ajoutent /v1 eux-mêmes, d'autres non. Si vous obtenez un 404 sur /v1/v1/chat/completions, retirez le suffixe du champ.

SDK et frameworks

Les SDK officiels OpenAI fonctionnent sans modification. Les surcouches populaires aussi — pointez-les vers l'URL de base et elles nous traitent comme 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)

Quelques notes qui font gagner un après-midi : LangChain appelle /v1/embeddings si vous utilisez un stockage vectoriel — gardez les embeddings chez un autre fournisseur. LlamaIndex exige OpenAILike avec is_chat_model=True. streamText du Vercel AI SDK fonctionne tel quel, car notre format SSE correspond à celui d'OpenAI.

Migrer vers Modelry

From OpenAI

ChangeFromTo
Base URLhttps://api.openai.com/v1https://api.tokenaimodels.com/v1
API keysk-...sk-live-... from the dashboard
Model idgpt-4o-mini / gpt-4.1deepseek-chat
Model id (hard tasks)o-series / gpt-5-classdeepseek-reasoner
Embeddings/v1/embeddingskeep on another provider (not offered here)

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

DeepSeek directModelry
Base URL https://api.deepseek.comhttps://api.tokenaimodels.com/v1
deepseek-flashdeepseek-chat
deepseek-v4-prodeepseek-reasoner
Your own provider keyOne Modelry key across models
Anthropic-shaped endpointnot offered
Provider-side tools (search etc.)not offered

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.

Liste de contrôle pour la production

  1. Pointez vers api.tokenaimodels.com, pas vers le domaine racine, sinon le streaming arrivera par paquets.
  2. Placez la clé dans une variable d'environnement ou un gestionnaire de secrets. Jamais dans un bundle client.
  3. Définissez max_tokens explicitement. La valeur par défaut de 4 096 convient au chat et ne convient pas à la génération de texte long.
  4. Traitez le dernier événement SSE : choices vide, usage renseigné, puis [DONE].
  5. Ne réessayez que sur 429/502/503, avec backoff exponentiel et jitter, et jamais après le premier token.
  6. Maintenez une file au niveau des requêtes pour que concurrence × latence reste dans votre RPM.
  7. Journalisez x-request-id, le modèle, les comptes de tokens et le statut pour chaque appel — c'est votre seule piste d'audit.
  8. Surveillez usage.prompt_cache_hit_tokens sur votre charge principale ; un préfixe de prompt stable peut réduire le coût d'entrée d'un ordre de grandeur.
  9. Alertez sur 402 comme sur 5xx. Tomber à sec en pleine journée est un incident, pas une ligne de journal.
  10. Routez selon la difficulté : deepseek-chat par défaut, deepseek-reasoner seulement quand la tâche justifie quatre à cinq fois le prix.

Questions fréquentes

Pourquoi mon contenu est vide, avec un compte de tokens énorme ?

Le raisonnement était activé. Sur deepseek-chat, nous le désactivons par défaut, mais si vous passez vous-même thinking:{"type":"enabled"}, le budget de réflexion consomme max_tokens et peut ne rien laisser pour la réponse. Vérifiez finish_reason et augmentez max_tokens.

402 alors que le solde est positif — pourquoi ?

Le solde doit couvrir la *pré-autorisation*, pas le coût final. Une requête avec max_tokens: 384000 sur deepseek-reasoner gèle plusieurs dollars avant même de commencer. Réduisez max_tokens ou rechargez.

Changer de modèle modifie-t-il autre chose ?

Seulement l'identifiant de modèle. Même endpoint, même clé, même facturation ; les prix et les limites diffèrent selon le modèle.

Puis-je obtenir un /v1/embeddings au format OpenAI ?

Pas aujourd'hui. Utilisez un autre fournisseur pour les vecteurs et transmettez-nous le contexte obtenu sous forme de texte.

Mes données servent-elles à l'entraînement ?

Non. Nous ne conservons pas le contenu des prompts ; voir Traitement des données.

Que se passe-t-il si mon solde tombe à zéro en plein flux ?

La requête en cours se termine et se règle ; la suivante échoue avec 402. Nous ne coupons pas un flux en deux.

Prenez-vous en charge /v1/messages au format Anthropic ?

Non. Chat Completions uniquement. Les SDK Anthropic ne peuvent pas pointer ici sans adaptateur tel que LiteLLM.

Comment signaler un écart de facturation ?

Ouvrez la requête dans usage, copiez son x-request-id et contactez le support depuis le tableau de bord avec cet identifiant. Chaque écriture du grand livre se rapproche d'une ligne d'usage.

Puis-je l'utiliser pour un projet gouvernemental ou de défense ?

Pas sans autorisation écrite préalable. Les usages gouvernementaux, militaires, de renseignement et de sous-traitance de défense sont refusés par défaut — voir Conformité et mentions légales. Une autorisation, lorsqu'elle est accordée, s'accompagne de conditions sur le traitement des données et l'usage final.

Puis-je construire un produit sur l'API et le vendre à mes clients ?

Vous pouvez construire un produit par-dessus et le vendre. Émettre des clés brutes pour que des tiers nous appellent directement sous votre compte exige un accord écrit. La distinction porte sur l'identité du cocontractant de l'utilisateur final.

Puis-je l'utiliser depuis la Chine continentale ?

Non. Le service n'est pas proposé aux clients situés en Chine continentale, et le relayer vers des utilisateurs finaux qui s'y trouvent viole les Conditions. Voir Disponibilité régionale.

Toujours bloqué

Contactez le support depuis le tableau de bord avec l'identifiant x-request-id de l'appel en échec, l'identifiant de modèle et l'horodatage. Pour les litiges de modération, utilisez le formulaire de recours ; pour une augmentation de limites, écrivez-nous depuis la page de l'abonnement Business.

Modelry API v1 · référence mise à jour en 2026 · les prix et les limites sont affichés en direct sur la page des tarifs.

Référence de l'API — Modelry API DeepSeek