TokenMen Documentation

TokenMen is a unified AI model gateway that exposes models from OpenAI, Anthropic, Google, DeepSeek and more through a single OpenAI-compatible endpoint. This guide gets you integrated in minutes.

OpenAI CompatiblePay-per-TokenMulti-VendorSmart Routing

Quick Start

1

Register an account

Go to the login page and create an account. New accounts receive starter credits to begin calling the API immediately.

2

Create an API key

Once logged in, head to API Keys and click “New Key” to generate a token. Use separate keys per project so usage and limits stay clean.

3

Configure the base URL

Use the following URL as the Base URL in any OpenAI-compatible SDK or client:

http://localhost:4000/v1Copy

This is the new API entry — the LiteLLM gateway domain. The URL above reflects the current environment; production deployments set it via the NEXT_PUBLIC_GATEWAY_API_BASE_URL env var.

4

Make your first call

Swap the placeholder key for the one you just generated and run any of the snippets in the API Examples section below.

API Examples

TokenMen is fully OpenAI-compatible. Swap the base URL and API key, and your existing OpenAI client just works.

1curl http://localhost:4000/v1/chat/completions \
2 -H "Content-Type: application/json" \
3 -H "Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx" \
4 -d '{
5 "model": "anthropic/claude-sonnet-4-5",
6 "messages": [
7 {"role": "user", "content": "Hello, TokenMen!"}
8 ]
9 }'

Migrating from OpenAI

The API is wire-compatible with OpenAI. Migration is two edits: point the base URL at TokenMen and swap in a TokenMen key. Model names gain a vendor prefix (gpt-4o → openai/gpt-4o); everything else stays untouched.

 OpenAITokenMen
Base URLhttps://api.openai.com/v1http://localhost:4000/v1
API Keysk-...(OpenAI 后台)sk-myrouter-xxxxxxxxxxxxxxxx
Model namegpt-4oopenai/gpt-4o

The change is identical across OpenAI SDKs — one line:

1from openai import OpenAI
2
3client = OpenAI(
4 api_key="sk-myrouter-xxxxxxxxxxxxxxxx",
5 base_url="http://localhost:4000/v1", # the only change; was https://api.openai.com/v1
6)

Environment variables work the same way — set OPENAI_BASE_URL to the address above (see the Supported Tools section for Codex and friends).

Framework Integration

Any framework that lets you point at a custom OpenAI endpoint works out of the box — pass the base URL and key below. Minimal working snippets for three common frameworks:

openaiSDK

The official SDK, straight through, with streaming:

1from openai import OpenAI
2
3client = OpenAI(api_key="sk-myrouter-xxxxxxxxxxxxxxxx", base_url="http://localhost:4000/v1")
4
5stream = client.chat.completions.create(
6 model="anthropic/claude-sonnet-4-5",
7 messages=[{"role": "user", "content": "Tell me a one-liner joke"}],
8 stream=True,
9)
10for chunk in stream:
11 print(chunk.choices[0].delta.content or "", end="")

LangChainLangChain

ChatOpenAI accepts a custom base_url natively — use the prefixed model name from the catalog:

1from langchain_openai import ChatOpenAI
2
3llm = ChatOpenAI(
4 model="anthropic/claude-sonnet-4-5",
5 api_key="sk-myrouter-xxxxxxxxxxxxxxxx",
6 base_url="http://localhost:4000/v1", # point at this platform
7)
8
9resp = llm.invoke("Introduce yourself in one sentence")
10print(resp.content)

Vercel AI SDKVercel AI SDK

createOpenAI builds a custom provider you can compose with anything in the ai package (generateText / streamText / generateObject):

1import { createOpenAI } from "@ai-sdk/openai";
2import { generateText } from "ai";
3
4const myrouter = createOpenAI({
5 apiKey: "sk-myrouter-xxxxxxxxxxxxxxxx",
6 baseURL: "http://localhost:4000/v1",
7});
8
9const { text } = await generateText({
10 model: myrouter("anthropic/claude-sonnet-4-5"),
11 prompt: "Introduce yourself in one sentence",
12});
13
14console.log(text);

Provider Routing

On TokenMen, each "group" is a route — a provider. The same model can be served by different groups (different upstream routes) with different pricing and measured performance. Routing is determined by the group your API key belongs to; the model name stays the same.

1 · Use the key of a group

A key's group decides which route it uses. Issue a key in the group whose provider you want.

2 · The auto group: one key, all providers

Set a key to the auto group and the platform routes across every available group with automatic failover — one key spans all providers.

3 · Compare on the model page

Each model's detail page has a “Providers” tab listing per-group price, throughput, first-token latency and availability, so you can route by cost, speed or reliability.

Note: routing is set by the key's group, not a request parameter — you don't pass a provider field in the request body; switch keys (or use auto) to change routes.

Multimodal & Video

Beyond chat, TokenMen exposes OpenAI-compatible endpoints for vision understanding, image generation, image editing, and text-to-video. All endpoints share the same base URL and API key.

Image Input (Gemini / GPT / Claude)Vision

In chat/completions, upgrade content to an array mixing text and image_url parts. url accepts either a public URL or an inline data:image/...;base64 string.

1curl http://localhost:4000/v1/chat/completions \
2 -H "Content-Type: application/json" \
3 -H "Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx" \
4 -d '{
5 "model": "google/gemini-2.5-pro",
6 "messages": [
7 {
8 "role": "user",
9 "content": [
10 {"type": "text", "text": "What is in this image?"},
11 {
12 "type": "image_url",
13 "image_url": {"url": "https://example.com/photo.jpg"}
14 }
15 ]
16 }
17 ]
18 }'

Recommended models: google/gemini-2.5-pro · openai/gpt-4o · anthropic/claude-sonnet-4-5

Image Generation (/v1/images/generations)Text-to-Image

Generate images from a text prompt. Responses contain data[].url (or b64_json for some models).

1curl http://localhost:4000/v1/images/generations \
2 -H "Content-Type: application/json" \
3 -H "Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx" \
4 -d '{
5 "model": "google/imagen-3",
6 "prompt": "Cyberpunk Kyoto at night, neon rain",
7 "size": "1024x1024",
8 "n": 1
9 }'

Recommended models: openai/dall-e-3 · google/imagen-3 · black-forest-labs/flux-pro

Image Edit (/v1/images/edits)Image Edit

Upload the source image (optional mask) as multipart/form-data, with a prompt describing the edit.

1curl http://localhost:4000/v1/images/edits \
2 -H "Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx" \
3 -F image=@source.png \
4 -F mask=@mask.png \
5 -F model=openai/gpt-image-1 \
6 -F prompt="Replace the background with a starry sky and aurora" \
7 -F size=1024x1024

Note: the request must be multipart/form-data. Do not set Content-Type manually — let the SDK or curl generate the boundary.

Text-to-Video (Submit + Poll)Text-to-Video

Video generation is asynchronous: POST /v1/videos/generations to receive a task id, then poll GET /v1/videos/generations/{id} until the task completes. Typical latency is 30 s – a few minutes.

Step 1: Submit the task

1curl http://localhost:4000/v1/videos/generations \
2 -H "Content-Type: application/json" \
3 -H "Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx" \
4 -d '{
5 "model": "google/veo-2",
6 "prompt": "Cinematic slow-motion waves crashing on rocks",
7 "duration": 5,
8 "aspect_ratio": "16:9"
9 }'
10# => {"id":"task_abc123","status":"pending"}

Step 2: Poll for completion

1# Poll every few seconds until status is done or failed
2curl http://localhost:4000/v1/videos/generations/task_abc123 \
3 -H "Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx"
4
5# {
6# "id": "task_abc123",
7# "status": "done",
8# "video_url": "https://cdn.example.com/out.mp4",
9# "thumbnail_url": "https://cdn.example.com/out.jpg"
10# }

Recommended models: google/veo-2 · kling/kling-v1 · minimax/video-01. Supported parameters (duration / aspect_ratio / fps) vary per provider — check the Model Library for details.

API Reference

TokenMen is fully OpenAI-compatible. Below is the canonical reference for every available endpoint: authentication, request parameters, response fields, and error codes.

AuthenticationAuthentication

All requests use Bearer Token authentication. Include your API key in the HTTP headers.

1Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx
2Content-Type: application/json

Base URLBase URL

Common prefix for all v1 endpoints. Replace the base_url of any OpenAI SDK with this URL and it just works.

http://localhost:4000/v1Copy

Endpoint OverviewOverview

All open endpoints grouped by capability. Every path is relative to the Base URL above.

POST/v1/chat/completionsChat completions (primary)
POST/v1/completionsText completions (legacy)
POST/v1/embeddingsText embeddings
POST/v1/images/generationsText-to-image
POST/v1/images/editsImage edits (inpaint)
POST/v1/images/variationsImage variations
POST/v1/audio/speechText-to-speech (TTS)
POST/v1/audio/transcriptionsSpeech-to-text (ASR)
POST/v1/audio/translationsSpeech translation to English
POST/v1/videos/generationsText-to-video (submit task)
GET/v1/videos/generations/{id}Query video task status
POST/v1/moderationsContent moderation
POST/v1/rerankDocument rerank
GET/v1/modelsList available models
GET/v1/models/{model}Retrieve a single model

Chat CompletionsPOST

POST/v1/chat/completions

Create a multi-turn chat completion. This is the most-used endpoint and supports streaming, tool calls, JSON mode, vision input and more.

Request Body

NameTypeRequiredDescription
modelstringrequiredModel identifier, e.g. anthropic/claude-sonnet-4-5 or openai/gpt-4o.
messagesarrayrequiredMessage list. Each item has role (system/user/assistant/tool) and content (string or multimodal parts).
streambooleanoptionalStream the response as SSE chunks. Default false.
temperaturenumberoptionalSampling temperature, 0–2. Higher = more diverse. Default 1.
top_pnumberoptionalNucleus sampling threshold, 0–1. Use instead of temperature.
max_tokensintegeroptionalMaximum tokens to generate in the completion.
stopstring | string[]optionalStop strings — generation halts on any match. Up to 4.
nintegeroptionalNumber of choices to return per prompt. Default 1.
toolsarrayoptionalTool definitions for function calling.
tool_choicestring | objectoptionalControls tool selection: auto / none / a specific function.
response_formatobjectoptionalOutput format, e.g. {"type":"json_object"} to enable JSON mode.
userstringoptionalEnd-user identifier for abuse tracking on your side.

Response Example

1{
2 "id": "chatcmpl-abc123",
3 "object": "chat.completion",
4 "created": 1743000000,
5 "model": "anthropic/claude-sonnet-4-5",
6 "choices": [
7 {
8 "index": 0,
9 "message": {
10 "role": "assistant",
11 "content": "Hello! How can I help you today?"
12 },
13 "finish_reason": "stop"
14 }
15 ],
16 "usage": {
17 "prompt_tokens": 12,
18 "completion_tokens": 10,
19 "total_tokens": 22
20 }
21}

When stream=true each SSE chunk is data: { ...delta ... }, ended by data: [DONE].

Text CompletionsLegacy

POST/v1/completions

Legacy OpenAI Completion endpoint — only works with base models that accept a raw prompt. Prefer chat/completions for new work.

NameTypeRequiredDescription
modelstringrequiredModel name.
promptstring | string[]requiredPrompt string or array of prompts.
max_tokensintegeroptionalMaximum tokens to generate.
temperaturenumberoptionalSampling temperature.
top_pnumberoptionalNucleus sampling threshold.
nintegeroptionalNumber of completions.
streambooleanoptionalStream the response.
stopstring | string[]optionalStop sequences.
suffixstringoptionalSuffix appended after the completion.
echobooleanoptionalEcho the prompt in the response.

EmbeddingsPOST

POST/v1/embeddings

Convert text into vector representations for semantic search, clustering, similarity, and more.

NameTypeRequiredDescription
modelstringrequiredEmbedding model, e.g. openai/text-embedding-3-small.
inputstring | string[]requiredText or array of texts. Typical max batch is 2048.
encoding_formatstringoptionalVector encoding: float (default) or base64.
dimensionsintegeroptionalOutput dimensionality (supported by select models).
userstringoptionalEnd-user identifier.
1curl http://localhost:4000/v1/embeddings \
2 -H "Content-Type: application/json" \
3 -H "Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx" \
4 -d '{
5 "model": "openai/text-embedding-3-small",
6 "input": ["hello, world"]
7 }'

Text-to-Speech (TTS)POST

POST/v1/audio/speech

Synthesize text into an audio file. The response body is a binary audio stream (application/octet-stream).

NameTypeRequiredDescription
modelstringrequiredTTS model, e.g. openai/tts-1 or openai/tts-1-hd.
inputstringrequiredText to synthesize.
voicestringrequiredVoice id, e.g. alloy / echo / fable / onyx / nova / shimmer.
response_formatstringoptionalAudio format: mp3 (default) / opus / aac / flac / wav / pcm.
speednumberoptionalPlayback speed, 0.25–4.0. Default 1.0.
1curl http://localhost:4000/v1/audio/speech \
2 -H "Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx" \
3 -H "Content-Type: application/json" \
4 -d '{
5 "model": "openai/tts-1",
6 "voice": "alloy",
7 "input": "Welcome to TokenMen"
8 }' \
9 --output speech.mp3

Speech-to-Text (ASR)POST

POST/v1/audio/transcriptions

Transcribe audio to text in the same language. Requires multipart/form-data upload.

NameTypeRequiredDescription
filefilerequiredAudio file (mp3/mp4/m4a/wav/webm, etc), ≤ 25MB.
modelstringrequiredASR model, e.g. openai/whisper-1.
languagestringoptionalISO-639-1 language code (zh / en). Auto-detect if omitted.
promptstringoptionalOptional prompt to bias recognition (e.g. proper nouns).
response_formatstringoptionalFormat: json (default) / text / srt / vtt / verbose_json.
temperaturenumberoptionalSampling temperature, 0–1.
1curl http://localhost:4000/v1/audio/transcriptions \
2 -H "Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx" \
3 -F file=@audio.mp3 \
4 -F model=openai/whisper-1 \
5 -F response_format=text

For speech translation to English use /v1/audio/translations instead — same parameter schema.

ModerationsPOST

POST/v1/moderations

Classify whether text violates content policy (sexual, violence, hate, self-harm, etc.) and return per-category scores and flags.

NameTypeRequiredDescription
inputstring | string[]requiredText or array of texts to moderate.
modelstringoptionalModeration model, defaults to omni-moderation-latest.

RerankPOST

POST/v1/rerank

Re-rank candidate documents against a query — a standard precision stage in RAG pipelines.

NameTypeRequiredDescription
modelstringrequiredRerank model, e.g. cohere/rerank-3.
querystringrequiredQuery text.
documentsstring[]requiredCandidate documents.
top_nintegeroptionalReturn the top N results.
return_documentsbooleanoptionalInclude original document text in the response.

ModelsGET

GET/v1/models

Return the list of models available to the current API key (OpenAI-compatible shape).

1curl http://localhost:4000/v1/models \
2 -H "Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx"
GET/v1/models/{model}

Retrieve metadata for a single model. {model} is the model id (URL-encode the slash, e.g. anthropic%2Fclaude-sonnet-4-5).

Error ResponsesErrors

All error bodies follow the OpenAI convention: non-2xx HTTP status + JSON details. Common statuses:

NameTypeRequiredDescription
400bad_requestoptionalInvalid parameters, e.g. unknown model or empty messages.
401invalid_api_keyoptionalMissing / invalid / disabled API key.
402insufficient_quotaoptionalInsufficient balance — top up in the dashboard.
403model_not_allowedoptionalThis key is not authorised to call the requested model.
429rate_limitoptionalRate-limited (RPM or concurrency). Retry with exponential backoff.
500internal_erroroptionalPlatform error, safe to retry.
502/503/504upstream_erroroptionalUpstream model provider unavailable or timed out.
1{
2 "error": {
3 "message": "Incorrect API key provided: sk-***",
4 "type": "invalid_request_error",
5 "code": "invalid_api_key",
6 "param": null
7 }
8}

Rate Limits & Quotas

Limits are enforced per API key to protect upstream routes and overall stability. The defaults fit most workloads; contact support for higher throughput.

DimensionDefaultNotes
Requests per minute (RPM)~600 / KeyExceeding it returns 429; can be lowered per key
Tokens per minute (TPM)Unlimited by defaultCap configurable per key in the console
Daily request capUnlimited by defaultTypically used as a spend guardrail

Handling 429

When a key trips the limit the gateway returns 429 with a rate_limit_error body. Retry with exponential backoff (1s → 2s → 4s …, capped at 60s), honor any Retry-After response header, and check for retry storms or burst concurrency.

1{
2 "error": {
3 "message": "Rate limit exceeded for this key: ~600 RPM. Retry later.",
4 "type": "rate_limit_error",
5 "code": "rate_limit_exceeded",
6 "param": null
7 }
8}

Per-key quotas

The console's API Keys page lets you set per-key RPM, TPM and daily request caps — handy for isolating sub-users or capping project spend.

Supported Tools

These mainstream AI clients all work with OpenAI- or Claude-compatible APIs. Replace sk-myrouter-xxxxxxxxxxxxxxxx in the snippets with the key you generated in API Keys.

Claude CodeCLI

Anthropic’s official AI coding assistant. A single env file routes all requests through TokenMen.

Step 1: Edit ~/.claude/settings.json

On Windows the path is %USERPROFILE%\.claude\settings.json. Paste:

1{
2 "env": {
3 "ANTHROPIC_BASE_URL": "http://localhost:4000",
4 "ANTHROPIC_AUTH_TOKEN": "sk-myrouter-xxxxxxxxxxxxxxxx",
5 "API_TIMEOUT_MS": "600000",
6 "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
7 "ANTHROPIC_MODEL": "anthropic/claude-sonnet-4-5",
8 "ANTHROPIC_SMALL_FAST_MODEL": "anthropic/claude-haiku-4-5",
9 "ANTHROPIC_DEFAULT_SONNET_MODEL": "anthropic/claude-sonnet-4-5",
10 "ANTHROPIC_DEFAULT_OPUS_MODEL": "anthropic/claude-sonnet-4-5",
11 "ANTHROPIC_DEFAULT_HAIKU_MODEL": "anthropic/claude-haiku-4-5"
12 }
13}

Step 2: Skip the onboarding flow

Edit ~/.claude.json (Windows: %USERPROFILE%\.claude.json) and add:

1{
2 "hasCompletedOnboarding": true
3}

Now run claude and Claude Code will route all calls through TokenMen.

Codex (OpenAI)CLI

OpenAI’s official coding agent. Point OPENAI_BASE_URL at TokenMen and you’re done.

1# Add to ~/.bashrc or ~/.zshrc
2export OPENAI_BASE_URL=http://localhost:4000/v1
3export OPENAI_API_KEY=sk-myrouter-xxxxxxxxxxxxxxxx
4
5# Launch Codex
6codex

CursorIDE

AI-first code editor with built-in chat and completions.

1

Open model settings

Cursor → Settings → Models
2

Fill in your API key

Paste your token into the OpenAI API Key field:

sk-myrouter-xxxxxxxxxxxxxxxxCopy
3

Override Base URL

Enable “Override OpenAI Base URL” and use:

http://localhost:4000/v1Copy
4

Add and enable models

Add models like openai/gpt-4o or anthropic/claude-sonnet-4-5 under Model Names, click Verify, and use them in Chat or Composer.

ContinueVS Code Plugin

Open-source AI coding assistant for VS Code and JetBrains.

1

Install the extension

Search “Continue” in the VS Code marketplace and install.
2

Edit the config file

Open ~/.continue/config.json and update the models array:

1{
2 "models": [
3 {
4 "title": "GPT-5.5 (TokenMen)",
5 "provider": "openai",
6 "model": "gpt-5.5",
7 "apiBase": "http://localhost:4000/v1",
8 "apiKey": "sk-myrouter-xxxxxxxxxxxxxxxx"
9 },
10 {
11 "title": "Claude Sonnet 4.5 (TokenMen)",
12 "provider": "openai",
13 "model": "anthropic/claude-sonnet-4-5",
14 "apiBase": "http://localhost:4000/v1",
15 "apiKey": "sk-myrouter-xxxxxxxxxxxxxxxx"
16 }
17 ]
18}
3

Start chatting

Press Cmd/Ctrl + L to open the chat panel and pick a model.

ClineVS Code Plugin

Autonomous coding agent that reads, writes, and runs commands for you.

1

Install Cline

Search “Cline” in the VS Code marketplace and install.
2

Configure the API

Open the Cline sidebar → settings icon → fill in:

API Provider:OpenAI Compatible
Base URL:http://localhost:4000/v1
API Key:sk-myrouter-xxxxxxxxxxxxxxxx
Model ID:anthropic/claude-sonnet-4-5
3

Give it a task

Describe your task in the Cline panel and let the agent take it from there.

General Desktop ClientsDesktop

All of the following speak the OpenAI-compatible protocol — configuration is largely identical.

1# Settings → Model Services → Add Provider
2Type: OpenAI Compatible
3Name: TokenMen
4API URL: http://localhost:4000/v1
5API Key: sk-myrouter-xxxxxxxxxxxxxxxx
6# After saving, click “Fetch Models” to auto-load the list.

Model List

TokenMen aggregates models from OpenAI, Anthropic, Google, DeepSeek, Zhipu, Moonshot, Alibaba and ByteDance. Browse the catalog and live pricing in the Model Library.

Browse Model Library

FAQ

Still stuck? Reach us via the channels in the footer.