# Xailon Token Factory Docs > One OpenAI-compatible API for every model in the catalogue, with metering, credits and enforcement before a request runs. This document contains the full content of all documentation pages for AI consumption. --- ## Authentication **URL:** https://tf-stage-site.iamsaif.ai/docs/authentication **Description:** API keys, auth headers, key hierarchy, request ids, and how auth failures are reported. ## Auth headers Two headers are accepted on every path; read order is `authorization` first, then `x-api-key`: | Header | Use with | |---|---| | `Authorization: Bearer ` | OpenAI SDKs (default) | | `x-api-key: ` | Anthropic SDKs (default) | ```bash curl https://tf-stage-api.iamsaif.ai/v1/chat/completions \ -H "Authorization: Bearer $INFINIA_API_KEY" \ ... ``` ```bash curl https://tf-stage-api.iamsaif.ai/v1/messages \ -H "x-api-key: $INFINIA_API_KEY" \ ... ``` Building an app that other TokenFactory users connect to? Instead of asking them to paste a key, let them approve your app and receive a key for them with [Connect TokenFactory (OAuth PKCE)](/docs/connect-tokenfactory). ## Key hierarchy and scope Keys are hierarchical: **Organisation → Project → API key**. A key carries: | Property | Enforced where | |---|---| | Model allowlist | before the provider is called (`403 model_not_allowed`) | | IP allowlist (CIDR) | before the provider is called (`403 ip_not_allowed`) | | Plan / model plan gating | before the provider is called (`403 model_not_on_plan`) | | RPM rate limit | token bucket, checked on every request (`429 rate_limit_exceeded`) | | Token quotas (daily/monthly) | quota windows (`429 quota_exceeded`) | | USD spend cap | pre-flight (`402 key_spend_cap_reached`) | A project-scoped key whose project is disabled returns `403 project_disabled`. Any key of a suspended organization returns `403 organization_suspended` until the organization is resumed. Per-key and project USD spend caps surface as `402` — see [Billing](/docs/billing). All of this is decided by the gateway's policy engine **before any provider is called** — a denied request never reaches a provider, and is never billed. ## Request ids - Request ids are **minted server-side**. Any `X-TF-Request-Id` or `X-Request-Id` you send is ignored and overwritten. - Every response (success or error, JSON or audio or stream) carries the `X-TF-Request-Id` response header. - Every error body carries the same id as `error.request_id`. - **Quote the `X-TF-Request-Id` in support requests** — it is the correlation key we use across the whole product. ## 401 responses | Code | Meaning | Recovery | |---|---|---| | `missing_api_key` | No `Authorization` / `x-api-key` header on the request. | Send the header. | | `invalid_api_key` | Key hash not found. | Re-copy the key; confirm the deployment. | | `inactive_api_key` | Key resolved but deactivated. | Re-enable in Settings → API keys. | | `expired_api_key` | Key's expiry has passed. | Create a new key. | ```json { "error": { "type": "authentication_error", "message": "Invalid API key", "code": "invalid_api_key", "param": null, "request_id": "req_01J8EXAMPLE" } } ``` ## When a provider credential fails If a provider rejects **our** credential, you never see a 401/403 for it — you cannot fix that, we can. Instead of a confusing provider auth failure you get a clean, actionable error: ``` 502 provider_unavailable "a provider rejected the platform credential" ``` with the provider's own text withheld. See [Errors](/docs/errors) for the full status-mapping table. --- ## Billing **URL:** https://tf-stage-site.iamsaif.ai/docs/billing **Description:** The prepaid credit balance, request-time credit reservations, metered usage. ## Prepaid credit balance Every organisation has a prepaid credit balance. Usage is metered per model (SKU) from the provider's own reported `usage` — **never estimated** — and priced at the catalogue rate for that model at nano-USD precision. ## How reservations work Before calling the provider, the gateway **reserves** an estimated cost against *balance minus open reservations*: 1. The estimate is sized from `max_tokens` (falling back to a platform default when omitted), priced at the model's rate. 2. The reservation is held for the life of the request. 3. Once usage is metered, the reservation is settled to the real cost (or released, if the request failed). Because the check is against balance minus open reservations, **concurrent requests cannot collectively overspend a small balance**. This reservation gate applies to prepaid credit balances — postpaid orgs are capped by a monthly budget instead (a counter cap, not a reservation). ## Why 402 is not 429 If the credit balance cannot cover the reservation you get **HTTP 402**: ```json { "error": { "type": "insufficient_quota", "message": "Insufficient credit balance — top up to continue", "code": "insufficient_funds", "param": null, "request_id": "req_01J8EXAMPLE" } } ``` A funds denial is deliberately **not** a 429: - It is not congestion — SDK retry/backoff does not help. - No `Retry-After` is sent. - Retrying without topping up will keep failing. Top up in **Billing** (Stripe) and retry. ## Other money-related errors | Status | Code | Trigger | |---|---|---| | 402 | `insufficient_funds` | Credit balance cannot cover the reservation. | | 402 | `key_spend_cap_reached` | Per-key USD spend cap reached. | | 402 | `project_quota_exceeded` | Project monthly cost ceiling reached. | | 429 | `quota_exceeded` / `project_quota_exceeded` | Token quota windows (not funds). | ## Cached tokens Provider-reported prompt-cache tokens are surfaced, never estimated: - OpenAI-dialect bodies: `usage.prompt_tokens_details.cached_tokens` / `.cache_write_tokens` - Anthropic-dialect bodies: `usage.cache_read_input_tokens` / `usage.cache_creation_input_tokens` - Every body: `provider_metadata.cache.read_tokens` / `.write_tokens` On OpenAI-dialect chat/embeddings responses these `prompt_tokens_details` fields are always present (`0` when the backend didn't report caching) — see [Normalized usage shape](/docs/api-reference/chat-completions#normalized-usage-shape). The billed amount always matches what's displayed, including the cache discount: the same cache figures the client sees are what's metered, never a separately-computed number. Cached tokens are priced at the model's cached rate when the catalogue defines one, and the standard rate otherwise. ## Inspecting spend - Portal → **Billing**: credit balance, top-ups, invoices. - Portal → **Analytics**: token/cost breakdown per model and per key. - Every response's `usage` block shows exactly what was metered for that request. ## Related - [Rate Limits & Quotas](/docs/rate-limits) --- ## Connect TokenFactory (OAuth PKCE) **URL:** https://tf-stage-site.iamsaif.ai/docs/connect-tokenfactory **Description:** Let users connect your app to TokenFactory in one click — your app receives a project API key for them through an OAuth 2.0 Authorization Code + PKCE (S256) flow, with no client registration. **Connect TokenFactory** lets a third-party app — a web app, an IDE extension, a CLI agent — get a TokenFactory API key for a user without asking them to copy one out of the portal. The user signs in to TokenFactory, sees which app is asking, picks the project the key is for and clicks **Authorize**; your app receives an ordinary project API key it can use against `https://tf-stage-api.iamsaif.ai/v1`. The flow is OAuth 2.0 Authorization Code with PKCE ([RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636)) and has the same shape and parameter names as [OpenRouter's OAuth PKCE flow](https://openrouter.ai/docs/guides/overview/auth/oauth), so an existing "Connect OpenRouter" client needs only a few changes — see [Differences from OpenRouter](#differences-from-openrouter). - **No client registration and no client secret.** Your `callback_url` is your app's identity. `localhost` callbacks on any port work for local tools. - **The key is a normal project API key.** The user sees it with the project's other API keys and can revoke it there at any time. Usage is attributed to it like any other key. - **Codes are single-use and expire after 10 minutes**, are stored hashed, and are bound to your app by PKCE — an intercepted code is useless without your `code_verifier`. ## Endpoints | Step | Method and URL | Who calls it | |---|---|---| | Consent page | `GET https://tf-stage-portal.iamsaif.ai/authorize?…` | The user's browser (your app redirects or links to it) | | Code exchange | `POST https://tf-stage-portal.iamsaif.ai/api/portal/v1/oauth/exchange` | Your app's backend (or your CLI) | | Inference with the key | `https://tf-stage-api.iamsaif.ai/v1/*` | Your app, with `Authorization: Bearer ` | `` is the TokenFactory deployment's domain. Both OAuth URLs are on the **portal** host; only inference uses the API host. ## Step 1: Create a code verifier and an S256 challenge For every connect attempt, generate: - a **`code_verifier`**: a cryptographically random string of 43–128 characters from `A–Z a–z 0–9 - . _ ~` (32 random bytes, base64url-encoded without padding, gives 43 characters); - a **`code_challenge`**: `BASE64URL(SHA256(code_verifier))`, without padding; - a **`state`**: a random, unguessable value (1–512 characters) your app will check when the user comes back. Keep the verifier and `state` on your side (server session, or in memory for a CLI). Never put the verifier in the URL. ```typescript function base64url(bytes: Uint8Array): string { let s = ''; for (const b of bytes) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } export async function createPkce() { const codeVerifier = base64url(crypto.getRandomValues(new Uint8Array(32))); const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier)); const codeChallenge = base64url(new Uint8Array(digest)); const state = base64url(crypto.getRandomValues(new Uint8Array(16))); return { codeVerifier, codeChallenge, state }; } ``` ```python import base64, hashlib, secrets def b64url(raw: bytes) -> str: return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() def create_pkce(): code_verifier = b64url(secrets.token_bytes(32)) code_challenge = b64url(hashlib.sha256(code_verifier.encode()).digest()) state = secrets.token_urlsafe(16) return code_verifier, code_challenge, state ``` ```bash CODE_VERIFIER=$(openssl rand 32 | base64 | tr '+/' '-_' | tr -d '=\n') CODE_CHALLENGE=$(printf '%s' "$CODE_VERIFIER" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=\n') STATE=$(openssl rand -hex 16) ``` ## Step 2: Send the user to the TokenFactory consent page Redirect (or link) the user's browser to: ```text https://tf-stage-portal.iamsaif.ai/authorize ?callback_url= &code_challenge= &code_challenge_method=S256 &state= &key_label= ``` | Parameter | Required | Description | |---|---|---| | `callback_url` | **Yes** | Where the browser is sent back with the code. See [Callback URL rules](#callback-url-rules). | | `code_challenge` | **Yes** | `BASE64URL(SHA256(code_verifier))` from step 1. | | `code_challenge_method` | **Yes** | Must be `S256`. `plain` and requests without a challenge are refused. | | `state` | **Yes** | Your random CSRF value (1–512 characters). It comes back unchanged on the callback — on success **and** on deny. | | `key_label` | No | The label for the key that will be created, at most **100 characters**. The key is named **`OAuth: