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.
Quick Start
Register an account
Go to the login page and create an account. New accounts receive starter credits to begin calling the API immediately.
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.
Configure the base URL
Use the following URL as the Base URL in any OpenAI-compatible SDK or client:
http://localhost:4000/v1CopyThis 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.
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.
| OpenAI | TokenMen | |
|---|---|---|
| Base URL | https://api.openai.com/v1 | http://localhost:4000/v1 |
| API Key | sk-...(OpenAI 后台) | sk-myrouter-xxxxxxxxxxxxxxxx |
| Model name | gpt-4o | openai/gpt-4o |
The change is identical across OpenAI SDKs — one line:
1from openai import OpenAI23client = OpenAI(4 api_key="sk-myrouter-xxxxxxxxxxxxxxxx",5 base_url="http://localhost:4000/v1", # the only change; was https://api.openai.com/v16)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 OpenAI23client = OpenAI(api_key="sk-myrouter-xxxxxxxxxxxxxxxx", base_url="http://localhost:4000/v1")45stream = 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 ChatOpenAI23llm = ChatOpenAI(4 model="anthropic/claude-sonnet-4-5",5 api_key="sk-myrouter-xxxxxxxxxxxxxxxx",6 base_url="http://localhost:4000/v1", # point at this platform7)89resp = 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";34const myrouter = createOpenAI({5 apiKey: "sk-myrouter-xxxxxxxxxxxxxxxx",6 baseURL: "http://localhost:4000/v1",7});89const { text } = await generateText({10 model: myrouter("anthropic/claude-sonnet-4-5"),11 prompt: "Introduce yourself in one sentence",12});1314console.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": 19 }'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=1024x1024Note: 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 failed2curl http://localhost:4000/v1/videos/generations/task_abc123 \3 -H "Authorization: Bearer sk-myrouter-xxxxxxxxxxxxxxxx"45# {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-xxxxxxxxxxxxxxxx2Content-Type: application/jsonBase 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/v1CopyEndpoint OverviewOverview
All open endpoints grouped by capability. Every path is relative to the Base URL above.
/v1/chat/completionsChat completions (primary)/v1/completionsText completions (legacy)/v1/embeddingsText embeddings/v1/images/generationsText-to-image/v1/images/editsImage edits (inpaint)/v1/images/variationsImage variations/v1/audio/speechText-to-speech (TTS)/v1/audio/transcriptionsSpeech-to-text (ASR)/v1/audio/translationsSpeech translation to English/v1/videos/generationsText-to-video (submit task)/v1/videos/generations/{id}Query video task status/v1/moderationsContent moderation/v1/rerankDocument rerank/v1/modelsList available models/v1/models/{model}Retrieve a single modelChat CompletionsPOST
/v1/chat/completionsCreate a multi-turn chat completion. This is the most-used endpoint and supports streaming, tool calls, JSON mode, vision input and more.
Request Body
| Name | Type | Required | Description |
|---|---|---|---|
model | string | required | Model identifier, e.g. anthropic/claude-sonnet-4-5 or openai/gpt-4o. |
messages | array | required | Message list. Each item has role (system/user/assistant/tool) and content (string or multimodal parts). |
stream | boolean | optional | Stream the response as SSE chunks. Default false. |
temperature | number | optional | Sampling temperature, 0–2. Higher = more diverse. Default 1. |
top_p | number | optional | Nucleus sampling threshold, 0–1. Use instead of temperature. |
max_tokens | integer | optional | Maximum tokens to generate in the completion. |
stop | string | string[] | optional | Stop strings — generation halts on any match. Up to 4. |
n | integer | optional | Number of choices to return per prompt. Default 1. |
tools | array | optional | Tool definitions for function calling. |
tool_choice | string | object | optional | Controls tool selection: auto / none / a specific function. |
response_format | object | optional | Output format, e.g. {"type":"json_object"} to enable JSON mode. |
user | string | optional | End-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": 2220 }21}When stream=true each SSE chunk is data: { ...delta ... }, ended by data: [DONE].
Text CompletionsLegacy
/v1/completionsLegacy OpenAI Completion endpoint — only works with base models that accept a raw prompt. Prefer chat/completions for new work.
| Name | Type | Required | Description |
|---|---|---|---|
model | string | required | Model name. |
prompt | string | string[] | required | Prompt string or array of prompts. |
max_tokens | integer | optional | Maximum tokens to generate. |
temperature | number | optional | Sampling temperature. |
top_p | number | optional | Nucleus sampling threshold. |
n | integer | optional | Number of completions. |
stream | boolean | optional | Stream the response. |
stop | string | string[] | optional | Stop sequences. |
suffix | string | optional | Suffix appended after the completion. |
echo | boolean | optional | Echo the prompt in the response. |
EmbeddingsPOST
/v1/embeddingsConvert text into vector representations for semantic search, clustering, similarity, and more.
| Name | Type | Required | Description |
|---|---|---|---|
model | string | required | Embedding model, e.g. openai/text-embedding-3-small. |
input | string | string[] | required | Text or array of texts. Typical max batch is 2048. |
encoding_format | string | optional | Vector encoding: float (default) or base64. |
dimensions | integer | optional | Output dimensionality (supported by select models). |
user | string | optional | End-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
/v1/audio/speechSynthesize text into an audio file. The response body is a binary audio stream (application/octet-stream).
| Name | Type | Required | Description |
|---|---|---|---|
model | string | required | TTS model, e.g. openai/tts-1 or openai/tts-1-hd. |
input | string | required | Text to synthesize. |
voice | string | required | Voice id, e.g. alloy / echo / fable / onyx / nova / shimmer. |
response_format | string | optional | Audio format: mp3 (default) / opus / aac / flac / wav / pcm. |
speed | number | optional | Playback 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.mp3Speech-to-Text (ASR)POST
/v1/audio/transcriptionsTranscribe audio to text in the same language. Requires multipart/form-data upload.
| Name | Type | Required | Description |
|---|---|---|---|
file | file | required | Audio file (mp3/mp4/m4a/wav/webm, etc), ≤ 25MB. |
model | string | required | ASR model, e.g. openai/whisper-1. |
language | string | optional | ISO-639-1 language code (zh / en). Auto-detect if omitted. |
prompt | string | optional | Optional prompt to bias recognition (e.g. proper nouns). |
response_format | string | optional | Format: json (default) / text / srt / vtt / verbose_json. |
temperature | number | optional | Sampling 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=textFor speech translation to English use /v1/audio/translations instead — same parameter schema.
ModerationsPOST
/v1/moderationsClassify whether text violates content policy (sexual, violence, hate, self-harm, etc.) and return per-category scores and flags.
| Name | Type | Required | Description |
|---|---|---|---|
input | string | string[] | required | Text or array of texts to moderate. |
model | string | optional | Moderation model, defaults to omni-moderation-latest. |
RerankPOST
/v1/rerankRe-rank candidate documents against a query — a standard precision stage in RAG pipelines.
| Name | Type | Required | Description |
|---|---|---|---|
model | string | required | Rerank model, e.g. cohere/rerank-3. |
query | string | required | Query text. |
documents | string[] | required | Candidate documents. |
top_n | integer | optional | Return the top N results. |
return_documents | boolean | optional | Include original document text in the response. |
ModelsGET
/v1/modelsReturn 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"/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:
| Name | Type | Required | Description |
|---|---|---|---|
400 | bad_request | optional | Invalid parameters, e.g. unknown model or empty messages. |
401 | invalid_api_key | optional | Missing / invalid / disabled API key. |
402 | insufficient_quota | optional | Insufficient balance — top up in the dashboard. |
403 | model_not_allowed | optional | This key is not authorised to call the requested model. |
429 | rate_limit | optional | Rate-limited (RPM or concurrency). Retry with exponential backoff. |
500 | internal_error | optional | Platform error, safe to retry. |
502/503/504 | upstream_error | optional | Upstream 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": null7 }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.
| Dimension | Default | Notes |
|---|---|---|
| Requests per minute (RPM) | ~600 / Key | Exceeding it returns 429; can be lowered per key |
| Tokens per minute (TPM) | Unlimited by default | Cap configurable per key in the console |
| Daily request cap | Unlimited by default | Typically 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": null7 }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": true3}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 ~/.zshrc2export OPENAI_BASE_URL=http://localhost:4000/v13export OPENAI_API_KEY=sk-myrouter-xxxxxxxxxxxxxxxx45# Launch Codex6codexCursorIDE
AI-first code editor with built-in chat and completions.
Open model settings
Fill in your API key
Paste your token into the OpenAI API Key field:
sk-myrouter-xxxxxxxxxxxxxxxxCopyOverride Base URL
Enable “Override OpenAI Base URL” and use:
http://localhost:4000/v1CopyAdd and enable models
ContinueVS Code Plugin
Open-source AI coding assistant for VS Code and JetBrains.
Install the extension
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}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.
Install Cline
Configure the API
Open the Cline sidebar → settings icon → fill in:
OpenAI Compatiblehttp://localhost:4000/v1sk-myrouter-xxxxxxxxxxxxxxxxanthropic/claude-sonnet-4-5Give it a task
General Desktop ClientsDesktop
All of the following speak the OpenAI-compatible protocol — configuration is largely identical.
1# Settings → Model Services → Add Provider2Type: OpenAI Compatible3Name: TokenMen4API URL: http://localhost:4000/v15API Key: sk-myrouter-xxxxxxxxxxxxxxxx6# 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