Build with AI Pay

AI Pay lets your app call models with the user's own AI credits: through "Sign in with AI Pay", the user grants your app an "AI credit authorization", and within the spending limits they set, every AI request settles directly against the user's AI Pay wallet.

  • You never touch cards or front the cost — payment, credit and risk control all live in AI Pay; your app has no model bill.
  • Users stay in control — pausing, revoking and changing limits immediately stop new AI usage (requests already dispatched may still settle under their original rules); your app must handle the corresponding 403s.
  • The receipt travels with the response — every successful response carries a receipt (the actual charge and its split); every request can be reconciled.
  • Not “bring your own API key” (BYOK), not prepaid credits locked inside your app — users never paste a model API key and never buy credit from you; they pay for their own AI usage from their AI Pay wallet, within the spending limits they set, and every request is metered with a receipt.

Current status in production: free beta. Only invited users can create an account and use the service; public registration is not open. Your users must also be invited before their first sign-in through your app's "Sign in with AI Pay"; a person with no AI Pay account and no invitation stays on the AI Pay sign-in page and cannot complete the authorization. Test credit depends on the invitation; production does not accept top-ups at the moment, so users cannot add credit once it is used up. Invitation requirements, test credit and feature status are on /about. Not invited yet? Write to contact@coswic.ai and say what you want to build. In other environments, features and payment methods follow that environment's screens; Stripe / PayPal test modes do not make real charges, and test credits are not real payments or developer earnings. In the examples below the API base is https://ai-pay.coswic.ai and the authorization endpoint is https://auth.ai-pay.coswic.ai — both values are filled in by the environment you fetched this document from, so you can copy them as they are.

The user-pays model

In an app built on AI Pay, the end user pays for their own AI usage. The user keeps one balance of AI credit in AI Pay and, through "Sign in with AI Pay", authorizes your app to spend from it within the per-request, daily and monthly limits they set on AI Pay's consent screen. Every successful request is metered against that user's wallet, and the receipt comes back in the response.

  • Your app does not hold a model API key. It calls AI Pay with the user's authorization token, which is not a model key, and AI Pay calls the model provider; the provider's account and keys stay on AI Pay's side.
  • Your app has no model bill. AI Pay settles each request from the user's own AI credit; apps cannot add a per-request service fee or a surcharge on the AI usage fee (both are retired).
  • Not "bring your own API key" (BYOK). Users do not open a developer account at a model provider or paste a key into your app: they sign in with AI Pay and set a limit.
  • Not prepaid credits locked inside one app. The same balance works in every app the user allows, and the user can pause or revoke any app at any time.

What is open today (an invitation-only Beta; production does not accept top-ups) is on /about.

Quick start

Package versions: typed multimodal, tool, sampling and embeddings interfaces require SDK 0.6.0 or later; CLI 0.8.2 adds operation-aware chat-model selection. Check the version available on npm and installed in your project before using these interfaces; if you cannot obtain the required version, use the documented HTTP endpoints. aipay test verifies text chat and its receipt, not every multimodal capability.

Before you start, sign in to the Dashboard with your own Google account, complete the country/region details and current Terms of Service confirmation shown there, then open the Console. Creating an account on first sign-in requires a valid invitation; installing the SDK or CLI does not bypass these prerequisites. If the API returns region_required, finish setup in the Dashboard or use the aipay region command below.

  1. In the Console (app control panel), click "Create app" at the top right: just enter a name. The local callback http://127.0.0.1:{Port}/auth/aipay/callback is registered automatically (the port of 127.0.0.1 is not compared, so any local port works; add your production HTTPS URL later with the CLI callback command below) and you get your client_id. AI Pay uses a public client with PKCE S256 — there is no client secret. After creation the Console hands you a prompt for your coding agent, or run the CLI yourself — next section.
  2. Get the SDK (TypeScript, one package for server and browser): npm i @coswic/aipay-sdk (published on public npm). Browser rules are in the "Serverless apps" section.
  3. Send the user to the authorization URL (next section); the user signs in to AI Pay, sets limits, consents, and returns to your callback.
  4. Exchange the code for tokens and call POST /v1/chat/completions to send your first request.
  5. Reconcile under the Console's "Requests" tab (every request_id is searchable). App service fees and usage surcharges are retired and payouts are not open yet (see "App pricing (service fees)" and "Usage reconciliation and payouts"); for now, the end of the integration path is a successful response with a verifiable receipt.

Connect with the CLI or a coding agent (recommended)

After creating the app, the Console gives you a prompt you can paste straight into Claude Code, Cursor, Codex or a similar tool; the AI reads this guide and completes the integration with your app's settings. The prompt contains no tokens or keys. You can also run the same CLI yourself (@coswic/aipay, public npm):

npx @coswic/aipay@latest login --api https://ai-pay.coswic.ai
npx @coswic/aipay@latest init --app <client_id> --auth https://auth.ai-pay.coswic.ai --api https://ai-pay.coswic.ai
npx @coswic/aipay@latest test

Developer CLI sign-in manages your Apps; it is separate from a user authorizing AI spending. On a remote machine use login --device and ask the developer to approve the browser prompt. Before deploying, run aipay apps callbacks add --app <client_id> --callback https://yourapp.example/auth/aipay/callback; this preserves the existing local callback. Use apps callbacks list to inspect and apps callbacks remove --callback <url> to remove one. In a linked project, --app may be omitted. init --callback only writes local configuration. A concurrent edit or unknown outcome requires readback; the CLI does not blindly repeat a write. Callback changes require a server with ETag support.

init does this in your project (preserves existing application scaffolding, but updates project metadata, environment values and the downloaded guide on each run): detects the package manager and framework (Next.js / Express / Fastify / Hono / Node, or a Vite browser SPA; --framework overrides it; TypeScript or JavaScript), writes .aipay/project.json (commit it; no secrets), .env.local (four public values AIPAY_CLIENT_ID / AIPAY_AUTH_ORIGIN / AIPAY_API_BASE / AIPAY_CALLBACK_URL, and adds it to .gitignore), a start/callback route pair for your framework, aipay-agent.md (project facts plus a snapshot of this guide for offline reading; re-run init or fetch the current environment’s docs to refresh it), and finally installs @coswic/aipay-sdk.

test provides a real OAuth, text-chat and receipt check: the CLI receives the callback on any free port of 127.0.0.1 (AI Pay does not compare the port for loopback, so your dev server can keep running), opens a browser for you to sign in and authorize with your own account, exchanges the code, sends one chat completion on your behalf, and prints the receipt (request_id, amount). The green checks under "Verify" in the Console come from server-side facts, not from the CLI's own report. You can also verify through your running app. This text smoke test does not verify image, audio, PDF, embeddings or every model capability.

Command Purpose
aipay init --app <client_id> [--auth] [--api] [--callback] [--dry-run] [--no-install] Link the project and scaffold the integration; --auth / --api are optional once you are signed in
aipay test [--model] [--port] [--no-open] Real sign-in + first request + receipt
aipay doctor [--offline] Checks Node, the link, .env.local, the SDK, and reachability of the authorization server and API
aipay status / aipay unlink Show which app is linked / forget the link (keeps your code)
aipay login --api https://ai-pay.coswic.ai / whoami / logout Developer sign-in for the CLI itself (loopback PKCE, audience aipay-developer-api; on a remote or browserless machine add --device: it prints a URL and a short code you enter in a browser on any device); tokens live in the OS keychain (macOS Keychain / Linux keyring / a DPAPI-encrypted file on Windows), with a 0600 file only when none is available
aipay apps list / aipay apps create --name <name> / aipay init --create <name> Create apps from the CLI once signed in (sends an Idempotency-Key, so a rerun never creates a second app) and link them directly
aipay region / aipay region set --country <CC> [--state US-XX --line1 <street> --city <city> --zip <ZIP>] --accept-terms Show or set your account's country/region and accept the current Terms of Service; US accounts also need the full postal address (the backend locates the sales-tax jurisdiction — state / county / city / special district — and aipay region shows it); until everything is on file the developer API answers 403 region_required (aipay region prints the version to accept and the terms URL)

When creating an app directly with POST /v1/developer/apps, send an Idempotency-Key whenever possible; the name and Redirect URI list must remain the same for that key. Creation returns 201; retrieving the completed app with the same key returns 200. For 409 provisioning_in_progress, or 502 oauth_provider_error with details.outcome: 'unknown', wait and retry with the same key. A 502 with outcome: 'cancelled' means this creation was cancelled; you may reuse the key to create again. If you explicitly deleted a successfully created app, its original key returns 409 idempotency_key_consumed; use a new key for a new app. If creation without a key is interrupted and remains incomplete after 15 minutes, the system schedules automatic cleanup.

Every command accepts --json (one JSON document on stdout; the authorization URL goes to stderr) and --dir; exit codes are 0 ok, 1 fixable locally, 2 usage, 3 network or auth. For connection issues, see Connection and error troubleshooting.

When you are signed in, init and test report their results to the Console (framework, files written, receipt id), and the "Hand it to your AI" card on the app page turns from "Waiting for the tool" into "The CLI finished init". To revoke that connection: Console → "Connected apps" → "AI-Pay CLI" → Revoke authorization; the CLI's next call will then ask you to sign in again.

Sign in with AI Pay (OAuth 2.0 + PKCE)

AI Pay can be your sign-in service directly (OIDC): the user signs in to AI Pay with Google or email, and your app receives a stable user identifier (sub) and email — no other identity provider to integrate, no passwords to handle. For sign-in only, request just the identity scopes (openid email) — this creates a "sign-in connection"; to use AI, add the spending scopes and the same authorization creates an "AI credit authorization".

sub is a pseudonym specific to your app: the same user always gets the same sub in your app (safe to use as the account key), but a different value in other apps — apps cannot correlate a user through the identifier (a privacy design, like Sign in with Apple). If you also request email, the email itself can be correlated across services; it is data the user explicitly authorized you to receive.

The SDK builds the authorization URL in one line (state and the PKCE code_verifier are generated for you):

import { createConnectUrl, getUserInfo, handleCallback, refreshAccessToken } from '@coswic/aipay-sdk'

const cfg = {
  authOrigin: 'https://auth.ai-pay.coswic.ai', // the AI Pay authorization server origin (SDK 0.5.1 and later)
  clientId: '<the client_id the Console gave you>',
  redirectUri: 'http://127.0.0.1:4567/auth/aipay/callback',
  // Sign-in-only app: scopes: ['openid', 'email'] (the consent screen then shows no spending limits)
  // offline_access is not included by default — add it to scopes explicitly only if your server app must renew while the user is away
}

// 1. Build the authorization URL — store { state, codeVerifier } in your session (browser = sessionStorage)
const { url, state, codeVerifier } = await createConnectUrl(cfg)
// 2. The user signs in to AI Pay, sets limits (only with spending scopes), consents → returns to your callback (?code=…&state=…)
// 3. Callback: handleCallback does "check error → verify state → exchange the token" in one step —
//    you never write state verification yourself (hand-written checks get skipped, and a skipped check = a CSRF / code-injection surface);
//    a user pressing "Deny" or a lost session both throw a ConnectError with a clear message
let tokens = await handleCallback(cfg, callbackUrl, { state, codeVerifier })
// tokens.accessToken (15 minutes); tokens.refreshToken (null without offline_access)
// tokens.idToken: the OIDC id_token (only when openid was granted)
// Renew only when a server app explicitly requested and received offline_access; browser apps do not request it
if (tokens.refreshToken) {
  tokens = await refreshAccessToken(cfg, tokens.refreshToken)
  // Save the updated tokens in the server session; rotation invalidates the old refresh token
}

// 4. Fetch the user's identity (verified server-side; no need to verify the id_token signature yourself)
const user = await getUserInfo(cfg, tokens.accessToken)
// user.sub = a stable pseudonym specific to your app — use it as the account key in your database (email can change; never key on it)
// user.email / user.emailVerified / user.name depend on which scopes were granted

You can also skip the SDK — it is the standard OAuth 2.0 authorization code flow. Parameters of the authorization endpoint GET /oauth2/auth:

Parameter Value
client_id The client_id the Console gave you
response_type code
scope Sign-in: openid email; for chat add ai.chat.create wallet.charge; for embeddings use ai.embeddings.create wallet.charge; for long-term access add offline_access to get a refresh token
audience aipay-api (required — the token audience)
redirect_uri Exact match with the registered value
state Your CSRF random value; must be verified at the callback
code_challenge / code_challenge_method PKCE; the method is always S256

Token exchange: POST /oauth2/token (grant_type=authorization_code + code_verifier; renew with grant_type=refresh_token). Access tokens live 15 minutes — refreshing once on a 401 and retrying is a normal event, not an error.

Requestable scopes (what the user sees on the consent screen is the plain-language version of these):

scope What the user sees
openid Sign in with the AI Pay identity (the sub in the id_token / userinfo — a pseudonym specific to your app)
email Provide the email address (with email_verified — true only if it was once verified through Google)
profile Provide the display name
ai.chat.create Create AI requests (text, images, files, audio, etc.)
ai.embeddings.create Create text embeddings
wallet.charge Deduct the user's credits by actual usage
offline_access Renew the authorization while the user is away (long-term access with a refresh token)

Text embeddings require ai.embeddings.create wallet.charge; ai.chat.create is not required. Explicitly set the requested permissions in SDK ConnectConfig.scopes; the chat defaults do not expand automatically. For an existing app, its owner first saves the callback settings again, checks that the returned allowed scopes contain ai.embeddings.create, and then asks the user to complete interactive authorization. Existing tokens do not gain this permission.

Embedding availability: the API contract exists, but the production catalog checked on 2026-10-21 had no embedding model. Enable this feature in your app only after the selected environment lists an available aipay.operation="embeddings" model. No matching row means the feature is unavailable; do not substitute a chat model.

Choose a model from GET /v1/models with aipay.operation="embeddings" and aipay.availability.status="available", then call POST /v1/embeddings. The current shape accepts one nonempty text string and returns a float vector at the default dimensions; limits are in aipay.embedding. Batches, token arrays, multimodal input, custom dimensions, base64 and streaming are unsupported. Replace MODEL_ID with that model ID. First set the current shell’s ACCESS_TOKEN variable to the token obtained through the normal OAuth authorization; the command expands this variable. Do not store a real token in example files or version control.

curl "https://ai-pay.coswic.ai/v1/embeddings" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: UNIQUE_REQUEST_KEY" \
  -d '{"model":"MODEL_ID","input":"Searchable text","encoding_format":"float"}'

Use a new idempotency key for each request. If the outcome is unknown, query with the same key instead of resending with a new one. To recover the original vector, send a valid Replay-Key on the first request and retain it securely with the idempotency key. The idempotency key alone retrieves a receipt and does not guarantee a vector.

The embedding JSON body is limited to 64 KiB, independently of the model's input limits. This endpoint counts Idempotency-Key as 1–200 JavaScript string characters; images count 1–200 UTF-8 bytes, so UUIDs avoid that difference. After dispatch, a non-200 upstream response is an unknown outcome (502 usage_unknown), not proof of free execution; preserve the key while the hold is resolved or expires. A valid late vector may still be returned after hold expiry with a zero-charge receipt; use the receipt rather than assuming returned data means a charge.

The consent screen is provided by AI Pay: with spending scopes (AI credit authorization) the user sets monthly / daily / per-request limits there; with identity scopes only (sign-in connection) it is a lightweight two-step sign-in authorization with no money UI at all. Granted scope = everything you requested — to lower the user's hesitation, request fewer scopes.

Return visits and renewed consent: on return visits, users must first complete account region information and acceptance of the current Terms of Service. Repeat authorization consent can be skipped only while the account, App and existing authorization remain active, the scopes match exactly, and the consent-document fingerprint is current. Spending authorizations also need a budget and consent covering current platform pricing policies and rate ceilings. Scope changes, Terms or authorization-document updates, unaccepted pricing policies, rates above accepted ceilings or missing required records can require confirmation again. Account confirmation is not skipped.

Users can revoke the authorization in AI Pay at any time. Revocation blocks new AI usage under that authorization and initiates credential revocation; requests already dispatched may still settle. Handle a 401 / ConnectError from getUserInfo by asking the user to connect again. Revocation does not automatically end your App’s own sessions or delete data it already obtained; your App must handle its own sessions and data obligations.

Redirect URI (where the authorization result is delivered)

After authorization, AI Pay delivers the one-time authorization code (code) through a browser redirect — to the redirect URI you entered when registering the app. It is an allow-list: only registered URLs receive the authorization result, matched character for character (scheme, host, port, path, query; the only exception: the port of http://127.0.0.1 may vary, see the table below). You can register several (one per line), so development and production coexist.

Every kind of app uses the same mechanism; there are no special cases:

Your appredirect URINotes
Website with a serverhttps://yourapp.com/auth/callbackThe callback is handled by your server
Front-end only (SPA / static site)https://yourapp.com/callbackThe callback is a JS page that exchanges the token directly in the browser (PKCE needs no secret)
Local developmenthttp://127.0.0.1:<port>/callbackhttp is allowed only for the local hostnames 127.0.0.1 and localhost (RFC 8252). Only the port of 127.0.0.1 is excluded from matching, so changing ports needs no re-registration; http://localhost:<port>/… can be registered too, but the whole string (port included) must match exactly; IPv6 [::1] cannot be registered yet
iOS apphttps://yourapp.com/auth/aipay (Universal Link)An https URL on your domain configured as a Universal Link; iOS verifies domain ownership and opens it back into your app — to AI Pay it is a plain https URL, zero special cases
Android appSame as above (App Links)Same mechanism: the OS opens the https URL back into the app
CLI / desktop toolhttp://127.0.0.1:<port>/callbackThe program opens a temporary local port to receive the code (use 127.0.0.1 to get the variable port)

Custom schemes (myapp://callback) are not accepted: any app can claim the same scheme, so the authorization code could be intercepted by another app on the same device; Universal Links / App Links are verified by the OS against domain ownership and have no such weakness. This is the industry-standard practice of OAuth 2.1 / RFC 8252 (Apple, Google and GitHub do the same).

What if someone registers a malicious address? It does not affect you or your users. A redirect URI only decides where "that app's own authorization result" goes; the authorization code is bound to the client that started the flow and to its PKCE verifier, so another app cannot steal your code. The most a malicious developer can achieve is getting users to authorize "their own app" — and on the consent screen the user sees exactly that app's name and its charges, spending is bounded by the limits the user sets, and it can be revoked at any time.

Serverless (front-end only) apps

With or without your own server, the flow is exactly the same — the only difference is who keeps the token and who sends the requests. A front-end-only app (static site / SPA) can run the whole flow in the browser: PKCE never needed a client secret, and both the token endpoint and the AI endpoints allow CORS. Use the SDK's getUserInfo to obtain the user's sub / email.

The SDK works directly in the browser (it uses only WebCrypto and fetch) — the same functions as the server version:

import { createConnectUrl, handleCallback, AIPayClient } from '@coswic/aipay-sdk'

// Start authorization (for example a "Connect AI Pay" button): store { state, codeVerifier } in sessionStorage
const { url, state, codeVerifier } = await createConnectUrl(cfg)
sessionStorage.setItem('aipay_flow', JSON.stringify({ state, codeVerifier }))
location.href = url

// Callback page: handleCallback does "check error → verify state → exchange the token" in one step → stream (all in the browser)
const saved = JSON.parse(sessionStorage.getItem('aipay_flow'))
sessionStorage.removeItem('aipay_flow') // single-use: clear once consumed
const tokens = await handleCallback(cfg, location.href, saved)
const client = new AIPayClient({ baseUrl: AIPAY_API_URL, accessToken: tokens.accessToken })
const stream = await client.chat.completions.create({ model, messages, stream: true })
for await (const ev of stream) { /* assemble content from delta frames; the receipt frame comes last (fields: see the receipt table under "Calling models") */ }

You can also skip the SDK — fetch the same endpoints directly (authorization parameters: see the table above). SSE frame format: each frame is data: <JSON>; the normal sequence is delta frames → the receipt frame (with usage + aipay) → data: [DONE]. Errors appear as frames inside the 200 stream ({ "error": { code, message, request_id, details } }), after which the stream may end immediately or may still append a [DONE] — receiving a receipt frame proves settlement; the SDK throws on an error frame, which must be interpreted using its details.outcome / details.retryable and the endpoint contract. [DONE] is merely a transport marker and cannot by itself establish execution or settlement. Frame order and final-state rules are in the "Calling models" section.

Browser integration guidelines:

  • Do not request offline_access: a refresh token in the browser is a long-lived credential exposed to XSS. Access tokens live only 15 minutes; when one expires, let the user go through authorization again — repeat consent is skipped only when the return-visit checks described above pass.
  • Keep tokens in memory (variables); avoid persisting them in localStorage.
  • The worst case is bounded: a token can only spend within the limits the user set, and the user can revoke at any time — this is a platform design guarantee.
  • CORS is open only for the AI endpoints (/v1/chat/completions, /v1/models, /v1/embeddings, /v1/images) and the token endpoint; the Dashboard API is a cookie-session surface and is not open cross-origin.

Calling models

Available models and live prices: GET /v1/models (no Bearer token, OpenAI-compatible, CORS open) — replace model in the example below with an id whose availability.status is available.

import { AIPayClient } from '@coswic/aipay-sdk'

const client = new AIPayClient({
  baseUrl: 'https://ai-pay.coswic.ai',
  accessToken: tokens.accessToken,
})

const res = await client.chat.completions.create({
  model: 'openai/gpt-oss-20b',   // example; check GET /v1/models for the real list
  messages: [{ role: 'user', content: '…' }],
  max_tokens: 200,
})
res.choices[0].message.content
res.aipay.cost_uusd   // the actual charge for this request (integer µUSD string; $1 = 1,000,000 µUSD)
res.aipay.breakdown   // split between provider / platform (the app service fee field is retired: 0 on new requests)

// Streaming (SSE)
const stream = await client.chat.completions.create({ model, messages, stream: true })
for await (const ev of stream) {
  if (ev.type === 'delta') process.stdout.write(ev.content)
  if (ev.type === 'receipt') console.log('charged', ev.aipay.cost_uusd, 'µUSD')
}

Raw HTTP: POST /v1/chat/completions with the headers Authorization: Bearer <access token> and Idempotency-Key (required, 1–200 characters); the body is OpenAI-compatible but only a fixed set of fields is accepted, and the sampling parameters only conditionally (see below). Available models and rates: GET /v1/models (no Bearer token) — the price is frozen as a snapshot at request time, so later price changes never affect requests already sent.

Strict rules for the request body

Web search is not available: plugins, web_search_options and web_search tool types are rejected with 400 invalid_request. Appending :online does not enable it; that model ID is rejected with 400 model_not_allowed, before a hold or charge.

  • The body accepts model / messages / max_tokens (or its OpenAI alias max_completion_tokens; when both are given they must be equal) / n (only the value 1) / stream. The sampling parameters temperature (0–2), top_p (0–1), top_k (integer, 0 or above), min_p (0–1), top_a (0–1), frequency_penalty (−2 to 2), presence_penalty (−2 to 2), repetition_penalty (0–2), seed (integer; whether it makes output repeatable is up to the upstream provider), stop (one string, or up to 4 strings of 1–64 characters each) and logit_bias (up to 300 entries mapping a token id written as a decimal string to a bias from −100 to 100) are conditionally accepted: they are sent upstream only when every endpoint of the model's currently approved route declares support for them; otherwise the request is a 400 invalid_request before any charge, whose details.reason is model_parameter_unsupported (the verified facts for this route do not include the parameter) or model_parameter_unverified (the route has no verified parameter facts yet) and whose details.parameter names the first such field. At present only models published through the new listing review carry verified parameter facts; every other model returns model_parameter_unverified. None of these parameters changes what is charged; the output ceiling is still max_tokens. SDK 0.6.0 adds typed forwarding of these sampling parameters and uses max_tokens for the output limit. max_completion_tokens, n, stream_options and usage are HTTP compatibility fields, not official SDK ChatParams; extra JavaScript properties are not forwarded. Earlier published SDKs also omit the sampling parameters, so use HTTP directly until you have the required version. stream_options ({ "include_usage": boolean }, which many OpenAI-compatible SDKs add to every streamed call) and usage ({ "include": boolean }) are accepted for SDK compatibility but have no effect: the platform accounts usage on every call and returns it in the response and on the receipt whether or not you ask, so there is nothing for these flags to change, and neither field is forwarded upstream; any other shape (not an object, extra keys, a non-boolean flag) is still a 400 invalid_request whose details.parameter names the field. Fields the platform sets itself (user, provider, models, route, max_price) and features not offered yet (deferred_tools, reasoning / include_reasoning request parameters, prediction, transforms, plugins / web_search_options) are a 400 invalid_request whose message says why; any other field is a 400 invalid_request whose message reads unknown field and names it — nothing is silently ignored, because a parameter that did not take effect must not look as if it did.
  • response_format (structured output) is conditionally accepted too: {"type":"text"} is the default behaviour, accepted and not forwarded; {"type":"json_object"} requires every endpoint of the model's approved route to declare response_format; {"type":"json_schema","json_schema":{"name":…,"schema":{…},"strict":true}} requires them to declare structured_outputs. The boolean flag structured_outputs is also accepted: true too requires structured_outputs; false is the default behaviour, accepted and not forwarded. Without support the request is a 400 invalid_request before any charge, with the same details.reason values and details.parameter set to response_format or structured_outputs. json_schema.name is 1–64 letters, digits, _ or -; description is at most 4,096 characters; schema is forwarded as parsed, property order kept (JSON parsing itself moves integer-like property names first and normalizes number spelling, such as 1.0 to 1); the whole response_format is at most 100,000 bytes of JSON and 64 levels deep. Billing: the answer is still the string content (JSON text), charged by usage; the hold and the model's input ceiling count response_format as input: every non-ASCII character as its 6-byte escape, 2 more per JSON node, plus a fixed allowance for the prompt the provider injects itself (1,024 tokens each for json_schema, json_object or structured_outputs: true), so a request close to the input ceiling is refused sooner. A declined answer explains itself in choices[0].message.refusal, with content null when there is no text. These fields require SDK 0.6.0 or a direct HTTP call.
  • tools (function calling) is conditionally accepted too: only type: "function" (the web_search family and every other server tool, i.e. any type other than function, are a 400), at most 128 with unique names (1–64 letters, digits, _ or -), parameters a JSON Schema object forwarded as parsed; the whole set at most 200,000 bytes of JSON. Every endpoint of the model's approved route must declare tools, otherwise the request is a 400 invalid_request before any charge (details.parameter is tools). tool_choice ("none", "auto", "required" or a named function) and parallel_tool_calls (boolean) go together with tools: "auto" and parallel_tool_calls: true are the default behaviour, accepted and not forwarded; other values require tool_choice / parallel_tool_calls to be declared. messages can carry earlier calls and their results: an assistant message with tool_calls (its content may then be null) and role: "tool" messages with tool_call_id and string content; that history also requires tools to be declared. Billing: the hold and the input ceiling count the JSON of tools as input (non-ASCII as escaped bytes: 6 per UTF-16 unit, 12 for an emoji, 2 more per JSON node, 32 per tool, plus a fixed 1,024 tokens for the tool prompt the provider injects itself), the calls in the history by the same rule (parseable arguments add an allowance for their inner nodes and numbers) and tool message content by its JSON-escaped bytes; calls the model produces are billed as output tokens and stay under max_tokens. Calls in the response are in choices[0].message.tool_calls; with calls and no text, content is null (finish_reason as given upstream, usually tool_calls), a normal completion. These fields require SDK 0.6.0 or a direct HTTP call.
  • logprobs (boolean) and top_logprobs (an integer from 0 to 20; requires logprobs: true) are conditionally accepted too: only when the model declares support, otherwise the request is a 400 invalid_request before any charge (details.reason is model_parameter_unsupported or model_parameter_unverified, details.parameter is logprobs or top_logprobs). logprobs: false is the default behaviour, accepted and not forwarded; top_logprobs is forwarded as given (0 included); null is a 400, not treated as absent. The probability of each output token is in choices[0].logprobs.content (declined tokens in .refusal); each entry has token, logprob, bytes (the UTF-8 bytes of the token, possibly null) and top_logprobs (up to top_logprobs alternatives, each with token, logprob, bytes), shaped as in OpenAI; when streaming, they are in each delta frame's choices[0].logprobs; when the model returns none or an unreadable shape, the value is null and the request is settled normally. Billing: not charged separately; the hold and the output ceiling are unchanged. A non-streaming request allows at most 49,152 for max_tokens × (top_logprobs + 1) (with max_tokens after the clamp to the hard maximum); above that it is a 400 invalid_request before any charge (details.parameter is top_logprobs, or the output-limit field when it is absent) — lower one of them or use stream: true; streaming has no such limit. Within the limit, if a non-streaming response with its logprobs would be larger than 8 MiB (it takes a great many very long tokens), that response's logprobs is null and aipay.note says so; the content and the charge are unaffected — use stream: true to receive them. Non-streaming requests above 8,192 entries are processed a few at a time; when that capacity is full the request is a 503 service_overloaded (details.reason: 'large_logprobs_capacity') before any charge — retry with the same key or use stream: true. A replay with Replay-Key keeps logprobs only up to 1 MiB in total (judged by a conservative size estimate); above that the replayed logprobs is null and aipay.note says so; the first response is still complete. These fields require SDK 0.6.0 or a direct HTTP call.
  • modalities (output modalities) and audio (audio output options) are format-checked; audio output is available on approved models whose aipay.capabilities.outputs includes audio. Chat image output is not supported; use the dedicated images endpoint below. modalities is an array of "text", "image" and "audio", each at most once, that must include "text"; ["text"] is the default, accepted but not forwarded. Audio output takes modalities: ["text", "audio"], audio: { "voice": "alloy", "format": "pcm16" } (voice is a voice name of 1–64 letters, digits, _ or -, and which voices exist is up to the model; format is wav, aac, mp3, flac, opus or pcm16) and stream: true (audio output is streaming only); a missing piece or a wrong shape is a 400 invalid_request whose details.parameter names the field (audio also needs a modalities that includes "audio"). On a model without the requested output modality, the request is refused before a charge with 400 invalid_request, details.reason: 'modality_unsupported', details.modality and details.parameter: 'modalities'. On an audio-output model: the stream's delta chunks carry audio (data, a base64 piece of the audio; transcript, its text), it is charged by usage (audio output tokens at that model's audio output price, reserved in advance from the output ceiling), and a replay with Replay-Key joins the pieces into choices[0].message.audio (data as one base64 string, and transcript; content is null when there is no text) up to 8 MiB in total — above that the replay leaves audio out and aipay.note says so, while the first stream is still complete. Assistant messages sent back as history do not take audio; to continue the conversation, put the transcript in content. These fields require SDK 0.6.0 or a direct HTTP call.
  • messages: 1–1,000 entries; each entry accepts only role, content, for function calling tool_calls (assistant) and tool_call_id (tool), and for reasoning history reasoning, reasoning_content and reasoning_details (assistant only; see the reasoning paragraph below) (any extra field is also a 400). role is limited to system / user / assistant / tool; content is a non-empty string or an OpenAI-style content-part array (1–64 parts per message, at most 1,000 text parts across the whole request); on an assistant message with tool_calls or reasoning history it may be null, and on a tool message it is a string (possibly empty) — these two take strings only, not content-part arrays. Text parts are open ({ type: 'text', text: '…' }, without cache_control or prompt_cache_breakpoint), and so are image parts in user messages ({ type: 'image_url', image_url: { url: 'data:image/png;base64,…', detail? } }, conditions in the next item); audio and PDF parts additionally require the capabilities and combinations described below; video is not supported. Unsupported media are refused before execution and charging. The combined length depends on the model: models with aipay.input_token_cap (see below) are limited by that ceiling and by the request size limit; for models without it, all text, call ids / names / arguments and tool_call_id combined are limited to 100,000 characters; the whole request body is limited to 8 MiB (larger bodies get a 413).
  • Image input is conditional: choose a chat model whose aipay.capabilities.inputs includes image. Send user content parts such as {type:"image_url", image_url:{url:"data:image/png;base64,...", detail:"high"}}. Only base64 data URLs for PNG, JPEG, WebP or GIF are accepted; HTTPS URLs are refused with media_url_unsupported. Each decoded image is at most 5 MiB and 4,096 pixels per side, at most 8 images per request, and only static images are accepted. Total decoded media is at most 20 MiB (the 8 MiB request-body limit still applies first); some model families also limit the long-to-short side ratio to 100:1, returning media_too_large above it. The whole request is also bounded by the 8 MiB body limit; read capabilities.image_limits for the published limits. Malformed images return media_unreadable, animations media_animated, oversized images media_too_large, and models without a verified bound media_bound_unknown; an unsupported or unpriced modality returns modality_unsupported or modality_unpriced. Ordinary image-capable models reserve the conservative image-token bound from dimensions, model rules and detail, plus text and control fields (4 more per image part); some models normalize absent or auto detail to high. Models exposing aipay.image_input instead reserve their full approved input window; images do not consume the separate text estimate, while surrounding text and controls still must fit its ceiling. Actual billing uses measured input tokens. SDK 0.6.0 supports typed content parts; earlier SDKs need direct HTTP.
  • Audio input is separate from audio output. Choose a chat model exposing aipay.audio_input and capabilities.inputs containing audio; send one user part {type:"input_audio", input_audio:{data:"BASE64_WAV_OR_MP3", format:"wav"}} (format may also be mp3; data has no data-URL prefix). The one decoded clip is at most 5 MiB; WAV/MP3 headers and the published model limits are checked. Use text around the clip, with text output only: do not combine it with images or files. Other parameters remain subject to the model’s separate capability checks. Both streaming text and non-streaming text responses are supported. The hold reserves the full input window at the highest approved input-unit price, not an estimate from seconds or bytes; actual usage separates audio_in from the remaining in_tok. An unverified clip or unsupported combination is refused before execution.

Audio admission failures use 400 invalid_request with details.modality: "audio" and details.parameter: "messages"; reasons include audio_count, audio_role, audio_mixed_media, audio_content, audio_text_unbounded, input_text_cap and modality_unsupported. Earlier content-shape validation can reject the request first and name messages[i].content instead. Once an audio or native-PDF request has been sent, a non-success upstream HTTP response, including a 4xx, does not prove that preprocessing was free or no execution occurred: non-streaming returns 504 provider_timeout with outcome: "unknown"; streaming reports an error frame. Keep both original keys and do not automatically create a new request.

  • Native PDF input requires aipay.native_pdf_input and capabilities.inputs containing file on an available model. The production catalog checked on 2026-10-21 had no such model; do not enable a PDF picker without that catalog entry. When available, send exactly one user part {type:"file", file:{filename:"report.pdf", file_data:"data:application/pdf;base64,..."}}, at most 5 MiB decoded. The complete PDF must pass header, cross-reference and end-marker checks. URLs, file IDs, other media, tools and reasoning history cannot accompany it. Structured output remains conditional on the model and contributes to the text estimate. Processing is native, with no selectable OCR plugin or per-page charge. The hold reserves the full 128,000-token input window plus the output allowance; measured prompt plus completion tokens must stay within 128,000. Text around the PDF, and ordinary text/image requests on this model, use native_pdf_input.text_input_token_cap. Invalid native requests return native_pdf_unverified without a details.parameter; file input on an ordinary model remains modality_unsupported. Structural acceptance is not a guarantee that the model understands the PDF.
  • max_tokens: a positive integer. Above the model's aipay.hard_max_output_tokens it is silently clamped to the hard limit (no error; per-model values are in GET /v1/models); omitted = the model's aipay.default_max_output_tokens. For some chat models (text or image input; not models priced with cache or web search, nor audio, native PDF or full-context image input models) these two values and aipay.input_token_cap follow upstream down: they are lowered while two checks of the upstream endpoints the model's route reaches, at least ten minutes apart, both show an output limit, prompt limit, context or long-context price threshold too small for the reviewed values, and return to the reviewed values as soon as the latest check serves them; never above the reviewed values. While lowered, aipay.reviewed_limits lists the reviewed values. With a fixed reasoning effort, a lowered output limit also bounds the tokens available for reasoning.
  • stream: boolean; true on a model that does not support streaming returns 400 invalid_request before any money moves.
  • Optional header Replay-Key: 24–200 characters with at least 12 distinct characters; a malformed value returns 400 (see "Retry discipline and the two keys").

The receipt frame is sent only after settlement completes: seeing receipt in the stream = the money has been charged. An interrupted stream never charges twice — after a disconnect the request settles on what actually happened, and resending with the same pair of keys retrieves the outcome (see the next section).

The response's choices[0].finish_reason is stop, length, content_filter, or tool_calls; missing or other upstream values default to stop. Non-streaming responses, streaming receipts, and replay capsules use the same value. A reasoning model can spend its output budget on reasoning, returning empty content with length; complete, trustworthy upstream usage is still billed. With logprobs: true, choices[0] also carries logprobs (see above; the same shape in non-streaming responses and replay capsules, null on the streaming receipt frame).

This is a documented compatibility subset: chat responses do not include created or system_fingerprint. Top-level usage contains only prompt_tokens, completion_tokens and total_tokens, without *_tokens_details or provider cost. The priced breakdown is in aipay.usage; on a stream, usage and finish_reason arrive together in the final receipt frame. Do not assume another provider’s SDK or every OpenAI field has been validated.

A reasoning model's reasoning is in choices[0].message.reasoning (a string; null when there are only reasoning_details) and choices[0].message.reasoning_details (an array; each item has a type of reasoning.text, reasoning.summary or reasoning.encrypted, and possibly id, format and index; format is a format string to send back as is); without reasoning from the model neither field is present, and when the visible text is empty but reasoning came back, content is null. When streaming, the same fields are in each delta chunk (before the text of the same chunk) and concatenate in order. Reasoning tokens are already part of completion_tokens and are billed as output. In a multi-turn conversation (especially with function calls) you can put the previous assistant message back unchanged, reasoning included: plain-text reasoning (reasoning, and reasoning.text and reasoning.summary items without a signature or an id) is forwarded to the model as sent. Opaque reasoning items (reasoning.encrypted, or any item with a non-empty signature or a non-empty id) are accepted but not forwarded for now: a message with such an item is sent without its reasoning fields (an empty content instead of null when it has no function calls), only what is sent counts toward the input estimate, and aipay.note says so — how much input such content uses once sent back cannot be verified in advance yet. On a model without verified support for reasoning history, reasoning fields are accepted but not forwarded in the same way. When reasoning is not forwarded, the model does not see its earlier reasoning on that turn; a model that needs it to continue may not continue that turn. reasoning_content is an alias of reasoning, so send only one of them; only assistant messages may carry these fields (any other role gets a 400), and what you send back counts toward the input estimate as its JSON-escaped bytes (plus 16 per message). When the reasoning has a shape that cannot be read, that response comes without it and is settled normally; when a non-streaming response with its reasoning would be larger than 8 MiB, that response comes without the reasoning and aipay.note says so — the content and the charge are unaffected; use stream: true to receive it. A replay with Replay-Key keeps reasoning only up to 1 MiB in total; above that the replay leaves both fields out and aipay.note says so. Reasoning text is not stored in usage records. Valid reasoning chunks keep the stream's first-event and idle timers alive, but never extend its total deadline. Heartbeats and empty chunks do not extend these timers. An interruption after reasoning is still an unknown outcome even without visible text; query the outcome with the same pair of keys. Providers that emit no progress or stay silent for too long can still time out. Execution limits deduct time already spent opening the hold and waiting for dispatch, reserving time for settlement; follow the response retryable/outcome flags.

Some models expose aipay.input_token_cap in /v1/models. The conservative estimate is the total UTF-8 byte length of the message text plus 8 per message (plus 4 per text part in a content-part array, and 4 per image part plus that image's bound; function-call history, tool messages, assistant reasoning history and control fields such as response_format and tools are counted separately by their rules above). Each piece of text (strings inside JSON included) counts as the largest byte length among its original form and its two Unicode normalization forms (NFC and NFKC); for ordinary text the three are the same. It must be below the ceiling; reaching it returns 400 invalid_request before reserving funds. Models with this ceiling are not subject to the 100,000-character combined limit; their input is bounded by this ceiling and the 8 MiB request body limit. Because the estimate counts UTF-8 bytes, the tokens you can actually send are fewer than the ceiling (roughly a quarter of it for English text). AI Pay may configure a model's reasoning effort; client-supplied reasoning / include_reasoning / reasoning_effort request parameters and timeout parameters remain unsupported (assistant reasoning history: see above). In the current server, reasoning_effort is rejected as an unknown field with 400 invalid_request, not a supported request setting.

The default first-event and idle waits are 120 seconds (upstream keep-alives count), and non-streaming waits 60 seconds by default; approved models may use a longer non-streaming waiting preference, bounded by 300 seconds. These are maximum preferences, not guaranteed execution times: operator limits, the stream total deadline and the hold's settlement reserve may shorten them. Models without settings keep the existing defaults, and prolonged silence can still time out. A reported non-default upstream service tier is recorded as a route incident; user charges still use the request's frozen model prices.

SSE frame order and final states

  • Normal sequence: delta frames (object: 'chat.completion.chunk', text in choices[0].delta.content, function-call pieces in choices[0].delta.tool_calls, shaped as in OpenAI: a call's first piece carries index, id, type and function.name, later pieces only index and what is new, usually function.arguments; when the model declines, pieces of its explanation in choices[0].delta.refusal; with logprobs: true every delta frame also carries choices[0].logprobs, that frame's probabilities (null when there are none; a frame with only probabilities and an empty content can appear)) → the receipt frame (also a chunk, with the completion reason above, usage + aipay) → data: [DONE]. Without visible text, the receipt can be the first frame.
  • Keep-alive comments: while the upstream is still working (reasoning, queueing), the stream may contain SSE comment lines : keep-alive (about one every 15 seconds); ignore them per the SSE specification — the official SDK and OpenAI-compatible SDKs already do.
  • Error frames: an error that happens after HTTP 200 was already sent and the stream is open is expressed as one frame data: {"error":{"code","message","request_id","details"}}, with the same meaning as in the error-code table: provider_unavailable (charged: false; retryable: true = the upstream never ran, retry with the same key; retryable: false = the upstream ran but failed, retry with a new key, or the model cannot take this request and retrying will not help), rate_limit_exceeded (charged: false, retryable: true: the model is temporarily rate limited and nothing ran; wait at least retry_after seconds when given (at most 60), then retry with the same key), content_policy (charged: false, retryable: false: the content was refused by the content policy for this model; revise the input instead of resending it), provider_timeout (retryable: true when execution budget expired before dispatch and release was confirmed; reuse the same key), or provider_timeout / usage_unknown (outcome: 'unknown' — resend with the same pair of keys to learn the outcome), internal_error. The SDK throws the corresponding exception when it receives an error frame and does not retry that frame automatically. Save requestKeysOf(error); if the flags permit retry, resend the same payload with the same keys yourself.
  • [DONE] is not a financial final state: after an upstream failure or timeout mid-stream the stream simply ends, without [DONE]; whereas after a usage_unknown error frame ("content was sent but could not be priced") a [DONE] is still appended. If an error frame was parsed, follow its details.retryable/details.outcome first (for example, confirmed release before execution permits retry with the same key). Otherwise, a receipt frame received = settled; a stream that ends without a receipt frame (with or without [DONE]) = outcome unknown — resend with the same pair of keys to learn the outcome (the SDK raises StreamTruncatedError).
  • A streaming request that fails before the SSE opens (401 / 403 / 422 / 429 / 503…) gets the ordinary JSON error envelope; resending an already-settled streaming request with the same key also returns a one-off JSON body (the receipt, or the original text when a Replay-Key was used) — the SSE is not replayed.

Receipt fields (aipay; the same object in non-streaming responses and in the streaming receipt frame)

Field Meaning
usage_event_id / request_id The id of this usage event (searchable under the Console "Requests" tab; the chatcmpl_ suffix of the response id is the same value) / the request_id of this HTTP request.
hold_id The credit-reservation reference for this request — the id of the per-request hold; on the credit-lease fast path it is the lease ticket id (same uuid shape, same meaning).
amount_max_uusd The hold ceiling frozen at request time (the estimate cap). The actual charge is always ≤ it. Normally computed from the input estimate and max_tokens; for a model whose upstream has returned more output than max_tokens, the hold goes higher within the per-request limit and the available balance (up to the endpoint's declared maximum output), and the unused part is released at settlement.
total_charged_uusd / cost_uusd The total actual charge (identical; cost_uusd is a compatibility alias).
reference_base_uusd / aipay_markup_uusd / model_charge_uusd / app_service_fee_uusd / usage_tax_uusd The actually collected amount per component: the reference base (frozen reference unit price × usage) / the applicable platform markup / the model charge (= the sum of the previous two, i.e. the catalog price) / the app service fee (retired: 0 on new requests; requests frozen before the retirement keep their value) / usage tax (currently always 0). model_charge_uusd = reference_base_uusd + aipay_markup_uusd; total_charged_uusd = model_charge_uusd + app_service_fee_uusd + usage_tax_uusd. Do not add the model charge and its components twice.
breakdown.provider_cost_uusd / platform_fee_uusd / app_margin_uusd Three compatibility fields, equal to reference_base_uusd / aipay_markup_uusd / app_service_fee_uusd respectively. Note that provider_cost_uusd is the reference base used for pricing, not the upstream's actual cost for this request (the actual cost may differ).
usage Billable units keyed by the frozen tariff, for example in_tok, out_tok, audio_in, audio_out or image_count. When audio is itemized, in_tok / out_tok are the remaining tokens after the itemized subset, not the top-level prompt/completion totals again; do not count a subset twice.
settlement_state / clamped Normally 'settled' / false. If the amount computed from actual usage exceeds the hold ceiling amount_max_uusd, only the ceiling is charged: clamped: true, settlement_state: 'settled_capped_loss', plus computed (the components and total_uusd that were contractually due) and component_shortfall (the uncollected difference per component, total_uusd being the total; the user is not charged the shortfall afterwards. Uncollected reference-base and platform-markup amounts are recorded as platform-absorbed loss. Uncollected App fees are borne by the developer and do not create a payable for that portion; the platform does not absorb the entire shortfall).
replayed / note replayed: true = this is a receipt / original text retrieved by resending with the same key, not a new execution. note appears only in special situations (receipt-only replay, 0 charge after a hold expired, logprobs over the replay allowance, logprobs dropped from an oversized non-streaming response, etc.).
pricing_policy / pricing_semantics_version / markup_bps / catalog_pricing_version / price_snapshot_hash / reference_fetched_at / reference_valid_until / reference_prices_per_million_uusd / retail_prices_per_million_uusd Traceability fields of the frozen price snapshot — this charge can be recomputed from the receipt alone even after the old catalog is retired.

Generate images

Use POST /v1/images with an available aipay.operation="image_generation" model and ai.chat.create wallet.charge scopes under current consent. This is a dedicated endpoint; it is not /v1/images/generations, and asking chat for modalities: ["text","image"] does not invoke it. Read aipay.image_generation for the selected model's limits and allowed options.

curl "https://ai-pay.coswic.ai/v1/images" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: ${IMAGE_REQUEST_KEY}" \
  -H "Replay-Key: ${IMAGE_REPLAY_KEY}" \
  -d '{"model":"MODEL_ID","prompt":"A small blue house","n":1}'

Set MODEL_ID from the current catalog, ACCESS_TOKEN from the user's normal authorization, a new UUID as IMAGE_REQUEST_KEY, and a cryptographically random IMAGE_REPLAY_KEY (24–200 characters, at least 12 distinct). Keep both keys with the exact payload securely; never commit them. Idempotency-Key is 1–200 UTF-8 bytes on this endpoint. SDK 0.6.0 provides client.images.generate(...), automatically generating both keys even when chat auto-replay is off; it sends one POST, without automatic retries or count reduction.

  • prompt is non-empty, at most 16 KiB UTF-8 (the model may allow less). The whole POST /v1/images JSON body is limited to 128 KiB; larger bodies receive 413. n is a maximum of 1–10 globally and may be lower per model; the hold reserves that many images, while billing charges complete images actually returned. Exceeding the model's maximum is a 400, with no automatic reduction.
  • aspect_ratio and output_format must be in that model's published arrays. An empty array means omit the option; it does not mean every value is supported. Do not guess output_format from the image MIME type. No reference images, editing, URLs, streaming or variable-price tiers are supported.
  • The response has data: [{ b64_json, media_type }] for base64 images and their media types, plus aipay with the authoritative receipt. Each decoded image is at most 4 MiB and the total at most 12 MiB. Treat SVG as untrusted image data, never executable markup. Use the returned media type rather than a hard-coded file extension.
  • New image generation requires Replay-Key; a missing key is a 400 invalid_request without a reason field. Successful image ciphertext is retained permanently: same payload plus both keys retrieves the original image result; without the right Replay-Key, history returns the receipt and empty data. A settled request is never generated or charged again. Each API process handles one image request or replay at a time; a second returns 429 without retryable details or Retry-After in the current implementation. Back off with the original keys. A 5xx without retryable: true is not permission to retry automatically; unknown outcomes must keep the original keys.

Connection and error troubleshooting

Use the API and authorization endpoints provided in this guide for normal sign-in, app registration, and OAuth authorization. The browser, CLI, and application server each need to reach the relevant HTTPS endpoints.

  • Browsers and front-end-only apps: Use PKCE, token exchange, and getUserInfo. Check the API and authorization endpoints and the callback URL registered in the Console.
  • CLI and application servers: Check the configured endpoints and HTTPS connectivity, then use OAuth tokens for API calls. With remote aipay login --device, both the CLI and the browser approving sign-in need to reach the service.
  • Model catalog and prices: GET /v1/models and the price page provide the live list and prices. The catalog needs no Bearer token; AI requests still require user authorization and available credits.
  • An empty 404 or connection failure: Check the full URL, HTTP method, and selected environment, then DNS and TLS connectivity. An empty 404 alone cannot identify the cause. If the response includes an error code, follow "Error codes"; note the HTTP status and any available request_id for tracing.

Normal account, OAuth authorization, revocation, budget, and charge checks still apply.

Model catalog and pricing

Catalog today: text chat, image input, audio input/output and dedicated image generation are supported on the models approved for each operation. The live list, prices and per-model capabilities come from GET /v1/models (no Bearer token); the human-readable page is https://ai-pay.coswic.ai/models?lang=en. Do not hard-code model IDs, counts, prices or capability lists. PDF and embeddings require their own available catalog entries; the production catalog checked on 2026-10-21 had none. Web search, video, external image/file URLs and image output inside chat are not supported.

Select a model for the request

  1. Match aipay.operation: absent means chat; image_generation is for POST /v1/images; embeddings is for POST /v1/embeddings. Never send an image-generation or embedding model to chat, including a text-only smoke test.
  2. Require aipay.availability.status === "available" and reason === null, and respect checked_at / valid_until. Re-fetch before a new request when the observation is stale. This is permission to accept a request at current pricing, not an upstream-health guarantee.
  3. For chat, match aipay.capabilities.inputs (text, image, audio, file) and outputs (text, audio) to the request. image_limits gives resource bounds; audio_output.stream_required is true. Its formats are the gateway's accepted formats, not proof that every provider voice/format combination works; voices: null means there is no verified voice list. Do not invent supported voices.
  4. capabilities.parameters declares tools, tool_choice, parallel_tool_calls, response_format_json_object, response_format_json_schema, logprobs and top_logprobs. A true value means the model-capability check accepts that feature; payload limits, valid combinations, authorization, budget, price freshness and provider outcomes still apply. It does not promise every value or a combination of independently supported modalities. The individual sampling parameters remain conditional on the model's verified parameter facts; handle model_parameter_unsupported / model_parameter_unverified.
  5. capabilities.reasoning.returned_when_upstream_provides means returned reasoning is passed through when present, not that the model always reasons. fixed_effort is a configured model property, not a request option. aipay.upstream_modalities records provider-declared inputs/outputs and does not grant AI Pay support. aipay.upstream_quantization is the precision of the upstream endpoints the model's route can reach, from the latest price observation (for example fp8, fp4, bf16; unknown means the upstream does not say). It follows upstream renames and precision changes; null means not known yet. aipay.upstream_zero_data_retention says whether the upstream's zero-data-retention (ZDR) list includes every upstream endpoint the model's route can reach (true: all are listed; false: at least one is not; null: not known yet), from the same price observation, using a copy of the list read within the two hours before it. It describes the upstream's list, not an AI Pay guarantee: data handling follows each upstream provider's policy, AI Pay's own content retention is described under idempotency and replay, and when a listed endpoint is withdrawn the route may move to one that is not listed, which this field then shows. Older servers may omit capabilities; absence is unverified, never permission to enable a feature.

How one request is priced

The formula below applies to reference_markup_v1. The catalog can also contain legacy policies; use each model’s policy and retail prices instead of assuming 12%. The consent screen discloses platform rate ceilings; unaccepted pricing policies or platform rates above accepted ceilings require the user’s consent again.

catalog price  = ceil( Σ(billable units × retail unit price) ÷ 1,000,000 )      ← integer µUSD, rounded up once
retail unit price = ceil( reference unit price × (10000 + markup_bps) ÷ 10000 ) ← v3 policy
what the user pays = catalog price (apps add no per-request service fee or usage surcharge)
  • The reference unit price (reference_prices_per_million_uusd) is the billing reference frozen at publication: the highest of qualified upstream quotes, any verified cost floor and the previous reference. It can therefore exceed a provider quote. The catalog’s reference_basis identifies an upstream route reference or a cost floor; neither represents the actual provider cost of each request. The user is charged using the request’s frozen retail prices.
  • The platform markup follows each model’s markup_bps; for example, 1200 means 12%. It is already included in the v3 retail price. Legacy fee and margin components are also included in their retail price and must not be added again.
  • Rounding happens once (on the sum over all billing dimensions), not once per dimension.

Example (assuming 12% markup, not a live quote; openai/gpt-oss-20b, reference price in $0.03 / M, out $0.14 / M → retail in $0.0336 / M, out $0.1568 / M): one request with 1,000 input + 500 output tokens

reference cost = (1000 × 30000 + 500 × 140000) ÷ 1e6 = 100 µUSD
catalog price  = (1000 × 33600 + 500 × 156800) ÷ 1e6 = 112 µUSD   ← this is what the user pays
                                    of which AI Pay markup = 12 µUSD

The receipt (res.aipay.breakdown) splits this per component so you can trace it back to this formula.

The *_per_million_uusd maps are integer µUSD per million of the named unit. in_tok / out_tok count text-token remainders; audio_in / audio_out count audio tokens; image_count counts complete images. For a per-image USD price, divide the image_count map value by 1,000,000 twice (million units, then µUSD to USD). Image generation charges actual returned images, with n as the maximum reserved count. Full-window image/audio/PDF holds can be much larger than a short text request; a 422 budget refusal does not mean the quoted unit price changed.

Price freezing and freshness

  • The price is frozen as a snapshot at the moment the hold is created; later price changes do not affect requests already sent.
  • Every model's price has a freshness deadline (valid_until). AI Pay checks prices automatically and extends that deadline at the existing approved price when renewal conditions are met. Some text-priced models can keep selling when the approved price is still supportable, or when upstream data is temporarily unreadable and the renewal conditions still hold. This does not cover every model or guarantee that upstream requests will succeed. Once the price actually expires, new requests for that model are blocked with 503 pricing_stale; other models are unaffected. Always check aipay.availability when selecting a model, rather than relying on its presence in the catalog.
  • Once automatic repricing is enabled, retail prices are conservative: provider price drops do not automatically lower them; a unit rate rises only when needed to cover verified complete costs, with the same markup. This applies to eligible text, image input and generation, audio input/output, embedding and PDF models within their approved capabilities and quantity rules. Repricing does not enable new capabilities. If an endpoint disappears, a replacement must meet the existing conditions and pass cost verification; other non-price changes still require trusted review. Publication updates the model page and GET /v1/models to the same new version and effective time. Only subsequently created holds use the new price; old versions remain available for receipt reconciliation.

Pricing fields in GET /v1/models

Field Meaning
aipay.pricing_policy reference_markup_v1 = the fields below are in effect
aipay.reference_prices_per_million_uusd Reference unit price frozen at publication, including any applicable cost floor; actual request costs may differ
aipay.reference_basis aipay_verified_route_ceiling for an upstream route reference; aipay_verified_cost_floor for a reference including a verified cost floor
aipay.markup_bps Markup in basis points; 1200 = +12%
aipay.retail_prices_per_million_uusd Retail unit price = the unit price the user is actually billed at
aipay.availability {status, reason, checked_at}: local catalog permission for a new request, not an upstream health guarantee. available has reason: null; unavailable gives pricing_stale, model_price_unavailable, or pricing_unverified.
aipay.valid_until Freshness deadline of this price (once expired, new requests are blocked)
aipay.price_locked_at_request true = frozen at request time; price changes are not retroactive
aipay.default_max_output_tokens / hard_max_output_tokens The default when max_tokens is omitted / the hard limit (some chat models follow upstream down, see max_tokens; never above the reviewed value)
aipay.operation / capabilities / upstream_modalities Operation, AI Pay accepted chat capabilities, and separately provider-declared modalities; see selection rules above.
aipay.upstream_quantization Precision of the endpoints the route can reach, from the latest price observation; follows upstream renames and precision changes (unknown: not stated by the upstream; null: not known yet).
aipay.upstream_zero_data_retention Whether the upstream's zero-data-retention list includes every endpoint the route can reach, from the latest price observation, which used a copy of the list read within the two hours before it (true / false; null: not known yet); the upstream's list, not an AI Pay guarantee: data handling follows the upstream provider's policy.
aipay.input_token_cap Ordinary chat: exclusive conservative-input ceiling. Full-window audio: inclusive reserved input pool. Embeddings: inclusive token ceiling, with a separate byte limit. Image generation: zero. Native PDF models use native_pdf_input.text_input_token_cap for ordinary text/image input.
aipay.reviewed_limits Present only while the limits are lowered for upstream: the reviewed {default_max_output_tokens, hard_max_output_tokens, input_token_cap}; gone once upstream serves them again.
aipay.image_input / audio_input / native_pdf_input / image_generation / embedding Operation-specific limits and pricing behavior; existence does not override availability.

fee_bps / margin_bps are legacy fields, always 0 for v3 models; do not derive prices from them.

Unavailable models remain listed. Select only availability.status === "available"; a model appearing in the list is not sufficient. checked_at is this response’s evaluation time, using the same catalog cache as chat (normally 30 seconds), not a provider probe time. Responses require revalidation (Cache-Control: no-cache); expiry is rechecked even while the catalog object is cached. Missing or invalid pricing observations return pricing_unverified; unverified v3 pricing fields may be omitted, and new requests fail with HTTP 503 before a charge.

Retry discipline and the two keys

The core of the money semantics: a lost response must never turn into a second charge. The SDK has these conventions built in (raw HTTP should do the same):

  • Idempotency-Key (required, 1–200 characters; the SDK generates a UUID): keep the original key when recovering a lost response. A settled request with the same key and payload is replayed without another execution or charge. A still-occupied key with a different payload returns 409 idempotency_conflict. Uniqueness is scoped to your app (all users under one client_id share one namespace) — use UUIDs, not sequence numbers that could collide. A refusal before a hold is created does not take the key. Once a hold exists, a confirmed no-execution failure can release the key even when retryable is false (for example content-policy refusal); settled, in-flight and unknown-outcome keys stay occupied. Reusing a released key can execute a corrected request; replay is guaranteed for settled results, not for every failure.
  • Replay-Key for chat (optional; not generated by the SDK by default — enable with new AIPayClient({ autoReplayKey: true }) or pass replayKey per request): with it, the original response text is encrypted and stored atomically with the settlement — resending the same payload with the same pair of keys within the validity window (15 minutes) retrieves the original text (repeatable within the window — it is not consumed on first read); without it you only get the receipt (how much was charged, how much usage; choices is empty). Format: 24–200 characters with at least 12 distinct characters (the SDK's generateReplayKey() complies). It is off by default because every key costs the server one deliberately expensive key derivation — an app that stores its own responses does not need it.
  • Retry on the flags, not on the HTTP status: chat HTTP requests in the SDK (0.5.0 and later) auto-retry only six error-code situations — provider_unavailable / provider_timeout / catalog_unavailable / service_overloaded / service_unavailable / ledger_unavailable with details.retryable: true (the flag permits retry under that endpoint contract; it is not independent proof of execution, settlement or key retention; a 504 timeout during the estimate phase counts too; the SDK waits the Retry-After the server sends when there is one; SDK 0.4.x did not auto-retry the last two), 429, and network-layer errors — exponential backoff with the same pair of keys (the original request plus at most 2 retries by default; the separate 422 shrink attempt below is additional). pricing_stale / model_price_unavailable / pricing_unverified may be flagged retryable: true; a rejected pricing snapshot can be retryable: false, and older non-chat endpoints may omit details. The SDK does not auto-retry them (it throws a plain AIPayApiError) — whether to wait, how long, or whether to switch models is your decision. details.outcome: 'unknown' (e.g. usage_unknown, a timed-out 504) is never auto-retried — unknown outcome = the money may already be settled, and firing again with a new key would be a second AI action; resending with the same pair of keys to learn the outcome is the correct move.
  • 422 budget_exceeded: max_affordable_uusd is a micro-USD amount, not a token count. Only with shrinkOnBudgetExceeded enabled (the default), a positive amount and an available output-token price does the SDK convert 95% of that amount through the price into max_tokens. It makes at most one additional attempt with new keys if the result is at least 1 token and below the known current limit (if the current limit cannot be obtained, a positive result can still trigger this attempt). If pricing is unavailable or no suitable limit can be calculated, it throws the original error; shrinking does not guarantee success. A 422 happens before a hold and does not take the old key; new keys are the SDK convention for the smaller payload.

Embeddings have no automatic SDK retries; a Replay-Key is optional and preserves vectors for 15 minutes while receipts remain permanent. Image generation also sends one POST without automatic retries; a new image request requires a Replay-Key and successful image ciphertext is kept permanently. An image provider_error may follow a confirmed rejection/no dispatch that releases the key, or an executed result absorbed at zero charge that retains it. The code alone does not establish which state applies; a released key can execute again even when retryable is false. Preserve unknown-outcome keys and inspect the original result before any new intent.

For an unknown or potentially unknown result, check AIPayApiError.outcomeUnknown, StreamTruncatedError, and non-API errors carrying request keys (for example a fetch failure, or a body-read / JSON-parse failure after HTTP 200). A null result from requestKeysOf(e) does not prove no execution. This non-streaming example disables automatic shrinking so that the saved payload matches what was sent; for streaming, include the for await consumption loop in the same error-handling scope. Every error is rethrown to the caller; the catch block does not issue another POST. A same-key POST is not read-only: it replays a settled result but may execute if the first request never arrived or the key was released. Recovery requires an explicit choice by the user or caller.

import {
  AIPayClient, AIPayApiError, StreamTruncatedError, requestKeysOf, type ChatParams,
} from '@coswic/aipay-sdk'

// Disable shrinking so the SDK cannot replace the payload and keys behind this snapshot.
const client = new AIPayClient({
  baseUrl: 'https://ai-pay.coswic.ai', accessToken, shrinkOnBudgetExceeded: false,
})
// Save a snapshot before sending; persist recoveryRequest according to your app policy.
const originalParams: ChatParams = structuredClone(params)
let recoveryRequest: ChatParams | undefined

try {
  await client.chat.completions.create(originalParams)
} catch (e) {
  const keys = requestKeysOf(e)
  const potentiallyUnknown =
    (e instanceof AIPayApiError && e.outcomeUnknown) ||
    e instanceof StreamTruncatedError ||
    (!(e instanceof AIPayApiError) && keys !== null)
  if (potentiallyUnknown && keys) {
    // Preserve the available original keys; replayKey exists only if supplied or auto-generated.
    recoveryRequest = {
      ...originalParams,
      idempotencyKey: keys.idempotencyKey,
      ...(keys.replayKey ? { replayKey: keys.replayKey } : {}),
    }
  }
  throw e
}

// Later, only after the user or caller explicitly chooses recovery:
// if (recoveryRequest) await client.chat.completions.create(recoveryRequest)
// A settled request returns its receipt; original text also needs a Replay-Key within 15 minutes.

Error codes

Errors always use the uniform envelope { "error": { "code", "message", "request_id", "details" } } — branch on code; never parse the message text.

HTTP code Meaning / what to do
400 invalid_request Malformed request — fix the parameters, do not retry: an unknown or refused field (the chat body accepts only model / messages / max_tokens or max_completion_tokens / n / stream, plus the conditional sampling parameters, structured-output and function-calling fields listed under "Calling models" and, in the shape given there, the no-effect compatibility fields stream_options / usage; a field the platform sets itself or a feature not offered yet gets a message that says why), a sampling parameter of the wrong type or out of range (no details.reason), a sampling parameter the model cannot use (details.reason: 'model_parameter_unverified' or 'model_parameter_unsupported'), max_tokens and max_completion_tokens both given but not equal, n other than 1, logprobs not a boolean, top_logprobs not an integer from 0 to 20 or without logprobs: true, max_tokens × (top_logprobs + 1) over 49,152 on a non-streaming request, content that is neither a non-empty string nor a valid content-part array, a non-text part that is not accepted (video, or audio/PDF/images on a model that does not take them: details.reason: 'modality_unsupported'; images can also get 'modality_unpriced', 'media_bound_unknown', 'media_url_unsupported', 'media_too_large', 'media_unreadable' or 'media_animated', see "Calling models"; all with details.modality, and details.parameter naming the part, except audio admission may name messages), modalities / audio of the wrong shape or audio asked for without stream: true, audio output on a model without that capability, or any chat image output ( details.reason: 'modality_unsupported', plus details.modality, with details.parameter modalities), a part with cache_control or prompt_cache_breakpoint ('prompt_cache_unpriced'), an invalid role, max_tokens not a positive integer, a missing Idempotency-Key (details.reason: 'missing_idempotency_key'), a malformed Replay-Key ('invalid_replay_key'), or stream: true on a model that does not support streaming. 'modality_unsupported' has the same shape on the input and the output side — details is { reason: 'modality_unsupported', modality, parameter } in both — so tell them apart by details.parameter: for ordinary image/file/video admission it is the part position (messages[i].content[j]); audio admission can instead name messages as described above; for an output modality that is not offered it is modalities; details.modality: 'image' can therefore mean a refused image input or image output that was asked for. The message names the field; for unknown or refused fields, the sampling parameters, max_tokens / max_completion_tokens, n, logprobs / top_logprobs and modalities / audio, details.parameter names it as well; when content fails validation (including 'prompt_cache_unpriced'), details.parameter is messages[i].content (field errors on tool messages and on assistant messages with tool_calls are located by the message only); for part-level errors the message gives the exact position.
400 model_not_allowed The model is not on the allow-list (typo in the id, or retired) — look up GET /v1/models and change the id; do not retry.
400 return_url_not_registered The checkout's return_url is not exactly equal to any redirect URI registered for this app (one extra query parameter, one different character or a case difference all count; the system test callback does not count) — fix the URL or register it first; do not retry.
401 unauthorized Token missing / expired (15 minutes) — refresh, then run once more. For POST /v1/chat/completions only, requests that declare a Content-Length over 320 KiB and up to 8 MiB have their token checked first, before the body is read: a missing or invalid token is a 401 straight away (for example also when Idempotency-Key is missing, instead of the 400). A declared length over 8 MiB is a 413 without a token check; a body without Content-Length is counted while it is read and gets a 411 once it passes 320 KiB.
402 insufficient_balance The user's available credit is below the hold this request needs (details carry shortfall_uusd) — nothing was sent or charged, and it is not your error; tell the user their AI credit is too low. Production does not accept top-ups at the moment, so do not send users to top up.
402 subscription_ai_allowance_exhausted Only for users subscribed to your App: this period's subscription AI allowance cannot cover the request (details carry subscription_id, remaining_uusd, resumes_at = when the next period starts, left out when already past; when the subscription is set to stop at the period end, it is when the subscription ends and AI goes back to per-use charging) — nothing was sent, and it is never charged to the wallet instead; tell the user this period's AI allowance is used up and when it comes back. They can change the next period's allowance in AI Pay's "My subscriptions". Live's error event carries the same code and details.
402 subscription_past_due Only for users subscribed to your App: the renewal has not succeeded yet (grace period; details carry subscription_id, grace_until, left out when already past) — this App's AI is paused until it does, and it is never charged to the wallet instead; the rest of your App works as usual. Live's error event does the same.
403 authorization_revoked / authorization_paused The user revoked / paused the authorization — respect it; after revocation the authorization flow must run again.
403 platform_pricing_changed The platform pricing policy or rate exceeds the user’s accepted scope. Ask the user to authorize again; do not retry automatically.
403 consent_terms_changed AI Pay's consent document was updated and the user has not re-consented — guide the user to authorize again (the consent screen appears automatically at the next sign-in).
403 region_required The account has no declared region or has not accepted the current Terms of Service (returned by the developer API and the self-service API) — from the CLI run aipay region set --country <CC> --accept-terms; the dashboard opens the setup gate automatically. An app's AI requests can return it too (details.reason: 'region_required'): the country/region on the user's account must be declared again, and nothing ran or was charged — send the user to AI Pay to update their country/region, or ask them to authorize again (the consent screen asks them to choose one).
403 authorization_circuit_broken / forbidden Authorization circuit-broken (wait for the platform to recover) / insufficient permission: the app, user or wallet is not active, or a scope is missing (details.reason: 'scope_missing', details.scope names the missing one — chat requires ai.chat.create, embeddings require ai.embeddings.create, and both require wallet.charge).
403 content_policy (details.retryable: false) The request content was refused by the content policy for this model — nothing ran, 0 charge. The same input will be refused again: revise it instead of retrying (the SDK does not auto-retry this one).
403 commerce_disabled Checkouts: one-time purchases are not open in this environment (COMMERCE_PURCHASES_ENABLED is off, details.reason: 'purchases_disabled'), or the product is a subscription plan and subscriptions are not open in this environment (COMMERCE_SUBSCRIPTIONS_ENABLED is off, details.reason: 'subscriptions_unavailable') — no checkout was opened and nothing was charged. For the same code from the developer console and developer API, see the table at the end of the "Charging users" chapter.
403 app_inactive The app is not active when the checkout is opened (suspended, being deleted, or without an owner), or the app's developer has not accepted the current Developer Sales Agreement (details.reason: 'developer_terms_outdated') — no checkout was opened.
403 forbidden (checkouts) The token lacks wallet.charge (details.reason: 'scope_missing', details.scope: 'wallet.charge'), or the user's account is not active — no checkout was opened.
404 product_not_found The product of the checkout does not exist or does not belong to this app.
404 resource_not_found No such checkout: it does not exist, or it belongs to another app or another user (the answer is the same either way).
409 idempotency_conflict A conflict on the same Idempotency-Key; branch on details.reason: payload_mismatch = same key, different payload → use a new key for the new intent; in_flight = the previous request with this key is still running → wait for it to finish, then resend with the same key; unknown_outcome = the previous outcome is unknown (the hold expired and was reclaimed; awaiting reconciliation) → do not fire again with a new key; reclaimed_before_dispatch = dispatch was not claimed (authorization, catalog or request state may have changed), without confirmation that the hold expired or was released → query with the same key; fresh execution is not guaranteed.
409 product_inactive The product is a draft, retired, or has no price yet — activate it in the Console before opening checkouts.
411 / 413 invalid_request For POST /v1/chat/completions: over 8 MiB is a 413; over 320 KiB without a Content-Length header is a 411. POST /v1/images has a 128 KiB body limit; POST /v1/embeddings has a 64 KiB body limit (413 above either limit). Nothing was processed or charged — shrink the content or, for chat, send Content-Length.
422 budget_exceeded Over the user's limit (details carry which / limit_uusd / max_affordable_uusd) — retry smaller (new key) or guide the user to raise the limit.
429 rate_limit_exceeded Rate limited — back off and retry (same key). When the model itself is temporarily rate limited, details.retryable: true is also present (nothing ran, 0 charge); wait at least the Retry-After header (in a stream error frame, details.retry_after seconds; never more than 60) when given. Requests over 320 KiB: how many one authorization may have in progress at once is limited; beyond it the answer is also a 429 (details.reason: 'large_request_source_capacity', retryable: true, Retry-After: 2; nothing ran, 0 charge) — retry shortly with the same key.Every 429 from the charging API (/v1/commerce/*) carries Retry-After (seconds) and details.reason — token_rate: more than 120 requests a minute with one access token; address_rate: more than 600 not-yet-verified requests a minute from one address (no token, or a token that has not passed authentication here recently; your server's requests with valid tokens do not count toward it); checkout_rate: more than 10 checkouts a minute for one user in one app; open_checkouts: 20 open unexpired checkouts already (Retry-After is the seconds until the oldest one expires, at most 30 minutes; a payment or cancellation frees a slot sooner). Wait for Retry-After, then retry; no checkout was opened and nothing was charged.
503 rate_limit_unavailable Request admission could not be checked, so the request was refused before authorization checks, a hold or model execution. This response currently omits details.retryable; missing is not true, and the SDK does not auto-retry it. Retry deliberately after service recovery, retaining the original key.
500 / 503 internal_error Platform-internal error (for example missing model configuration or failed settlement). A 503 with details.reason: invalid_timing_policy or invalid_model_execution_policy is a configuration refusal before any hold or dispatch; retryable: false, and an operator must correct it. Other internal errors do not prove whether execution or settlement occurred. Preserve the original keys, inspect the endpoint contract and request state before a deliberate retry, and do not automatically resend merely because the retry flag is absent.
500 / 502 / 503 usage_unknown (details.outcome: 'unknown') Outcome unknown — do not retry blindly. 500 = the upstream responded successfully but settlement could not be persisted (the money may be settled, or held until the hold TTL); 502 = a release or zero-charge settlement was not confirmed; on image/embedding requests execution may already have happened and its outcome may be unknown. The status alone does not prove no execution or a released hold. 503 = no upstream dispatch, but hold release was not confirmed (the hold may have expired); do not assume a completed release permits fresh execution. Resend later with the same pair of keys to learn the outcome.
502 provider_unavailable (details.retryable: true) The upstream failed before executing (connection layer / upstream rejected the request) — known not to have executed, 0 charge; back off and retry (same key).
502 provider_error Images and embeddings: a confirmed failed or unbillable result, with details.outcome: "failed" and charged_uusd: "0"; do not automatically retry. For images, confirmed rejection/no dispatch uses retryable: false and releases the key, so sending that key again can execute a new attempt. An executed image result absorbed at zero charge retains the key and can omit retryable; an unbillable embedding result also retains its key. The code or a missing/false retry flag alone does not prove no execution, key retention, or that resending only reads history.
502 provider_unavailable (details.charged: false, retryable: false) The upstream executed but reported failure (including mid-stream failures) — 0 charge, but this key is finished (the same key will never call the upstream again); to try again you must use a new key.
502 / 504 provider_unavailable / provider_timeout (details.outcome: 'unknown') Outcome unknown — do not retry blindly. The upstream timed out, or returned something that could not be priced — it may have executed and incurred cost. After replying, the gateway confirms this request's cost with the upstream (usually within seconds to minutes): once confirmed, the platform absorbs it (the user is charged nothing and the hold is released); only if it cannot be confirmed do funds stay held until the TTL. The key stays occupied. Resend with the same pair of keys to learn the outcome (409 in_flight while confirming; afterwards a zero-charge receipt, or 409 unknown_outcome if it could not be confirmed).
503 catalog_unavailable The model catalog could not be read before execution. If details.retryable is true, back off with the same key; some older image, embedding or Live responses omit this flag, which must not be interpreted as true.
503 ledger_unavailable (no details.reason, retryable: true) Accounting could not accept the hold, before dispatch; this refusal has zero economic effect. Back off and retry with the same key. Do not confuse this with hold_budget_unavailable below, or assume every ledger error has a reason.
503 ledger_unavailable (details.reason: hold_budget_unavailable) The hold's remaining execution time could not be confirmed before dispatch. The upstream was not called and zero-charge release was confirmed. retryable: true; retry later with the same key (SDK 0.5.0 and later auto-retry an HTTP refusal, but never an error frame after the stream opens). An unconfirmed release returns usage_unknown; use the same pair of keys to learn the outcome. An open stream receives the same error in an error frame.
503 pricing_stale / model_price_unavailable / pricing_unverified The model's price expired / was paused by the pricing circuit breaker / could not be verified (details.model) — 0 charge, other models are unaffected. Follow details.retryable; a rejected pricing snapshot can be false, and older non-chat responses can omit details. The SDK does not auto-retry these errors: back off yourself or switch models. Current image/embedding timing-configuration failures can instead use 503 pricing_unverified without retryability or a reason; neither missing field is a false or true flag, and the chat-specific internal-error reason does not apply on those endpoints.
503 provider_unavailable (details.retryable: true) The model is temporarily unavailable — nothing ran, 0 charge; retry later with the same key (the SDK auto-retries this one).
503 provider_unavailable (details.retryable: false) The model cannot take this request right now — nothing ran, 0 charge; retrying the same request will not help, so consider another model.
503 service_overloaded The server is saturated and this request has not started (with Retry-After: 2; when too many requests over 320 KiB are in progress it also carries details.reason: 'large_request_capacity', and 'large_logprobs_capacity' when too many non-streaming logprobs requests above 8,192 entries are) — retryable: true, 0 charge; back off and retry with the same key (the SDK auto-retries this one, honouring Retry-After).
503 service_unavailable (details.reason: server_draining) The service is temporarily unable to accept new requests and the request was not sent upstream. Any hold created for it has a confirmed zero-charge release. retryable: true; retry later with the same key (SDK 0.5.0 and later auto-retry an HTTP refusal, but never an error frame after the stream opens). An unconfirmed release returns usage_unknown instead and must not be treated as released.
503 service_unavailable (no details.reason) Image/embedding transport is not configured, or a historical receipt cannot currently be read. These responses may omit retryability. Do not treat them as server_draining or proof that the original request never executed; retain the keys and investigate the endpoint state before a deliberate retry.
503 service_unavailable (details.reason: redirect_uris_unavailable) The app's registered redirect URIs could not be read when the checkout was opened — no checkout was opened; retry later.
503 commerce_rate_unavailable The platform commission rate is not set yet, so checkouts cannot be opened — no checkout was opened; try again later.
503 maintenance_mode The system is under maintenance (with Retry-After: 120) — try again later; balances and authorizations are unaffected.
503 / 504 provider_timeout (details.retryable: true) 504 = estimate timeout before creating a hold. 503 with details.reason: hold_execution_budget_exhausted = execution budget was exhausted before dispatch and zero-charge release was confirmed. Neither invoked the upstream; retry with the same key.

General rule: retry on details.retryable and details.outcome, not on the HTTP status — the same 502 / 503 / 504 can carry two completely different meanings, "known not to have executed" and "outcome unknown". Preserve the same Idempotency-Key when querying an unknown outcome; settled results are never executed twice.

Charging users (one-time purchases and subscriptions)

⚠️ Not open in production yet: one-time purchases are switched per environment by COMMERCE_PURCHASES_ENABLED; while it is off, creating a checkout returns 403 commerce_disabled, and the developer console cannot accept the agreement or create or change products (reads still work; pausing sales and retiring still work). Production opens only after the terms are final and prerequisites such as refunds are in place. Subscriptions have their own switch, COMMERCE_SUBSCRIPTIONS_ENABLED (see "Subscriptions" in this chapter).

There is exactly one way to charge a user: your app opens a checkout and sends the user to AI Pay's own payment confirmation page, where the user confirms in person. The money comes from the user's AI Pay wallet (where purchases are open, promo credits can pay too) and is collected by AI Pay. There is no direct-charge endpoint and no way to confirm on a user's behalf.

  1. Create a product and a price on the app's Products tab in the Console: a one-time price is US$0.01–US$1,000 in whole cents. A price cannot be changed after it is created; a new price is a new version and applies only to checkouts opened afterwards. The name (up to 60 characters, one line) and description (up to 280) are plain text: control characters, invisible characters, direction marks and unassigned code points are refused (a zero-width joiner only between two characters; emoji and joined letters in any language are fine; a variation selector only right after a character, one at a time; tag characters only in a subdivision flag), with at most 4 combining marks on one character (a zero-width joiner between them counts). App names and publisher names (Console Settings, PATCH /v1/developer/apps/{appId}) follow the same rule, because they appear on the consent and payment confirmation pages. An app can have at most 100 products, retired ones included, and a product at most 50 price versions. When you create a product or add a price through the API you can send an Idempotency-Key (1–200 characters): repeating the same key with the same content returns the original one (200, replayed: true) instead of creating another; the same key with different content returns 409 idempotency_conflict (details.reason: 'payload_mismatch'). Before your first product, accept the current Developer Sales Agreement yourself on the same tab (CLI tokens can only read the acceptance status).
  2. Your app calls POST /v1/commerce/checkouts with the user's access token (it needs wallet.charge), sending product_id, return_url and, optionally, client_reference (up to 128 characters, your own order label). return_url must be exactly equal to one of the app's registered redirect URIs (case and query included, no wildcards); to use another return page, register it first. These three endpoints are server to server: there is no CORS, so a front-end-only app needs a backend for these three calls; that backend uses the same user's access token.
  3. Send the user to the url in the response (/pay/<checkout id>). The page is on AI Pay's domain and cannot be framed by your app; the user signs in there, sees the app, item, amount and the balance after payment, and confirms.
  4. When the payment completes or the user gives up, AI Pay sends the user back to return_url?checkout_id=<checkout id>&status=paid|canceled. status is only a hint: when the user presses "Cancel and return to the App" they come back right away with status=canceled, but a checkout that was submitted before (for example, refused for insufficient balance) settles only after it expires, and in a rare case (a delayed copy of the earlier attempt was accepted before expiry) a checkout the user canceled still ends paid.
  5. URL parameters are never proof — always re-query: GET /v1/commerce/checkouts/{id}. Deliver only when status is paid and product_id and amount_uusd are exactly what you sell, and deliver once per checkout id. client_reference is only your label, not proof of payment. If it is still open, query again later; do not treat it as not bought.
curl -s -X POST "https://ai-pay.coswic.ai/v1/commerce/checkouts" \
  -H "Authorization: Bearer $USER_ACCESS_TOKEN" -H "Content-Type: application/json" \
  -d '{"product_id":"<product id>","return_url":"https://yourapp.example/paid","client_reference":"order-123"}'
# 201 {"object":"commerce.checkout","id":"…","url":"https://ai-pay.coswic.ai/pay/…","status":"open","amount_uusd":"990000",…}
curl -s "https://ai-pay.coswic.ai/v1/commerce/checkouts/<checkout id>" -H "Authorization: Bearer $USER_ACCESS_TOKEN"
Endpoint Returns
POST /v1/commerce/checkouts The checkout (id, url, status: open, expires_at, product, price_id, amount_uusd); valid for 30 minutes
GET /v1/commerce/checkouts/{id} The same checkout object; status is open / paid / canceled / expired, and after payment this id is the purchase id; a one-time purchase also carries refunded_uusd and refund_status (see Refunds in this chapter). Another app's or another user's checkout returns 404 resource_not_found
GET /v1/commerce/purchases This user's one-time purchases in your app (id, product_id, price_id, amount_uusd, paid_at, refunded_uusd, refund_status), with optional product_id, limit, cursor; a purchase appears a few seconds after it completes
  • A checkout expires after 30 minutes (expired). Request limits: 120 requests a minute per access token; 600 not-yet-verified requests a minute per address (no token, or a token that has not passed authentication here recently) — your server's requests with valid tokens do not count toward that one. Opening checkouts is also limited per user per app to 10 a minute and 20 open, unexpired checkouts. Beyond a limit you get 429 rate_limit_exceeded with details.reason token_rate, address_rate, checkout_rate or open_checkouts, always with Retry-After (seconds): wait that long, then retry.
  • If the user confirmed but the result is not known yet (for example, the ledger was briefly unreachable), the checkout stays open while AI Pay resends the same checkout, never charging twice; re-query about every 10 seconds (AI Pay resends a checkout at most once every 10 seconds, so polling faster does not settle it sooner) until it is paid, canceled or expired. While you keep querying, it settles at the latest a minute or two after the checkout expires.
  • AI usage inside your app is separate: it is still charged from the user's wallet at catalog prices and is not part of the item price.
  • The platform takes a commission from each sale and records the rest as your revenue-share attribution: it is not a payable, and payouts are not open; the part a user paid with promo credits can never be withdrawn, even after payouts open. The sales list on the Console's Products tab shows each sale's amount, platform commission, your share and the buyer's per-app pseudonymous id.
  • On the payment confirmation page users see the Purchase and Subscription Terms. Both documents are drafts pending counsel review, and the final text replaces them before launch; the drafts are served only in test environments (the Console's Products tab links the Developer Sales Agreement), and this guide does not link them until they are final.

Subscriptions

Subscriptions are switched per environment by COMMERCE_SUBSCRIPTIONS_ENABLED: while it is off, opening a subscription checkout returns 403 commerce_disabled (details.reason: 'subscriptions_unavailable') and users cannot change their allowance; subscriptions that already exist keep renewing and can still be queried and canceled. A subscription plan is a product too: creating and changing one also needs one-time purchases to be open in this environment (COMMERCE_PURCHASES_ENABLED, see the start of this chapter), so with subscriptions open but purchases closed the Console cannot create subscription plans. Not open in production yet.

  • A subscription product's price version has four fields: the service fee per period (US$0–US$1,000), the period (month or year; test environments also accept test_5m, one period every 5 minutes with a 5-minute grace, which production refuses), and the suggested and minimum AI allowance (each US$0–US$1,000, the minimum not above the suggested amount; the fee plus the minimum allowance at least US$0.01, the fee plus the suggested allowance at most US$1,000), all in whole cents. Create it in the Console's "Products" tab (the "Subscription" choice appears where subscriptions are open), or through the developer API with kind: "subscription" and the four fields (service_fee_usd, interval, ai_allowance_suggested_usd, ai_allowance_min_usd).
  • Each period's total is the service fee plus the AI allowance the user chooses: the payment confirmation page starts from the suggested amount, and the user can raise it or lower it down to the minimum. The AI allowance is the user's money: while subscribed, your App's AI draws only from this period's allowance (at catalog prices), and whatever is left returns to the user's wallet at the period end. It is not your income: your share is calculated from the service fee only, and the sales records list only the service fee for each period. While subscribed, the daily and monthly limits the user set when authorizing do not apply; the per-request limit still does.
  • Open the checkout with the same POST /v1/commerce/checkouts (use the subscription product as product_id). The response also carries interval, service_fee_uusd, ai_allowance_uusd, ai_allowance_suggested_uusd and ai_allowance_min_uusd; once paid, the checkout's id is the subscription ID. A user has at most one unended subscription to your App: when there is one already, or another subscription checkout is being paid or was just paid and is being recorded, opening returns 409 already_subscribed with details.reason active_subscription (with subscription_id and ending), pending_checkout or recording (these two with checkout_id). A user who revoked and authorized again can usually subscribe again at once (the old subscription ends immediately and its unused allowance returns to the wallet); on a 409 with ending: true, try again in about a minute.
  • Always query the subscription: GET /v1/commerce/subscriptions (optional product_id, limit, cursor). status is active, past_due (the period has ended and the renewal has not succeeded yet, within the grace: the short time after every period end before the renewal is recorded, a renewal short of money and platform pauses of renewals all show this status; keep providing the service until entitled_until), canceled (renewals stopped; usable until entitled_until) or ended; ai_status is what says whether AI can be used (available, exhausted = this period's allowance is used up, past_due = this period's allowance is closed and AI waits until the renewal succeeds; while a past_due subscription's allowance is still open, it is available or exhausted). Provide the service by status and entitled_until; do not compute the end date yourself.
  • Each period renews automatically at the period end with the same service fee and the next period's allowance; when money is short it is retried within the 7-day grace and ends if it is still short then. Users cancel (renewals stop at the period end, no refund for the remaining days) or change the next period's allowance in the Dashboard's "My subscriptions"; you can stop one subscriber's renewals under Subscribers in the Console's "Products" tab (a reason is required and kept in the audit log). A past_due subscription that is canceled or stopped ends at once (status becomes ended).
curl -s "https://ai-pay.coswic.ai/v1/commerce/subscriptions?product_id=<subscription product id>" -H "Authorization: Bearer $USER_ACCESS_TOKEN"
# {"object":"list","data":[{"object":"commerce.subscription","id":"…","status":"active","entitled_until":"…","ai_status":"available","ai_allowance_remaining_uusd":"…",…}],"next_cursor":null}
Field Meaning
status, entitled_until The status and until when the user is entitled (the grace end while past due; this period's end once renewals stopped)
current_period_end, canceled_at This period's end; when renewals were stopped (null if they were not)
service_fee_uusd, ai_allowance_uusd, next_ai_allowance_uusd The service fee per period, this period's AI allowance, the next period's AI allowance (the new one if the user changed it)
ai_allowance_used_uusd, ai_allowance_held_uusd, ai_allowance_remaining_uusd This period's allowance used, held and remaining (remaining already excludes what is held)
ai_status, as_of Whether AI can be used; the ledger time this data reflects
current_period_refunded_uusd How much of the current period's service fee was refunded (0 when none; see Refunds in this chapter)

Errors from the developer console and developer API (products, prices, agreement):

HTTP code Meaning / what to do
400 invalid_request A field breaks a rule; details.parameter names it: a product name or description that is too long or not plain text (rules in step 1), a malformed price (the four subscription fields are in "Subscriptions"), a stop of renewals without a reason (reason, 1–300 characters); an app name or publisher name that is not plain text also carries details.reason: 'plain_text'. Nothing was written.
403 commerce_disabled (details.reason: 'purchases_disabled') One-time purchases are not open in this environment: the agreement cannot be accepted and products and prices cannot be created or changed (reads still work); only pausing sales (status: 'draft') and retiring ('retired') are always accepted, so you can take a product off sale before the switch comes back. Listing subscribers and stopping their renewals are not affected.
403 developer_terms_required Accept the current version of the Developer Sales Agreement before creating a product (details carries version, fingerprint and url).
403 developer_terms_unavailable The Developer Sales Agreement is not published in this environment (production does not serve the draft before launch), so it cannot be accepted and products cannot be created.
403 forbidden (details.reason: 'console_session_required') POST /v1/developer/commerce/terms: acceptance was attempted with a CLI or other program token — accept the agreement yourself, signed in to the Console; tokens can only read the acceptance status.
409 idempotency_conflict (details.reason: 'payload_mismatch') Creating a product or adding a price: the same Idempotency-Key was sent with different content — use a new key for new content.
409 product_retired The product is retired (final); it can no longer be edited or get a new price.
409 developer_terms_changed The agreement version or fingerprint you accepted is not the current one — read the agreement again, then accept.
409 commerce_limit_reached A limit was reached: at most 100 products per app, retired ones included (details.reason: 'products_per_app'), and at most 50 price versions per product ('prices_per_product'); details.limit is the limit. Nothing was written.

Refunds

Refunds follow each environment's switch COMMERCE_REFUNDS_ENABLED: while it is off the Console offers no Refund button and a refund returns 403 commerce_disabled (details.reason: 'refunds_disabled'); existing refunds can still be read. Not open in production yet.

  • In the Console Products tab you can refund one-time purchases of your own app and a subscriber's current period service fee (before that period ends), fully or in part: each one-time sales row, the sales row of a subscription's current period and each subscriber row has a Refund button (past periods of a subscription only show what was refunded). Money goes back only to the AI Pay wallet that paid. A reason is required (1–300 characters, kept in the audit log; neither the user nor your app sees it). Refunds must be made by you, signed in to the Console (a CLI or other program token gets 403 forbidden, details.reason: 'console_session_required'); resending from the same dialog reuses the same Idempotency-Key, so nothing is refunded twice; one charge has at most one refund in progress at a time; each app may make at most 30 refunds a minute.
  • Amount: the default is everything refundable (the price minus what was already refunded); a partial refund must be in whole cents. A refund takes back your share and the platform fee in proportion: refunding one charge in several steps takes back exactly that charge's whole share in total. The AI allowance is the user's money anyway and goes back at the period end, so it is outside refunds.
  • A refund does not stop a subscription: use Stop renewals on the subscriber row for that. Only the current period of a subscription can be refunded; once it is over it cannot.
  • When an app is deleted or suspended, its subscriptions stop at once and AI Pay refunds the rest of the current period's service fee to the wallet automatically (for the time left at the stop, counted on what is still unrefunded; your share is taken back in proportion). You cannot refund that period yourself. One-time purchases are not refunded automatically when an app is deleted.
  • Some charges need to be checked and handled by AI Pay (the Console says "Please contact AI Pay about this charge"). AI Pay operators can also refund any charge (for example a purchase of a deleted app, or a period that is over).
  • Whether to take back what was bought is up to your app; AI Pay does not do it for you: one-time purchases in GET /v1/commerce/checkouts/{id} and GET /v1/commerce/purchases carry refunded_uusd (how much was refunded) and refund_status (none / partial / full; null for subscription checkouts), and each subscription in GET /v1/commerce/subscriptions carries current_period_refunded_uusd (how much of the current period's service fee was refunded). Users see refunds in their Dashboard purchases, My subscriptions and activity.
HTTP code Meaning / what to do
403 commerce_disabled (details.reason: 'refunds_disabled') Refunds are not open in this environment. A resend with the same Idempotency-Key still returns the original refund.
409 refund_not_allowed details.reason: period_ended (the period is over, or the period shown on screen has passed: refresh), auto_refund_period (the period stopped because the app was deleted or suspended; AI Pay refunds it automatically), nothing_refundable (nothing left to refund), operator_review_required (please contact AI Pay about this charge). No refund was created.
409 refund_exceeds_remaining More than what is left to refund; details.remaining_uusd is how much can still be refunded.
409 refund_in_progress A refund of this charge is already in progress; try again once it finishes.
503 busy Temporarily busy (with Retry-After): resend later with the same Idempotency-Key; nothing is refunded twice.

App pricing (service fees)

⚠️ App service fees and usage surcharges are retired: apps cannot add a per-request service fee or a surcharge on the AI usage fee. The settings endpoint no longer accepts per_request_fee_usd / surcharge_bps (sending either returns 400 invalid_request with details.reason app_fees_retired), the consent screen discloses no app service fee, and real requests do not charge the user any app fee; the receipt fields app_service_fee_uusd and breakdown.app_margin_uusd stay: they are "0" on new requests, and requests frozen before the retirement (including their receipt replays) keep their values. Service-fee attribution records from before the retirement are kept; no new ones are created.

What the user pays = catalog price. The catalog price follows that model’s policy and frozen prices (see "Catalog and pricing"); subscriptions or other charges your app collects outside the platform are separate from AI Pay.

You can set a suggested monthly limit on the app's Settings tab in the Console, under Authorization defaults (or with suggested_monthly_usd on PATCH /v1/developer/apps/{appId}) — the default on the consent screen (daily / per-request are derived as 10:1:100), at most $200 (the platform ceiling for suggestions); the amount is still the user's decision and they can raise it themselves. Every change leaves an audit record.

Usage reconciliation and payouts

The Console's "Requests" tab lists your app's requests one by one: status (settled / failed / pending confirmation — do not retry pending ones), tokens, charges and service-fee attribution from before the retirement; each row expands to identifiers such as request_id / Idempotency-Key for matching against your logs. This tab does not directly display user email or full prompt/response bodies. Request, authorization and pseudonymous identifiers can be linked to your App's own records and are not anonymous data.

Service-fee attribution from before the retirement is reconciled against actual settlements and attribution records; reserve periods, refund or dispute reversals, and payments depend on the formal agreement. Payouts and automated reversals are not currently available; no opening date is promised.

⚠️ Payouts are not open yet: payout account setup and payout requests are unavailable (503 payouts_disabled). App service fees are retired, so new requests do not generate app service fees. Existing records are retained; their status and future payout eligibility depend on actual transactions, the formal agreement, and applicable law. Test records are not real-money payables.

References

  • Product overview and current status: /about — what AI Pay is, who pays, and what is open today.
  • API contract: /openapi.yaml (OpenAPI 3.1, the external developer contract — generated from the code, covering the endpoints you call and every error code). Feed it straight to a coding agent, import it into Postman/Bruno, or generate a client from it.
  • SDK and CLI: @coswic/aipay-sdk (TypeScript SDK; the README covers the full usage and the built-in conventions) and @coswic/aipay (CLI; the command list is in the "Connect with the CLI or a coding agent" section) — both are public npm packages.
  • Provider and packages: AI Pay is a product of Coswic Labs (coswic.ai); contact contact@coswic.ai. The npm packages are published only under the @coswic scope (@coswic/aipay-sdk, @coswic/aipay) — packages with a similar name but without that scope are not part of AI Pay.
  • Legal documents: Terms of Service, Privacy Policy — before your app guides users to authorize, make sure your usage is compatible with both.
  • Complete example: QuickGist (a full reference implementation of "Sign in with AI Pay" → streaming call → per-class error handling → unknown-outcome lookup) currently ships inside the AI Pay source repository (showcase/quickgist/, shared skeleton in showcase/kit/) and is not yet published as a standalone download; to get the same wiring in your own project, run the CLI's aipay init (it generates the start/callback routes for your framework plus aipay-agent.md; see the "Connect with the CLI or a coding agent" section).
Amounts are always shown in USD (integer µUSD strings, $1 = 1,000,000 µUSD).