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.

If you can call the OpenAI API, you can call Tokex. Set 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.

EnvironmentBase URL
Productionhttps://api.tokex.exchange
Live sandbox
The live sandbox is open and runs the exact same market engine — fake money and simulated suppliers, but real routing, clearing, signed receipts and settlement. Every example on this page works against it as-is. Watch it live on the exchange →

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-xxxxxxxxxxxxxxxxxxxx

Create a key

POST/v1/keys

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 }
Open sandbox: the demo runs key-free by default. Pass X-Account: buyer:demo to bill the demo wallet, or send a real Bearer key for scoped, rate-limited, spend-capped access. Invalid key returns 401, missing scope 403, over rate limit 429, over spend cap 402. Never ship a secret key in client-side code.

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

POST/v1/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

FieldTypeDescription
messagesarrayREQUIREDThe conversation, as {role, content} objects. content may include image parts to require a vision-capable perimeter.
modelstringoptionalAccepted for compatibility and ignored. Use "auto". The analyzer selects the perimeter; the market selects the winner.
max_tokensintegeroptionalMax output tokens (default 1024). Billed in units of 1,000 output tokens.
max_pricenumberoptionalA limit price (USD per unit). The market will only clear at or below it; otherwise returns 402.
toolsarrayoptionalTool/function specs. Presence requires a tool-capable perimeter.
streambooleanoptionalStream 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.

FieldTypeDescription
trade_idstringUnique id of the cleared trade (look it up via the receipts endpoint).
modelstringThe instrument/model that won the clear. Informational — you never request it.
supplier_idstringThe supplier that filled the job.
clearing_pricenumberMarket price paid, USD per unit (1,000 output tokens).
units · cost · feenumberUnits cleared, total cost, and the exchange taker fee.
perimeterstring[]The set of models the analyzer judged sufficient for this request. The cheapest in this set wins.
verificationobjectpassed, sla_passed (latency/throughput), quality_score (0–1), attempts (escalations before a conforming fill).
receiptobjectThe 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.

GradeMin qualityMax TTFTMin throughputContext / output
FAST0.403,000 ms40 tok/s32k / 4k
PRIME0.701,500 ms33 tok/s200k / 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

GET/api/models

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

GET/api/orderbook?model_id=claude-sonnet-4

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

GET/api/index?limit=200

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.

GET/api/pubkey
{ "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
If verification ever fails the SLA or quality bar, the trade is re-cleared up a tier at no charge to you (the verify-and-escalate cascade). You are only ever billed for a conforming fill.

Streaming (SSE)

SSE/api/stream

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 toolDescription
list_modelsEnumerate tradeable instruments + grades and their qualification status.
get_orderbookLive supply book per instrument.
buy_inferenceClear a request at the market price (analyzer perimeter → cheapest ask), spend-checked against the agent's wallet.
check_walletBalance + ledger for the calling agent.
verify_receiptIndependently 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": "…" }.

StatusMeaning
200Cleared and verified. Completion + _tokex returned.
401Missing or invalid API key.
402Insufficient wallet balance, or the market couldn't clear at or below your max_price.
422Malformed request body.
502No 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.