# floprouter > The floprouter API: one HTTP API for every GPU miner and every model on FLOP Network. The router lists and scores every registered miner from chain data, picks a ready miner per request (or uses the miners you name), pays it through an on-chain payment channel, and handles the differences between models and miners. Runs on FLOP devnet; devnet and testnet FLOP have no monetary value. Base URL: https://api.floprouter.com/v1 Auth: Authorization: Bearer fr_... (a key from signing a challenge with a FLOP wallet). Request: POST /v1/chat/completions with model, messages, max_tokens; optional routing preferences in provider (order, only, ignore, sort, allow_fallbacks; a provider is a miner) and flop (payer, fallback_payer, wait_for_settlement). Tool calls are not supported. Timing: replies take about 15 to 50 s; non-streaming calls answer within about 85 s or return 202 with a session to poll; settlement follows 2 to 4 minutes later. Agent skill with every step and a verification script: https://floprouter.com/skill.md --- # Agent skill > Hand the integration to a coding agent with one prompt and a hosted skill file. ## The skill [`https://floprouter.com/skill.md`](https://floprouter.com/skill.md) is an agent skill: a Markdown file with YAML front matter (`name`, `description`) and precise steps to integrate floprouter. It covers keys, the base URL, request and response shapes, payer modes and the grant, the balance, routing, errors and what is safe to retry, streaming, timing, MCP and CLI setup, and a verification step the agent runs at the end. The same file is at `https://floprouter.com/skills/floprouter/SKILL.md` and `https://floprouter.com/.well-known/skills/floprouter/SKILL.md`, for tools that look for skills in those places. To install it as a local skill, save it as `.claude/skills/floprouter/SKILL.md` (or your agent's skills folder) in your project. ## The prompt The **Copy prompt for your agent** button copies a short prompt. Paste it into Claude Code, Cursor, Codex or any LLM chat. It tells the agent to read the skill, ask you for your key, and run the verification step when it is done. ## For agents reading these docs - [`/llms.txt`](/llms.txt) is the index. [`/llms-full.txt`](/llms-full.txt) is everything in one file. - Every page is Markdown at its path plus `.md`. - [`/openapi.json`](/openapi.json) is the schema. ## Also for agents - [MCP server](/docs/mcp/): tools for agents that speak MCP. - [CLI](/docs/cli/): the wallet steps on the user's machine. --- # Overview > What floprouter is, what happens on each request, and where to start. floprouter is one API in front of every GPU miner and every model on FLOP Network. FLOP is a Substrate chain where miners sell LLM inference and are paid through payment channels. The router lists every registered miner, scores each one from its on-chain record, and sends your request to a ready miner, or to the miners you name. You write one request shape. Models on the network differ in prompt format and decode policy, and miners differ in how a channel is opened with them. The router handles those differences, so your code does not change when a model or a miner is added. It runs on FLOP devnet today. Devnet and testnet FLOP have no monetary value. ## What happens on each request 1. **A miner is chosen.** Auto mode takes the best ready miner for the model by score. You can name miners with the `provider` object instead. 2. **A payment channel opens on chain.** Escrow for this one request is locked, normally against the miner's signed offer. 3. **The miner answers.** The reply is checked against the miner's signed receipt before the request completes. On devnet a reply takes about 15 to 50 s. 4. **The miner settles.** The settlement is final on chain 2 to 4 minutes later, in the background. Follow it with `GET /v1/sessions/{id}` or in the [playground](/playground/). ## Base URL ```text https://api.floprouter.com/v1 ``` Every path in these docs is relative to `https://api.floprouter.com`. Send your key as `Authorization: Bearer fr_...`. `https://api.floprouter.com/api/v1` serves the same routes as `https://api.floprouter.com/v1`. (not live yet) ## Where to go next | You want to | Read | | - | - | | Send a first request | [Quickstart](/docs/quickstart/) | | Pick models and miners | [Models](/docs/models/), [Provider selection](/docs/routing/) | | Keep your wallet as the payer on chain | [Payer modes](/docs/payer-modes/) | | Hand the work to a coding agent | [For agents](/docs/for-agents/) | | Use an existing SDK | [SDK compatibility](/docs/compatibility/) | | See every endpoint | [API reference](/docs/api-reference/) | ## What is live | Part | State | | - | - | | Miner directory, scores, models | Live | | Chat completions, auto and pinned routing | Live | | Session status with on-chain links | Live | | Wallet sign-in and API keys | (live) | | Your wallet as the on-chain payer (grant) | (live) | | Prepaid balance and withdrawals | (live) | | Router fee charged | (live) | | Streaming (text forwarded as the miner sends it) | (live) | | Tool calls | Not supported | The website checks the endpoints against the API it talks to on every visit; the [status page](/status/) shows the result. ## For agents and LLMs - [`/skill.md`](/skill.md) is an agent skill with every step to integrate floprouter. The "Copy prompt for your agent" button points an agent at it. - [`/llms.txt`](/llms.txt) lists every page. [`/llms-full.txt`](/llms-full.txt) is the whole documentation in one file. - Every docs page is plain Markdown at its path plus `.md`, for example [`/docs/quickstart.md`](/docs/quickstart.md). - The OpenAPI schema is at [`/openapi.json`](/openapi.json). --- # For miner operators > Make your miner reachable, see how it is scored, and what the router checks. Your miner is in the [directory](/miners/) as soon as it is registered on chain. To receive routed sessions, the router also needs your worker's URL. Session URLs are not on chain, so you submit it. ## Submit your endpoint Use the [form](/operators/) or: ```bash curl -X POST https://api.floprouter.com/v1/miners//endpoint \ -H "Content-Type: application/json" \ -d '{"url": "https://miner.example.org"}' ``` `200` accepted and routable, `202` recorded but not routable until the chain ties the session key to your miner, `422` rejected or unreachable. No key is needed. Anyone may submit a URL; the proof decides which miner it belongs to. ## What the router checks 1. The URL is https, canonical, and resolves to public addresses. 2. `GET /session/info` answers 401 with a session challenge, as a live worker does. 3. `POST /session/info-proof` answers a fresh random challenge with a signature for this chain. 4. The account named in the proof is a registered miner. 5. The session key that signed is tied to that miner on chain: by a signed offer of yours, or a finalized channel of yours that used it. An entry that passes 1 to 4 but not 5 is kept as "key not tied" and is not routed to. Publish a signed offer, or complete one channel, and the next check picks it up. Entries are checked again every few minutes and before every session, and dropped when they keep failing. Use a host name that is yours and not similar to floprouter, so nobody mistakes your worker for this service. ## How you are scored Your score comes from your on-chain record: how your paid sessions ended, how many and how recent, how many payers, your stake, your slashing record and your calibration. The formula is not published; every input is shown on your [miner page](/miners/). Router-measured facts (endpoint answers, proof latency) are shown separately and are not part of the score. See [miners and scores](/docs/miners/). ## Getting more sessions - Keep your calibration live and your worker reporting ready. - Publish signed session offers. Grant-mode requests use offers, and an offer ties your session key to your account. - Settle every channel. Timeouts and failed acknowledgements lower the score. --- # Miners and scores > How the directory is built, what the score is made from, and how a miner operator submits an endpoint. ## Where the list comes from Every miner in the on-chain registry is listed, reachable or not. Stake, calibration, capacity, slashing and models come from chain storage, read at a finalized block and refreshed every few minutes. Session history comes from finalized chain events: every compute channel the miner was paid through and how it ended. New miners appear on the next pass with no manual step. ## The score A number from 0 to 100, with a rank. It is computed from on-chain facts only: - how the miner's paid sessions ended: settled, timed out, acknowledgement expired, refunded, voided, fraud upheld, - how many there were, how recent, and from how many distinct payers, - stake, - slashing record: strikes, blacklist, failed acknowledgements, - the state of its hardware calibration. The exact formula is not published. Every input is returned beside the score, so anyone can judge a miner for themselves. The same chain state always gives the same score. Scores are recomputed about once a minute. Facts the router measures itself, such as whether the endpoint answers and how fast, are reported separately under `router_measured` and are not part of the score. ## Endpoints Session URLs are not on chain. The router collects candidate URLs from public sources and from operators, and accepts one only when the worker behind it proves which miner it is: 1. The URL is https, canonical, and resolves only to public addresses. 2. `GET /session/info` answers 401 with a session challenge, as a live worker does. 3. `POST /session/info-proof` answers a fresh random challenge with a signature for this chain. 4. The account named in the proof is a registered miner. 5. The session key that signed is tied to that miner on chain, by a signed offer of the miner or a finalized channel of the miner that used it. An entry that passes 1 to 4 but not 5 is kept as not yet tied and is never routed to. Entries are checked again every few minutes and before every session. | Directory label | Meaning | | - | - | | Ready | Proven, and the worker reports ready. Takes traffic. | | Live, not ready | Proven and answering, but the worker reports it is not ready. | | Key not tied | Valid proof, but the session key is not yet tied to the miner on chain. | | Down | Proven before, failing its checks now. | | No endpoint | No session URL is known. | ## Submitting an endpoint Miner operators submit their worker URL so the router can reach them. See [for miner operators](/docs/miner-operators/). ## Network totals `GET /v1/stats` returns totals for the whole network: miners, reachable miners, models, sessions routed, settle rate. (live) --- # Quickstart > Send a first request in three steps with plain HTTP. ## 1. Get a key Open the [account page](/account/), connect a Polkadot wallet (polkadot-js, Talisman or SubWallet), and sign the login message. Signing it is free and moves no funds. You get a key that starts with `fr_`. It is shown once. ```bash export FLOPROUTER_API_KEY=fr_... ``` A new key makes your wallet the payer on chain, which needs one more signature: the grant, on the same page. To skip the grant, switch the key to **Balance** there and deposit a little FLOP. See [payer modes](/docs/payer-modes/). ## 2. Pick a model ```bash curl https://api.floprouter.com/v1/models ``` A model with `available: true` has at least one ready miner. The [models page](/models/) shows the same list. No key is needed for this call. ## 3. Send a request ```bash curl curl https://api.floprouter.com/v1/chat/completions \ -H "Authorization: Bearer $FLOPROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "qwen/qwen3-8b", "messages": [{"role": "user", "content": "What is a payment channel?"}], "max_tokens": 128 }' ``` ```js fetch const res = await fetch("https://api.floprouter.com/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${process.env.FLOPROUTER_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "qwen/qwen3-8b", messages: [{ role: "user", content: "What is a payment channel?" }], max_tokens: 128, }), }); const reply = await res.json(); console.log(reply.choices[0].message.content); ``` ```python Python import os, requests res = requests.post( "https://api.floprouter.com/v1/chat/completions", headers={"Authorization": f"Bearer {os.environ['FLOPROUTER_API_KEY']}"}, json={ "model": "qwen/qwen3-8b", "messages": [{"role": "user", "content": "What is a payment channel?"}], "max_tokens": 128, }, timeout=120, ) print(res.json()["choices"][0]["message"]["content"]) ``` To use an SDK or framework instead, see [SDK compatibility](/docs/compatibility/). The call returns when the miner's reply is verified, usually in 15 to 50 s. Set client timeouts to 120 s or more. `max_tokens` sizes the escrow, so keep it close to what you need. ## 4. Read the response The body is a chat completion with two extra fields: `provider`, the miner that served it, and `flop`, the record of the session. ```json { "id": "gen-mwto3ds1-0811fd3833f3", "object": "chat.completion", "model": "qwen/qwen2.5-0.5b-instruct", "provider": "5HdTbhVY9jZCsfJVFENYF89hRfkBvoby2YxPest3XLLRhnrt", "choices": [{"index": 0, "message": {"role": "assistant", "content": "..."}, "finish_reason": "length"}], "usage": {"prompt_tokens": 6, "completion_tokens": 24, "total_tokens": 30}, "flop": { "session_id": "gen-mwto3ds1-0811fd3833f3", "status": "settling", "channel_id": "0x96cc8fd277657749a32b2acd6b0ee035fe5837785663a8d31ce4179212f3cddb", "miner": "5HdTbhVY9jZCsfJVFENYF89hRfkBvoby2YxPest3XLLRhnrt", "via": "force", "payer": {"address": "5Gmdxzsm...", "kind": "router-wallet"}, "escrow": "0.01", "miner_paid": null, "router_fee": {"percent": 5, "amount": "0.0005", "charged": false, "status": "pending"}, "on_chain": {"open_block": 4467284, "outcome": null, "outcome_block": null, "outcome_tx": null} } } ``` This is an abridged real response from devnet. Amounts are decimal strings in FLOP. ## 5. Watch it settle ```bash curl https://api.floprouter.com/v1/sessions/gen-mwto3ds1-0811fd3833f3 ``` `status` moves from `settling` to `settled`, and `miner_paid` and `on_chain.outcome_tx` fill in, 2 to 4 minutes after the reply. The channel is on the explorer at `https://explorer.devnet.flop.network/channels/`. ## Next - [Provider selection](/docs/routing/): choose miners yourself. - [Payer modes](/docs/payer-modes/): keep your wallet as the payer on chain. - [Streaming](/docs/streaming/): read the reply as it arrives. - [For agents](/docs/for-agents/): hand this to a coding agent. --- # Authentication > Wallet sign-in, API keys, and how to get a key from a script without a browser. (live) Send your key as a bearer token: ```text Authorization: Bearer fr_... ``` A key belongs to one FLOP wallet. There are no accounts, emails or passwords. Your wallet signs a one-time login message and the server gives you a key for that wallet. Signing the message is free and is not a transaction. ## In the browser Go to the [account page](/account/), connect a wallet extension and press **Sign and create key**. The key is shown once. You can keep it in that browser for the playground. ## From a script or an agent Two calls. The challenge is a short string that expires. ```bash curl -X POST https://api.floprouter.com/v1/auth/challenge \ -H "Content-Type: application/json" \ -d '{"address": "5YourWalletAddress..."}' # {"challenge": "...", "expires_at": "..."} ``` Sign the challenge string's UTF-8 bytes with the wallet's sr25519 or ed25519 key, then exchange the signature for a key: ```bash curl -X POST https://api.floprouter.com/v1/auth/keys \ -H "Content-Type: application/json" \ -d '{"address": "5YourWalletAddress...", "challenge": "...", "signature": "0x..."}' # {"key": "fr_...", "address": "5YourWalletAddress..."} ``` The challenge is a few lines of text naming your address, the network and an expiry. It states that signing does not move funds. The same flow in Node with polkadot-js: ```js import { Keyring } from "@polkadot/keyring"; import { cryptoWaitReady } from "@polkadot/util-crypto"; import { stringToU8a, u8aToHex } from "@polkadot/util"; const API = "https://api.floprouter.com"; await cryptoWaitReady(); const pair = new Keyring({ type: "sr25519" }).addFromUri(process.env.FLOP_WALLET_URI); const post = (path, body) => fetch(API + path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).then((r) => r.json()); const { challenge } = await post("/v1/auth/challenge", { address: pair.address }); const signature = u8aToHex(pair.sign(stringToU8a(challenge))); const { key } = await post("/v1/auth/keys", { address: pair.address, challenge, signature }); console.log(key); ``` Browser wallet extensions wrap the bytes as `...` before signing. The website signs that way; a script usually signs the bare bytes. The response includes the key's `id` and its `payer_mode`. ## Payer mode of a key A new key starts in `grant` mode: your wallet pays on chain, which needs the one-time grant. Until you sign it, chat requests with that key fail with `402 grant_required`. Either sign the grant on the [account page](/account/), or switch the key to `credit` so the router pays from your prepaid balance: ```bash curl -X PATCH https://api.floprouter.com/v1/auth/keys/ \ -H "Authorization: Bearer $FLOPROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{"payer": "credit"}' ``` See [payer modes](/docs/payer-modes/). ## List and revoke keys ```bash curl https://api.floprouter.com/v1/auth/keys -H "Authorization: Bearer $FLOPROUTER_API_KEY" curl -X DELETE https://api.floprouter.com/v1/auth/keys/ -H "Authorization: Bearer $FLOPROUTER_API_KEY" ``` Both act on the wallet that owns the key you send. A wallet can hold a limited number of active keys; past it, creating one fails with `409 too_many_keys`. ## Without a key The directory endpoints (`/v1/miners`, `/v1/models`, `/v1/stats`, `/health`) need no key. Chat completions need one, unless the server runs an anonymous demo mode. That mode is off unless the operator turns it on; it is limited to devnet, has a small rate limit, and the router pays. (not live yet) ## Keep keys secret A key can spend your balance and, with a grant, open sessions paid by your wallet within the grant's limits. Do not put it in front-end code or public repositories. Revoke a key you no longer use. --- # MCP server > floprouter's tools for any MCP client, from Claude Code to Cursor and Codex. `floprouter-mcp` lets an agent list models and miners, run paid chat completions, and check sessions, balance and grant state. It never handles wallet keys. **Not published yet.** The package is built and tested, but it is not on npm. The commands below work once it is. ```bash npx -y floprouter-mcp # stdio, what desktop and IDE clients use npx -y floprouter-mcp --http # streamable HTTP on http://127.0.0.1:8792/mcp ``` | Variable | Meaning | | - | - | | `FLOPROUTER_API_KEY` | Your `fr_...` key. Without it, the read-only tools work. Falls back to the key saved by `floprouter login`. | | `FLOPROUTER_BASE_URL` | Default `https://api.floprouter.com` | | Tool | What it does | Paid | | - | - | - | | `list_models` | Models, ready and reachable miners, escrow per 1,000 tokens | no | | `list_miners` | Miners with score, settle rate, sessions, strikes, calibration and reachability | no | | `get_miner` | One miner in detail | no | | `chat` | One chat completion, auto or pinned miner | yes | | `session_status` | Settlement state of a session | no | | `account` | Balance, deposit address, fee and grant state | no | | `router_status` | Network, sync state and payer | no | Claude Code: ```bash claude mcp add floprouter --scope user -e FLOPROUTER_API_KEY=fr_... -- npx -y floprouter-mcp ``` Claude Desktop (`claude_desktop_config.json`) and Cursor (`~/.cursor/mcp.json`): ```json { "mcpServers": { "floprouter": { "command": "npx", "args": ["-y", "floprouter-mcp"], "env": { "FLOPROUTER_API_KEY": "fr_..." } } } } ``` Codex (`~/.codex/config.toml`): ```toml [mcp_servers.floprouter] command = "npx" args = ["-y", "floprouter-mcp"] env = { FLOPROUTER_API_KEY = "fr_..." } ``` `chat` returns once the reply is verified. Use `session_status` for the settlement; many MCP clients time a tool out before a settlement finishes. --- # Models > Which models the network serves, how to name them, and how one request shape covers all of them. ## List the models ```bash curl https://api.floprouter.com/v1/models ``` No key is needed. Every verified model in the chain registry is listed, with how many miners serve it now: ```json { "id": "qwen/qwen3-8b", "object": "model", "name": "Qwen/Qwen3-8B", "hash": "0xfab8ec57f3bc1b5d4ca644fe12fab2ca1c35c24697d577c610b382cfea14d52d", "params_billion": 8, "precisions": ["BF16"], "gflops_per_token": 17, "miners_reachable": 3, "miners_ready": 1, "available": true, "pricing": { "escrow_per_1000_tokens": "0.05", "basis": "token_price", "tariff_floor_per_1000_tokens": "0.000000000000017001", "router_fee_percent": 5 } } ``` | Field | Meaning | | - | - | | `id` | What you send as `model`. The model hash works too. | | `miners_reachable` | Miners serving this model whose session endpoint the router has proven. | | `miners_ready` | Of those, how many report ready. A request needs at least one. | | `available` | `true` when `miners_ready` is 1 or more. | | `pricing.escrow_per_1000_tokens` | What the router escrows per 1,000 tokens of prompt plus `max_tokens`. | | `pricing.tariff_floor_per_1000_tokens` | The chain's minimum for the same tokens. | | `pricing.router_fee_percent` | The router fee as a percentage of escrow. | The [models page](/models/) shows the same data live, and each model has a page with the miners serving it. ### The extended model object (not live yet) The model object gains `context_length`, `architecture`, per-token `pricing`, `top_provider` and `supported_parameters`. The FLOP details move under `flop`; the top-level `available`, `miners_ready`, `miners_reachable` and `params_billion` stay for one release. ```json { "id": "qwen/qwen3-8b", "name": "Qwen/Qwen3-8B", "context_length": 10000, "architecture": {"modality": "text->text", "input_modalities": ["text"], "output_modalities": ["text"]}, "pricing": {"prompt": "", "completion": "", "request": "0"}, "top_provider": {"context_length": 10000, "max_completion_tokens": "", "is_moderated": false}, "supported_parameters": ["max_tokens"], "flop": { "model_hash": "0x...", "providers_reachable": 3, "providers_ready": 1, "available": true, "min_charge_per_request": "0.01", "escrow_per_1000_tokens": "0.05", "router_fee_percent": 5, "pricing_note": "A request escrows prompt plus max_tokens at this price ..." } } ``` - `pricing` is in FLOP per token, not USD. - `context_length` is the largest prompt plus completion one payment covers on this router, not the model's own window. With a 0.5 FLOP escrow ceiling at 50 FLOP per million tokens, that is 10,000 tokens, although today's models have a 32,768-token window. - The cost follows `max_tokens`, not the tokens produced: a request escrows prompt plus `max_tokens`, and a settled session pays the whole escrow. One model, and the miners serving it, one endpoint per miner: ```bash curl https://api.floprouter.com/v1/models/qwen/qwen3-8b curl https://api.floprouter.com/v1/models/qwen/qwen3-8b/endpoints curl https://api.floprouter.com/v1/models/count ``` Each endpoint is one miner: `tag` is the miner's address, `provider_name` its endpoint host, `status` 0 for ready, -1 for reachable but not ready, -2 for not answering. `uptime_last_1d` is the share of signed-proof probes that succeeded, and `latency_last_30m.p50` the mean time to the verified reply in seconds. The miner's score, key binding and live signed offer are under `flop`. ## One request shape for every model Each model on FLOP Network has a decode policy fixed on chain, and miners run different worker versions. The router reads the model's policy, builds the turn in the format that model and worker expect, and verifies the reply against the miner's signed receipt. You send `model`, `messages` and `max_tokens` the same way for every model. A model added to the registry is usable with no change on your side. Sampling parameters (`temperature`, `top_p`, `seed`) are accepted and ignored, because the decode policy on chain decides them. Every miner serving a model answers with the same policy. ## Which miners serve a model ```bash curl "https://api.floprouter.com/v1/miners?model=qwen/qwen3-8b&reachable=true&view=full" ``` See [miners and scores](/docs/miners/) for the fields, and [provider selection](/docs/routing/) to send a request to particular miners. --- # CLI > Browse miners, chat, and do the wallet steps (key, grant, deposit) from a terminal. `floprouter` browses miners and models, runs chat, and does the wallet steps on your own machine: creating a key, signing the grant, depositing FLOP. Keys stay local. The router receives your address, a signature over its login challenge, and the transactions you sign. **Not published yet.** The commands below work once the package is on npm. It needs Node 18.17 or later. ```bash npx floprouter models npx floprouter miners --reachable --sort settle_rate npx floprouter login --key-file ./my-wallet.json # polkadot-js JSON export, or --seed-file, or a hidden prompt npx floprouter grant # one signature: your wallet stays the payer on chain npx floprouter deposit 1 # fund the balance for the router fee npx floprouter chat "What is a payment channel?" npx floprouter session ``` A seed or password is never accepted as a command-line argument. Before signing a grant, the CLI checks the chain's genesis hash against the router's and refuses any call other than `flopSessionKeys.createSession` limited to `ComputeChannel`. --- # SDK compatibility > Use floprouter from SDKs, frameworks and editor tools that let you set a base URL for a chat completions API. Tools that let you set a custom base URL for a chat completions API work with floprouter: set the base URL and the key, keep the rest. The SDKs below are usage examples. | Setting | Value | | - | - | | Base URL | `https://api.floprouter.com/v1` | | API key | your `fr_...` key from the [account page](/account/) | | Model | an id from [`/v1/models`](/models/), for example `qwen/qwen3-8b` | Two things to know first: - **Plain chat.** Tool calling is not supported, so a request that sends `tools` is rejected with 400. Agent modes in editors and frameworks usually send tools. Use their chat mode. - **Slow by API standards.** Replies take 15 to 50 s on devnet. Raise client timeouts to 120 s or more. ## Python: the `openai` package ```python from openai import OpenAI client = OpenAI(base_url="https://api.floprouter.com/v1", api_key="fr_...", timeout=120) reply = client.chat.completions.create( model="qwen/qwen3-8b", messages=[{"role": "user", "content": "Hello"}], extra_body={"provider": {"sort": "latency"}}, ) print(reply.choices[0].message.content) print(reply.model_extra["flop"]["channel_id"]) ``` Router fields (`provider`, `flop`) go in `extra_body`. The `flop` record of the response is in `reply.model_extra["flop"]`. ## JavaScript: the `openai` package ```js import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://api.floprouter.com/v1", apiKey: process.env.FLOPROUTER_API_KEY, timeout: 120_000 }); const reply = await client.chat.completions.create({ model: "qwen/qwen3-8b", messages: [{ role: "user", content: "Hello" }], }); console.log(reply.choices[0].message.content, reply.flop.channel_id); ``` In TypeScript the extra `flop` and `provider` fields are not in the SDK's types. Add `// @ts-expect-error` above them, or pass the body through a variable typed as `any`. ## LangChain Checked against responses recorded from the live API, not with separate paid calls. ```python from langchain_openai import ChatOpenAI llm = ChatOpenAI(base_url="https://api.floprouter.com/v1", api_key="fr_...", model="qwen/qwen3-8b", max_tokens=64, timeout=300) print(llm.invoke("What does a GPU miner do?").content) ``` ## Vercel AI SDK Use `@ai-sdk/openai-compatible`, which calls chat completions. The Responses API is not offered. Checked against recorded responses. ```js import { generateText } from "ai"; import { createOpenAICompatible } from "@ai-sdk/openai-compatible"; const floprouter = createOpenAICompatible({ name: "floprouter", baseURL: "https://api.floprouter.com/v1", apiKey: process.env.FLOPROUTER_API_KEY }); const { text } = await generateText({ model: floprouter("qwen/qwen3-8b"), prompt: "In one sentence, what is a payment channel?" }); ``` ## LiteLLM Not tested against floprouter. ```python import litellm r = litellm.completion(model="openai/qwen/qwen3-8b", api_base="https://api.floprouter.com/v1", api_key="fr_...", messages=[{"role": "user", "content": "Hello"}]) ``` ## Editor tools and chat apps Tools with a custom chat-completions provider setting take the base URL, key and model id above. Use chat, not agent or edit modes that depend on tool calls. Keep the output limit low, since `max_tokens` sizes the escrow of every request. --- # Provider selection > Choose miners with the provider object, or let auto mode choose by score. Routing preferences go in the `provider` object. A provider is a miner, named by its account address. ## Auto mode Send no `provider` object and the router chooses. It considers miners that - serve the requested model, - have a session endpoint the router has proven, and - report ready, and tries them in order of score. In grant mode a miner also needs a live signed offer. What happens when a miner fails is on the [fallbacks](/docs/fallbacks/) page. The score runs from 0 to 100 and comes from on-chain facts: how a miner's paid sessions ended, how many and how recent, who paid for them, its stake, its slashing record and its calibration. The formula is not published. The inputs are, on every miner in `GET /v1/miners` and on the [miners page](/miners/). ## The provider object | Field | Type | Meaning | | - | - | - | | `order` | string[] | Try these miners first, in this order. | | `only` | string[] | Use these miners and no others. | | `ignore` | string[] | Never use these miners. | | `sort` | `reliability` or `latency` | `reliability` (default) orders by score. `latency` orders by the router's measured proof latency. | | `allow_fallbacks` | boolean | With `order`: whether other miners may be tried after the listed ones. Default `true`. | ### More routing preferences (not live yet) More routing preferences: | Field | Here | | - | - | | `order`, `only`, `ignore` | Miner addresses, or the host of a miner's session endpoint. | | `sort` | A string or `{by, partition}`. `reliability` (the default): the miner's score. `latency` and `throughput`: router-measured time to the verified reply. `price`: every miner serving a model costs the same here, so the default order applies. | | `max_price` | `{prompt, completion, request}` in FLOP, per million tokens (`request`: per request). A model above it is skipped. | | `require_parameters` | `true`: refuse the request (503) when the model ignores a parameter you sent, instead of ignoring it. | | `quantizations` | Matched against the model's precision in the chain registry, `bf16` today. | | `data_collection: "deny"`, `zdr: true` | Cannot be honoured, because miners keep signed session evidence for audit and settlement. The request gets 503. | | `preferred_min_throughput`, `preferred_max_latency` | Accepted and ignored. | `GET /v1/providers` lists the miners with a proven endpoint, one entry per miner (`slug` is the miner address). The directory with every registered miner stays at `GET /v1/miners`. Pin one miner, and fail instead of moving to another: ```json { "model": "qwen/qwen3-8b", "messages": [{"role": "user", "content": "Hello"}], "provider": {"only": ["5HKiGNFSqSyEMVMjjr8JBKkkppytaqFZCRm27KGbCeHhUq92"], "allow_fallbacks": false} } ``` Prefer two miners, then let the router choose: ```json "provider": {"order": ["5HKiGN...", "5CJxjZ..."], "allow_fallbacks": true} ``` Avoid a miner: ```json "provider": {"ignore": ["5HbvZY..."]} ``` Order by measured latency: ```json "provider": {"sort": "latency"} ``` ## Which miner served you - `provider` at the top level of the response is the miner's address. - `flop.miner`, `flop.endpoint` and `flop.via` say who served it and how the channel was opened: `offer` (against the miner's signed offer) or `force` (a force-open, when the miner has no live offer). - `flop.attempts` lists every try, failed ones included, with the stage it reached and the error. ## Finding miners ```bash # miners with a proven endpoint for one model, best first curl "https://api.floprouter.com/v1/miners?reachable=true&view=full&model=qwen/qwen3-8b" # every registered miner, by settle rate curl "https://api.floprouter.com/v1/miners?sort=settle_rate&limit=1000" ``` Filters: `reachable`, `ready`, `active`, `calibrated`, `model`, `min_score`. Sort: `score`, `settle_rate`, `sessions`, `stake`, `latency`, `capacity`, with `order`, `limit` and `offset`. Without `view=full`, `reachable=true` returns the compact list of proven pairs. ## Price FLOP Network has no per-miner price, so the router does not route on price. It routes on reliability and reachability. See [fees](/docs/fees/). --- # Examples > Small, complete patterns: a client module, a streaming reader, and an agent loop without tool calls. ## A client module Every request needs the key, a `User-Agent`, a long timeout, and handling for `202` (poll the session) and for errors whose reason the user can act on. ```python Python import json, os, time, urllib.request, urllib.error HOST = os.environ.get("FLOPROUTER_BASE_URL", "https://api.floprouter.com").rstrip("/") KEY = os.environ["FLOPROUTER_API_KEY"] def _call(method, path, body=None): req = urllib.request.Request(HOST + path, method=method, data=None if body is None else json.dumps(body).encode(), headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json", "User-Agent": "my-app/1.0"}) try: with urllib.request.urlopen(req, timeout=130) as r: return r.status, json.loads(r.read()) except urllib.error.HTTPError as e: raw = e.read() try: return e.code, json.loads(raw) except ValueError: return e.code, {"error": {"message": raw[:200].decode(errors="replace")}} def chat(messages, model="qwen/qwen3-8b", max_tokens=256): status, r = _call("POST", "/v1/chat/completions", {"model": model, "messages": messages, "max_tokens": max_tokens}) if status == 202: # no verified reply within the deadline: poll, do not resend for _ in range(60): time.sleep(5) status, s = _call("GET", r["poll"]) if status == 200 and s.get("reply"): return s["reply"]["content"], s raise TimeoutError(f"session {r['id']} has no reply yet") if status != 200: err = r.get("error", {}) reason = (err.get("metadata") or {}).get("reason") or err.get("code") raise RuntimeError(f"{status} {reason}: {err.get('message')}") return r["choices"][0]["message"]["content"], r["flop"] ``` ## Reading a stream ```js fetch const res = await fetch("https://api.floprouter.com/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${process.env.FLOPROUTER_API_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ model: "qwen/qwen3-8b", messages: [{ role: "user", content: "Hello" }], stream: true }), }); const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; for (;;) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); let i; while ((i = buffer.indexOf("\n\n")) >= 0) { const event = buffer.slice(0, i); buffer = buffer.slice(i + 2); for (const line of event.split("\n")) { if (!line.startsWith("data: ")) continue; // ": FLOPROUTER PROCESSING" keep-alives if (line === "data: [DONE]") process.exit(0); const chunk = JSON.parse(line.slice(6)); if (chunk.error) throw new Error(chunk.error.message); process.stdout.write(chunk.choices?.[0]?.delta?.content ?? ""); } } } ``` ## An agent loop without tool calls Tool calling is not supported, so ask the model for a JSON action in plain text and run it yourself. ```python Python SYSTEM = ( "You can use one tool: calc(expression). To use it, reply with JSON only: " '{"tool": "calc", "expression": "..."}. When you have the answer, reply with JSON only: {"answer": "..."}.' ) def run(question): messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}] for _ in range(5): text, _ = chat(messages, max_tokens=128) messages.append({"role": "assistant", "content": text}) action = json.loads(text[text.index("{"): text.rindex("}") + 1]) if "answer" in action: return action["answer"] result = str(eval(action["expression"], {"__builtins__": {}})) # a sandboxed calculator in real code messages.append({"role": "user", "content": f"calc result: {result}"}) ``` Each turn is one paid session. Keep loops short and `max_tokens` small. --- # Fallbacks > What the router does when a miner fails, and when it stops trying. ## Before any output If an attempt fails before the miner produces any text, the router tries the next miner in the order: auto order, or your `order` list. It stops after a fixed number of attempts and then answers `503 all_attempts_failed`, with every attempt listed in `flop.attempts` of the session record. Failures that move on to the next miner include a miner that does not acknowledge the channel, an endpoint that stops answering, and a channel open that the chain rejects. ## After output Once a miner has sent text, the router does not move to another miner. You never get two answers, or two charges, for one request. If the miner goes silent after that point, the router closes the channel on chain (see [settlement](/docs/settlement/)) and the request ends with an error. ## Model fallbacks (not live yet) Name more models to try when the first has no miner that can serve it: ```json { "model": "qwen/qwen3-8b", "models": ["qwen/qwen2.5-0.5b-instruct"], "messages": [{"role": "user", "content": "Hello"}] } ``` The router tries `model`, then each entry of `models` in order, when a model has no serving miner (404, 502, 503) or the request is too large for it. It never moves to another model after output. The response `model` names the model used. `route: "fallback"` is accepted. ## Turning fallbacks off ```json "provider": {"only": ["5HKiGN..."], "allow_fallbacks": false} ``` With `only`, no other miner is tried. With `order` and `allow_fallbacks: false`, the listed miners are tried in order and no others. ## Payer fallback In grant mode a request can be served through miners with a live signed offer. When none is ready, or the grant cannot pay, the request fails. To run it in balance mode instead: ```json "flop": {"fallback_payer": "credit"} ``` It is off by default, so your wallet stays the payer unless you ask for the fallback. See [payer modes](/docs/payer-modes/). ## Retrying on your side The router already retries across miners. Retry a request yourself after `503` or `429`, waiting for the `Retry-After` header. Do not retry a slow request: a normal reply takes 15 to 50 s, and a second request opens a second channel. The full list is on the [errors](/docs/errors/) page. --- # Payer modes and grants > Who pays on chain for each session, and why the grant keeps the on-chain record with your wallet. Every session opens a payment channel on chain. The account that opens it is the channel's payer, recorded in the channel's `agent` field. floprouter has two ways to pay: `grant` and `credit`. You choose per key (new keys start in `grant`), and can override per request with `"flop": {"payer": "credit"}`. Switch a key's mode on the [account page](/account/) or with `PATCH /v1/auth/keys/{id}` and `{"payer": "grant"}` or `{"payer": "credit"}`. | | Grant | Balance | | - | - | - | | Payer on chain | your wallet | the router's wallet | | What you sign | one grant, once | nothing per request | | Escrow paid from | your wallet | your router balance | | Router fee paid from | your router balance | your router balance | | Best for | people and agents that want the on-chain record in their own name | quick scripts and agents | Every response says who paid, in `flop.payer`: ```json "payer": {"address": "5...", "kind": "session-key"} ``` `kind` is `session-key` when your wallet paid through a grant, and `router-wallet` when the router's wallet paid. ## Grant mode (`grant`, recommended) (live) You sign one extrinsic with your wallet: `flopSessionKeys.createSession`. It names a delegate key held by the router and sets limits: a total spending cap, a per-transaction limit, a daily cap, a duration in blocks, and the pallets the delegate may use. floprouter asks only for `ComputeChannel`. After that, for each request, the router signs `flopSessionKeys.executeViaSession` with its delegate key. The chain runs the inner call, opening the channel, **as your account**. So: - The channel's payer on chain is your address, not the router's. The explorer shows your address as the payer. - The escrow comes from your wallet. - Your wallet signs nothing during the session. The router holds the per-channel session key and does everything after the open. Grant mode opens channels only against a miner's signed offer. When no ready miner has a live offer, or the grant cannot pay, a grant-mode request fails. To have it run in balance mode instead, send `"flop": {"fallback_payer": "credit"}`. It is off by default, so your wallet stays the payer unless you ask otherwise. ### What the delegate can and cannot do - It can open compute channels to any miner, at any escrow, within your caps. The chain enforces the caps. - It cannot transfer your funds or call anything outside `ComputeChannel`. - It stops working when the grant expires or when you revoke it with `flopSessionKeys.revokeSession`, signed by your wallet. ### Limits The chain limits how long a grant lasts and how many grants one delegate key can hold. `GET /v1/grants/params` returns the delegate address, the caps the router asks for (`amounts`), the chain's limits (`limits`), and the exact call to sign, both as `call` (pallet, method, arguments) and as encoded `call_data`. Without a key, pass `?address=`. `GET /v1/grants` returns your grant's state: sessions left and expiry. After you sign, `POST /v1/grants/sync` asks the router to read it from the chain at once. ```bash curl https://api.floprouter.com/v1/grants/params -H "Authorization: Bearer $FLOPROUTER_API_KEY" curl https://api.floprouter.com/v1/grants -H "Authorization: Bearer $FLOPROUTER_API_KEY" curl -X POST https://api.floprouter.com/v1/grants/sync -H "Authorization: Bearer $FLOPROUTER_API_KEY" ``` The [account page](/account/) does all three and builds the transaction for your wallet to sign. Signing the same delegate again replaces the old grant, so renewing is the same one signature. ## Balance mode (`credit`) (live) The router's wallet opens the channel and the cost, escrow plus fee, is taken from your prepaid balance. Nothing to sign per request. On chain, the payer of each session is the router, not you. ## What the current server offers `GET /health` lists the payer modes the server offers in `payer.modes`, and the router wallet's address in `payer.router_wallet`. Every response says who actually paid, in `flop.payer`. --- # Prepaid FLOP balance > Fund your prepaid balance, read it, and see what was taken from it. (live) Your balance pays the router fee in both payer modes, and the escrow too in balance mode (`credit`). It belongs to the wallet that owns your key. ## Deposit Send a plain FLOP transfer (`balances.transferKeepAlive`) from your wallet to the router's deposit address. It is credited to the sending address once its block is finalized, usually within a minute. Send from the wallet that owns your key: a transfer from another wallet is credited to that other wallet. ```bash curl https://api.floprouter.com/v1/balance -H "Authorization: Bearer $FLOPROUTER_API_KEY" ``` ```json { "object": "balance", "address": "5...", "currency": "FLOP", "balance": "0", "held": "0", "available": "0", "deposit_address": "5...", "fee_percent": 5, "deposit_note": "Send a plain transfer ...", "recent": [] } ``` | Field | Meaning | | - | - | | `balance` | Everything credited to you and not spent. | | `held` | Reserved for sessions in progress and withdrawals in flight. | | `available` | What new requests and withdrawals can use. | | `deposit_address` | Where to send deposits. | | `recent` | The latest ledger entries: deposits, escrow and fee charges, refunds, withdrawals. | The [account page](/account/) shows the same, with the deposit address ready to copy. ## Your key's usage (not live yet) ```bash curl https://api.floprouter.com/v1/key -H "Authorization: Bearer $FLOPROUTER_API_KEY" ``` Usage in FLOP over the sessions paid through this key (day, week from Monday, month, UTC) and the rate limits. `limit` is `null`: spending is bounded by your prepaid FLOP balance and, in grant mode, by the grant's caps. Under `flop`: the key id, wallet address and payer mode. There is no credits endpoint: the prepaid FLOP balance is `GET /v1/balance`. ## When the balance is short A request the balance cannot cover is refused with `402 insufficient_balance` before any channel opens. The error carries `available` and `required`, so you can show the user how much to deposit. ## Taking it out See [withdrawals](/docs/withdrawals/). --- # Fees and pricing > What a request costs, who receives it, and how to fund a balance. A request has two costs. 1. **Escrow.** The amount locked in the payment channel. A cooperative settlement pays all of it out: to the miner, with the protocol's shares for validators and audit taken from it. Miners do not set prices. The chain sets a tariff floor per request, and the payer chooses the escrow above it. 2. **Router fee.** A percentage of the escrow, in FLOP, charged only for sessions that settle as paid. (live) ## How the escrow is sized The router sets the escrow per request as the largest of: - the chain's tariff floor for the model and token count, plus a margin, - the configured price per token times the prompt estimate plus `max_tokens`, - a configured minimum, - the minimum the miner's signed offer asks for. A request whose escrow would pass the configured maximum is refused with `escrow_limit`. Lower `max_tokens` to lower the escrow. `GET /v1/models` shows each model's escrow per 1,000 tokens and the chain's tariff floor: ```json "pricing": { "escrow_per_1000_tokens": "0.05", "basis": "token_price", "tariff_floor_per_1000_tokens": "0.000000000000030001", "router_fee_percent": 5 } ``` On devnet the tariff floor is tiny, so the configured price or the minimum decides. The minimum per request is 0.01 FLOP on this server, so short requests all cost 0.01 FLOP plus the 5% fee, 0.0105 FLOP. ## The router fee The current percentage is in `pricing.router_fee_percent` of every model and in `flop.router_fee` of every response: ```json "router_fee": {"percent": 5, "amount": "0.0005", "charged": false, "status": "pending"} ``` | `status` | Meaning | | - | - | | `pending` | The session has not settled yet. The fee is taken if it settles as paid. | | `charged` | Taken from your balance. `charged_amount` says how much. | | `not_charged` | The session ended without a paid settlement: no fee. | | `not_billed` | The request had no wallet key, so there was no balance to bill. | ## Paying the fee The fee comes from your prepaid [balance](/docs/balance/) in both payer modes. When the balance cannot cover it, the request is refused before any channel opens, with `402 insufficient_balance`. Devnet and testnet FLOP have no monetary value. --- # Withdrawals > Send your prepaid balance back to your wallet. `POST /v1/balance/withdraw` sends FLOP from the deposit wallet to the wallet that owns your key. It cannot send anywhere else. ```bash curl -X POST https://api.floprouter.com/v1/balance/withdraw \ -H "Authorization: Bearer $FLOPROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{"amount": "0.5"}' ``` | Field | Meaning | | - | - | | `amount` | Decimal FLOP, or `"all"` for the whole available balance. | | `to` | Optional. When given, it must equal the wallet that owns the key. | The amount is held first, so a withdrawal cannot race a session or another withdrawal. The chain fee is estimated and taken out of the amount sent. ## Response `200` once the transfer is final on chain. The shape, with placeholder values: ```json { "object": "withdrawal", "id": "...", "to": "5...", "status": "sent", "requested": "0.5", "sent": "", "chain_fee": "", "tx": "0x...", "block": 4498929, "balance_after": "" } ``` `sent` is the requested amount minus the fee estimate. `chain_fee` is the fee the chain charged. The ledger in `GET /v1/balance` books both, as `withdrawal` and `withdrawal_fee`. ## Limits and errors - One withdrawal per wallet at a time, and at most 10 per wallet per hour. | HTTP | `code` | What it means | | - | - | - | | 400 | `invalid_amount`, `amount_too_small`, `invalid_destination` | The amount or `to` is not valid. Nothing was sent. | | 402 | `insufficient_balance` | The available balance is less than the amount. Nothing was sent. | | 409 | `withdrawal_in_progress` | Another withdrawal for this wallet is in flight. Wait for it. | | 429 | `rate_limited` | More than 10 in the hour. Wait for `Retry-After`. | | 503 | `withdrawals_unavailable`, `treasury_insufficient`, `withdrawal_failed` | The transfer was not sent. Your balance is unchanged. Retry later. | | 503 | `withdrawal_outcome_unknown` | The transfer's outcome is not known yet. The amount stays held until the router reconciles it. Do not retry; check `GET /v1/balance`. | --- # Streaming > Text as the miner decodes it, how it is verified, and what the stream carries. `"stream": true` returns server-sent events of `chat.completion.chunk` objects, ending with `data: [DONE]`. (live) The stream carries: 1. the first bytes once the router's own checks pass (payer, balance, grant, miner availability), or after 8 s, 2. keep-alive comments (lines that start with `:`, such as `: FLOPROUTER PROCESSING`) at least every 15 s while the miner works, so proxies and clients do not time out, 3. text deltas, forwarded **as the miner streams them**, 4. a last chunk with `usage` and the `flop` session record (it repeats `finish_reason` in `choices`), 5. `data: [DONE]`. ```python Python import json, os, requests with requests.post( "https://api.floprouter.com/v1/chat/completions", headers={"Authorization": f"Bearer {os.environ['FLOPROUTER_API_KEY']}"}, json={"model": "qwen/qwen3-8b", "messages": [{"role": "user", "content": "Hello"}], "stream": True}, stream=True, timeout=300, ) as res: for line in res.iter_lines(decode_unicode=True): if not line or not line.startswith("data: "): continue # blank lines and ': keep-alive' comments data = line[6:] if data == "[DONE]": break chunk = json.loads(data) if "error" in chunk: raise RuntimeError(chunk["error"]) for choice in chunk.get("choices", []): print(choice["delta"].get("content", ""), end="", flush=True) ``` ```bash curl curl -N https://api.floprouter.com/v1/chat/completions \ -H "Authorization: Bearer $FLOPROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "qwen/qwen3-8b", "messages": [{"role": "user", "content": "Hello"}], "stream": true}' ``` The router forwards text as soon as the miner sends it. Miners on devnet today (worker 0.1.418) send the reply in one piece at the end of the turn, so for now a stream shows keep-alives and then the whole reply at once. When workers stream as they decode, the same requests show text as it is produced; nothing changes on your side. ## Verification The streamed text is provisional while it arrives. When the turn ends, the miner's signed receipt is checked against the whole reply, and the finish chunk is sent only after that check. The receipt commits to the same bytes, so the two match. If they ever did not, the stream ends with an error chunk that carries the verified text: ```json {"error": {"message": "the streamed text differs from the verified reply; use the verified content", "type": "server_error", "code": "stream_mismatch", "verified_content": "..."}} ``` Once text has reached you, the router does not fail over to another miner, so you never get two answers for one request. ### Errors after the stream started (not live yet) A mid-stream error arrives as one chunk with a top-level `error` (`code`, `message`, `metadata`) and `choices: [{"delta": {"content": ""}, "finish_reason": "error"}]`. The stream ends after it, with no `[DONE]`. The reason is in `error.metadata.reason`, and for `stream_mismatch` the verified text is in `error.metadata.verified_content`. ## Why stream - You see text within seconds instead of waiting for the whole reply. - Non-streaming calls have a response deadline. When no verified reply arrives in time, they return `202` with a pending body and you poll for the reply (see [settlement](/docs/settlement/)). A stream has no such deadline. Streams never wait for the settlement. Read it from `GET /v1/sessions/{id}` with the `flop.session_id` from the last chunk. --- # Payment channels and sessions > What a session is, how its payment channel moves on chain, and how to read both. Each request is one **session**. A session opens one **payment channel** on FLOP Network: an on-chain account between the payer and the miner that holds the escrow for this request. The miner answers through it and is paid from it. ## The life of a channel | Stage | On chain | In the session record | | - | - | - | | Opened | The channel exists with the escrow locked. Opened against the miner's signed offer (`via: "offer"`) or by force-open (`via: "force"`). | `status: "running"`, `channel_id`, `on_chain.open_block` | | Answered | Nothing yet. The reply and the miner's signed receipt travel off chain. | `status: "settling"`, `usage` | | Settled | The miner posts the settlement and the escrow is paid out. | `status: "settled"`, `miner_paid`, `on_chain.outcome_tx` | | Recovered | If the miner goes silent, the router closes the channel with a timeout or force-settle. | `status: "recovering"`, then the outcome | Settlement timing and the recovery calls are on the [settlement](/docs/settlement/) page. ## Read a session ```bash curl https://api.floprouter.com/v1/sessions/ -H "Authorization: Bearer $FLOPROUTER_API_KEY" ``` The session id is the `id` of the chat completion, and `flop.session_id`. The record carries: | Field | Meaning | | - | - | | `status` | `running`, `settling`, `settled`, `refunded`, `recovering`, `failed`, `fraud` or `voided`. | | `channel_id` | The payment channel, `0x` plus 64 hex characters. | | `miner`, `endpoint`, `via` | Who served it and how the channel was opened. | | `payer` | `address` and `kind`: who paid on chain (see [payer modes](/docs/payer-modes/)). | | `escrow`, `miner_paid` | What was locked, and what the settlement paid. | | `router_fee` | Percent, amount and `status`: `pending`, `charged`, `not_charged` or `not_billed`. | | `on_chain` | `open_block`, `outcome`, `outcome_block`, `outcome_tx`. | | `attempts` | Every try, with the miner, stage, error and any recovery calls. | | `reply` | The verified reply, to the key that made the request, once there is one. | ## Generation records (not live yet) A generation lookup reads the same session by its id: ```bash curl "https://api.floprouter.com/v1/generation?id=gen-..." -H "Authorization: Bearer $FLOPROUTER_API_KEY" ``` It returns tokens, `total_cost` in FLOP, finish reason, latency and the verified reply, with the full session under `flop`. Every chat response carries the id in the `X-Generation-Id` header as well as in `id`. ### Cost in the response `usage.cost` is the request's cost in FLOP: escrow plus router fee. It is final when the session settles (`usage.cost_details.final`), and 0 for a session that is refunded. `usage.cost_details.upstream_inference_cost` is the escrow, split into prompt and completion by token share. ## List your sessions ```bash curl "https://api.floprouter.com/v1/sessions?limit=20" -H "Authorization: Bearer $FLOPROUTER_API_KEY" ``` ## On the explorer - A channel: `https://explorer.devnet.flop.network/channels/` - A transaction: `https://explorer.devnet.flop.network/transactions/` - A payer or miner: `https://explorer.devnet.flop.network/account/
` In grant mode the explorer shows your address as the payer of the channel. --- # Settlement > Timing, session states, and how to follow a payment channel to its final state on chain. Each request opens one payment channel. Its life on devnet: | Step | Typical time | | - | - | | Miner chosen, channel opened | a few seconds | | Verified reply | about 15 to 50 s after the request, sometimes longer | | Settlement final on chain | 2 to 4 minutes after the reply, in the background | ## When the call returns A non-streaming call returns as soon as the reply is verified, with `flop.status: "settling"`. The settlement continues in the background. To wait for the settlement instead, send `"flop": {"wait_for_settlement": true}`. The call then returns once the settlement is final, with `miner_paid` set, but only up to the response deadline below. ### The response deadline Some proxies drop responses that stay idle for long. So a non-streaming call answers within a fixed deadline (85 s on this server). If no verified reply has arrived by then, it returns `202` instead of failing: ```json { "id": "gen-...", "object": "chat.completion.pending", "status": "pending", "message": "no verified reply within 85 s; the session continues. Poll GET /v1/sessions/gen-... until reply is set, or use stream: true.", "poll": "/v1/sessions/gen-...", "flop": {"session_id": "gen-...", "status": "running"} } ``` The session keeps running. Poll `GET /v1/sessions/{id}` with the same key until `reply` is set. Streaming avoids this case entirely. ## Following a session ```bash curl https://api.floprouter.com/v1/sessions/ ``` | `status` | Meaning | | - | - | | `running` | The request is in progress. | | `settling` | The reply was delivered. The settlement is not final yet. | | `settled` | The miner was paid on chain. `miner_paid` and `on_chain.outcome_tx` are set. | | `refunded` | The escrow went back to the payer. | | `recovering` | The miner went silent after the channel opened. The router is closing the channel on chain. | | `failed` | No attempt produced output. | | `fraud`, `voided` | Final outcomes decided on chain. | `on_chain` holds the open block, the outcome, the outcome block and the transaction. With the key that made the request, the record also carries `reply`: the verified reply, once there is one. Look the channel up on the explorer: `https://explorer.devnet.flop.network/channels/`. ## When a miner goes silent The router watches every channel it opened. If a channel stays open past its deadlines, the router sends the matching recovery call on chain (`expire_force_open`, `timeout`, `force_settle` or `finalize`). These calls are open to anyone on FLOP; the router pays their transaction fees. The session's `attempts[].recovery` lists what was sent. ## One channel per request A multi-turn conversation is one request per turn, each with its own channel. Send the whole history in `messages` each time, as with any chat API. --- # Errors > The error shape, every error code, and what to do about each. Errors are a JSON object with an `error` field: ```json {"error": {"message": "no ready miner serves this model", "type": "invalid_request_error", "code": "no_miner_available"}} ``` ### Numeric codes and reasons (not live yet) ```json {"error": {"code": 402, "message": "prepaid balance ...", "metadata": {"reason": "insufficient_balance", "available": "0", "required": ""}}} ``` `code` becomes the HTTP status as a number, and the reason string below moves to `error.metadata.reason`. Read the reason as `error.metadata.reason`, falling back to `error.code` when it is a string, and the code works with both shapes. When a session was started before the error, `error.session_id` (or `error.metadata.session_id`) is set. Look it up with `GET /v1/sessions/{id}` to see every attempt and any channel that was opened. | HTTP | `code` | Meaning | What to do | | - | - | - | - | | 202 | (not an error) | `object: "chat.completion.pending"`: no verified reply within the response deadline. The session continues. | Poll `GET /v1/sessions/{id}` until `reply` is set, or use `stream: true`. | | 400 | `invalid_json`, `model_required`, `messages_required`, `invalid_message`, `invalid_max_tokens` | The body is not valid. | Fix the request. The message says which field. | | 400 | `unsupported` | The request asks for something not supported: `tools`, or `n` above 1. | Remove the field. | | 400 | `invalid_provider`, `invalid_sort`, `invalid_payer`, `invalid_address` | A `provider`, `flop.payer` or address value is wrong. | See [routing](/docs/routing/) and [payer modes](/docs/payer-modes/). | | 400 | `escrow_limit` | The escrow for this request would pass the maximum per request. | Lower `max_tokens` or shorten the prompt. | | 401 | `unauthorized` | Missing, unknown or revoked key, or the payer mode needs a wallet key. | Check the `Authorization` header. Create a key on the [account page](/account/). | | 401 | `invalid_challenge`, `challenge_expired`, `challenge_used`, `invalid_signature` | Sign-in failed. | Ask for a new challenge and sign it with the same address. | | 402 | `insufficient_balance` | Your prepaid balance cannot cover the request. The error carries `available` and `required`. | [Top up](/docs/fees/) or lower `max_tokens`. | | 402 | `insufficient_funds` | In grant mode, your wallet cannot cover the escrow. | Fund your wallet. | | 402 | `grant_required`, `grant_expired`, `grant_expiring`, `grant_revoked`, `grant_exhausted`, `grant_not_usable`, `grant_per_tx_limit` | Grant mode, and the grant cannot pay for this request. | Sign a new grant on the [account page](/account/), or raise its caps. | | 404 | `model_not_found` | Unknown model id. | Use an id from `GET /v1/models`. | | 404 | `miner_not_found`, `session_not_found`, `key_not_found`, `not_found` | Unknown miner, session, key or path. | | | 403 | `forbidden` | The request did not come through the public endpoint. | Use the documented base URL. | | 409 | `too_many_keys` | This wallet has the most active keys allowed. | Revoke one first. | | 200, in a stream | `stream_mismatch` | The streamed text differs from the verified reply. | Use `verified_content` from the error chunk. | | 413 | `body_too_large` | The request body is too large. | Shorten the prompt. | | 429 | `rate_limited`, `too_many_concurrent`, `grant_daily_cap`, `demo_budget_exhausted` | A rate, concurrency, grant daily or demo limit was reached. | Wait for the `Retry-After` header, or use a wallet key. | | 503 | `all_attempts_failed` | Every miner tried failed before producing output. It is 503, not 502, because common SDKs retry a 502 at once, and each retry can cost an on-chain fee. | Wait for `Retry-After`, or choose other miners. | | 503 | `no_miner_available` | No ready miner matches the model and your `provider` rules. | Check the [ready miners](/miners/?reach=ready) or relax `provider`. | | 503 | `payer_underfunded`, `daily_cap_reached`, `delegate_unfunded`, `payer_unavailable` | The router's wallet cannot pay right now, or hit its daily cap. | Retry later. | | 503 | `shutting_down` | The service is restarting. | Retry in a few seconds. | This list follows the server at the time of writing; [`/openapi.json`](/openapi.json) is the reference. Treat an unknown 5xx as retryable after a pause, and any 4xx as a problem with the request. 429 and 503 responses carry a `Retry-After` header. ## Retries The router already retries on another miner when an attempt fails before any output. A reply that started is never retried, so a client-side retry can open a second channel. Retry only on errors, not on slow replies: a normal reply takes 15 to 50 s on devnet. Set your client timeout to at least 120 s. ```python requests.post(url, json=body, headers=headers, timeout=120) # one request, no automatic retries ``` --- # Limits and supported fields > Which request fields work, which are ignored or rejected, and the limits on each request. ## Request fields | Field | Support | | - | - | | `model` | Required. An id or model hash from `GET /v1/models`. | | `messages` | Required. Roles `system`, `developer`, `user`, `assistant`. Text content. | | `max_tokens` | 1 to 32768, default 256. `max_completion_tokens` is an alias. It sizes the escrow. | | `stream` | Text as the miner decodes it, see [streaming](/docs/streaming/). | | `provider` | Miner choice, see [routing](/docs/routing/). | | `flop` | `wait_for_settlement` (default `false`), `payer` (`grant` or `credit`) to override the key's payer mode, and `fallback_payer: "credit"` to fall back to balance mode when the grant cannot serve a request. | | `temperature`, `top_p`, `seed`, `stop`, penalties | Accepted and ignored. You cannot set sampling on FLOP Network today: each model has a decode policy fixed on chain, and the miner's reply is verified against it. The router reports such fields as ignored. | | `tools`, `tool_choice`, `functions` | Rejected: 400 today, 404 "No endpoints found that support tool use" on the extended API. Tool calls are not supported. (not live yet) | | `models`, `route` | Model fallback list, see [fallbacks](/docs/fallbacks/). (not live yet) | | `n` above 1 | Rejected with 400. | | `response_format`, `logprobs` | Ignored. | | other fields | Ignored, not rejected, so clients that send extra fields keep working. | ## Ignored parameters (not live yet) Each model lists what it supports in `supported_parameters`; today that is `max_tokens`, because sampling is fixed by the model's decode policy on chain. Parameters a model ignores are named in the `X-Floprouter-Ignored-Parameters` response header and in `flop.ignored_parameters`. Send `provider.require_parameters: true` to have such a request refused instead. ## Per request - One payment channel per request. Multi-turn chat sends the history each time. - A non-streaming call answers within a response deadline (85 s on this server); past it you get `202` and poll the session. See [settlement](/docs/settlement/). - The escrow has a maximum per request. Past it the request fails with `escrow_limit`. - The router has a daily spending cap for the sessions it pays. Past it requests fail with `daily_cap_reached`. ## Per key - Rate limits apply per key. Past them the API answers 429. - In grant mode your grant's caps apply as well: total, per transaction, daily, and its expiry. The chain enforces them. ## Not supported - Tool and function calling. (not live yet) - Images, audio, embeddings, the Responses API and the legacy completions API. --- # FAQ > Short answers to the questions people ask first. ## Is this real money? No. floprouter runs on FLOP devnet. Devnet and testnet FLOP have no monetary value. ## Who runs floprouter? An independent operator. It is not run by FLOP Labs. ## Why does a reply take 15 to 50 s? Each request opens a payment channel on chain, and the miner's reply is checked against its signed receipt before you get it. Streaming shows text as soon as the miner sends it. ## Why is the settlement later than the reply? The miner posts the settlement on chain after the reply, usually 2 to 4 minutes later. Your request does not wait for it unless you send `"flop": {"wait_for_settlement": true}`. See [settlement](/docs/settlement/). ## Who is the payer on chain? In grant mode, your wallet: the chain records your address on every channel. In balance mode (`credit`), the router's wallet. See [payer modes](/docs/payer-modes/). ## Can the router move my funds with the grant? No. The grant covers the `ComputeChannel` pallet, within the caps you sign, until it expires. It cannot transfer your funds. Revoke it with `flopSessionKeys.revokeSession`. ## How do I get my balance back? `POST /v1/balance/withdraw` sends it to the wallet that owns your key. See [withdrawals](/docs/withdrawals/). ## Why does my model say "no reachable miner"? No miner serving it has a proven, ready endpoint right now. Session URLs are not on chain, so a miner becomes reachable once its operator submits its URL. Pick a model marked available on the [models page](/models/). ## Can I choose the miner? Yes. Name it with `provider.only` or `provider.order`. See [provider selection](/docs/routing/). ## Does it support tools, images or embeddings? No. Chat completions with text messages. See [limits](/docs/limits/). ## My agent keeps failing with 400. Check whether it sends `tools`. Tool calling is not supported; use the client's plain chat mode. ## Where is the API reference? At [/docs/api-reference/](/docs/api-reference/), rendered from [`/openapi.json`](/openapi.json). --- # Good to know > How requests, prices and payments work on FLOP Network, and what the API does not offer. - **A provider is a miner.** In routing preferences, name a miner by its account address, or by the host of its session endpoint. - **Cost follows `max_tokens`.** A request escrows the prompt plus `max_tokens` at the model's price, with a minimum per request, and a settled session pays the whole escrow to the miner. Keep `max_tokens` close to what you need. - **The largest request is what one payment covers.** `context_length` is the largest prompt plus completion one request can pay for here. It is set by the escrow ceiling and is smaller than the model's own window. - **Sampling is fixed.** Each model's decode policy is set on chain and every reply is verified against it, so `temperature`, `top_p` and similar fields are accepted and reported as ignored. - **No tool calling.** No model on the network is served with tools yet. - **Amounts are in FLOP.** Prices, costs and your balance are FLOP. Devnet and testnet FLOP have no monetary value. - **A prepaid FLOP balance.** You fund it with an on-chain transfer and can [withdraw](/docs/withdrawals/) it. - **Accounts are wallets.** Keys come from a wallet signature. There are no organisations, workspaces or management keys. - **Every request is settled on chain.** Each response carries a `flop` record with its payment channel, and the settlement follows 2 to 4 minutes after the reply. See [payment channels and sessions](/docs/sessions/). - **You can be the payer of record.** In grant mode your wallet pays every session on chain. See [payer modes and grants](/docs/payer-modes/). - **Replies take 15 to 50 s.** A non-streaming call returns `202` with a session to poll when no reply is ready within about 85 s. - **No zero data retention.** Miners keep signed session evidence for audit and settlement, so `data_collection: "deny"` gets 503. ## Not offered Responses and legacy completions endpoints; embeddings, images, audio, video and rerank; plugins; presets, guardrails, batch and analytics.