<!-- TokenOS docs · P2P AI · Markdown mirror of https://tokenos.ai/docs/p2p-buy · HTML: https://tokenos.ai/docs/p2p-buy · index: https://tokenos.ai/llms.txt -->

# Buy inference

The buyer node is a local OpenAI-compatible server. Point any SDK at it and every request is routed directly to the cheapest trusted seller for that model, with a budget per session and spend limits per key. Prompts travel on an encrypted link between your machine and the seller — TokenOS never sees them.

1. **Fund credits** — Buy credits on [/p2p/buy](https://tokenos.ai/p2p/buy) with USDC or $TOS (1 credit = $0.10 of provider usage). Credits are shared with the rest of TokenOS.
2. **Create a buyer key** — On the same page create a `tos_…` key with optional daily / monthly / total limits and an expiry. The key is shown once.
3. **Run the node** — `tokenos-p2p buyer start` with the key in `TOKENOS_API_KEY`. It discovers sellers through the indexer and the DHT and dials them directly.
4. **Point your SDK at it** — Base URL `http://127.0.0.1:8377/v1`. Routes: chat/completions, completions, responses, messages (Anthropic shape), embeddings, audio/transcriptions, images/generations.
5. **Watch spend** — Sessions, the daily spend chart and price alerts live on [/p2p/buy](https://tokenos.ai/p2p/buy); `tokenos-p2p buyer sessions` lists them from the terminal.

**terminal**

```
export TOKENOS_API_KEY=tos_…               # created on tokenos.ai/p2p/buy (shown once)
npm i -g tokenos-p2p
tokenos-p2p buyer start                      # local OpenAI-compatible endpoint on http://127.0.0.1:8377/v1
curl http://127.0.0.1:8377/v1/models         # every model at least one online peer offers
```

**python — any OpenAI SDK works**

```
from openai import OpenAI
client = OpenAI(base_url="http://127.0.0.1:8377/v1", api_key="unused")   # the node holds your tos_ key
r = client.chat.completions.create(model="gpt-5.5", messages=[{"role": "user", "content": "hello"}])
print(r.choices[0].message.content)
# response headers carry x-tokenos-peer and x-tokenos-session
```

### Embeddings and audio transcription

The same routing, sessions and receipts cover two non-chat routes. `/v1/embeddings` reaches sellers that mark a service `embedding` and is billed on `usage.prompt_tokens` at the seller's input price (no output tokens). `/v1/audio/transcriptions` reaches sellers marked `audio` and is billed **per minute of audio** — the catalog shows `$ / min` for those models. Send the file as multipart (what every OpenAI SDK does); the gateway or your buyer node converts it to JSON with a base64 `file` for the encrypted hop, and the seller rebuilds the upload for its engine. Both sides read the `duration` the engine returns (`verbose_json`, used automatically for JSON formats; `text` / `srt` / `vtt` pass through and fall back to the audio size at ≈128 kbps), so buyer and seller metering agree. Files up to 25 MB. The TokenOS reference provider offers `whisper-1`, `whisper-large-v3-turbo` and `bge-m3` so the routes work before any independent seller lists a speech or embedding model; both routes need a key (they are not quoted over x402).

**embeddings + transcription**

```
# embeddings — billed on usage.prompt_tokens at the seller's input price
curl https://tokenos.ai/api/p2p/v1/embeddings -H 'Authorization: Bearer tos_…' -H 'content-type: application/json' \
  -d '{"model":"bge-m3","input":["hello world","second sentence"]}'

# audio transcription — multipart exactly like the OpenAI SDK sends it; billed per minute of audio
curl https://tokenos.ai/api/p2p/v1/audio/transcriptions -H 'Authorization: Bearer tos_…' \
  -F model=whisper-1 -F file=@meeting.mp3 -F response_format=verbose_json

# python — the same two calls through any OpenAI SDK (hosted gateway or your local buyer node)
e = client.embeddings.create(model="bge-m3", input="hello world")
t = client.audio.transcriptions.create(model="whisper-1", file=open("meeting.mp3", "rb"), response_format="verbose_json")
print(len(e.data[0].embedding), t.duration, t.text)
```

### Routing and controls

- **Routing rule** — Cheapest offer for the requested model first, then higher trust. Unscored (“new”) peers are eligible unless you set --min-trust.
- **--max-credits n** — Budget per session (default 10). The first session with a seller you have never used is capped at 10 credits regardless.
- **--min-trust n** — Skip sellers below this trust score.
- **--pin-peer <id> / x-tokenos-pin-peer** — Force a specific seller for the node or for one request (header).
- **--no-dht** — Indexer-only discovery, for networks that block outbound UDP.
- **Key limits** — Daily, monthly and total credit limits per key; the node returns 402 spend_limit_reached when one is hit. Revoke a key at any time.

### What protects you

- **Holds, not prepayment.** TokenOS holds only the session budget; whatever the seller does not meter is refunded at settlement.
- **You authorise every charge.** After each response your node signs a cumulative SpendingAuth for the tokens it counted itself. A seller claim above your own count + 15% is a dispute: you authorise only your figure and the node avoids that peer.
- **Ghosted sellers.** `buyer close-stale` requests closure; after a 15-minute grace the unspent hold is withdrawn and the session counts against the seller's trust.
- **Low-balance nudge.** Save an email on /p2p/buy and you are warned once a day when credits cannot cover another session.

### Cost

| Item | Amount |
| --- | --- |
| Credit | $0.10 of provider usage; bought with USDC or $TOS (the $TOS pack is cheaper) |
| Per-token price | Exactly what the seller announced, converted at $0.10 per credit — visible in the catalog with the savings vs the vendor list price |
| Protocol fee | 4%, deducted from the seller side — nothing is added on top of the buyer price |
| Unused hold | Refunded to your balance when the session settles or closes |

### Hosted gateway and x402 pay-per-request

Cannot run a node — a serverless function, a hosted agent, or a one-off script? Point the SDK at `https://tokenos.ai/api/p2p/v1` with your `tos_` key as the API key. TokenOS runs a buyer node for you with the same sellers, routing and session caps; your key pays from your credits. The trade-off is explicit: on the hosted path your prompts pass through the TokenOS gateway on their way to the seller, whereas the local node is relay-free.

**python — hosted gateway**

```
from openai import OpenAI
client = OpenAI(base_url="https://tokenos.ai/api/p2p/v1", api_key="tos_…")   # your P2P buyer key
r = client.chat.completions.create(model="gpt-5.5", messages=[{"role": "user", "content": "hello"}])
print(r.choices[0].message.content)   # x-tokenos-peer / x-tokenos-session headers tell you who served it
```

Agents without a TokenOS account pay per request with [x402](https://x402.org): the first call answers `402` with a `PAYMENT-REQUIRED` challenge whose USDC amount is quoted for that exact request (prompt size plus the `max_tokens` cap at the cheapest trusted peer). Pay it in USDC on Solana and retry the identical body with the transaction signature — or let an x402 v2 client sign the challenge. The resource is described at `/api/p2p/v1/x402` and carries the x402 Bazaar discovery metadata, so agent marketplaces (Coinbase Bazaar, Agentic.Market) can index it.

**x402 — pay per request**

```
curl -i https://tokenos.ai/api/p2p/v1/chat/completions -H 'content-type: application/json' \
  -d '{"model":"gpt-5.5","messages":[{"role":"user","content":"hello"}],"max_tokens":256}'
# HTTP/1.1 402 Payment Required
# PAYMENT-REQUIRED: <base64 x402 v2 challenge: accepts[].amount in USDC atomic units, payTo, asset, bazaar extension>
# body.quote → {"usd": 0.0019, "inputTokensEstimate": 27, "maxOutputTokens": 256, "model": "gpt-5.5"}

# pay the quoted USDC (SPL, Solana) to accepts[].payTo, then retry the identical body:
curl https://tokenos.ai/api/p2p/v1/chat/completions -H 'content-type: application/json' \
  -H 'X-PAYMENT: tx:<solana transaction signature>' -d '{…same body…}'
# x402 v2 clients (x402-fetch, x402 python) do this automatically: PAYMENT-SIGNATURE → PAYMENT-RESPONSE
# guardrails: 120 req/min per address, 30 req/min and 50 USDC/hour per payer
```

| Path | Who pays | Prompts seen by TokenOS | Best for |
| --- | --- | --- | --- |
| Local buyer node | Your credits (tos_ key) | Never | Developers, teams, anything latency- or privacy-sensitive |
| Hosted gateway + tos_ key | Your credits | Pass through the gateway | Serverless / hosted code that cannot run a node |
| Hosted gateway + x402 | USDC on Solana per request, quoted up front | Pass through the gateway | Autonomous agents and marketplaces with no TokenOS account |

> **Note — Quotes are upper bounds**
> An x402 quote covers the whole output cap, whether or not the model uses it, so set `max_tokens` (or `max_output_tokens`) deliberately. The same quote logic applies to `/v1/messages` (Anthropic shape — `system` counts toward the prompt) and `/v1/responses` (`input`, `instructions`, `tools`). Key holders are never quoted: they pay exactly the metered usage like a local node.

## Enterprise tier

Teams that need an availability target, priority routing and a named support channel can ask for the Enterprise tier at [/p2p/enterprise](https://tokenos.ai/p2p/enterprise) (pricing per agreement). TokenOS flags the `tos_` keys you choose as `enterprise`: the first-session cap with a new seller is lifted, the hosted gateway reserves 100-credit session holds instead of 10 (fewer settle round-trips), failover tries five sellers instead of three, Proof-of-Model-verified and bonded sellers are preferred within a 25% price band with trust breaking ties before price, up to 50 keys per wallet, and every gateway response carries `x-tokenos-tier: enterprise`. Your own daily / monthly / total spend limits stay in force. Enterprise wallets also see a monthly SLA availability report in the buyer console (hosted gateway and reference seller, measured from the same one-minute status samples as [/status](https://tokenos.ai/status); `GET /api/p2p/enterprise/sla?month=YYYY-MM`), and every session in the list carries receipt chips — enterprise priority, verified, bonded, reference seller — recorded when the session was reserved. The SLA (99.9% monthly for the hosted gateway and the reference seller, with service credits) and the support channel (Sev-1 response within an hour, 24×7) are written into the agreement — nothing about the protocol, the sellers or their posted prices changes.

Protocol details — session flow, SpendingAuth and receipt formats, public API: [protocol docs](https://tokenos.ai/p2p/docs).

---

*P2P AI · TokenOS documentation. Canonical page: https://tokenos.ai/docs/p2p-buy. All docs as Markdown: https://tokenos.ai/llms.txt. Payments on TokenOS are for metered usage only; nothing on this page is investment advice or a promise of income.*
