Developer docs

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.

Base URLhttps://tokenmaster.store/v1
FormatJSON · SSE
AuthBearer tm-…
OpenAI-compatible

Chat Completions protocol with streaming, tools, structured output and images.

One key, every model

Change model to switch between GPT, Claude, Gemini, DeepSeek, Qwen, Kimi and more.

Prepaid, per token

Charged in real time per request; requests stop before your balance runs out.

Quickstart

Three steps, about three minutes.

01

Sign up & top up

Create an account in the console and add at least $10.

02

Create an API key

Console → API keys → Create key. It is shown once — save it right away.

03

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"

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"}]
  }'
To switch models, change only 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:

HTTP
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.
Never ship a key in browser or mobile code. Anyone holding it can spend your balance. Call TokenMaster from your own server.

SDKs & tools

Anything that supports an "OpenAI-compatible" endpoint works. Configure three values:

SettingValue
Base URL / API Basehttps://tokenmaster.store/v1
API KeyYour tm-… key
ModelA 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)

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"

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/auto lets 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/messages and /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 IDDimensionsGood for
baai/bge-m31024Multilingual incl. CJK — recommended
qwen/qwen3-embedding-0.6b1024Multilingual, longer texts
baai/bge-small-en-v1.5 · bge-base-en-v1.5 · bge-large-en-v1.5384 · 768 · 1024English, ≤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)
  • Up to 100 inputs per request, 32,000 characters each; dimensions and 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-..."
  }
}
  • 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-side web_search tool 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"
  • Supported: text and image input, instructions, function and free-form (custom) tools, streaming events, text.format structured output, max_output_tokens, and reasoning.effort on OpenAI models.
  • Not supported: previous_response_id and 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-usd headers 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 model to tokenmaster/auto (or just auto). 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 model field and the x-tm-routed-model header 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-id header (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)

POST/v1/chat/completions

Generates a reply from a list of messages. Request and response match OpenAI Chat Completions.

Request body

FieldTypeDescription
model*stringModel ID from /v1/models.
messages*arrayConversation. role is system, user, assistant or tool; content is a string or an array of text / image_url parts.
max_tokensintegerMaximum tokens to generate. Defaults to 8192; may be lowered to what your balance covers — see Holds & output caps.
max_completion_tokensintegerSame as above; preferred for reasoning models and includes reasoning tokens.
streambooleanStream as server-sent events — see Streaming.
stream_optionsobjectinclude_usage is always on; the stream ends with a usage chunk.
temperaturetop_pnumbernumberSampling controls; valid ranges depend on the model.
stopstring | arrayStop sequences.
toolstool_choiceparallel_tool_callsarraystring | objectbooleanFunction calling — see Tool calling.
response_formatobjectjson_object or json_schema — see Structured output.
reasoning_effortstringReasoning effort (e.g. low/medium/high) on models that support it.
seedpresence_penaltyfrequency_penaltylogprobstop_logprobsuserintegernumbernumberbooleanintegerstringPassed through with OpenAI semantics; ignored or rejected by models that don't support them.
Unlisted fields are dropped. 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."}
    ]
  }'

Response headers

HeaderMeaning
x-tm-request-idUnique request ID — include it when contacting support.
x-tm-cost-usdAmount charged in USD (non-streaming). For streams, see Usage in the console.
x-tm-routed-modelWith smart routing (tokenmaster/auto): the model that actually answered.
x-tm-searchesWith web search on: how many searches this request made.
x-tm-max-tokensOutput cap actually applied.
x-tm-max-tokens-clampedtrue 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. Raise max_tokens or check your balance (see x-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)
Check that 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.

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

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

Python
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_tokens and billed at the output price.
  • They also consume the output cap. A small cap can end with finish_reason: "length" and no visible answer. Use max_completion_tokens ≥ 4096.
  • Where supported, reasoning_effort trades depth for speed and cost.
Python
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 tokens

GET/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"

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/auto bills 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:

math
1,200 × 2.40 / 1,000,000 = $0.002880
  300 × 12.00 / 1,000,000 = $0.003600
                          total = $0.006480

Holds & output caps

So your balance can never go negative, every request goes through three steps before reaching the model:

  1. Estimate the worst-case cost from your input length (conservatively) and the output cap.
  2. Hold that amount from your available balance. Concurrent requests hold separately.
  3. 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.

Tips: set max_tokens explicitly so holds stay small; keep enough balance for long documents on premium models; alert on /v1/balance.

Rate limits

LimitDefaultWhen exceeded
Requests per key300 / minute429 rate_limited
Concurrent requests per account16429 too_many_concurrent
Max cost per request$20400 request_too_large
Max output per request128,000 tokensCapped
Context lengthPer model400 context_length_exceeded

Need more? Contact us with the models, expected QPS and monthly token volume.

Errors

Errors follow the OpenAI format:

JSON
{
  "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"
  }
}
HTTPcodeMeaningWhat to do
400nullBad request (missing fields, n ≠ 1…)Fix the request; don't retry
400request_too_largeEstimated cost above the $20 per-request limitShorten input or lower max_tokens
400context_length_exceededInput exceeds the model's contextTrim history or use a longer-context model
401invalid_api_keyMissing, wrong or revoked keyCheck the Authorization header
402insufficient_balanceNot enough balance to start the requestTop up, or reduce input / max_tokens
403region_restrictedProvider unavailable in your regionUse another provider's model
403account_suspendedAccount suspendedContact support
404model_not_foundUnknown model IDCheck /v1/models
429rate_limitedPer-minute rate exceededRetry with backoff
429too_many_concurrentMore than 16 in-flight requestsReduce concurrency or queue
429 / 5xxnullProvider busy or temporarily failingRetry with backoff or fail over to a similar model
502nullUpstream unavailableRetry 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.
Python
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.

Python
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_restricted when 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.

Need help integrating?
Tell us your target models, expected QPS and monthly token volume.
Open console