TokenMaster API
One OpenAI-compatible API for leading global and Chinese models. Swap the base URL and API key and your existing code, SDKs and tools keep working.
Chat Completions protocol with streaming, tools, structured output and images.
Change model to switch between GPT, Claude, Gemini, DeepSeek, Qwen, Kimi and more.
Charged in real time per request; requests stop before your balance runs out.
Quickstart
Three steps, about three minutes.
Create an API key
Console → API keys → Create key. It is shown once — save it right away.
Send a request
Store the key in an environment variable and call the API.
Set the environment variable
export TOKENMASTER_API_KEY="tm-your-key"
$env:TOKENMASTER_API_KEY = "tm-your-key"
First request
curl https://tokenmaster.store/v1/chat/completions \
-H "Authorization: Bearer $TOKENMASTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-6-luna",
"messages": [{"role": "user", "content": "Introduce yourself in one sentence"}]
}'
# pip install openai
import os
from openai import OpenAI
client = OpenAI(base_url="https://tokenmaster.store/v1", api_key=os.environ["TOKENMASTER_API_KEY"])
resp = client.chat.completions.create(
model="openai/gpt-6-luna",
messages=[{"role": "user", "content": "Introduce yourself in one sentence"}],
)
print(resp.choices[0].message.content)
print(resp.usage)
// npm install openai
import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://tokenmaster.store/v1", apiKey: process.env.TOKENMASTER_API_KEY });
const resp = await client.chat.completions.create({
model: "openai/gpt-6-luna",
messages: [{ role: "user", content: "Introduce yourself in one sentence" }],
});
console.log(resp.choices[0].message.content, resp.usage);
model — e.g. anthropic/claude-sonnet-5.5, deepseek/deepseek-v4-pro, moonshotai/kimi-k2.6. See the catalog or GET /v1/models.Authentication
Every /v1/* request sends your API key in the Authorization header:
Authorization: Bearer tm-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- Keys start with
tm-and are shown once at creation. We store only a hash, so a lost key cannot be recovered — create a new one. - One account can hold many keys (per environment or project). They share one balance.
- Revoke a leaked key in the console; it stops working immediately.
SDKs & tools
Anything that supports an "OpenAI-compatible" endpoint works. Configure three values:
| Setting | Value |
|---|---|
| Base URL / API Base | https://tokenmaster.store/v1 |
| API Key | Your tm-… key |
| Model | A model ID such as anthropic/claude-sonnet-5.5 |
LangChain
# pip install langchain-openai
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
base_url="https://tokenmaster.store/v1",
api_key=os.environ["TOKENMASTER_API_KEY"],
model="deepseek/deepseek-v4-pro",
max_tokens=1024,
)
print(llm.invoke("Write a haiku about Manila").content)
// npm install @langchain/openai
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "deepseek/deepseek-v4-pro",
apiKey: process.env.TOKENMASTER_API_KEY,
configuration: { baseURL: "https://tokenmaster.store/v1" },
maxTokens: 1024,
});
console.log((await llm.invoke("Write a haiku about Manila")).content);
Desktop clients & low-code platforms
Cherry Studio, LobeChat, Dify, Continue and similar tools: pick the "OpenAI-compatible" or "Custom OpenAI" provider, fill in the base URL and key from the table, then add the model IDs you want. Almost every tool expects the base URL to include /v1.
Step-by-step settings for Claude Code, Codex CLI, Cherry Studio, Chatbox, LobeHub, Open WebUI, Dify, n8n, Cline, Continue and Cursor are in the integration guides. Claude Code uses the Anthropic protocol and Codex CLI the Responses protocol — see Anthropic & Responses APIs.
GET/v1/models
Lists the models you can call right now. Only models with published prices appear; see the catalog for prices.
curl https://tokenmaster.store/v1/models -H "Authorization: Bearer $TOKENMASTER_API_KEY"
{
"object": "list",
"data": [
{ "id": "tokenmaster/auto", "object": "model", "owned_by": "tokenmaster" },
{ "id": "anthropic/claude-sonnet-5.5", "object": "model", "owned_by": "Anthropic" },
{ "id": "openai/gpt-6-sol", "object": "model", "owned_by": "OpenAI" },
{ "id": "deepseek/deepseek-v4-pro", "object": "model", "owned_by": "DeepSeek" },
{ "id": "moonshotai/kimi-k2.6", "object": "model", "owned_by": "Moonshot AI" }
]
}
Model IDs
- Format is
vendor/model, lowercase — e.g.google/gemini-3.8-flash,alibaba/qwen3.7-plus,zhipu/glm-5.2. - Special ID
tokenmaster/autolets us pick the model — see Smart routing. - Models marked "Coming soon" in the catalog cannot be called yet and return 400.
- Text models (including multimodal input) are served on
/v1/chat/completions,/v1/messagesand/v1/responses; embedding models on/v1/embeddings. Image, video and speech generation are not offered yet. - Some providers restrict regions — see Security & compliance.
Embeddings POST /v1/embeddings
Turn text into vectors for semantic search, RAG and clustering. The endpoint is OpenAI-compatible, so client.embeddings.create() in the official SDKs works as is (including their default base64 format).
| Model ID | Dimensions | Good for |
|---|---|---|
baai/bge-m3 | 1024 | Multilingual incl. CJK — recommended |
qwen/qwen3-embedding-0.6b | 1024 | Multilingual, longer texts |
baai/bge-small-en-v1.5 · bge-base-en-v1.5 · bge-large-en-v1.5 | 384 · 768 · 1024 | English, ≤512 tokens per input |
pfn/plamo-embedding-1b | — | Japanese |
from openai import OpenAI client = OpenAI(base_url="https://tokenmaster.store/v1", api_key="tm-...") r = client.embeddings.create(model="baai/bge-m3", input=["退货政策是什么?", "What is the refund policy?"]) print(len(r.data[0].embedding), r.usage.prompt_tokens)
curl https://tokenmaster.store/v1/embeddings \
-H "Authorization: Bearer $TOKENMASTER_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "baai/bge-m3", "input": ["hello", "world"]}'
- Up to 100 inputs per request, 32,000 characters each;
dimensionsand token-array inputs are not supported. - Billed per input token (see the Embedding category in the model list); there is no output charge.
- Use one embedding model per index: vectors from different models are not comparable.
Anthropic Messages & Responses APIs
Besides Chat Completions, TokenMaster speaks two more protocols with the same key, prices and balance: POST /v1/messages (Anthropic Messages — Claude Code, Anthropic SDKs) and POST /v1/responses (OpenAI Responses — Codex CLI and other tools that default to it). Both work with every text model, not only Claude or GPT.
Anthropic Messages (Claude Code)
Use https://tokenmaster.store as the base URL, without /v1 (the SDK adds /v1/messages). Send the key as x-api-key or Authorization: Bearer. Anthropic-style names such as claude-sonnet-4-6 or claude-opus-5-5 map to catalog IDs automatically; any catalog ID such as openai/gpt-6-sol works too.
// ~/.claude/settings.json
{
"env": {
"ANTHROPIC_BASE_URL": "https://tokenmaster.store",
"ANTHROPIC_AUTH_TOKEN": "tm-..."
}
}
import anthropic
client = anthropic.Anthropic(base_url="https://tokenmaster.store", api_key="tm-...")
msg = client.messages.create(
model="anthropic/claude-sonnet-5.5", max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
)
print(msg.content[0].text)
- Supported: text and image input, system prompts, tool use (tool_use / tool_result), streaming SSE,
stop_sequences,/v1/messages/count_tokens(a free estimate) and/v1/models. The server-sideweb_searchtool runs on TokenMaster web search, billed per search. - Not supported: extended-thinking blocks are not returned; PDF and other document attachments; Anthropic-hosted code execution, bash and text-editor tools; the Batch and Files APIs.
- Claude 5-generation models (Sonnet / Opus / Haiku 5.x, Fable) do not accept
temperature,top_p, a forced tool choice or an assistant prefill; these are ignored instead of failing the request, on all three protocols.
OpenAI Responses (Codex CLI)
Base URL https://tokenmaster.store/v1. TokenMaster does not store responses: send the full conversation in input each time (store: false) — which is what Codex CLI does.
# ~/.codex/config.toml (export TOKENMASTER_API_KEY=tm-...) model = "openai/gpt-6-sol" model_provider = "tokenmaster" [model_providers.tokenmaster] name = "TokenMaster" base_url = "https://tokenmaster.store/v1" env_key = "TOKENMASTER_API_KEY" wire_api = "responses"
from openai import OpenAI client = OpenAI(base_url="https://tokenmaster.store/v1", api_key="tm-...") r = client.responses.create(model="openai/gpt-6-luna", instructions="Be brief", input="Hello") print(r.output_text)
- Supported: text and image input,
instructions, function and free-form (custom) tools, streaming events,text.formatstructured output,max_output_tokens, andreasoning.efforton OpenAI models. - Not supported:
previous_response_idand conversations (400), background mode, file inputs, and OpenAI-hosted tools (web_search, file_search, code_interpreter… are ignored). For web search use a model ID ending in:online. - Billing, holds, per-key spending limits and the
x-tm-request-id/x-tm-cost-usdheaders work exactly as on Chat Completions.
Smart routing tokenmaster/auto
Not sure which model to pick? Let us choose per request: simple asks go to cheaper models, hard tasks to stronger ones — the same budget goes further.
- Usage: set
modeltotokenmaster/auto(or justauto). Everything else stays the same — streaming, tools and image input all work. - How it picks: it classifies the task and its difficulty, then weighs quality against price across the candidates and picks the best value; if that model is unavailable it falls back to the next. Current candidates:
- Billing: you pay the per-token price of the model that actually answered; routing itself is free. The response
modelfield and thex-tm-routed-modelheader name that model, and these requests carry an auto tag under Usage in the console. - Holds: the pre-authorisation uses the highest price among the candidates and is settled to the actual model afterwards, so it needs a little more available balance than calling a cheap model directly.
- Conversations: send an
x-tm-session-idheader (any string, up to 64 chars) and a conversation stays on one model where possible — better cache hits, lower cost. - Regions: candidates are filtered by your country / region; if none remain you get
403 region_restricted. - When not to use it: if you need a fixed style, reproducible output, or top quality on a critical task, name the model explicitly.
resp = client.chat.completions.with_raw_response.create(
model="tokenmaster/auto",
messages=[{"role": "user", "content": "Summarise this paragraph in one sentence: ..."}],
extra_headers={"x-tm-session-id": "conv-42"}, # optional: keep one model per conversation
)
print(resp.headers["x-tm-routed-model"]) # e.g. openai/gpt-6-luna
print(resp.parse().choices[0].message.content)
curl -i https://tokenmaster.store/v1/chat/completions \
-H "Authorization: Bearer $TOKENMASTER_API_KEY" \
-H "Content-Type: application/json" \
-H "x-tm-session-id: conv-42" \
-d '{"model": "tokenmaster/auto", "messages": [{"role": "user", "content": "Hello"}]}'
# x-tm-routed-model: openai/gpt-6-luna
# x-tm-cost-usd: 0.000034
# { "model": "openai/gpt-6-luna", "choices": [ ... ] }
Web search
Models have a knowledge cut-off. With web search on, the model looks things up when it needs to and tells you where the facts came from — ideal for news, prices, versions, policies and anything that changes.
- Turn it on (any one): add
"web_search": true; or"web_search": {"max_uses": 1}to cap searches; or append:onlineto the model, e.g.openai/gpt-6-luna:online. OpenAI'sweb_search_optionsalso works. - How it works: the model decides whether and what to search. Up to 3 searches per request, 5 results each; answers cite results as [1], [2] and list the source links.
- Billing: $0.0003 per search, plus the model tokens of every round (results are fed back as input, so input tokens grow noticeably). No search, no search fee. The
x-tm-searchesheader counts searches;usageandx-tm-cost-usdare totals across all rounds. - Response: the standard Chat Completions shape plus
citations(the source URLs the answer actually cites; empty if none) andsearch(count, queries, result titles and links). When streaming, both arrive in the final chunk that carriesusage. - Streaming:
"stream": trueworks, but output starts after the searches finish, so the first token takes a few seconds longer. - Combines with your own
toolsand with smart routing (tokenmaster/auto:online). The model must support tool calling; very small models may not search on their own. - Holds: the hold assumes the maximum number of searches and is settled to the actual cost; every round stays within the hold.
resp = client.chat.completions.create(
model="openai/gpt-6-luna",
messages=[{"role": "user", "content": "What changed in the latest Python release?"}],
extra_body={"web_search": True}, # or model="openai/gpt-6-luna:online"
)
print(resp.choices[0].message.content) # answer with [1] [2] citations
print(resp.model_extra["citations"]) # ["https://...", "https://..."]
curl -i https://tokenmaster.store/v1/chat/completions \
-H "Authorization: Bearer $TOKENMASTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "tokenmaster/auto:online", "messages": [{"role": "user", "content": "Latest GPU prices"}]}'
# x-tm-searches: 1
# x-tm-cost-usd: 0.000540
# { "choices": [ ... ], "citations": ["https://..."], "search": { "searches": 1, "queries": ["GPU prices"], "results": [ ... ] } }
Knowledge bases
Upload your documents and get a Q&A bot that answers only from them and cites its sources. Chunking, embeddings, indexing and retrieval are handled for you — just upload files and call the API.
- Create: Console → Knowledge bases → New, then upload documents. PDF, Word, Excel, CSV, Markdown, TXT, HTML and images are supported; PDF and plain text up to 10 MB, others 4 MB; scanned pages are read with OCR. Ask questions once a file shows Ready. Up to 5 knowledge bases per account, 200 files each.
- API: add
"knowledge_base": "kb_…"to any Chat Completions request. Works with any model, smart routing, web search and streaming. Answers cite excerpts as [1], [2] and the response addssources(number, file, excerpt); when streaming they arrive in the final chunk. - Billing: a one-off indexing fee at upload, estimated from file size ($1.50/1M tokens); $0.0015 per question for retrieval; the answering model's tokens as usual; storage is free. Deleting a document does not refund its indexing fee.
- Website widget: switch on the widget on the knowledge-base page and paste one line into your site's HTML — a chat bubble appears in the corner. Optional
data-color,data-position="left",data-theme. Visitor questions are charged to your balance, protected by a domain allowlist, a daily spending cap and per-visitor rate limits. - Data: each knowledge base is a separate index usable only with your account's API keys; deleting it removes the documents and the index.
resp = client.chat.completions.create(
model="tokenmaster/auto",
messages=[{"role": "user", "content": "What is the return policy?"}],
extra_body={"knowledge_base": "kb_your_id"},
)
print(resp.choices[0].message.content) # "Within 30 days … [1]"
print(resp.model_extra["sources"]) # [{"n": 1, "file": "policy.pdf", "excerpt": "…"}]
<!-- paste before </body>; copy your own key from the console --> <script src="https://tokenmaster.store/kb.js" data-key="pk_your_embed_key" data-color="#2563eb" async></script>
POST/v1/chat/completions
Generates a reply from a list of messages. Request and response match OpenAI Chat Completions.
Request body
| Field | Type | Description |
|---|---|---|
model* | string | Model ID from /v1/models. |
messages* | array | Conversation. role is system, user, assistant or tool; content is a string or an array of text / image_url parts. |
max_tokens | integer | Maximum tokens to generate. Defaults to 8192; may be lowered to what your balance covers — see Holds & output caps. |
max_completion_tokens | integer | Same as above; preferred for reasoning models and includes reasoning tokens. |
stream | boolean | Stream as server-sent events — see Streaming. |
stream_options | object | include_usage is always on; the stream ends with a usage chunk. |
temperaturetop_p | numbernumber | Sampling controls; valid ranges depend on the model. |
stop | string | array | Stop sequences. |
toolstool_choiceparallel_tool_calls | arraystring | objectboolean | Function calling — see Tool calling. |
response_format | object | json_object or json_schema — see Structured output. |
reasoning_effort | string | Reasoning effort (e.g. low/medium/high) on models that support it. |
seedpresence_penaltyfrequency_penaltylogprobstop_logprobsuser | integernumbernumberbooleanintegerstring | Passed through with OpenAI semantics; ignored or rejected by models that don't support them. |
n must be 1 (other values return 400); fields that change pricing, such as service_tier, are removed; for web search use web_search — see Web search.Example
curl https://tokenmaster.store/v1/chat/completions \
-H "Authorization: Bearer $TOKENMASTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-sonnet-5.5",
"max_tokens": 600,
"temperature": 0.3,
"messages": [
{"role": "system", "content": "You are a senior cloud architect. Answer concisely."},
{"role": "user", "content": "What is edge computing good for? Give 3 points."}
]
}'
HTTP/1.1 200 OK
content-type: application/json
x-tm-request-id: req_d2894d1a736f47c5961c
x-tm-cost-usd: 0.006480
x-tm-max-tokens: 600
{
"id": "chatcmpl-…",
"object": "chat.completion",
"created": 1792137165,
"model": "anthropic/claude-sonnet-5.5",
"choices": [{
"index": 0,
"message": { "role": "assistant", "content": "1. Low-latency interaction…" },
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 1200,
"completion_tokens": 300,
"total_tokens": 1500,
"prompt_tokens_details": { "cached_tokens": 0 }
}
}
Response headers
| Header | Meaning |
|---|---|
x-tm-request-id | Unique request ID — include it when contacting support. |
x-tm-cost-usd | Amount charged in USD (non-streaming). For streams, see Usage in the console. |
x-tm-routed-model | With smart routing (tokenmaster/auto): the model that actually answered. |
x-tm-searches | With web search on: how many searches this request made. |
x-tm-max-tokens | Output cap actually applied. |
x-tm-max-tokens-clamped | true when the cap was set or lowered by the platform (missing, or not covered by your balance). |
finish_reason values
stop— finished normally.length— hit the output cap. Raisemax_tokensor check your balance (seex-tm-max-tokens-clamped).tool_calls— the model wants to call a tool.content_filter— blocked by the provider's safety system.
Streaming
Set "stream": true to receive text/event-stream. Each data: line is a JSON chunk; the second-to-last chunk has empty choices and carries usage; the stream ends with data: [DONE].
stream = client.chat.completions.create(
model="google/gemini-3.8-flash",
messages=[{"role": "user", "content": "Tell a 100-word story"}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage: # last chunk: choices == []
print("\n", chunk.usage)
const stream = await client.chat.completions.create({
model: "google/gemini-3.8-flash",
messages: [{ role: "user", content: "Tell a 100-word story" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
if (chunk.usage) console.log("\n", chunk.usage); // last chunk: choices = []
}
data: {"id":"chatcmpl-…","object":"chat.completion.chunk","model":"google/gemini-3.8-flash","choices":[{"index":0,"delta":{"content":"Once"}}]}
data: {"id":"chatcmpl-…","object":"chat.completion.chunk","model":"google/gemini-3.8-flash","choices":[{"index":0,"delta":{"content":" upon a time"}}]}
data: {"id":"chatcmpl-…","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":168,"total_tokens":182}}
data: [DONE]
choices is non-empty before indexing — the final usage chunk has none. Disconnecting early still bills the tokens already generated.Tool calling
Declare functions in tools. When the model returns tool_calls, run them and send results back with role: "tool". Supported by GPT, Claude, Gemini, Qwen, DeepSeek, Kimi, GLM and other mainstream models.
import json
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What's the weather in Manila right now?"}]
first = client.chat.completions.create(model="openai/gpt-6-sol", messages=messages, tools=tools)
call = first.choices[0].message.tool_calls[0]
args = json.loads(call.function.arguments) # {"city": "Manila"}
messages += [first.choices[0].message,
{"role": "tool", "tool_call_id": call.id, "content": json.dumps({"temp_c": 31, "sky": "thunderstorms"})}]
final = client.chat.completions.create(model="openai/gpt-6-sol", messages=messages, tools=tools)
print(final.choices[0].message.content)Tool definitions count as input tokens on every turn.
Structured output
Use response_format for reliable JSON. json_schema enforces fields and types; fall back to {"type": "json_object"} plus instructions if a model lacks schema support.
resp = client.chat.completions.create(
model="openai/gpt-6-luna",
messages=[{"role": "user", "content": "Extract: William is in Manila, meeting next Wednesday at 10am"}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "meeting",
"strict": True,
"schema": {
"type": "object",
"properties": {
"person": {"type": "string"},
"city": {"type": "string"},
"time": {"type": "string"},
},
"required": ["person", "city", "time"],
"additionalProperties": False,
},
},
},
)
print(resp.choices[0].message.content) # {"person":"William","city":"Manila","time":"next Wednesday 10:00"}Image input
Vision-capable models accept image_url parts inside content. Use an https URL or a data:image/png;base64,… URI.
resp = client.chat.completions.create(
model="anthropic/claude-sonnet-5.5",
max_tokens=500,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What are the single points of failure in this architecture diagram?"},
{"type": "image_url", "image_url": {"url": "https://example.com/arch.png"}},
],
}],
)Images are billed as input tokens per the provider's rules. Holds assume about 3,000 tokens per image and settle to actual usage afterwards.
Reasoning models
- Reasoning tokens are included in
completion_tokensand billed at the output price. - They also consume the output cap. A small cap can end with
finish_reason: "length"and no visible answer. Usemax_completion_tokens≥ 4096. - Where supported,
reasoning_efforttrades depth for speed and cost.
resp = client.chat.completions.create(
model="openai/o3",
reasoning_effort="low",
max_completion_tokens=6000,
messages=[{"role": "user", "content": "Prove that the sum of any two odd numbers is even"}],
)
print(resp.usage.completion_tokens) # includes reasoning tokensGET/v1/balance
Check the account balance with an API key — useful for low-balance alerts.
curl https://tokenmaster.store/v1/balance -H "Authorization: Bearer $TOKENMASTER_API_KEY"
{
"object": "balance",
"currency": "USD",
"balance": 42.183200, // total balance
"available": 41.902100, // usable for new requests
"held": 0.281100, // held by in-flight requests
"inflight": 2,
"frozen": false
}
How billing works
- Per token: cost = input × input price + cached × cached price + output × output price. Prices per 1M tokens (USD) are in the catalog.
- Cache hits are cheaper: keep long prompt prefixes stable; cached tokens appear in
prompt_tokens_details.cached_tokens. - Long-context tiers: models marked
*switch to a higher tier above the threshold. - Smart routing:
tokenmaster/autobills at the price of the model that answered — see Smart routing. - Web search: $0.0003 per search plus the tokens to read the results — see Web search.
- Precision: charged to $0.000001; every request is listed under Usage.
- Failures are free: upstream errors that generate nothing are not charged.
Worked example
anthropic/claude-sonnet-5.5 at $2.40/1M input and $12.00/1M output; 1,200 input and 300 output tokens:
1,200 × 2.40 / 1,000,000 = $0.002880
300 × 12.00 / 1,000,000 = $0.003600
total = $0.006480Holds & output caps
So your balance can never go negative, every request goes through three steps before reaching the model:
- Estimate the worst-case cost from your input length (conservatively) and the output cap.
- Hold that amount from your available balance. Concurrent requests hold separately.
- Settle on actual usage when the request ends; the rest of the hold is released immediately.
If your balance can't cover the requested max_tokens, the cap is lowered to what it can cover and x-tm-max-tokens-clamped: true is returned. If it can't cover the input plus 64 output tokens, you get 402.
max_tokens explicitly so holds stay small; keep enough balance for long documents on premium models; alert on /v1/balance.Rate limits
| Limit | Default | When exceeded |
|---|---|---|
| Requests per key | 300 / minute | 429 rate_limited |
| Concurrent requests per account | 16 | 429 too_many_concurrent |
| Max cost per request | $20 | 400 request_too_large |
| Max output per request | 128,000 tokens | Capped |
| Context length | Per model | 400 context_length_exceeded |
Need more? Contact us with the models, expected QPS and monthly token volume.
Errors
Errors follow the OpenAI format:
{
"error": {
"message": "Insufficient balance: this request needs at least $0.0123, available $0.0040. Top up in the console.",
"type": "insufficient_quota",
"code": "insufficient_balance"
}
}| HTTP | code | Meaning | What to do |
|---|---|---|---|
| 400 | null | Bad request (missing fields, n ≠ 1…) | Fix the request; don't retry |
| 400 | request_too_large | Estimated cost above the $20 per-request limit | Shorten input or lower max_tokens |
| 400 | context_length_exceeded | Input exceeds the model's context | Trim history or use a longer-context model |
| 401 | invalid_api_key | Missing, wrong or revoked key | Check the Authorization header |
| 402 | insufficient_balance | Not enough balance to start the request | Top up, or reduce input / max_tokens |
| 403 | region_restricted | Provider unavailable in your region | Use another provider's model |
| 403 | account_suspended | Account suspended | Contact support |
| 404 | model_not_found | Unknown model ID | Check /v1/models |
| 429 | rate_limited | Per-minute rate exceeded | Retry with backoff |
| 429 | too_many_concurrent | More than 16 in-flight requests | Reduce concurrency or queue |
| 429 / 5xx | null | Provider busy or temporarily failing | Retry with backoff or fail over to a similar model |
| 502 | null | Upstream unavailable | Retry later |
Retries & timeouts
- Retry only 429 and 5xx, with exponential backoff and jitter (1s, 2s, 4s… up to 5 tries). Don't retry 400/401/402/403/404.
- A retried request that already completed is billed again. Retry only when no response arrived.
- Stream long outputs to avoid idle timeouts; for non-streaming calls use a client timeout ≥ 120s.
- The official OpenAI SDKs retry automatically; tune
max_retries/maxRetries.
client = OpenAI(
base_url="https://tokenmaster.store/v1",
api_key=os.environ["TOKENMASTER_API_KEY"],
max_retries=3,
timeout=120,
)Request tracing
Every response carries x-tm-request-id. Log it with your own IDs and share it with support. The console's Usage page lists each request with time, model, tokens and cost.
raw = client.chat.completions.with_raw_response.create(
model="openai/gpt-6-luna",
messages=[{"role": "user", "content": "ping"}],
)
print(raw.headers["x-tm-request-id"], raw.headers.get("x-tm-cost-usd"))
resp = raw.parse()Security & compliance
- Encryption: HTTPS everywhere.
- Keys: stored only as hashes; use one key per environment and rotate regularly.
- Data: TokenMaster never trains on your requests. Each provider's own data policy applies.
- Regions: OpenAI, Anthropic, Google and xAI do not serve some regions. We apply the country you chose at sign-up and return 403
region_restrictedwhen restricted. Chinese and open models are not affected. - Usage policies: provider policies apply; violating content may be filtered (
content_filter) and abusive accounts suspended.
FAQ
Why was the reply cut off?
finish_reason: "length" means the cap was hit. Check x-tm-max-tokens; with x-tm-max-tokens-clamped: true, top up or set a larger max_tokens.
Does streaming cost more?
No — same per-token price.
Anthropic SDK or Responses API?
Yes. /v1/messages works with the Anthropic SDKs and Claude Code, and /v1/responses with the Responses API and Codex CLI (stateless) — see Anthropic & Responses APIs.
Does credit expire? Refunds?
Channel fees paid at top-up are non-refundable. Unused credit follows our Terms of Service.