# TokenRex — complete integration guide for AI coding agents

> Paste this whole file into Lovable, Codex, Claude Code, Cursor or any AI agent. It contains every base URL, endpoint, parameter, variant and model available on TokenRex, plus copy-ready code for each feature.

## Rules for the agent
- TokenRex is an OpenAI-compatible API gateway. Use the base URLs and endpoints below exactly.
- Ask the user for their TokenRex API key (starts with `sk-tb-`). Store it as a server-side secret named `TOKENBAZAAR_API_KEY`. Never put it in browser code or commit it.
- Always send an exact model ID from the list at the end. There is no default model. Variants (`-low`, `-high`, `-2k`, `-4k`, `-fast`, `-lite` …) are separate model IDs with their own price.
- Call the API from server code only (server function, API route or backend). For live voice in the browser, proxy through your server so the key stays hidden.
- Billing is prepaid from the user's TokenRex wallet. HTTP 402 means the wallet needs a top-up.

## Base URLs
| What | URL |
| --- | --- |
| REST API (OpenAI-compatible) | https://tokenrex.ai/api/public/v1 |
| Live voice (WebSocket) | wss://tokenrex.ai/api/public/v1/live |
| Live model list + prices (JSON) | https://tokenrex.ai/api/public/v1/models |
| Wallet balance | https://tokenrex.ai/api/public/v1/balance |
| Health check | https://tokenrex.ai/api/public/v1/health |
| Human docs | https://tokenrex.ai/docs |
| Model pages | https://tokenrex.ai/models/{model-slug} |
| Create API keys | https://tokenrex.ai/keys |
| Top up wallet | https://tokenrex.ai/wallet |
| Coding tool guides (Claude Code, Codex, Cursor…) | https://tokenrex.ai/integrations |
| This guide | https://tokenrex.ai/tokenbazaar-agent-guide.md |

## Authentication
```
Authorization: Bearer $TOKENBAZAAR_API_KEY
```
Works with the official OpenAI SDKs (Python, Node, Go, Rust), LangChain, LlamaIndex, Vercel AI SDK and any tool that accepts a custom `base_url`. Each key can be limited to specific models and given a per-minute spending cap.

## All endpoints
| Endpoint | What it does |
| --- | --- |
| `POST /v1/chat/completions` | Chat, streaming, vision and function tools |
| `POST /v1/images/generations` | Image generation |
| `POST /v1/images/edits` | Image editing |
| `POST /v1/audio/speech` | Text-to-speech |
| `POST /v1/audio/transcriptions` | Speech-to-text |
| `POST /v1/music` | Music generation (Lyria 3), MP3 out, billed per track |
| `POST /v1/embeddings` | Vector embeddings |
| `POST /v1/decisions` | Typed decisions (classify, score, route) with probabilities |
| `POST /v1/videos` | Start a Veo 3.1 video job (billed per second) |
| `GET /v1/videos/{id}` | Poll a video job (free) |
| `WSS /v1/live` | Live voice calls with GPT Live 1 ($0.05/min, billed per second) |
| `GET /v1/models` | List all available models and prices |
| `GET /v1/balance` | Remaining wallet balance (paise) |
| `POST /v1/messages` | Anthropic-style messages for Claude models |
| `POST /v1/completions` | Legacy text completions |
| `GET /v1/videos/{id}/content` | Download the finished MP4 |

## Pricing, limits and errors
- Every model is at market price (₹96 = $1). Charges come from the wallet in paise when a request completes.
- Chat and embeddings: per input/output token. OpenAI images: per text-input, image-input and image-output token. Gemini images and music: per image / per track. Video and live voice: per second.
- Each response has an `x-tokenbaazar-cost-paise` header with the exact charge.
- Rate limit: the per-minute spending cap set on the key. Over it returns 429 with the seconds to wait. No tokens-per-minute limit.

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

## Chat models: thinking levels and variants
- Chat needs only `model`, `messages` and optional `stream: true`. Other behaviour settings are ignored.
- Thinking level is chosen by model ID, not a parameter: a `-low` or `-high` suffix (where listed) selects lower or higher reasoning effort. The base ID uses the model's normal level.
- Vision: send images inside `messages` as `image_url` parts. PDFs are supported on chat models.
- Your own function `tools` work on supported models; hosted provider tools (web search, code interpreter) are not available.

## Image models: quality, size, resolution
| Model | Quality | Size / resolution | Aspect ratio | Formats | Transparent | Editing | Price (market → TokenRex) |
| --- | --- | --- | --- | --- | --- | --- | --- |
| `openai/gpt-image-2.5-sunburst` | Low / Medium / High / XHigh / Max | Flexible (size param) | Flexible (1:3 to 3:1) | PNG / JPEG / WebP | Yes | Yes (multiple references, mask) | $5 text in · $8 image in · $30 image out per 1M tokens → ₹300 text in · ₹480 image in · ₹1,800 image out per 1M tokens |
| `openai/gpt-image-2.5-flare` | Low / Medium / High / XHigh / Max | Flexible (size param) | Flexible (1:3 to 3:1) | PNG / JPEG / WebP | Yes | Yes (multiple references, mask) | $5 text in · $8 image in · $30 image out per 1M tokens → ₹300 text in · ₹480 image in · ₹1,800 image out per 1M tokens |
| `openai/gpt-image-2` | Low / Medium / High | Flexible (size param) | Flexible (1:3 to 3:1) | PNG / JPEG / WebP | No | Yes (multiple references, mask) | $5 text in · $8 image in · $30 image out per 1M tokens → ₹300 text in · ₹480 image in · ₹1,800 image out per 1M tokens |
| `openai/gpt-image-1-mini` | Low / Medium / High | 1024² / 1024×1536 / 1536×1024 | Limited | PNG / JPEG / WebP | No | Yes | $2 text in · $2.50 image in · $8 image out per 1M tokens → ₹120 text in · ₹150 image in · ₹480 image out per 1M tokens |
| `google/gemini-3-pro-image` | Fixed | 1K (default) · 2K · 4K versions | 10 ratios (image_config.aspect_ratio) | PNG | No | Yes (multiple references) | $0.134 at 1K/2K · $0.24 at 4K per image → ₹8.04 at 1K/2K · ₹14.4 at 4K per image |
| `google/gemini-3.1-flash-image` | Fixed | 1K (default) · 2K · 4K versions | 14 ratios (image_config.aspect_ratio) | PNG | No | Yes (multiple references) | $0.067 at 1K · $0.101 at 2K · $0.151 at 4K per image → ₹4.03 at 1K · ₹6.06 at 2K · ₹9.06 at 4K per image |
| `google/gemini-3.1-flash-lite-image` | Fixed | 1K only | Default only | PNG / JPEG | No | Yes | $0.0336 per image → ₹2.01 per image |
| `google/gemini-2.5-flash-image` | Fixed | 1K | Default only | PNG | No | Yes | $0.039 per image → ₹2.34 per image |

- OpenAI quality: `quality` = `low` | `medium` | `high` (GPT Image 2.5 Flare and Sunburst also `xhigh` | `max`). Lower quality costs far less.
- OpenAI size: `size` such as `1024x1024`, `1536x1024`, `1024x1536`; custom sizes must be multiples of 16.
- Format: `output_format` = `png` | `jpeg` | `webp`, optional `output_compression` 0–100. Transparent: `background: "transparent"` with PNG/WebP (Flare, Sunburst).
- Gemini resolution is picked by model ID: base = 1K, `-2k` = 2K, `-4k` = 4K. Aspect ratio: `"image_config": {"aspect_ratio": "16:9"}`.
- Editing: `POST /v1/images/edits` with the source image.

## Video models: resolution, duration, quality
| Model | Resolutions | Durations | Notes |
| --- | --- | --- | --- |
| `google/veo-3.1` | 720p, 1080p, 4k | 4, 6 or 8 s (1080p/4k must be 8 s) | Highest quality |
| `google/veo-3.1-fast` | 720p, 1080p, 4k | 4, 6 or 8 s (1080p/4k must be 8 s) | Faster, cheaper |
| `google/veo-3.1-lite` | 720p, 1080p | 4, 6 or 8 s (1080p must be 8 s) | Cheapest Veo; no 4k |
| `google/gemini-omni-1.1-flash` | 360p, 720p, 1080p, 4k | 3–10 s | Only model with 360p |

- Body: `model`, `prompt` (required), `duration_seconds`, `resolution` (default 720p), `aspect_ratio` (e.g. `16:9`, `9:16`), `negative_prompt`, `seed`, `generate_audio`, `image` (base64 or data URL for image-to-video).
- Billed per second × resolution multiplier: 360p ×0.4, 720p ×1, 1080p ×1.5, 4k ×2.5. Charged when the job starts; polling is free; failed jobs are not charged.
- Flow: `POST /v1/videos` → poll `GET /v1/videos/{id}` until `status` is `completed` or `failed` → download `GET /v1/videos/{id}/content`.

## Live voice (GPT Live 1)
- Model `openai/gpt-live-1`, audio only (use a chat model for images/vision). Full-duplex: listens and speaks at once, handles interruptions.
- Connect to `wss://tokenrex.ai/api/public/v1/live`, send `session.start` with instructions, voice, your tools and a WebRTC offer; send `gateway.heartbeat` every second (the call ends after 5 s without one).
- Voice is billed per second. Tools are defined and executed by your app (`tokenbaazar.tool.request` → `tokenbaazar.tool.result`).
- Full example in the Live voice section below, and all voices at https://tokenrex.ai/models/openai--gpt-live-1

## Prompt caching: input, writes and output
- Calls go to the Lovable AI Gateway. Eligible repeated prefixes may be cached; a cache hit is not guaranteed. Minimum prefix length and cache lifetime vary by model. Keep stable instructions/documents first and the changing question last.
- OpenAI and Gemini use eligible prompt prefixes automatically. Claude /v1/chat/completions requests get cache markers added automatically; native /v1/messages requests should include their own cache_control blocks.
| Token type | Billing |
| --- | --- |
| Fresh input | Normal input rate |
| Cached input | The exact model’s listed cached-input rate for gateway-reported cache reads; normal input rate if no separate rate is listed |
| Cache write | The listed write rate for gateway-reported cache creation; otherwise no separate write fee |
| Cached output | Not offered; generated output is billed at the standard output rate |
- Read actual usage: chat usage.prompt_tokens_details.cached_tokens; Responses usage.input_tokens_details.cached_tokens; Claude usage.cache_read_input_tokens and usage.cache_creation_input_tokens. Do not assume a cache hit based on repeated text alone.
- Chat total input includes cached input; do not add cached tokens to prompt_tokens again. Native Claude input_tokens, cache reads and cache creation are separate input categories.
- Streaming chat requests: add stream_options: { include_usage: true } to inspect the final usage event where supported.

### Native Claude cache example
```bash
curl https://tokenrex.ai/api/public/v1/messages -H "Authorization: Bearer $TOKENBAZAAR_API_KEY" -H "Content-Type: application/json" -d '{
  "model": "anthropic/claude-fable-5-1", "max_tokens": 1024,
  "system": [{"type":"text","text":"Your long reusable instructions and reference document…","cache_control":{"type":"ephemeral"}}],
  "messages": [{"role":"user","content":"Answer this new question using the reference."}]
}'
```
The short placeholder above illustrates request structure only; it is not long enough to guarantee caching. Resend the same eligible prefix with a different final question and inspect actual usage.
Full caching reference and live per-model rates: https://tokenrex.ai/docs#prompt-caching

## GPT-6 Astra Fast
- `openai/gpt-6-astra-fast` / `openai/gpt-6-sol-fast`, plus `-fast-low`, `-fast-high`, `-fast-xhigh`: same model with the chosen thinking level on priority (Fast) serving at 2x price. Normal versions accept `-low`, `-high`, `-xhigh`. GPT-6 Sol: $2 input, $0.20 cached input, $10 output per 1M tokens; no cache-write fee; cached output not offered.
- Billing follows the tier actually served: if a reply is served on standard (for example tool calls, which need the Responses path), you pay the normal Astra price.

## Every feature with code

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

Suggested models: `openai/gpt-5.5`, `openai/gpt-5.4-mini`, `google/gemini-3.6-flash`, `google/gemini-3.1-pro-preview`

**cURL**
```bash
curl https://tokenrex.ai/api/public/chat/completions \
  -H "Authorization: Bearer $TOKENBAZAAR_API_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."}
    ]
  }'
```

**Python**
```python
from openai import OpenAI

client = OpenAI(api_key="$TOKENBAZAAR_API_KEY", base_url="https://tokenrex.ai/api/public")

r = client.chat.completions.create(
    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."},
    ],
)
print(r.choices[0].message.content)
```

**Node.js**
```ts
import OpenAI from "openai";

const client = new OpenAI({ apiKey: "$TOKENBAZAAR_API_KEY", baseURL: "https://tokenrex.ai/api/public" });

const r = await client.chat.completions.create({
  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." },
  ],
});
console.log(r.choices[0].message.content);
```

### Live streaming (token-by-token)
Type-writer effect — perfect for chatbots. Set `stream: true` and read the SSE data frames.

Suggested models: `openai/gpt-5.5`, `openai/gpt-5.4-mini`, `google/gemini-3.6-flash`

**Python**
```python
from openai import OpenAI

client = OpenAI(api_key="$TOKENBAZAAR_API_KEY", base_url="https://tokenrex.ai/api/public")

with client.chat.completions.stream(
    model="openai/gpt-6-astra",
    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)
```

**Node.js**
```ts
import OpenAI from "openai";

const client = new OpenAI({ apiKey: "$TOKENBAZAAR_API_KEY", baseURL: "https://tokenrex.ai/api/public" });

const stream = await client.chat.completions.create({
  model: "openai/gpt-6-astra",
  stream: true,
  messages: [{ role: "user", content: "Write a short poem about the ocean." }],
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
```

**cURL**
```bash
curl -N https://tokenrex.ai/api/public/chat/completions \
  -H "Authorization: Bearer $TOKENBAZAAR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6-astra",
    "stream": true,
    "messages": [{"role":"user","content":"Write a short poem about the ocean."}]
  }'
```

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

Suggested models: `openai/gpt-5.5`, `openai/gpt-5.4-mini`, `google/gemini-3.1-pro-preview`, `google/gemini-3.6-flash`

**Python**
```python
from openai import OpenAI

client = OpenAI(api_key="$TOKENBAZAAR_API_KEY", base_url="https://tokenrex.ai/api/public")

r = client.chat.completions.create(
    model="openai/gpt-6-astra",
    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)
```

**Node.js**
```ts
import OpenAI from "openai";
const client = new OpenAI({ apiKey: "$TOKENBAZAAR_API_KEY", baseURL: "https://tokenrex.ai/api/public" });

const r = await client.chat.completions.create({
  model: "openai/gpt-6-astra",
  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" } },
    ],
  }],
});
console.log(r.choices[0].message.content);
```

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

Suggested models: `openai/gpt-5.5`, `openai/gpt-5.4-mini`, `google/gemini-3.6-flash`

**Python**
```python
from openai import OpenAI
client = OpenAI(api_key="$TOKENBAZAAR_API_KEY", base_url="https://tokenrex.ai/api/public")

r = client.chat.completions.create(
    model="openai/gpt-6-astra",
    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"}
```

**Node.js**
```ts
const r = await client.chat.completions.create({
  model: "openai/gpt-6-astra",
  messages: [
    { role: "system", content: "Reply ONLY with JSON: {name,email,city}." },
    { role: "user",   content: "Hi, I'm Ravi from Mumbai — ravi@example.com" },
  ],
});
console.log(JSON.parse(r.choices[0].message.content));
```

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

Suggested models: `openai/gpt-image-2.5-sunburst`, `openai/gpt-image-2.5-flare`, `google/gemini-3-pro-image`

**cURL**
```bash
curl https://tokenrex.ai/api/public/images/generations \
  -H "Authorization: Bearer $TOKENBAZAAR_API_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"
  }'
```

**Python**
```python
import requests, base64
r = requests.post(
    "https://tokenrex.ai/api/public/images/generations",
    headers={"Authorization": "Bearer $TOKENBAZAAR_API_KEY"},
    json={
        "model": "openai/gpt-image-2.5-sunburst",
        "prompt": "A cinematic sunset over the Himalayas, 4k",
        "size": "1024x1024",
    },
).json()
img_b64 = r["data"][0]["b64_json"]
open("out.png","wb").write(base64.b64decode(img_b64))
```

**Node.js**
```ts
import fs from "node:fs";

const r = await fetch("https://tokenrex.ai/api/public/images/generations", {
  method: "POST",
  headers: {
    Authorization: "Bearer $TOKENBAZAAR_API_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "openai/gpt-image-2.5-sunburst",
    prompt: "A cinematic sunset over the Himalayas, 4k",
    size: "1024x1024",
  }),
}).then(r => r.json());

fs.writeFileSync("out.png", Buffer.from(r.data[0].b64_json, "base64"));
```

### Text-to-Speech (TTS)
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.

Suggested models: `openai/gpt-4o-mini-tts`, `google/gemini-2.5-pro-tts`, `google/gemini-3.1-flash-tts-preview`

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

**Python**
```python
from openai import OpenAI
client = OpenAI(api_key="$TOKENBAZAAR_API_KEY", base_url="https://tokenrex.ai/api/public")

with client.audio.speech.with_streaming_response.create(
    model="openai/gpt-4o-mini-tts",
    voice="alloy",
    input="Hello! Welcome to TokenRex.",
) as resp:
    resp.stream_to_file("hello.mp3")
```

**Live stream (SSE)**
```bash
curl -N https://tokenrex.ai/api/public/audio/speech \
  -H "Authorization: Bearer $TOKENBAZAAR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini-tts",
    "voice": "ash",
    "input": "Namaste! Yeh live streaming audio hai.",
    "stream_format": "sse"
  }'
# Each line: data: {"type":"speech.audio.delta","audio":"<base64 mp3 chunk>"}
# Ends with: data: {"type":"speech.audio.done", ...}
```

### Speech-to-Text (STT)
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.

Suggested models: `openai/gpt-transcribe`, `openai/gpt-4o-transcribe`, `openai/gpt-4o-mini-transcribe`

**cURL**
```bash
curl https://tokenrex.ai/api/public/audio/transcriptions \
  -H "Authorization: Bearer $TOKENBAZAAR_API_KEY" \
  -F file="@hello.mp3" \
  -F model="openai/gpt-4o-mini-transcribe"
```

**Python**
```python
from openai import OpenAI
client = OpenAI(api_key="$TOKENBAZAAR_API_KEY", base_url="https://tokenrex.ai/api/public")

with open("hello.mp3", "rb") as f:
    r = client.audio.transcriptions.create(model="openai/gpt-4o-mini-transcribe", file=f)
print(r.text)
```

**Live stream (SSE)**
```bash
curl -N https://tokenrex.ai/api/public/audio/transcriptions \
  -H "Authorization: Bearer $TOKENBAZAAR_API_KEY" \
  -F file="@hello.mp3" \
  -F model="openai/gpt-4o-transcribe" \
  -F stream=true
# Words arrive live: data: {"type":"transcript.text.delta","delta":"Namaste"}
# Ends with:         data: {"type":"transcript.text.done","text":"..."}
```

### Music generation (Lyria 3)
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. Full capability list: tokenrex.ai/models/google--lyria-3-pro-preview

Suggested models: `google/lyria-3-clip-preview`, `google/lyria-3-pro-preview`

**cURL**
```bash
curl https://tokenrex.ai/api/public/music \
  -H "Authorization: Bearer $TOKENBAZAAR_API_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
```

**Python**
```python
import requests
r = requests.post("https://tokenrex.ai/api/public/music",
    headers={"Authorization": "Bearer $TOKENBAZAAR_API_KEY"},
    json={"model": "google/lyria-3-pro-preview",
          "input": "A soulful Hindi ballad with piano, strings and emotional vocals, about 2 minutes."})
r.raise_for_status()
open("song.mp3", "wb").write(r.content)
```

**JavaScript**
```js
const r = await fetch("https://tokenrex.ai/api/public/music", {
  method: "POST",
  headers: { Authorization: "Bearer $TOKENBAZAAR_API_KEY", "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "google/lyria-3-clip-preview",
    input: "Lo-fi hip hop loop, chill study beats, vinyl crackle, 30 seconds.",
    // optional: image: "data:image/png;base64,..." — set the mood from a picture
  }),
});
const blob = await r.blob(); // MP3 audio
document.querySelector("audio").src = URL.createObjectURL(blob);
```

### Video generation (Veo 3.1)
Text → video. Start a job with POST /v1/videos, then poll GET /v1/videos/{id} until it's ready.

Suggested models: `google/veo-3.1`, `google/veo-3.1-fast`, `google/veo-3.1-lite`

**cURL**
```bash
# 1) create the job (wallet is charged per second up-front)
curl https://tokenrex.ai/api/public/videos \
  -H "Authorization: Bearer $TOKENBAZAAR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google/veo-3.1-lite",
    "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 $TOKENBAZAAR_API_KEY"
```

**Python**
```python
import requests, time

H = {"Authorization": "Bearer $TOKENBAZAAR_API_KEY"}
job = requests.post("https://tokenrex.ai/api/public/videos", headers=H, json={
    "model": "google/veo-3.1-fast",
    "prompt": "A cinematic drone shot over the Himalayas at golden hour",
    "duration_seconds": 6,
    "resolution": "720p",
}).json()

while True:
    r = requests.get(f"https://tokenrex.ai/api/public/videos/{job['id']}", headers=H).json()
    if r.get("status") in ("completed", "failed"):
        print(r)
        break
    time.sleep(5)
```

**Node.js**
```ts
const H = { Authorization: "Bearer $TOKENBAZAAR_API_KEY", "Content-Type": "application/json" };

const job = await fetch("https://tokenrex.ai/api/public/videos", {
  method: "POST",
  headers: H,
  body: JSON.stringify({
    model: "google/veo-3.1-lite",
    prompt: "A cinematic drone shot over the Himalayas at golden hour",
    duration_seconds: 8,
    resolution: "1080p",
  }),
}).then((r) => r.json());

let out;
do {
  await new Promise((r) => setTimeout(r, 5000));
  out = await fetch(`https://tokenrex.ai/api/public/videos/${job.id}`, { headers: H }).then((r) => r.json());
} while (out.status !== "completed" && out.status !== "failed");
console.log(out);
```

### Live voice & tools (GPT Live 1)
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. Full capability list, all 12 voices and the pricing table: tokenrex.ai/models/openai--gpt-live-1

Suggested models: `openai/gpt-live-1`

**Browser JS**
```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=$TOKENBAZAAR_API_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 $TOKENBAZAAR_API_KEY", "Content-Type": "application/json" },
    body: JSON.stringify({
      model: "openai/gpt-6-astra",
      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)
Text → number array. Store in Postgres / Pinecone for semantic search.

Suggested models: `openai/text-embedding-3-small`, `openai/text-embedding-3-large`

**Python**
```python
from openai import OpenAI
client = OpenAI(api_key="$TOKENBAZAAR_API_KEY", base_url="https://tokenrex.ai/api/public")

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

**Node.js**
```ts
const r = await client.embeddings.create({
  model: "text-embedding-3-small",
  input: ["hello world", "TokenRex rocks"],
});
console.log(r.data[0].embedding.length); // 1536
```

### Typed decisions (classify / score / route)
Text in → typed answers with probabilities. Perfect for moderation, ticket routing and ranking.

Suggested models: `typesafe/jev-latest`

**cURL**
```bash
curl https://tokenrex.ai/api/public/decisions \
  -H "Authorization: Bearer $TOKENBAZAAR_API_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"]
      }
    }
  }'
```

**Python**
```python
import requests

r = requests.post("https://tokenrex.ai/api/public/decisions",
    headers={"Authorization": "Bearer $TOKENBAZAAR_API_KEY"},
    json={
        "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"},
            },
        },
    }).json()

print(r["answers"]["category"]["choice"])       # refund
print(r["answers"]["category"]["probabilities"])
print(r["answers"]["urgent"]["noul"])            # 0.0 - 1.0
```

**Node.js**
```ts
const r = await fetch("https://tokenrex.ai/api/public/decisions", {
  method: "POST",
  headers: {
    Authorization: "Bearer $TOKENBAZAAR_API_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    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",
        },
      },
      severity: {
        type: "score",
        instructions: "Rate severity.",
        criteria: ["Minor annoyance", "Moderate issue", "Severe issue"],
      },
    },
  }),
}).then((res) => res.json());

console.log(r.answers.category.choice, r.answers.severity.score);
```

### Check wallet balance
Read your remaining TokenRex wallet balance in real-time.

Suggested models: 

**cURL**
```bash
curl https://tokenrex.ai/api/public/balance \
  -H "Authorization: Bearer $TOKENBAZAAR_API_KEY"
```

**Python**
```python
import requests
r = requests.get("https://tokenrex.ai/api/public/balance",
    headers={"Authorization": "Bearer $TOKENBAZAAR_API_KEY"}).json()
print(r)  # { currency: "INR", balance_paise: 500000, ... }
```

## Every available model (0)
Prices are per 1M tokens unless the unit says otherwise. Market price → TokenRex price.
