Documentation

TokenRex API Docs

One OpenAI-compatible API for chat, images, voice, music, video, embeddings and decisions — every model at market price. Pick a feature on the left, choose a model, copy the code.

Using an AI coding agent?

Base URLs, every endpoint, all models, cached-input prices, cache-write fees and caching examples.

Open guide

Quickstart

From zero to your first response in three steps.

  1. 1
    Add balance

    Top up your wallet with UPI, cards or netbanking on the Wallet page.

  2. 2
    Create an API key

    Open API Keys and copy your sk-tb-… key. It is shown only once.

  3. 3
    Make your first call

    Use any OpenAI SDK with the base URL below and a model ID from the Models & Pricing page.

tokenrex — curl
curl https://tokenrex.ai/api/public/chat/completions \
  -H "Authorization: Bearer sk-tb-YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6-astra",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user",   "content": "Explain quantum computing in 2 lines for a 12-year-old."}
    ]
  }'

Base URL & SDKs

All endpoints are OpenAI-compatible. Point any OpenAI SDK at:

https://tokenrex.ai/api/public

Works with the official OpenAI SDKs (Python, Node, Go, Rust), LangChain, LlamaIndex, Vercel AI SDK, Continue.dev, Cursor and any tool that accepts a custom base_url.

Authentication

Send your TokenRex key as a Bearer token on every request:

Authorization: Bearer sk-tb-YOUR_KEY

Create keys on the API Keys page. Each key can be limited to specific models and given a per-minute spending cap.

Simple chat completion

POST /v1/chat/completions

Basic Q&A / assistant reply — the most common call. Works with every GPT / Gemini text model.

openai/gpt-5.5
Full model details

Frontier coding & analysis

₹480 / 1M input₹2,880 / 1M output
Supported settings
  • modelRequired. Exact model ID, including any effort suffix.
  • messagesRequired. System, user and assistant turns; image parts on vision models.
  • streamToken-by-token Server-Sent Events, same format as OpenAI.
  • max_completion_tokensCaps the reply length (up to 128,000).
  • tools / tool_choiceYour own function tools, on models that support them.
  • Thinking depthChoose it with the model ID (e.g. -low, -high). Same price per token.
  • temperature, top_p, seed, stop, penaltiesIgnored — the model's defaults are used.
  • response_formatIgnored — ask for JSON in your prompt instead.
Example prompt

You are an expert full-stack developer. When the user describes an app idea, respond with: 1) a short product summary, 2) tech stack (React + Vite + Tailwind + Supabase), 3) file tree, 4) full production-ready code for every file in fenced code blocks. Use TypeScript, shadcn/ui, clean semantic design tokens — no inline styles, no placeholders, no TODOs.

tokenrex — curl
curl https://tokenrex.ai/api/public/chat/completions \
  -H "Authorization: Bearer sk-tb-YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.5",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user",   "content": "Explain quantum computing in 2 lines for a 12-year-old."}
    ]
  }'

Live streaming (token-by-token)

POST /v1/chat/completions · stream: true

Type-writer effect — perfect for chatbots. Set `stream: true` and read the SSE data frames.

openai/gpt-5.5
Full model details

Frontier coding & analysis

₹480 / 1M input₹2,880 / 1M output
Supported settings
  • modelRequired. Exact model ID, including any effort suffix.
  • messagesRequired. System, user and assistant turns; image parts on vision models.
  • streamToken-by-token Server-Sent Events, same format as OpenAI.
  • max_completion_tokensCaps the reply length (up to 128,000).
  • tools / tool_choiceYour own function tools, on models that support them.
  • Thinking depthChoose it with the model ID (e.g. -low, -high). Same price per token.
  • temperature, top_p, seed, stop, penaltiesIgnored — the model's defaults are used.
  • response_formatIgnored — ask for JSON in your prompt instead.
Example prompt

Stream your response as you think. Build me a landing page for a SaaS product — output the full React + Tailwind component code, token by token, with brief inline comments explaining each section as you go.

tokenrex — python
from openai import OpenAI

client = OpenAI(api_key="sk-tb-YOUR_KEY", base_url="https://tokenrex.ai/api/public")

with client.chat.completions.stream(
    model="openai/gpt-5.5",
    messages=[{"role": "user", "content": "Write a short poem about the ocean."}],
) as stream:
    for event in stream:
        if event.type == "content.delta":
            print(event.delta, end="", flush=True)

Vision — analyse an image

POST /v1/chat/completions

Send an image URL (or base64 data URL) as part of the user message. Use a vision-capable model.

openai/gpt-5.5
Full model details

Frontier coding & analysis

₹480 / 1M input₹2,880 / 1M output
Supported settings
  • modelRequired. Exact model ID, including any effort suffix.
  • messagesRequired. System, user and assistant turns; image parts on vision models.
  • streamToken-by-token Server-Sent Events, same format as OpenAI.
  • max_completion_tokensCaps the reply length (up to 128,000).
  • tools / tool_choiceYour own function tools, on models that support them.
  • Thinking depthChoose it with the model ID (e.g. -low, -high). Same price per token.
  • temperature, top_p, seed, stop, penaltiesIgnored — the model's defaults are used.
  • response_formatIgnored — ask for JSON in your prompt instead.
Example prompt

You are a senior front-end engineer. Look at this screenshot of a website / Figma design and rebuild it exactly as a responsive React + Tailwind + shadcn/ui component. Return the complete code, matched colors, spacing, typography, and hover states. No placeholders.

tokenrex — python
from openai import OpenAI

client = OpenAI(api_key="sk-tb-YOUR_KEY", base_url="https://tokenrex.ai/api/public")

r = client.chat.completions.create(
    model="openai/gpt-5.5",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What is in this image? Describe it in one paragraph."},
            {"type": "image_url", "image_url": {"url": "https://picsum.photos/512"}},
        ],
    }],
)
print(r.choices[0].message.content)

Structured JSON output

POST /v1/chat/completions

Get replies as strict JSON for extraction, tagging and classification. Describe the exact JSON shape in your prompt — the response_format setting is ignored.

openai/gpt-5.5
Full model details

Frontier coding & analysis

₹480 / 1M input₹2,880 / 1M output
Supported settings
  • modelRequired. Exact model ID, including any effort suffix.
  • messagesRequired. System, user and assistant turns; image parts on vision models.
  • streamToken-by-token Server-Sent Events, same format as OpenAI.
  • max_completion_tokensCaps the reply length (up to 128,000).
  • tools / tool_choiceYour own function tools, on models that support them.
  • Thinking depthChoose it with the model ID (e.g. -low, -high). Same price per token.
  • temperature, top_p, seed, stop, penaltiesIgnored — the model's defaults are used.
  • response_formatIgnored — ask for JSON in your prompt instead.
Example prompt

You are an app-builder planner. From the user's app idea, return STRICT JSON only: { "app_name": string, "stack": string[], "pages": [{ "route": string, "purpose": string }], "components": string[], "db_tables": [{ "name": string, "columns": string[] }] }. No prose, no markdown — JSON only.

tokenrex — python
from openai import OpenAI
client = OpenAI(api_key="sk-tb-YOUR_KEY", base_url="https://tokenrex.ai/api/public")

r = client.chat.completions.create(
    model="openai/gpt-5.5",
    messages=[
        {"role": "system", "content": "Reply ONLY with JSON: {name,email,city}."},
        {"role": "user",   "content": "Hi, I'm Ravi from Mumbai — ravi@example.com"},
    ],
)
print(r.choices[0].message.content)  # {"name":"Ravi","email":"...","city":"Mumbai"}

Image generation

POST /v1/images/generations · /v1/images/edits

Text → image. Returns a base64 image or URL you can save/display.

openai/gpt-image-2.5-sunburst
Full model details

Quality-first OpenAI image generation and editing — Low to Max quality, billed by tokens

₹480 / 1M input₹2,880 / 1M output
Supported settings
  • promptRequired. Describe the image.
  • sizeOpenAI models: 1024x1024, 1024x1536, 1536x1024 and more. Gemini: pick the -2k / -4k model ID.
  • qualityOpenAI models: low, medium, high (some add xhigh, max). Priced by tokens used.
  • output_format / backgroundPNG, JPEG, WebP and transparent background on supported OpenAI models.
  • Image editingSend source images to /v1/images/edits.
Example prompt

Generate a hero image for a modern SaaS app landing page — clean, minimal, glassmorphism, indigo-to-sky gradient background, floating 3D UI cards, subtle grid, ultra-detailed 4k. No text in the image.

tokenrex — curl
curl https://tokenrex.ai/api/public/images/generations \
  -H "Authorization: Bearer sk-tb-YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-image-2.5-sunburst",
    "prompt": "A cinematic sunset over the Himalayas, ultra-detailed, 4k",
    "size": "1024x1024"
  }'

Image quality, resolution, pricing and editing

Every price below is the official provider price converted at ₹96 per US dollar, and you pay exactly that price. OpenAI image models are billed by the tokens the request actually uses, so Low quality costs far less than Max. Gemini image models are billed per image, and each resolution has its own model ID.

ModelQualitySize / resolutionAspect ratioFormatsTransparentEditingPrice
openai/gpt-image-2.5-sunburst
Low / Medium / High / XHigh / MaxFlexible (size param)Flexible (1:3 to 3:1)PNG / JPEG / WebPYesYes (multiple references, mask)
₹300 text in · ₹480 image in · ₹1,800 image out per 1M tokens
At 1024×1024: Low ≈ ₹0.36, Medium ≈ ₹0.8, High ≈ ₹3.16, XHigh ≈ ₹5.62, Max ≈ ₹12.65 per image. Larger sizes use more tokens.
openai/gpt-image-2.5-flare
Low / Medium / High / XHigh / MaxFlexible (size param)Flexible (1:3 to 3:1)PNG / JPEG / WebPYesYes (multiple references, mask)
₹300 text in · ₹480 image in · ₹1,800 image out per 1M tokens
Same token rates as Sunburst; tuned for speed. At 1024×1024: Low ≈ ₹0.36, Medium ≈ ₹0.8, High ≈ ₹3.16, Max ≈ ₹12.65.
openai/gpt-image-2
Low / Medium / HighFlexible (size param)Flexible (1:3 to 3:1)PNG / JPEG / WebPNoYes (multiple references, mask)
₹300 text in · ₹480 image in · ₹1,800 image out per 1M tokens
At 1024×1024: Low ≈ ₹0.36, Medium ≈ ₹3.16, High ≈ ₹12.65. $15/M is OpenAI Batch pricing, which does not apply to live requests.
openai/gpt-image-1-mini
Low / Medium / High1024² / 1024×1536 / 1536×1024LimitedPNG / JPEG / WebPNoYes
₹120 text in · ₹150 image in · ₹480 image out per 1M tokens
Being retired upstream — choose GPT Image 2.5 Flare for new work.
google/gemini-3-pro-image
Fixed1K (default) · 2K · 4K versions10 ratios (image_config.aspect_ratio)PNGNoYes (multiple references)
₹8.04 at 1K/2K · ₹14.4 at 4K per image
Use google/gemini-3-pro-image-2k or -4k for higher resolution.
google/gemini-3.1-flash-image
Fixed1K (default) · 2K · 4K versions14 ratios (image_config.aspect_ratio)PNGNoYes (multiple references)
₹4.03 at 1K · ₹6.06 at 2K · ₹9.06 at 4K per image
Use google/gemini-3.1-flash-image-2k or -4k. 0.5K is not available through the gateway.
google/gemini-3.1-flash-lite-image
Fixed1K onlyDefault onlyPNG / JPEGNoYes
₹2.01 per image
2K is rejected by the provider; no higher-resolution versions.
google/gemini-2.5-flash-image
Fixed1KDefault onlyPNGNoYes
₹2.34 per image
Older model kept for existing apps.

How to use each control

  • Quality (OpenAI): send quality as low, medium or high. GPT Image 2.5 Flare and Sunburst also accept xhigh and max. If you leave it out, high is used.
  • Size (OpenAI): send size such as 1024x1024, 1536x1024 or 1024x1536. Custom sizes must be multiples of 16, between 1:3 and 3:1, up to 3840 px per side. Bigger images use more tokens and cost more.
  • File format: output_format = png, jpeg or webp, with optional output_compression 0–100.
  • Transparent background: GPT Image 2.5 Flare and Sunburst accept background: "transparent" with PNG or WebP. Tested: Sunburst Max returned a real transparent PNG.
  • Resolution (Gemini): pick the model ID — google/gemini-3.1-flash-image (1K), -2k or -4k; same for google/gemini-3-pro-image. Tested: 1K returned 1024×1024, 2K returned 2048×2048, 4K returned 4096×4096. Lite and 2.5 Flash are 1K only.
  • Aspect ratio (Gemini 3 Pro / 3.1 Flash): send "image_config": {"aspect_ratio": "16:9"}. Tested: 3.1 Flash 4K at 16:9 returned 5504×3072. Gemini does not accept OpenAI quality, size, format or background fields.
  • Editing: POST /v1/images/edits with one image or several image[] files, in order. OpenAI models also accept a PNG mask. Gemini makes one image per request (n=1).
  • Charges: you only pay for images actually returned. A failed request is refunded. The exact charge is in the x-tokenbaazar-cost-paise response header.

Tested token usage at 1024×1024

Image-output tokens from real requests (one image each). Multiply by ₹1,440 per 1M tokens for your price.

openai/gpt-image-2
Low 196 · Medium 1,756 · High 7,024
openai/gpt-image-2.5-flare
Low 196 · Medium 439 · High 1,756 · XHigh 3,122 · Max 7,024
openai/gpt-image-2.5-sunburst
Low 196 · Medium 439 · High 1,756 · XHigh 3,122 · Max 7,024

OpenAI pricing · Gemini pricing · OpenAI image controls · Gemini image controls

tokenrex — openai quality
curl https://tokenrex.ai/api/public/v1/images/generations \
  -H "Authorization: Bearer $TOKENBAZAAR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"openai/gpt-image-2.5-sunburst","prompt":"A blue ceramic cup, isolated","quality":"low","size":"1024x1024","background":"transparent","output_format":"png"}'

Text-to-Speech (TTS)

POST /v1/audio/speech

Text → MP3 audio. Download the file, or add "stream_format": "sse" (OpenAI models) to get audio chunks live as they are made — playback can start in under a second.

openai/gpt-4o-mini-tts
Full model details

OpenAI streaming TTS

₹1.43 / 1K chars
Supported settings
  • inputRequired. The text to speak.
  • voiceOpenAI and Gemini each have their own voice list (use the picker).
Example prompt

Welcome to my app! I'm your AI assistant — describe what you want to build and I'll generate the code for you.

tokenrex — curl
curl https://tokenrex.ai/api/public/audio/speech \
  -H "Authorization: Bearer sk-tb-YOUR_KEY" \
  -H "Content-Type: application/json" \
  -o hello.mp3 \
  -d '{
    "model": "openai/gpt-4o-mini-tts",
    "voice": "alloy",
    "input": "Hello! Welcome to TokenRex."
  }'

Speech-to-Text (STT)

POST /v1/audio/transcriptions

Audio file → transcript. Upload MP3/WAV/M4A and get plain text, or send stream=true to receive the words live as transcript.text.delta events. Hindi and Hinglish work.

openai/gpt-transcribe
Full model details

Latest OpenAI speech-to-text — context, keyword and language hints for names & specialist words

₹0.432 / audio minute
Supported settings
  • fileRequired. Audio file upload (multipart).
  • languageOptional hint; auto-detected when omitted.
Example prompt

(Upload any audio file)

tokenrex — curl
curl https://tokenrex.ai/api/public/audio/transcriptions \
  -H "Authorization: Bearer sk-tb-YOUR_KEY" \
  -F file="@hello.mp3" \
  -F model="openai/gpt-transcribe"

Music generation (Lyria 3)

POST /v1/music

Text (or an image) → 48 kHz stereo MP3 music. Lyria 3 Clip makes 30-second clips and loops ($0.04/clip); Lyria 3 Pro makes full songs up to ~3 minutes with verses, choruses, bridges and timed lyrics ($0.08/song) at market price. Control genre, BPM, key/scale, mood, instruments, vocals and arrangement through the prompt; supply custom lyrics with [Verse]/[Chorus] tags.

google/lyria-3-clip-preview
Full model details

30-second music clips, loops and previews — vocals or instrumentals, from text or an image

₹3.84 / clip
Supported settings
  • Text promptGenre, BPM, key, mood, instruments, vocals and lyrics all go in the prompt.
  • Image inspirationOptional inline image to set the mood.
  • stream / backgroundNot supported — one call returns one MP3 track.
Example prompt

An upbeat Bollywood-style pop track with sitar, tabla and a catchy female vocal hook.

tokenrex — curl
curl https://tokenrex.ai/api/public/music \
  -H "Authorization: Bearer sk-tb-YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google/lyria-3-clip-preview",
    "input": "An upbeat Bollywood-style pop track with sitar, tabla and a catchy female vocal hook."
  }' \
  --output track.mp3

Video generation (Veo 3.1)

POST /v1/videos · GET /v1/videos/{id}

Text → video. Start a job with POST /v1/videos, then poll GET /v1/videos/{id} until it's ready.

google/veo-3.1
Full model details

Highest-quality Veo video

₹38.4 / second
Supported settings
  • promptRequired. Describe the scene.
  • resolution720p, 1080p or 4k depending on the model.
  • duration_seconds4, 6 or 8 seconds. Billed per second.
  • PollingStart the job, then poll GET /v1/videos/{id} (free) until done.
Example prompt

A cinematic drone shot flying over the Himalayas at golden hour, snow peaks, volumetric light, 8 seconds.

tokenrex — curl
# 1) create the job (wallet is charged per second up-front)
curl https://tokenrex.ai/api/public/videos \
  -H "Authorization: Bearer sk-tb-YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google/veo-3.1",
    "prompt": "A cinematic drone shot over the Himalayas at golden hour",
    "duration_seconds": 6,
    "resolution": "720p"
  }'

# 2) poll until status = completed (polling is free)
curl https://tokenrex.ai/api/public/videos/VIDEO_ID \
  -H "Authorization: Bearer sk-tb-YOUR_KEY"

Live voice & tools (GPT Live 1)

WSS /v1/live

Build real-time full-duplex voice agents that listen and speak at the same time, handle interruptions, and hand tasks to customer-defined weather, search, browser, or API tools. Voice is $0.05/min (the official $0.05/min, billed per second); delegated backend models and tools use their normal usage price. GPT Live is audio-only.

openai/gpt-live-1
Full model details

Real-time two-way voice conversation — phone-call style, billed per second

₹0.08 / second
Supported settings
  • Voice in / voice outFull duplex with interruptions. Billed per second.
  • Function toolsYour own tools; their usage is billed at normal prices.
  • Image / video inputGPT Live is audio-only.
Example prompt

A friendly Hindi-English customer support agent for my shop that answers calls, takes orders and speaks first with a short greeting.

tokenrex — browser js
// 1) microphone + WebRTC offer
const mic = await navigator.mediaDevices.getUserMedia({ audio: true });
const pc = new RTCPeerConnection();
mic.getTracks().forEach((t) => pc.addTrack(t, mic));
pc.createDataChannel("oai-events");
const audio = new Audio(); audio.autoplay = true;
pc.ontrack = (e) => (audio.srcObject = e.streams[0]);
await pc.setLocalDescription(await pc.createOffer());
await new Promise((r) => pc.iceGatheringState === "complete" ? r() :
  pc.addEventListener("icegatheringstatechange", () => pc.iceGatheringState === "complete" && r()));

// 2) connect to TokenRex (use a server-side proxy in production to hide your key)
const ws = new WebSocket("wss://tokenrex.ai/api/public/v1/live?key=sk-tb-YOUR_KEY");
ws.onopen = () => ws.send(JSON.stringify({
  type: "session.start",
  session: {
    instructions: "You are a friendly assistant. Use customer tools when needed and ask for confirmation before sensitive actions.",
    audio: { output: { voice: "marin" } },
  },
  tools: [
    { name: "get_weather", description: "Current weather from my app's weather service" },
    { name: "web_search", description: "Current web results from my app's search service" },
    { name: "browser_action", description: "A user-approved browser action executed by my app" },
  ],
  transport: { type: "webrtc", sdp: pc.localDescription.sdp },
}));

// 3) apply the answer + send a heartbeat every second (call ends after 5s without one)
let hb;
ws.onmessage = async (m) => {
  const ev = JSON.parse(m.data);
  if (ev.type === "gateway.session.created") {
    await pc.setRemoteDescription({ type: "answer", sdp: ev.transport.sdp });
    hb = setInterval(() => ws.send(JSON.stringify({ type: "gateway.heartbeat" })), 1000);
  }
  if (ev.type === "session.usage.updated") console.log("seconds:", ev.usage.seconds);
  // Your app chooses and executes the right tool. TokenRex never controls
  // the computer or calls third-party APIs without your app's permission.
  if (ev.type === "tokenbaazar.tool.request") {
    const result = await runMyApprovedTool(ev.transcript); // weather/search/browser/etc.
    ws.send(JSON.stringify({
      type: "tokenbaazar.tool.result",
      call_id: ev.call_id,
      name: result.name,
      output: result.output,
    }));
  }
  if (ev.type === "tokenbaazar.error") console.error(ev.error.message);
};

// 4) Camera or screen vision uses a separate TokenRex vision request.
// Capture only after the user grants permission and clicks your visible control.
async function shareVisualContext(dataUrl, source = "screen") {
  const vision = await fetch("https://tokenrex.ai/api/public/chat/completions", {
    method: "POST",
    headers: { Authorization: "Bearer sk-tb-YOUR_KEY", "Content-Type": "application/json" },
    body: JSON.stringify({
      model: "openai/gpt-live-1",
      messages: [{ role: "user", content: [
        { type: "text", text: "Describe visible text, controls and objects accurately. Do not guess hidden details." },
        { type: "image_url", image_url: { url: dataUrl } },
      ] }],
    }),
  }).then((r) => r.json());
  ws.send(JSON.stringify({
    type: "tokenbaazar.context.append",
    source,
    content: vision.choices[0].message.content,
  }));
}

// 5) hang up
function endCall() {
  clearInterval(hb);
  ws.send(JSON.stringify({ type: "session.close" }));
  mic.getTracks().forEach((t) => t.stop());
  pc.close();
}

Embeddings (vector search)

POST /v1/embeddings

Text → number array. Store in Postgres / Pinecone for semantic search.

openai/text-embedding-3-small
Full model details

Lightweight embeddings

₹1.92 / 1M input
Supported settings
  • inputA string or an array of strings. Billed per input token.
Example prompt

Embed my app's docs / codebase so users can ask questions in natural language and get answers grounded in the actual source files (RAG for an AI app builder).

tokenrex — python
from openai import OpenAI
client = OpenAI(api_key="sk-tb-YOUR_KEY", base_url="https://tokenrex.ai/api/public")

r = client.embeddings.create(
    model="openai/text-embedding-3-small",
    input=["hello world", "TokenRex rocks"],
)
print(len(r.data[0].embedding))  # 1536

Typed decisions (classify / score / route)

POST /v1/decisions

Text in → typed answers with probabilities. Perfect for moderation, ticket routing and ranking.

typesafe/jev-latest
Full model details

Typed decisions with probabilities — classification, scoring and routing

₹4.03 / 1M input
Supported settings
  • questionsTyped questions (choice, score, yes/no) answered with probabilities.
Example prompt

Classify incoming support tickets into refund / shipping / technical / other, flag urgency, and score severity so my app can auto-route them.

tokenrex — curl
curl https://tokenrex.ai/api/public/decisions \
  -H "Authorization: Bearer sk-tb-YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "typesafe/jev-latest",
    "state": "Customer says: my order never arrived and I want a refund.",
    "questions": {
      "category": {
        "type": "choice",
        "instructions": "Classify the support ticket.",
        "criteria": {
          "refund": "Wants money back",
          "shipping": "Delivery problem",
          "technical": "Product not working",
          "other": "Anything else"
        }
      },
      "urgent": {
        "type": "noul",
        "instructions": "Is this urgent?",
        "criteria": { "true": "Needs action today", "false": "Can wait" }
      },
      "severity": {
        "type": "score",
        "instructions": "Rate severity.",
        "criteria": ["Minor annoyance", "Moderate issue", "Severe issue"]
      }
    }
  }'

Check wallet balance

GET /v1/balance

Read your remaining TokenRex wallet balance in real-time.

tokenrex — curl
curl https://tokenrex.ai/api/public/balance \
  -H "Authorization: Bearer sk-tb-YOUR_KEY"

Pricing & billing

Every model runs at its real market price (converted at ₹96 per US dollar). Charges are taken from your wallet in paise when a request completes:

  • Chat and embeddings — by input and output tokens.
  • OpenAI images — by text-input, image-input and image-output tokens.
  • Gemini images, music — per image or per track. Video and live voice — per second.

Prompt caching. Eligible repeated input prefixes can be charged at this model’s cached-input rate when the gateway reports a cache hit. Cache creation uses the listed cache-write rate where applicable. Output is always billed at the standard output rate. See Prompt caching & rates for every chat model’s live rates, usage fields and request examples.

GPT-6 Astra Fast and GPT-6 Sol Fast — openai/gpt-6-astra-fast or openai/gpt-6-sol-fast, plus -fast-low, -fast-high, -fast-xhigh: the same model with that thinking level on priority (faster) serving at 2x price. Normal versions also take -low, -high, -xhigh. Billing follows what was actually served: requests with tools run on standard serving and are billed at the normal price.

Jev Latest (typesafe/jev-latest) costs $0.042 per 1M input tokens at market, and the same on TokenRex.

Each response includes an x-tokenbaazar-cost-paise header with the exact charge. Your Dashboard shows what you spent next to the market price.

Prompt caching & rates

Cached input reuses an eligible unchanged prompt prefix. Requests still go to the Lovable AI Gateway; a cache hit depends on the model, prefix length and cache lifetime, and is not guaranteed.

Token typeHow it is billed
Fresh inputNormal input rate for tokens not read from or written to cache.
Cached inputThis exact model’s cached-input rate when the gateway reports a cache read. If no separate rate is listed, the normal input rate applies.
Cache writeThe listed write rate when the gateway reports cache creation; otherwise no separate write fee.
Cached outputNot offered. Generated output uses the standard output rate.

OpenAI and Gemini use eligible prompt prefixes automatically. Claude chat requests receive cache markers automatically. For native Claude Messages, mark stable content with cache_control. Keep the reusable prefix unchanged and put the new question last.

// Native Claude Messages: mark a reusable system block
"system": [{ "type": "text", "text": "Your long reusable instructions…",
  "cache_control": { "type": "ephemeral" } }]

// Inspect actual cache use in response usage:
// Chat: usage.prompt_tokens_details.cached_tokens
// Responses: usage.input_tokens_details.cached_tokens
// Claude: usage.cache_read_input_tokens / cache_creation_input_tokens

Rates below come from the live enabled-model list and include each thinking and Fast variant. These are model-specific token rates, not promotional discounts.

Exact chat modelCached input / 1MCache write / 1MCached output

Rate limits

Each key has a per-minute spending cap you set yourself. Go over it and the API returns 429 with a message like "Please wait 8s". There is no tokens-per-minute limit.

Error codes

CodeMeaning
400A setting this model does not accept (e.g. an unsupported size or quality)
401Invalid or revoked API key
402Wallet balance too low — top up on the Wallet page
403This key is not allowed to use this model
429Per-minute spending cap reached — wait the number of seconds shown
5xxUpstream provider error — failed requests are not charged

Security

Keys are stored hashed — only the prefix (sk-tb-abcd…) is shown after creation. Revoke a key on the API Keys page and it stops working immediately.

All endpoints

EndpointWhat it does
POST /v1/chat/completionsChat, streaming, vision and function tools
POST /v1/images/generationsImage generation
POST /v1/images/editsImage editing
POST /v1/audio/speechText-to-speech
POST /v1/audio/transcriptionsSpeech-to-text
POST /v1/musicMusic generation (Lyria 3), MP3 out, billed per track
POST /v1/embeddingsVector embeddings
POST /v1/decisionsTyped decisions (classify, score, route) with probabilities
POST /v1/videosStart a Veo 3.1 video job (billed per second)
GET /v1/videos/{id}Poll a video job (free)
WSS /v1/liveLive voice calls with GPT Live 1 ($0.05/min, billed per second)
GET /v1/modelsList all available models and prices
GET /v1/balanceRemaining wallet balance (paise)

Model catalog

163 models. Call GET /v1/models for the live list or browse Models & Pricing. Always send the full vendor/model ID — variants such as -2k, -4k or -high are separate IDs.

Chat & reasoning130 models

OpenAI-compatible /v1/chat/completions with live token streaming.

Image generation12 models

/v1/images/generations and /v1/images/edits.

Text-to-speech5 models

/v1/audio/speech — MP3/WAV audio out.

Speech-to-text4 models

/v1/audio/transcriptions — audio file in, text out.

Embeddings4 models

/v1/embeddings for search, RAG and clustering.

Video generation4 models

POST /v1/videos to start a job, GET /v1/videos/{id} to poll.

Typed decisions1 models

POST /v1/decisions — classification, scoring and routing with probabilities.

Live voice1 models

WebSocket wss://tokenrex.ai/api/public/v1/live — real-time voice calls, billed per second.

Music generation2 models

POST /v1/music — text or image in, MP3 music out.

Coding tools & BYOK

Use your TokenRex key inside Claude Code, Codex, Xcode, Cursor, VS Code extensions and other bring-your-own-key apps. Each tool has a step-by-step guide.

Browse all integration guides

Are we missing something?

Need another example, a clearer explanation or a new guide? Send a suggestion.