Tokex API reference
A drop-in, OpenAI-compatible gateway that clears your inference request against the cheapest qualifying supplier at the real-time market price — model-agnostic, with a cryptographically signed proof of delivery for every job.
You don't choose a model. You send a request; Tokex's sufficiency analyzer determines which models are sufficient for it (difficulty + required capabilities), then the market clears the cheapest ask within that perimeter. Every response carries an _tokex block with the clearing price, the supplier, the verification result, and an Ed25519-signed receipt you can verify independently.
base_url to the Tokex endpoint and model="auto" — that's the whole migration.Base URL & sandbox
All endpoints are served over HTTPS. The OpenAI-compatible surface lives under /v1; market data and trust endpoints under /api.
| Environment | Base URL |
|---|---|
| Production | https://api.tokex.exchange |
| Live sandbox | — |
Authentication
Authenticate with a secret API key in the Authorization header. Each key is scoped to a wallet and carries spend + rate limits. Keys are stored only as a SHA-256 hash, never in cleartext.
Authorization: Bearer tk-live-xxxxxxxxxxxxxxxxxxxxCreate a key
Self-serve a sandbox key with its own funded wallet. The key is returned once; only its hash is stored.
{ "api_key": "tk-live-…", "account": "key:9f3a…", "balance": 25.0, "scopes": ["trade"], "spend_limit": 25.0, "rate_limit": 30 }Quickstart
Buy inference in one call. The market routes, clears, verifies and settles — and returns the completion plus its proof.
# pip install openai from openai import OpenAI client = OpenAI(base_url="https://api.tokex.exchange/v1", api_key="om_live_…") r = client.chat.completions.create( model="auto", # the market decides — never a brand messages=[{"role": "user", "content": "Write FizzBuzz in Python."}], max_tokens=500, ) print(r.choices[0].message.content) om = r._tokex print(om["model"], om["clearing_price"], om["receipt"]["signature_hex"])
curl https://api.tokex.exchange/v1/chat/completions \ -H "Authorization: Bearer om_live_…" \ -H "Content-Type: application/json" \ -d '{ "model": "auto", "messages": [{"role":"user","content":"Write FizzBuzz in Python."}], "max_tokens": 500 }'
const res = await fetch("https://api.tokex.exchange/v1/chat/completions", { method: "POST", headers: { "Authorization": "Bearer om_live_…", "Content-Type": "application/json" }, body: JSON.stringify({ model: "auto", messages: [{ role: "user", content: "Write FizzBuzz in Python." }], max_tokens: 500 }), }); const data = await res.json(); console.log(data.choices[0].message.content, data._tokex.clearing_price);
Chat completions
Drop-in compatible with the OpenAI Chat Completions schema. The model field is accepted for compatibility but ignored — set it to "auto" and let the market route. The response is the standard OpenAI shape with an added _tokex block.
Request body
| Field | Type | Description | |
|---|---|---|---|
| messages | array | REQUIRED | The conversation, as {role, content} objects. content may include image parts to require a vision-capable perimeter. |
| model | string | optional | Accepted for compatibility and ignored. Use "auto". The analyzer selects the perimeter; the market selects the winner. |
| max_tokens | integer | optional | Max output tokens (default 1024). Billed in units of 1,000 output tokens. |
| max_price | number | optional | A limit price (USD per unit). The market will only clear at or below it; otherwise returns 402. |
| tools | array | optional | Tool/function specs. Presence requires a tool-capable perimeter. |
| stream | boolean | optional | Stream completion deltas as SSE (token stream). The _tokex block is sent on the final chunk. |
Response
{
"id": "chatcmpl-9f3a…",
"object": "chat.completion",
"model": "gpt-4o-mini", // the supplier-side model that won the clear
"choices": [{ "index": 0, "message": { "role": "assistant", "content": "def fizzbuzz(n): …" }, "finish_reason": "stop" }],
"usage": { "prompt_tokens": 14, "completion_tokens": 128, "total_tokens": 142 },
"_tokex": {
"trade_id": "trd_7c1…",
"model": "gpt-4o-mini",
"supplier_id": "sup-b",
"clearing_price": 0.0412, // USD per unit (1k tokens)
"units": 1, "cost": 0.0412, "fee": 0.0,
"perimeter": ["gpt-4o-mini", "llama-3-70b", "claude-sonnet-4"],
"verification": { "passed": true, "sla_passed": true, "quality_score": 0.92, "attempts": 1 },
"receipt": { "signature_hex": "19bbdc…c371", "pubkey_hex": "a3ف…", "payload": "{…}" }
}
}The _tokex object
Attached to every completion. It's the trade ticket: what cleared, at what price, against whom, and the proof it was delivered to spec.
| Field | Type | Description |
|---|---|---|
| trade_id | string | Unique id of the cleared trade (look it up via the receipts endpoint). |
| model | string | The instrument/model that won the clear. Informational — you never request it. |
| supplier_id | string | The supplier that filled the job. |
| clearing_price | number | Market price paid, USD per unit (1,000 output tokens). |
| units · cost · fee | number | Units cleared, total cost, and the exchange taker fee. |
| perimeter | string[] | The set of models the analyzer judged sufficient for this request. The cheapest in this set wins. |
| verification | object | passed, sla_passed (latency/throughput), quality_score (0–1), attempts (escalations before a conforming fill). |
| receipt | object | The Ed25519 proof-of-task: signature_hex, pubkey_hex, and the signed payload. See Proof-of-task. |
Grades & instruments
An instrument is a task market priced in USD, e.g. CODING/USD. A grade is a published performance specification a (model, supplier) must qualify against — it is not a hand-set tier. The qualifying-model list changes as models meet or fall below the spec.
| Grade | Min quality | Max TTFT | Min throughput | Context / output |
|---|---|---|---|---|
| FAST | 0.40 | 3,000 ms | 40 tok/s | 32k / 4k |
| PRIME | 0.70 | 1,500 ms | 33 tok/s | 200k / 16k |
You never request a grade directly — the analyzer maps your request's difficulty to the minimum sufficient grade, and the market clears within it. Qualification status per instrument is exposed on List instruments.
List instruments
The registry the analyzer routes over: capabilities, measured competence, base price, SLA, and which grades each instrument currently qualifies for.
[
{
"model_id": "claude-sonnet-4",
"capabilities": { "max_context": 200000, "max_output": 16000, "modalities": ["text"], "tools": true },
"competence": { "code": 0.86, "math": 0.81 },
"base_price_per_unit": 0.34,
"sla": { "max_ttft_ms": 1500, "min_tps": 33 },
"qualified": { "CODING/USD@FAST": true, "CODING/USD@PRIME": true },
"last_qualified_at": 1782620000.0
}
]Order book
Live supply per instrument — the open asks suppliers have posted, sorted by price. The cheapest qualifying ask is what your request clears against.
{
"claude-sonnet-4": [
{ "ask_id": "ask_1a…", "supplier_id": "sup-a", "price_per_unit": 0.3243, "capacity_units": 64 },
{ "ask_id": "ask_2b…", "supplier_id": "sup-c", "price_per_unit": 0.3411, "capacity_units": 90 }
]
}Intelligence Index
The macro signal: per instrument, spread = market_price − production_cost, where market price is the VWAP of recent clearings. A widening spread signals tight supply or surging demand — the GDP of Machine Intelligence.
[
{ "ts": 1782620001.2, "model_id": "claude-sonnet-4", "market_price": 0.3424, "prod_cost": 0.221, "spread": 0.1214 }
]Proof-of-task & receipts
Every cleared job is signed with an Ed25519 key over a payload that commits to the input hash, output hash, clearing price, measured latency/throughput, quality score and timestamp. Anyone can verify a receipt independently against the exchange's public key — no trust in the supplier required.
{ "algorithm": "ed25519", "public_key_hex": "a3f9…c371" }Verify a receipt
from nacl.signing import VerifyKey # pip install pynacl import requests pk = requests.get("https://api.tokex.exchange/api/pubkey").json()["public_key_hex"] rc = r._tokex["receipt"] VerifyKey(bytes.fromhex(pk)).verify( rc["payload"].encode(), bytes.fromhex(rc["signature_hex"])) # raises BadSignatureError if the receipt was tampered with — else it's authentic
import nacl from "tweetnacl"; const ok = nacl.sign.detached.verify( enc(rc.payload), hexToBytes(rc.signature_hex), hexToBytes(pubkeyHex)); // ok === true ⇒ the supplier delivered exactly what the receipt attests
Streaming (SSE)
A live event feed of everything happening on the market — subscribe with any EventSource client. Event types: trade, receipt, account, index, orderbook, qualification.
const es = new EventSource("https://api.tokex.exchange/api/stream"); es.addEventListener("trade", e => { const t = JSON.parse(e.data).data; console.log(t.model_id, t.clearing_price, t.units); // a fill just cleared }); es.addEventListener("index", e => updateChart(JSON.parse(e.data).data));
Agents & MCP
Tokex is machine-native: autonomous agents transact on the same order book as human buyers, through a Model Context Protocol (MCP) server. An agent authenticates with its own API key (a wallet with a spend limit) and buys at the market price — the same clear → verify → receipt → settle path as the gateway.
| MCP tool | Description |
|---|---|
| list_models | Enumerate tradeable instruments + grades and their qualification status. |
| get_orderbook | Live supply book per instrument. |
| buy_inference | Clear a request at the market price (analyzer perimeter → cheapest ask), spend-checked against the agent's wallet. |
| check_wallet | Balance + ledger for the calling agent. |
| verify_receipt | Independently check the Ed25519 proof-of-task for a trade. |
{
"mcpServers": {
"tokex": {
"command": "python",
"args": ["-m", "app.mcp_server"],
"env": { "TOKEX_AGENT_KEY": "om-agent-…" }
}
}
}Errors
Standard HTTP status codes. Errors return { "detail": "…" }.
| Status | Meaning |
|---|---|
| 200 | Cleared and verified. Completion + _tokex returned. |
| 401 | Missing or invalid API key. |
| 402 | Insufficient wallet balance, or the market couldn't clear at or below your max_price. |
| 422 | Malformed request body. |
| 502 | No conforming fill after the escalation cascade (no supplier met the grade). No charge. |
Rate limits & SLAs
Rate limits are enforced per API key and batched into machine-sized clearing windows. Each grade carries an SLA (max TTFT, min throughput) that is measured market-side on every fill — never self-reported by the supplier — and attested in the receipt. Breaching the SLA triggers a re-clear at no charge.