Docs

For AI API providers

You already run an AI API: a relay on new-api, a gateway, an aggregator, or your own open models. TapeAPI adds a signing sidecar in front of it. Your API, your keys and your billing stay exactly as they are; your users keep their official SDKs and change only the base URL.

This guide is for providers that operate within their upstream providers' terms (see Compliance).

From zero to live

Start from nothing (no circuit, no container) and check every step before the next one. Every step is yours to pay for and to run: TapeAPI hosts no one's sidecar and pays for no circuit, container or gas. 42.1013.tape in this guide is an example name; no service is published under it. In the commands, put your own TapeOut name and your sidecar's address.

Step 0 needs a checkout of this repository with its dependencies installed, once, at its root (Node.js 22 or later):

git clone https://github.com/BruceLanLan/tapeapi.git && cd tapeapi
npm ci --no-audit --no-fund

The checks of steps 1 to 7 are tapeapi-doctor (experimental), which ships in the SDK's release package since 1.2.0. Every tapeapi-doctor in the table stands for this, run from any directory, with nothing to clone:

npx -y --package=https://github.com/BruceLanLan/tapeapi/releases/download/v3.0.0/tapeapi-sdk-3.0.0.tgz tapeapi-doctor <your name>

In a checkout, node sdk/bin/tapeapi-doctor.js <your name> at its root does the same. Either way the report writes the next command the way you ran it.

#StepWhere (who pays)CheckWhat you should see
0See the whole path work on your machine: no key, no circuit, no costa checkout of this repository, after npm ci at its root (above)node examples/relay-trial/trial.mjsit prints "The trial passed."
1Get a TapeOut circuittapeout.net (you buy it)tapeapi-doctor <your name>name and circuit pass
2Open its containertapeout.net (one transaction, your gas)tapeapi-doctor <your name>container passes; activation warns until step 2b; manifest-file fails, as it should until step 5
2bActivate the name (TAP-10 §6.3): without it a TAP-11 client gets unpaid and does not resolve your servicethe holder's wallet calls bind("<your name>", <your container>, <months>) on DomainBinding of your chain, with msg.value = months × monthlyFee() (you pay the fee, in BNB, OKB or ETH, and the gas); the doctor prints the exact call and the fee it reads from the chain now, which can change at any timetapeapi-doctor <your name>activation passes and shows the date it is paid until
3Run the sidecar in front of your gateway, on your server, behind your HTTPS reverse proxybelow (your server)tapeapi-doctor --offline https://api.example.comthe report names the setup-mode variables still missing
4Service key and delegation; put the values in .env and restart the sidecarholder console steps 3 and 4 (no fee, no gas)tapeapi-doctor https://api.example.comdelegation, reach and receipt pass; manifest-file warns "not published on chain yet"
5Publish the manifest, price table includedconsole step 5 (one transaction, your gas)tapeapi-doctor <your name>every check passes: exit status 0
6Tell your usersWhat your users dotapeapi-verify <your name> on a user's machineone OK line per call
7Renew the delegation before it expires (30 days by default), and keep the activation paidconsole step 4, "Renew"; pay again as in step 2btapeapi-doctor <your name>, daily in your CIdelegation warns from 7 days before expiry; activation warns once the name is no longer paid

The same steps as a wizard: tapeapi init (experimental, since 2.3, outside the compatibility promise). From a checkout, node sdk/bin/tapeapi.js init --dir <the folder of your sidecar's docker-compose.yml> runs one step at a time: what you do, where, who pays (you, every time), then the step's check from the table above, read-only, and the next command. It asks for no key, password or token, never reads your .env, pays nothing and sends no transaction. From step 3 on, --formats is required and has no default: the formats your gateway really serves and you have tested; all four need --confirm-all-formats, because they all go into the manifest on chain. Steps 3 and 4 also need --upstream new-api when no terminal asks (it is the only gateway this version writes for, and it is not assumed: a LiteLLM operator follows examples/litellm-sidecar/README.md instead). It writes a .env once, with FORMATS set to that choice and every secret left empty for you.

tapeapi-doctor checks, in order: the name resolves, the circuit exists, the container is opened, the name is activated (TAP-10 §6.3; a warning only: the site files stay readable, but a TAP-11 client answers unpaid and does not resolve the service), the manifest file is on chain, its format, the delegation (and the days left), the ai field, the price table, the endpoints, that they are reachable (TLS, sidecar out of setup mode, the key it signs with), CORS, that a real request gets a receipt that verifies, and the receipt lookup. That request costs nothing: it carries a key that cannot be valid, your gateway refuses it, and the sidecar signs a receipt for the refusal too. If your gateway accepts any key, it answers instead, and each run costs you a few input tokens and 1 output token per endpoint (16 on openai-responses, whose minimum is 16); the receipt check then warns you to fix the gateway's authentication. --key-env VAR adds one real call per endpoint with your own key, of the same size, at whatever your gateway charges. That key goes only to the host you are checking (the URL you give, or, for a name, the hosts of its signed endpoints.live), never to another host a manifest names, and only over https (plain http only to a loopback sidecar with --allow-http); every text in the report, --json included, shows it as ***, even when a gateway echoes it back. Every check that fails says what is missing, where to fix it and the next command, in English and Chinese. Exit status: 0 passed (warnings allowed; --strict counts them), 1 a check failed, 2 a usage mistake, 3 the chain or the network could not be read (a timeout, a refused connection, DNS: run it again); --json prints the report for CI; --lang en or --lang zh prints one language only. It reads only: it signs nothing and sends no transaction. Given a sidecar's URL, it probes that address, not the one the served manifest publishes, and warns when the two differ. It is experimental: its checks and its output may still change in a 1.x release.

For a daily check in your CI, read the activation check of --json rather than its text (experimental, since 2.2): paidUntil is the end of the container's paid period in ISO 8601 UTC, paidUntilSeconds the same as read from DomainBinding.containerPaidUntil(container) (Unix seconds; the payment contract compares it with the chain's block time, not your clock), and monthlyFeeWei is monthlyFee() in wei, as a string. A value that could not be read, or was not read (paidUntil while the name is not activated, or when only the name was paid and the container-level value is 0), is null, and unread says why. null does not mean expired: a script checks the check's status first and excludes null before comparing a date (in JavaScript new Date(null) < now and null < now are both true). The fields are there when the check reached the chain (pass, warn or fail) and absent when it was skipped or undecided. They come from plain reads at the nodes' latest block during that run, not from a pinned block, so no block number comes with them. When monthlyFee() is not 0, the text report adds a note: line (and its Chinese 提示: line) under the check; the check still passes and the exit status is the same.

Once every check passes, you may list your service in the provider directory with a pull request of your own that adds its name to site/directory/providers.json (the steps are in directory/). The directory reruns the doctor on every entry once a day and shows the result. A listing only means the automated checks passed, not a recommendation, a guarantee or an audit; your service works the same without one.

What you get

  • An on-chain identity. The service is a TapeOut circuit's container. Who answered is a chain lookup; move to another domain or server and users follow the on-chain record.
  • A price list pinned on chain. The manifest's ai field (TAPI-20 §3.9) lists one endpoint per API format and your price table: per model, one price per currency, per 1M tokens, with cache and reasoning prices where you charge them. Anyone can recompute what a call should cost.
  • A signed usage receipt for every call (TAPI-21 §3.5): the model, the token counts, the amount per currency, whether the answer completed, and the hashes of the exact request bytes and of the answer (its exact bytes; for a stream, the data of its events), signed by the key your circuit's holder delegated. Receipts ride along with the answer (a response header, or an SSE comment the official SDKs ignore), so nothing breaks for clients that do not read them. The one exception: a stream with a line that starts with U+FEFF before the point where the sidecar signs gets no receipt, since clients read such a line differently and no receipt could say what they were shown.
  • No custody. TapeAPI holds no keys, no funds and no traffic of yours. The sidecar runs on your own machine; the identity and the price list live on chain, readable without any server of ours.
  • No change for your users. OpenAI Chat Completions, OpenAI Responses, Anthropic Messages and OpenAI Embeddings pass through byte for byte, streams included. Claude Code, Codex and the official SDKs work as before.

What a receipt proves, and what it does not

A receipt proves who answered (the on-chain signer), to exactly which request bytes, with exactly which answer (its bytes; for a stream, the data of its events), and what usage and price were claimed. It does not prove which model actually ran: a provider could label a cheaper model's answer as a dearer one. What the signature adds is that such a substitution is attributable: a receipt cannot be disowned, so spot checks (anyone sending test prompts and publishing the results) leave evidence. Say this plainly to your users.

Choose how to run the sidecar

The same sidecar (createAIProxy from @tapeapi/server/ai-proxy) comes in several packages. Whichever you pick, you run it: it sees your users' API keys, so TapeAPI never hosts it for you.

You runUseWhere
new-apiA docker-compose package: new-api plus the sidecar in front of it, both on loopback behind your HTTPS reverse proxyexamples/new-api-sidecar/
Any OpenAI- or Anthropic-compatible API, on a serverNode: the example entry, or createAIProxy inside your own server (it is a fetch-style handler)examples/ai-proxy/index.mjs
Any such API, without a server of your ownA Cloudflare Worker on a hostname of yours, in front of your APIexamples/ai-proxy/worker.js
LiteLLM ProxyA docker-compose package: LiteLLM (with its PostgreSQL) plus the sidecar in front of it, all on loopback behind your HTTPS reverse proxy; the price table's ids are LiteLLM's model_namesexamples/litellm-sidecar/

The sidecar sits in front of your gateway, never inside it: new-api has no hook on text relaying, a LiteLLM callback sees parsed Python objects rather than the bytes a receipt proves, and in front the receipt covers the price and usage you charge your own users.

The new-api package in brief

git clone https://github.com/BruceLanLan/tapeapi.git && cd tapeapi/examples/new-api-sidecar
cp env.example .env && cp models.example.json models.json     # fill in both
# in .env, set FORMATS to the API formats your new-api really serves: openai-chat for an OpenAI-compatible relay
docker compose up -d

Set FORMATS: the formats it names (openai-chat, openai-responses, anthropic-messages, openai-embeddings, comma-separated, or all) are the only ones published in the manifest and signed; a metered path of a format left out is answered HTTP 400 naming FORMATS, never forwarded. Unset, the sidecar runs as all (the four formats 2.0.0 published) and warns in its startup log and in the warning of /tapeapi/v1/health, naming FORMATS and its values. Upgrading a 2.0.0 deployment: its .env has no FORMATS, so it keeps serving the four formats with that warning; set only the formats your new-api serves (or FORMATS=all if it serves all four) and restart.

From this directory the checkout's doctor is node ../../sdk/bin/tapeapi-doctor.js; the npx form of the table works from anywhere.

Your reverse proxy sends https://api.example.com to the sidecar (127.0.0.1:8080) and new-api's web console to 127.0.0.1:3000 on a hostname of its own. Until the identity is complete the sidecar runs in setup mode and says what is missing. The package's README has the full steps, the reverse-proxy settings, how to add the sidecar to an existing new-api deployment, and how to try it all locally without Docker.

The price table

The table is a JSON array; the sidecar publishes it in the manifest and prices every receipt from it:

[
  { "id": "claude-sonnet-4-5", "aliases": ["claude-sonnet-4-5-20250929"], "prices": [
    { "currency": "USDT", "unit": "1M tokens", "input": "3", "output": "15", "cacheRead": "0.3", "cacheWrite": "3.75", "cacheWrite1h": "6" }
  ] },
  { "id": "text-embedding-3-small", "formats": ["openai-embeddings"], "prices": [
    { "currency": "USDT", "unit": "1M tokens", "input": "0.02", "output": "0" }
  ] }
]
  • Currencies: BEM, BNB, USDT, USDC, ETH, USD1, or USD for display only; one entry per currency.
  • Prices are decimal strings per 1M tokens: input and output, and optionally cacheRead, cacheWrite, cacheWrite1h and reasoning.
  • A receipt is priced by the model the upstream reported, matched exactly against each id and alias. If your gateway renames models, list the reported names as aliases, or those receipts carry no price.
  • Prices are published, not settled. Your users pay you as they do today; the amount in a receipt is a checkable claim, not a payment.

From new-api's price list, node sdk/bin/tapeapi.js prices convert and prices check (experimental, since 2.3) run the new-api package's converter with the same arguments, output and exit status (a checkout only), and prices show --models models.json prints the table with its source record: who fetched the price list, the rate and quota_per_unit, what was refused or flagged. Files only: save /api/pricing and /api/status of your own new-api yourself, without a cookie or a token.

Identity and publishing the manifest

The identity steps are those of any TapeAPI service (see Run a service), done in the holder console at tapeapi.fun/console: connect the wallet that holds the circuit, generate the service key (it becomes the sidecar's SIGNER_KEY), sign the delegation (the console reads the sidecar's signing address from its setup-mode health check; the delegation lasts 30 days by default, and the page takes any number of days from 1 to 366), then publish the manifest on chain.

Publish the price table with the console

Step 5 of the console publishes the sidecar's manifest, ai field included:

  1. Preview (optional, no wallet needed). In step 5, paste or upload your models.json (the sidecar's price table, a bare array of models), the ai field itself, or a whole manifest. A models.json has no addresses, so the page adds one endpoint per format on the service URL of step 4, exactly as the sidecar does (/v1 for the OpenAI formats, the root itself for Anthropic Messages). The page checks the field with the same rules as the SDK's validateAIField (TAPI-20 §3.9) and shows it as tables: every API format with its address, then every model with its aliases and, per currency, the input, output, cache read, cache write, 1-hour cache write and reasoning prices, per 1M tokens. A price the manifest does not state is shown in grey italics with the value the spec gives it (cache prices default to input, 1-hour cache writes to cacheWrite, reasoning to output).
  2. Hints, not refusals. Cells and a list below the table point out what is probably a mistake: a price of 0, a price far above what any model costs (per currency; for example above 1,000 USDT per 1M tokens: a missing decimal point?), an output price below the input price, a cache read dearer than input, an endpoint clients would ignore, USD (display only), and a table too large for one transaction. They never stop publishing: you decide.
  3. Check and publish. The page reads the manifest the sidecar serves, checks every field as before and the ai field as the SDK does, and requires a previewed table to be exactly the served one. It shows the price table again, then asks your wallet to confirm the one SiteRegistry.putFile transaction. The delegation of step 4 covers only the signing key; this transaction is what puts the prices on chain.
  4. Read back. Once the transaction is mined, the page reads the manifest back from the chain as every client does (length and SHA-256 against the SiteRegistry) and confirms the bytes, price table included, are the ones it sent.

Prices are published, not settled, on every chain. The console publishes on BNB Chain, X Layer and Base; on X Layer and Base payments are not open, and the page says so: the table is for display only there. Under TAPI-20 §3.9 the currencies BNB, USDT, USDC, ETH and USD1 name the tokens on BNB Chain.

Renewal. Renew the delegation in its last 7 days at the latest: console step 4, "Renew" (same service key), set the new DELEGATION_EXPIRES and DELEGATION_SIG, restart the sidecar, and publish again. An expired delegation stops the service until it is renewed.

What your users do

They keep their keys and their SDKs and change the base URL to the endpoint of their format in your manifest:

ClientBase URL
OpenAI SDKs and OpenAI-compatible toolshttps://api.example.com/v1
Anthropic SDKs, Claude Code (ANTHROPIC_BASE_URL)https://api.example.com (the SDK adds /v1)
Codex (OPENAI_BASE_URL, or base_url in config.toml with wire_api = "responses")https://api.example.com/v1

Checking receipts. Developers wrap the official SDK's fetch; every answer is then checked against the manifest on chain (signer, price table, exact bytes), and a receipt that fails is an error, never swallowed:

import OpenAI from 'openai'
import { createTapeAPI, rpcUrlsFor, ai } from '@tapeapi/sdk'

const api = createTapeAPI({ rpcUrls: rpcUrlsFor(56) })            // BNB Chain nodes of distinct operators, 2 must agree
const svc = await api.resolve('42.1013.tape')                    // your service's TapeOut name (this one is an example)
const fetch = ai.createVerifyingFetch({ api, service: svc })
const baseURL = svc.manifest.ai.endpoints.find((e) => e.format === 'openai-chat').baseUrl
const client = new OpenAI({ baseURL, apiKey: process.env.API_KEY, fetch })  // the user's key with your service, as before

Use the baseUrl from the manifest exactly. A request to a metered path on any other host (localhost for 127.0.0.1, another port) is refused with INVALID_ARGUMENT before it is sent, naming the endpoint it expected; with strict: false it goes through and onReport says not verified: endpoint mismatch. So is a metered path written loosely (/v1//chat/completions, /v1/chat/%63ompletions, a trailing /), which OpenAI and Anthropic still answer: not verified: path mismatch. Streams are verified too. A stream ends at its final event, at [DONE] or when the connection closes, whichever comes first; with the default strict: true the part in which it ends is passed on only once a receipt that came before it verifies, so a stream that fails makes the SDK's iterator throw RECEIPT_INVALID. With strict: false nothing is held back, and the verdict goes to onReport. The receipt is checked against the stream as it stood at its end, however the network cut the bytes into chunks. In strict mode the stream is passed on up to its end and closed there, so nothing after the end reaches the application; a stream that the connection closes on in the middle of an event, or that has a line starting with U+FEFF (the SDKs and the receipt rule read both differently), fails with RECEIPT_INVALID. With strict: false these are only reported, as is an event after the end (tapeapi-verify below does the same). verifyUsageReceipt({ responseBytes }) over a whole stream you hold hashes every event in it (TAPI-21 §3.5), so for a stream with events after its end it can disagree with the streaming check. A whole (not streamed) answer whose receipt fails comes back, in strict mode, as an HTTP 502 in the API's error shape with code RECEIPT_INVALID and the headers x-should-retry: false and x-tapeapi-verify-error: RECEIPT_INVALID: the official SDKs throw an APIError and do not retry it; code that calls the fetch itself checks res.ok. Whether a paid call is retried after other 5xx errors is up to you (the SDKs' maxRetries).

Claude Code and Codex users cannot read receipts themselves. They run the local verifying proxy tapeapi-verify and point the client at it. tapeapi-verify keeps running in the foreground, so the client starts in a second terminal:

# Terminal 1. 42.1013.tape is an example name: put your service's TapeOut name here
npx -y --package=https://github.com/BruceLanLan/tapeapi/releases/download/v3.0.0/tapeapi-sdk-3.0.0.tgz tapeapi-verify 42.1013.tape
# Terminal 2, macOS or Linux
ANTHROPIC_BASE_URL=http://127.0.0.1:8790 claude
OPENAI_BASE_URL=http://127.0.0.1:8790/v1 codex             # Codex (or base_url in config.toml)
# Terminal 2, Windows PowerShell
$env:ANTHROPIC_BASE_URL="http://127.0.0.1:8790"; claude
$env:OPENAI_BASE_URL="http://127.0.0.1:8790/v1"; codex

With the example name as written it stops with "no file at /.well-known/tapeapi.json": nothing is published under 42.1013.tape. No service of your own yet? Run the local trial first (From zero to live, step 0): it runs this proxy against a local sidecar.

Before that, tapeapi connect (experimental, new in 2.1, outside the compatibility promise) shows your users your service as the chain has it and prints client settings only for the formats your manifest declares (no Claude Code settings without anthropic-messages, no Codex settings without openai-responses):

# any directory, no clone needed; 42.1013.tape is an example name
npx -y --package=https://github.com/BruceLanLan/tapeapi/releases/download/v3.0.0/tapeapi-sdk-3.0.0.tgz tapeapi connect 42.1013.tape            # the service card and the settings
# with the SDK installed, the command is tapeapi connect …
tapeapi connect 42.1013.tape --proxy    # then runs tapeapi-verify for it

In a checkout (npm ci once at the root), node sdk/bin/tapeapi.js connect … does the same.

It reads the chain and the manifest only: no transaction, no key or password asked for (the settings read the token from API_KEY in the user's own environment), nothing uploaded, nothing paid. An unpaid, not-opened or store-changed service is shown as unavailable (exit 1) and --proxy starts nothing; exit 2 is a usage mistake (also --tool naming a format the manifest does not declare), 3 means it could not be read. In code the same is @tapeapi/sdk/connect (snippetsFor, connectReport, renderConnect), experimental too. A manifest with no ai field is not an AI service: connect shows it as unavailable (not-ai), unless it declares MCP tools (mcp, see MCP).

Afterwards, your users can look at their receipts and set them against your bill with tapeapi receipts and tapeapi reconcile (experimental, since 2.2, outside the compatibility promise). Both read files on the user's machine only: no network, no key.

# any directory, no clone needed
npx -y --package=https://github.com/BruceLanLan/tapeapi/releases/download/v3.0.0/tapeapi-sdk-3.0.0.tgz tapeapi receipts tail --receipts ~/.tapeapi/receipts.jsonl   # what tapeapi-verify --log wrote
# with the SDK installed, the commands are tapeapi receipts … and tapeapi reconcile …
tapeapi receipts show <id> --receipts ~/.tapeapi/receipts.jsonl         # one receipt, its checks replayed offline
tapeapi reconcile --receipts ~/.tapeapi/receipts.jsonl --bill usage.csv # set against a bill file

In a checkout (npm ci once at the root), node sdk/bin/tapeapi.js receipts … and node sdk/bin/tapeapi.js reconcile … do the same.

show replays a receipt's checks (signature, container, method and path, price table; the hashes too with the exact bytes, request bytes only from a tapeapi-verify --no-salt run or the files its --save-requests <dir> writes) against your manifest as the user saved it next to the receipts (manifest.json); without it, nothing is decided (exit 3). reconcile lists matches, rows missing on one side, and fields that differ from what the receipt claims, each with its two lines; it decides nothing. --preset new-api names the fields of the JSON new-api's GET /api/log/self returns (data.items; read in new-api's source code, not yet checked against a real instance). It is not new-api's web CSV export: that file has localized headers, a formatted Cost that is not a comparable amount and request_id rather than upstream_request_id, so the preset does not match it (exit 2); name its columns with --map, as for any other bill.

Which columns to export so your users can reconcile, the checks on each request, and the comparison with a mandate and with local limits: Reconcile your receipts (experimental).

tapeapi-verify resolves your service on chain, passes the answers through unchanged, prints one verdict per call, and turns a failed receipt into an error the client sees (HTTP 502, or an error event in place of a stream's final event). That is the default since 3.0, as for createVerifyingFetch; --no-strict only logs the failure and passes the answer on, as 2.x did without --strict (still accepted, it changes nothing). A single receipt can also be pasted into the verification page. All of these need your manifest on chain (console step 5, above).

Request salt (on by default in both). A receipt carries requestSha256, the SHA-256 of the exact request bytes, and the official SDKs serialise a request the same way every time. A short prompt ("yes", one word to embed, a question from a known list) could then be confirmed from a shared receipt by hashing guesses. So createVerifyingFetch and tapeapi-verify append 64 random whitespace characters (space, tab, line feed, carriage return: 128 random bits) after the JSON text of each request body on a receipt path, and the receipt is checked over the bytes actually sent.

  • Why prompt caching is unaffected: JSON allows whitespace after the value (RFC 8259 §2), so the upstream parses exactly the same request. The whitespace is outside every string, so it is in no message and becomes no token; the caches (OpenAI's automatic prefix cache, Anthropic's cache_control breakpoints) are keyed on the parsed prompt's tokens, which are identical.
  • No field is added or changed. In particular user (OpenAI) and metadata.user_id (Anthropic, which Claude Code already sets) stay as the client wrote them: gateways use them to route a conversation to the same account, which is what makes its cache hit.
  • Left alone: compressed bodies (Content-Encoding other than identity: appending would corrupt them), non-JSON bodies, and every path without a receipt. salt: false / --no-salt sends the bytes exactly as written.
  • Keeping the salted bytes (experimental, 2.5, off by default): tapeapi-verify --save-requests <dir> writes each metered request it sends, salt included, to <dir>/<sha256>.request (directory 700, files 600), for tapeapi reconcile --requests <dir>. Those files are the conversation in clear, which the receipt and --log never hold: use it only for the calls you mean to check, and delete them afterwards (see the reconcile guide).
  • A proxy that re-serialises the request between the client and the sidecar changes the bytes either way; the receipt check then fails on requestSha256, which is how such a proxy shows itself.
  • Not yet measured: the JSON grammar says every upstream must accept the trailing whitespace, and the tests check it against the reference sidecar; a check against the live OpenAI Chat, OpenAI Responses and Anthropic Messages APIs is still to be done.

A budget of their own (experimental, 3.0)

A user can also refuse their own calls before they are sent, with a policy file they write (Reconcile your receipts):

tapeapi-verify 11.1013.tape --policy my-limits.json --budget-store spend.jsonl

A metered call whose worst case would take a rule over its limit gets HTTP 400 with code budget_exceeded (one that cannot be bounded, such as a request without max_tokens, budget_no_limit, ...), with x-should-retry: false, and is not forwarded, strict or not. The store file (mode 600) keeps the verified receipts and one line per call, so the count survives a restart; an HTTP 4xx or 5xx answered with no receipt is released, a broken connection keeps counting at its worst case. It is a convenience on the user's side: it binds nobody else, and it bounds the prices the receipts claim, not what the user pays you. Nothing changes for the service.

The usage of a streamed Chat answer: three ways

An OpenAI Chat stream reports its token usage only when the request sets stream_options.include_usage to true: the stream then ends with one more chunk, choices: [] and the usage. The official openai package does not set it (at the time of writing, 7.x), so a plain chat.completions.create({ stream: true }) gets no usage at all. This section is about that case: OpenAI Chat clients (the openai SDKs and tools that speak the same API) streaming /v1/chat/completions. Claude Code (Anthropic Messages) and Codex (OpenAI Responses) are not affected: their streams carry the usage whether or not they ask, and the receipt's usage is compared with it. Embeddings do not stream.

Who asks the upstream for the usageDoes the application get the usage chunkIs the receipt's usage compared with the stream
1. Defaultthe sidecar, on its ownno: the sidecar takes it outno: listed in unchecked
2. The application asksthe application, in its requestyes, one more chunkyes
3. requestUsage / --request-usagethe verifying side, in the request's bytesyes, one more chunkyes

1. The default: the sidecar asks, you cannot compare

When a streamed request does not ask for the usage, the sidecar sends the upstream a copy that does, reads the usage from the chunk that causes, and removes the chunk from what your client receives, so you get exactly the answer you asked for. The receipt says usageInjected: true and states the usage the sidecar read. Your client never saw that chunk and has nothing to compare the number with: its report lists the usage in unchecked ("usage (usageInjected: the answer the client received lacks the usage chunk the sidecar read)"), and the verification page says the usage was not compared.

  • Guaranteed: the signer, the model, whether the answer completed, and that the request and response hashes are those of the bytes you sent and received. The price is recomputed from the receipt's usage.
  • Not guaranteed: the usage figure. It is the sidecar's statement, and nothing you hold can contradict it: a sidecar could sign a higher number and every other check would still pass. For a whole (not streamed) answer, or any other API format, this gap does not exist.

2. Ask for the usage yourself

Set stream_options: { include_usage: true } in the request (Python: stream_options={"include_usage": True}). The sidecar sees that the request already asks, so it injects nothing, removes nothing and sets no usageInjected. The usage chunk is part of the stream the receipt hashes and part of what your application receives, so the verifying client compares the receipt's usage with it. It costs nothing and needs no option of ours:

const stream = await client.chat.completions.create({
  model: 'your-model', stream: true,
  stream_options: { include_usage: true },        // the last chunk has choices: [] and the usage
  messages: [{ role: 'user', content: 'Hello' }],
})
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta?.content ?? '')

3. Let the verifying side ask: requestUsage

For an application you do not want to change, or one you cannot (a tool that never sets stream_options), the verifying side sets the member for it. createVerifyingFetch({ requestUsage: true }), or tapeapi-verify --request-usage (1.6.0 and later), is off by default; only true turns the option on.

const fetch = ai.createVerifyingFetch({ api, service: svc, requestUsage: true })
tapeapi-verify --request-usage 42.1013.tape        # started as in "What your users do"

The effect is the same as in way 2: the sidecar injects nothing, and the usage chunk is in the signed stream the application receives. What the option does and does not do:

  • It changes a request only where the sidecar would have changed it: a stream OpenAI Chat request whose stream_options.include_usage is not true. A request that already asks, a request that is not a stream, and any other API format are sent as they are.
  • It changes one place in the bytes and keeps every other byte. No stream_options: ,"stream_options":{"include_usage":true} goes after the last member. A stream_options object without include_usage: ,"include_usage":true goes inside it. An include_usage of another value (false, null, "true", ...): the value is replaced by true. A stream_options that is not an object (null, an array, a string): it is replaced by {"include_usage":true}. The result is checked against the sidecar's own rule before it is sent. Then the salt is added and the request goes; requestSha256 is the hash of the bytes finally sent.
  • It leaves a request alone when it cannot change it safely: a compressed body; a Content-Type that is not JSON; a body that is not UTF-8 or starts with a byte order mark; a custom format that names no member to set; a key that appears twice at the top level or in stream_options; a result that fails the check. With strict (the default for createVerifyingFetch), the SDK throws INVALID_ARGUMENT before sending anything (data.reason names the cause) and tapeapi-verify (strict by default since 3.0) answers HTTP 400 (usage_request_skipped, with x-should-retry: false) without forwarding. Without strict (strict: false, --no-strict) the request goes as it is, the report says usageRequestSkipped: <reason>, and the usage is unchecked as in way 1.
  • Reports. With the option on, each report carries usageRequested: true when this fetch set the member, false when it did not (the application asked itself, it is not a Chat stream, or the change was skipped). With the option off, the field does not exist. tapeapi-verify writes the same fields to --log and prints usage=asked or usage-request-skipped=<reason> on the verdict line. If the request asked for the usage and the stream carries none (the upstream did not send it, or something on the way took it out), there is a warning to that effect.

What the application sees (ways 2 and 3). One more chunk before [DONE], with choices: [] and the usage; nothing is taken out on the client. Code that reads chunk.choices[0] without checking that the list is not empty fails on it (a TypeError in the JavaScript SDK), so read chunk.choices[0]?.delta instead. The openai package's .stream() helper works unchanged, and finalChatCompletion().usage has the value. The reason nothing is removed: the bytes your application holds are then exactly the bytes the receipt hashes, which keeps an archived stream checkable offline (the verification page, a dispute).

What ways 2 and 3 guarantee, and what they do not. The usage in the receipt is the usage in the signed stream your application received, the standard a whole answer already has. A sidecar that states one number in the receipt and sends another in the stream fails the check (RECEIPT_INVALID), and one that overstates the usage in both has signed it into an answer you can show to others: attributable, not impossible. Neither way shows what the upstream really counted: the sidecar that signs the receipt also produces the stream. Say it to your users as it is.

Limits, and why way 3 is off by default.

  • A JSON body sent with a Content-Type that is not JSON is skipped by the client, but the sidecar does not look at Content-Type and still injects: that call's usage cannot be checked, and under strict it is refused locally.
  • An upstream that ignores include_usage sends no usage chunk: the receipt then passes with usage null, and the report warns.
  • If your upstream rejects stream_options, so that your sidecar does not ask for the usage itself (the reference has no switch for it; it takes a custom formats table whose Chat adapter has no prepareUpstream), clients that turn on way 2 or 3 get HTTP 400 from your upstream. A sidecar that takes the usage chunk out although the request asked for it fails the check under strict (correct by the rules, but a loss of availability).
  • The salt now also reaches the upstream for these requests (a sidecar that re-serialised the request used to drop it): it is whitespace after the JSON text, which JSON allows.
  • Under strict, the official SDKs may wrap the INVALID_ARGUMENT as a connection error and retry it up to maxRetries times (not measured; no request is sent in any retry).

Fees

There is no mandatory protocol fee, and today nothing is charged by the protocol: prices in the ai field are published, not settled, and the paid-call escrow is not deployed (it will be only after an independent audit). When paid calls do settle through the TapeAPI escrow, a default 1% maintenance contribution comes out of the provider's share (the user's price does not change); any provider can set it to 0 for its own service, and the operator has no fee switch. See docs/FEES.md.

Limits

  • A receipt proves who answered and what was claimed, not which model ran (above).
  • The usage of a streamed OpenAI Chat answer is checked only when the request asks for it (stream_options.include_usage, by the application or by requestUsage); by default it is the sidecar's statement (above).
  • Formats with receipts: OpenAI Chat Completions, OpenAI Responses, Anthropic Messages, OpenAI Embeddings. Other paths under /v1 pass through without a receipt. A metered path of one of these formats that your sidecar does not serve (left out of FORMATS, or of formats in createAIProxy) is answered HTTP 400 bad_path, never forwarded; since 3.0 this is also createAIProxy's default (refuseOtherFormats: false passes it through without a receipt, as 2.x did). Not yet: Gemini's native API, WebSocket modes (Realtime, Responses WebSocket), Batch.
  • Receipts are kept in the sidecar's memory for one hour (configurable); the copy delivered with the answer is the primary one. The free receipt method has its own per-IP budget. If your upstream's answer ids are guessable (Ollama's are chatcmpl- and a number below 999; the sidecar's log says so), turn on requireRequestHash (RECEIPT_REQUIRE_HASH=1) so that a lookup must name the request hash as well.
  • The sidecar authenticates no one itself: your users' keys go to your gateway as they are, and your gateway decides.
  • The sidecar passes the clients' session headers (x-claude-code-session-id, session-id, thread-id) to your gateway, as the clients expect; they let whoever receives them tie a user's requests into one session. Set FORWARD_SESSION_HEADERS=0 (forwardSessionHeaders: false) to leave them out; a user can do the same on their side with tapeapi-verify --strip-session-headers.

Compliance

TapeAPI is for providers operating within their upstream providers' terms. Identity, prices and reputation live on chain, where no single platform can hold them hostage; the protocol does not offer, and does not help with, evading an upstream provider's bans or regional restrictions.

Security

  • The sidecar sees your users' API keys. Run it yourself, on your own machine or account; never let a third party host it.
  • The service key (SIGNER_KEY) signs every receipt. Keep it out of git, chat and screenshots; if it leaks, generate a new one in the console and redo the delegation rather than renewing.
  • The sidecar stores no prompts and no answers: it keeps signed receipts (hashes, model, token counts, amounts) for an hour, and nothing else.

The idea of a service layer for TapeOut came from @Theairresearch.

Edit this page on GitHub