# Cruxy Learn: full corpus > OpenAI-compatible LLM gateway for the Cruxy model tiers (canto, saga, and epos), plus embeddings, rerank, and content moderation behind one base URL (https://api.cruxy.ai) and one Bearer key. Every documentation page, concatenated in navigation order. Each block below is fenced by a rule stating the page title, its canonical URL, and the markdown source it was rendered from. The per-page link index is at https://learn.cruxyai.com/llms.txt. ================================================================================ Page: Start here URL: https://learn.cruxyai.com/learn/en/start-here Markdown: https://learn.cruxyai.com/learn/en/start-here.md ================================================================================ # Start here Two reading paths through the Cruxy API: the whole API in nine pages, and building an agent with tools, structured output, memory, and rules. There are two paths here. Each step names one page and what you take from it. The pages build on each other, so read a path in order the first time; after that, each page stands on its own as a reference. - [The API in nine pages](#the-api-in-nine-pages) goes from your first call to running in production. - [Build an agent](#build-an-agent) is for when the model has to act: call your functions, return data your code can parse, and remember. ## The API in nine pages 1. **Make your first call** [Quickstart](/docs/en/get-started/quickstart) takes you from an empty terminal to your first model response: you get an API key with device login, then send a chat request to the `canto` tier. 2. **Choose a tier** [Choosing a tier](/docs/en/build/choosing-a-tier) compares the tiers you pass as `model` (`canto`, `saga`, and `epos`) by profile, output cap, and how each one reasons by default, and shows how to read the live catalog from `GET /api/v1/models` instead of hardcoding it. 3. **Hold a conversation** [Chat](/docs/en/build/chat) documents `POST /api/v1/chat`, the OpenAI-compatible chat completion: the request options, a single JSON completion or a Server-Sent Events stream, the `cruxy` block, and usage. 4. **Let the model call your functions** [Tutorial: build a tool-using agent](/docs/en/build/tool-agent) builds on the same endpoint. You describe two functions, run the calls the model returns, send the results back, and loop on `finish_reason` until the model answers. 5. **Answer from your own documents** [Retrieval-augmented generation](/docs/en/resources/cookbook/rag) is a cookbook recipe that chains three endpoints: embeddings for a first-pass search, rerank to sharpen the shortlist, and chat to write the answer. 6. **Screen content** [Moderations](/docs/en/build/moderations) checks text against the content-safety categories with the `cruxy-guard` model and returns an overall `flagged` result. 7. **Handle failures** [Errors and retries](/docs/en/build/errors-and-retries) defines the error envelope, lists every error code, and says which failures to retry and how long to wait, so your client branches on the stable `code`, never on the wording of the message. 8. **Run it reliably** [Reliability](/docs/en/build/reliability) puts the production rules in one place: the per-tier deadlines, which failures to retry, `Idempotency-Key`, how to tell a finished stream from a failed one, and where to check platform status. 9. **Know the limits** [Known limitations](/docs/en/build/known-limitations) lists what the API does not do today, such as reporting a reasoning-token count or running a non-streaming call past 90 seconds, and the workaround for each. ## Build an agent An agent is a loop: the model asks for a function call, your code runs it and sends the result back, and the model continues until it has an answer. This path assumes you have made a chat call; if not, start with the first three steps above. 1. **Describe your functions** [Define tools](/docs/en/build/tools) shows how to describe each function in the `tools` array with a JSON Schema for its arguments, how `tool_choice` controls when the model calls one, and why tools are billed as input. 2. **Run the calls the model returns** [Handle tool calls](/docs/en/build/tool-calls) covers the other half: read the tool calls on the response, run each function, send every result back by `tool_call_id`, and repeat until `finish_reason` is `stop`. 3. **Put the loop together** [Tutorial: build a tool-using agent](/docs/en/build/tool-agent) builds a working TypeScript agent from those two pages: two tools, their handlers, and the loop on `finish_reason`, with the reasons the loop is shaped the way it is. 4. **Get answers your code can parse** [Ask for structured output](/docs/en/best-practices/prompting#ask-for-structured-output) explains `response_format`: send a JSON schema to constrain the output, read which tiers support it from `GET /api/v1/models`, and handle output that does not match. 5. **Let the agent remember** [Memory](/docs/en/build/memory) lets chat recall stored facts and capture new ones. It is off for a developer API key until a request opts in, so read [Opt in from a developer key](/docs/en/build/memory#opt-in-from-a-developer-key) before you rely on it. 6. **Give it standing instructions** [Standing rules](/docs/en/build/rules) injects your organization's rules into chat as defaults. Like memory, rules are off for a developer key unless you opt in, per request or once on the key. 7. **Make the loop survive failures** [Reliability](/docs/en/build/reliability) matters more in a loop, where one failed request stalls the whole task: the per-tier deadlines, which failures to retry, `Idempotency-Key`, and how to tell a finished stream from a failed one. ## Next steps [Cookbook](/docs/en/resources/cookbook) has more recipes that combine endpoints to finish a real job, and [API Reference](/docs/en/reference/api) lists every endpoint with its exact request and response shape. Working from a terminal instead? [Get started with the CLI](/docs/en/cruxy-code) installs Cruxy Code, the `cruxy` coding agent, and signs it in with the same device login. Moving code that already calls OpenAI? [Migrate from OpenAI](/docs/en/migrate/from-openai) changes the base URL, the key, and `model`, and [OpenAI SDK compatibility](/docs/en/migrate/openai-sdk-compatibility) says what carries over. ================================================================================ Page: One gateway for every model tier URL: https://learn.cruxyai.com/docs/en Markdown: https://learn.cruxyai.com/docs/en.md ================================================================================ # One gateway for every model tier An OpenAI-compatible LLM gateway for the Cruxy model tiers: chat, embeddings, and moderation behind one API key. ## Choose how you build Two ways into the same gateway: call the endpoints directly, or start from a pattern and copy what fits. - [Chat](/docs/en/build/chat) - [Embeddings](/docs/en/build/embeddings) - [Rerank](/docs/en/build/rerank) - [Moderations](/docs/en/build/moderations) - [Feedback](/docs/en/build/feedback) - [API Reference](/docs/en/reference/api) - [Cookbook](/docs/en/resources/cookbook) - [API guide for agents](/docs/en/resources/api-guide) - [Glossary](/docs/en/resources/glossary) - [Changelog](/docs/en/reference/changelog) ## From key to production Every integration walks the same path; each stage links into the guide that covers it. To read it as one ordered path, follow [Start here](/learn/en/start-here). - [Features overview](/docs/en/get-started/features) - [Quickstart](/docs/en/get-started/quickstart) - [Get your API key](/docs/en/get-started/api-keys) - [Authentication](/docs/en/get-started/authentication) - [Chat](/docs/en/build/chat) - [Streaming](/docs/en/build/streaming) - [Define tools](/docs/en/build/tools) - [Embeddings](/docs/en/build/embeddings) - [Rerank](/docs/en/build/rerank) - [Moderations](/docs/en/build/moderations) - [Models](/docs/en/reference/models) - [Errors and retries](/docs/en/build/errors-and-retries) - [Rate limits and budgets](/docs/en/build/rate-limits) - [Production checklist](/docs/en/best-practices/production-checklist) - [Feedback](/docs/en/build/feedback) - [API Reference](/docs/en/reference/api) ## Pick a model You pass a tier id as `model` (or `auto` to let the router choose), and the gateway routes the call. The tier is the contract; the upstream model behind it is never exposed. [Choosing a tier](/docs/en/build/choosing-a-tier) compares them, and [Models](/docs/en/reference/models) documents every id and alias. - `canto` (Deep): Deepest reasoning, text only; reach for it on the hardest tasks. - `saga` (Balanced): Strong quality at lower latency and cost, a sensible default for everyday calls. - `epos` (Fast): Lowest latency and cost for short, high-volume calls; the budget-downgrade target. ## Start from a recipe Four working patterns that combine the endpoints to do a real job; copy the one shaped like yours. [Cookbook](/docs/en/resources/cookbook) indexes them all. ## Start building One key, one endpoint, three tiers behind it. ================================================================================ Page: Features overview URL: https://learn.cruxyai.com/docs/en/get-started/features Markdown: https://learn.cruxyai.com/docs/en/get-started/features.md ================================================================================ # Features overview What the Cruxy gateway gives you: OpenAI-compatible chat on three tiers, specialized model endpoints, and memory and rules you control. Cruxy is an OpenAI-compatible LLM gateway. You call one API at `https://api.cruxy.ai` with one key and name a model tier instead of a provider model. Cruxy-native fields are additive and namespaced under a `cruxy` key, so an OpenAI client keeps parsing the response and ignores what it does not know. ## Three tiers and auto You pass a tier id as the chat `model`. The gateway resolves the tier to an upstream model on the server; an upstream provider model is never accepted or returned, so the tier is the stable contract your code depends on. | Tier | Profile | Default reasoning | Reasoning control | | --- | --- | --- | --- | | `canto` | Deep | `high` | Graded: `low`, `medium`, and `high` are different depths. | | `saga` | Balanced | `low` | Graded: `low`, `medium`, and `high` are different depths. | | `epos` | Fast | `none` | Graded: `low`, `medium`, and `high` are different depths. | The reasoning columns are the shipped defaults. `GET /api/v1/models` reports each tier's live `reasoning.default_effort` and `reasoning.graded`, along with its context window, output cap, and pricing; [Models](/docs/en/reference/models) shows how to read the catalog at runtime, and [Choosing a tier](/docs/en/build/choosing-a-tier) compares the tiers. A reasoning tier thinks inside the same `max_tokens` budget as its answer, and the thinking is not returned as content. A small `max_tokens` on `canto` can be spent entirely on thinking, ending with `finish_reason: "length"` and empty content. Send `reasoning_effort: "none"` for a short, direct answer, or leave `max_tokens` unset to keep the tier's cap; see [Reasoning effort](/docs/en/build/reasoning-effort). Send `model: "auto"` to let the server-side router pick the tier from the request. It resolves to a concrete tier before billing and before the upstream call, and the tier that served the request comes back as `cruxy.routed_tier`. An `auto` request may be budget-downgraded to `epos`, so read `routed_tier` rather than assuming it; [Auto routing](/docs/en/build/auto-routing) covers the router, and [Rate limits and budgets](/docs/en/build/rate-limits) explains the budgets behind the downgrade. ## What you can call | Area | Endpoints | What it does | | --- | --- | --- | | [Chat](/docs/en/build/chat) | `POST /api/v1/chat` | OpenAI-compatible chat with Cruxy features: [Streaming](/docs/en/build/streaming), tool calling (see [Define tools](/docs/en/build/tools)), [Memory](/docs/en/build/memory), [Standing rules](/docs/en/build/rules), and attached files. | | Native chat | `POST /api/v2/chat` | The Cruxy-native wire: named SSE events that always end in a `finish` or `error` frame. | | OpenAI wire | `POST /v1/chat/completions`, `GET /v1/models` | The plain OpenAI protocol for OpenAI clients and evaluation harnesses, with none of the Cruxy-native features. | | [Models](/docs/en/reference/models) | `GET /api/v1/models` | The tier catalog. | | Token counting | `POST /api/v1/tokens/count` | The input tokens a chat request would bill, counted without inference and not billed. | | [Embeddings](/docs/en/build/embeddings) | `POST /api/v1/embeddings` | 1024-dimension vectors from `cruxy-embed`. | | [Rerank](/docs/en/build/rerank) | `POST /api/v1/rerank` | Documents ranked against a query by `cruxy-rerank`. | | [Moderations](/docs/en/build/moderations) | `POST /api/v1/moderations` | Content classification by `cruxy-guard`. | | [Feedback](/docs/en/build/feedback) | `POST /api/v1/feedback` | A signal about an earlier call, joined to it by `request_id`. | | [Files](/docs/en/build/files) | `/api/v1/files` | Uploads that a chat message attaches with `file_ids`; chat reads text, PDF, and Word (`.docx`) files, and images on a tier that reads them. | | [Conversations](/docs/en/build/conversations) | `/api/v1/conversations` | Conversation history stored server-side, private to its author, with search and branches. | | [Memory](/docs/en/build/memory) | `/api/v1/memories` | Stored facts, personal, organization-wide, or shared in a vault, that chat can recall. | | [Vaults](/docs/en/build/vaults) | `/api/v1/vaults` | Shared spaces in an organization, with members, memory, rules, and files. | | Rules | `/api/v1/rules`, `/api/v1/rules/resolved` | Standing instructions for chat, set for your organization or a vault. | | [Prompts](/docs/en/build/prompts) | `/api/v1/prompts` | Named prompts with immutable versions. | | [Evals](/docs/en/build/evals) | `/api/v1/evals/suites` | Test suites run against a tier; every case is a billed completion. | | Account | `/api/v1/me`, `/api/v1/profile`, `/api/v1/limits`, `/api/v1/limits/month`, `/api/v1/limits/plans` | Your identity, profile, live limits, the month so far by day, and every plan's entitlements; see [Plan limits](/docs/en/build/plan-limits). | | [Organization](/docs/en/build/organization) | `/api/v1/org/members`, `/api/v1/workspaces`, `/api/v1/logs` | Members, invitations, workspaces with spend caps, and request-log metadata. | | Sign-in | `/api/v1/device/code`, `/api/v1/device/token` | Device login, which issues API keys; see [Get your API key](/docs/en/get-started/api-keys). | | Status | `GET /api/status`, `GET /api/health`, `GET /api/ready` | Public platform status and health probes. | Every `/api/v1` endpoint is also served under `/api/v2` with identical behavior, and this site documents the `/api/v1` path. Chat is the one exception: `POST /api/v2/chat` is a different wire from `POST /api/v1/chat`. [API Reference](/docs/en/reference/api) has every operation with its exact request and response shape. ## Memory and standing rules Two chat features add context beyond the messages you send. You control both per request, and their defaults depend on how the key was issued: - **On by default** for a signed-in credential: what a person gets by signing in to the Cruxy web app, desktop, the CLI, or mobile. A key minted by device login or OAuth login is a signed-in credential whichever client ran the flow, a third-party tool included. - **Off by default** for a developer API key or a headless key, which opts in per request. `GET /api/v1/limits` reports which kind a key is as `bucket`: `subscription` is a signed-in credential, and `apikey` and `headless` are not. A server, or anything that serves people other than the key's owner, should use a developer API key; see [Get your API key](/docs/en/get-started/api-keys#two-kinds-of-key). To get the same behavior from any key, set both on every request. ### Memory Memory has two independent sides, each set in the request's `memory` object: - **Recall** (`recall`) adds the stored memories most relevant to the turn as background context and reports them in `cruxy.memory_recall`: the scope and key of each, never the stored value. - **Capture** (`capture`) lets the gateway store a durable fact from the turn, such as a stated preference, and reports it in `cruxy.memory_capture`. No field means nothing was stored. Captures go to your personal memory, or to a vault you can write when the request names one, never to organization-wide memory. Content carrying an email address, phone number, or card number is dropped before any write. `true` needs a key whose allowed scopes include memory; otherwise the request fails with `403` `key_scope_forbidden`. `false` needs no scope. Pin `Cruxy-Version: 2026-09-26` on every request that relies on `false`, so a gateway that predates the field refuses the request instead of ignoring it. `GET /api/v1/memories` lists what is stored, and `DELETE /api/v1/memories/{id}` removes an entry. [Memory](/docs/en/build/memory) covers recall, capture, and the scope a key needs. ### Standing rules Standing rules are instructions your organization sets for chat, and a vault can have its own. They are injected into the turn as defaults that the user's own message overrides. A developer API key gets them only when the request sends `rules: true`, or when the key's allowed scopes name the rules family. Any key may send `rules: false` to decline them for a turn. When rules apply, the response carries `cruxy.rules_applied` with counts and sources, never the rule text. `GET /api/v1/rules/resolved` returns the exact rules a turn would get. Injected rule text counts as input tokens. [Standing rules](/docs/en/build/rules) covers opting in and what gets injected. This request recalls memory, stores nothing new, and declines standing rules: ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -H "Cruxy-Version: 2026-09-26" \ -d '{ "model": "saga", "stream": false, "memory": { "recall": true, "capture": false }, "rules": false, "messages": [ { "role": "user", "content": "Which time zone should my meeting use?" } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', 'Cruxy-Version': '2026-09-26', }, body: JSON.stringify({ model: 'saga', stream: false, memory: { recall: true, capture: false }, rules: false, messages: [{ role: 'user', content: 'Which time zone should my meeting use?' }], }), }) const completion = await res.json() console.log(completion.message.content) console.log(completion.cruxy.memory_recall) // undefined when nothing was recalled ``` ## Versioning The API is versioned by date. Send `Cruxy-Version: YYYY-MM-DD` to pin a version, or omit it for the server's current default; an unknown or malformed value is rejected with `400`. Every response, errors included, echoes the resolved version in its `Cruxy-Version` header. A breaking change, such as a change to streaming frame order, ships under a new dated version. Additive fields, including new `cruxy.*` fields, ship without one, so ignore JSON fields you do not recognize. [Changelog](/docs/en/reference/changelog) records what changed. ## Next steps - [Get your API key](/docs/en/get-started/api-keys): mint the key every call needs. - [Quickstart](/docs/en/get-started/quickstart): make your first chat call. - [Streaming](/docs/en/build/streaming): read a chat completion as it is written. - [Errors and retries](/docs/en/build/errors-and-retries): handle failures. ================================================================================ Page: Quickstart URL: https://learn.cruxyai.com/docs/en/get-started/quickstart Markdown: https://learn.cruxyai.com/docs/en/get-started/quickstart.md ================================================================================ # Quickstart Get an API key with device login, then make your first chat call. You'll go from an empty terminal to your first model response against the `canto` tier. Every request in this guide goes to `https://api.cruxy.ai`. ## 1. Start device login Ask the gateway for a device code. This endpoint needs no authentication. ```bash curl -X POST https://api.cruxy.ai/api/v1/device/code ``` You get back a `user_code` to type, a URL to approve it, and the `device_code` your client polls with. ```json { "device_code": "cxy_dev_QK3f...redacted", "user_code": "WDJB-MJHT", "verification_uri": "https://cruxy.ai/device", "verification_uri_complete": "https://cruxy.ai/device?user_code=WDJB-MJHT", "expires_in": 600, "interval": 5 } ``` ## 2. Approve in the browser Open `verification_uri_complete` and approve the request. The `user_code` (`WDJB-MJHT`) is pre-filled; if you open the plain `verification_uri` instead, type it in by hand. You have `expires_in` seconds (600 = ten minutes) to finish. ## 3. Poll for the key Poll the token endpoint with your `device_code`, waiting `interval` seconds (5) between attempts. ```bash curl -X POST https://api.cruxy.ai/api/v1/device/token \ -H "Content-Type: application/json" \ -d '{ "device_code": "cxy_dev_QK3f...redacted" }' ``` > **Note:** Until someone approves, you get `400` with an `authorization_pending` > code. That is expected; keep polling. ```json { "code": "authorization_pending", "error": "authorization_pending", "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" } ``` Once approved, the same request returns `200` with your key. > **Warning:** The key is shown exactly once; there is no way to retrieve it again. > Copy it now and store it before you move on. ```json { "access_token": "cxy_live_...redacted", "token_type": "bearer", "key_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "user_id": "6f9c1e2a-1b2c-4d5e-8f90-1a2b3c4d5e6f", "expires_at": "2026-10-20T12:00:00.000Z", "org": { "id": "8c1a5b3e-2d4f-4a6b-9c8d-0e1f2a3b4c5d", "name": "Acme Corp", "role": "member" } } ``` Export it into your shell. Never commit a key to source control. ```bash export CRUXY_API_KEY="cxy_live_..." ``` For the full flow (every polling error code, verifying the key, and key hygiene), see [Get your API key](/docs/en/get-started/api-keys). ## 4. Make your first call Send a prompt to the `canto` tier. `stream: false`, which is also the default, asks for a single JSON response instead of a stream, so there is one block to read on a first call. ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "canto", "stream": false, "messages": [ { "role": "user", "content": "Hello" } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'canto', stream: false, messages: [{ role: 'user', content: 'Hello' }], }), }) const completion = await res.json() console.log(completion) ``` The response is one JSON object: the reply is the top-level `message`, with `finish_reason` and `usage` beside it, and the call's cost is `usage.cost`. Cruxy adds a namespaced `cruxy` block carrying the `request_id`, the `routed_tier`, and the `reasoning_effort`. See [Chat](/docs/en/build/chat) for the streaming form and the full request options. ## Where to go next - [Chat](/docs/en/build/chat): Streaming SSE, tiers, temperature, and the cruxy block. - [Get your API key](/docs/en/get-started/api-keys): The device-login flow end to end, the key format, and key hygiene. - [API Reference](/docs/en/reference/api): Every endpoint, typed and interactive. - [TypeScript SDK](/docs/en/sdk/typescript): The typed client for these endpoints: install @cruxy/api and call them as methods. ================================================================================ Page: Get your API key URL: https://learn.cruxyai.com/docs/en/get-started/api-keys Markdown: https://learn.cruxyai.com/docs/en/get-started/api-keys.md ================================================================================ # Get your API key Pick the right kind of key, mint a signed-in key with device login, verify it with GET /api/v1/me, and know when it expires. Every authenticated request sends a `cxy_live_` user key, and a user key is one of two kinds. A signed-in credential comes from device login and belongs in a person's own tool, such as a CLI or a desktop app. A developer API key is created in the Cruxy Console and belongs on a server. > **Warning:** Device login gives you a signed-in credential, with memory and standing rules on > by default. For a server, or anything that serves people other than you, use a > developer API key from the Cruxy Console. A signed-in key expires 90 days after > it is issued; revoke it yourself when you sign out. ## Two kinds of key | | Signed-in credential | Developer API key | | --- | --- | --- | | How you get it | Device login, or native OAuth login, whichever client runs the flow. | Created in the Cruxy Console. | | Use it for | A person's own tool, such as a CLI or a desktop app. | A server, and anything that serves people other than the key's owner. | | Memory and rules | On by default. | Off unless a request opts in. | | Expires | At `expires_at`, 90 days after issue. Use does not renew it. | Never. | | Rotate or revoke | Revoke it yourself with `DELETE /api/v1/me/key`. It cannot be rotated. | In the Console. | | Spend limits | A monthly spend cap. | The Console can limit it to chosen models and a monthly spend cap. | | Limits bucket | `subscription` | `apikey` | A signed-in credential on a server would recall its owner's memory into other people's turns, store what they say in that memory, and apply the owner's organization rules, unless every request sends `memory: {"recall": false, "capture": false}` and `rules: false`. A headless key, billed from prepaid credit, has memory and rules off by default, like a developer API key. To see which kind a key is, read `bucket` on `GET /api/v1/limits`; see [Rate limits and budgets](/docs/en/build/rate-limits#read-your-limits). A developer API key needs a paid plan, and the API can use up to 25% of the plan's usage; see [Plan limits](/docs/en/build/plan-limits). ## Device login Cruxy issues signed-in credentials through an [RFC 8628][rfc] device-authorization flow: your client asks for a code, a person approves it in a browser, and your client polls until the key is minted. The browser and the client can be different machines. [rfc]: https://datatracker.ietf.org/doc/html/rfc8628 The two device-login endpoints take no key and no `Authorization` header: their job is to issue one. Both are rate-limited and return `429` with `rate_limited` if you call them too often. 1. **Request a device code** `POST /api/v1/device/code` with no body. ```bash title="curl" curl -X POST https://api.cruxy.ai/api/v1/device/code ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/device/code', { method: 'POST', }) if (!res.ok) throw new Error(`device code request failed: ${res.status}`) const device = await res.json() console.log(`Open ${device.verification_uri_complete} to approve.`) console.log(`Confirm this code on that page: ${device.user_code}`) ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' // Device login takes no key. const cruxy = new Cruxy() const { result: device } = await cruxy.deviceLogin.startDeviceLogin() console.log(`Open ${device.verificationUriComplete} to approve.`) console.log(`Confirm this code on that page: ${device.userCode}`) ``` ```json { "device_code": "cxy_dev_QK3f...redacted", "user_code": "WDJB-MJHT", "verification_uri": "https://cruxy.ai/device", "verification_uri_complete": "https://cruxy.ai/device?user_code=WDJB-MJHT", "expires_in": 600, "interval": 5 } ``` | Field | Meaning | | --- | --- | | `device_code` | The code your client polls with. The person approving never needs it. | | `user_code` | The short code the person confirms in the browser. | | `verification_uri` | The approval page. The person types `user_code` there. | | `verification_uri_complete` | The approval page with `user_code` already filled in. | | `expires_in` | Seconds until `device_code` expires. | | `interval` | Seconds to wait between polls. | Read `verification_uri`, `expires_in`, and `interval` from each response rather than hardcoding the example values. 2. **Approve in the browser** Send the person to `verification_uri_complete`, or to `verification_uri` with the `user_code` to type. They approve the request before `expires_in` seconds pass. If they decline, polling returns `access_denied`. 3. **Poll for the key** `POST /api/v1/device/token` with the `device_code`, waiting `interval` seconds between attempts. Polling faster than the limiter allows returns `429` with `rate_limited`; wait the `Retry-After` seconds, then resume at `interval`. ```bash title="curl" # DEVICE_CODE holds the device_code from step 1. curl -X POST https://api.cruxy.ai/api/v1/device/token \ -H "Content-Type: application/json" \ -d "{\"device_code\": \"$DEVICE_CODE\"}" ``` ```ts title="TypeScript" // `device` is the response from step 1. const sleep = (seconds: number) => new Promise((r) => setTimeout(r, seconds * 1000)) async function pollForKey(device: { device_code: string; interval: number; expires_in: number }) { const deadline = Date.now() + device.expires_in * 1000 while (Date.now() < deadline) { await sleep(device.interval) const res = await fetch('https://api.cruxy.ai/api/v1/device/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ device_code: device.device_code }), }) if (res.ok) return res.json() if (res.status === 429) { // Polling faster than the limiter allows: honour Retry-After, then resume. await sleep(Number(res.headers.get('Retry-After')) || device.interval) continue } const { code, reason } = await res.json() if (code === 'authorization_pending') continue throw new Error(`device login stopped: ${code}${reason ? ` (${reason})` : ''}`) } throw new Error('device_code expired before approval; start a new device login') } const key = await pollForKey(device) // Store key.access_token in your secrets manager now. Log the id, never the key. console.log(`Minted key ${key.key_id} for ${key.org.name}, expires ${key.expires_at}`) ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' import type { DeviceCodeResponse } from '@cruxy/api/models' import { CruxyError, DeviceTokenPendingResponseError } from '@cruxy/api/models/errors' // `device` is the result of step 1. Device login takes no key. const cruxy = new Cruxy() const sleep = (seconds: number) => new Promise((r) => setTimeout(r, seconds * 1000)) async function pollForKey(device: DeviceCodeResponse) { const interval = device.interval const deadline = Date.now() + device.expiresIn * 1000 while (Date.now() < deadline) { await sleep(interval) try { const { result } = await cruxy.deviceLogin.pollDeviceToken({ body: { deviceCode: device.deviceCode }, }) return result } catch (err) { // Polling faster than the limiter allows: honour Retry-After, then resume. if (err instanceof CruxyError && err.statusCode === 429) { await sleep(err.retryAfter ?? interval) continue } if (err instanceof DeviceTokenPendingResponseError && err.code === 'authorization_pending') { continue } // Refused for good: access_denied, expired_token, or invalid_grant. // err.reason refines it, such as org_membership_revoked. throw err } } throw new Error('device_code expired before approval; start a new device login') } const key = await pollForKey(device) // Store key.accessToken in your secrets manager now. Log the id, never the key. console.log(`Minted key ${key.keyId} for ${key.org.name}, expires ${key.expiresAt.toISOString()}`) ``` Until the flow resolves, the endpoint returns `400` with an OAuth-style body carrying `code`, `error`, and `request_id`: ```json { "code": "authorization_pending", "error": "authorization_pending", "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" } ``` Only `authorization_pending` means keep polling: | `code` | Meaning | What to do | | --- | --- | --- | | `authorization_pending` | Not approved yet. | Wait `interval` seconds and poll again. | | `access_denied` | The person declined. | Stop. | | `expired_token` | The `device_code` expired. | Start a new device login. | | `invalid_grant` | The `device_code` is not valid. | Start a new device login. | A refusal can also carry `reason` and `error_description`. The one `reason` today is `org_membership_revoked`: the login was approved for an organization the account no longer belongs to. A new login succeeds, but it may bind to a different organization, so tell the person instead of retrying silently. Branch on `reason`; `error_description` is for people and is not meant to be parsed. On approval the endpoint returns `200` with the key: ```json { "access_token": "cxy_live_...redacted", "token_type": "bearer", "key_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "user_id": "6f9c1e2a-1b2c-4d5e-8f90-1a2b3c4d5e6f", "expires_at": "2026-10-20T12:00:00.000Z", "org": { "id": "8c1a5b3e-2d4f-4a6b-9c8d-0e1f2a3b4c5d", "name": "Acme Corp", "role": "member" } } ``` > **Warning:** The key is returned exactly once. Store it before you do anything else. ## What the token response tells you | Field | Meaning | | --- | --- | | `access_token` | Your API key. Send it as `Authorization: Bearer `. | | `token_type` | `bearer`. | | `key_id` | The key's id. Safe to log. | | `user_id` | The account the key belongs to. | | `expires_at` | When the key stops working, 90 days after issue. Record it with the key; see [Expiry and revocation](#expiry-and-revocation). | | `org` | The one organization this key is bound to: its `id`, `name`, and your `role` in it (`owner`, `admin`, or `member`). | A key is bound to exactly one organization, fixed when it is issued. That organization decides which shared memory, rules, vaults, and conversations the key can reach. A login is not always bound to the same organization as your previous one, so show `org.name` to the person after every login, and read `org.role` rather than inferring authority from anything else. ## Key format | Prefix | What it is | | --- | --- | | `cxy_live_` | A user key, either kind: what you send as a Bearer token. | | `cxy_svc_` | A service token, minted by an operator. It is not a user key, and an endpoint that expects one rejects the other with `401`. | Treat everything after the prefix as opaque. ## Verify the key `GET /api/v1/me` echoes the identity behind a key. Call it once after you store a new key to confirm it works end to end. ```bash title="curl" curl https://api.cruxy.ai/api/v1/me \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/me', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) if (!res.ok) throw new Error(`key check failed: ${res.status}`) const me = await res.json() console.log(`key ${me.api_key_id} belongs to user ${me.user_id}`) ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) // Throws a CruxyError with status 401 when the key does not work. const { result: me } = await cruxy.auth.getCurrentIdentity() console.log(`key ${me.apiKeyId} belongs to user ${me.userId}`) ``` ```json { "api_key_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "user_id": "6f9c1e2a-1b2c-4d5e-8f90-1a2b3c4d5e6f" } ``` A `200` means the key works. A `401` `unauthorized` means it is missing, malformed, unknown, expired, or revoked: the same answer for each. Check the `Authorization` header, then the key itself, then its `expires_at`. ## Expiry and revocation - **A signed-in credential stops working at `expires_at`,** 90 days after issue. The time is fixed when the key is issued: use does not extend it, and there is no refresh grant. Prompt for a new device login before it passes. - **A developer API key does not expire.** Rotate or revoke it in the Console. - **Any key can revoke itself** with `DELETE /api/v1/me/key`, a signed-in credential included. Call it when a person signs out of your tool; see [Revoke the current key](#revoke-the-current-key). A signed-in credential cannot be rotated, so otherwise it ends at `expires_at`, when its organization membership ends, or when Cruxy support revokes it. - **An expired, revoked, or unknown key is `401` `unauthorized`,** with `WWW-Authenticate: Bearer`. A key whose owner's account is suspended is `403` `account_suspended`. - **Revocation applies from the next request,** since nothing is cached. A stream already running is not cut. ## Revoke the current key `DELETE /api/v1/me/key` revokes the key that authenticates the request, and only that key. It takes no key id, so it cannot reach any other credential: other keys of the same account stay live, and usage already recorded against this key is kept. Call it when a person signs out, so the key stops working now rather than at `expires_at`. ```bash title="curl" curl -X DELETE https://api.cruxy.ai/api/v1/me/key \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/me/key', { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) // 204: revoked. 401: the key was already unusable. Either way it is signed out. if (res.status !== 204 && res.status !== 401) { throw new Error(`revoke failed: ${res.status}`) } ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) // Resolves with the response headers (there is no body) once the key is revoked. await cruxy.auth.revokeCurrentKey() ``` | Status | Meaning | | --- | --- | | `204` | Revoked. The key stops authenticating as soon as this returns. | | `401` `unauthorized` | The key is missing, malformed, unknown, expired, or already revoked, so it is already unusable. A repeat of a successful revoke gets this. | | `403` `key_scope_forbidden` | The key's allowed scopes exclude the `account` family. | | `403` `key_read_only` | The key is read-only, and revoking is a change. | Treat `204` and `401` as signed out, then delete the stored key. Neither `403` clears by waiting: revoke a developer API key in the Console instead. The revoke is recorded in your organization's audit trail. ## What a key is allowed to do A key can carry restrictions. A request outside them is refused: | Restriction | Refusal | | --- | --- | | Allowed scopes: the endpoint families the key may call, and whether it may use memory, rules, or files | `403` `key_scope_forbidden`, naming `required_scope` when a request field asked for a family the key lacks | | Model allowlist: the tiers the key may call | `403` `model_not_allowed` | | Read-only: the key may not perform billable operations | `403` `key_read_only` | | Monthly spend cap | `429` `key_spend_cap_exceeded` | A `403` never clears by waiting; re-scope the key or issue a new one. For a developer API key, the Console sets the model allowlist and the monthly spend cap. Memory recall, memory capture, and your organization's standing rules are on by default for a signed-in credential, which includes every key device login mints, and off by default for a developer API key. To get the same behavior from any key, set `memory` and `rules` on each chat request; see [Memory](/docs/en/build/memory) and [Standing rules](/docs/en/build/rules). ## Keep the key safe - **Treat it like a password.** Anyone who holds it can call the API as you. - **Keep it on the server.** Never ship a key to a browser. Put a server route between the browser and the gateway that adds the key; see [Streaming chat in the browser](/docs/en/resources/cookbook/streaming-ui). - **Read it from the environment.** Keep it in an environment variable or a secrets manager, never in source control. Every sample on this site reads `CRUXY_API_KEY`. - **Use a developer API key on a server.** A signed-in credential carries its owner's memory and rules into every request, and expires. - **Revoke a signed-in credential on sign-out.** Call `DELETE /api/v1/me/key` before you delete the stored key, so a copy left behind stops working too. - **Store it the moment it is issued.** The token endpoint returns it once; if you lose it, run device login again for a new key. - **Log the `key_id`, never the key.** `key_id` and `expires_at` identify a key and tell you when to replace it. - **Use one key per environment.** Separate keys for local, staging, and production keep each `key_id` meaningful in your logs. - **Issue the narrowest key a service needs.** A key whose allowed scopes omit memory can never read or write anyone's memory through chat. - **Send it only to `https://api.cruxy.ai`.** ## Next steps - [Authentication](/docs/en/get-started/authentication): send the key on every request. - [Quickstart](/docs/en/get-started/quickstart): make your first chat call. - [Errors and retries](/docs/en/build/errors-and-retries): handle `401`, `403`, and every other error code. ================================================================================ Page: Authentication URL: https://learn.cruxyai.com/docs/en/get-started/authentication Markdown: https://learn.cruxyai.com/docs/en/get-started/authentication.md ================================================================================ # Authentication Send your Cruxy API key as a Bearer token in the Authorization header on every authenticated request. Every authenticated endpoint reads one header: `Authorization: Bearer` followed by your `cxy_live_` key. To mint a key, confirm it works, and store it safely, see [Get your API key](/docs/en/get-started/api-keys). ## The Authorization header Send the key on every authenticated request: ```bash title="curl" curl https://api.cruxy.ai/api/v1/me \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/me', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) console.log(res.status, await res.json()) ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result } = await cruxy.auth.getCurrentIdentity() console.log(result) ``` The same key and header work on the OpenAI-compatible routes, `POST /v1/chat/completions` and `GET /v1/models`: point an OpenAI client at the base URL `https://api.cruxy.ai/v1` and give it your Cruxy key as its API key. [Migrate from OpenAI](/docs/en/migrate/from-openai) covers the rest of the switch. ## Endpoints that take no key These endpoints are public: | Endpoint | Why it is public | | --- | --- | | `POST /api/v1/device/code`, `POST /api/v1/device/token` | Device login issues keys. | | `POST /api/v1/auth/oauth/start`, `POST /api/v1/auth/oauth/token` | Native sign-in issues keys. | | `GET /api/status`, `GET /api/health`, `GET /api/ready` | Platform status and health probes. | ## When the key is rejected A `401` `unauthorized` means the key is missing, malformed, unknown, expired, or revoked: the same answer for each. A signed-in key stops working at its `expires_at`; see [Expiry and revocation](/docs/en/get-started/api-keys#expiry-and-revocation). Check the `Authorization` header, then [verify the key](/docs/en/get-started/api-keys#verify-the-key). A `403` means the key is valid but its authority does not cover the call: | `code` | Meaning | | --- | --- | | `key_scope_forbidden` | The key is not scoped for this endpoint family, or for the memory, rules, or files feature a request field asked for. | | `model_not_allowed` | The key's model allowlist excludes the requested tier. | | `key_read_only` | The key may not perform billable operations. | A `403` never clears by waiting: re-scope the key or issue a new one. [Errors and retries](/docs/en/build/errors-and-retries) lists every error code. ## Next steps - [Get your API key](/docs/en/get-started/api-keys): device login, key format, and key hygiene. - [Chat](/docs/en/build/chat): make an authenticated chat call. - [API Reference](/docs/en/reference/api): which endpoints require a key. ================================================================================ Page: Migrate from OpenAI URL: https://learn.cruxyai.com/docs/en/migrate/from-openai Markdown: https://learn.cruxyai.com/docs/en/migrate/from-openai.md ================================================================================ # Migrate from OpenAI Move an OpenAI client to Cruxy: change the base URL and the key, pass a tier as the model, and know what carries over and what differs. Cruxy serves OpenAI-compatible chat completions at `POST /v1/chat/completions` and an OpenAI-compatible model list at `GET /v1/models`. Both take OpenAI's request and return OpenAI's response, so code written for the official `openai` npm package moves over with three changes: the base URL, the API key, and `model`. ## Change three settings | Setting | Set it to | | --- | --- | | Base URL | `https://api.cruxy.ai/v1` | | API key | Your Cruxy API key, read from `CRUXY_API_KEY`. It travels as `Authorization: Bearer `, as on OpenAI. | | `model` | A Cruxy tier, `canto`, `saga`, or `epos`, or `auto` to let the router pick one. | The key needs the `chat` endpoint family, the same as for `POST /api/v1/chat`; a key without it is `403`. On a server, use a developer API key from the Cruxy Console: [Get your API key](/docs/en/get-started/api-keys) covers the kinds of key and how to create one. Authentication, rate limits, and billing work as they do on `POST /api/v1/chat`. ## Before and after The same request, first to OpenAI, then to Cruxy. Only the base URL, the key, and `model` change; the request body and the response you read stay the same. ```bash title="Before (curl)" # OPENAI_MODEL is the OpenAI model id you call today. curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "'"$OPENAI_MODEL"'", "messages": [ { "role": "user", "content": "Hello" } ] }' ``` ```bash title="After (curl)" curl https://api.cruxy.ai/v1/chat/completions \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "canto", "messages": [ { "role": "user", "content": "Hello" } ] }' ``` ```ts title="Before (TypeScript)" import OpenAI from 'openai' const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }) const completion = await client.chat.completions.create({ // The OpenAI model id you call today. model: process.env.OPENAI_MODEL ?? '', messages: [{ role: 'user', content: 'Hello' }], }) console.log(completion.choices[0].message.content) ``` ```ts title="After (TypeScript)" import OpenAI from 'openai' const client = new OpenAI({ apiKey: process.env.CRUXY_API_KEY, baseURL: 'https://api.cruxy.ai/v1', }) const completion = await client.chat.completions.create({ model: 'canto', messages: [{ role: 'user', content: 'Hello' }], }) console.log(completion.choices[0].message.content) ``` ## Pass a tier as model `model` takes a tier or `auto`. Any other value, an OpenAI model id included, is `400` `invalid_request`. These docs map no OpenAI model to a tier: the model behind a tier is never exposed, and it can change while the tier stays the same. Choose a tier by its profile, then test it on your own prompts. | `model` | Profile | Default `reasoning_effort` | `max_tokens` cap | | --- | --- | --- | --- | | `canto` | Deep | `high` | 65,536 | | `saga` | Balanced | `low` | 131,072 | | `epos` | Fast | `none` | 131,072 | | `auto` | The router picks a tier for each request. | Chosen per request | The cap of the tier that serves | The response's `model` is the tier that served the request. With `auto`, it is the tier the router chose, which a budget can also have downgraded, so read it rather than assume it. [Choosing a tier](/docs/en/build/choosing-a-tier) compares the tiers, and [Auto routing](/docs/en/build/auto-routing) covers what the router does. `GET /v1/models` returns OpenAI's list shape, `{"object": "list", "data": [...]}`, and its ids are the tiers. For each tier's context window, output cap, tool support, and reasoning defaults, read `GET /api/v1/models`; see [Models](/docs/en/reference/models). ## What carries over unchanged - **The request.** `messages` with the `system`, `user`, `assistant`, and `tool` roles, plus `temperature`, `top_p`, `max_tokens`, `stream`, `stream_options`, `tools`, `tool_choice`, `response_format`, and `reasoning_effort`. - **The response.** A `chat.completion` object with `id`, `object`, `created`, `model`, `choices[].message`, `choices[].finish_reason` (`stop`, `tool_calls`, `length`, or `content_filter`), and `usage` with `prompt_tokens`, `completion_tokens`, and `total_tokens`. - **Streaming.** `chat.completion.chunk` frames that end with `data: [DONE]`, and a usage frame only when you set `stream_options.include_usage`. - **Tool calling.** `tools` and `tool_choice` on the request, `tool_calls` on the assistant message, and a `tool` message with `tool_call_id` for each result. - **Errors.** OpenAI's envelope, `{"error": {"message", "type", "param", "code"}}`, which the SDK raises as an `APIError`. ## What differs - **`model` is a tier,** and the response's `model` names the tier that served. - **Fields Cruxy does not implement are ignored, not rejected:** `n`, `stop`, `seed`, `presence_penalty`, `frequency_penalty`, `logit_bias`, `logprobs`, `user`, and the rest. A request that sends them still runs, and they have no effect. - **`max_tokens` is clamped to the tier's cap, and thinking spends it.** `canto` thinks by default, so a small `max_tokens` on `canto` can end with `finish_reason: "length"` and empty content. `max_completion_tokens` is accepted as an alias of `max_tokens`, and wins when you send both. - **`reasoning_effort` takes `none`, `low`, `medium`, or `high`.** Any other value, OpenAI's `minimal` included, is `400` `invalid_request`. - **A non-streaming call has a deadline:** 90 seconds on `canto` and `saga`, 45 on `epos`. Past it, the call is `504` `upstream_timeout`. - **An error's `code` is a Cruxy code,** and `param` is always `null`. - **The route carries none of the Cruxy-native chat features:** no memory, no standing rules, no vaults, no `file_ids`, and no `cruxy` block. For those, call `POST /api/v1/chat`; see [Chat](/docs/en/build/chat). - **The request ID is only in a header,** `X-Request-Id`, and the response's `usage` carries no cost. - **A tool call's `id` may not start with `call_`.** Treat it as opaque. [OpenAI SDK compatibility](/docs/en/migrate/openai-sdk-compatibility) covers each of these parameter by parameter, with streaming, errors, and how the SDK retries. ## Next steps - [OpenAI SDK compatibility](/docs/en/migrate/openai-sdk-compatibility): what the route supports, ignores, and rejects. - [Choosing a tier](/docs/en/build/choosing-a-tier): pick the tier to pass as `model`. - [Reasoning effort](/docs/en/build/reasoning-effort): keep thinking from spending your `max_tokens`. - [Known limitations](/docs/en/build/known-limitations): the limits to plan around. ================================================================================ Page: OpenAI SDK compatibility URL: https://learn.cruxyai.com/docs/en/migrate/openai-sdk-compatibility Markdown: https://learn.cruxyai.com/docs/en/migrate/openai-sdk-compatibility.md ================================================================================ # OpenAI SDK compatibility What POST /v1/chat/completions supports, ignores, and rejects from an OpenAI request, and how its streams, tool calls, and errors behave in the openai SDK. `POST /v1/chat/completions` is the route the official `openai` npm package calls when you set `baseURL` to `https://api.cruxy.ai/v1`. It runs your messages on the tier you name and nothing else: no memory, no standing rules, and no `cruxy` block, so a run is reproducible. This page goes field by field through what it does with an OpenAI request. To move a client over first, see [Migrate from OpenAI](/docs/en/migrate/from-openai). ## Request parameters | Parameter | Status | Behavior | | --- | --- | --- | | `model` | Supported | `canto`, `saga`, `epos`, or `auto`. Required. The former ids `kavi`, `vaani`, and `mira` are still accepted; see [Deprecated aliases](/docs/en/reference/models#deprecated-aliases). | | `messages` | Supported | Required. Each message has a `role`, one of `system`, `user`, `assistant`, or `tool`, and a string `content`. An assistant message can replay `tool_calls`, and a `tool` message needs `tool_call_id`. | | `max_tokens` | Supported, clamped | Unset, or above the tier's cap, is clamped to the cap: 65,536 on `canto`, 131,072 on `saga` and `epos`. Thinking is generated inside it. Ignored when `max_completion_tokens` is also sent. | | `max_completion_tokens` | Supported, clamped | OpenAI's newer name for `max_tokens`, with the same meaning and the same clamp. When a request sends both, `max_completion_tokens` is used and `max_tokens` is ignored. | | `temperature` | Supported | Forwarded upstream unchanged; the gateway adds no bound of its own. Omit it for the model's default. | | `top_p` | Supported | Forwarded upstream unchanged. `0` is a real value, so sending it is not the same as omitting it. Omit it for the model's default. | | `stream` | Supported | `false` by default. | | `stream_options` | Supported | `include_usage: true` adds the usage frame to a stream. Ignored when `stream` is `false`. | | `reasoning_effort` | Supported | `none`, `low`, `medium`, or `high`. Omit it for the tier's default. | | `tools` | Supported | Functions the model may call: `type: "function"`, with `function.name`, `description`, and a JSON Schema `parameters`. | | `tool_choice` | Supported | `"none"`, `"auto"`, `"required"`, or `{"type": "function", "function": {"name": "…"}}` to force one function. | | `response_format` | Supported | `{"type": "text"}`, `{"type": "json_object"}`, or `{"type": "json_schema", "json_schema": {"name", "schema", "strict"}}`. | | `n`, `stop`, `seed`, `presence_penalty`, `frequency_penalty`, `logit_bias`, `logprobs`, `user` | Ignored | Accepted and not applied, so a request that sends them still runs. | | Any other OpenAI field | Ignored | The route ignores the OpenAI fields it does not implement. | | `file_ids` | Rejected | The file attachments of `POST /api/v1/chat` are refused here. | `messages` takes the four roles above; OpenAI's `developer` role is not one of them, so send your instructions as a `system` message. ### Requests the route rejects These requests fail with a `4xx` and the code shown: | Request | Status and `code` | | --- | --- | | `model` other than `canto`, `saga`, `epos`, `auto`, or a deprecated alias | `400` `invalid_request` | | `reasoning_effort` other than `none`, `low`, `medium`, or `high`, OpenAI's `minimal` included | `400` `invalid_request` | | `tool_choice` names a function that is not in `tools`, or is `"required"` with no tools | `400` `invalid_request` | | A tool's `parameters` schema exceeds a bound on bytes, depth, or nodes | `400` `invalid_tool_schema` | | A `response_format` JSON schema is malformed, oversized, too deep, or uses an unsupported keyword | `400` `invalid_schema` | | The input exceeds the tier's context window | `400` `context_overflow` | | The server-side input moderation gate refuses the request's text | `400` `moderation_rejected`, not billed | | The turn brings more new text than the moderation gate reads in one request | `400` `moderation_input_too_large`, not billed; `limit_bytes` is not carried in this envelope | | `response_format` on a tier that does not do constrained decoding | `422` `structured_output_unsupported` | | An `Idempotency-Key` reused with a different body | `409` `idempotency_conflict` | One more `422` comes after the model call: `structured_output_unsatisfied` means the output did not satisfy your `json_schema`. That request is billed, and it may pass on a retry. ## Response fields With `stream: false`, the response is a standard `chat.completion` object: | Field | Value | | --- | --- | | `id` | The completion id, such as `chatcmpl-8f3a1c2d`. | | `object` | `chat.completion`. | | `created` | Unix seconds at which the completion was produced. | | `model` | The tier that served the request. With `auto`, the tier the router chose. | | `choices[].message` | The assistant message, with `tool_calls` when the model called tools. | | `choices[].finish_reason` | `stop`, `tool_calls`, `length`, or `content_filter`. | | `choices[].logprobs` | Always `null`. The key is there because OpenAI sends it. | | `usage` | `prompt_tokens`, `completion_tokens`, and `total_tokens`, plus `prompt_tokens_details.cached_tokens` when the prompt cache was involved. | The response has no `cruxy` block, no `request_id`, and no cost. ## Cruxy extensions in the SDK Every Cruxy extension this route honors is either a typed SDK parameter or a header, so you never need an untyped body field: - **`reasoning_effort`** is OpenAI's own parameter, typed in `chat.completions.create`, with Cruxy's values: send only `none`, `low`, `medium`, or `high`, although the SDK's type allows more. `canto` thinks at `high` by default, `saga` at `low`, and `epos` not at all. See [Reasoning effort](/docs/en/build/reasoning-effort). - **`Idempotency-Key`** is a request header; pass it in the SDK's per-request `headers` option. The first success under a key is stored for 24 hours, and a retry with the same key and body replays it without calling the model or billing again. Only a success is stored, and only with `stream: false`. The SDK does not send this header for you. See [Reliability](/docs/en/build/reliability). - **`X-Request-Id`** is on every response, and it is the only request ID this route returns. The SDK exposes it as `_request_id` on a result and as `requestID` on an error. Send your own, up to 128 characters of `[A-Za-z0-9_-]`, and the gateway reuses it. See [Request IDs and metadata](/docs/en/build/request-ids). ```bash title="curl" # -i prints the response headers, including X-Request-Id. curl -i https://api.cruxy.ai/v1/chat/completions \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "model": "canto", "reasoning_effort": "none", "max_tokens": 256, "messages": [ { "role": "user", "content": "In one sentence, what is a monsoon?" } ] }' ``` ```ts title="TypeScript" import { randomUUID } from 'node:crypto' import OpenAI from 'openai' const client = new OpenAI({ apiKey: process.env.CRUXY_API_KEY, baseURL: 'https://api.cruxy.ai/v1', }) const completion = await client.chat.completions.create( { model: 'canto', // Thinking off: the whole max_tokens budget goes to the answer. reasoning_effort: 'none', max_tokens: 256, messages: [{ role: 'user', content: 'In one sentence, what is a monsoon?' }], }, // The SDK resends the same headers when it retries, so a retry after a // dropped connection replays a stored success instead of billing again. { headers: { 'Idempotency-Key': randomUUID() } }, ) console.log(completion.choices[0].message.content) console.log(completion.model, completion._request_id) ``` ### Memory and standing rules This route does no memory recall, no memory capture, and no standing-rules injection, and it takes no `vault_id`. There is nothing to pass through the SDK to turn them on. To use them, call `POST /api/v1/chat` or `POST /api/v2/chat` with `fetch`: the SDK's `chat.completions` methods call `/chat/completions` under the base URL, so they cannot reach either route. See [Memory](/docs/en/build/memory) and [Standing rules](/docs/en/build/rules). ## Tool calls Tool calling keeps OpenAI's shapes. Declare `tools`, and when `finish_reason` is `tool_calls`, run each call in `message.tool_calls`, append the assistant message and one `tool` message per call, and call again. A tool call's `id` is a string with no documented format. It may not start with `call_`, even though examples show `call_abc123`. Copy it unchanged into `tool_call_id`, and never parse, validate, or build one; see [Tool-call IDs may not use OpenAI's call\_ format](/docs/en/build/known-limitations#tool-call-ids-may-not-use-openais-call_-format). ```ts import OpenAI from 'openai' const client = new OpenAI({ apiKey: process.env.CRUXY_API_KEY, baseURL: 'https://api.cruxy.ai/v1', }) const tools: OpenAI.ChatCompletionTool[] = [ { type: 'function', function: { name: 'get_weather', description: 'Get the current weather for a city', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'], }, }, }, ] const messages: OpenAI.ChatCompletionMessageParam[] = [ { role: 'user', content: 'Is it raining in Pune?' }, ] let completion = await client.chat.completions.create({ model: 'saga', tools, messages }) while (completion.choices[0].finish_reason === 'tool_calls') { const message = completion.choices[0].message messages.push(message) for (const call of message.tool_calls ?? []) { if (call.type !== 'function') continue const args = JSON.parse(call.function.arguments) // Echo the id exactly as it arrived; do not assume a call_ prefix. messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify({ city: args.city, raining: true }), }) } completion = await client.chat.completions.create({ model: 'saga', tools, messages }) } console.log(completion.choices[0].message.content) ``` ## Streaming With `stream: true`, the route speaks OpenAI's Server-Sent Events protocol, in this order: 1. A role primer: the first `chat.completion.chunk`. 2. Content deltas in `choices[0].delta.content`, or tool-call fragments in `choices[0].delta.tool_calls`, which you assemble per `index`. 3. A frame that carries `finish_reason`. 4. With `stream_options: {"include_usage": true}` only, a usage frame: `choices` is an empty array and `usage` is complete. Check `choices` before you index it. 5. `data: [DONE]`. If the model fails after the stream has opened, the stream ends with a `data: {"error": {...}}` frame instead of `[DONE]`, so a cut-off answer never looks finished. The SDK throws that frame as an `APIError` from the loop: catch it and discard the partial text. The gateway retries a failing model only while the stream opens, never after a byte has reached you, and a stream may run for up to five minutes. ```bash title="curl" # -N turns off buffering so frames print as they arrive. curl -N https://api.cruxy.ai/v1/chat/completions \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "saga", "stream": true, "stream_options": { "include_usage": true }, "messages": [ { "role": "user", "content": "Write a haiku about monsoon rain." } ] }' ``` ```ts title="TypeScript" import OpenAI from 'openai' const client = new OpenAI({ apiKey: process.env.CRUXY_API_KEY, baseURL: 'https://api.cruxy.ai/v1', }) const stream = await client.chat.completions.create({ model: 'saga', stream: true, stream_options: { include_usage: true }, messages: [{ role: 'user', content: 'Write a haiku about monsoon rain.' }], }) let text = '' try { for await (const chunk of stream) { // The usage frame has an empty choices array. if (chunk.choices.length > 0) text += chunk.choices[0].delta.content ?? '' if (chunk.usage) console.log('usage:', chunk.usage) } } catch (err) { // A failure after the stream opened arrives as a data: {"error": ...} frame, // and the SDK throws it here. The partial text is not a finished answer. throw new Error('stream failed before it finished', { cause: err }) } console.log(text) ``` A stream stores and replays nothing under `Idempotency-Key`. A retry with the same key and body streams a new generation; when both attempts complete, the request is billed once. [Streaming](/docs/en/build/streaming) covers the stream of `POST /api/v1/chat`, which differs: it sends no error frame. ## Errors Errors on `POST /v1/chat/completions` and `GET /v1/models` use OpenAI's envelope: ```json { "error": { "code": "unauthorized", "message": "unauthorized", "param": null, "type": "authentication_error" } } ``` - **`code`** is the stable Cruxy error code, the same vocabulary as the rest of the API. Branch on it. - **`type`** is a coarse category derived from the HTTP status: `invalid_request_error`, `authentication_error`, `permission_error`, `not_found_error`, `rate_limit_error`, or `server_error`. - **`param`** is always `null`: no error on this route names the field at fault. Only the code travels. The detail fields a Cruxy error adds next to `code`, such as `tier`, `reason`, or `hazard_codes`, are not part of this envelope, on any code. The `/api/v1` routes use Cruxy's own envelope instead. The two differ in where each value sits: | Item | `/v1/chat/completions` and `/v1/models` | `/api/v1` routes | | --- | --- | --- | | Envelope | `{"error": {"message", "type", "param", "code"}}` | `{"code", "error", "request_id", ...}` | | The code to branch on | `error.code` | `code` | | The message | `error.message` | `error` | | The request ID | The `X-Request-Id` header only | `request_id` in the body | | Detail fields such as `reset_at`, `epos_available`, or `limit` | Not carried | In the body | Because this envelope has no place for the detail fields, read the headers instead: every `429` carries `Retry-After`, and the `X-RateLimit-*` headers describe the per-minute request window. [Errors and retries](/docs/en/build/errors-and-retries) lists every code and which ones to retry. The SDK throws a non-2xx response as an `APIError`, with the status in `status`, the Cruxy code in `code`, and `X-Request-Id` in `requestID`: ```bash title="curl" # OpenAI's "minimal" is not a Cruxy reasoning_effort, so this is a 400. curl -i https://api.cruxy.ai/v1/chat/completions \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "canto", "reasoning_effort": "minimal", "messages": [ { "role": "user", "content": "Hello" } ] }' ``` ```ts title="TypeScript" import OpenAI from 'openai' const client = new OpenAI({ apiKey: process.env.CRUXY_API_KEY, baseURL: 'https://api.cruxy.ai/v1', }) try { await client.chat.completions.create({ model: 'canto', // OpenAI's "minimal" is not a Cruxy reasoning_effort, so this is a 400. reasoning_effort: 'minimal', messages: [{ role: 'user', content: 'Hello' }], }) } catch (err) { if (!(err instanceof OpenAI.APIError)) throw err // 400 invalid_request, and the X-Request-Id to quote in a support request. console.error(err.status, err.code, err.requestID) } ``` ### Retries in the SDK The `openai` package retries a failed request twice by default: after a connection error, and on `408`, `409`, `429`, and any `5xx`. It waits for `Retry-After` when that is 60 seconds or less. Against Cruxy, three of those retries are unlikely to help: - **`504` `upstream_timeout`.** The gateway made one attempt and does not retry it, and the same request usually takes as long again. Stream long turns, or lower `max_tokens` or `reasoning_effort`, rather than rely on the retry. - **`429` spend and budget codes,** such as `budget_exhausted`. They clear only at their reset, and their `Retry-After` can be days away, so a retry sooner fails the same way. Branch on `code` and stop retrying them. - **`409` `idempotency_conflict`.** The key was reused with a different body, and the SDK resends that same body. Send the new body under a new key. A `504` or a `429` is not billed. To make the SDK's retries after a dropped connection safe, send an `Idempotency-Key`, as the extensions sample does. ## Known differences These are the places where this route behaves unlike OpenAI's, collected in one list: - `model` takes a tier or `auto`, and the response's `model` is the tier that served, never an upstream model id. - Fields the route does not implement are ignored without an error, so a `stop` sequence or `n` has no effect. - Thinking spends `max_tokens` and is not returned; see [Canto's thinking spends max_tokens](/docs/en/build/known-limitations#cantos-thinking-spends-max_tokens). - A non-streaming call ends at the tier's deadline with `504` `upstream_timeout`; see [Non-streaming calls have a 90-second ceiling](/docs/en/build/known-limitations#non-streaming-calls-have-a-90-second-ceiling). - A tool call's `id` may not use the `call_` format; see [Tool-call IDs may not use OpenAI's call\_ format](/docs/en/build/known-limitations#tool-call-ids-may-not-use-openais-call_-format). - `error.code` is a Cruxy code, `param` is always `null`, and the detail fields of a Cruxy error do not travel. - The response carries no request ID in its body and no cost in its `usage`. - No memory, standing rules, vaults, or file attachments. [Known limitations](/docs/en/build/known-limitations) lists the limits that apply across the API, each with a workaround. ## Next steps - [Migrate from OpenAI](/docs/en/migrate/from-openai): change the base URL, the key, and `model`. - [Chat](/docs/en/build/chat): the Cruxy-native route, with memory, standing rules, and the `cruxy` block. - [Errors and retries](/docs/en/build/errors-and-retries): every error code, and which ones to retry. - [Known limitations](/docs/en/build/known-limitations): the limits to plan around. ================================================================================ Page: Chat URL: https://learn.cruxyai.com/docs/en/build/chat Markdown: https://learn.cruxyai.com/docs/en/build/chat.md ================================================================================ # Chat OpenAI-compatible chat completions across the Cruxy tiers, streaming or not. `POST /api/v1/chat` runs an OpenAI-compatible chat completion. You pick a public tier, send a list of messages, and read back either a single JSON completion or a stream of Server-Sent Events. Here is the smallest complete call: ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "canto", "stream": false, "messages": [ { "role": "user", "content": "Hello" } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'canto', stream: false, messages: [{ role: 'user', content: 'Hello' }], }), }) const completion = await res.json() ``` ## Tiers, not provider models `model` is a **public tier**, one of: | Tier | Profile | | --- | --- | | `canto` | Deep | | `saga` | Balanced | | `epos` | Fast | The gateway resolves each tier to an upstream provider model on the server. You never send or receive an upstream provider id. Tiers are the stable contract, so your code keeps working when the backing model changes. [Choosing a tier](/docs/en/build/choosing-a-tier) compares them; to discover the catalog at runtime rather than hardcoding these strings, see [Models](/docs/en/reference/models). `model` also accepts `"auto"`, which hands tier selection to the gateway's router. It resolves to a concrete tier before billing and the upstream call, and `routed_tier` on the response (see [The cruxy block](#the-cruxy-block)) names the tier that served. [Auto routing](/docs/en/build/auto-routing) covers what the router guarantees. ## Request options Beyond `model` and `messages`, the request accepts: | Field | Type | Example | Purpose | | --- | --- | --- | --- | | `stream` | boolean | `true` | Stream SSE chunks. Optional and `false` by default, which returns one JSON object. | | `temperature` | number | `0.7` | Sampling temperature. | | `max_tokens` | integer | `1024` | Cap on tokens generated. | | `reasoning_effort` | string | `"medium"` | How much the model thinks before answering: `none`, `low`, `medium`, or `high` (see [Reasoning effort](/docs/en/build/reasoning-effort)). | | `tools` | array | | Functions the model may call (see [Define tools](/docs/en/build/tools)). | | `tool_choice` | string or object | `"auto"` | Whether and which tool the model calls. | | `memory` | object | `{ "recall": true }` | Memory recall and capture for this request (see [Memory](/docs/en/build/memory)). | | `rules` | boolean | `false` | Standing-rules injection for this request (see [Standing rules](/docs/en/build/rules)). | Each `messages` entry has a `role` and `content`. Assistant turns that call tools carry `tool_calls`, and your replies to those calls carry a `tool_call_id`; both are covered in [Handle tool calls](/docs/en/build/tool-calls). ## Streaming vs. not `stream` controls the response format. ### stream: false This is what you get when you omit `stream`: a single JSON object. Cruxy flattens it: the assistant reply is the top-level `message`, alongside `finish_reason`, `usage`, and the `cruxy` block. There is no OpenAI `choices[]` array. Read `message.content` directly, not `choices[0].message`. ```json { "id": "chatcmpl-8f3a1c2d", "model": "canto", "message": { "role": "assistant", "content": "Namaste." }, "finish_reason": "stop", "usage": { "input_tokens": 12, "output_tokens": 48, "billable_input_tokens": 12, "cache_read_tokens": 0, "cache_write_tokens": 0, "cost": { "tier": "canto", "amount": "", "currency": "" } }, "cruxy": { "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "routed_tier": "canto", "reasoning_effort": "high" } } ``` `` and `` are placeholders: a real `amount` is a number. See [Usage and cost](/docs/en/build/usage-and-cost) for the full `cost` object. ### stream: true You get an OpenAI-style Server-Sent Events stream: a sequence of `chat.completion.chunk` events, each on a `data:` line, terminated by a final `data: [DONE]`. Unlike the non-streaming reply, a chunk uses the OpenAI `choices[]` shape: each token arrives in `choices[0].delta.content`. ```bash curl -N https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "canto", "stream": true, "messages": [ { "role": "user", "content": "Write a haiku about monsoon rain." } ] }' ``` `data: [DONE]` is the only signal that the completion finished: a stream that ends without it failed partway. [Streaming](/docs/en/build/streaming) covers the frame order, the chunk and usage shapes, a complete TypeScript reader, and how to detect a failed stream. ## The cruxy block Cruxy-native fields are additive and namespaced under a `cruxy` key. They never alter the OpenAI-shaped fields, so a vanilla OpenAI client parses the response unchanged and ignores the extra key. On a chat response the block carries three fields for the turn: - `request_id`: a UUID for the call, e.g. `a1b2c3d4-e5f6-7890-abcd-ef1234567890`. Log it; it identifies the call in support requests and pairs with [Feedback](/docs/en/build/feedback). - `routed_tier`: the tier that actually served the request. This is how you learn which tier ran when you send `model: "auto"`. - `reasoning_effort`: the effort the call ran at, after any tier default is applied. When they apply, the block also reports what the turn recalled, captured, or injected: `memory_recall`, `memory_capture`, `rules_applied`, `files_omitted`, and `undeclared_tool_replay`. When the tier reasoned, `reasoning` holds its thinking trace, kept out of `message`; see [Reasoning effort](/docs/en/build/reasoning-effort#see-the-thinking). [Request IDs and metadata](/docs/en/build/request-ids#the-cruxy-block) lists every field, and how to quote `request_id` when you report a problem. Cost and token counts are not in this block; they live in `usage`. ## Usage Every chat response carries a `usage` object with the token accounting and the call's `cost`. The token fields depend on the response mode: non-streaming uses `input_tokens` and `output_tokens`; streaming uses `prompt_tokens`, `completion_tokens`, and `total_tokens`. Both can also carry `billable_input_tokens`, `cache_read_tokens`, and `cache_write_tokens`; on a stream each is omitted when it is zero. `usage.cost` breaks down the price of the call: | Field | Meaning | | --- | --- | | `tier` | The public tier that served the request. | | `amount` | Total cost of the call. | | `currency` | Currency of `amount`. | | `input_unit` | Input rate, per million tokens. | | `output_unit` | Output rate, per million tokens. | | `cache_read_unit` | The rate for cached reads, per million tokens: the tier's own cache-read rate where it has one, otherwise `input_unit` × the cache discount. | Amounts and rates are specific to your account and shown in your Cruxy Console. [Usage and cost](/docs/en/build/usage-and-cost) covers which tokens are billed and how a stream reports usage. ## Errors Chat returns `400` for a malformed request, `401` `unauthorized` for a missing, expired, or revoked key, `429` when you hit a limit, such as `rate_limited` or `budget_exhausted`, and `5xx` when the model call fails. With `stream: false` the gateway makes one attempt, bounded by the tier's deadline; an attempt that runs past it is `504` `upstream_timeout`, which the gateway does not retry and does not bill (see [Timeouts](/docs/en/build/errors-and-retries#timeouts)). See [Errors](/docs/en/reference/errors) for the response shape, [Errors and retries](/docs/en/build/errors-and-retries) for every code and which ones to retry, and [Rate limits and budgets](/docs/en/build/rate-limits) for how to tell a rate limit from a budget. ## Next steps - [Streaming](/docs/en/build/streaming): read the SSE stream and detect a failed one. - [Define tools](/docs/en/build/tools): let the model call your functions. - [Reasoning effort](/docs/en/build/reasoning-effort): keep thinking from spending your `max_tokens`. - [Known limitations](/docs/en/build/known-limitations): the limits to plan around, such as the 90-second non-streaming ceiling. - [Streaming chat in the browser](/docs/en/resources/cookbook/streaming-ui): consume the SSE stream in a UI. - [Models](/docs/en/reference/models): discover tiers at runtime. - [Errors and retries](/docs/en/build/errors-and-retries): handle `400`, `401`, and `429`, and retry safely. ================================================================================ Page: Streaming URL: https://learn.cruxyai.com/docs/en/build/streaming Markdown: https://learn.cruxyai.com/docs/en/build/streaming.md ================================================================================ # Streaming Read chat completions as Server-Sent Events: the frame order, the chunk and usage shapes, and how to tell a finished stream from a failed one. `stream` is optional and `false` by default. With `stream: true`, `POST /api/v1/chat` answers with `text/event-stream`: OpenAI-style Server-Sent Events in which every event is one `chat.completion.chunk` JSON object on a `data:` line. The stream ends with the literal line `data: [DONE]`, and that line is the only signal that the completion finished. ```bash title="curl" curl -N https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "saga", "stream": true, "messages": [ { "role": "user", "content": "Write a haiku about monsoon rain." } ] }' | tee stream.txt # The completion finished only if the stream ended with [DONE]. grep -q '^data: \[DONE\]' stream.txt || echo "stream failed before [DONE]" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'saga', stream: true, messages: [{ role: 'user', content: 'Write a haiku about monsoon rain.' }], }), }) if (!res.ok || !res.body) throw new Error(`chat failed: ${res.status} ${await res.text()}`) const reader = res.body.getReader() const decoder = new TextDecoder() let buffer = '' let text = '' let finishReason: string | null = null let usage: Record | undefined let sawDone = false read: while (true) { const { value, done } = await reader.read() if (done) break buffer += decoder.decode(value, { stream: true }) const lines = buffer.split('\n') buffer = lines.pop() ?? '' // keep a partial line for the next read for (const raw of lines) { const line = raw.trim() if (!line.startsWith('data:')) continue const data = line.slice('data:'.length).trim() if (data === '[DONE]') { sawDone = true break read } const chunk = JSON.parse(data) if (chunk.usage) usage = chunk.usage const choice = chunk.choices[0] // undefined on the usage frame if (!choice) continue if (choice.delta.content) text += choice.delta.content if (choice.finish_reason) finishReason = choice.finish_reason } } if (!sawDone) { // The stream ended early: a failed completion, not a short one. throw new Error('stream ended before [DONE]; discard the partial output') } console.log(text) console.log(finishReason, usage) ``` ## Frame order A successful stream sends these frames, in this order: | # | Frame | `choices` | What it carries | | --- | --- | --- | --- | | 1 | Role primer | One element; `delta` is `{"role": "assistant", "content": ""}` | The turn's `cruxy` block: `routed_tier`, `request_id`, and `reasoning_effort`, plus `memory_recall` and `rules_applied` when they apply. | | 2 | Content or tool-call deltas, zero or more | One element; `delta` has a `content` fragment or `tool_calls` fragments, never both | The answer, piece by piece. `finish_reason` is `null`. | | 2 | Reasoning frames, zero or more, among the deltas | One element; `delta` is `{}` and `finish_reason` is `null` | `cruxy.reasoning`: one fragment of the tier's thinking trace. See [Reasoning frames](#reasoning-frames). | | 3 | Finish | One element; `delta` is `{}` | `finish_reason`. No usage. | | 4 | Usage | `[]`, an empty array | The final `usage` object, plus `cruxy.memory_capture` when the turn stored memory. | | 5 | `data: [DONE]` | | Nothing. It is not JSON; do not parse it. | On the wire: ```text data: {"id":"chatcmpl-8f3a1c2d","object":"chat.completion.chunk","model":"saga","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}],"cruxy":{"routed_tier":"saga","request_id":"a1b2c3d4-e5f6-7890-abcd-ef1234567890","reasoning_effort":"low"}} data: {"id":"chatcmpl-8f3a1c2d","object":"chat.completion.chunk","model":"saga","choices":[{"index":0,"delta":{"content":"Clouds lean"},"finish_reason":null}]} data: {"id":"chatcmpl-8f3a1c2d","object":"chat.completion.chunk","model":"saga","choices":[{"index":0,"delta":{"content":" on the hills"},"finish_reason":null}]} data: {"id":"chatcmpl-8f3a1c2d","object":"chat.completion.chunk","model":"saga","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]} data: {"id":"chatcmpl-8f3a1c2d","object":"chat.completion.chunk","model":"saga","choices":[],"usage":{"prompt_tokens":12,"completion_tokens":48,"total_tokens":60,"cost":{"amount":,"currency":"","tier":"saga",...}}} data: [DONE] ``` Changing the framing or this order is a breaking change that ships only under a new dated `Cruxy-Version`, so you can rely on it. New `cruxy.*` fields can appear without a version change, so ignore fields you do not recognize. ## The chunk | Field | Meaning | | --- | --- | | `id` | The completion id. | | `object` | `chat.completion.chunk`. | | `model` | The tier. | | `choices` | One element on every frame that carries output; an empty array on the usage frame. | | `choices[0].index` | `0`. | | `choices[0].delta` | The fragment: `role` on the primer, then `content` or `tool_calls`, then `{}` on the finish frame. A reasoning frame's `delta` is `{}` too. | | `choices[0].finish_reason` | `null` until the finish frame, then `stop`, `tool_calls`, `length`, or `content_filter`. | | `usage` | Present only on the usage frame. | | `cruxy` | The Cruxy-native block; see [Chat](/docs/en/build/chat#the-cruxy-block). | > **Warning:** Check that `choices` is non-empty before you read `choices[0]`. The usage frame > has `choices: []` and arrives on every successful stream, so indexing it > unguarded crashes every time. The role primer's `content` is an empty string, not absent. Appending every `content` you see is safe; the primer adds nothing. ### Tool-call deltas When the model calls a tool, deltas carry `tool_calls` fragments instead of `content`. Every fragment has an `index` and a piece of `function.arguments`, a JSON string; fragments can also carry the call's `id`, `type`, and `function.name`. Assemble the fragments per `index`, concatenating the `arguments` pieces. A finish frame with `finish_reason: "tool_calls"` means the fragments are complete: run the calls and answer them as [Handle tool calls](/docs/en/build/tool-calls) describes. ## Reasoning frames When a tier reasons, the stream carries its thinking trace beside the answer. Each fragment rides a frame of its own, among the content deltas: `delta` is an empty object, `finish_reason` is `null`, and the `cruxy` block holds only `reasoning`. ```text data: {"id":"chatcmpl-8f3a1c2d","object":"chat.completion.chunk","model":"canto","choices":[{"index":0,"delta":{},"finish_reason":null}],"cruxy":{"reasoning":"The user wants 17*23."}} ``` - Concatenate the fragments in order for the trace. It is not part of the answer: never append it to `content`, and do not send it back in the conversation. - A reasoning frame has an empty `delta`, as the finish frame does. Detect the finish frame by a non-null `finish_reason`, never by the empty `delta`. - The trace changes no figure and no bill. `usage` already counts the thinking inside the output tokens, and there is no separate reasoning-token count. Reasoning frames are sent from `Cruxy-Version: 2026-11-12`, and when a request sends no `Cruxy-Version`. A request pinned to an earlier date receives none, and its stream is the one in the table above without them. A non-streaming response carries the whole trace as `cruxy.reasoning`; see [Reasoning effort](/docs/en/build/reasoning-effort#see-the-thinking). ### Thought lines A thought line is a few words saying what one part of the thinking trace is doing, such as `Comparing the three forecasts`, so a client can show progress in plain words. It arrives as `cruxy.reasoning_summary` on a frame of its own, shaped like a reasoning frame: an empty `delta`, a `null` `finish_reason`, and a `cruxy` block that holds only `reasoning_summary`. | Field | Meaning | | --- | --- | | `index` | Which part of the trace the line describes, counted from 0. | | `text` | The line: plain text, under 60 characters, in the language of the user's message. | | `start`, `end` | The half-open span `[start, end)` of that part in the concatenated `reasoning` fragments, counted in Unicode code points. | A turn carries at most 12 thought lines, always before the finish frame. They are best-effort: a line that is late or fails is never sent, so a part of the trace can have none, and lines can arrive out of order. Key on `index`. The gateway writes them and does not bill them: they add nothing to `usage`. Whether a deployment sends thought lines at all is a switch you read, not assume: `cruxy.reasoning_summaries` on `GET /api/v1/models`. - **`false`:** no turn gets thought lines. - **`true`:** a turn gets them only when it is a stream from a signed-in credential that pins `Cruxy-Version: 2026-11-13` or later. A request with no `Cruxy-Version` does not get them. A developer or headless key never gets them, whatever the switch says, and `POST /v1/chat/completions` never sends them. When a turn does not qualify, the stream is exactly the one before `2026-11-13`. `GET /v1/models` does not carry the switch. ```bash title="curl" curl -s https://api.cruxy.ai/api/v1/models \ -H "Authorization: Bearer $CRUXY_API_KEY" \ | jq '.cruxy.reasoning_summaries' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/models', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) const { cruxy } = await res.json() // Only a signed-in credential's stream, pinned to 2026-11-13 or later, can // get thought lines, and only when this is true. const showThoughtLines: boolean = cruxy.reasoning_summaries console.log('thought lines on this deployment:', showThoughtLines) ``` ## The usage frame The usage frame is the only frame with `usage`, and it is never merged into the finish frame before it, because an OpenAI-compatible client reads usage only from the frame whose `choices` is empty. | Field | Meaning | | --- | --- | | `prompt_tokens` | Input tokens. | | `completion_tokens` | Output tokens. | | `total_tokens` | The sum. | | `billable_input_tokens`, `cache_read_tokens`, `cache_write_tokens` | Omitted when zero; absence means zero. | | `prompt_tokens_details` | The prompt-cache breakdown, present only when the prompt cache was used. | | `cost` | An object, not a number: `amount`, `currency`, `tier`, and the per-million-token rates `input_unit`, `output_unit`, and `cache_read_unit`. Read `cost.amount` for a scalar. | A stream names its token fields the OpenAI way (`prompt_tokens`, `completion_tokens`); a non-streaming response uses `input_tokens` and `output_tokens`. [Usage and cost](/docs/en/build/usage-and-cost) covers both shapes, the `cost` object, and which tokens are billed. ## [DONE] is the only success signal Once the stream opens, the `200` is already sent. If the completion fails after that, no error frame follows: the gateway stops sending and closes the response without the finish frame, the usage frame, or `data: [DONE]`. > **Important:** A stream that ends before `data: [DONE]`, whether the body closes or a read > returns end-of-stream, is a failed, incomplete completion. Discard the partial > output or retry; never present it as a finished answer. The tokens already > delivered are real and are billed as a partial usage row. To detect it on the client: 1. Set a flag when you read `data: [DONE]`, as the sample above does with `sawDone`. 2. When the read loop ends, treat a missing flag as a failure. 3. Treat an exception from the read itself, such as a dropped connection, as a failure too. A stream that ends with `[DONE]` is complete, but the answer can still be cut short: `finish_reason: "length"` means the output reached `max_tokens` or the tier's cap. On `canto`, which reasons by default, a small `max_tokens` can be spent entirely on thinking; see [Features overview](/docs/en/get-started/features#three-tiers-and-auto). The gateway retries a failing model only while the stream opens, never after a byte has reached you. A stream may run for up to five minutes. A stream stores and replays nothing under `Idempotency-Key`, since a stream cannot be replayed: a retry with the same key and body streams a new generation. When both attempts complete, the request is billed once. An attempt that did not complete is billed for the tokens it delivered, and the retry is billed as well. ## Other chat wires The rules above are for `POST /api/v1/chat`. The other two chat endpoints end their streams differently: - `POST /api/v2/chat` sends named events (`start`, `reasoning`, `delta`, and `reasoning_summary` for a thought line, on the same terms) and always ends with exactly one `finish` or `error` frame. It has no `[DONE]`; a stream that closes without `finish` or `error` failed. - `POST /v1/chat/completions` ends a stream that fails after it opens with a `data: {"error": {...}}` frame instead of `[DONE]`. It sends the usage frame only when the request sets `stream_options: {"include_usage": true}`. To render a stream in a browser without exposing your key, see [Streaming chat in the browser](/docs/en/resources/cookbook/streaming-ui). ## Next steps - [Chat](/docs/en/build/chat): the request options and the non-streaming response. - [Reliability](/docs/en/build/reliability): retry a stream that failed, and the deadlines it avoids. - [Handle tool calls](/docs/en/build/tool-calls): answer the tool calls a stream returns. - [Errors and retries](/docs/en/build/errors-and-retries): what to retry, and how. ================================================================================ Page: Embeddings URL: https://learn.cruxyai.com/docs/en/build/embeddings Markdown: https://learn.cruxyai.com/docs/en/build/embeddings.md ================================================================================ # Embeddings Turn text into vectors with the cruxy-embed model. `POST /api/v1/embeddings` takes one string or an array and returns a vector per input, ready to store and compare for search, clustering, or retrieval. It is OpenAI-compatible. Here is a single-string embedding: ```bash title="curl" curl https://api.cruxy.ai/api/v1/embeddings \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "cruxy-embed", "input": "The quick brown fox" }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/embeddings', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'cruxy-embed', input: 'The quick brown fox', }), }) const { data } = await res.json() const vector = data[0].embedding // number[] ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) // The SDK's `input` is an array: send one string as a one-element array. const { result } = await cruxy.embeddings.createEmbeddings({ body: { model: 'cruxy-embed', input: ['The quick brown fox'] }, }) const vector = result.data[0]?.embedding // number[] ``` ## The model `model` must be `"cruxy-embed"`. It is the only embedding model on the gateway. ## Single string or array `input` accepts either a single string or an array of strings. Pass an array to embed a batch in one call: ```bash curl https://api.cruxy.ai/api/v1/embeddings \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "cruxy-embed", "input": ["The quick brown fox", "jumps over the lazy dog"] }' ``` Each input maps to one entry in `data`, and the entry's `index` matches the position of its input. ## Response shape ```json { "object": "list", "model": "cruxy-embed", "data": [ { "object": "embedding", "index": 0, "embedding": [0.0023, -0.0117] } ], "usage": { "prompt_tokens": 8, "total_tokens": 8 }, "cruxy": { "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "cost": { "tier": "cruxy-embed" } } } ``` The `embedding` array is shown truncated; a real vector holds many more floats. The `cost` object carries the same fields documented under [Chat](/docs/en/build/chat#usage). | Field | Meaning | | --- | --- | | `object` | Always `"list"`. | | `data` | One `embedding` entry per input, each with its `index` and `embedding` vector. | | `usage` | `prompt_tokens` and `total_tokens` for the request. | | `cruxy` | Additive block with the `request_id` and `cost` (see [Chat](/docs/en/build/chat#the-cruxy-block)). | The `embedding` array holds the vector as floating-point numbers. Read a result at `data[i].embedding`, matching `data[i].index` to your input's position. ## Errors Embeddings returns `400` for a malformed request, `401` for a bad key, `429` for `rate_limited` or `budget_exhausted`, and the model failures, which nothing bills: `502` `upstream_error` (the provider rejected the request; it fails the same way again, so do not retry it), `503` `upstream_overloaded`, `model_unavailable`, `service_unavailable`, `server_shutting_down`, or `limits_unavailable`, and `504` `upstream_timeout`. Retry the `503`s and the `504` with backoff; see [Embeddings, rerank, and moderations](/docs/en/build/reliability#embeddings-rerank-and-moderations). [Errors](/docs/en/reference/errors) lists every code. ## Next steps - [Retrieval-augmented generation](/docs/en/resources/cookbook/rag): index a corpus and answer from it, end to end. - [Rerank](/docs/en/build/rerank): order retrieved candidates against a query. - [Chat](/docs/en/build/chat): completions across the tiers. - [Errors](/docs/en/reference/errors): the error shape. ================================================================================ Page: Rerank URL: https://learn.cruxyai.com/docs/en/build/rerank Markdown: https://learn.cruxyai.com/docs/en/build/rerank.md ================================================================================ # Rerank Order candidate documents against a query with the cruxy-rerank model. `POST /api/v1/rerank` scores each candidate document against your query and returns them best-first, so you can pick the strongest matches from a shortlist. Here is a working request: ```bash title="curl" curl https://api.cruxy.ai/api/v1/rerank \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "cruxy-rerank", "query": "What is the capital of France?", "documents": [ "Paris is the capital and largest city of France.", "Berlin is the capital of Germany.", "The Louvre is a museum in Paris.", "France is in Western Europe." ], "top_n": 3 }' ``` ```ts title="TypeScript" const documents = [ 'Paris is the capital and largest city of France.', 'Berlin is the capital of Germany.', 'The Louvre is a museum in Paris.', 'France is in Western Europe.', ] const res = await fetch('https://api.cruxy.ai/api/v1/rerank', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'cruxy-rerank', query: 'What is the capital of France?', documents, top_n: 3, }), }) const { results } = await res.json() const top = results[0] // highest relevance_score const topDocument = documents[top.index] ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const documents = [ 'Paris is the capital and largest city of France.', 'Berlin is the capital of Germany.', 'The Louvre is a museum in Paris.', 'France is in Western Europe.', ] const { result } = await cruxy.rerank.rerankDocuments({ body: { model: 'cruxy-rerank', query: 'What is the capital of France?', documents, topN: 3, }, }) const top = result.results[0] // highest relevanceScore const topDocument = top && documents[top.index] ``` ## The model `model` must be `"cruxy-rerank"`. It is the only rerank model on the gateway. ## Not OpenAI-compatible Most of the gateway mirrors the OpenAI shape. This endpoint does not; it follows a Cohere-style rerank contract instead. There is no `object` envelope, and the results carry **indices into your input**, not the document text. Map each `index` back to your own `documents` array to recover the text, as the TypeScript example does above. ## Request fields | Field | Type | Example | Purpose | | --- | --- | --- | --- | | `model` | string | `"cruxy-rerank"` | Must be `"cruxy-rerank"`. | | `query` | string | `"What is the capital of France?"` | Scored against each document. | | `documents` | array | | Candidate strings to rank. | | `top_n` | integer | `3` | Cap on how many results come back. Omit to rank every document. | ## Ranking and top_n Every document is scored against `query`, and the response is sorted by `relevance_score` in **descending** order, the most relevant document first. `top_n` caps how many results return; with `top_n: 3` over four documents, only the top three come back. Omit `top_n` to get all of them, still ranked. ## Response shape ```json { "model": "cruxy-rerank", "results": [ { "index": 0, "relevance_score": 0.98 }, { "index": 2, "relevance_score": 0.71 }, { "index": 3, "relevance_score": 0.12 } ], "usage": { "prompt_tokens": 8, "total_tokens": 8 }, "cruxy": { "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "cost": { "tier": "cruxy-rerank" } } } ``` | Field | Meaning | | --- | --- | | `model` | Always `"cruxy-rerank"`. | | `results` | Ranked entries, `relevance_score` descending, capped to `top_n`. | | `index` | Position of the document in the request `documents` array. | | `relevance_score` | Relevance of that document to `query`; higher is more relevant. | | `usage` | `prompt_tokens` and `total_tokens` for the request. | | `cruxy` | Additive block with the `request_id` and `cost` (see [Chat](/docs/en/build/chat#the-cruxy-block)). | Each result's `index` points back into the `documents` you sent, so read the ranked text as `documents[results[i].index]`. A dropped document (one below the `top_n` cut) has no entry. ## Where it fits Rerank and [Embeddings](/docs/en/build/embeddings) are the two retrieval primitives on the gateway, and they work at different stages. A common pattern is to retrieve broadly with embeddings, then rerank the top candidates to settle their final order. | | Embeddings | Rerank | | --- | --- | --- | | Model id | `cruxy-embed` | `cruxy-rerank` | | What it does | Turns text into vectors you compare with cosine similarity. | Scores each candidate document against the query directly. | | Best for | A first-pass search over a large corpus. | Ordering a shortlist before you use it. | | Learn more | [Embeddings](/docs/en/build/embeddings) | [Retrieval-augmented generation](/docs/en/resources/cookbook/rag) | ## Errors Rerank returns `400` for a malformed request, `401` for a bad key, `429` for `rate_limited` or `budget_exhausted`, and the model failures, which nothing bills: `502` `upstream_error` (the provider rejected the request; it fails the same way again, so do not retry it), `503` `upstream_overloaded`, `model_unavailable`, `service_unavailable`, `server_shutting_down`, or `limits_unavailable`, and `504` `upstream_timeout`. Retry the `503`s and the `504` with backoff; see [Embeddings, rerank, and moderations](/docs/en/build/reliability#embeddings-rerank-and-moderations). [Errors](/docs/en/reference/errors) lists every code. ## Next steps - [Retrieval-augmented generation](/docs/en/resources/cookbook/rag): the embeddings-to-chat recipe this endpoint sits in. - [Embeddings](/docs/en/build/embeddings): the vectors you retrieve candidates with. - [Models](/docs/en/reference/models): discover tiers at runtime. - [Errors](/docs/en/reference/errors): the error shape. ================================================================================ Page: Moderations URL: https://learn.cruxyai.com/docs/en/build/moderations Markdown: https://learn.cruxyai.com/docs/en/build/moderations.md ================================================================================ # Moderations Classify text against content-safety categories with the cruxy-guard model. `POST /api/v1/moderations` checks text against the content-safety categories and returns whether each one matched, plus an overall `flagged`. It is OpenAI-compatible. Here is a single-string check: ```bash title="curl" curl https://api.cruxy.ai/api/v1/moderations \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "cruxy-guard", "input": "I want to learn how to bake bread." }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/moderations', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'cruxy-guard', input: 'I want to learn how to bake bread.', }), }) const { results } = await res.json() if (results[0].flagged) { // handle flagged content } ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) // The SDK's `input` is an array: send one string as a one-element array. const { result } = await cruxy.moderations.createModeration({ body: { model: 'cruxy-guard', input: ['I want to learn how to bake bread.'] }, }) if (result.results[0]?.flagged) { // handle flagged content } ``` ## The model `model` must be `"cruxy-guard"`. It is the only moderation model on the gateway. ## Single string or array `input` accepts a single string or an array of strings. With an array, `results` holds one entry per input, in order. ## Response shape ```json { "id": "modr-a1b2c3d4-e5f6-7890-abcd-ef1234567890", "model": "cruxy-guard", "results": [ { "flagged": false, "categories": { "example_category": false }, "category_scores": { "example_category": 0.0 } } ] } ``` | Field | Meaning | | --- | --- | | `flagged` | `true` when the guard flagged the input. Check this first. A flagged result can have every category `false`; `cruxy.hazard_codes` on the result then names the guard's own codes. | | `categories` | Map of category name to a boolean: whether that category matched. | | `category_scores` | Map of category name to a score. See the caveat below. | `cruxy.hazard_codes` holds the guard's raw codes (MLCommons S-codes), uppercased, in the order the guard emitted them. Nine of the fourteen codes map onto an OpenAI category. The other five map onto none: `S6` (specialized advice), `S7` (privacy), `S8` (intellectual property), `S13` (elections), and `S14` (code interpreter abuse). That is why a flagged result can have every category `false`. On a flagged result the list is never null and may be empty, when the guard flagged the input without naming a code; an unflagged result has no `cruxy` key. `categories` and `category_scores` share the same keys, one per moderation category. The keys shown above are illustrative; treat the category set as whatever the response returns rather than a fixed list. ## category_scores is binary The scores are **not** calibrated probabilities. The guard model emits labels, not likelihoods, so each value in `category_scores` is either `1.0` or `0.0`, the same information as the boolean in `categories`, expressed as a number. Do not threshold these scores or read them as confidence. To decide whether to act, use `flagged` (or the per-category booleans in `categories`). To run this check in front of a chat call, see the [Moderation gate](/docs/en/resources/cookbook/moderation-gate) recipe. ## Errors Moderations returns `400` for a malformed request, `401` for a bad key, `429` for `rate_limited` or a spend cap (`key_spend_cap_exceeded`, `workspace_spend_cap_exceeded`, `credits_exhausted`), never `budget_exhausted`, and the model failures, which nothing bills: `502` `upstream_error` (the provider rejected the request; it fails the same way again, so do not retry it), `503` `upstream_overloaded`, `model_unavailable`, `service_unavailable`, `server_shutting_down`, or `limits_unavailable`, and `504` `upstream_timeout`. Retry the `503`s and the `504` with backoff; see [Embeddings, rerank, and moderations](/docs/en/build/reliability#embeddings-rerank-and-moderations). [Errors](/docs/en/reference/errors) lists every code. ## Next steps - [Moderation gate](/docs/en/resources/cookbook/moderation-gate): screen input before it reaches chat. - [Chat](/docs/en/build/chat): completions across the tiers. - [Errors](/docs/en/reference/errors): the error shape. ================================================================================ Page: Feedback URL: https://learn.cruxyai.com/docs/en/build/feedback Markdown: https://learn.cruxyai.com/docs/en/build/feedback.md ================================================================================ # Feedback Report the outcome of a prior call: accepts, rejects, thumbs, test results. `POST /api/v1/feedback` records how an earlier call turned out (an edit accepted or rejected, a thumbs rating, or a generated test's result), attached to that call by its `request_id`. Here is a working request: ```bash title="curl" curl https://api.cruxy.ai/api/v1/feedback \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "type": "thumbs", "consent": true, "payload": { "value": "up" } }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/feedback', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ request_id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', type: 'thumbs', consent: true, payload: { value: 'up' }, }), }) const { stored } = await res.json() // 202 Accepted; see below ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result } = await cruxy.feedback.submitFeedback({ body: { requestId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', type: 'thumbs', consent: true, payload: { value: 'up' }, }, }) const { stored } = result // 202 Accepted; see below ``` ## Joining to a prior call `request_id` ties the feedback to the call it is about. It is the same UUID the gateway returns in the `cruxy.request_id` field of a chat, embeddings, or rerank response. A moderations response carries it as the top-level `id`, prefixed `modr-`, which you strip; see [the cruxy block](/docs/en/build/chat#the-cruxy-block). Log that id when you make a call, then send it back here when you learn the outcome. ## Event types `type` must be one of: | Value | | | --- | --- | | `edit_accepted` | | | `edit_rejected` | | | `thumbs` | | | `test_result` | | Each `type` fixes the shape of `payload`, and the gateway validates it, rejecting unknown keys, wrong types, missing required fields, and bad enum values with a `400`. `edit_accepted` and `edit_rejected` share one shape; `thumbs` and `test_result` each have their own. The [API Reference](/docs/en/reference/api) carries the exact fields for each; the request above sends a `thumbs` payload. ## Request fields | Field | Type | Example | Purpose | | --- | --- | --- | --- | | `request_id` | string | `"a1b2c3d4-…"` | The prior call this feedback is about. | | `type` | string | `"thumbs"` | One of the values above. | | `consent` | boolean | `true` | Whether this event may be stored. See [What gets stored](#what-gets-stored). | | `payload` | object | | Event data; its shape is fixed by `type` and validated (see [Event types](#event-types)). | ## What gets stored Feedback is privacy-gated, and the gate is strict. Two things decide whether an event is kept: - `consent`: the per-event boolean you send. - The account's opt-out: a setting outside this request. The outcomes are: - **Not consented, or the account has opted out**: the event is dropped entirely. No row is written and the payload is never stored. The response has `stored: false`. - **Consented, and not opted out**: a row is written, but its payload is redacted. The event is recorded; the payload you sent is not kept verbatim. The payload you send is never persisted as-is. A dropped event keeps nothing; a stored event keeps its payload with secrets and personal data redacted. Do not rely on reading the raw payload back later. ## The response A valid event **always returns `202 Accepted`**, for a stored event and for a dropped one alike. A `202` means the event was accepted for processing, not that it was stored, so read `stored` to tell the two apart. ```json { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "stored": true } ``` | Field | Meaning | | --- | --- | | `stored` | `true` if a row was written (payload redacted), `false` if the event was dropped. | | `id` | Identifier for the stored event. | ## Errors Feedback returns `400` for a malformed request, `401` for a bad key, and `404` `request_not_found` for a `request_id` that is not a call your account made. A privacy drop is **not** an error; it still returns `202` with `stored: false`. See [Errors](/docs/en/reference/errors). ## Next steps - [Chat](/docs/en/build/chat#the-cruxy-block): where `request_id` comes from. - [Errors](/docs/en/reference/errors): the error shape. ================================================================================ Page: Conversations URL: https://learn.cruxyai.com/docs/en/build/conversations Markdown: https://learn.cruxyai.com/docs/en/build/conversations.md ================================================================================ # Conversations Store chat history on the server: create a conversation, append each turn, list and count the shelves, search your own messages, and archive. A conversation is chat history the gateway stores for you, so a thread can be reopened on another device. You store each turn yourself: send it to [Chat](/docs/en/build/chat), then append the user message and the reply. Conversations are private to their author. No other member of the organization, an owner or admin included, can read, list, or search one. ## Create a conversation and append a turn `POST /api/v1/conversations` creates a conversation. Every field is optional: `title` and `model` are presentation only, `vault_id` holds it inside a vault you can write to, and `source` is `chat` (the default) or `cli` for a Cruxy Code session. `POST /api/v1/conversations/{id}/messages` appends one message with a `role` of `system`, `user`, `assistant`, or `tool`, and its `content`. ```bash title="curl" # 1. Create the conversation and keep its id. CONVERSATION_ID=$(curl -s https://api.cruxy.ai/api/v1/conversations \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' | sed -E 's/.*"id":"([^"]+)".*/\1/') # 2. Append the user's message. The first user message titles the conversation. curl https://api.cruxy.ai/api/v1/conversations/$CONVERSATION_ID/messages \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "role": "user", "content": "Why is this query doing a seq scan?" }' # 3. Append the reply you got from chat, with what you know about it. curl https://api.cruxy.ai/api/v1/conversations/$CONVERSATION_ID/messages \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "role": "assistant", "content": "The planner chose a seq scan because the estimate is low.", "status": "complete", "routed_tier": "saga", "routing_mode": "explicit", "reply_ms": 14200, "input_tokens": 48210 }' ``` ```ts title="TypeScript" const base = 'https://api.cruxy.ai/api/v1' const headers = { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', } async function post(path: string, body: unknown, idempotencyKey?: string) { const res = await fetch(`${base}${path}`, { method: 'POST', headers: idempotencyKey ? { ...headers, 'Idempotency-Key': idempotencyKey } : headers, body: JSON.stringify(body), }) if (!res.ok) throw new Error(`${path} failed: ${res.status} ${await res.text()}`) return res.json() } // 1. Create the conversation. const conversation = await post('/conversations', {}) // 2. Append the user's message. The first user message titles the conversation. const question = 'Why is this query doing a seq scan?' await post( `/conversations/${conversation.id}/messages`, { role: 'user', content: question }, crypto.randomUUID(), ) // 3. Ask chat, timing the reply. const sentAt = Date.now() const completion = await post('/chat', { model: 'saga', stream: false, messages: [{ role: 'user', content: question }], }) // 4. Append the reply, with what the response says about it. const stored = await post( `/conversations/${conversation.id}/messages`, { role: 'assistant', content: completion.message.content, status: completion.finish_reason === 'length' ? 'incomplete' : 'complete', ...(completion.finish_reason === 'length' && { incomplete_reason: 'length' }), routed_tier: completion.cruxy.routed_tier, routing_mode: 'explicit', // 'auto' when you send model: 'auto' reply_ms: Date.now() - sentAt, input_tokens: completion.usage.input_tokens, }, crypto.randomUUID(), ) console.log(stored.message.id, stored.conversation.title) ``` The `201` carries the stored `message`, the `conversation` as it now stands, and `leaf_moved`. The gateway assigns each message's `sequence`, so concurrent appends cannot collide or reorder the transcript. An append moves the conversation's `updated_at` and its `retention_until`, the deadline after which the conversation and its messages are deleted: 365 days from last activity by default. Send an `Idempotency-Key` header with every append. A retry with the same key and body replays the stored `201` instead of writing the turn twice, and the same key with a different body is `409` `idempotency_conflict`; see [Errors and retries](/docs/en/build/errors-and-retries#make-retries-idempotent). `content` is required, except on an assistant message that carries `tool_calls`, and holds at most 1,048,576 bytes of UTF-8; longer is `400` `invalid_request`. An agentic turn must carry its tool fields: `tool_calls` on the assistant message that requested them, and `tool_call_id` on each `tool` result. A user message can attach up to 20 files in `file_ids`, on a request that pins `Cruxy-Version: 2026-10-06` or later. ## Record what a reply did An append can store facts about the reply beside its text, so a client can show them again when the conversation is reopened. All are optional, each is written once, and a read omits the ones that were never stored. | Field | On | Meaning | | --- | --- | --- | | `status` | Any message | `complete` (the default), `incomplete` when the answer is not whole, or `cancelled` when a person stopped it. A reply that ended with `finish_reason: "length"` is `incomplete` even though its stream closed cleanly. | | `incomplete_reason` | An `incomplete` message | Why the answer is not whole: `length`, `content_filter`, `error` (the stream ended in an error), or `connection` (the stream ended with no finish at all). Any other value, or a reason on a message that is not `incomplete`, is `400` `invalid_request`. | | `routed_tier` | Assistant messages | The tier that answered, as the chat response named it in `cruxy.routed_tier`: `canto`, `saga`, or `epos`. `auto` is `400` `invalid_request`. | | `routing_mode` | Assistant messages | How the tier was chosen: `explicit` when you named a tier, `auto` when you sent `model: "auto"`, or `auto_degraded`, which the native wire reports in `routing.mode`. | | `reply_ms` | Assistant messages | How long the reply took by your measure, from sending the chat request to its last token, in whole milliseconds from 0 to 86,400,000. | | `input_tokens` | Assistant messages | The chat response's `usage.input_tokens` for the request that produced the message, from 0 to 16,777,216. On a turn that called tools, send that one request's count, never a sum. Billing never reads it. | | `activity` | Assistant messages | A JSON object of your own shape recording what the turn did, at most 65,536 bytes of compact JSON. The gateway stores and returns it as sent, never reads inside it, and never sends it to a model. | On a read, treat `incomplete_reason` and `routing_mode` as open lists: show a value you do not know as you would an absent one. To show how full the context window is, divide the newest reply's `input_tokens` by the `context_window` that `GET /api/v1/limits` reports for its tier. ## Titles Every conversation carries `title` and `title_source`, which says who wrote the title: | `title_source` | Meaning | | --- | --- | | `auto` | Derived from the first user message, in the same append: its first line, truncated to 80 characters on a word boundary. | | `generated` | Written by the gateway a few seconds after the first reply, replacing an `auto` title with one of 2 to 6 words. This happens for a `chat` conversation written through a first-party login. | | `user` | Set at create or with `PATCH /api/v1/conversations/{id}`. It is never replaced. | | `null` | The conversation is untitled, or was titled before the field existed. | A client that drew an `auto` title reads the conversation again shortly after a reply to pick up a generated one. `PATCH /api/v1/conversations/{id}` changes `title`, `model`, or both; an explicit `null` clears a field, and an empty patch is `400` `invalid_request`. ## List and count `GET /api/v1/conversations` lists your own conversations, most recently active first, without their messages. Page with `limit` (default 50, at most 100) and the `cursor` from the previous page's `next_cursor`, which is `null` on the last page. Three filters narrow it: `vault_id`, `archived` (`false`, the default, lists live conversations; `true` lists the archived shelf), and `source` (`chat`, the default, `cli`, or `agent`). `GET /api/v1/conversations/counts` counts both shelves in one read: `live` is how many conversations the listing pages through with `archived=false`, and `archived` how many with `archived=true`. It applies the listing's own visibility and its `vault_id` and `source` filters, so a count never includes a conversation the list cannot return. It takes no `archived` parameter. ```bash title="curl" curl https://api.cruxy.ai/api/v1/conversations/counts \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/conversations/counts', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) if (!res.ok) throw new Error(`counts request failed: ${res.status}`) const counts = await res.json() console.log(`${counts.live} live, ${counts.archived} archived (${counts.source})`) ``` ```json { "object": "conversation_counts", "source": "chat", "live": 42, "archived": 7 } ``` ## Read a conversation `GET /api/v1/conversations/{id}` returns the conversation and a page of its messages under `messages`. Page with `message_limit` (default 100, at most 200) and the `message_cursor` from `messages.next_cursor`. `message_order` is `asc` (the default, oldest first) or `desc`, which returns the newest messages first; a cursor works only with the order it was issued for. A conversation can branch: an append that names a `parent_id` answers that message instead of the newest one, which is how an edit or a regeneration is stored. A read returns one path through the tree, the active branch on a first page, and each message lists its `sibling_ids`. `POST /api/v1/conversations/{id}/switch` with a `message_id` moves the conversation onto the branch through that message for every device, and returns the branch's `leaf_id`. To read another branch without switching to it, pass `message_branch` on the read. ## Search your messages `GET /api/v1/conversations/search` runs a full-text search over your own messages, most relevant first. It sees exactly what the listing sees, so it never matches another person's message. Archived conversations are searched too, and so is every branch of a branched conversation. ```bash title="curl" curl -G https://api.cruxy.ai/api/v1/conversations/search \ -H "Authorization: Bearer $CRUXY_API_KEY" \ --data-urlencode 'q="seq scan" -vacuum' \ --data-urlencode 'limit=10' ``` ```ts title="TypeScript" const params = new URLSearchParams({ q: '"seq scan" -vacuum', limit: '10' }) const res = await fetch(`https://api.cruxy.ai/api/v1/conversations/search?${params}`, { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) if (!res.ok) throw new Error(`search failed: ${res.status}`) const escapeHtml = (s: string) => s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') const { data } = await res.json() for (const hit of data) { // Escape the whole snippet first, then turn the markers into markup. const html = escapeHtml(hit.snippet) .replaceAll('[[hl]]', '') .replaceAll('[[/hl]]', '') console.log(hit.conversation_id, hit.message_id, hit.on_active_path, html) } ``` `q` is required and takes web-search syntax: quoted phrases, `or`, and a leading `-` to exclude a term. No input is a syntax error. `limit` defaults to 20, at most 50, and `source` filters as it does on the listing. Each hit carries `conversation_id`, `conversation_title`, `message_id`, `role`, `sequence`, `status`, `created_at`, `rank`, `on_active_path`, and a `snippet`. > **Warning:** A `snippet` is not HTML. It mixes raw text a person wrote with the literal > markers `[[hl]]` and `[[/hl]]` around matched terms. Escape the whole snippet > first and substitute the markers afterwards, or strip the markers if you do > not highlight. `on_active_path` is `false` for a hit on a branch that is not the active one. To open it, send its `message_id` to `POST /api/v1/conversations/{id}/switch`. ## Archive, restore, and delete - `PUT /api/v1/conversations/{id}/archive` archives a conversation: it leaves the default listing and appears only with `archived=true`. Nothing is deleted, and archived conversations are still searched. Archiving does not extend the retention deadline. - `DELETE /api/v1/conversations/{id}/archive` restores it to the default listing. - `DELETE /api/v1/conversations/{id}` deletes the conversation and every message in it, immediately and irreversibly. Files its messages attached as chat attachments are deleted with it, unless a message in another conversation still attaches them. Both archive calls are idempotent and answer `204`. ## Append a run of messages `POST /api/v1/conversations/{id}/messages/batch` appends up to 100 messages in one transaction: either every message is stored or none is. It is built for copying in a transcript you already have. Each message is validated as a single append validates one, every message after the first answers the one before it, and `file_ids` is not accepted. The body may be at most 1 MiB; send a longer transcript as several batches. Send an `Idempotency-Key` here too. ## Errors | Status | `code` | When | | --- | --- | --- | | `400` | `invalid_request` | A field is malformed, out of range, or set on a role that cannot carry it. | | `403` | `conversation_forbidden` | A write to a conversation held in a vault you may read but not write. | | `404` | `conversation_not_found` | The id is not a conversation of yours. Another member's conversation reads the same as one that never existed. | | `404` | `message_not_found` | A `message_id` or `message_branch` that is not a message of this conversation. | | `409` | `idempotency_conflict` | An `Idempotency-Key` reused with a different body. | | `413` | `payload_too_large` | The request body is over the route's limit. Nothing is stored. | See [Errors and retries](/docs/en/build/errors-and-retries) for the envelope and what to retry. ## Next steps - [Chat](/docs/en/build/chat): send the turn whose messages you store here. - [Streaming](/docs/en/build/streaming): read a reply's `finish_reason`, the source of `status` and `incomplete_reason`. - [Rate limits and budgets](/docs/en/build/rate-limits): the `context_window` that `input_tokens` is measured against. - [API Reference](/docs/en/reference/api): every conversation operation with its exact request and response shape. ================================================================================ Page: Files URL: https://learn.cruxyai.com/docs/en/build/files Markdown: https://learn.cruxyai.com/docs/en/build/files.md ================================================================================ # Files Upload a file, read its metadata, download its content, and attach it to a chat turn with file_ids. Chat reads text, PDF, Word, and image files. A file is content you upload once and name by id afterwards. A chat message attaches files with `file_ids`, and the gateway reads each one into the turn. A file belongs to you, within the organization your key names: only you can list, read, or delete it. To hold a file where a team can read it, put it in a vault; see [Vaults](/docs/en/build/vaults#files-in-a-vault). ## Upload a file `POST /api/v1/files` takes `multipart/form-data` with the content in a part named `file`. The upload is rate-limited and not billed. ```bash title="curl" curl https://api.cruxy.ai/api/v1/files \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -F "file=@report.pdf" \ -F "purpose=general" ``` ```ts title="TypeScript" import { openAsBlob } from 'node:fs' const form = new FormData() form.append('file', await openAsBlob('report.pdf'), 'report.pdf') form.append('purpose', 'general') const res = await fetch('https://api.cruxy.ai/api/v1/files', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, body: form, }) if (!res.ok) throw new Error(`upload failed: ${res.status} ${await res.text()}`) const file = await res.json() console.log(file.id, file.content_type, file.text_status) ``` ```ts title="SDK" import { openAsBlob } from 'node:fs' import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result: file } = await cruxy.files.uploadFile({ body: { file: await openAsBlob('report.pdf'), purpose: 'general' }, }) console.log(file.id, file.contentType, file.textStatus) ``` The `201` describes the stored file: | Field | Meaning | | --- | --- | | `id` | The id you name in `file_ids` and in every other file call. | | `filename` | The name the upload carried. The content is never addressed by it. | | `bytes` | The size of the content. | | `content_type` | The media type the gateway detected from the content's first bytes. The `Content-Type` you declared on the part is ignored. | | `purpose` | The label you sent: a short token of letters, digits, `.`, `_`, and `-`. It defaults to `general`. | | `expires_at` | When the file stops existing, or `null` for a file kept until you delete it. | | `text_status`, `text_tokens` | For a PDF or Word document, what reading its text at upload found. Both are `null` for every other file. | Two optional fields change how long a file lives: - `expires_in` gives the file a lifetime in seconds, from 60 to 604800 (7 days). Once it passes, the file is gone to every read and to chat, and its bytes are deleted within 15 minutes. Setting it requires `Cruxy-Version: 2026-10-07` or later; without the pin, or with a value out of range, the upload is `400` `invalid_request` and nothing is stored. - `purpose=chat_attachment` marks a file uploaded to be attached to a stored conversation message. One that no message has attached 24 hours after upload is deleted. See [Conversations](/docs/en/build/conversations). Without either, a file lives until you delete it. ## Documents A PDF or a Word document (`.docx`) has its text read once, as part of the upload, so chat can read it like a text file. Reading never fails the upload: the file is stored whatever it holds, and `text_status` says what was found. | `text_status` | Meaning | | --- | --- | | `extracted` | Chat can read the document. `text_tokens` is the size of its text, by a characters-over-four estimate. | | `no_text` | No text was found, as in a scanned PDF. | | `encrypted` | The document needs a password. | | `corrupt` | The document is damaged, or uses a feature the reader does not support. | | `too_long` | The text is over 1 MiB and is not kept. `text_tokens` says how much there was. | | `too_many_pages`, `too_big` | The document is over the reader's bounds: 500 pages, or 64 MiB. | | `failed` | Reading ran out of time or memory. | | `busy` | Every reader stayed busy while the document waited. Nothing is wrong with the file: upload it again and it is read. | Chat refuses a turn that attaches a document with any status but `extracted`. A legacy Word 97-2003 document (`.doc`) is stored and not read. ## Attach files to a chat turn Name the files on a user message in `file_ids`. The gateway places each one in the turn immediately before that message. The request must pin `Cruxy-Version: 2026-10-05` or later; without the pin, `file_ids` is `400` `invalid_request` with `required_version`. ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -H "Cruxy-Version: 2026-10-05" \ -d "{ \"model\": \"saga\", \"stream\": false, \"messages\": [ { \"role\": \"user\", \"content\": \"List the three main findings.\", \"file_ids\": [\"$FILE_ID\"] } ] }" ``` ```ts title="TypeScript" const fileId = process.env.FILE_ID // the id an upload returned const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', 'Cruxy-Version': '2026-10-05', }, body: JSON.stringify({ model: 'saga', stream: false, messages: [ { role: 'user', content: 'List the three main findings.', file_ids: [fileId] }, ], }), }) if (!res.ok) throw new Error(`chat failed: ${res.status} ${await res.text()}`) const completion = await res.json() console.log(completion.message.content) // Files on earlier messages that this turn left out, and why. console.log(completion.cruxy.files_omitted?.items ?? []) ``` What chat reads: - **Text.** A UTF-8 text file, as it is. - **Documents.** A PDF or Word document, as the text read from it at upload, measured and billed as that text. - **Images.** A JPEG, PNG, or WebP image, on a tier that reads images: `supports_vision` in `GET /api/v1/models`. `model: "auto"` routes a turn with an image to a tier that does. You do not need to resize an image first. The rules for a turn: - `file_ids` is valid on user messages only, on `POST /api/v1/chat` and `POST /api/v2/chat`. `POST /v1/chat/completions` and `POST /api/v1/tokens/count` refuse it. - The messages after the last assistant message may name at most 20 distinct files, and each must be readable, or the request fails with one of the codes below. - A file on an earlier message never fails the request. It is sent again while it still resolves and fits, newest first; otherwise it is left out, the model is told so, and the response lists it in `cruxy.files_omitted` with a `reason`, such as `not_found`, `over_budget`, `context_window`, or `no_vision`. More reasons may be added, so read one you do not know as "left out". - A file's tokens are input like any other. They are billed in full on the turn that attaches the file, and again as history on each later turn that replays the message; see [Usage and cost](/docs/en/build/usage-and-cost). A file on the current turn that cannot be read fails the request: | Status | `code` | When | | --- | --- | --- | | `404` | `file_not_found` | An id that is not a file of yours. | | `400` | `file_not_text` | A file that is not text, a document whose text could not be read, or an image that does not open. | | `400` | `file_too_large` | A file over the token caps, a PDF too big to read, an image over 15,000,000 bytes or with one side over 200 times the other, or images over 30,000,000 bytes together. | | `400` | `image_not_supported` | An image on a tier that does not read images. | ## List, read, and download `GET /api/v1/files` lists your files, newest first. Page with `limit` (default 20, at most 100) and the `cursor` from the previous page's `next_cursor`, which is `null` on the last page. `total` is how many files the listing pages through. `GET /api/v1/files/{id}` returns one file's metadata. Both name the conversations of yours a file is attached in, under `conversations`. `GET /api/v1/files/{id}/content` streams the file's raw bytes. The response is always `application/octet-stream` with `Content-Disposition: attachment`, so content is never rendered inline. ```bash title="curl" curl https://api.cruxy.ai/api/v1/files/$FILE_ID/content \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -o report-copy.pdf ``` ```ts title="TypeScript" import { writeFile } from 'node:fs/promises' const fileId = process.env.FILE_ID // the id an upload returned const res = await fetch(`https://api.cruxy.ai/api/v1/files/${fileId}/content`, { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) if (!res.ok) throw new Error(`download failed: ${res.status}`) await writeFile('report-copy.pdf', Buffer.from(await res.arrayBuffer())) ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result: files } = await cruxy.files.listFiles({ limit: 20 }) for (const file of files.data) { console.log(file.id, file.filename, file.bytes) } ``` A file that belongs to another user, or to another of your own organizations, answers `404` `file_not_found` on every one of these calls, the same as an id that never existed. ## Delete a file `DELETE /api/v1/files/{id}` deletes the file and its content, and answers `200` with `deleted: true`. A repeat delete is `404` `file_not_found`. ## Limits Your plan sets how many files and images you may upload a month, the largest single file, and a storage pool. An upload past one of them is refused before a byte is stored: `429` `file_limit_reached` or `image_limit_reached`, or `413` `payload_too_large` or `storage_quota_exceeded`. [Plan limits](/docs/en/build/plan-limits#uploads-and-storage) has each plan's numbers, and `GET /api/v1/limits` reports yours as `files`, `images`, `storage`, and `plan_limits`. ## Next steps - [Vaults](/docs/en/build/vaults): hold files where every member of a vault can read them. - [Chat](/docs/en/build/chat): the request a file is attached to. - [Conversations](/docs/en/build/conversations): keep a message's files with the stored conversation. - [Errors and retries](/docs/en/build/errors-and-retries): the error envelope and what to retry. ================================================================================ Page: Choosing a tier URL: https://learn.cruxyai.com/docs/en/build/choosing-a-tier Markdown: https://learn.cruxyai.com/docs/en/build/choosing-a-tier.md ================================================================================ # Choosing a tier Compare canto, saga, and epos by profile, output cap, deadline, and reasoning default, then pick the tier that fits each call. You choose a tier on every chat request with the `model` field. A tier is a stable public id: the gateway resolves it to an upstream model on the server and never exposes which one, so the tier is the contract your code depends on. `GET /api/v1/models` returns the live catalog, so read it at runtime instead of hardcoding what this page shows: ```bash title="curl" curl https://api.cruxy.ai/api/v1/models \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/models', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) const { data } = await res.json() for (const tier of data) { console.log(tier.id, tier.label, tier.profile, tier.max_output, tier.reasoning) } ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result } = await cruxy.models.listModels() for (const tier of result.data) { console.log(tier.id, tier.label, tier.profile, tier.maxOutput, tier.reasoning) } ``` ## The three tiers Each tier has a display name (`label`) and a one-word `profile` that names its role. The profile is a qualitative descriptor, not a performance number. The former ids `kavi`, `vaani`, and `mira` still work; see [Deprecated aliases](/docs/en/reference/models#deprecated-aliases). | Tier | Label | Profile | Output cap | Non-streaming deadline | Structured output | | --- | --- | --- | --- | --- | --- | | `canto` | Canto | Deep | 65,536 tokens | 90 s | Yes | | `saga` | Saga | Balanced | 131,072 tokens | 90 s | Yes | | `epos` | Epos | Fast | 131,072 tokens | 45 s | Yes | - **Output cap** is the tier's `max_output`. A `max_tokens` you send above it, or no `max_tokens` at all, is clamped to the cap, so the gateway never generates more than the cap. - **Non-streaming deadline** bounds a `stream: false` call. The gateway makes one attempt; a call that runs past the deadline is cancelled and answered `504` `upstream_timeout`, and nothing is billed. A streaming call may run for up to five minutes. - **Structured output** is the tier's `supports_structured_output`: whether it honours `response_format` `json_object` and `json_schema`. A structured request that names a tier without it is `422` `structured_output_unsupported`. With `model: "auto"`, a structured request is routed only to a tier that has it; see [Ask for structured output](/docs/en/best-practices/prompting#ask-for-structured-output). `saga` and `epos` read images (`supports_vision` is `true` on each); `canto` does not, so an explicit `canto` turn that attaches an image is `400` `image_not_supported`, and `auto` routes a turn with an image to `saga` or `epos`. Every tier's `context_window` is 1,048,576 tokens, and your plan holds a turn to its own window, 256,000 on Free; see [Plan limits](/docs/en/build/plan-limits). Read each tier's `context_window`, `latency_target_ms`, `supports_tools`, and `pricing` from the catalog response. ## How each tier reasons A tier can think before it answers. Each catalog entry's `reasoning` object gives the effort a request gets when it sends no `reasoning_effort` (`default_effort`) and whether `low`, `medium`, and `high` are different depths on that tier (`graded`): | Tier | Profile | `default_effort` | `graded` | What that means | | --- | --- | --- | --- | --- | | `canto` | Deep | `high` | `true` | Thinks deeply by default; `low` and `medium` think less. | | `saga` | Balanced | `low` | `true` | Thinks lightly by default; `medium` and `high` think longer. | | `epos` | Fast | `none` | `true` | Answers without thinking unless you ask; `low`, `medium`, and `high` are graded. | These are the shipped defaults; the catalog reports the live ones. [Reasoning effort](/docs/en/build/reasoning-effort) covers every value and when to change it. > **Warning:** `canto` thinks by default, and its thinking spends the same `max_tokens` budget > as the answer without coming back as content. A small `max_tokens` on `canto` > can run out before any answer is written: the turn ends with > `finish_reason: "length"` and empty content. Send `reasoning_effort: "none"` > for a short, direct answer, or leave `max_tokens` unset to keep the tier's cap. ## Pick a tier for the job | | Canto | Saga | Epos | | --- | --- | --- | --- | | Model id | `canto` | `saga` | `epos` | | Reach for it when | The task needs multi-step reasoning. It thinks deeply by default. Text only: it does not read images. | Everyday calls. It thinks lightly by default, and its graded effort gives you more depth when a request needs it. | Short, direct calls. It answers without thinking unless you ask. | | Watch for | Thinking spends `max_tokens`. Leave `max_tokens` unset or large, or send `reasoning_effort: "none"` for a direct answer. | An answer past its 131,072-token output cap ends with `finish_reason: "length"`. It reads images. | A 45 s non-streaming deadline: stream a long turn. It reads images. On a signed-in plan, `epos` has a monthly request cap of its own. | [Rate limits and budgets](/docs/en/build/rate-limits) shows how to read the `epos` request cap and the other budgets in `GET /api/v1/limits`, where it sits in the signed-in plan's `token_pool` as `token_pool.epos`. The same cap is also under its former name, `token_pool.mira`, so existing code keeps working. ## Pin a tier or let the router choose Name a tier when you need its behavior to hold on every call: the same output cap, deadline, and reasoning default. Send `model: "auto"` when your requests vary and you would rather the gateway pick per request; [Auto routing](/docs/en/build/auto-routing) covers what the router guarantees and how to read the tier it chose. A developer API key can carry a model allowlist. A request for a tier the allowlist excludes is `403` `model_not_allowed`; see [Get your API key](/docs/en/get-started/api-keys#what-a-key-is-allowed-to-do). ## Next steps - [Auto routing](/docs/en/build/auto-routing): let the gateway pick the tier per request. - [Reasoning effort](/docs/en/build/reasoning-effort): control how much a tier thinks. - [Models](/docs/en/reference/models): every field in the catalog response. - [Chat](/docs/en/build/chat): send your first request to a tier. - [Tier and effort for cost and latency](/docs/en/best-practices/tiers-and-effort): a default tier and effort for each kind of call. ================================================================================ Page: Auto routing URL: https://learn.cruxyai.com/docs/en/build/auto-routing Markdown: https://learn.cruxyai.com/docs/en/build/auto-routing.md ================================================================================ # Auto routing Send model auto and the gateway picks a tier for each request before billing; read cruxy.routed_tier to see which tier served it. Send `model: "auto"` instead of a tier id and the gateway's server-side router picks the tier from the request content. It resolves `auto` to `canto`, `saga`, or `epos` before billing and before the upstream call, so `auto` never reaches a model, and every response names the tier that served it. ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "auto", "stream": false, "messages": [ { "role": "user", "content": "Summarize the causes of the monsoon in three sentences." } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'auto', stream: false, messages: [ { role: 'user', content: 'Summarize the causes of the monsoon in three sentences.' }, ], }), }) const completion = await res.json() console.log(completion.cruxy.routed_tier) // the tier that served the call console.log(completion.cruxy.reasoning_effort) // the effort it ran at console.log(completion.message.content) ``` ## Read the tier that served The routed tier comes back on every response, in a field that depends on the endpoint: | Endpoint | Where the routed tier is | | --- | --- | | `POST /api/v1/chat` | `cruxy.routed_tier`. On a stream it rides the role primer, the first frame, before any model output. | | `POST /api/v2/chat` | `routing.tier`, with `routing.mode` set to `explicit`, `auto`, or `auto_degraded`. On a stream it rides the `start` frame. | | `POST /v1/chat/completions` | The response's `model`. | `usage.cost.tier` also names the tier that served the request. The router can choose differently for two similar requests, so log `routed_tier` with each `request_id` and branch on the value you read, never on the tier you expected. ```json { "cruxy": { "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "routed_tier": "canto", "reasoning_effort": "high" } } ``` ## What auto does for you - **Picks a healthy tier.** The router chooses a tier that is available before the call is sent. Once sent, a call never moves to another tier. When every tier is unavailable, the request is `503` `all_models_unavailable`; retry it with backoff. - **Chooses the reasoning effort.** With `reasoning_effort` omitted, `auto` chooses the effort per request and echoes it as `cruxy.reasoning_effort` (`routing.reasoning_effort` on the native wire). Send `reasoning_effort` to set it yourself. - **Routes images to a tier that reads them.** A turn whose messages attach an image goes to a tier with `supports_vision`: `saga` or `epos`, never `canto`. - **Routes within your plan.** The pick, and every move above, stays among the tiers your plan includes (`models` on `GET /api/v1/limits`), so `auto` on Free is always served `saga`; see [Plan limits](/docs/en/build/plan-limits). - **Moves to `epos` instead of failing a budget.** When a budget would refuse the request and `epos` can serve it, the gateway moves an `auto` request to `epos` rather than answering `429` `budget_exhausted`. On the native wire, `routing.mode` is `auto_degraded`. [Rate limits and budgets](/docs/en/build/rate-limits) explains the budgets. ## Size max_tokens for any tier `max_tokens` is clamped to the cap of the tier the router picks: 65,536 on `canto`, and 131,072 on `saga` and `epos`. If you set a small `max_tokens` on an `auto` request, also send `reasoning_effort`. Otherwise the router may pick `canto`, whose default thinking can spend the whole budget and end the turn with `finish_reason: "length"` and empty content; see [Reasoning effort](/docs/en/build/reasoning-effort). ## When to name a tier instead - **You need the same behavior on every call:** one output cap, one non-streaming deadline, one reasoning default. - **You are measuring.** An evaluation or benchmark compares like with like, so pin the tier it measures. - **You count tokens first.** `POST /api/v1/tokens/count` rejects `auto` with `400`; count against the tier you plan to send. [Choosing a tier](/docs/en/build/choosing-a-tier) compares the three tiers. ## Next steps - [Choosing a tier](/docs/en/build/choosing-a-tier): what each tier is for. - [Reasoning effort](/docs/en/build/reasoning-effort): set the effort instead of letting `auto` choose. - [Streaming](/docs/en/build/streaming): read the routed tier from the role primer. - [Errors and retries](/docs/en/build/errors-and-retries): retry `503` `all_models_unavailable`. ================================================================================ Page: Reasoning effort URL: https://learn.cruxyai.com/docs/en/build/reasoning-effort Markdown: https://learn.cruxyai.com/docs/en/build/reasoning-effort.md ================================================================================ # Reasoning effort Set how much a tier thinks before it answers, from none to high, and keep hidden thinking from spending your whole max_tokens budget. `reasoning_effort` caps the hidden thinking a tier does before it answers. You send one of four values on a chat request, or omit it and the tier applies its default. The effort the call ran at comes back on the response as `cruxy.reasoning_effort`. This request asks `canto` for a one-line answer, so it turns thinking off and keeps the budget small: ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "canto", "stream": false, "reasoning_effort": "none", "max_tokens": 256, "messages": [ { "role": "user", "content": "Is Mumbai north or south of Chennai? Answer in one sentence." } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'canto', stream: false, reasoning_effort: 'none', max_tokens: 256, messages: [ { role: 'user', content: 'Is Mumbai north or south of Chennai? Answer in one sentence.' }, ], }), }) const completion = await res.json() console.log(completion.cruxy.reasoning_effort) // "none" console.log(completion.message.content) ``` ## The four values | Value | Effect | | --- | --- | | `none` | Turns thinking off. The tier answers directly. | | `low`, `medium`, `high` | Turn thinking on. On a graded tier the three are different depths, from `low` to `high`; on an on-or-off tier each one turns thinking on. | Any other value is `400`. The field is accepted on `POST /api/v1/chat`, `POST /api/v2/chat`, and `POST /v1/chat/completions`. ## Defaults per tier Omit `reasoning_effort` and each tier applies its own default. `graded` says whether `low`, `medium`, and `high` are different depths on the tier. Every tier is graded today; on a tier where it is `false` the control is on or off: `none` turns thinking off, every other value turns it on, `low` thinks as long as `high`, and only `max_tokens` bounds it. | Tier | Profile | Default | `graded` | | --- | --- | --- | --- | | `canto` | Deep | `high` | `true` | | `saga` | Balanced | `low` | `true` | | `epos` | Fast | `none` | `true` | With `model: "auto"`, the router chooses the effort per request unless you send one. These are the shipped defaults; `GET /api/v1/models` reports each tier's live `reasoning.default_effort` and `reasoning.graded`, read from the same configuration the chat endpoints apply. ## Thinking spends max_tokens A tier that thinks generates its thinking inside the same output budget as its answer. On `POST /api/v1/chat` and `POST /v1/chat/completions`, the thinking is not returned as content. So a small `max_tokens` on a tier that thinks can be used up before the answer starts. > **Warning:** `canto` thinks by default (`high`), so `canto` with a small `max_tokens` and no > `reasoning_effort` can return nothing: the turn ends with > `finish_reason: "length"` and empty content. For a short, direct answer, send > `reasoning_effort: "none"`. To > keep the thinking, leave `max_tokens` unset, which clamps it to the tier's cap, > or set it large. Check for the trap when you read a response, so a truncated turn never reaches your user as an empty answer: ```ts const { message, finish_reason } = completion if (finish_reason === 'length' && !message.content) { // The budget ran out before the answer began. Resend with // reasoning_effort: 'none', or with max_tokens unset. } ``` ## When to send none Send `none` when the answer needs no deliberation and you want it fast: - **Short, direct answers:** a classification, a yes or no, an extracted field, a one-line reply. - **A small `max_tokens`:** any time you cap the output tightly, so thinking cannot consume the cap. - **A turn that times out:** a `stream: false` call is bounded by the tier's deadline and answered `504` `upstream_timeout` past it. Lowering `reasoning_effort` or `max_tokens` shortens the turn; streaming lifts the limit to five minutes. Keep thinking on when the answer needs deliberation, and leave `max_tokens` unset there so the thinking and the answer share the tier's full cap. ## See the thinking The thinking is never part of the answer's content, and two of the three chat wires return it beside the answer. Either way it is present only when the tier reasoned. - `POST /api/v1/chat` returns it as `cruxy.reasoning`, from `Cruxy-Version: 2026-11-12` and when a request sends no `Cruxy-Version`. A request pinned to an earlier date never receives it. A non-streaming response carries the whole trace; a stream sends it as reasoning frames, one fragment each. See [Streaming](/docs/en/build/streaming#reasoning-frames). - `POST /api/v2/chat`, the native wire, carries a top-level `reasoning` string on a non-streaming response, and a stream sends the thinking as `reasoning` events, separate from the answer's `delta` events. It is the same field as `cruxy.reasoning`, with the same meaning. - `POST /v1/chat/completions` does not return the thinking. Whichever wire you read it on: - It is not part of the answer, and it sits outside `message` on purpose. Do not send it back in the conversation. - There is no separate reasoning-token count. `usage.output_tokens` already includes the thinking, undivided, on every API version, so receiving the trace changes no figure and no bill. - The effort is echoed as `cruxy.reasoning_effort`, and as `routing.reasoning_effort` on the native wire. A stream can also carry thought lines, short plain-text notes on what each part of the trace is doing. Read `cruxy.reasoning_summaries` on `GET /api/v1/models` to learn whether the deployment sends them; when it is `true`, a stream from a signed-in credential that pins `Cruxy-Version: 2026-11-13` or later gets them, and a developer or headless key never does. See [Streaming](/docs/en/build/streaming#thought-lines). ## Next steps - [Choosing a tier](/docs/en/build/choosing-a-tier): each tier's profile, output cap, and default. - [Auto routing](/docs/en/build/auto-routing): let the router choose the tier and the effort. - [Streaming](/docs/en/build/streaming): read the stream and its `finish_reason`. - [Errors and retries](/docs/en/build/errors-and-retries#timeouts): what to do about `504` `upstream_timeout`. - [Tier and effort for cost and latency](/docs/en/best-practices/tiers-and-effort): pick an effort by cost and latency. ================================================================================ Page: Memory URL: https://learn.cruxyai.com/docs/en/build/memory Markdown: https://learn.cruxyai.com/docs/en/build/memory.md ================================================================================ # Memory Let chat recall stored facts and capture new ones. Memory is on by default for signed-in keys and off for developer keys until a request opts in. Memory gives chat two independent abilities, each set per request in the `memory` object. **Recall** reads the stored memories most relevant to the turn into it as background context. **Capture** lets the gateway store a durable fact from the turn for later ones. When a request sends no `memory` object, the key decides whether each one runs. ## Defaults depend on the key | Key | Recall and capture when `memory` is omitted | `bucket` in `GET /api/v1/limits` | | --- | --- | --- | | Signed-in credential: device login, OAuth login, and the Cruxy web app, desktop, CLI, and mobile | On | `subscription` | | Developer API key, created in the Cruxy Console | Off | `apikey` | | Headless key | Off | `headless` | A key minted by device login or OAuth login is a signed-in credential whichever client ran the flow, a third-party tool included. A developer key's memory is off because the key often serves people other than its owner: recall would put the owner's stored memory into their turns, and capture would store what they say. Use a developer API key for a server; see [Get your API key](/docs/en/get-started/api-keys#two-kinds-of-key). ## Opt in from a developer key Send `true` for each side you want. This request comes from an internal tool that only the key's owner uses, so it recalls the owner's memory and lets the turn store a new fact: ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "saga", "stream": false, "memory": { "recall": true, "capture": true }, "messages": [ { "role": "user", "content": "I work in IST. When should our weekly sync with the London team be?" } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'saga', stream: false, memory: { recall: true, capture: true }, messages: [ { role: 'user', content: 'I work in IST. When should our weekly sync with the London team be?', }, ], }), }) const completion = await res.json() console.log(completion.message.content) console.log(completion.cruxy.memory_recall) // what was recalled, or undefined console.log(completion.cruxy.memory_capture) // what was stored, or undefined ``` `true` needs a key whose allowed scopes include the `memory` family. An unscoped key has every family. A key without it gets `403` `key_scope_forbidden`, refused before anything is billed: | Error field | Value | | --- | --- | | `code` | `key_scope_forbidden` | | `required_scope` | `memory` | | `allowed_scopes` | The key's own families, for example `["chat"]` | A `403` never clears by waiting. A key whose allowed scopes omit `memory` can never use memory through chat, which makes it the key to issue for a service that must never see anyone's memory. > **Warning:** Never store secrets in memory, and never enable capture on anonymous or public > traffic. Memory has no expiry: a stored value stays, and recall can place it in > later turns, until someone deletes it. The capture filter drops content that > carries an email address, a phone number, or a card number; it does not > promise to catch a password, an API key, or a token. Capture on public traffic > stores what strangers say into the key owner's memory. ## What recall adds Recall draws on the same resolved view `GET /api/v1/memories` lists: your personal memory, your organization's, and every vault you can read whose `memory_scope` is `default`. - **`vault_id`** names the vault a chat is inside. Inside a `vault_only` vault, recall draws on that vault's memory alone, without personal or organization memory. A `vault_id` you cannot read is treated as if you sent none, never reported. - **`mentioned_vault_ids`** adds up to three vaults the turn references, such as an `@VersionGate` your picker resolved. Mentions share the turn's recall budget rather than enlarging it, and never make a vault writable. - **Billing.** The recalled block is billed input, so input tokens fall by its size when recall is off. The response reports what was recalled in `cruxy.memory_recall`: the scope and key of each memory, and for a vault memory its `vault_id` (and `vault_name` when it resolves). It never includes the stored value, and the field is absent when nothing was recalled. ```json { "cruxy": { "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "routed_tier": "saga", "reasoning_effort": "low", "memory_recall": { "count": 1, "items": [{ "scope": "personal", "key": "timezone" }] } } } ``` ## What capture stores After the turn is answered, capture decides whether the exchange held a durable fact, such as a stated preference, a stable setting, or a constraint about your work, and stores it. - **Where it goes.** Your personal memory, or the vault the request's `vault_id` names when you can write to it. A vault you can only read demotes the capture to your personal memory. Capture never writes organization-wide memory, whatever your role. - **What it drops.** Content carrying an email address, a phone number, or a card number is dropped before any write. - **What it reports.** Every capture appears in `cruxy.memory_capture`, with the scope and key of each memory stored and never the value. No field means nothing was stored. - **What it never does.** Capture cannot fail or delay a turn. If extraction is unavailable, it stores nothing. On a stream, `memory_recall` rides the role primer and `memory_capture` rides the terminal usage frame, because what a turn stored is known only once the answer is complete. ## Turn memory off for one request Any key may send `false` for either side, and `false` needs no scope: ```json { "memory": { "recall": false, "capture": false } } ``` `recall: false` reads no memory and ignores `mentioned_vault_ids`. `capture: false` stores nothing. The two are independent, so `{ "capture": false }` alone keeps the turn personalized by what is already stored while adding nothing new. Pin `Cruxy-Version: 2026-09-26` on every request that relies on `false`. A gateway that predates the field would ignore it and capture anyway; with the pin, such a gateway refuses the request with `400` `unknown_version` instead. A server should use a developer API key. If a signed-in credential does serve other people, every request must send both `false` values, and `rules: false`, or the owner's memory and rules reach their turns. ## Review and remove what is stored - `GET /api/v1/memories` lists your effective memory, one entry per key, with the `id` of the row that won. - `DELETE /api/v1/memories/{id}` removes that entry. You can delete what you can write: your own memories, a vault's where your membership grants `can_write`, and organization memory if you are an owner or admin. - `PUT /api/v1/memories` stores a value by hand. A key or value carrying an email address, a phone number, or a card number is refused with `400` `pii_rejected`, and nothing is stored. [API Reference](/docs/en/reference/api) has every field of the memories endpoints. ## Next steps - [Standing rules](/docs/en/build/rules): the other per-request context, with the same default split. - [Get your API key](/docs/en/get-started/api-keys): the two kinds of key and their restrictions. - [Streaming](/docs/en/build/streaming): where the `cruxy` signals ride on a stream. - [Errors and retries](/docs/en/build/errors-and-retries): handle `403` `key_scope_forbidden`. - [Security](/docs/en/best-practices/security): keep secrets out of memory and capture off for anonymous traffic. ================================================================================ Page: Standing rules URL: https://learn.cruxyai.com/docs/en/build/rules Markdown: https://learn.cruxyai.com/docs/en/build/rules.md ================================================================================ # Standing rules Inject your organization's standing rules into chat as defaults. Rules are on for signed-in keys and off for developer keys unless you opt in. Standing rules are instructions your organization sets for chat, such as "Always answer in British English." A vault can have its own. When rules apply, the gateway injects them into the turn as defaults that the user's own message overrides, never as constraints that outrank the user. The `rules` field on a chat request turns injection on or off for that request. ## Defaults depend on the key | Key | Rules when `rules` is omitted | | --- | --- | | Signed-in credential: device login, OAuth login, and the Cruxy web app, desktop, CLI, and mobile | Injected | | Developer API key or headless key | Not injected, unless the key was issued with allowed scopes that name the `rules` family | An unscoped developer key has every family but has not opted in, so it gets no rules by default. A key's rules are its owner's organization's guidance, and a developer key often serves people other than its owner. ## Opt in A developer key opts in one of two ways: - **Per request:** send `rules: true`. - **Once, on the key:** issue the key with allowed scopes that name the `rules` family. Every request from it then gets rules unless it sends `rules: false`. ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "saga", "stream": false, "rules": true, "messages": [ { "role": "user", "content": "Draft a two-line status update for the launch." } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'saga', stream: false, rules: true, messages: [{ role: 'user', content: 'Draft a two-line status update for the launch.' }], }), }) const completion = await res.json() console.log(completion.message.content) console.log(completion.cruxy.rules_applied) // { count, sources }, or undefined ``` `rules: true` needs a key whose allowed scopes include `rules`. A key without it gets `403` `key_scope_forbidden` with `required_scope: "rules"`, refused before anything is billed, and such a key never gets rules. `rules: false` needs no scope: any key may send it to decline rules for one turn, since the user's own message already overrides them. > **Warning:** A model can repeat an injected rule. Anyone chatting through a key that gets > rules can ask the model to repeat them. Before you opt in a key > that serves other people, read `GET /api/v1/rules/resolved` and confirm > nothing in the result is meant to stay internal. ## What gets injected The switch covers the whole resolved ruleset: a turn gets exactly what `GET /api/v1/rules/resolved` returns for its context, or nothing. - **No `vault_id`:** the organization's rules. - **A `vault_id` for a vault that inherits** (the default): the organization's rules first, then the vault's own. - **A `vault_id` for a vault that does not inherit:** the vault's own rules only. A `vault_id` you cannot read is treated as none, so the turn runs with organization rules. Injected rule text is real input and counts in `usage.input_tokens`. Rules are separate from memory: the `memory` field never affects them. `POST /v1/chat/completions` never injects rules. Preview the rules a turn would get. Pass `vault_id` as a query parameter for a chat inside a vault: ```bash title="curl" curl https://api.cruxy.ai/api/v1/rules/resolved \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/rules/resolved', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) const resolved = await res.json() for (const rule of resolved.rules) { console.log(rule.source, rule.text) // "org" or "vault", then the instruction } ``` Each rule carries its `source`, `org` or `vault`, so an unexpected instruction traces back to the ruleset that contributed it. An empty `rules` array is a real answer: there is no default ruleset. Unlike chat, this endpoint answers `404` `vault_not_found` for a `vault_id` you cannot read, so a mistyped id is reported rather than resolved for the wrong context. ## Know when rules applied When at least one rule applied, the response carries `cruxy.rules_applied`: how many rules applied and from which rulesets, never the rule text. The field is absent when nothing was injected. On a stream it rides the role primer. ```json { "cruxy": { "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "routed_tier": "saga", "reasoning_effort": "low", "rules_applied": { "count": 3, "sources": [{ "scope": "org", "count": 3 }] } } } ``` ## Edit the rules `GET /api/v1/rules` returns one stored ruleset, the organization's or, with `vault_id`, a vault's, and `PUT /api/v1/rules` replaces it whole. Its `permissions.can_write` tells you whether you may change it: the organization's ruleset is owner or admin only, and a vault's also admits a member the vault grants `can_write`. A refused write is `403` `rules_forbidden`. Rules are re-injected on every request in scope, so each ruleset is capped: | Cap | Limit | | --- | --- | | Rules per ruleset | 50 | | Characters per rule | 1000 | | Characters in total | 8000 | Exceeding a cap is `400` `rules_too_large`. A rule carrying an email address, a phone number, or a card number is refused with `400` `pii_rejected`, and nothing is stored. [API Reference](/docs/en/reference/api) has every field of the rules endpoints. ## Next steps - [Memory](/docs/en/build/memory): recall and capture, with the same default split. - [Get your API key](/docs/en/get-started/api-keys#what-a-key-is-allowed-to-do): allowed scopes and other key restrictions. - [Chat](/docs/en/build/chat): the rest of the request and the `cruxy` block. ================================================================================ Page: Vaults URL: https://learn.cruxyai.com/docs/en/build/vaults Markdown: https://learn.cruxyai.com/docs/en/build/vaults.md ================================================================================ # Vaults A vault is a shared space in your organization: its members share memory, rules, and files. Create one, manage members, and chat inside it. A vault is a container inside your organization that a set of members share. It holds memory that chat can recall, its own standing rules, and files. A chat request names the vault it is happening inside with `vault_id`. Access is by membership: administering an organization does not, by itself, let you read a vault you are not a member of. ## Create a vault `POST /api/v1/vaults` creates a vault. Only `name` is required, and names are unique within an organization. You become the owner, and a member with read, write, and share. ```bash title="curl" curl https://api.cruxy.ai/api/v1/vaults \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Platform team", "description": "Shared context for the platform team", "external_id": "app-vault-8f2c" }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/vaults', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ name: 'Platform team', description: 'Shared context for the platform team', external_id: 'app-vault-8f2c', // your own id for the vault; makes a retry safe }), }) if (!res.ok) throw new Error(`create failed: ${res.status} ${await res.text()}`) const vault = await res.json() // 201 with created: true the first time; 200 with created: false on a retry. console.log(vault.id, vault.created, vault.permissions) ``` Send `external_id`, your own system's identifier for the vault, whenever a retry is possible. A second create naming an `external_id` your organization has already seen returns the existing vault with `200` and `created: false`, and writes nothing. Without it, a retry after a timeout hits `409` `vault_name_exists`, which carries no vault id. Reusing an `external_id` that names a vault somebody else owns is `409` `vault_external_id_conflict`. The optional fields: | Field | Meaning | | --- | --- | | `description` | Free text, at most 2000 characters. | | `icon`, `color` | Presentation, each from a fixed vocabulary that [API Reference](/docs/en/reference/api) lists. An unknown value is `400` `invalid_request`. | | `memory_scope` | `default` or `vault_only`; see [Chat inside a vault](#chat-inside-a-vault). | | `external_id` | Your identifier for the vault, which makes the create idempotent. | `PATCH /api/v1/vaults/{id}` changes `name`, `description`, `icon`, `color`, or `memory_scope`, and requires `can_write`. `GET /api/v1/vaults/{id}` reads one vault, and `GET /api/v1/vaults` lists the vaults you can use, with two filters: `scope` (`all`, `owned`, or `shared`) and `archived`. ## Permissions Every vault read carries a `permissions` block with your own four flags: | Flag | What it allows | | --- | --- | | `can_read` | Read the vault's content. | | `can_write` | Change the vault's content and metadata, and archive it. | | `can_share` | Add and remove members, granting only permissions you hold yourself. | | `can_administer` | Delete the vault, and hold or restore its members. It is `true` for the vault's owner and for an admin of its organization. | The four do not imply one another: a member with read, write, and share does not administer the vault. Each flag is resolved from the same check that gates the matching request, so you can show or hide controls from this block alone. Treat an absent `can_administer` as `false`. A vault you cannot read answers `404` `vault_not_found`, whether it is in another organization, you are not a member, or you are held. A member who is refused an action they lack the flag for gets `403` `vault_forbidden`. ## Members `POST /api/v1/vaults/{id}/members` adds a member of your organization with the permissions you name. All four fields are required. ```bash title="curl" curl https://api.cruxy.ai/api/v1/vaults/$VAULT_ID/members \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d "{ \"user_id\": \"$USER_ID\", \"can_read\": true, \"can_write\": true, \"can_share\": false }" ``` ```ts title="TypeScript" const vaultId = process.env.VAULT_ID const userId = process.env.USER_ID // a member of your organization const res = await fetch(`https://api.cruxy.ai/api/v1/vaults/${vaultId}/members`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ user_id: userId, can_read: true, can_write: true, can_share: false }), }) if (!res.ok) throw new Error(`add member failed: ${res.status} ${await res.text()}`) const member = await res.json() console.log(member.user_id, member.email, member.held) ``` - **Who may add.** The vault's owner and organization admins may grant anything. A member with `can_share` may grant only permissions they hold: a member who cannot write cannot create a member who can. - **Errors.** A user outside your organization is `404` `user_not_found`, and one who is already a member is `409` `vault_member_exists`. - **List.** `GET /api/v1/vaults/{id}/members` lists the members with their permissions, held members included. - **Change.** `PATCH /api/v1/vaults/{id}/members/{user_id}` changes a member's read, write, and share flags; omitted fields keep their value. The rule against granting more than you hold applies to the resulting set of permissions. - **Remove.** `DELETE /api/v1/vaults/{id}/members/{user_id}` removes a member, and their access ends immediately. The owner cannot be removed, and nobody can modify the owner's membership; delete the vault instead. ## Hold a member A hold suspends a member without changing their permissions. `PUT /api/v1/vaults/{id}/members/{user_id}/held` with `{"held": true}` makes the member's read, write, and share inert, and the vault reads to them as if it did not exist. `{"held": false}` restores exactly the permissions they had. ```bash title="curl" curl -X PUT https://api.cruxy.ai/api/v1/vaults/$VAULT_ID/members/$USER_ID/held \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "held": true }' ``` ```ts title="TypeScript" const vaultId = process.env.VAULT_ID const userId = process.env.USER_ID const res = await fetch( `https://api.cruxy.ai/api/v1/vaults/${vaultId}/members/${userId}/held`, { method: 'PUT', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ held: true }), }, ) if (!res.ok) throw new Error(`hold failed: ${res.status} ${await res.text()}`) const member = await res.json() console.log(member.user_id, member.held) // the flags are unchanged ``` Only the vault's owner or an organization admin may set or clear a hold, which is what `can_administer` reports; `can_share` does not allow it. The owner cannot be held. ## Archive and pin - **Archive.** `PUT /api/v1/vaults/{id}/archive` hides the vault from the default list; it appears only with `archived=true`, and reads report `archived: true`. The vault and all its memory are untouched. `DELETE /api/v1/vaults/{id}/archive` restores it. Both require `can_write`, are idempotent, and answer `204`. - **Pin.** `PUT /api/v1/vaults/{id}/pin` pins the vault for you alone: a personal bookmark, reported as `pinned` on your reads of the vault and never visible to other members. `DELETE /api/v1/vaults/{id}/pin` removes it. Both need only that you can read the vault, are idempotent, and answer `204`. - **Delete.** `DELETE /api/v1/vaults/{id}` deletes the vault, its membership list, and all memory stored in it. It requires `can_administer`. ## Files in a vault A vault holds files for every member who can read it. - `POST /api/v1/vaults/{id}/files` uploads a file into the vault. It is the same multipart upload as `POST /api/v1/files`, with the same detection, document reading, and limits; see [Files](/docs/en/build/files). It requires `can_write`, and `purpose=chat_attachment` is refused. - `POST /api/v1/vaults/{id}/files/share` copies one of your own files into the vault, named by `file_id`, as a new vault file with its own id. The original stays yours and unchanged, and deleting either one never touches the other. The copy counts against your storage pool and spends no monthly upload allowance. - `GET /api/v1/vaults/{id}/files` lists the vault's files, newest first, paged like `GET /api/v1/files`. `GET /api/v1/vaults/{id}/files/{file_id}` reads one, and `GET /api/v1/vaults/{id}/files/{file_id}/content` downloads its bytes. All three require `can_read`. - `DELETE /api/v1/vaults/{id}/files/{file_id}` deletes a vault file for every member. Any member with `can_write` may delete any file in the vault, not only their own. ```bash title="curl" # Upload a file straight into the vault. curl https://api.cruxy.ai/api/v1/vaults/$VAULT_ID/files \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -F "file=@handbook.pdf" # Or copy in a file you already uploaded. curl https://api.cruxy.ai/api/v1/vaults/$VAULT_ID/files/share \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d "{ \"file_id\": \"$FILE_ID\" }" ``` ```ts title="TypeScript" import { openAsBlob } from 'node:fs' const vaultId = process.env.VAULT_ID const auth = { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` } // Upload a file straight into the vault. const form = new FormData() form.append('file', await openAsBlob('handbook.pdf'), 'handbook.pdf') const uploaded = await fetch(`https://api.cruxy.ai/api/v1/vaults/${vaultId}/files`, { method: 'POST', headers: auth, body: form, }) if (!uploaded.ok) throw new Error(`upload failed: ${uploaded.status}`) const vaultFile = await uploaded.json() console.log(vaultFile.id, vaultFile.retention_until, vaultFile.shared_with) // List what the vault holds. const listed = await fetch(`https://api.cruxy.ai/api/v1/vaults/${vaultId}/files`, { headers: auth, }) if (!listed.ok) throw new Error(`list failed: ${listed.status}`) const { data, total } = await listed.json() console.log(`${total} files`, data.map((f: { filename: string }) => f.filename)) ``` A vault file carries the fields of any file, plus `vault_id`, `uploaded_by` (the user who uploaded or shared it, kept after they leave), `shared_with` (how many members can read the vault), and `retention_until`. A vault file has no `expires_at`: it is deleted at `retention_until`, 365 days from its last use. An upload, a share, and a download each count as a use; reading metadata does not. ## Chat inside a vault Send `vault_id` on `POST /api/v1/chat` to say which vault the chat is happening inside. It changes two things for the turn: - **Memory.** Which stored memories recall may draw on. With no vault, that is your personal memory, your organization's, and every vault you can read whose `memory_scope` is `default`. Inside a `vault_only` vault, recall draws on that vault's memory alone, and its memory is withheld everywhere outside it. See [Memory](/docs/en/build/memory). - **Rules.** Which standing rules apply: the vault's own ruleset, merged with the organization's when the vault inherits them. See [Standing rules](/docs/en/build/rules). A user message can also attach a file the vault holds, by naming its id in `file_ids` like any other file. The gateway reads a vault file only while you are a member who reads that vault and is not held. ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -H "Cruxy-Version: 2026-10-05" \ -d "{ \"model\": \"saga\", \"stream\": false, \"vault_id\": \"$VAULT_ID\", \"messages\": [ { \"role\": \"user\", \"content\": \"What does the handbook say about on-call handover?\", \"file_ids\": [\"$FILE_ID\"] } ] }" ``` ```ts title="TypeScript" const vaultId = process.env.VAULT_ID const vaultFileId = process.env.FILE_ID // a file the vault holds const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', 'Cruxy-Version': '2026-10-05', // file_ids needs this pin or later }, body: JSON.stringify({ model: 'saga', stream: false, vault_id: vaultId, messages: [ { role: 'user', content: 'What does the handbook say about on-call handover?', file_ids: [vaultFileId], }, ], }), }) if (!res.ok) throw new Error(`chat failed: ${res.status} ${await res.text()}`) const completion = await res.json() console.log(completion.message.content) console.log(completion.cruxy.rules_applied) // the rules the vault added, or undefined ``` A `vault_id` you cannot read is not an error and is never reported: the turn runs exactly as if you had sent none, so a chat request cannot be used to discover whether a vault id is real. Sending a vault id grants no access you do not already have. `mentioned_vault_ids` is different from `vault_id`. It names up to three vaults the turn references without being inside them, and adds their memory to the turn's recall. It changes nothing about isolation and never makes a vault writable. ## Next steps - [Memory](/docs/en/build/memory): what recall and capture do inside a vault. - [Standing rules](/docs/en/build/rules): give a vault its own rules. - [Files](/docs/en/build/files): upload files and attach them to a chat turn. - [Conversations](/docs/en/build/conversations): hold a conversation inside a vault. ================================================================================ Page: Indic languages URL: https://learn.cruxyai.com/docs/en/build/indic-languages Markdown: https://learn.cruxyai.com/docs/en/build/indic-languages.md ================================================================================ # Indic languages Cruxy supports 20+ Indic languages. Send text as UTF-8, measure token counts per script with the tokens endpoint, and test each language before launch. Cruxy supports 20+ Indic languages. It publishes no list of which ones, and these docs make no claim about how well a tier handles any one of them; see [No per-language list for Indic languages](/docs/en/build/known-limitations#no-per-language-list-for-indic-languages). This page covers the practical side: sending the text, measuring what it costs in tokens, and testing it before you launch. ## Send the text as UTF-8 Request bodies are JSON, and JSON travels as UTF-8. Put the text in `content` in its own script, as your users wrote it. It needs no escaping beyond what JSON itself requires. - **From a shell,** make sure the terminal and the file you send are UTF-8. For anything longer than a line, keep the body in a file and send it with `curl --data-binary @body.json`. - **Attached files** named in `file_ids` must be UTF-8 text files, PDFs, Word documents (`.docx`), or JPEG, PNG, or WebP images; see the [API Reference](/docs/en/reference/api). - **Keep one Unicode normalization form,** such as NFC, across your application. The same visible text can be encoded as different sequences of code points, and different bytes can count as different tokens. ## Token counts vary by script A token is neither a character nor a word, and the same sentence can count as a different number of tokens in a different script, and on a different tier. Do not estimate tokens from character counts: measure them. `POST /api/v1/tokens/count` returns the input tokens a chat request would bill on a tier. It calls no model, is not billed, and is exact for single-turn prompts on every tier. It takes a tier, not `auto`. This sample counts the same question in Hindi and in English on each tier: ```bash title="curl" curl https://api.cruxy.ai/api/v1/tokens/count \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "saga", "messages": [ { "role": "user", "content": "भारत में मानसून कब आता है?" } ] }' ``` ```ts title="TypeScript" const texts = { hindi: 'भारत में मानसून कब आता है?', english: 'When does the monsoon reach India?', } for (const model of ['canto', 'saga', 'epos']) { for (const [name, content] of Object.entries(texts)) { const res = await fetch('https://api.cruxy.ai/api/v1/tokens/count', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model, messages: [{ role: 'user', content }] }), }) if (!res.ok) throw new Error(`count failed: ${res.status} ${await res.text()}`) const { input_tokens } = await res.json() console.log(`${model} ${name}: ${input_tokens} input tokens`) } } ``` The count includes the tier's own prompt, which the gateway adds to every turn, so compare counts on the same tier rather than reading one as the cost of your text alone. ## Size max_tokens in tokens, not characters `max_tokens` caps output tokens, so an answer of the same length can need a different budget in a different script. Read `usage.output_tokens` from real responses in each language you serve, and size `max_tokens` from those, with room to spare. On a tier that thinks, the thinking spends the same budget; see [Reasoning effort](/docs/en/build/reasoning-effort). ## Byte limits count bytes Most Indic scripts take three bytes per character in UTF-8, where ASCII text takes one, so a limit in bytes is reached in fewer characters. `POST /api/v1/tokens/count` refuses with `400` `input_not_countable` text that carries a single unbroken run of more than 1024 bytes, with no word, digit, or punctuation boundary in it, or more than 262144 bytes of text in one request. Ordinary prose with spaces between words stays far inside both. ## Test each language before launch Before you launch in a language, test it on each tier you plan to use, with prompts from your own product. An eval suite under `/api/v1/evals/suites` runs the same cases against the tier you name; each case is billed as a chat completion. Test embeddings, rerank, and moderation in that language too, if you use them: these docs make no per-language claim for them either. ## Next steps - [Prompting basics](/docs/en/best-practices/prompting): what the model reads on every turn. - [Usage and cost](/docs/en/build/usage-and-cost): the token counts each response reports. - [Known limitations](/docs/en/build/known-limitations): the limits to plan around. ================================================================================ Page: Prompts URL: https://learn.cruxyai.com/docs/en/build/prompts Markdown: https://learn.cruxyai.com/docs/en/build/prompts.md ================================================================================ # Prompts Store a prompt under a stable name, add immutable versions as you revise it, and fetch a version at runtime to send to chat. A prompt is a named container for template text that you revise over time. Each revision is an immutable, numbered version, so the text a release was tested with is always retrievable. Prompts live in the workspace your key names: there is no workspace or organization id in any path or body, and no way to address another workspace. ## Create a prompt `POST /api/v1/prompts` creates a prompt whose first version holds the `content` you send. ```bash title="curl" curl https://api.cruxy.ai/api/v1/prompts \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Code Review", "slug": "code-review", "content": "You are a meticulous code reviewer. Review this diff:\n\n{{diff}}" }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/prompts', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ name: 'Code Review', slug: 'code-review', content: 'You are a meticulous code reviewer. Review this diff:\n\n{{diff}}', }), }) if (!res.ok) throw new Error(`create failed: ${res.status} ${await res.text()}`) const prompt = await res.json() console.log(prompt.id, prompt.slug, prompt.version.version) // version 1 ``` | Field | Required | Meaning | | --- | --- | --- | | `name` | Yes | The display name, 1 to 128 bytes. | | `content` | Yes | The template text of version 1, 1 to 102,400 bytes. It is stored and returned verbatim. | | `slug` | No | A stable, URL-safe handle. Omitted, it is derived from the name: lowercased, with runs of other characters collapsed to hyphens. Send it yourself when the name has no usable characters. | A slug already used in the workspace is `409` `prompt_slug_exists`. The `201` is the prompt with its version 1 embedded under `version`. > **Note:** Content is stored as you wrote it and is not filtered for personal data, so > keep secrets and personal details out of a prompt. ## Add a version `POST /api/v1/prompts/{id}/versions` appends a new version. Its number is the previous highest plus one, and existing versions are never modified. ```bash title="curl" curl https://api.cruxy.ai/api/v1/prompts/$PROMPT_ID/versions \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "content": "You are a meticulous code reviewer. Be concise. Review this diff:\n\n{{diff}}" }' ``` ```ts title="TypeScript" const promptId = process.env.PROMPT_ID // the id a create returned const res = await fetch(`https://api.cruxy.ai/api/v1/prompts/${promptId}/versions`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ content: 'You are a meticulous code reviewer. Be concise. Review this diff:\n\n{{diff}}', }), }) if (!res.ok) throw new Error(`add version failed: ${res.status} ${await res.text()}`) const version = await res.json() console.log(version.prompt_id, version.version, version.created_at) ``` A version carries `prompt_id`, `version`, `content`, `created_by`, and `created_at`. ## Read prompts and versions | Call | Returns | | --- | --- | | `GET /api/v1/prompts` | Every prompt in the workspace, oldest first, each with its `slug`, `latest_version`, and `version_count`, without content. | | `GET /api/v1/prompts/{id}` | One prompt with a single version embedded: the latest, or the one `version` names, as in `?version=2`. | | `GET /api/v1/prompts/{id}/versions` | Every version of the prompt, newest first, each with its content. | | `DELETE /api/v1/prompts/{id}` | Nothing: `204`. The prompt and all of its versions are deleted. | A prompt id in another workspace or organization, or one that names nothing, is `404` `prompt_not_found`. A `version` the prompt does not have is `404` `prompt_version_not_found`. ## Use a prompt in chat A chat request has no field that names a stored prompt, and the gateway returns `content` verbatim. So your code fetches the version it wants, fills in any placeholders its own templates use, and sends the text as a message. Pin a `version` number in production, so that adding a version never changes what a deployed build sends. ```bash title="curl" # 1. Fetch version 2 of the prompt and read its content. curl "https://api.cruxy.ai/api/v1/prompts/$PROMPT_ID?version=2" \ -H "Authorization: Bearer $CRUXY_API_KEY" # 2. Send the content, with your own values filled in, as the system message. curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "saga", "stream": false, "messages": [ { "role": "system", "content": "You are a meticulous code reviewer. Be concise." }, { "role": "user", "content": "Review this diff:\n\n- const retries = 3\n+ const retries = 30" } ] }' ``` ```ts title="TypeScript" const promptId = process.env.PROMPT_ID const headers = { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', } // 1. Fetch the pinned version. const promptRes = await fetch(`https://api.cruxy.ai/api/v1/prompts/${promptId}?version=2`, { headers, }) if (!promptRes.ok) throw new Error(`prompt fetch failed: ${promptRes.status}`) const prompt = await promptRes.json() // 2. Fill in the placeholder. The gateway does not do this for you. const diff = '- const retries = 3\n+ const retries = 30' const content = prompt.version.content.replaceAll('{{diff}}', diff) // 3. Send it to chat. const chatRes = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers, body: JSON.stringify({ model: 'saga', stream: false, messages: [{ role: 'user', content }], }), }) if (!chatRes.ok) throw new Error(`chat failed: ${chatRes.status} ${await chatRes.text()}`) const completion = await chatRes.json() console.log(`prompt v${prompt.version.version}:`, completion.message.content) ``` The `{{diff}}` marker is this sample's own convention. Use whatever placeholder syntax suits your templates; the gateway treats the content as opaque text. An eval suite can record which prompt it tests: `prompt_id` on `POST /api/v1/evals/suites` links a prompt in the same workspace. The link is advisory metadata, and an eval run sends each case's `input` as it is. ## Errors | Status | `code` | When | | --- | --- | --- | | `400` | `invalid_request` | A missing or empty `name` or `content`, or a field over its size. | | `404` | `prompt_not_found` | The id is not a prompt in your workspace. | | `404` | `prompt_version_not_found` | The prompt exists and has no such version. | | `409` | `prompt_slug_exists` | The slug is already used in the workspace. | | `413` | `payload_too_large` | The request body is over the route's 64 KiB limit. | See [Errors and retries](/docs/en/build/errors-and-retries) for the envelope and what to retry. ## Next steps - [Chat](/docs/en/build/chat): the request the prompt's content goes into. - [Prompting basics](/docs/en/best-practices/prompting): what to put in a prompt. - [API Reference](/docs/en/reference/api): every prompt operation with its exact request and response shape. ================================================================================ Page: Define tools URL: https://learn.cruxyai.com/docs/en/build/tools Markdown: https://learn.cruxyai.com/docs/en/build/tools.md ================================================================================ # Define tools Describe your functions in the tools array with a JSON Schema for their arguments, and use tool_choice to control when the model calls one. Tool calling lets a chat model ask your code to run a function. You describe the functions on the request; when the model decides to use one, the turn ends with the call and its arguments, you run it, and you send the result back. This page covers the first part. [Handle tool calls](/docs/en/build/tool-calls) covers answering the calls, and [Tutorial: build a tool-using agent](/docs/en/build/tool-agent) runs the whole loop. ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "canto", "stream": false, "messages": [ { "role": "user", "content": "What is the weather in Paris?" } ], "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a city", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "City name, for example Paris" } }, "required": ["city"] } } } ], "tool_choice": "auto" }' ``` ```ts title="TypeScript" const tools = [ { type: 'function', function: { name: 'get_weather', description: 'Get the current weather for a city', parameters: { type: 'object', properties: { city: { type: 'string', description: 'City name, for example Paris' }, }, required: ['city'], }, }, }, ] const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'canto', stream: false, messages: [{ role: 'user', content: 'What is the weather in Paris?' }], tools, tool_choice: 'auto', }), }) const completion = await res.json() console.log(completion.finish_reason) // "tool_calls" when the model wants get_weather console.log(completion.message.tool_calls) ``` ## Describe a tool `tools` is an array. Each entry describes one function: | Field | Required | What it is | | --- | --- | --- | | `type` | Yes | `"function"`. | | `function.name` | Yes | The name the model calls the function by, and the name it returns in a tool call. | | `function.description` | No | What the function does, rendered into the prompt the model reads. | | `function.parameters` | No | A JSON Schema object describing the function's arguments, also rendered into the prompt. | Write the `description` and each parameter's `description` for the model: say what the function returns and when to use it, the way you would brief a colleague. ## Control tool use `tool_choice` controls whether the model may call your tools, and which: | `tool_choice` | Effect | | --- | --- | | Omitted | The provider default. | | `"none"` | The model calls no tool. | | `"auto"` | The model decides whether to call a tool. | | `"required"` | The model calls at least one tool. | | `{ "type": "function", "function": { "name": "get_weather" } }` | The model calls that function. This is the only form that makes a tool call deterministic. | A forced function must appear in `tools`, and `"required"` needs at least one tool. Either mistake is `400` `invalid_request`, answered before anything goes upstream. ## Schema bounds The gateway bounds each tool's `parameters` schema by size, depth, and node count. A schema past a bound is `400` `invalid_tool_schema`, which adds three fields: | Field | Meaning | | --- | --- | | `tool` | The function whose schema broke the bound. | | `bound` | Which bound: `bytes`, `depth`, or `nodes`. | | `limit` | That bound's value. | Retrying never helps, because the fix belongs in the tool definitions your client ships. To check them ahead of time, send the same `tools` to `POST /api/v1/tokens/count`: it applies the same bounds with the same `400` answer, is not billed, and returns the input tokens the request would bill, tools included. ## Tools are billed input The provider renders each function's name, description, and parameters into the prompt, so every request that sends `tools` is billed for them as input tokens. Count them with `POST /api/v1/tokens/count`, and keep descriptions as long as the model needs and no longer. ## Where tools work `tools` and `tool_choice` are accepted on `POST /api/v1/chat`, `POST /api/v2/chat`, and `POST /v1/chat/completions`. Each tier reports `supports_tools` in `GET /api/v1/models`; [Models](/docs/en/reference/models) shows how to read the catalog. ## Next steps - [Handle tool calls](/docs/en/build/tool-calls): run the calls the model returns and send the results back. - [Tutorial: build a tool-using agent](/docs/en/build/tool-agent): the full loop in one program. - [Chat](/docs/en/build/chat): the rest of the request and the response. ================================================================================ Page: Handle tool calls URL: https://learn.cruxyai.com/docs/en/build/tool-calls Markdown: https://learn.cruxyai.com/docs/en/build/tool-calls.md ================================================================================ # Handle tool calls Read the tool calls the model returns, run each function, send every result back by tool_call_id, and repeat until finish_reason is stop. When the model decides to call one of the tools you defined, the turn ends with `finish_reason: "tool_calls"` and the assistant message carries `tool_calls`. You run each function, then send a new request with the results; the model reads them and continues. [Define tools](/docs/en/build/tools) covers the request that offers the tools. ## Read the tool calls On `POST /api/v1/chat` with `stream: false`, the assistant reply is the top-level `message`. A turn that calls a tool looks like this, trimmed to the fields that matter here: ```json { "message": { "role": "assistant", "content": "", "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "get_weather", "arguments": "{\"city\":\"Paris\"}" } } ] }, "finish_reason": "tool_calls" } ``` Each entry in `tool_calls` has three fields: | Field | What it is | | --- | --- | | `id` | The call's id. Your result for this call carries it back as `tool_call_id`. | | `type` | `"function"`. | | `function` | The `name` of the function to run, and its `arguments`. | `arguments` is a JSON-encoded string, not an object. Parse it before you dispatch: ```ts const args = JSON.parse(call.function.arguments) // { city: "Paris" } ``` ## Send the results back 1. **Append the assistant message whole** Push the `message` the gateway returned onto your conversation, `tool_calls` included. The model needs its own call in the history next to the result that answers it. 2. **Append one tool message per call** For every entry in `tool_calls`, run the function and append a message with `role: "tool"`, the call's `id` as `tool_call_id`, and the result as a string in `content`. 3. **Call chat again with the same tools** Send the whole conversation back with the same `tools`. The model reads the results and either answers or calls another tool. This request carries a finished tool exchange back to the model: ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "canto", "stream": false, "messages": [ { "role": "user", "content": "What is the weather in Paris?" }, { "role": "assistant", "content": "", "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "get_weather", "arguments": "{\"city\":\"Paris\"}" } } ] }, { "role": "tool", "tool_call_id": "call_abc123", "content": "{\"city\":\"Paris\",\"tempC\":18,\"sky\":\"clear\"}" } ], "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a city", "parameters": { "type": "object", "properties": { "city": { "type": "string" } }, "required": ["city"] } } } ] }' ``` ```ts title="TypeScript" const tools = [ { type: 'function', function: { name: 'get_weather', description: 'Get the current weather for a city', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'], }, }, }, ] // The assistant turn the gateway returned, kept whole. const assistantTurn = { role: 'assistant', content: '', tool_calls: [ { id: 'call_abc123', type: 'function', function: { name: 'get_weather', arguments: '{"city":"Paris"}' }, }, ], } const messages = [ { role: 'user', content: 'What is the weather in Paris?' }, assistantTurn, // Your result, tied back to the call by its id. { role: 'tool', tool_call_id: 'call_abc123', content: JSON.stringify({ city: 'Paris', tempC: 18, sky: 'clear' }), }, ] const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'canto', stream: false, messages, tools }), }) const completion = await res.json() console.log(completion.finish_reason) // "stop" once the model has its answer console.log(completion.message.content) ``` ## Loop on finish_reason `finish_reason` tells you what to do with each turn: | `finish_reason` | What it means | What you do | | --- | --- | --- | | `tool_calls` | The model wants the calls in `message.tool_calls`. | Run them, append the results, and call again. | | `stop` | The model finished its reply. | Read the answer in `message.content`. | | `length` | The output hit `max_tokens` or the tier's cap. | Raise `max_tokens` or lower `reasoning_effort`; see [Reasoning effort](/docs/en/build/reasoning-effort). | | `content_filter` | The upstream model stopped for safety. | Stop the loop and handle the turn as unanswered. | Keep calling while `finish_reason` is `tool_calls`, and stop when it returns `stop`. Put a ceiling on the number of rounds too, so a model that keeps calling tools cannot run your loop forever. ## Several calls in one turn `tool_calls` is an array, so one turn can ask for several calls. Run all of them and append one `tool` message for each before you call chat again. The `tool_call_id` on each result is what pairs it with its call. If a function fails, still answer its call: put a short description of the failure in that tool message's `content`, so every call in the turn has a result. ## Send the tools on every request Keep sending the same `tools` for as long as the conversation holds tool exchanges. When the history replays a tool call to a function that the request's `tools` does not declare, the gateway sends that exchange to the model as prose instead of as a tool call, and reports it in `cruxy.undeclared_tool_replay`: | Field | Meaning | | --- | --- | | `exchanges` | How many assistant messages were sent as prose. | | `tool_calls` | How many tool calls those messages carried. | The field is absent when nothing was rewritten, and nothing you store or send is changed: only what the model reads that turn. ## Tool calls on a stream With `stream: true`, the calls arrive in pieces. Deltas carry `tool_calls` fragments instead of `content`; each fragment has an `index` and a piece of `function.arguments`, and may carry the call's `id`, `type`, and `function.name`. Assemble the fragments per `index`, concatenating the `arguments` pieces. The finish frame with `finish_reason: "tool_calls"` means the calls are complete; answer them as above. [Tool-call deltas](/docs/en/build/streaming#tool-call-deltas) shows the frames. On the native wire, `POST /api/v2/chat`, the fragments ride `delta` events and the terminal `finish` event carries `finish_reason`. ## Next steps - [Tutorial: build a tool-using agent](/docs/en/build/tool-agent): this loop as one working program. - [Define tools](/docs/en/build/tools): the tool shape, `tool_choice`, and schema bounds. - [Streaming](/docs/en/build/streaming): the full frame order. ================================================================================ Page: Tutorial: build a tool-using agent URL: https://learn.cruxyai.com/docs/en/build/tool-agent Markdown: https://learn.cruxyai.com/docs/en/build/tool-agent.md ================================================================================ # Tutorial: build a tool-using agent Build a working TypeScript agent that offers two tools, runs the calls the model returns, and loops on finish_reason until it answers. In this tutorial you build a small agent: one TypeScript file that answers a travel question by calling two functions of yours. It uses `POST /api/v1/chat` with `stream: false` and the loop from [Handle tool calls](/docs/en/build/tool-calls). You finish with a program you can run, and a loop you can reuse with your own tools. ## Before you start - Node.js 22 or later, for the built-in `fetch`. - A developer API key in `CRUXY_API_KEY`; see [Get your API key](/docs/en/get-started/api-keys). - A way to run TypeScript directly. The commands here use `npx tsx`. ## Step 1: Watch one tool call Before writing the loop, send one request by hand and look at what comes back. Offer a `get_weather` tool and ask about the weather: ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "canto", "stream": false, "messages": [ { "role": "user", "content": "What is the weather in Paris?" } ], "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a city", "parameters": { "type": "object", "properties": { "city": { "type": "string" } }, "required": ["city"] } } } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'canto', stream: false, messages: [{ role: 'user', content: 'What is the weather in Paris?' }], tools: [ { type: 'function', function: { name: 'get_weather', description: 'Get the current weather for a city', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'], }, }, }, ], }), }) const { message, finish_reason } = await res.json() console.log(finish_reason) // "tool_calls" console.log(message.tool_calls) ``` When the model chooses the tool, `finish_reason` is `"tool_calls"` and `message.tool_calls` holds the call: an `id`, the function `name`, and its `arguments` as a JSON string. The model does not run anything. Your program runs the function and sends the result back, and the rest of this tutorial automates that. ## Step 2: Describe the tools Create `agent.mts`. Start with the types the loop passes around and the two tools the model may call: ```ts const BASE = 'https://api.cruxy.ai' interface ToolCall { id: string type: 'function' function: { name: string; arguments: string } } type Message = | { role: 'system' | 'user'; content: string } | { role: 'assistant'; content: string; tool_calls?: ToolCall[] } | { role: 'tool'; tool_call_id: string; content: string } interface Completion { message: { role: 'assistant'; content: string; tool_calls?: ToolCall[] } finish_reason: 'stop' | 'tool_calls' | 'length' | 'content_filter' } const tools = [ { type: 'function', function: { name: 'get_weather', description: 'Get the current weather for a city: temperature in Celsius and the sky.', parameters: { type: 'object', properties: { city: { type: 'string', description: 'City name, for example Paris' } }, required: ['city'], }, }, }, { type: 'function', function: { name: 'get_local_time', description: 'Get the current local time in a city.', parameters: { type: 'object', properties: { city: { type: 'string', description: 'City name, for example Mumbai' } }, required: ['city'], }, }, }, ] ``` [Define tools](/docs/en/build/tools) covers every field of a tool. ## Step 3: Write the handlers Each tool name maps to a function of yours. `runTool` parses the call's `arguments`, runs the matching handler, and always returns a string for the tool message, even when the call names an unknown tool or the handler throws: ```ts const TIME_ZONES: Record = { paris: 'Europe/Paris', mumbai: 'Asia/Kolkata', london: 'Europe/London', } const handlers: Record Promise> = { async get_weather({ city }) { // Replace with a call to your weather service. return { city, tempC: 18, sky: 'clear' } }, async get_local_time({ city }) { const timeZone = TIME_ZONES[city.toLowerCase()] if (!timeZone) return { city, error: 'unknown city' } return { city, time: new Date().toLocaleTimeString('en-GB', { timeZone }) } }, } async function runTool(call: ToolCall): Promise { const handler = handlers[call.function.name] if (!handler) return JSON.stringify({ error: `no tool named ${call.function.name}` }) try { const result = await handler(JSON.parse(call.function.arguments)) return JSON.stringify(result) } catch (err) { return JSON.stringify({ error: String(err) }) } } ``` ## Step 4: Call the model `chat` sends the conversation so far, with the tools, and returns the turn. It throws on an error response, naming the stable `code` and the `request_id`: ```ts async function chat(messages: Message[]): Promise { const res = await fetch(`${BASE}/api/v1/chat`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'canto', stream: false, messages, tools }), }) if (!res.ok) { const { code, error, request_id } = await res.json() throw new Error(`${res.status} ${code}: ${error} (request ${request_id})`) } return res.json() } ``` The request leaves `max_tokens` unset. `canto` thinks by default, and its thinking shares the `max_tokens` budget, so a small cap could end a turn with `finish_reason: "length"` before the model writes a call or an answer; see [Reasoning effort](/docs/en/build/reasoning-effort). ## Step 5: Run the loop The loop calls the model, keeps the assistant turn, and branches on `finish_reason`. On `tool_calls` it answers every call by `id` and goes around again; on `stop` the turn's `content` is the answer: ```ts async function runAgent(question: string, maxRounds = 8): Promise { const messages: Message[] = [{ role: 'user', content: question }] for (let round = 0; round < maxRounds; round++) { const { message, finish_reason } = await chat(messages) messages.push(message) // the assistant turn, tool_calls and all if (finish_reason === 'tool_calls') { for (const call of message.tool_calls ?? []) { messages.push({ role: 'tool', tool_call_id: call.id, content: await runTool(call) }) } continue } if (finish_reason === 'stop') return message.content throw new Error(`the turn ended with finish_reason "${finish_reason}"`) } throw new Error(`no answer after ${maxRounds} rounds`) } console.log( await runAgent( 'I fly from Mumbai to Paris tonight. What is the weather in Paris, and what time is it there now?', ), ) ``` ## Step 6: Run it With the four pieces in `agent.mts`, in order, run: ```bash npx tsx agent.mts ``` The program prints the model's answer. Along the way the model asks for `get_weather` and `get_local_time`, possibly both in one turn, and the loop answers each call before it asks again. ## Why the loop is shaped this way - **It branches on `finish_reason`.** `tool_calls` means the model is waiting on your results, and `stop` means it has answered. `length` and `content_filter` end the loop with an error, because neither carries a finished answer. - **It appends the assistant turn whole.** The model needs to see its own call next to the result that answers it, so the turn goes into the history, `tool_calls` included, before any result. - **It answers every call by `id`.** One turn can request several calls. Each result carries its call's `id` as `tool_call_id`, which is how the model pairs results with calls. - **It sends the same `tools` every round.** A replayed call to a tool the request does not declare reaches the model as prose, not as a tool call. - **It always returns a string from `runTool`.** A failed or unknown call still gets a result, so no call goes unanswered. - **It stops after `maxRounds`.** The bound is a backstop for a model that never settles; reaching it is worth logging, not presenting as an answer. ## Next steps - [Handle tool calls](/docs/en/build/tool-calls): the response shapes the loop reads, and tool calls on a stream. - [Define tools](/docs/en/build/tools): `tool_choice` and the schema bounds. - [Errors and retries](/docs/en/build/errors-and-retries): decide which errors `chat` should retry. ================================================================================ Page: Reliability URL: https://learn.cruxyai.com/docs/en/build/reliability Markdown: https://learn.cruxyai.com/docs/en/build/reliability.md ================================================================================ # Reliability Run Cruxy in production: per-tier deadlines, which errors to retry and how, Idempotency-Key, telling a finished stream from a failed one, and status. This page collects what the gateway guarantees when a call is slow or fails, and what it leaves to your client. Each section links to the page that covers its topic in full. The sample streams a long `canto` turn, accepts the answer only once the stream finishes, and retries a failed attempt: ```bash title="curl" # One key per logical request: reuse it if you send this request again. IDEMPOTENCY_KEY=$(uuidgen) # A long canto turn: stream it. --max-time sits above the five-minute limit # on a stream, so the gateway, not curl, decides when the turn has run long. curl -sN --max-time 330 https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ -d '{ "model": "canto", "stream": true, "messages": [ { "role": "user", "content": "Plan a three-day walking tour of Old Delhi." } ] }' > stream.txt # The completion finished only if the stream ended with [DONE]. grep -q '^data: \[DONE\]' stream.txt && echo "complete" || echo "incomplete: send it again" ``` ```ts title="TypeScript" // Your retry budget and timeout. Tune them for your workload; they are not API // limits. A stream may run for up to five minutes, so the timeout sits above it. const MAX_ATTEMPTS = 3 const BASE_DELAY_MS = 500 const TIMEOUT_MS = 330_000 // Transient failures the API marks retryable. const RETRYABLE = new Set([ 'rate_limited', 'credits_unavailable', 'headless_concurrency_limit', 'limits_unavailable', 'upstream_overloaded', 'model_unavailable', 'all_models_unavailable', 'server_shutting_down', 'internal_error', ]) const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) // Exponential backoff with full jitter. const backoff = (attempt: number) => Math.random() * BASE_DELAY_MS * 2 ** attempt type Attempt = { answer: string } | { retryInMs: number } async function streamOnce( body: Record, idempotencyKey: string, attempt: number, ): Promise { let res: Response try { res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey, }, body: JSON.stringify({ ...body, stream: true }), signal: AbortSignal.timeout(TIMEOUT_MS), }) } catch { return { retryInMs: backoff(attempt) } // no response at all: send it again } if (!res.ok) { const { code, error, request_id } = await res.json() if (!RETRYABLE.has(code)) throw new Error(`${res.status} ${code}: ${error} (request_id ${request_id})`) const retryAfter = Number(res.headers.get('Retry-After')) return { retryInMs: retryAfter > 0 ? retryAfter * 1000 : backoff(attempt) } } if (!res.body) return { retryInMs: backoff(attempt) } const reader = res.body.getReader() const decoder = new TextDecoder() let buffer = '' let answer = '' try { while (true) { const { value, done } = await reader.read() if (done) break buffer += decoder.decode(value, { stream: true }) const lines = buffer.split('\n') buffer = lines.pop() ?? '' // keep a partial line for the next read for (const raw of lines) { const line = raw.trim() if (!line.startsWith('data:')) continue const data = line.slice('data:'.length).trim() if (data === '[DONE]') return { answer } // the only success signal const choice = JSON.parse(data).choices[0] // undefined on the usage frame if (choice?.delta.content) answer += choice.delta.content } } } catch { // The connection dropped mid-stream: fall through and treat it as a failure. } // The stream ended before [DONE]: a failed completion. Discard the partial answer. return { retryInMs: backoff(attempt) } } async function chat(body: Record): Promise { // One key per logical request, reused on every retry of it: if two attempts // both complete, the request is billed once. const idempotencyKey = crypto.randomUUID() for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { const result = await streamOnce(body, idempotencyKey, attempt) if ('answer' in result) return result.answer if (attempt < MAX_ATTEMPTS) await sleep(result.retryInMs) } throw new Error(`no complete answer after ${MAX_ATTEMPTS} attempts`) } const answer = await chat({ model: 'canto', messages: [{ role: 'user', content: 'Plan a three-day walking tour of Old Delhi.' }], }) console.log(answer) ``` ## Deadlines and timeouts With `stream: false`, the gateway makes one attempt at the model, bounded by the tier's deadline: | Tier | Deadline | | --- | --- | | `canto` | 90 seconds | | `saga` | 90 seconds | | `epos` | 45 seconds | An attempt that runs past its deadline is cancelled and answered `504` `upstream_timeout`. Nothing is billed, and the gateway does not retry it, since a turn that needed longer needs longer again. The same deadlines apply on all three chat wires: `POST /api/v1/chat`, `POST /api/v2/chat`, and `POST /v1/chat/completions`. - **Stream long turns.** A stream may run for up to five minutes. A long `canto` turn, with reasoning on and a large output, belongs on a stream. - **Or ask for less.** A lower `max_tokens` or `reasoning_effort` shortens the turn; see [Reasoning effort](/docs/en/build/reasoning-effort). - **Set your client timeout above the deadline,** or above five minutes for a stream, so a slow model reaches you as a `504` with a `request_id` rather than as your own abort. ## What the gateway retries for you - **A failing model, inside the gateway.** An overloaded or failing model, or a dropped connection to it, is retried a bounded number of times, with backoff, before the gateway answers `503` `upstream_overloaded` or `model_unavailable`. On a stream, that happens only while the stream opens, never after a byte has reached you. - **Never a non-streaming timeout.** See [Deadlines and timeouts](#deadlines-and-timeouts). - **Never on another tier.** Once a call is sent, it stays on its tier. `model: "auto"` picks a healthy tier before the call, and an explicit tier that keeps failing is refused at once with `503` `model_unavailable` while it cools down. See [Auto routing](/docs/en/build/auto-routing). ## What to retry Branch on the error's `code`, never on its message: | Response | What to do | | --- | --- | | `429` `rate_limited`, `credits_unavailable`, `headless_concurrency_limit`, or `503` `limits_unavailable` | Wait the `Retry-After` seconds, then retry. | | `503` `upstream_overloaded`, `model_unavailable`, `all_models_unavailable`, `service_unavailable`, `server_shutting_down`, or `500` `internal_error` | Back off, then retry. | | `504` `upstream_timeout` on chat | Change the request first: stream it, or lower `max_tokens` or `reasoning_effort`. On embeddings, rerank, and moderations, retry it with backoff; see [Embeddings, rerank, and moderations](#embeddings-rerank-and-moderations). | | `502` `upstream_error` | Do not retry. The model provider rejected the request, and it fails the same way again. | | `429` `budget_exhausted`, `key_spend_cap_exceeded`, `workspace_spend_cap_exceeded`, `credits_exhausted` | Stop. Each clears only at its `reset_at`, or when the cap changes. | | No response, or a stream that ended before it finished | Send the request again, with the same `Idempotency-Key`. | | Any other code | Look it up in [Errors and retries](/docs/en/build/errors-and-retries#which-failures-to-retry). Most describe the request or the key, and fail the same way until you change them. | When you retry: - **Honour `Retry-After`.** Every `429` sends it, and so does a `503` `limits_unavailable`. - **Otherwise back off exponentially, with jitter,** so many clients that failed together do not retry together. - **Cap the attempts and the total wait,** so a persistent failure ends instead of hanging. - **Log the `request_id` of every failure,** retried or not; see [Request IDs and metadata](/docs/en/build/request-ids). ### Embeddings, rerank, and moderations `POST /api/v1/embeddings`, `POST /api/v1/rerank`, and `POST /api/v1/moderations` fail on the model the same way, with one difference from chat: a timeout is worth retrying unchanged. Nothing is billed on any of these: | Response | Retry? | | --- | --- | | `502` `upstream_error` | No. The model provider rejected the request the gateway sent, and the same request fails the same way. | | `503` `upstream_overloaded`, `model_unavailable`, `server_shutting_down`, `limits_unavailable` | Yes, with backoff. `limits_unavailable` sends `Retry-After: 5`. | | `503` `service_unavailable` | Yes, in a few minutes. The model provider refused to serve Cruxy at all: an outage on Cruxy's side, never caused by the request. | | `504` `upstream_timeout` | Yes, with backoff. Unlike a chat turn, the same request is not expected to take as long again. | ## Retry safely with Idempotency-Key Send an `Idempotency-Key` header, one per logical request, and reuse it on every retry of that request: - **A success is stored for 24 hours.** A later or concurrent call with the same key and the same body replays it byte for byte, without calling the model and without billing again. A concurrent duplicate waits for the first call to finish. - **Only a success is stored.** An error, a `429` or any `5xx` included, releases the key, so a retry with the same key and body runs the request again. That is the intended way to retry. - **A different body under the same key** is `409` `idempotency_conflict`. - **A response over 256 KiB** is served but not stored, so a retry runs again. It is still billed once. - **A key is at most 255 characters,** and is scoped to your API key and the endpoint. - **A stream stores and replays nothing.** A retry with the same key and body streams a new generation. When both attempts complete, the request is billed once; an attempt that did not complete is billed for the tokens it delivered, and the retry is billed as well. [Errors and retries](/docs/en/build/errors-and-retries#make-retries-idempotent) lists the endpoints that accept the header. ## Confirm a stream finished Once a stream opens, its `200` is already sent, so a failure after that point cannot change the status. How the stream tells you it failed depends on the wire: - **`POST /api/v1/chat`:** `data: [DONE]` is the only success signal. A failure after the stream opens sends no error frame; the stream stops early. Treat a stream that ends before `[DONE]` as a failed completion: discard the partial output or retry, and never show it as a finished answer. - **`POST /api/v2/chat`:** the stream always ends with exactly one `finish` or `error` frame. It has no `[DONE]`. - **`POST /v1/chat/completions`:** a failure after the stream opens ends it with a `data: {"error": {...}}` frame instead of `[DONE]`. The tokens a failed stream delivered are billed as a partial usage row. [Streaming](/docs/en/build/streaming#done-is-the-only-success-signal) shows how to detect each case. ## Check platform status [status.cruxyai.com](https://status.cruxyai.com) is the Cruxy status page. For the same picture in code, `GET /api/status` returns a status document. It takes no key. ```bash title="curl" curl https://api.cruxy.ai/api/status ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/status') // A 503 still carries the document, with status "unknown": no model component // has a fresh measurement, so the document cannot be trusted. const status = await res.json() console.log(`platform: ${status.status}`) // public_id names a chat tier by its public id. A chat tier's id keeps the // tier's former name, so map it only when public_id is absent. const FORMER_IDS: Record = { kavi: 'canto', vaani: 'saga', mira: 'epos' } // Iterate the array and read each row's kind; new components are appended. for (const component of status.components) { const id = component.public_id ?? FORMER_IDS[component.id] ?? component.id console.log(`${id} (${component.kind}): ${component.status}`) } ``` - **`status`** is the whole platform in one word: `healthy`, `degraded`, `down`, or `unknown`. - **`components`** has a row for the API, the database, each chat tier, and the `cruxy-embed`, `cruxy-rerank`, and `cruxy-guard` models, each with its own `status` and when it was last checked. A component that is measurably down is a `200` carrying `down`; the document is a `503` only when no model component has a fresh measurement. - **`public_id` names each component by its public id.** A chat tier's component `id` keeps its former name on every version to date (`kavi` is Canto, `vaani` is Saga, and `mira` is Epos), and its `public_id` is `canto`, `saga`, or `epos`. On every other component, `public_id` equals `id`. Compare `public_id` against the tier ids. If a component has no `public_id`, map its former id, as the sample does. - **The verdicts come from active probes,** not from live traffic, and the response is never cached. `GET /api/health` reports only that the gateway's HTTP listener is up. It checks no model or database, so do not read it as platform status. ## Production checklist The short list for reliability is below. The full list, with keys, memory, and logging, is [Production checklist](/docs/en/best-practices/production-checklist). - **Use a developer API key on a server.** See [Get your API key](/docs/en/get-started/api-keys). - **Pin `Cruxy-Version`,** and ignore JSON fields you do not recognize. - **Set client timeouts above the tier deadline,** or above five minutes for a stream. - **Stream long `canto` turns,** and size `max_tokens` for the thinking as well as the answer. - **Send an `Idempotency-Key`** on every request that takes one, and reuse it on that request's retries. - **Retry only what the table above says,** honouring `Retry-After`, with a cap on attempts. - **Check for `[DONE]`,** or a `finish` frame on v2, before you show a streamed answer. - **Log the `X-Request-Id`, the `request_id`, and the `Cruxy-Version`** of every call. - **Read [Known limitations](/docs/en/build/known-limitations)** before you launch. ## Next steps - [Errors and retries](/docs/en/build/errors-and-retries): every error code, and a retrying client. - [Streaming](/docs/en/build/streaming): the frames, and a complete stream reader. - [Rate limits and budgets](/docs/en/build/rate-limits): read your headroom before you hit a `429`. - [Known limitations](/docs/en/build/known-limitations): what the API does not do yet, and the workarounds. ================================================================================ Page: Errors and retries URL: https://learn.cruxyai.com/docs/en/build/errors-and-retries Markdown: https://learn.cruxyai.com/docs/en/build/errors-and-retries.md ================================================================================ # Errors and retries Read the error envelope, look up every error code the API defines, and decide which failures to retry and how long to wait. A failed request returns a non-2xx status and a JSON error body. Read the HTTP status first, then branch on the body's `code`: the code is stable, while the wording of the message can change. ## The error envelope ```json { "code": "invalid_request", "error": "invalid JSON body", "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" } ``` | Field | Meaning | | --- | --- | | `code` | A stable, machine-readable error code. Branch on this. | | `error` | A human-readable message. Log it; do not parse it. | | `request_id` | The id of the failed call, equal to the response's `X-Request-Id` header. Log it with every failure; see [Request IDs and metadata](/docs/en/build/request-ids). | Some codes add fields next to these three. Each is optional, and present only on the codes listed: | Field | Sent on | | --- | --- | | `tier` | The tier a model failure or context check was about: `upstream_error`, `upstream_overloaded`, `upstream_timeout`, `model_unavailable`, `service_unavailable`, `server_shutting_down`, and `client_closed_request` on chat, `context_overflow`, and `image_not_supported`. | | `reason` | Why: `rate` or `concurrency` on `rate_limited` from chat; why a document's text could not be read on `file_not_text`. | | `retry_after` | The `Retry-After` value in seconds: `rate_limited`, `limits_unavailable`, `credits_unavailable`, `headless_concurrency_limit`. | | `reset_at` | When the refusal clears (RFC 3339): `budget_exhausted`, `api_share_exhausted`, `key_spend_cap_exceeded`, `workspace_spend_cap_exceeded`, `credits_exhausted`, `file_limit_reached`, and `image_limit_reached`. `null` on `model_not_allowed`, since waiting never clears an allowlist. | | `model`, `state`, `window`, `epos_available`, `mira_available` | A spend or budget refusal: `budget_exhausted`, `api_share_exhausted`, `key_spend_cap_exceeded`, `workspace_spend_cap_exceeded`, `model_not_allowed`. `model_not_in_plan` sends `model` and `plan` alone, and `file_limit_reached` and `image_limit_reached` send `state` and `window` with no `model`. `window` is `monthly` or `burst`; `epos_available` says whether the same request on `epos` would be served now. `mira_available` is the same value under the field's former name, kept so existing code keeps working; read `epos_available`. | | `balance`, `currency` | A headless key's remaining credit, on `credits_exhausted`. | | `dimension` | The check that faulted on `limits_unavailable`: `rate` or `budget`. | | `required_scope`, `allowed_scopes` | The family the key would need and the families it has, on `key_scope_forbidden`. | | `required_version` | The `Cruxy-Version` a request field needs pinned, on `invalid_request`. | | `hazard_codes` | The blocking classifier codes behind `moderation_rejected`. | | `tool`, `bound`, `limit` | The function and the cap it broke, on `invalid_tool_schema`. `bound` and `limit` also name the cap on `file_too_large`, and `bound` is `chunk` or `input` on `input_not_countable`. `limit` is the context window on `context_overflow`, the plan's monthly allowance on `file_limit_reached` and `image_limit_reached`, the plan's largest upload in bytes on `payload_too_large`, and its storage pool in bytes on `storage_quota_exceeded`. | | `file_id`, `filename`, `content_type`, `tokens` | The refused file, on `file_not_found`, `file_not_text`, `file_too_large`, and `image_not_supported`. | | `vision_tiers` | The tiers that read images, heaviest first, on `image_not_supported`. | | `measured_bytes`, `limit_bytes` | The size and the cap on `input_not_countable`. `limit_bytes` alone is the moderation gate's limit on `moderation_input_too_large`. | Ignore fields you do not recognize. Three surfaces use a different shape: - **`POST /v1/chat/completions`** uses the OpenAI envelope, `{"error": {"message", "type", "param", "code"}}`. Its `code` is the same Cruxy code listed here; `type` is a coarse category derived from the status (`invalid_request_error`, `authentication_error`, `permission_error`, `not_found_error`, `rate_limit_error`, or `server_error`); `param` is always `null`. Only the code travels: none of the fields in the table above, such as `tier` or `hazard_codes`, are carried. - **Device login** answers a pending or refused poll with an OAuth-style body; see [Get your API key](/docs/en/get-started/api-keys#device-login). - **A `POST /api/v2/chat` stream** that fails after it opens ends with an `error` event carrying `code`, `error`, and `request_id`. ## Handle errors and retry safely This request sends an `Idempotency-Key`, so once it succeeds, running it again with the same key replays the stored response instead of calling the model and billing again. The gateway stores only a success, so a retry after an error runs the request again under the same key. The TypeScript version retries the codes the API marks retryable, waiting `Retry-After` when it is sent, and retries a request that got no response with the same key: ```bash title="curl" IDEMPOTENCY_KEY=$(uuidgen) # -i prints the status line and headers, including Cruxy-Version and the # X-RateLimit-* headers. Run it twice: once the first call succeeds, the # second replays it. curl -i https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ -d '{ "model": "saga", "stream": false, "messages": [ { "role": "user", "content": "Hello" } ] }' ``` ```ts title="TypeScript" class CruxyError extends Error { constructor( readonly status: number, readonly code: string, readonly requestId: string, message: string, ) { super(`${status} ${code}: ${message} (request_id ${requestId})`) } } // Your retry budget and timeout. Tune them for your workload; they are not API limits. // TIMEOUT_MS sits above the longest tier deadline (90 s), so a slow model // reaches you as 504 upstream_timeout rather than as your own abort. const MAX_ATTEMPTS = 4 const BASE_DELAY_MS = 500 const TIMEOUT_MS = 120_000 // Transient failures the API marks retryable. upstream_timeout is left out: // the gateway already made its one attempt, and the same request usually // times out again. const RETRYABLE = new Set([ 'rate_limited', 'credits_unavailable', 'headless_concurrency_limit', 'limits_unavailable', 'upstream_overloaded', 'model_unavailable', 'all_models_unavailable', 'server_shutting_down', 'internal_error', ]) const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) // Exponential backoff with full jitter. const backoff = (attempt: number) => Math.random() * BASE_DELAY_MS * 2 ** attempt async function chat(body: Record) { // One key per logical request, reused on every retry of it. const idempotencyKey = crypto.randomUUID() for (let attempt = 1; ; attempt++) { let res: Response try { res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey, }, body: JSON.stringify({ ...body, stream: false }), signal: AbortSignal.timeout(TIMEOUT_MS), }) } catch (err) { // No response: the call may or may not have run. If it succeeded, the // same key replays its stored response rather than running and billing // it a second time; if it failed, the same key runs it again. if (attempt >= MAX_ATTEMPTS) throw err await sleep(backoff(attempt)) continue } if (res.ok) return res.json() const { code, error, request_id } = await res.json() // An error is never stored, so the same key runs the request again. if (RETRYABLE.has(code) && attempt < MAX_ATTEMPTS) { const retryAfter = Number(res.headers.get('Retry-After')) await sleep(retryAfter > 0 ? retryAfter * 1000 : backoff(attempt)) continue } throw new CruxyError(res.status, code, request_id, error) } } const completion = await chat({ model: 'saga', messages: [{ role: 'user', content: 'Hello' }], }) console.log(completion.message.content) ``` ## Which failures to retry | Failure | Retry? | How | | --- | --- | --- | | `429` `rate_limited`, `credits_unavailable`, `headless_concurrency_limit` | Yes | Wait `Retry-After` seconds, then retry. | | `503` `upstream_overloaded`, `model_unavailable`, `all_models_unavailable`, `service_unavailable`, `server_shutting_down`, `limits_unavailable` | Yes | Back off, honouring `Retry-After` where it is sent. The gateway already retried the model before it answered `upstream_overloaded` or `model_unavailable`. | | `500` `internal_error` | Yes | Back off. A write may have run, so retry with the same `Idempotency-Key` where the route takes one. | | `504` `upstream_timeout` on chat | Only if changed | The same request usually times out again. Stream it, or lower `max_tokens` or `reasoning_effort`; see [Timeouts](#timeouts). | | `504` `upstream_timeout` on embeddings, rerank, or moderations | Yes | Back off, then retry unchanged; see [Embeddings, rerank, and moderations](/docs/en/build/reliability#embeddings-rerank-and-moderations). | | `429` `budget_exhausted`, `api_share_exhausted`, `key_spend_cap_exceeded`, `workspace_spend_cap_exceeded`, `credits_exhausted`, `file_limit_reached`, `image_limit_reached` | Not now | The allowance clears only at `reset_at`, or when the cap changes. `Retry-After` counts down to that moment. | | `403` `model_not_in_plan` | No | The account's plan does not include the tier the request named. Send a tier from `models` on `GET /api/v1/limits`, or `auto`; see [Plan limits](/docs/en/build/plan-limits). | | `422` `structured_output_unsatisfied` | Yes | It may pass on a retry. The attempt was billed; a retry with the same key and body is not billed again. | | `409` `idempotency_conflict` | Yes, adjusted | Resend the original body to replay the stored response, or send the new body under a new key. | | No response at all: a dropped connection or your own timeout | Yes | Retry with the same `Idempotency-Key`. | | A stream that ended before `data: [DONE]` | Yes | Send the request again; see [Streaming](/docs/en/build/streaming#done-is-the-only-success-signal). | | `502` `upstream_error` from a model call | No | The model provider rejected the request, and it fails the same way again. From native sign-in it is retryable. | | `503` `count_unavailable` | No | A fact of the deployment; it does not clear. | | Every other code | No | It describes the request or the credential. Fix the request, the key, or the target first. | [Rate limits and budgets](/docs/en/build/rate-limits) explains the difference between a rate limit and a budget, and how to read your remaining headroom. ### Timeouts With `stream: false`, the gateway makes one attempt at the model, bounded by the tier's deadline: | Tier | Deadline | | --- | --- | | `canto` | 90 seconds | | `saga` | 90 seconds | | `epos` | 45 seconds | An attempt that runs past the deadline is cancelled and answered `504` `upstream_timeout`, and nothing is billed. The gateway does not retry a timeout: a turn that needed longer needs longer again. Send `stream: true` instead, since a stream may run for up to five minutes, or ask for less with a lower `max_tokens` or `reasoning_effort`. [Reliability](/docs/en/build/reliability) collects the deadlines, retries, and stream checks in one place. Other upstream failures, such as an overloaded or failing model or a dropped connection, are retried inside the gateway a bounded number of times, with backoff, before it answers `503` `upstream_overloaded` or `model_unavailable`. On `stream: true` that happens only while the stream opens, never after a byte has reached you. A call never moves to another tier once it is sent: `model: "auto"` picks a healthy tier before the call, and an explicit tier that keeps failing is refused at once with `503` `model_unavailable` while it cools down. ### Back off - **Honour `Retry-After`.** Every `429` carries it, and so does a `503` `limits_unavailable`. On `rate_limited`, `X-RateLimit-Reset` gives the same moment as an absolute Unix time in seconds. On a budget or spend-cap refusal, `Retry-After` counts down to `reset_at` instead, while the `X-RateLimit-*` headers still describe the per-minute request window. - **Otherwise back off exponentially, with jitter.** Double the wait after each failed attempt and randomize it, so many clients that failed together do not retry together. - **Cap the attempts and the total wait.** A retry budget keeps a persistent failure from turning into a stuck request. - **Log `request_id` for every failure,** retried or not. ### Make retries idempotent `Idempotency-Key` makes a retry safe. The first call with a key is served, and when it succeeds its response is stored for 24 hours. A later or concurrent call with the same key and the same body replays that response byte for byte, without calling the model again and without billing again; a concurrent duplicate waits for the first call to finish. Only a success is stored. An error, a `429` or any `5xx` included, releases the key, so a retry with the same key and body runs the request again. Reusing the key is the intended way to retry a `429` or a `5xx`. - **Scope:** a key belongs to your API key and to the endpoint. On a conversation append, it belongs to the conversation. - **Conflicts:** the same key with a different body is `409` `idempotency_conflict`. - **Large responses:** a response over 256 KiB is served but not stored, so a retry runs again. It is still billed once. - **Length:** keys are at most 255 characters. These endpoints accept it: - `POST /api/v1/chat`, `POST /api/v2/chat`, and `POST /v1/chat/completions` - `POST /api/v1/embeddings`, `POST /api/v1/rerank`, and `POST /api/v1/moderations` - `POST /api/v1/conversations/{id}/messages` and `POST /api/v1/conversations/{id}/messages/batch`, which store their `201` and replay it without appending a second time `POST /api/v1/files` reads the header for the upload count alone: a retry under the same key and content is counted once, but every attempt stores a file. > **Note:** A `stream: true` chat stores and replays nothing, because a stream cannot be > replayed. A retry with the same key and body streams a new generation; when > both attempts complete, the request is billed once. An attempt that did not > complete is billed for the tokens it delivered, and the retry is billed as well. ## Error codes The codes the API defines, grouped by the status each is returned with. Codes that belong to a feature that is switched off are left out. ### 400 Bad Request The request itself is wrong. Fix it; sending it again unchanged fails the same way. | `code` | Meaning | | --- | --- | | `invalid_request` | Malformed JSON, or a field that is missing or invalid. Carries `required_version` when the request uses a field that needs a newer `Cruxy-Version` pin. | | `context_overflow` | The input exceeds the context window: the smaller of the tier's and the plan's, named in `limit`. | | `moderation_input_too_large` | Chat only (`POST /api/v1/chat`, `POST /api/v2/chat`, and `POST /v1/chat/completions`). The input moderation gate reads the whole request: every message of every role, tool-call arguments, and the text of attached files. Text it already passed for your account, such as earlier turns of the same thread, is not read again. A turn that brings more new text than the gate reads in one request is refused rather than served unread. Carries `limit_bytes`, that limit in bytes (262,144 by default), except on `POST /v1/chat/completions`, whose envelope has no place for it. Nothing is billed. The same body fails the same way: send the new text over several turns. | | `invalid_schema` | A `response_format` JSON schema is malformed, oversized, too deep, or uses an unsupported keyword. | | `invalid_tool_schema` | A tool's `parameters` schema exceeds a bound. Adds `tool`, `bound`, and `limit`. The fix belongs in your client, so a retry cannot help. | | `file_not_text` | A file named in `file_ids` cannot be read as text. Names the file; a document that could not be read also carries a `reason`. | | `file_too_large` | A file named in `file_ids` exceeds a size cap. Names the file, with `bound`, `limit`, and `tokens`. | | `image_not_supported` | A file named in `file_ids` on this turn is an image, and the tier serving the turn does not read images. Names the image and the tier, and lists the tiers that do in `vision_tiers`. | | `moderation_rejected` | The server-side input moderation gate refused the request's text. Carries `hazard_codes`. Not billed. | | `pii_rejected` | A memory or rule contains an email address, phone number, or card number. Rephrase without it and retry. | | `rules_too_large` | A ruleset exceeds a size cap. Names the cap. | | `input_not_countable` | `POST /api/v1/tokens/count` refuses to count this text and returns no count. | | `invalid_version` | The `Cruxy-Version` header is not a `YYYY-MM-DD` date. Answered on every route, before authentication. | | `unknown_version` | `Cruxy-Version` is a well-formed date this server does not support. The message lists the supported dates. Answered on every route, before authentication. | | `invalid_payload` | `POST /api/v1/feedback` only: the payload does not match the schema for its type. | | `provider_not_supported` | Native sign-in named a provider that is not supported. | | `redirect_uri_not_allowed` | Native sign-in named a redirect URI that is not allowlisted. | | `scope_unsupported` | Retired: never sent. It stays in the vocabulary so the string is never reused. | ### 401 Unauthorized | `code` | Meaning | | --- | --- | | `unauthorized` | The Bearer credential is missing, malformed, unknown, expired, or revoked, or its holder no longer belongs to the organization it names. Each case gets the same answer, with `WWW-Authenticate: Bearer`. It is the only `401` code; see [Get your API key](/docs/en/get-started/api-keys#expiry-and-revocation). | ### 403 Forbidden The credential is genuine, but it cannot make this call. Waiting never widens a credential, so retrying cannot succeed. | `code` | Meaning | | --- | --- | | `account_suspended` | The key's owner's account is suspended. | | `credential_quarantined` | The organization the key belongs to could not be established, so the key is refused rather than trusted. Signing in again does not clear it; contact support. | | `forbidden_bucket` | The credential's billing kind cannot be billed on this route. No key issued today can reach it. | | `key_scope_forbidden` | The key is not scoped for this endpoint family, or for the memory, rules, or files feature a request field asked for. Names `required_scope` in the second case. Re-scope or re-issue the key. | | `model_not_allowed` | The key's model allowlist excludes the requested tier. | | `model_not_in_plan` | Chat only: the request named a tier the account's plan does not include. Carries `model` and `plan`. | | `plan_required` | A developer API key whose owner's plan does not include API access. A signed-in credential is not refused this way. | | `web_credential_required` | The route is available to Cruxy's own apps only, not to API keys or CLI logins. | | `key_read_only` | The key may not perform billable operations. | | `org_forbidden` | The operation needs an organization owner or admin. | | `workspace_forbidden` | Workspace management needs an organization owner or admin. | | `logs_forbidden` | Request logs need an organization owner or admin. | | `rules_forbidden` | You may not read or change this ruleset. | | `vault_forbidden` | You take part in the vault but lack the permission the operation needs. | | `conversation_forbidden` | The conversation is in a vault you may read but not write. | ### 404 Not Found The target does not exist, or you cannot see it. The API gives the same answer for an id that is missing and one you cannot see, so a `404` never confirms that an id exists. | `code` | What was not found | | --- | --- | | `user_not_found` | A user. | | `file_not_found` | A file of yours under this key's organization, including one named in `file_ids`. | | `request_not_found` | A `request_id` from a call this account made, on `POST /api/v1/feedback`. | | `memory_suggestion_not_found` | `POST /api/v1/memories/suggestions/{id}/approve` and `/reject` only: your organization has no pending suggestion with that id. One already approved or rejected, one in another organization, and one that never existed all get this answer. | | `memory_not_found` | A memory. | | `vault_not_found` | A vault you take part in. | | `vault_member_not_found` | A vault member. | | `org_member_not_found` | An organization member. | | `invitation_not_found` | An invitation addressed to you that is still open. | | `workspace_not_found` | A workspace in your organization. | | `log_not_found` | A request log in your organization. | | `conversation_not_found` | A conversation you can see. | | `message_not_found` | A message in the conversation. | | `prompt_not_found` | A prompt in your workspace. | | `prompt_version_not_found` | That version of the prompt. | | `eval_suite_not_found` | An eval suite in your workspace. | | `eval_run_not_found` | An eval run in your workspace. | | `eval_case_not_found` | A case in that eval suite. | ### 409 Conflict The request conflicts with existing state. Only `idempotency_conflict` has a retry path. | `code` | Meaning | | --- | --- | | `idempotency_conflict` | The `Idempotency-Key` was reused with a different body. Resend the original body to replay the stored response, or use a new key. | | `vault_name_exists` | A vault with this name already exists in your organization. | | `vault_external_id_conflict` | The `external_id` names a vault somebody else owns. | | `vault_member_exists` | The user is already a member of the vault. | | `org_member_exists` | The user is already a member of the organization. | | `org_member_active` | The member has not left the organization. | | `workspace_slug_exists` | A workspace with this slug already exists. | | `workspace_not_empty` | The workspace holds, or has held, a credential, so it cannot be deleted. | | `workspace_is_default` | The default workspace cannot be deleted. | | `prompt_slug_exists` | A prompt with this slug already exists. | | `eval_suite_slug_exists` | An eval suite with this slug already exists. | ### 413 Payload Too Large | `code` | Meaning | | --- | --- | | `payload_too_large` | The upload or message is over its size cap. | | `storage_quota_exceeded` | The upload would take your files past your total storage allowance. | ### 422 Unprocessable Content | `code` | Meaning | | --- | --- | | `structured_output_unsupported` | The tier that served the request does not support constrained decoding for `response_format`. | | `structured_output_unsatisfied` | The model's non-streaming output did not satisfy the requested JSON schema. The request is still billed. | ### 429 Too Many Requests Every `429` carries `Retry-After`, and nothing is billed. | `code` | Meaning | | --- | --- | | `rate_limited` | Too many requests: `reason` is `rate` (the per-minute request window) or `concurrency` (too many of your requests in flight at once). Retry after `Retry-After`. | | `budget_exhausted` | A signed-in plan's monthly or 12-hour burst pool is spent, or `epos`'s monthly request cap. `epos_available` says whether the same request on `epos` would be served now. Clears at `reset_at`. | | `api_share_exhausted` | Chat, embeddings, and rerank, on a developer API key: the account's developer keys have used the plan's API share, 25% of its monthly units. Clears at `reset_at`. | | `file_limit_reached`, `image_limit_reached` | `POST /api/v1/files`: the plan's monthly allowance of stored files or images is used. Clears at `reset_at`. | | `message_limit_reached` | Retired: never sent. It stays in the vocabulary so the string is never reused. | | `key_spend_cap_exceeded` | The key's monthly spend cap is spent. Clears at `reset_at`. | | `workspace_spend_cap_exceeded` | The workspace's monthly spend cap is spent. Clears at `reset_at`. | | `credits_exhausted` | A headless key's credit pool is drained. Clears at `reset_at`. | | `credits_unavailable` | A headless key's credit balance could not be read. Retry after `Retry-After` (2 seconds). | | `headless_concurrency_limit` | Chat only: a headless key already has its maximum requests in flight. Retry after `Retry-After` (1 second). | ### 5xx Server errors On chat, every model failure adds `tier`, and none is billed. | `code` | Status | Meaning | | --- | --- | --- | | `internal_error` | `500` | An unexpected server fault, on any route. Retry with backoff. | | `upstream_error` | `502` | On a model call, the model provider rejected the request the gateway sent, and a retry fails the same way. On native sign-in, the identity provider could not be reached or answered unusably; retry. | | `upstream_overloaded` | `503` | The model is overloaded, and the gateway's own retries ran out. Retry with backoff. | | `model_unavailable` | `503` | The tier is temporarily unavailable: it kept failing and is cooling down, or it failed again on this request after the gateway's retries. Retry with backoff. | | `all_models_unavailable` | `503` | Chat only: `model: "auto"` was sent and every tier is unavailable. Retry with backoff. | | `service_unavailable` | `503` | The model provider refused to serve Cruxy at all: an outage on Cruxy's side, never caused by the request. Nothing is billed. Retry in a few minutes. | | `server_shutting_down` | `503` | The gateway restarted, for a deploy, before it answered. Retry with backoff. | | `limits_unavailable` | `503` | A rate-limit or budget check could not be read, so the request was refused rather than served unmetered. Adds `dimension`. Retry after `Retry-After` (5 seconds). | | `count_unavailable` | `503` | `POST /api/v1/tokens/count` cannot count for this tier, because the count could disagree with billing. It does not clear on a retry. | | `upstream_timeout` | `504` | The model did not answer in time. With `stream: false` the gateway made one attempt and does not retry it; see [Timeouts](#timeouts). On embeddings, rerank, and moderations it is transient: retry with backoff. | ### Stream errors A stream that fails after it opens has already sent its `200`, so the code arrives in the stream, not the status: - `POST /api/v2/chat` ends with an `error` event whose `code` is one of `upstream_error`, `upstream_overloaded`, `upstream_timeout`, `model_unavailable`, `server_shutting_down`, or `internal_error`. - `POST /v1/chat/completions` ends with a `data: {"error": {...}}` frame. - `POST /api/v1/chat` sends no error frame: the stream ends without `data: [DONE]`; see [Streaming](/docs/en/build/streaming#done-is-the-only-success-signal). ### Codes in request logs `client_closed_request` (`499`) records that the caller disconnected before the gateway had an answer. Nobody receives it; it appears only in request logs. ## Next steps - [Reliability](/docs/en/build/reliability): deadlines, retries, idempotency, and platform status together. - [Request IDs and metadata](/docs/en/build/request-ids): find the `request_id` and quote it when you report a problem. - [Rate limits and budgets](/docs/en/build/rate-limits): read your headroom before you hit a `429`. - [Streaming](/docs/en/build/streaming): detect a stream that failed partway. - [Get your API key](/docs/en/get-started/api-keys): fix `401` and `403` at the key. ================================================================================ Page: Rate limits and budgets URL: https://learn.cruxyai.com/docs/en/build/rate-limits Markdown: https://learn.cruxyai.com/docs/en/build/rate-limits.md ================================================================================ # Rate limits and budgets How the gateway meters you: rate_limited versus budget_exhausted, the rate-limit headers, spend caps, and reading your live headroom. Two separate controls can refuse a request with `429`: a **rate limit** on how fast you send requests, and a **budget** on how much you spend. The body's `code` tells you which one you hit, and they need different handling. Your account's limits are shown in your Console, and `GET /api/v1/limits` returns them, with live headroom, to your code. ## rate_limited or budget_exhausted | | rate_limited | budget_exhausted | | --- | --- | --- | | What ran out | Request rate: too many requests in the current window. | Allowance: the plan's monthly cap, its 12-hour burst pool, or the monthly `epos` request cap is spent. A developer key that has used the plan's API share reads `api_share_exhausted` instead. | | What to do | Back off and retry after `Retry-After`. | Stop retrying. No immediate retry succeeds. | | Clears | When the rate window resets. | At `reset_at`, when the spent window resets. | | Headroom | `rate_limits.chat` on `GET /api/v1/limits` | `token_pool` and `api_share` on `GET /api/v1/limits` | Spend caps refuse with `429` too, under their own codes: a monthly cap on a key (`key_spend_cap_exceeded`), a monthly cap on a workspace (`workspace_spend_cap_exceeded`), and the credit pool (`credits_exhausted`). Like `budget_exhausted`, they mean an allowance is spent, and they clear only at `reset_at` or when the cap changes. Every `429` carries `Retry-After`; on these codes and on `budget_exhausted` it counts down to `reset_at`, and retrying sooner fails the same way. `POST /api/v1/moderations` never returns `budget_exhausted`: moderation is exempt from the subscription pool, so a spent allowance cannot switch it off. It can still return `rate_limited` or a spend-cap code. ## Rate-limit headers Metered responses carry the state of the bucket the route is metered on: | Header | Meaning | | --- | --- | | `X-RateLimit-Limit` | Requests allowed per window. | | `X-RateLimit-Remaining` | Requests left in the current window, never below `0`. | | `X-RateLimit-Reset` | When the current window ends, as an absolute Unix time in seconds, not a duration. | | `Retry-After` | On every `429`, the seconds to wait. On a budget or spend-cap refusal, the seconds until `reset_at`. | The `X-RateLimit-*` headers always describe the per-minute request window, so a budget refusal can still show requests remaining. The `X-RateLimit-*` headers are absent on a `401`, because authentication runs before the limiter, and on a `403` from the key check (`key_scope_forbidden`, `key_read_only`). They are also absent when the limiter cannot reach its own storage; that request is served unmetered, or refused with `503` `limits_unavailable` where the deployment fails closed. ```bash title="curl" # -D - prints the response headers; look for X-RateLimit-* and, on a 429, Retry-After. curl -s -D - -o /dev/null https://api.cruxy.ai/api/v1/limits \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" // These clear only at reset_at; every other 429 clears after Retry-After. const ALLOWANCE_SPENT = new Set([ 'budget_exhausted', 'key_spend_cap_exceeded', 'workspace_spend_cap_exceeded', 'credits_exhausted', ]) const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'epos', stream: false, messages: [{ role: 'user', content: 'Hello' }], }), }) const remaining = res.headers.get('X-RateLimit-Remaining') const resetAt = res.headers.get('X-RateLimit-Reset') // Unix seconds if (res.status === 429) { const { code, reset_at, request_id } = await res.json() const waitSeconds = Number(res.headers.get('Retry-After')) if (ALLOWANCE_SPENT.has(code)) { // No retry succeeds before reset_at. console.log(`allowance spent: ${code}, resets at ${reset_at} (request_id ${request_id})`) } else { // rate_limited, or a transient headless check: wait Retry-After, then retry. console.log(`${code}; retry in ${waitSeconds}s (request_id ${request_id})`) } } else if (remaining !== null) { console.log(`${remaining} requests left until ${new Date(Number(resetAt) * 1000).toISOString()}`) } ``` Pace yourself before you reach `0`: when `X-RateLimit-Remaining` runs low, slow down until `X-RateLimit-Reset` rather than waiting for a `429`. ## Read your limits `GET /api/v1/limits` returns the limits that apply to your key, with live headroom. Every value comes from the same limiter and budget state that chat enforces, so `remaining` is exactly what your next request is checked against. The call costs nothing, writes nothing, and is rate-limited like any other route. ```bash title="curl" curl https://api.cruxy.ai/api/v1/limits \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/limits', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) if (!res.ok) throw new Error(`limits request failed: ${res.status}`) const limits = await res.json() const perKey = limits.rate_limits.chat.per_key console.log(`chat: ${perKey.remaining} of ${perKey.limit} left this window`) if (limits.token_pool) { console.log(`token pool: ${limits.token_pool.state}`) // healthy, low, or blocked } ``` Everything comes from the key you send; nothing is read from the request. Which blocks appear depends on your billing `bucket`: | Field | Meaning | | --- | --- | | `object` | `limits`. | | `bucket` | Which kind of key this is: `subscription` (a signed-in credential), `apikey` (a developer API key, which draws on its owner's plan and needs a paid one), or `headless` (billed from prepaid `credits`). Both `subscription` and `apikey` carry `token_pool`. Memory and standing rules are on by default only for `subscription`. | | `tier` | Your account's plan: `free`, `core`, `advanced`, `pro`, or `max`. It sizes `token_pool` and picks the `plan_limits` row; see [Plan limits](/docs/en/build/plan-limits). A Pro subscription from the beta reads `pro_legacy` and has Pro's limits. The field can also read `ultra` or `enterprise`. This is not a model tier. | | `models` | Subscription and developer-key buckets. The chat tiers your plan includes, by public id: `saga` on Free; `epos` and `saga` on Core; all three from Advanced. A request naming another is `403` `model_not_in_plan`, and `auto` routes only among these. | | `context_window` | Subscription and developer-key buckets. `plan` is your plan's window in tokens (256,000 on Free, 1,000,000 on a paid plan), and `models` maps each included tier to its effective window, the smaller of the tier's own and the plan's. A turn past it is `400` `context_overflow`. | | `api_share` | On every plan with API access. The share of the month's `token_pool` that developer API keys together may use: `share` (`0.25`), `cap`, `used`, `remaining`, `state`, `window` (`monthly`), `starts_at`, and `resets_at`, in `units`. Past it a developer-key request is `429` `api_share_exhausted`; a signed-in credential is never counted or refused by it. | | `rate_limits.chat.max_concurrent_per_key` | Developer keys only. How many chat requests this key may have in flight at once, streaming or not, within the account's `max_concurrent_requests`. One more is `429` `rate_limited` with `reason: concurrency` and `Retry-After: 1`. | | `rate_limits.chat.per_key` | The chat request-rate window for this key: `limit`, `remaining`, `resets_at`, and `window_seconds`. `resets_at` is `null` until a request opens the window. | | `rate_limits.chat.per_org` | The same window, for your whole organization. | | `rate_limits.chat.max_concurrent_requests` | How many chat requests your account may have in flight at once, across all three chat endpoints. One more is refused at once, not queued: `429` `rate_limited` with `reason: concurrency` and `Retry-After: 1`. | | `token_pool` | Subscription and developer-key buckets. The usage budget behind `budget_exhausted`, in `units`. | | `plan_limits` | Subscription and developer-key buckets. Your plan's row of the limits table: `files_per_month`, `images_per_month`, `files_per_message`, `images_per_message`, `storage_bytes`, `max_file_bytes`, `projects`, `works`, and `context_window`. A count that is `null` has no fixed cap. The row never changes within a month, so read it once; see [Plan limits](/docs/en/build/plan-limits). | | `files`, `images` | Subscription and developer-key buckets, for each kind of upload the plan caps (Max caps neither, so it has neither block). This month's stored uploads against the plan's allowance: `cap`, `used`, `remaining`, `state`, `window` (`monthly`), `starts_at`, and `resets_at`. An image is a file whose detected type is `image/*`; it never spends a file. | | `storage` | What you hold against the plan's storage pool, in `unit: bytes`: `cap`, `used`, `remaining`, and `state`. | | `credits` | Headless bucket only. The dollar-credit pool: `granted`, `adjustment`, `used`, `remaining`, and `resets_at`. | | `key_spend_cap` | Present only when the key has a monthly spend cap: `cap`, `spent`, `remaining`, and `resets_at`, in USD. | | `workspace_spend_cap` | Present only when the key's workspace has a monthly spend cap, in the same shape. | `token_pool` has two windows, each with `cap`, `used`, `remaining`, `percent_used`, `resets_at`, and a `state` of `healthy`, `low`, or `blocked`: - `monthly`: the cap over your account's own month, with `starts_at` beside `resets_at`. A paid plan's month is its billing period; a Free account's runs from the day of the month it was created. No allowance runs on the calendar month. - `burst`: the trailing 12-hour sliding cap, on every plan. Every monthly allowance on the response, `token_pool.monthly`, `api_share`, `files`, and `images`, is measured over that same month and resets at the same instant, the `resets_at` each one carries. There is no message allowance: nothing counts messages on any plan. The spend caps are the exception: they run on the UTC calendar month. `token_pool` also carries an overall `state`, `blocked_models`, and the `unit` (`units`). While an operator has the Epos request brake on, it carries `epos`, a monthly request cap on the `epos` tier with its own `cap`, `used`, `remaining`, `resets_at`, and `state`. Next to it, `mira` carries the same cap under the field's former name, present whenever `epos` is and with the same values, so existing code keeps working. Read `epos`. `percent_used` is `used` over `cap` as a percentage from 0 to 100, to one decimal place, rounded down, so it reads `100` only once the cap is reached. On a `token_pool` window it is `null` when there is no cap to measure against. `api_share`, `files`, `images`, and `storage` carry it too. Draw a usage bar from it instead of dividing `used` by `cap`. There is no tokens-per-minute limit and no per-model daily cap. The gateway enforces neither, so neither appears here. ## Read your month so far `GET /api/v1/limits/month` returns the month in progress day by day: one entry per UTC day from the day the month began to today, oldest first, each with a `date` and a `percent_used`. A day's `percent_used` is the share of the month's limit used from the start of the month through the end of that day, and through now for today. It is the same measure as `token_pool.monthly.percent_used` on `GET /api/v1/limits`, over the same month, so today's entry equals that figure, and the response's `starts_at` and `resets_at` are that window. ```bash title="curl" curl https://api.cruxy.ai/api/v1/limits/month \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/limits/month', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) if (!res.ok) throw new Error(`month request failed: ${res.status}`) const month = await res.json() if (!month.enforced) { // A headless key has no unit pool, so there is no series to draw. console.log('no monthly limit applies to this key') } else { for (const day of month.days) { console.log(`${day.date}: ${day.percent_used}%`) } console.log(`resets ${month.resets_at}`) } ``` ```json { "object": "limits.month", "enforced": true, "starts_at": "2026-11-19T09:30:00Z", "resets_at": "2026-12-19T09:30:00Z", "days": [ { "date": "2026-11-19", "percent_used": 40.1 }, { "date": "2026-11-20", "percent_used": 42.3 } ] } ``` The series has no gaps and never falls: a day with no usage repeats the day before. The response carries no unit count, cap, or remainder; read `GET /api/v1/limits` for those. Like that call, it reads everything from the key you send, writes nothing, and costs nothing, and it is rate-limited on its own bucket. A headless key, which draws on dollar credit and has no unit pool, gets `enforced: false` and an empty `days`. ## Budgets and auto A request with `model: "auto"` may be budget-downgraded to `epos`. Read `cruxy.routed_tier` on the response to see the tier that served it, rather than assuming the router's first choice; see [Auto routing](/docs/en/build/auto-routing). ## Next steps - [Plan limits](/docs/en/build/plan-limits): what each plan allows, every plan's entitlements from `GET /api/v1/limits/plans`, and when each allowance resets. - [Errors and retries](/docs/en/build/errors-and-retries): every `429` code, and a retry loop that honours `Retry-After`. - [Features overview](/docs/en/get-started/features): the tiers and `auto`. - [Get your API key](/docs/en/get-started/api-keys): key restrictions, including spend caps. ================================================================================ Page: Plan limits URL: https://learn.cruxyai.com/docs/en/build/plan-limits Markdown: https://learn.cruxyai.com/docs/en/build/plan-limits.md ================================================================================ # Plan limits What each Cruxy plan allows: models, context window, usage share for the API, uploads, storage, and projects, and when each allowance resets. Your Cruxy plan sets what the gateway allows a key to do: which tiers it can call, how much context a turn can carry, how much usage the API may draw, and how many files it can upload and store. `GET /api/v1/limits` reports your plan and the live headroom against each allowance; this page is the table it reads from. Prices are on [cruxyai.com/pricing](https://cruxyai.com/pricing). ## The table | | Free | Core | Advanced | Pro | Max | | --- | --- | --- | --- | --- | --- | | Tiers | `saga` | `epos`, `saga`, and `auto` | `epos`, `saga`, `canto`, and `auto` | `epos`, `saga`, `canto`, and `auto` | `epos`, `saga`, `canto`, and `auto` | | Context window | 256K | 1M | 1M | 1M | 1M | | Usage | Limited | 1/4 of Advanced | The baseline | 4x Advanced | 8x Advanced | | API | Not included | Up to 25% of the plan's usage | Up to 25% of the plan's usage | Up to 25% of the plan's usage | Up to 25% of the plan's usage | | File uploads a month | 100 | 2,000 | 5,000 | 20,000 | Unlimited, within fair use | | Image uploads a month | 50 | 1,000 | 2,500 | 10,000 | Unlimited, within fair use | | Files and images per message | 10 of each | 20 of each | 20 of each | 50 of each | Unlimited | | Storage | 1 GB | 10 GB | 25 GB | 100 GB | 500 GB | | Largest file | 25 MB | 50 MB | 100 MB | 100 MB | 100 MB | | Projects | Up to 3 | Unlimited | Unlimited | Unlimited | Unlimited | | Cruxy Code | `saga` | `saga` | `canto` | `canto` | `canto` | Sizes are decimal: 25 MB is 25,000,000 bytes. A Pro subscription from the beta reads `pro_legacy` on `GET /api/v1/limits` and has Pro's row. An enterprise account has no row and is held to the deployment's ceilings alone. ## Tiers and context A Free account calls `saga`. Core adds `epos` and `auto`; Advanced, Pro, and Max add `canto`. A chat request that names a tier outside the plan is `403` `model_not_in_plan`, carrying `model` and `plan`, before anything is billed; waiting does not help, so do not retry it. `auto` routes only among the plan's tiers, so on Free it is always served `saga`. `GET /api/v1/limits` lists the plan's tiers as `models`. [Choosing a tier](/docs/en/build/choosing-a-tier) compares the three, and [Auto routing](/docs/en/build/auto-routing) explains `auto`. The context window is the plan's: a turn on Free carries up to 256,000 tokens, and a turn on a paid plan up to 1,000,000, the smaller of the tier's own window and the plan's. Input past it is `400` `context_overflow`, whose `limit` is that number; see [Errors and retries](/docs/en/build/errors-and-retries). `GET /api/v1/limits` reports both as `context_window`. ## Usage and the API's share Every plan has a usage pool, `token_pool` on `GET /api/v1/limits`. Core is a quarter of Advanced, Pro four times it, and Max eight times it. Everything a plan does draws on the one pool: the web app, Cruxy Code, and the API. The API is included on every paid plan. Developer API keys together may use 25% of the plan's monthly units, in the account's month: `api_share` on `GET /api/v1/limits` reports the share with `cap`, `used`, `remaining`, and `resets_at`. Past it, a developer-key request on chat, embeddings, or rerank is `429` `api_share_exhausted`, in the shape of `budget_exhausted`, until `reset_at`. A signed-in credential is never counted toward the share and never refused by it. A developer key may also have 4 chat requests in flight at once, reported as `rate_limits.chat.max_concurrent_per_key`; one more is `429` `rate_limited` with `reason: concurrency`. A developer API key on a Free account is refused with `403` `plan_required`; a signed-in credential works on every plan. See [Get your API key](/docs/en/get-started/api-keys#two-kinds-of-key). ## When an allowance resets - **Every 12 hours.** Every plan has a trailing 12-hour window beside its month, `token_pool.burst`, which trickles back continuously. - **On your own monthly date.** A paid plan's month is its billing period. A Free account's month runs from the day of the month it was created, at the time it was created, in UTC; a day a month does not have is that month's last day. No allowance runs on the calendar month. Every monthly figure on `GET /api/v1/limits`, `token_pool.monthly`, `api_share`, `files`, and `images`, carries the `starts_at` and `resets_at` of that month, and every `429` that refuses for a spent allowance carries the same instant as `reset_at`. An upgrade applies to the month in progress; a downgrade applies at the next one. ## Uploads and storage `POST /api/v1/files` holds every upload to the plan's row: - **Files and images a month** are counted apart, by the file's detected media type: `image/*` is an image, anything else a file. One stored upload is one; a deleted or expired file stays counted. One past the allowance is `429` `file_limit_reached` or `image_limit_reached`, refused before a byte is stored, with `limit`, `used`, and `reset_at`. A retry under the same `Idempotency-Key` and content counts once. - **The largest file** is `413` `payload_too_large` past the plan's size, with `limit` in bytes. - **Storage** is `413` `storage_quota_exceeded` past the plan's pool, with `limit` and `used`, counted as files plus their extracted text per organization and user. A pool lowered under what an account holds refuses new uploads and deletes nothing. One chat request may name up to the plan's count of files and of images in `file_ids`. A Free account may create up to 3 projects. A cap only ever refuses creating more: nothing you have is deleted or hidden when you move to a smaller plan. ## Read every plan `GET /api/v1/limits/plans` returns this table for every plan on sale, in the order the pricing page lists them, the same for every caller and read from the tables the gateway enforces on, so a client that offers an upgrade holds no copy of it. Each entry carries `plan`, `models` (the tiers it includes, by the ids your `Cruxy-Version` names them), `context_window`, `usage_multiple` (the plan's monthly allowance over Advanced's: `0.25` on Core, `1` on Advanced, `4` on Pro, `8` on Max, `null` on Free), and `plan_limits` in the shape below. It says nothing about your own plan or usage; read `GET /api/v1/limits` for that. It is authenticated, rate-limited on its own bucket, and not billed. ```bash title="curl" curl https://api.cruxy.ai/api/v1/limits/plans \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/limits/plans', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) if (!res.ok) throw new Error(`plans request failed: ${res.status}`) const { plans } = await res.json() for (const p of plans) { // usage_multiple is null on free; a null count in plan_limits is unlimited. console.log( `${p.plan}: ${p.models.join(', ')}, ${p.context_window} tokens,`, `${p.usage_multiple ?? 'limited'}x Advanced, ${p.plan_limits.files_per_month ?? 'unlimited'} files a month`, ) } ``` ## Read your plan's row `plan_limits` on `GET /api/v1/limits` is your plan's row, so your code never holds a copy of this table. A count that is `null` has no fixed cap. ```bash title="curl" curl https://api.cruxy.ai/api/v1/limits \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/limits', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) if (!res.ok) throw new Error(`limits request failed: ${res.status}`) const limits = await res.json() console.log(`plan ${limits.tier}: ${limits.models.join(', ')}`) console.log(`context window: ${limits.context_window.plan} tokens`) const row = limits.plan_limits if (row) { // null means no fixed cap on this plan. console.log(`files a month: ${row.files_per_month ?? 'unlimited'}`) console.log(`largest file: ${row.max_file_bytes} bytes`) } if (limits.files) { console.log(`files: ${limits.files.used} of ${limits.files.cap}, resets ${limits.files.resets_at}`) } if (limits.storage) { console.log(`storage: ${limits.storage.remaining} bytes left`) } if (limits.api_share) { // Developer keys together: 25% of the plan's month. console.log(`API share: ${limits.api_share.remaining} of ${limits.api_share.cap} units left`) } ``` ## Next steps - [Rate limits and budgets](/docs/en/build/rate-limits): every block on `GET /api/v1/limits`, the month so far from `GET /api/v1/limits/month`, and the `429` codes. - [Get your API key](/docs/en/get-started/api-keys): the two kinds of key, and which plans the API needs. - [Errors and retries](/docs/en/build/errors-and-retries): which refusals to retry, and when. ================================================================================ Page: Usage and cost URL: https://learn.cruxyai.com/docs/en/build/usage-and-cost Markdown: https://learn.cruxyai.com/docs/en/build/usage-and-cost.md ================================================================================ # Usage and cost Read the usage object on each response: token counts, billable and cached tokens, the shape of the cost object, and how a stream reports usage. Every chat response reports what the call consumed in a `usage` object: its token counts and a `cost` object. This page documents the shape of both. Cost amounts and rates are specific to your account and shown in your Cruxy Console, so the examples here use placeholders where those numbers go. Read the real values from your own responses. ```bash title="curl" # usage, with its cost object, is near the end of the response body. curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "saga", "messages": [ { "role": "user", "content": "Name three monsoon fruits." } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'saga', messages: [{ role: 'user', content: 'Name three monsoon fruits.' }], }), }) if (!res.ok) throw new Error(`chat failed: ${res.status} ${await res.text()}`) const { usage, cruxy } = await res.json() console.log(`request ${cruxy.request_id} on ${usage.cost.tier}`) console.log(`input ${usage.input_tokens} (billable ${usage.billable_input_tokens})`) console.log(`output ${usage.output_tokens}`) // cost is an object, not a number: amount is the one figure, in cost.currency. console.log(`cost ${usage.cost.amount} ${usage.cost.currency}`) ``` ## The usage object A non-streaming `POST /api/v1/chat` response carries `usage` next to `message`. `input_tokens`, `output_tokens`, `billable_input_tokens`, and `cost` are always present. | Field | Meaning | | --- | --- | | `input_tokens` | The call's input tokens. | | `output_tokens` | The tokens the model generated. | | `billable_input_tokens` | The input tokens the call is billed for. | | `cache_read_tokens` | Input tokens read from the prompt cache. | | `cache_write_tokens` | Input tokens written to the prompt cache. | | `prompt_tokens_details` | The same cache split in OpenAI's shape, `cached_tokens` and `cache_write_tokens`. Present only when the prompt cache was used. | | `cost` | What the call cost, as an object; see [The cost object](#the-cost-object). | The token fields have different names on different endpoints. Each set belongs to a wire contract that has already shipped, so read the one for the endpoint and mode you called: | Endpoint and mode | Token fields | Cost | | --- | --- | --- | | `POST /api/v1/chat`, `stream: false` | `input_tokens`, `output_tokens`, `billable_input_tokens`, `cache_read_tokens`, `cache_write_tokens` | `usage.cost` | | `POST /api/v1/chat`, `stream: true` | `prompt_tokens`, `completion_tokens`, `total_tokens`, plus the three Cruxy counts when they are not zero | `usage.cost`, on the usage frame | | `POST /api/v2/chat`, either mode | `input_tokens`, `output_tokens`, `billable_input_tokens`, `cache_read_tokens`, `cache_write_tokens` | `usage.cost` | | `POST /api/v1/embeddings` and `POST /api/v1/rerank` | `prompt_tokens`, `total_tokens` | `cruxy.cost` | | `POST /v1/chat/completions` | `prompt_tokens`, `completion_tokens`, `total_tokens`, and `prompt_tokens_details.cached_tokens` when the cache was used | Not in the response | | `POST /api/v1/moderations` | Not in the response | Not in the response | ## The cost object `cost` is an object, not a number. Read `cost.amount` when you want one figure. ```json { "tier": "saga", "amount": "", "currency": "", "input_unit": "", "output_unit": "", "cache_read_unit": "" } ``` Each `<…>` is a placeholder. In a real response, `currency` is a string and the other placeholders are numbers. | Field | Meaning | | --- | --- | | `tier` | The tier that served the call. | | `amount` | The modeled cost of the call, in `currency`. | | `currency` | The currency of `amount`. | | `input_unit` | The input rate `amount` was computed from, per million tokens. | | `output_unit` | The output rate, per million tokens. | | `cache_read_unit` | The rate for input read from the prompt cache, per million tokens: the tier's own cache-read rate where it has one, otherwise `input_unit` times the cache discount. | Amounts and rates are specific to your account, and your Cruxy Console shows them. Take `cost.amount` from each response rather than computing it from token counts and a rate you copied, so your numbers match what the gateway records. ## Billable and cached tokens More goes into `input_tokens` than the messages you send. Each of these is billed as input: - **The tier's own prompt.** The gateway adds a per-tier system prompt and the tier's chat-template scaffolding. - **Standing rules,** when they are injected into the turn; see [Standing rules](/docs/en/build/rules). - **Recalled memory,** when recall runs. Sending `memory: {"recall": false}` lowers input by the size of that block; see [Memory](/docs/en/build/memory). - **Attached files,** on every request that sends them, including later turns that replay a message with `file_ids` in its history. - **Tools.** The `tools` array you send is real input; see [Define tools](/docs/en/build/tools). `billable_input_tokens` is the input the call is billed for, and `cache_read_tokens` and `cache_write_tokens` count prompt-cache activity. Input read from the cache is priced at `cost.cache_read_unit`. The API does not document how these counts relate to `input_tokens`, so read each one as reported rather than deriving one from another. Thinking is output. A reasoning tier writes its thinking inside the same `max_tokens` budget as the answer, `POST /api/v2/chat` reports that `output_tokens` includes the reasoning, and no response carries a separate reasoning-token count. See [Reasoning effort](/docs/en/build/reasoning-effort). `POST /api/v1/tokens/count` sizes a request before you send it: the `input_tokens` a chat request would bill for the same tier, messages, and tools, from a tokenizer vendored for the tier's model, with no model call and no bill. It takes a tier, not `"auto"`, and refuses `file_ids`. For now it answers `503` `count_unavailable` on every tier, because no tokenizer is vendored for the V1 models yet; see [Known limitations](/docs/en/build/known-limitations#token-counting-answers-count_unavailable-for-now). ## How a stream reports usage Usage arrives once, at the end of a successful stream: - **`POST /api/v1/chat`** sends exactly one usage frame: the frame whose `choices` is an empty array, after the finish frame and before `data: [DONE]`. It always carries `cost`. `billable_input_tokens`, `cache_read_tokens`, and `cache_write_tokens` are left out when they are zero, and `prompt_tokens_details` appears only when the cache was used, so a missing field means zero. See [Streaming](/docs/en/build/streaming#the-usage-frame). - **`POST /api/v2/chat`** carries `usage` on its terminal `finish` frame, in the same shape as a non-streaming v2 response. Its `error` frame can carry `usage` too. - **`POST /v1/chat/completions`** sends a usage frame only when the request sets `stream_options: {"include_usage": true}`, and that usage has no cost. A stream that fails partway sends no usage frame. The tokens it delivered were real, though, and are billed as a partial usage row. ## What is billed Not billed: - A non-streaming chat that runs past its tier's deadline: `504` `upstream_timeout`. - A model failure on chat: `502` `upstream_error`, and the `503` codes `upstream_overloaded`, `model_unavailable`, `all_models_unavailable`, `server_shutting_down`, and `limits_unavailable`. - A request the input moderation gate refuses: `400` `moderation_rejected`, or `400` `moderation_input_too_large` when the turn brings more new text than the gate reads in one request. - A request refused for its `Cruxy-Version`, for an attached file, or for the memory, rules, or files scope its key lacks: these are answered before anything is billed. - A replay of a stored success under the same `Idempotency-Key`. - `POST /api/v1/tokens/count`, and uploads to `POST /api/v1/files`. Billed: - `422` `structured_output_unsatisfied`. A retry with the same `Idempotency-Key` and body is not billed a second time. - A stream that ended early, for the tokens it delivered. - Every case in an eval run, as a chat completion. When a streamed request is retried under the same `Idempotency-Key`, it is billed once if both attempts complete. An attempt that did not complete is billed for the tokens it delivered, and the retry is billed as well; see [Errors and retries](/docs/en/build/errors-and-retries#make-retries-idempotent). ## Track spend - **Spend caps and credit.** `GET /api/v1/limits` reports the caps that bind your key: `key_spend_cap` and `workspace_spend_cap`, each with `cap`, `spent`, `remaining`, `resets_at`, and `unit`, and a headless key's `credits`. See [Rate limits and budgets](/docs/en/build/rate-limits#read-your-limits). - **Per-request tokens.** An organization owner or admin can read any call's token counts by its `request_id`; see [Look up a request](/docs/en/build/request-ids#look-up-a-request). - **Amounts.** Your Cruxy Console shows what your usage costs. ## Next steps - [Request IDs and metadata](/docs/en/build/request-ids): the `cruxy` block and the headers on each response. - [Streaming](/docs/en/build/streaming): the usage frame and the rest of the stream. - [Rate limits and budgets](/docs/en/build/rate-limits): spend caps, budgets, and live headroom. - [Reasoning effort](/docs/en/build/reasoning-effort): keep thinking from spending your `max_tokens`. ================================================================================ Page: Request IDs and metadata URL: https://learn.cruxyai.com/docs/en/build/request-ids Markdown: https://learn.cruxyai.com/docs/en/build/request-ids.md ================================================================================ # Request IDs and metadata Read the X-Request-Id header and each call's request_id, the Cruxy-Version header and the cruxy block, and quote a request when you report a problem. Every response the gateway sends carries an `X-Request-Id` header, and a call that succeeds also returns its own per-call `request_id` in the body. On an error, the two are the same value. On a success they differ, and the body's id is the one request logs and feedback take. Every response also names the API version that served it, in the `Cruxy-Version` header. ```bash title="curl" # -i prints the response headers above the body. X-Request-Id and # Cruxy-Version are headers; this call's own request_id is in the body, at # cruxy.request_id. curl -i https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "epos", "messages": [ { "role": "user", "content": "Hello" } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'epos', messages: [{ role: 'user', content: 'Hello' }], }), }) // Every response, errors included, carries both headers. const correlationId = res.headers.get('X-Request-Id') const version = res.headers.get('Cruxy-Version') const body = await res.json() if (res.ok) { // A success returns its own per-call id. Request logs and feedback take it. console.log(`request ${body.cruxy.request_id} (X-Request-Id ${correlationId}), Cruxy-Version ${version}`) } else { // An error's request_id equals the X-Request-Id header. console.log(`${res.status} ${body.code}: request_id ${body.request_id}, Cruxy-Version ${version}`) } ``` ## The X-Request-Id header `X-Request-Id` is a correlation id, sent on every response of every route, whether the call succeeded or failed. - **You can set it.** Send `X-Request-Id` on the request, up to 128 characters of `[A-Za-z0-9_-]`, and the gateway reuses your value. Any other value, or none, gets a new UUID. - **On an error, it equals the body's `request_id`.** The JSON error envelope (`code`, `error`, `request_id`) carries the same value as the header. - **On a success, it is not the call's id.** A success returns a separate per-call id, `cruxy.request_id`, or `request_id` on `POST /api/v2/chat`. Feedback and request logs take that per-call id, not the header. - **On `POST /v1/chat/completions` and `GET /v1/models`,** OpenAI's response and error shapes carry no `request_id`, so the header is the only request id a response there carries. Quote it when you report a problem; see [Report a problem](#report-a-problem). ```bash title="curl" # Send your own correlation id. -D - prints the response headers, where # X-Request-Id echoes it; -o /dev/null drops the body. curl -s -o /dev/null -D - https://api.cruxy.ai/api/v1/models \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "X-Request-Id: order-1234-attempt-1" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/models', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, // Up to 128 characters of [A-Za-z0-9_-]; anything else gets a new UUID. 'X-Request-Id': 'order-1234-attempt-1', }, }) console.log(res.headers.get('X-Request-Id')) // order-1234-attempt-1 ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { headers } = await cruxy.models.listModels( {}, // Up to 128 characters of [A-Za-z0-9_-]; anything else gets a new UUID. { headers: { 'X-Request-Id': 'order-1234-attempt-1' } }, ) console.log(headers['x-request-id']?.[0]) // order-1234-attempt-1 ``` ## Where the request ID appears A success returns its per-call id in the body. Where it sits depends on the endpoint: | Response | Where the per-call id is | | --- | --- | | `POST /api/v1/chat`, `stream: false` | `cruxy.request_id`. | | `POST /api/v1/chat`, `stream: true` | `cruxy.request_id` on the first frame, the role primer. | | `POST /api/v2/chat` | A top-level `request_id` in the body, and on the stream's `start` and `error` frames. | | `POST /api/v1/embeddings` and `POST /api/v1/rerank` | `cruxy.request_id`. | | `POST /api/v1/moderations` | The top-level `id`, formatted `modr-`. Strip the `modr-` prefix for the same id the other endpoints return. | An error carries `request_id` in the JSON error envelope, next to `code` and `error`, and its value equals the response's `X-Request-Id` header. Device login and native sign-in return the same three fields while pending or refused. `POST /v1/chat/completions` and `GET /v1/models`, the plain OpenAI wire, have no `cruxy` block, and their OpenAI error shape has no `request_id` field, so `X-Request-Id` is the only id a response there carries. When you need a per-call id that request logs and feedback accept, use `POST /api/v1/chat`. Log the `X-Request-Id` of every response and the per-call `request_id` of every success. The per-call id is the one that ties a line in your logs to the gateway's record of the call. ## The Cruxy-Version header The API is versioned by date, and `Cruxy-Version` carries the date both ways: - **On the request,** `Cruxy-Version: YYYY-MM-DD` pins a version. Omit it to get the current version, 2026-11-13. - **On the response,** `Cruxy-Version` names the version that served the call. Every response carries it, errors included. A value that is not a `YYYY-MM-DD` date is `400` `invalid_version`. A well-formed date this server does not support is `400` `unknown_version`, and its message lists the supported dates. Both are answered before authentication and before anything is billed. A few request fields work only under a minimum version, and the [Changelog](/docs/en/reference/changelog) lists each one with its date. Sent without that pin, `file_ids` is refused with `400` `invalid_request`, and the error names the version you need in `required_version`. A breaking change ships under a new dated version. Ordinary additive fields, new `cruxy.*` fields among them, ship without one, so ignore JSON fields you do not recognize. ## Other response headers | Header | Sent on | What it carries | | --- | --- | --- | | `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` | Metered responses | The per-minute request window; see [Rate limits and budgets](/docs/en/build/rate-limits#rate-limit-headers). | | `Retry-After` | Every `429`, and a `503` `limits_unavailable` | The seconds to wait before you retry. | | `Cache-Control` | Every JSON response | `no-store`: no cache, shared or private, may store the response. | ## The cruxy block Cruxy-native fields are additive and namespaced under a `cruxy` key, so an OpenAI client parses the rest of the response unchanged. What the block holds depends on the endpoint. ### On chat On `POST /api/v1/chat`, the block carries `request_id`, `routed_tier`, and `reasoning_effort` for the turn. The rest appear only when they apply: | Field | What it tells you | | --- | --- | | `request_id` | The call's id. | | `routed_tier` | The tier that served the call. With `model: "auto"`, this is the tier the router picked. | | `reasoning_effort` | The effort the call ran at, after the tier's default is applied. | | `reasoning` | The tier's thinking trace, present only when the tier reasoned. Sent from `Cruxy-Version: 2026-11-12`, and when a request sends no `Cruxy-Version`; a request pinned to an earlier date never receives it. See [Reasoning effort](/docs/en/build/reasoning-effort#see-the-thinking). | | `reasoning_summary` | Streams only: a thought line, a few words on one part of the thinking trace. Sent only where `cruxy.reasoning_summaries` on `GET /api/v1/models` is `true`, on a stream from a signed-in credential that pins `Cruxy-Version: 2026-11-13` or later; see [Streaming](/docs/en/build/streaming#thought-lines). | | `memory_recall` | Stored memories were recalled into the turn: the scope and key of each, never the stored value. See [Memory](/docs/en/build/memory). | | `memory_capture` | The turn stored memory: how many memories, and the scope and key of each. See [Memory](/docs/en/build/memory). | | `rules_applied` | Standing rules were injected: how many, and from which rulesets. See [Standing rules](/docs/en/build/rules). | | `files_omitted` | Files attached to earlier messages were left out of this turn, each with the reason. | | `undeclared_tool_replay` | Replayed tool exchanges called tools your `tools` array does not declare, so the model read them as prose. See [Handle tool calls](/docs/en/build/tool-calls). | A stream spreads the block across frames. The role primer carries `request_id`, `routed_tier`, and `reasoning_effort`, plus `memory_recall`, `rules_applied`, and `files_omitted` when they apply. The usage frame carries `memory_capture`, since what a turn stored is known only once the answer is complete. Each fragment of the thinking trace, and each thought line, rides a frame of its own whose block holds only `reasoning` or only `reasoning_summary`. [Streaming](/docs/en/build/streaming#frame-order) shows the frames in order. Token counts and cost are not in the chat block: they are in `usage`, which [Usage and cost](/docs/en/build/usage-and-cost) covers. ### On other endpoints - **Embeddings and rerank:** `cruxy` carries `request_id` and `cost`. - **Moderations:** no top-level block. A flagged result carries its own `results[].cruxy.hazard_codes`, the guard taxonomy codes behind the flag, and an unflagged result has no `cruxy` key; see [Moderations](/docs/en/build/moderations). - **`POST /api/v2/chat`:** no `cruxy` wrapper. The same signals are top-level fields: `request_id`, `routing` (the tier, how it was routed, and the effort), `memory_recall`, `memory_capture`, `rules_applied`, `files_omitted`, and `undeclared_tool_replay`. - **`POST /v1/chat/completions`:** none. That wire carries no Cruxy-native fields. New `cruxy.*` fields ship without a new API version. Ignore a field you do not recognize rather than failing on it. ## Look up a request An organization owner or admin can read a call's metadata by its per-call id, the `cruxy.request_id` a success returned, with `GET /api/v1/logs/{request_id}`. ```bash title="curl" # REQUEST_ID holds the cruxy.request_id of an earlier call. curl https://api.cruxy.ai/api/v1/logs/$REQUEST_ID \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" // REQUEST_ID holds the cruxy.request_id of an earlier call. const requestId = process.env.REQUEST_ID if (!requestId) throw new Error('set REQUEST_ID to the cruxy.request_id of an earlier call') const res = await fetch(`https://api.cruxy.ai/api/v1/logs/${requestId}`, { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) if (!res.ok) { const { code, request_id } = await res.json() throw new Error(`log lookup failed: ${res.status} ${code} (request_id ${request_id})`) } const log = await res.json() console.log(log.status, log.model, log.input_tokens, log.output_tokens, log.latency_ms) ``` ```json { "object": "request_log", "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "status": "success", "model": "canto", "input_tokens": 1024, "output_tokens": 256, "latency_ms": 842, "key_id": "6f9c1e2a-1b2c-4d5e-8f90-1a2b3c4d5e6f", "workspace_id": "2b7c9e4a-3d5f-4a6b-8c1d-9e0f1a2b3c4d", "created_at": "2026-07-18T12:34:56.000Z" } ``` - **Metadata only.** The model, token counts, latency, the lifecycle `status` (`success`, `error`, or `partial`), the key and workspace that made the call, and when. Prompt and completion content are never stored or returned. - **Owner or admin only.** Anyone else gets `403` `logs_forbidden`. - **One answer for a missing id.** An id from another organization, or one that names nothing, is `404` `log_not_found`, so the response never confirms that an id exists. - **The most recent row wins.** One id can map to more than one record, such as a reused `Idempotency-Key` or an error followed by a retried success; the most recent is returned. `GET /api/v1/logs` lists the same metadata for every key in your organization, newest first. ## Report a problem When you contact Cruxy support about a call, send enough to find it without a round of questions: - **The ids,** whole and exactly as the response returned them: the `X-Request-Id` header, and for a success its per-call `request_id` as well. If you retried, send the ids of every attempt you have. - **The `Cruxy-Version`** the response named. - **The method and path,** such as `POST /api/v1/chat`, and whether `stream` was on. - **The HTTP status and the `code`.** The `error` message alone is not enough; its wording can change. - **When it happened,** in UTC. - **For a stream,** whether it reached `data: [DONE]`, or a `finish` frame on `POST /api/v2/chat`. - **The `key_id`,** if the problem is with a key. Never send the key itself. To tell Cruxy how a call turned out, rather than report a fault, send [Feedback](/docs/en/build/feedback) joined to the same `request_id`. ## Next steps - [Usage and cost](/docs/en/build/usage-and-cost): the token counts and cost on each response. - [Errors and retries](/docs/en/build/errors-and-retries): the error envelope and every code. - [Feedback](/docs/en/build/feedback): attach an outcome to a `request_id`. - [Changelog](/docs/en/reference/changelog): the dated versions and what each one changed. ================================================================================ Page: Organizations and workspaces URL: https://learn.cruxyai.com/docs/en/build/organization Markdown: https://learn.cruxyai.com/docs/en/build/organization.md ================================================================================ # Organizations and workspaces Invite people to your organization, manage roles and memberships, review organization memory suggestions, and split spend across workspaces. An organization is the tenant your key belongs to: it owns the members, vaults, shared memory, rules, and workspaces that a key can reach. Every call on this page acts on the organization your key names. There is no organization id to pass, and no way to address another organization. ## Roles A member has one of three roles: `owner`, `admin`, or `member`. - **Owners and admins** manage the organization: they list and invite members, change roles, remove members, manage workspaces, and review memory suggestions. A `member` who calls one of those routes gets `403` `org_forbidden`, or `workspace_forbidden` on a workspace route. - **An owner's membership is immutable.** Nobody can change an owner's role or remove an owner, and an owner cannot leave, so an organization always keeps one. Granting `owner` requires the caller to be an owner. A role does not open a vault: an admin reads a vault's content only as a member of it. ## Invite someone `POST /api/v1/org/members` invites a person, addressed by `email` or by `user_id`, exactly one of the two. `role` is `member` (the default) or `admin`; to make someone an owner, change their role after they join. ```bash title="curl" curl https://api.cruxy.ai/api/v1/org/members \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "email": "dev@example.com", "role": "member" }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/org/members', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ email: 'dev@example.com', role: 'member' }), }) if (!res.ok) throw new Error(`invite failed: ${res.status} ${await res.text()}`) const invitation = await res.json() console.log(invitation.id, invitation.status, invitation.expires_at) ``` The call creates an invitation, not a membership: nobody joins an organization without accepting. It answers `202` with the invitation, and the answer is the same whether or not the address has an account, so the call cannot be used to find out who does. Re-inviting an address with a live invitation returns that invitation unchanged, and one whose invitation has lapsed gets a fresh 14-day window. Inviting someone who is already a member is `409` `org_member_exists`. `GET /api/v1/org/invitations` lists the invitations your organization has sent, live and settled, each with its `email`, `role`, and a `status` of `pending`, `accepted`, `declined`, or `revoked`. `DELETE /api/v1/org/invitations/{invitation_id}` withdraws one before it is accepted. ## Accept or decline an invitation The person invited acts with their own key. `GET /api/v1/invitations` lists the live invitations addressed to them across every organization, each with the inviting organization's `org_name` and the inviter's `invited_by_email`. ```bash title="curl" # See what you have been invited to. curl https://api.cruxy.ai/api/v1/invitations \ -H "Authorization: Bearer $CRUXY_API_KEY" # Accept one, by its id. To decline instead, POST to .../decline. curl -X POST https://api.cruxy.ai/api/v1/invitations/$INVITATION_ID/accept \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const headers = { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` } const inbox = await fetch('https://api.cruxy.ai/api/v1/invitations', { headers }) if (!inbox.ok) throw new Error(`inbox failed: ${inbox.status}`) const { data } = await inbox.json() for (const invitation of data) { console.log(`${invitation.org_name} invites you as ${invitation.role}`) console.log(` from ${invitation.invited_by_email}, until ${invitation.expires_at}`) } const first = data[0] if (first) { const res = await fetch(`https://api.cruxy.ai/api/v1/invitations/${first.id}/accept`, { method: 'POST', headers, }) if (!res.ok) throw new Error(`accept failed: ${res.status} ${await res.text()}`) const membership = await res.json() console.log(`joined ${membership.org_name} as ${membership.role}`) } ``` - `POST /api/v1/invitations/{invitation_id}/accept` joins the organization with the role the invitation offered and returns the new membership. - `POST /api/v1/invitations/{invitation_id}/decline` settles the invitation and creates nothing. It answers `204`. The inviting organization sees the outcome on its invitation list. An invitation that names somebody else, one that expired, one already settled, and one that never existed are all `404` `invitation_not_found`. Once you belong to more than one organization, issuing a new key can no longer pick an organization for you: the request must name one, or it is refused with `org_selection_required`. Existing keys are unaffected. ## Memberships `GET /api/v1/org/memberships` lists the organizations you belong to, with your `role` in each. `DELETE /api/v1/org/memberships/{org_id}` removes your own membership from the organization the path names. Any member may leave; an owner cannot, and gets `403` `org_forbidden`. It is the one call on this page that takes an organization id, because the organization you leave need not be the one your key names. ## Change a role or remove a member `GET /api/v1/org/members` lists the organization's members with each one's `user_id`, `email`, and `role`. - `PATCH /api/v1/org/members/{user_id}` with `{"role": "admin"}` changes a member's role. - `DELETE /api/v1/org/members/{user_id}` removes a member. Removing a member, or leaving, ends access and destroys nothing. The person's API keys bound to the organization are revoked in the same step. The memory they wrote at organization and vault scope is kept and frozen until an owner or admin settles it, and their own personal memory is never touched. `POST /api/v1/memories/departed/{user_id}` settles a departed member's shared memory with a `disposition`: `keep` retains every row and moves authorship to you, and `purge` deletes them. The response reports how many rows were `affected`. A user who is still a member is `409` `org_member_active`, and one who wrote nothing in your organization is `404` `org_member_not_found`. ## Suggest organization memory Only an owner or admin can turn a suggestion into organization memory, and any member can make one. `POST /api/v1/memories/suggestions` takes a `key` and a `value`. A suggestion is not memory: it is never recalled or added to a turn until it is approved. ```bash title="curl" # Any member: propose a memory for the whole organization. curl https://api.cruxy.ai/api/v1/memories/suggestions \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "key": "deploy-window", "value": "Production deploys go out on Tuesdays." }' # An owner or admin: read the pending queue, then approve one by its id. curl "https://api.cruxy.ai/api/v1/memories/suggestions?status=pending" \ -H "Authorization: Bearer $CRUXY_API_KEY" curl -X POST https://api.cruxy.ai/api/v1/memories/suggestions/$SUGGESTION_ID/approve \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const base = 'https://api.cruxy.ai/api/v1/memories/suggestions' const headers = { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', } // Any member: propose a memory for the whole organization. const suggested = await fetch(base, { method: 'POST', headers, body: JSON.stringify({ key: 'deploy-window', value: 'Production deploys go out on Tuesdays.', }), }) if (!suggested.ok) throw new Error(`suggest failed: ${suggested.status} ${await suggested.text()}`) // An owner or admin: read the pending queue and approve each entry. const queue = await fetch(`${base}?status=pending`, { headers }) if (!queue.ok) throw new Error(`queue failed: ${queue.status}`) const { data } = await queue.json() for (const suggestion of data) { const res = await fetch(`${base}/${suggestion.id}/approve`, { method: 'POST', headers }) if (!res.ok) throw new Error(`approve failed: ${res.status} ${await res.text()}`) const approved = await res.json() console.log(approved.key, approved.status, approved.memory_id) } ``` - **Suggesting.** Suggesting a key you already have pending replaces that pending value. The checks on a memory write apply: an empty value is refused, and content carrying obvious personal data is `400` `pii_rejected`. - **Listing.** `GET /api/v1/memories/suggestions` returns the newest 200. An owner or admin sees every member's; any other member sees only their own. `status` narrows it to `pending`, `approved`, or `rejected`. - **Approving.** `POST /api/v1/memories/suggestions/{id}/approve` writes the suggestion as organization memory under its key, replacing any organization memory already stored for that key, and names what it wrote in `memory_id`. - **Rejecting.** `POST /api/v1/memories/suggestions/{id}/reject` writes nothing. The suggestion is kept as `rejected`, and its author may suggest the key again. Approving or rejecting an id your organization has no pending suggestion under is `404` `memory_suggestion_not_found`: one already approved or rejected, one in another organization, and one that never existed get the same answer. See [Memory](/docs/en/build/memory) for how organization memory is recalled. ## Workspaces A workspace is a team's environment and spend budget inside an organization. Prompts and eval suites belong to the workspace a key names, and a workspace can carry a monthly spend cap. Every organization has a reserved default workspace. Workspace calls are for owners and admins. ```bash title="curl" curl https://api.cruxy.ai/api/v1/workspaces \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Production", "slug": "production", "spend_cap_micros": 5000000 }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/workspaces', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, // spend_cap_micros is in millionths of a US dollar: 5000000 is 5 USD a month. body: JSON.stringify({ name: 'Production', slug: 'production', spend_cap_micros: 5000000 }), }) if (!res.ok) throw new Error(`create failed: ${res.status} ${await res.text()}`) const workspace = await res.json() console.log(workspace.id, workspace.slug, workspace.spend_cap_micros, workspace.is_default) ``` | Field | Meaning | | --- | --- | | `name` | Required, 1 to 128 bytes. | | `slug` | A stable handle, derived from the name when omitted. One already used in the organization is `409` `workspace_slug_exists`, and `default` is reserved. It cannot be changed later. | | `spend_cap_micros` | An optional monthly ceiling in micro-USD, a positive integer. Omit it, or send `null`, for no cap. | Chat enforces the cap against the workspace's summed cost: past it, a request from a key in the workspace is `429` `workspace_spend_cap_exceeded`; see [Rate limits and budgets](/docs/en/build/rate-limits). | Call | Does | | --- | --- | | `GET /api/v1/workspaces` | Lists the organization's workspaces, the default first. | | `GET /api/v1/workspaces/{id}` | Returns one workspace. | | `PATCH /api/v1/workspaces/{id}` | Changes `name`, `spend_cap_micros`, or both. An explicit `null` cap removes the cap. | | `DELETE /api/v1/workspaces/{id}` | Deletes a workspace that has never held a key. One that has is `409` `workspace_not_empty`, and the default is `409` `workspace_is_default`. | ## Next steps - [Standing rules](/docs/en/build/rules): instructions that apply to every chat in the organization. - [Memory](/docs/en/build/memory): what chat recalls from organization memory. - [Get your API key](/docs/en/get-started/api-keys): the key that names your organization. - [API Reference](/docs/en/reference/api): every organization operation with its exact request and response shape. ================================================================================ Page: Production checklist URL: https://learn.cruxyai.com/docs/en/best-practices/production-checklist Markdown: https://learn.cruxyai.com/docs/en/best-practices/production-checklist.md ================================================================================ # Production checklist Check an integration before launch: the key kind, memory and rules on every request, idempotency, timeouts and retries, stream completion, request IDs, status. Run through this list before a Cruxy integration serves real traffic. Each item says what to do, why, and where the details live. The request below already does most of it: a developer API key, memory and rules set explicitly, a pinned `Cruxy-Version`, an `Idempotency-Key`, a client timeout above the tier's deadline, and the IDs logged. ```bash title="curl" # One Idempotency-Key per logical request; reuse it on every retry of it. # -i prints the X-Request-Id and Cruxy-Version headers to log with the body. curl -i https://api.cruxy.ai/api/v1/chat \ --max-time 120 \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -H "Cruxy-Version: 2026-10-18" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "model": "saga", "memory": { "recall": false, "capture": false }, "rules": false, "messages": [ { "role": "user", "content": "Summarize a refund policy in two sentences." } ] }' ``` ```ts title="TypeScript" import { randomUUID } from 'node:crypto' // One key per logical request: keep it, and send it again on every retry. const idempotencyKey = randomUUID() const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', 'Cruxy-Version': '2026-10-18', 'Idempotency-Key': idempotencyKey, }, body: JSON.stringify({ model: 'saga', // Explicit on every request, whatever the key's defaults are. memory: { recall: false, capture: false }, rules: false, messages: [{ role: 'user', content: 'Summarize a refund policy in two sentences.' }], }), // Your client timeout, not an API limit: above saga's 90-second deadline. signal: AbortSignal.timeout(120_000), }) const ids = { x_request_id: res.headers.get('X-Request-Id'), cruxy_version: res.headers.get('Cruxy-Version'), } const body = await res.json() if (!res.ok) { // Branch on code, never on the message. Log the ids, never the key. console.error(JSON.stringify({ status: res.status, code: body.code, request_id: body.request_id, ...ids })) throw new Error(`chat failed: ${res.status} ${body.code}`) } console.log( JSON.stringify({ request_id: body.cruxy.request_id, routed_tier: body.cruxy.routed_tier, finish_reason: body.finish_reason, ...ids, }), ) console.log(body.message.content) ``` ## Keys - **Run servers on a developer API key, never a signed-in credential.** A key from device login carries its owner's memory and standing rules into every request by default, and expires 90 days after issue. A developer API key, created in the Cruxy Console, has memory and rules off by default, never expires, and is rotated or revoked in the Console. See [Get your API key](/docs/en/get-started/api-keys#two-kinds-of-key). - **Confirm the key kind at startup.** `bucket` on `GET /api/v1/limits` is `apikey` for a developer key and `subscription` for a signed-in credential; [Security](/docs/en/best-practices/security#check-the-key-kind-at-startup) shows the check. - **Keep the key in the environment or a secrets manager,** one key per environment. See [Security](/docs/en/best-practices/security). ## Memory and rules - **Set `memory` and `rules` on every chat request.** Left out, the key decides, and the two kinds of key decide differently. Sending `memory: {"recall": false, "capture": false}` and `rules: false` makes a request behave the same whichever key sends it. Opt in with `true` only where you mean it; see [Memory](/docs/en/build/memory) and [Standing rules](/docs/en/build/rules). - **Pin `Cruxy-Version` 2026-09-26 or later when you rely on `false`.** A gateway that predates the field would ignore it and capture anyway; with the pin, it refuses the request instead. ## Versioning - **Pin `Cruxy-Version` on every request,** at the version you tested against, and move it deliberately. Responses name the tier by its current id from `2026-10-18`. See [Request IDs and metadata](/docs/en/build/request-ids#the-cruxy-version-header). - **Ignore JSON fields you do not recognize.** New `cruxy.*` fields ship without a version change. ## Timeouts and retries - **Set client timeouts above the tier's deadline.** A `stream: false` call gets one attempt: 90 seconds on `canto` and `saga`, 45 seconds on `epos`, then `504` `upstream_timeout`. A stream may run for up to five minutes. See [Reliability](/docs/en/build/reliability#deadlines-and-timeouts). - **Do not retry a `504` unchanged.** It takes as long again. Stream the turn, or lower `max_tokens` or `reasoning_effort`. - **Retry only what the API marks retryable,** honouring `Retry-After`, with exponential backoff and jitter, and a cap on attempts and total wait. Stop on a budget or spend-cap `429`: it clears only at its `reset_at`. See [Errors and retries](/docs/en/build/errors-and-retries#which-failures-to-retry). ## Idempotency - **Send an `Idempotency-Key` on every request that takes one,** and reuse it on every retry of the same logical request. A success is stored for 24 hours and replayed without billing again. The same key with a different body is `409` `idempotency_conflict`. See [Errors and retries](/docs/en/build/errors-and-retries#make-retries-idempotent). - **Expect a stream to replay nothing.** A retried stream generates again; when both attempts complete, the request is billed once. ## Streams - **Accept a streamed answer only once it finished.** On `POST /api/v1/chat`, `data: [DONE]` is the only success signal; on `POST /api/v2/chat`, the stream ends with exactly one `finish` or `error` frame. A stream that ends any other way failed: send the request again with the same `Idempotency-Key`. See [Streaming](/docs/en/build/streaming). - **Check `choices` before you read `choices[0]`.** The usage frame on every successful stream has `choices: []`. - **Treat `finish_reason: "length"` with empty content as a spent budget,** not an empty answer. On `canto`, thinking spends `max_tokens`; see [Reasoning effort](/docs/en/build/reasoning-effort). ## Logging - **Log the IDs of every call, success or failure:** the `X-Request-Id` header, the per-call `request_id` (`cruxy.request_id` on a success), the `Cruxy-Version` header, and `cruxy.routed_tier`. With `model: "auto"`, the router can pick differently for two similar requests, so log the tier that served. See [Request IDs and metadata](/docs/en/build/request-ids). - **Log the `key_id`, never the key,** and never the request body when it can carry personal data. ## Status - **Watch [status.cruxyai.com](https://status.cruxyai.com),** the Cruxy status page, and read `GET /api/status` from your own monitoring. It takes no key. `GET /api/health` reports only that the gateway's HTTP listener is up; do not read it as platform status. See [Reliability](/docs/en/build/reliability#check-platform-status). - **Know where to report a problem.** [Support](/docs/en/resources/support) lists what to send. ## Next steps - [Security](/docs/en/best-practices/security): keys, memory, and anonymous traffic. - [Tier and effort for cost and latency](/docs/en/best-practices/tiers-and-effort): size each call. - [Reliability](/docs/en/build/reliability): deadlines, retries, and stream checks in full. - [Known limitations](/docs/en/build/known-limitations): what to plan around before launch. ================================================================================ Page: Tier and effort for cost and latency URL: https://learn.cruxyai.com/docs/en/best-practices/tiers-and-effort Markdown: https://learn.cruxyai.com/docs/en/best-practices/tiers-and-effort.md ================================================================================ # Tier and effort for cost and latency Pick a tier and a reasoning effort for each kind of call by its cost and latency, starting from a default per job and measuring with each response's usage. Two settings decide most of what a chat call costs and how long it takes: the tier you send as `model`, and how much that tier thinks, set with `reasoning_effort`. This page gives a starting point for each kind of call. [Choosing a tier](/docs/en/build/choosing-a-tier) and [Reasoning effort](/docs/en/build/reasoning-effort) are the reference for every value. It quotes no prices: read each tier's rates from the catalog's `pricing` and each call's cost from `usage.cost`. ## Start from a default per job | Kind of call | Tier | `reasoning_effort` | Why | | --- | --- | --- | --- | | Classify, extract a field, route, or answer yes or no | `epos` | `none`, its default | Fast: answers without thinking, with the shortest non-streaming deadline (45 s). | | Everyday chat, summaries, drafting | `saga` | `low`, its default | Balanced: thinks lightly, and its graded effort lets you raise depth one step at a time. | | Multi-step reasoning or a long answer | `canto` | Omit it (`high`) | Deep: thinks deeply by default. Stream it, and leave `max_tokens` unset. | | A short, direct answer from `canto` | `canto` | `none` | Turns thinking off, so the whole `max_tokens` goes to the answer. | | Traffic you cannot sort ahead of time | `auto` | Omit it | The router picks the tier and the effort per request. | Change one setting at a time from there, and measure each change. ## What moves cost - **Thinking is output.** A tier that thinks writes its thinking inside the same `max_tokens` budget as the answer, and it is billed as output. Lowering `reasoning_effort`, or sending `none`, removes that output. On `canto` the control is on or off: `low` thinks as long as `high`. - **Input is more than your messages.** The gateway adds a per-tier system prompt. Standing rules, recalled memory, attached files, and `tools` are billed input whenever they are in the turn. `rules: false` and `memory: {"recall": false}` keep them out when you do not need them. See [Usage and cost](/docs/en/build/usage-and-cost#billable-and-cached-tokens). - **Each tier has its own rates.** `GET /api/v1/models` returns them in each entry's `pricing`, and every response carries the rates it was billed at in `usage.cost`. - **Count before you send.** `POST /api/v1/tokens/count` returns the input tokens a request would bill on a tier, calls no model, and is not billed. It takes a tier, not `auto`. ## What moves latency - **Thinking takes time.** A tier that thinks generates its thinking before it answers, inside the same turn. `none` turns thinking off, so the answer is the only thing the turn generates. - **Each tier states a target.** The catalog reports `latency_target_ms` per tier; read it from `GET /api/v1/models` rather than hardcoding it. - **A non-streaming call has a deadline:** 90 seconds on `canto` and `saga`, 45 seconds on `epos`, then `504` `upstream_timeout`. Stream long turns: a stream may run for up to five minutes, and its first tokens arrive before the turn ends. - **A smaller `max_tokens` bounds the turn,** but on a tier that thinks it can run out before any answer is written. Pair a small `max_tokens` with `reasoning_effort: "none"`. ## Use auto, or name a tier Send `model: "auto"` when your requests vary and you would rather the gateway pick per request. It chooses a healthy tier and an effort, and when a budget would refuse the request it can move it to `epos` instead of answering `429` `budget_exhausted`. Name a tier when you need the same output cap, deadline, and reasoning default on every call, when you count tokens first, and when you measure. See [Auto routing](/docs/en/build/auto-routing). ## Measure on your own prompts A tier's profile is a qualitative descriptor, not a performance number, and these docs publish no benchmarks. Send the same prompts from your product through each configuration you are weighing, and compare what each response reports: `usage.output_tokens`, `usage.cost.amount`, and how long the call took from your side. ```bash title="curl" # Run once per configuration you are weighing; change model and # reasoning_effort, keep the prompt. -w prints the wall-clock time. curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -H "Cruxy-Version: 2026-10-18" \ -w '\ntime_total: %{time_total}s\n' \ -d '{ "model": "epos", "reasoning_effort": "none", "memory": { "recall": false, "capture": false }, "rules": false, "messages": [ { "role": "user", "content": "Is this message a refund request? Answer yes or no: I was charged twice for one order." } ] }' ``` ```ts title="TypeScript" const prompt = 'Is this message a refund request? Answer yes or no: I was charged twice for one order.' // The configurations you are weighing, all on the same prompt. const configs = [ { model: 'epos', reasoning_effort: 'none' }, { model: 'saga', reasoning_effort: 'none' }, { model: 'saga', reasoning_effort: 'low' }, ] for (const config of configs) { const started = performance.now() const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', 'Cruxy-Version': '2026-10-18', }, body: JSON.stringify({ ...config, memory: { recall: false, capture: false }, rules: false, messages: [{ role: 'user', content: prompt }], }), }) if (!res.ok) throw new Error(`chat failed: ${res.status} ${await res.text()}`) const completion = await res.json() const ms = Math.round(performance.now() - started) console.log( `${config.model}/${config.reasoning_effort}: ${ms} ms, ` + `${completion.usage.output_tokens} output tokens, ` + `${completion.usage.cost.amount} ${completion.usage.cost.currency}: ${completion.message.content}`, ) } ``` Run each configuration on enough of your own prompts to see the spread, not one call: the same request can return different text and take a different time. ## Next steps - [Choosing a tier](/docs/en/build/choosing-a-tier): each tier's profile, output cap, and deadline. - [Reasoning effort](/docs/en/build/reasoning-effort): every effort value and the `max_tokens` trap. - [Usage and cost](/docs/en/build/usage-and-cost): the usage and cost objects in full. - [Prompting basics](/docs/en/best-practices/prompting): what the model sees on every turn. ================================================================================ Page: Prompting basics URL: https://learn.cruxyai.com/docs/en/best-practices/prompting Markdown: https://learn.cruxyai.com/docs/en/best-practices/prompting.md ================================================================================ # Prompting basics Write prompts for canto, saga, and epos: what the gateway adds to every turn, where your instructions go, how to size max_tokens, and how to test a prompt. A prompt to a Cruxy tier is an OpenAI-style `messages` array, but the model reads more than the messages you send, and some of it depends on the key and the request. This page covers what to control and how to check that a prompt works. Each point traces to the API's documented behavior; none of it is a benchmark. ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -H "Cruxy-Version: 2026-10-18" \ -d '{ "model": "epos", "reasoning_effort": "none", "max_tokens": 200, "memory": { "recall": false, "capture": false }, "rules": false, "messages": [ { "role": "system", "content": "You label support tickets. Reply with one word: billing, bug, or other." }, { "role": "user", "content": "I was charged twice for one order." } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', 'Cruxy-Version': '2026-10-18', }, body: JSON.stringify({ model: 'epos', // A one-word label needs no deliberation. reasoning_effort: 'none', max_tokens: 200, // Nothing from memory or standing rules: the turn is exactly these messages. memory: { recall: false, capture: false }, rules: false, messages: [ { role: 'system', content: 'You label support tickets. Reply with one word: billing, bug, or other.', }, { role: 'user', content: 'I was charged twice for one order.' }, ], }), }) if (!res.ok) throw new Error(`chat failed: ${res.status} ${await res.text()}`) const completion = await res.json() if (completion.finish_reason === 'length' && !completion.message.content) { throw new Error(`max_tokens ran out before an answer (request_id ${completion.cruxy.request_id})`) } console.log(completion.message.content) ``` ## What the model reads Every chat turn carries more than your `messages`: - **The tier's own prompt.** The gateway adds a per-tier system prompt and the tier's chat-template scaffolding. You cannot see or change them, and they are billed input. - **Standing rules,** when they apply. They go in as defaults that the user's own message overrides, never as constraints that outrank it. See [Standing rules](/docs/en/build/rules). - **Recalled memory,** when recall runs: the stored memories most relevant to the turn, as background context. See [Memory](/docs/en/build/memory). - **Attached files,** each placed as a framed block before the message that names it in `file_ids`. On a developer API key, rules and memory are off unless a request opts in. Send `memory: {"recall": false, "capture": false}` and `rules: false` anyway when you write and test a prompt, so the turn is exactly what you sent whichever key sends it. ## Put instructions in a system message `messages` takes four roles: `system`, `user`, `assistant`, and `tool`. Put the standing instructions for a task, such as the format, the audience, and what to refuse, in a `system` message, and the input for this call in a `user` message. OpenAI's `developer` role is not one of the four; send its content as `system`. Do not rely on standing rules for an instruction that must hold: a user's message overrides them by design. Put it in your own `system` message. ## Size max_tokens for the thinking A tier that thinks writes its thinking inside the same `max_tokens` budget as the answer, and `POST /api/v1/chat` returns it beside the answer as `cruxy.reasoning`, never as content. `canto` thinks by default, so a small `max_tokens` on `canto` can end the turn with `finish_reason: "length"` and empty content, as the sample checks. - **For a short, direct answer,** send `reasoning_effort: "none"`. - **To keep the thinking,** leave `max_tokens` unset, which gives the tier's output cap, or set it large. - **On `model: "auto"`,** send `reasoning_effort` whenever you set a small `max_tokens`: the router may pick `canto`. See [Reasoning effort](/docs/en/build/reasoning-effort). ## Ask for structured output To get JSON back, send `response_format` with a JSON schema instead of describing the shape in prose: ```json { "response_format": { "type": "json_schema", "json_schema": { "name": "ticket_label", "strict": true, "schema": { "type": "object", "properties": { "label": { "type": "string" } }, "required": ["label"] } } } } ``` ### Which tiers support it Only a tier that does constrained decoding honours `json_object` and `json_schema`. Each catalog entry on `GET /api/v1/models` says so in `supports_structured_output`; read it at runtime rather than hardcoding a tier. As shipped: | Tier | `supports_structured_output` | | --- | --- | | `canto` | Yes | | `saga` | Yes | | `epos` | Yes | - **A named tier is never moved.** A structured request that names a tier without support is `422` `structured_output_unsupported`. - **`model: "auto"` routes only to a supporting tier.** When the router picks a tier without support, the request moves to the nearest tier that has it and that your key may use, and health substitution stays among those tiers. Only a key none of whose allowed tiers supports it gets the same `422`. Structured output turns reasoning off for the request. ### Schema rules A `json_schema` request's `schema` is checked before any model call: - At most 131072 bytes, nested at most 8 levels deep, and at most 400 schema objects in all. - Every key in every schema object is one of the supported keywords: `$schema`, `additionalProperties`, `allOf`, `anyOf`, `const`, `default`, `description`, `enum`, `exclusiveMaximum`, `exclusiveMinimum`, `format`, `items`, `maxItems`, `maxLength`, `maximum`, `minItems`, `minLength`, `minimum`, `nullable`, `oneOf`, `pattern`, `properties`, `required`, `title`, `type`, `uniqueItems`. - `additionalProperties` is `true` or `false`, not a schema, and `items` is a single schema. - `pattern` is a regular expression in Go's RE2 syntax. - `$ref` and `$defs` are not supported, so a recursive schema cannot be expressed. - `strict` is accepted and has no effect: the schema is always enforced. A schema outside these rules is `400` `invalid_schema`. ### When the output does not match On a non-streaming request, the gateway re-validates the returned JSON against your schema. Output that does not conform is `422` `structured_output_unsatisfied`; the request is billed, and it may pass on a retry. A stream is constrained upstream but not re-validated, so parse and validate the JSON in your own code either way. ## Describe tools for the model A tool's `description` and its parameters' descriptions are rendered into the prompt the model reads, and billed as input on every request that sends them. Say what the function does and when to call it, as you would brief a colleague, and no longer. To make a call happen, force it with `tool_choice: {"type": "function", "function": {"name": "…"}}`: it is the only form that makes a tool call deterministic. See [Define tools](/docs/en/build/tools). ## Expect variation between runs The same request can return different text: - `temperature` is forwarded to the model unchanged. Omit it for the model's default. - `POST /api/v1/chat` has no `seed` field, and `POST /v1/chat/completions` accepts `seed` but does not apply it. - With `model: "auto"`, two similar requests can be served by different tiers. So test a prompt by checking properties of the answer, such as the label is one of three values, or the JSON validates, rather than comparing exact strings. Name a tier while you test. ## Test on the tier you ship A tier's profile is a qualitative descriptor, not a performance number. Before you ship a prompt, run it on the tier you plan to use with inputs from your own product. To size it first, `POST /api/v1/tokens/count` returns the input tokens it would bill on a tier, the tier's own prompt included, without calling a model. For repeated checks, an eval suite under `/api/v1/evals/suites` runs the same cases against the tier you name; each case is billed as a chat completion. See [Evals](/docs/en/build/evals). ## Next steps - [Tier and effort for cost and latency](/docs/en/best-practices/tiers-and-effort): choose the tier and effort the prompt runs on. - [Chat](/docs/en/build/chat): every request field. - [OpenAI SDK compatibility](/docs/en/migrate/openai-sdk-compatibility): the `response_format` forms and what the compatible route ignores. - [Indic languages](/docs/en/build/indic-languages): prompts in Indic scripts. ================================================================================ Page: Evals URL: https://learn.cruxyai.com/docs/en/build/evals Markdown: https://learn.cruxyai.com/docs/en/build/evals.md ================================================================================ # Evals Run the same test cases against a tier and read a pass or fail for each: create a suite, add cases, start a run, and poll for results. An eval suite is a set of test cases you run against a tier. Each case has an `input` to send and an `expected` answer to check the output against. A run sends every case through chat on the tier you name and records, per case, the output, whether it passed, and how long it took. Suites live in the workspace your key names. > **Warning:** A run costs money. Every case is a billed chat completion, charged to the > credential that started the run, exactly as an interactive chat call would be. ## Run an eval end to end The walkthrough below creates a suite, adds two cases, starts a run on `saga`, waits for it to finish, and prints each result. ```bash title="curl" # 1. Create a suite. curl https://api.cruxy.ai/api/v1/evals/suites \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Capital cities", "slug": "capital-cities" }' # 2. Add a case. Repeat for each case, with the suite id from step 1. curl https://api.cruxy.ai/api/v1/evals/suites/$SUITE_ID/cases \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "input": "What is the capital of France? Answer with the city name only.", "expected": "Paris", "match_mode": "contains" }' # 3. Start a run. It answers 202 at once with status "pending". curl https://api.cruxy.ai/api/v1/evals/suites/$SUITE_ID/runs \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "saga" }' # 4. Poll the run, with the run id from step 3, until status is "done" or "failed". curl https://api.cruxy.ai/api/v1/evals/runs/$RUN_ID \ -H "Authorization: Bearer $CRUXY_API_KEY" # 5. Read the per-case results. curl https://api.cruxy.ai/api/v1/evals/runs/$RUN_ID/results \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const base = 'https://api.cruxy.ai/api/v1' const headers = { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', } async function call(method: string, path: string, body?: unknown) { const res = await fetch(`${base}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), }) if (!res.ok) throw new Error(`${method} ${path} failed: ${res.status} ${await res.text()}`) return res.json() } // 1. Create a suite. const suite = await call('POST', '/evals/suites', { name: 'Capital cities' }) // 2. Add the cases. const cases = [ { input: 'What is the capital of France? Answer with the city name only.', expected: 'Paris' }, { input: 'What is the capital of Japan? Answer with the city name only.', expected: 'Tokyo' }, ] for (const c of cases) { await call('POST', `/evals/suites/${suite.id}/cases`, { ...c, match_mode: 'contains' }) } // 3. Start a run on one tier. Every case is a billed completion. let run = await call('POST', `/evals/suites/${suite.id}/runs`, { model: 'saga' }) // 4. Poll until the run finishes. while (run.status === 'pending' || run.status === 'running') { await new Promise((resolve) => setTimeout(resolve, 2000)) run = await call('GET', `/evals/runs/${run.id}`) console.log(`${run.status}: ${run.completed} of ${run.total_cases} cases`) } if (run.status === 'failed') throw new Error(`run failed: ${run.error}`) console.log(`${run.passed} passed, ${run.failed} failed`) // 5. Read the per-case results. const results = await call('GET', `/evals/runs/${run.id}/results`) for (const r of results.data) { console.log(r.passed ? 'pass' : 'FAIL', `${r.latency_ms} ms`, r.case_id, r.actual) } ``` ## Suites `POST /api/v1/evals/suites` creates a suite. `name` is required, 1 to 128 bytes. `slug` is an optional stable handle, derived from the name when you omit it; one already used in the workspace is `409` `eval_suite_slug_exists`. `prompt_id` optionally records the stored prompt the suite tests. It must be a prompt in the same workspace, or the create is `400` `invalid_request`. The link is advisory metadata: a run does not read the prompt. | Call | Returns | | --- | --- | | `GET /api/v1/evals/suites` | Every suite in the workspace, oldest first, each with its `case_count`. | | `GET /api/v1/evals/suites/{id}` | One suite. | | `DELETE /api/v1/evals/suites/{id}` | Nothing: `204`. The suite's cases, runs, and results are deleted with it. | ## Cases `POST /api/v1/evals/suites/{id}/cases` appends a case. All three fields are required: | Field | Meaning | | --- | --- | | `input` | The prompt, sent to the tier verbatim. 1 to 102,400 bytes. | | `expected` | The reference answer. 1 to 102,400 bytes. | | `match_mode` | How the output is judged: `exact` passes when the output equals `expected` after trimming, and `contains` passes when the output contains `expected`. | Both modes compare text, so write an `input` that asks for an answer you can match, such as a single word or a fixed label. `GET /api/v1/evals/suites/{id}/cases` lists a suite's cases, oldest first, and `DELETE /api/v1/evals/suites/{id}/cases/{case_id}` deletes one. ## Runs `POST /api/v1/evals/suites/{id}/runs` starts a run against the tier in `model`: `canto`, `saga`, or `epos`. `auto` is refused, because an eval measures one fixed tier. To compare tiers, start one run per tier on the same suite. The call answers `202` at once with the run in status `pending`, and does not wait for the cases. A background worker then sends each case through the standard chat path. Poll `GET /api/v1/evals/runs/{id}` for progress: | Field | Meaning | | --- | --- | | `status` | `pending`, `running`, `done`, or `failed`. | | `total_cases` | How many cases the run covers. | | `completed` | How many cases have a result so far. | | `passed`, `failed` | The pass and fail split of the completed cases. | | `started_at`, `finished_at` | When the run started and finished; each is `null` until then. | | `error` | An error message, or `null`. | | `model` | The tier the run measures. | A key whose model allowlist excludes the tier is refused when the run is started, with `403` `model_not_allowed`, the same check chat applies. ## Results `GET /api/v1/evals/runs/{id}/results` lists one result per completed case, oldest first: | Field | Meaning | | --- | --- | | `case_id` | The case the result is for. | | `actual` | The tier's output. | | `passed` | Whether `actual` matched the case's `expected` under its `match_mode`. | | `latency_ms` | How long the completion took, in milliseconds. | ## Errors | Status | `code` | When | | --- | --- | --- | | `400` | `invalid_request` | A missing or oversized field, or a `prompt_id` outside the workspace. | | `403` | `model_not_allowed` | The key's model allowlist excludes the tier. | | `404` | `eval_suite_not_found` | The id is not a suite in your workspace. | | `404` | `eval_case_not_found` | The case is not in the suite. | | `404` | `eval_run_not_found` | The id is not a run in your workspace. | | `409` | `eval_suite_slug_exists` | The slug is already used in the workspace. | See [Errors and retries](/docs/en/build/errors-and-retries) for the envelope and what to retry. ## Next steps - [Prompting basics](/docs/en/best-practices/prompting): write the prompt your cases test. - [Choosing a tier](/docs/en/build/choosing-a-tier): pick the tiers worth comparing. - [Usage and cost](/docs/en/build/usage-and-cost): what each case's completion costs. - [API Reference](/docs/en/reference/api): every eval operation with its exact request and response shape. ================================================================================ Page: Security URL: https://learn.cruxyai.com/docs/en/best-practices/security Markdown: https://learn.cruxyai.com/docs/en/best-practices/security.md ================================================================================ # Security Keep Cruxy keys out of browsers, code, and logs, scope each key to what it needs, keep secrets out of memory, and turn capture off for anonymous traffic. Most of what keeps a Cruxy integration safe comes down to three things: the key stays on your server, each key can do only what its service needs, and nothing a stranger types ends up in your memory. This page is the list. [Get your API key](/docs/en/get-started/api-keys#keep-the-key-safe) covers key handling in more detail. ## Keep the key on your server - **Never ship a key to a browser or a mobile app.** Anyone who can read the code can read the key. Put a server route between your client and the gateway that adds the key; see [Streaming chat in the browser](/docs/en/resources/cookbook/streaming-ui). - **Read it from the environment or a secrets manager,** never from source control. Use one key per environment. - **Log the `key_id`, never the key.** That goes for error reports too: when you contact [Support](/docs/en/resources/support), send the `key_id` and the request IDs, never the key itself. - **Send it only to `https://api.cruxy.ai`.** ## Check the key kind at startup A server must run on a developer API key, created in the Cruxy Console, never a signed-in credential from device login. A signed-in credential carries its owner's memory and standing rules into every request by default, and expires. `GET /api/v1/limits` names the kind in `bucket`: `apikey` for a developer key, `subscription` for a signed-in credential, `headless` for a key billed from prepaid credit. Refuse to start on the wrong one: ```bash title="curl" # bucket is apikey for a developer API key. curl https://api.cruxy.ai/api/v1/limits \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/limits', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) if (!res.ok) throw new Error(`limits check failed: ${res.status} ${await res.text()}`) const limits = await res.json() // A signed-in credential would bring its owner's memory and rules to // everyone this server answers. if (limits.bucket === 'subscription') { throw new Error('CRUXY_API_KEY is a signed-in credential; use a developer API key on a server') } console.log(`key kind: ${limits.bucket}`) ``` ## Give each key only what it needs A key can carry restrictions, and a request outside them is refused: - **Allowed scopes:** the endpoint families the key may call, and whether it may use memory, rules, or files. A key whose scopes omit `memory` can never read or write anyone's memory through chat, so it is the key to issue for a service that must never see memory. - **Model allowlist:** the tiers the key may call. A request for another tier is `403` `model_not_allowed`. - **Monthly spend cap:** past it, `429` `key_spend_cap_exceeded`. For a developer API key, the Console sets the model allowlist and the spend cap. See [Get your API key](/docs/en/get-started/api-keys#what-a-key-is-allowed-to-do). ## Rotate and revoke Rotate or revoke a developer API key in the Console. A signed-in credential cannot be rotated, but its holder can revoke it with `DELETE /api/v1/me/key`, sent with that key: do it on sign-out, and at once if it leaks. If you no longer hold the key, email [support@cruxyai.com](mailto:support@cruxyai.com) to have it revoked. It otherwise stays valid until its `expires_at`. See [Revoke the current key](/docs/en/get-started/api-keys#revoke-the-current-key). ## Never put secrets in memory Memory has no expiry. A stored value stays, and recall can place it in later turns, until someone deletes it. The capture filter drops content that carries an email address, a phone number, or a card number; it does not promise to catch a password, an API key, or a token. - **Never send a secret in a turn that captures,** and never store one by hand with `PUT /api/v1/memories`. - **Review what is stored** with `GET /api/v1/memories`, and remove an entry with `DELETE /api/v1/memories/{id}`. See [Memory](/docs/en/build/memory). ## Turn capture off for anonymous traffic On any request that serves people other than the key's owner, such as a public chat box or a support widget, send: ```json { "memory": { "recall": false, "capture": false }, "rules": false } ``` With capture on, the gateway stores what strangers say into the key owner's memory; with recall on, the owner's stored memory can surface in a stranger's answer. A developer API key has both off by default, but send them on every request anyway, so a key swapped by mistake cannot turn them on. Pin `Cruxy-Version` 2026-09-26 or later when you rely on `false`: a gateway that predates the field would ignore it and capture anyway. `rules: false` matters here too. A model can repeat an injected standing rule to anyone who asks for it. Before you opt a public-facing key into rules, read `GET /api/v1/rules/resolved` and confirm nothing in it is meant to stay internal. See [Standing rules](/docs/en/build/rules). ## Screen untrusted input To classify user text before it reaches chat, send it to `POST /api/v1/moderations` with the `cruxy-guard` model, and decide in your own code what to block. [Moderation gate](/docs/en/resources/cookbook/moderation-gate) builds that gate. ## Next steps - [Production checklist](/docs/en/best-practices/production-checklist): everything to check before launch. - [Memory](/docs/en/build/memory): recall, capture, and how to review what is stored. - [Get your API key](/docs/en/get-started/api-keys): the two kinds of key. ================================================================================ Page: TypeScript SDK URL: https://learn.cruxyai.com/docs/en/sdk/typescript Markdown: https://learn.cruxyai.com/docs/en/sdk/typescript.md ================================================================================ # TypeScript SDK Install the Cruxy TypeScript SDK, published on npm as @cruxy/api, create a client with your key, and call chat, embeddings, rerank, and more. The TypeScript SDK is a typed client for the Cruxy API, generated from the API's OpenAPI spec. It is published on npm as `@cruxy/api`. Each endpoint is a method on a `Cruxy` client, requests and responses are typed, and chat can stream. This section documents `@cruxy/api` 2.2.0. > **Warning:** Install `@cruxy/api`. The similarly named `@cruxy/sdk` package is the gateway > client the `cruxy` CLI uses internally: it streams chat and runs device login, > and has no embeddings, rerank, moderations, or models methods. It is not this > SDK. ## Requirements - **`@cruxy/api` 2.2.0 or later.** 2.2.0 adds `auth.revokeCurrentKey` and each tier's `supportsStructuredOutput`. 2.1.0 is the first release that accepts the tier ids `canto`, `saga`, and `epos`; an older release rejects them before the request is sent. Since 2.1.2, every request pins a `Cruxy-Version` that reads them back, so every response names the tier by its current id; see [Version pinning](/docs/en/sdk/typescript/chat#version-pinning). - **A runtime with ECMAScript 2020, `fetch`, Web Streams, and async iterators.** The package names Node.js LTS releases, Bun 1 and later, Deno 1.39, and evergreen browsers. - **A server, not a browser, for your key.** The SDK runs in a browser, but a key in browser code is a key anyone can read. Call the API from a server; see [Get your API key](/docs/en/get-started/api-keys#keep-the-key-safe). ## Install ```bash npm install @cruxy/api@^2.2.0 ``` The SDK's one dependency is `zod`, 4.6.6 or later from 2.2.0. It is published as an ES module only; from CommonJS, load it with `await import('@cruxy/api')`. ## Create a client ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) ``` `bearerAuth` is your API key, sent as `Authorization: Bearer ` on every request. It also takes an async function that returns the key, so you can read it from a secrets manager at request time. Left unset, the SDK reads the `CRUXY_BEARER_AUTH` environment variable, not `CRUXY_API_KEY`. The client calls `https://api.cruxy.ai` unless you pass `serverURL`. Every sample in these docs creates its client this way. For the kinds of key and how to get one, see [Get your API key](/docs/en/get-started/api-keys). ## Client options | Option | Default | What it does | | --- | --- | --- | | `bearerAuth` | `CRUXY_BEARER_AUTH` | The API key, or an async function that returns it. | | `serverURL` | `https://api.cruxy.ai` | The API host. | | `retryConfig` | no retries | Retry policy for every method, `chat.stream` included; see [SDK errors, retries, and timeouts](/docs/en/sdk/typescript/errors-and-retries#retries). | | `timeoutMs` | no timeout | Abort a request that takes longer, in milliseconds. On `chat.stream` it bounds only the wait for response headers; see [SDK errors, retries, and timeouts](/docs/en/sdk/typescript/errors-and-retries#timeouts). | | `httpClient` | `fetch` | A custom `HTTPClient`, for hooks around every request. | | `userAgent` | the SDK's own | Overrides the `User-Agent` header. | | `debugLogger` | none | A logger, such as `console`, that logs each request and response. | `debugLogger`, and the `CRUXY_DEBUG` environment variable that turns it on with `console`, redact credentials: the `Authorization` header, your key wherever it appears, and the key device login returns. Request and response bodies are still logged in full, prompts and answers included, so keep debug logging out of production logs. ## Methods Each namespace on the client maps to one area of the API. These are the HTTP requests that 2.2.0 sends: | Method | Request | Guide | | --- | --- | --- | | `chat.createChatCompletion` | `POST /api/v2/chat` | [Chat with the TypeScript SDK](/docs/en/sdk/typescript/chat) | | `chat.stream` | `POST /api/v2/chat` with `stream: true` | [Chat with the TypeScript SDK](/docs/en/sdk/typescript/chat#stream-a-response) | | `embeddings.createEmbeddings` | `POST /api/v1/embeddings` | [Embeddings, rerank, and more with the SDK](/docs/en/sdk/typescript/methods#embeddings) | | `rerank.rerankDocuments` | `POST /api/v1/rerank` | [Embeddings, rerank, and more with the SDK](/docs/en/sdk/typescript/methods#rerank) | | `moderations.createModeration` | `POST /api/v1/moderations` | [Embeddings, rerank, and more with the SDK](/docs/en/sdk/typescript/methods#moderations) | | `models.listModels` | `GET /api/v1/models` | [Embeddings, rerank, and more with the SDK](/docs/en/sdk/typescript/methods#models) | | `auth.getCurrentIdentity`, `auth.revokeCurrentKey` | `GET /api/v1/me`, `DELETE /api/v1/me/key` | [Embeddings, rerank, and more with the SDK](/docs/en/sdk/typescript/methods#identity) | | `deviceLogin.startDeviceLogin`, `deviceLogin.pollDeviceToken` | `POST /api/v1/device/code`, `POST /api/v1/device/token` | [Embeddings, rerank, and more with the SDK](/docs/en/sdk/typescript/methods#device-login) | | `feedback.submitFeedback` | `POST /api/v1/feedback` | [Embeddings, rerank, and more with the SDK](/docs/en/sdk/typescript/methods#feedback) | | `tokens.countTokens` | `POST /api/v1/tokens/count` | [Embeddings, rerank, and more with the SDK](/docs/en/sdk/typescript/methods#count-tokens) | | `files.uploadFile`, `files.listFiles`, `files.getFile`, `files.downloadFileContent`, `files.deleteFile` | `/api/v1/files` | [Attach files](/docs/en/sdk/typescript/chat#attach-files), for `files.uploadFile`. | Chat is the one method on `/api/v2/`. `POST /api/v2/chat` is the Cruxy-native chat wire: it returns the native completion shape and streams named events. `POST /api/v1/chat`, which the chat guides on this site use, returns its own flattened body and an OpenAI-shaped stream instead, and the SDK has no method for it. ## Requests and responses A method takes one request object. Its `body` is the JSON request body, and two optional fields set headers: - **`idempotencyKey`** sends `Idempotency-Key` on the methods that take one: `chat.createChatCompletion`, `chat.stream`, `embeddings.createEmbeddings`, `rerank.rerankDocuments`, `moderations.createModeration`, and `files.uploadFile`. See [SDK errors, retries, and timeouts](/docs/en/sdk/typescript/errors-and-retries#idempotency). - **`cruxyVersion`** sets the `Cruxy-Version` a request pins, on every method; see [Request IDs and metadata](/docs/en/build/request-ids#the-cruxy-version-header). Without it, every request pins the version the SDK was generated against; see [Version pinning](/docs/en/sdk/typescript/chat#version-pinning). A method resolves to `{ headers, result }`. `result` is the parsed response body, and `headers` holds every response header, keyed by lowercase name, each value an array of strings. Field names are camelCase on both sides: you write `maxTokens` and `topN`, and read `finishReason` and `requestId`. The SDK converts them to and from the snake_case names on the wire. It checks both directions against the spec: a request missing a required field throws `SDKValidationError` before it is sent, and a response missing one throws `ResponseValidationError`. A response field that 2.2.0 does not know is dropped from `result`. A second, optional argument sets per-call options: `timeoutMs`, `retries`, `retryCodes`, `serverURL`, and `fetch` options such as `headers` and `signal`. `chat.stream` also takes `idleTimeoutMs` and `totalTimeoutMs`. ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result, headers } = await cruxy.models.listModels({}, { timeoutMs: 10_000 }) console.log( result.data.map((model) => model.id), headers['x-request-id']?.[0], ) ``` ## Standalone functions Each method is also exported as a standalone function that takes a `CruxyCore` client, so a bundler can drop the methods you do not import. The methods and the functions behave the same; the SDK's `FUNCTIONS.md` lists them. ```ts import { CruxyCore } from '@cruxy/api/core.js' import { embeddingsCreateEmbeddings } from '@cruxy/api/funcs/embeddings-create-embeddings.js' const cruxy = new CruxyCore({ bearerAuth: process.env.CRUXY_API_KEY }) const res = await embeddingsCreateEmbeddings(cruxy, { body: { model: 'cruxy-embed', input: ['The quick brown fox'] }, }) if (!res.ok) throw res.error console.log(res.value.result.data[0]?.embedding.length) ``` A standalone function does not throw: it returns `{ ok: true, value }` or `{ ok: false, error }`. Streaming is the exception: its standalone form, `streamChatCompletion(cruxy, request, options)` from `@cruxy/api`, throws like `chat.stream`. ## Upgrade from 1.x 2.0.0 and 2.1.0 change these for code written against 1.0.0: - **Tier ids.** Send `canto`, `saga`, and `epos`. The SDK still accepts the former ids, but responses name the tier by its new id; see [Deprecated aliases](/docs/en/reference/models#deprecated-aliases). - **Paths and server.** Every method except chat calls its `/api/v1/` path, and the default server is `https://api.cruxy.ai`, so you can drop `serverURL`. The responses are the same. - **Required fields.** Fields the gateway always required are now required in the types. An assistant message that carries only `toolCalls` must send `content: ''`. - **Errors.** Every method throws `CruxyError`, with a parsed `code`, for every error status. See [Error classes](/docs/en/sdk/typescript/errors-and-retries#error-classes). - **Retries** follow the gateway's per-code contract, so budget and spend-cap `429`s are not retried, and `chat.stream` uses the client's `retryConfig`. - **Stream timeouts.** `timeoutMs` no longer cuts off a stream that is still sending. To cap a whole stream, pass `totalTimeoutMs`. - **Chat fields.** The request takes `memory`, `rules`, `toolChoice`, `vaultId`, `mentionedVaultIds`, and `fileIds` on a message, and the response carries `reasoning`. ## Next steps - [Chat with the TypeScript SDK](/docs/en/sdk/typescript/chat): Send a chat request, stream the reply, call tools, and control memory, rules, and files per request. - [Embeddings, rerank, and more with the SDK](/docs/en/sdk/typescript/methods): Embeddings, rerank, moderations, models, token counting, your key's identity, device login, and feedback. - [SDK errors, retries, and timeouts](/docs/en/sdk/typescript/errors-and-retries): The error classes, retries and the codes they skip, timeouts, idempotency, and request IDs. ================================================================================ Page: Chat with the TypeScript SDK URL: https://learn.cruxyai.com/docs/en/sdk/typescript/chat Markdown: https://learn.cruxyai.com/docs/en/sdk/typescript/chat.md ================================================================================ # Chat with the TypeScript SDK Send chat requests with the TypeScript SDK, read the native v2 response, stream the reply, call tools, and set memory, rules, and files per request. The SDK's chat methods call `POST /api/v2/chat`, the Cruxy-native chat endpoint. `chat.createChatCompletion` returns one completion, and `chat.stream` streams it. The request is the same in both; the response is the native v2 shape, with the reply in a top-level `message` and the serving tier in `routing`. For the endpoint itself, see [Chat](/docs/en/build/chat) and [Streaming](/docs/en/build/streaming). ## Send a request ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result } = await cruxy.chat.createChatCompletion({ body: { model: 'auto', messages: [ { role: 'system', content: 'Answer in one sentence.' }, { role: 'user', content: 'What is a monsoon?' }, ], maxTokens: 256, }, }) console.log(result.message.content) console.log(result.routing.tier, result.finishReason, result.requestId) ``` `model` is a tier, `canto`, `saga`, or `epos`, or `auto` to let the gateway choose. See [Choosing a tier](/docs/en/build/choosing-a-tier). ## Request fields These are the `body` fields 2.2.0 sends, with their names on the wire: | SDK field | Wire field | Notes | | --- | --- | --- | | `model` | `model` | `canto`, `saga`, `epos`, or `auto`. Required. | | `messages` | `messages` | Required. Each has `role` (`system`, `user`, `assistant`, `tool`) and a string `content`, both required. An assistant message can carry `toolCalls`, a tool message carries `toolCallId`, and a user message can carry `fileIds`. | | `maxTokens` | `max_tokens` | The output cap. | | `temperature` | `temperature` | | | `reasoningEffort` | `reasoning_effort` | `none`, `low`, `medium`, or `high`; see [Reasoning effort](/docs/en/build/reasoning-effort). | | `responseFormat` | `response_format` | `{ type: 'json_schema', jsonSchema: { name, schema, strict } }`, or `type` `text` or `json_object`. | | `tools` | `tools` | Function tools; see [Call tools](#call-tools). | | `toolChoice` | `tool_choice` | `none`, `auto`, `required`, or `{ type: 'function', function: { name } }`. | | `memory` | `memory` | `{ recall, capture }`, each `true` or `false`; see [Memory and rules](#memory-and-rules). | | `rules` | `rules` | `true` or `false`; see [Memory and rules](#memory-and-rules). | | `vaultId` | `vault_id` | The vault this chat runs inside. | | `mentionedVaultIds` | `mentioned_vault_ids` | Vaults this turn references without being inside them. | | `stream` | `stream` | Set for you by `chat.stream`. | ### Version pinning Every request the SDK sends carries `Cruxy-Version`, on every method, not only on chat. When you have not set one, it is the version the SDK was generated against, `2026-10-18` in 2.1.2 and 2.2.0. That version names the tier by its current id, so every response reads `canto`, `saga`, or `epos` in `routing.tier`, whatever version the gateway would choose for a request without the header. Two chat fields only work when the request pins a recent enough version: `fileIds` needs `2026-10-05` or later, and a `memory` side set to `false` needs `2026-09-26` or later. The SDK's own version covers both. If a field ever needs a newer one, the SDK raises the pin for that request. Before 2.1.2, the SDK sent `Cruxy-Version` only on a chat request that used one of those fields, and a request without the header was served the gateway's default. 2.1.0 pinned each field's minimum instead, so those responses named the tier by its former id; see [Deprecated aliases](/docs/en/reference/models#deprecated-aliases). A version you set always wins, earlier or later: `cruxyVersion` on a method, or a `Cruxy-Version` entry in `options.headers`. With an older one and a field that needs newer, the gateway answers `400` and names the version in `requiredVersion`. See [The Cruxy-Version header](/docs/en/build/request-ids#the-cruxy-version-header). ## Memory and rules `memory` and `rules` turn automatic memory and standing rules on or off for one request. Left out, the key's default applies: off for a developer API key, on for a signed-in client. Sending `true` needs a key whose allowed scopes include that family, or the gateway answers `403` `key_scope_forbidden`; sending `false` needs no scope. ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) // A turn that reads and stores no memory and gets no standing rules. // The memory opt-out needs Cruxy-Version 2026-09-26 or later; the SDK pins 2026-10-18. const { result } = await cruxy.chat.createChatCompletion({ body: { model: 'saga', messages: [{ role: 'user', content: 'Summarize this ticket for a new teammate.' }], memory: { recall: false, capture: false }, rules: false, }, }) console.log(result.message.content) ``` What each side does, and when a server must send both `false` values, is in [Memory](/docs/en/build/memory#turn-memory-off-for-one-request) and [Standing rules](/docs/en/build/rules). ## Attach files Upload a file with `files.uploadFile`, then name its id in `fileIds` on a user message. The gateway reads the file into that turn: UTF-8 text, PDFs, Word documents, and JPEG, PNG, and WebP images. ```ts import { openAsBlob } from 'node:fs' import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result: file } = await cruxy.files.uploadFile({ body: { file: await openAsBlob('report.pdf'), purpose: 'chat_attachment' }, }) // fileIds needs Cruxy-Version 2026-10-05 or later; the SDK pins 2026-10-18. const { result } = await cruxy.chat.createChatCompletion({ body: { model: 'canto', messages: [{ role: 'user', content: 'List the three main findings.', fileIds: [file.id] }], }, }) console.log(result.message.content) ``` A `chat_attachment` file that no message attaches within 24 hours of upload is deleted. A file the turn could not use is listed in the response's `filesOmitted`. ## Read the response `result` is the native v2 completion: | Field | What it holds | | --- | --- | | `message` | The reply: `role`, `content`, and `toolCalls` when the model called tools. | | `finishReason` | `stop`, `tool_calls`, `length`, or `content_filter`. | | `routing` | The served `tier`, how it was chosen in `mode` (`explicit`, `auto`, or `auto_degraded`), and `reasoningEffort`. | | `usage` | `inputTokens`, `outputTokens`, `billableInputTokens`, the cache counters, and `cost`. | | `requestId` | The call's request ID; see [Request IDs](/docs/en/sdk/typescript/errors-and-retries#request-ids). | | `id`, `model` | The completion's ID and the tier that served it. | | `reasoning` | A reasoning tier's thinking trace, when it thought. It is never part of `message.content`. | | `memoryRecall`, `memoryCapture`, `rulesApplied` | What memory was recalled and stored, and which rules were applied, when any were. | | `filesOmitted`, `undeclaredToolReplay` | Files the turn left out, and tool calls in the history that `tools` no longer declares. | `model`, `routing.tier`, and `usage.cost.tier` name the tier by its current id. A request pinned to a `cruxyVersion` before `2026-10-18` reads the former ids there instead; see [Deprecated aliases](/docs/en/reference/models#deprecated-aliases). ## Stream a response `chat.stream` sends the same request with `stream: true` and resolves to a `ChatCompletionStream`. Iterate it for the text as it arrives: ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const stream = await cruxy.chat.stream({ body: { model: 'auto', messages: [{ role: 'user', content: 'Write a haiku about rain.' }], }, }) for await (const delta of stream) { process.stdout.write(delta.content ?? '') } // Filled from the start and finish frames as the stream is read. console.log() console.log(stream.routing?.tier, stream.finishReason, stream.usage?.outputTokens) ``` The stream reads the named-event wire. Each `delta` frame is yielded; the other frames fill the stream's own properties instead: | Property | Filled from | | --- | --- | | `routing`, `id`, `model`, `requestId` | The `start` frame, before the first delta. | | `start` | The whole `start` frame, with `memoryRecall`, `rulesApplied`, `filesOmitted`, and `undeclaredToolReplay`. | | `content` | Every `delta` so far, joined. | | `reasoning` | Every `reasoning` frame so far, joined. Empty unless the tier thinks, and never mixed into `content`. | | `toolCalls` | Tool-call fragments so far, assembled by index into `{ index, id, type, name, arguments }`. | | `finishReason`, `usage` | The `finish` frame. | | `finish` | The whole `finish` frame, with `memoryCapture`. | | `completed` | `true` once the `finish` frame arrived. | A frame with an event name 2.2.0 does not know is skipped. A stream can be read once. ### Stream timeouts A stream takes three limits, as per-call options: | Option | Bounds | Default | | --- | --- | --- | | `timeoutMs` | The wait for response headers, on each attempt. | The client's `timeoutMs`. | | `idleTimeoutMs` | The longest gap between two reads of the body. Any bytes reset it, so a stream that keeps sending is never cut off. `0` turns it off. | `timeoutMs`, or none. | | `totalTimeoutMs` | The whole call, connect included. | None. | ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const stream = await cruxy.chat.stream( { body: { model: 'canto', messages: [{ role: 'user', content: 'Plan a three-day trip to Kyoto.' }] } }, { timeoutMs: 10_000, idleTimeoutMs: 30_000, totalTimeoutMs: 300_000 }, ) for await (const delta of stream) { process.stdout.write(delta.content ?? '') } ``` A body limit that passes closes the connection and throws `ChatStreamTimeoutError`. The gateway lets a stream run for up to five minutes; see [Deadlines and timeouts](/docs/en/build/reliability#deadlines-and-timeouts). ### Stream errors A stream that fails throws. Wrap the request and the loop together: | Error | When | | --- | --- | | `CruxyError` | The request failed before the stream opened, with any `4xx` or `5xx`. The same class, with the same fields, that `chat.createChatCompletion` throws. | | `ChatStreamFrameError` | The stream ended with an `error` frame. It carries `code`, `requestId`, `partialContent`, `usage` when the frame reports it, and `retryable`. | | `IncompleteChatStreamError` | The body ended with no `finish` or `error` frame, or the connection dropped; the original error is on `cause`. It carries `deltasReceived` and `partialContent`. Treat it as a failed request, never a short answer. | | `ChatStreamTimeoutError` | `idleTimeoutMs` or `totalTimeoutMs` passed. A subclass of `IncompleteChatStreamError`, with `timeout` (`idle` or `total`) and `timeoutMs`. | | `MalformedChatStreamError` | A frame did not parse, or was missing a required field. | | `RequestAbortedError` | Your `signal` aborted the stream. | `retryable` follows the gateway's retry contract, the same list the SDK's own retries use: it is `true` for `upstream_overloaded`, `upstream_timeout`, `model_unavailable`, `server_shutting_down`, and `internal_error`, and `false` for `upstream_error` and any code the SDK does not know. A stream can also throw `SDKValidationError`, `ConnectionError`, a `RequestTimeoutError` when no headers arrive within `timeoutMs`, and a `ChatStreamError` when it is iterated a second time. ```ts import { ChatStreamFrameError, ChatStreamTimeoutError, Cruxy, IncompleteChatStreamError, } from '@cruxy/api' import { CruxyError } from '@cruxy/api/models/errors' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) try { const stream = await cruxy.chat.stream( { body: { model: 'canto', messages: [{ role: 'user', content: 'Explain tides.' }] } }, { idleTimeoutMs: 30_000 }, ) for await (const delta of stream) { process.stdout.write(delta.content ?? '') } } catch (err) { if (err instanceof ChatStreamFrameError) { console.error(`stream failed: ${err.code} (retryable: ${err.retryable}, request ${err.requestId})`) } else if (err instanceof ChatStreamTimeoutError) { console.error(`stream hit its ${err.timeout} limit of ${err.timeoutMs} ms; retry the request`) } else if (err instanceof IncompleteChatStreamError) { console.error(`stream cut off after ${err.deltasReceived} deltas; retry the request`) } else if (err instanceof CruxyError) { console.error(`request refused: ${err.statusCode} ${err.code}: ${err.error}`) } else { throw err } } ``` `chat.stream` sends `idempotencyKey` as `Idempotency-Key`, and retries under the client's `retryConfig`, but only before the stream opens. See [SDK errors, retries, and timeouts](/docs/en/sdk/typescript/errors-and-retries#retries). ## Call tools Describe functions in `tools`, and use `toolChoice` to force or forbid a call. When the model calls one, the reply's `finishReason` is `tool_calls` and `message.toolCalls` lists the calls. Run each, send the result back as a `tool` message with the call's `toolCallId`, and ask again: ```ts import { Cruxy } from '@cruxy/api' import type { ChatMessage, ChatTool } from '@cruxy/api/models' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const tools: ChatTool[] = [ { type: 'function', function: { name: 'get_weather', description: 'Get the current weather for a city.', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'], }, }, }, ] const messages: ChatMessage[] = [{ role: 'user', content: 'Is it raining in Paris?' }] let { result } = await cruxy.chat.createChatCompletion({ body: { model: 'saga', messages, tools, toolChoice: 'auto' }, }) while (result.finishReason === 'tool_calls') { messages.push(result.message) for (const call of result.message.toolCalls ?? []) { const args = JSON.parse(call.function.arguments) as { city?: string } // Run your own function here. const output = { city: args.city, raining: false } messages.push({ role: 'tool', toolCallId: call.id, content: JSON.stringify(output) }) } const next = await cruxy.chat.createChatCompletion({ body: { model: 'saga', messages, tools }, }) result = next.result } console.log(result.message.content) ``` An assistant message you build yourself must send `content`, even when it only carries `toolCalls`: send `content: ''`. When streaming, read the assembled calls from `stream.toolCalls` after the loop: each has `id`, `name`, and the complete `arguments` string. For the full round trip and its rules, see [Tutorial: build a tool-using agent](/docs/en/build/tool-agent). ================================================================================ Page: Embeddings, rerank, and more with the SDK URL: https://learn.cruxyai.com/docs/en/sdk/typescript/methods Markdown: https://learn.cruxyai.com/docs/en/sdk/typescript/methods.md ================================================================================ # Embeddings, rerank, and more with the SDK Call embeddings, rerank, moderations, models, token counting, identity, device login, and feedback with the TypeScript SDK, and read the results. Each sample creates its own client so it runs on its own. In your code, create one `Cruxy` client and reuse it. Every method resolves to `{ headers, result }`; see [TypeScript SDK](/docs/en/sdk/typescript#requests-and-responses). ## Embeddings `embeddings.createEmbeddings` turns text into vectors with `cruxy-embed`. In the SDK, `input` is an array of strings, though the API also takes a bare string; send a one-element array for one text. See [Embeddings](/docs/en/build/embeddings). ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result } = await cruxy.embeddings.createEmbeddings({ body: { model: 'cruxy-embed', input: ['The quick brown fox', 'jumps over the lazy dog'], }, }) for (const item of result.data) { console.log(item.index, item.embedding.length) } console.log(result.usage.promptTokens, result.cruxy.requestId) ``` `result.data` holds one entry per input, in input order, each with its `index` and `embedding`. `result.usage` has `promptTokens` and `totalTokens`, and `result.cruxy` has `requestId` and `cost`. ## Rerank `rerank.rerankDocuments` scores documents against a query with `cruxy-rerank` and returns them best first. See [Rerank](/docs/en/build/rerank). ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const documents = [ 'Paris is the capital and largest city of France.', 'Berlin is the capital of Germany.', 'The Louvre is a museum in Paris.', ] const { result } = await cruxy.rerank.rerankDocuments({ body: { model: 'cruxy-rerank', query: 'What is the capital of France?', documents, topN: 2, }, }) for (const hit of result.results) { console.log(hit.relevanceScore, documents[hit.index]) } ``` Each result has the `index` of a document in your array and its `relevanceScore`. ## Moderations `moderations.createModeration` checks text with the `cruxy-guard` model. Like embeddings, `input` is an array of strings. See [Moderations](/docs/en/build/moderations). ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result } = await cruxy.moderations.createModeration({ body: { model: 'cruxy-guard', input: ['I want to learn how to bake bread.'] }, }) const verdict = result.results[0] if (verdict?.flagged) { console.log('flagged', verdict.categories, verdict.cruxy?.hazardCodes) } ``` Each result has `flagged`, the boolean `categories`, and `categoryScores`, with camelCase names such as `selfHarm`, `hateThreatening`, and `illicitViolent`, plus `cruxy.hazardCodes`. Decide on `flagged`, not on the scores. ## Models `models.listModels` reads the tier catalog. ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result } = await cruxy.models.listModels() for (const model of result.data) { console.log(model.id, model.profile, model.maxOutput, model.reasoning?.defaultEffort) } ``` Each entry has `id`, `label`, `profile`, `contextWindow`, `maxOutput`, `supportsTools`, `supportsVision`, `latencyTargetMs`, `reasoning` (`defaultEffort` and `graded`), and `pricing`. See [Models](/docs/en/reference/models) and [Choosing a tier](/docs/en/build/choosing-a-tier). ## Count tokens `tokens.countTokens` returns the input tokens a chat request would bill, for the same tier, messages, and tools. It calls no model and is not billed. It takes a tier, not `auto`. See [Usage and cost](/docs/en/build/usage-and-cost). ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result } = await cruxy.tokens.countTokens({ body: { model: 'epos', messages: [{ role: 'user', content: 'How many tokens is this?' }], }, }) console.log(result.model, result.inputTokens) ``` ## Identity `auth.getCurrentIdentity` returns the identity behind your key. Call it once after you store a new key to confirm it works. ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result: me } = await cruxy.auth.getCurrentIdentity() console.log(`key ${me.apiKeyId} belongs to user ${me.userId}`) ``` A key that is missing, wrong, expired, or revoked throws a `CruxyError` with status `401` and code `unauthorized`. `auth.revokeCurrentKey` revokes the key the client sends, and only that key. Call it when a person signs out, then delete the stored key: ```ts import { Cruxy } from '@cruxy/api' import { CruxyError } from '@cruxy/api/models/errors' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) try { await cruxy.auth.revokeCurrentKey() } catch (err) { // A 401 means the key was already unusable, so it is signed out either way. if (!(err instanceof CruxyError && err.statusCode === 401)) throw err } ``` It resolves once the key is revoked, and the key stops working at once. The `204` has no body, so the result carries only the response `headers`; the type also allows `undefined`. A key whose allowed scopes exclude `account`, or a read-only key, throws `403` (`key_scope_forbidden` or `key_read_only`). See [Revoke the current key](/docs/en/get-started/api-keys#revoke-the-current-key). ## Device login `deviceLogin.startDeviceLogin` and `deviceLogin.pollDeviceToken` run device login, which mints a signed-in credential. The endpoints need no key, so the sample creates its client without `bearerAuth`; a client that has a key, from `bearerAuth` or `CRUXY_BEARER_AUTH`, sends it on these calls too. For the flow, and when to use it, see [Get your API key](/docs/en/get-started/api-keys#device-login). ```ts import { Cruxy } from '@cruxy/api' import { CruxyError, DeviceTokenPendingResponseError } from '@cruxy/api/models/errors' const cruxy = new Cruxy() const sleep = (seconds: number) => new Promise((r) => setTimeout(r, seconds * 1000)) const { result: device } = await cruxy.deviceLogin.startDeviceLogin() console.log(`Open ${device.verificationUriComplete} and confirm ${device.userCode}`) const deadline = Date.now() + device.expiresIn * 1000 while (Date.now() < deadline) { await sleep(device.interval) try { const { result: key } = await cruxy.deviceLogin.pollDeviceToken({ body: { deviceCode: device.deviceCode }, }) // Store key.accessToken now: it is returned once. Log the id, never the key. console.log(`Minted key ${key.keyId} for ${key.org.name}, expires ${key.expiresAt.toISOString()}`) break } catch (err) { if (err instanceof DeviceTokenPendingResponseError && err.code === 'authorization_pending') { continue } if (err instanceof CruxyError && err.statusCode === 429) { await sleep(err.retryAfter ?? device.interval) continue } throw err // access_denied, expired_token, invalid_grant, or another failure } } ``` Every `400` from polling, pending or refused, is a `DeviceTokenPendingResponseError` with the OAuth-style `code`. Only `authorization_pending` means keep polling. A refusal can carry `reason`, such as `org_membership_revoked`, and `errorDescription`. A `429` from either call is a `CruxyError` with `retryAfter` in seconds. The token response's `org` is the organization the key is bound to, with its `id`, `name`, and the person's `role` in it; show it to them after login. `expiresAt` is a `Date`. ## Feedback `feedback.submitFeedback` records a signal about an earlier call, identified by its request ID. See [Feedback](/docs/en/build/feedback). ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result } = await cruxy.feedback.submitFeedback({ body: { requestId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', type: 'thumbs', consent: true, payload: { value: 'up' }, }, }) console.log(result.stored) ``` `type` is `thumbs`, `test_result`, `edit_accepted`, or `edit_rejected`, and fixes the shape of `payload`. The call answers `202`; `stored` says whether the event was kept. ================================================================================ Page: SDK errors, retries, and timeouts URL: https://learn.cruxyai.com/docs/en/sdk/typescript/errors-and-retries Markdown: https://learn.cruxyai.com/docs/en/sdk/typescript/errors-and-retries.md ================================================================================ # SDK errors, retries, and timeouts Catch the TypeScript SDK's typed errors, set up retries that follow the gateway's retry contract, and set timeouts, idempotency keys, and request IDs. The SDK throws on any failed request, with an error class that says where it failed. Retries and timeouts are off until you turn them on. For the API's error envelope and every error code, see [Errors and retries](/docs/en/build/errors-and-retries). ## Error classes Import the error classes from `@cruxy/api/models/errors`, and the streaming ones from `@cruxy/api`. | Class | Thrown when | What it carries | | --- | --- | --- | | `CruxyError` | The gateway answered with an error status and its JSON error envelope, from any method. | `code`, `error` (the message), `requestId`, the envelope's detail fields, and the `CruxyBaseError` fields. | | `CruxyDefaultError` | An error status whose body is not JSON, such as an HTML page from a proxy. | The `CruxyBaseError` fields. | | `DeviceTokenPendingResponseError` | `deviceLogin.pollDeviceToken` got a `400`: still pending, or refused for good. | `code` (`authorization_pending`, `access_denied`, `expired_token`, or `invalid_grant`), `error`, `errorDescription`, `reason`, `requestId`. | | `ResponseValidationError` | A response did not match the spec, such as a missing required field. | `rawValue`, the body as received. | | `SDKValidationError` | Your request failed the SDK's validation before it was sent. | `rawValue`. | | `ConnectionError` | The request could not reach the server. | `cause`. | | `RequestTimeoutError` | `timeoutMs` passed before a response arrived. | `cause`. | | `RequestAbortedError` | Your `signal` aborted the request. | `cause`. | | `ChatStreamFrameError`, `IncompleteChatStreamError`, `ChatStreamTimeoutError`, `MalformedChatStreamError` | A chat stream failed after it opened; see [Stream errors](/docs/en/sdk/typescript/chat#stream-errors). | | `CruxyError`, `CruxyDefaultError`, `DeviceTokenPendingResponseError`, and the stream errors all extend `CruxyBaseError`, which carries `statusCode`, `body` (the raw response text), `headers`, `contentType`, and `rawResponse`. None of them carries your key: the request attached to an error has no `Authorization` header. A `CruxyError` carries the envelope's detail fields when the code sends them, among them `retryAfter` (seconds), `resetAt`, `tier`, `model`, `window`, `limit`, `requiredScope`, and `requiredVersion`. Read the gateway's message from `error`, not `message`. A `CruxyError`'s `message` is `API error occurred: ` followed by the parsed envelope as JSON. ## Branch on the code Branch on `code`, never on the wording of the message: ```ts import { Cruxy } from '@cruxy/api' import { CruxyError } from '@cruxy/api/models/errors' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) try { const { result } = await cruxy.embeddings.createEmbeddings({ body: { model: 'cruxy-embed', input: ['The quick brown fox'] }, }) console.log(result.data.length) } catch (err) { if (!(err instanceof CruxyError)) throw err switch (err.code) { case 'rate_limited': // Wait err.retryAfter seconds and retry, or let the SDK retry; see Retries. break case 'budget_exhausted': // Retrying cannot help until err.resetAt. break case 'unauthorized': // Fix the key; retrying cannot help. break default: console.error(`${err.statusCode} ${err.code}: ${err.error} (request ${err.requestId})`) } } ``` The codes, and what each needs from you, are in [Errors and retries](/docs/en/build/errors-and-retries). ## Retries Retries are off by default: a failed request throws at once. Turn them on for the whole client with `retryConfig`, or for one call with the `retries` option. The client's `retryConfig` covers every method, `chat.stream` included. ```ts import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY, retryConfig: { strategy: 'backoff', backoff: { initialInterval: 1_000, maxInterval: 20_000, exponent: 1.5, maxElapsedTime: 60_000, }, retryConnectionErrors: true, }, }) const { result } = await cruxy.models.listModels() console.log(result.data.length) ``` - **What is retried:** a response whose status is in `retryCodes` (by default `429`, `500`, `502`, `503`, and `504`) and whose error `code` the gateway's retry contract says to retry. With `retryConnectionErrors: true`, attempts that could not connect or that passed `timeoutMs` are retried too. Set `retryCodes` on a call to change the statuses for that call. - **How long it waits:** exponential backoff with up to a second of random jitter on each wait. When `backoff` is left out, the waits grow from `initialInterval` 500 ms by `exponent` 1.5, capped at 60 s each and an hour in total. A `Retry-After` or `retry-after-ms` header on the response sets the wait instead, capped at `maxInterval`. - **What is resent:** the same request, headers included, so an `idempotencyKey` is reused on every attempt. ### Which codes are retried The SDK retries these codes, and no others: `rate_limited`, `limits_unavailable`, `credits_unavailable`, `headless_concurrency_limit`, `upstream_overloaded`, `model_unavailable`, `all_models_unavailable`, `service_unavailable`, `upstream_timeout`, `server_shutting_down`, and `internal_error`. So a retryable status is still not retried when its code says waiting cannot help: - **Budget and spend-cap `429`s are not retried:** `budget_exhausted`, `message_limit_reached`, `key_spend_cap_exceeded`, `workspace_spend_cap_exceeded`, and `credits_exhausted`. They clear only at `resetAt`, or when the cap changes, which can be days away. The SDK throws the `CruxyError` at once; read `resetAt` and decide. See [Rate limits and budgets](/docs/en/build/rate-limits). - **`upstream_error` (`502`) is not retried.** - **A code the SDK does not know is not retried.** A response with no Cruxy error envelope, such as an HTML `502` from a proxy, is retried by its status alone. The list is exported as `RETRYABLE_ERROR_CODES`, with `isRetryableErrorCode(code)`, from `@cruxy/api`, so your own retry logic can give the same answer. ### Streams `chat.stream` retries only while it opens: a `429` or `5xx` before any bytes arrive is retried under the same rules. Once the stream opens it is never resent for you, because a resent stream would repeat output. A stream that fails after it opens throws, and `ChatStreamFrameError.retryable` gives the same answer for its code as the list above. To retry it yourself, send the request again with the same `idempotencyKey`. ## Timeouts There is no timeout by default. On every method except `chat.stream`, `timeoutMs` on the client, or on one call, bounds the whole call: an attempt that runs longer throws a `RequestTimeoutError`. When you pass your own `signal`, `timeoutMs` does not apply to that call. On `chat.stream`, `timeoutMs` bounds only the wait for response headers, so it never cuts off a stream that is still sending. Bound the body with `idleTimeoutMs` and `totalTimeoutMs`; see [Stream timeouts](/docs/en/sdk/typescript/chat#stream-timeouts). For the gateway's own deadlines, see [Deadlines and timeouts](/docs/en/build/reliability#deadlines-and-timeouts). ## Idempotency `idempotencyKey` sends `Idempotency-Key` on `chat.createChatCompletion`, `chat.stream`, `embeddings.createEmbeddings`, `rerank.rerankDocuments`, `moderations.createModeration`, and `files.uploadFile`. Mint one key per logical request and reuse it on every retry, so a request the gateway already completed is not run and billed again: ```ts import { randomUUID } from 'node:crypto' import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY, retryConfig: { strategy: 'backoff', retryConnectionErrors: true }, }) const { result } = await cruxy.chat.createChatCompletion({ idempotencyKey: randomUUID(), body: { model: 'epos', messages: [{ role: 'user', content: 'Say hello.' }] }, }) console.log(result.message.content) ``` A stream is not replayed from the key; how the gateway bills a retried stream is in [Errors and retries](/docs/en/build/errors-and-retries#make-retries-idempotent). How it treats the key on every route is in [Retry safely with Idempotency-Key](/docs/en/build/reliability#retry-safely-with-idempotency-key). ## Request IDs Every response carries an `X-Request-Id` header, and most bodies carry the call's request ID too. Log it, and quote it when you email [support@cruxyai.com](mailto:support@cruxyai.com) about a call: | Where | How to read it | | --- | --- | | Any response | `headers['x-request-id']?.[0]` | | `chat.createChatCompletion` | `result.requestId` | | `chat.stream` | `stream.requestId`, from the `start` frame | | `embeddings.createEmbeddings`, `rerank.rerankDocuments` | `result.cruxy.requestId` | | A `CruxyError` or `ChatStreamFrameError` | `err.requestId` | | A `CruxyDefaultError` | `err.headers.get('x-request-id')` | To send your own ID, pass it as a header on the call, such as `{ headers: { 'X-Request-Id': 'order-1234-attempt-1' } }`. The rules for what the gateway accepts, and what else to send with a report, are in [Request IDs and metadata](/docs/en/build/request-ids#report-a-problem). ================================================================================ Page: Errors URL: https://learn.cruxyai.com/docs/en/reference/errors Markdown: https://learn.cruxyai.com/docs/en/reference/errors.md ================================================================================ # Errors The error response shape and what 400, 401, 403, and 429 mean. When a request fails, the gateway returns a non-2xx status and a JSON error body. Handle it by reading the HTTP status first, then the `code`. ```json { "code": "invalid_request", "error": "invalid JSON body", "request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" } ``` | Field | Meaning | | --- | --- | | `code` | A stable, machine-readable slug; branch on this. | | `error` | A human-readable message. Log it; don't parse it. | | `request_id` | The id of the failed call. Log it. | Check `code`, not the wording of `error`, in your control flow: the message can change, the code will not. [Errors and retries](/docs/en/build/errors-and-retries) lists every code the API defines and which failures to retry. ```ts const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'canto', messages: [] }), }) if (!res.ok) { const { code, error } = await res.json() console.error(`request failed (${res.status}): ${code} - ${error}`) } ``` ## Status codes The authenticated endpoints ([Chat](/docs/en/build/chat), [Embeddings](/docs/en/build/embeddings), [Rerank](/docs/en/build/rerank), and [Moderations](/docs/en/build/moderations)) share most of these failures. Moderations never returns `budget_exhausted` or `api_share_exhausted`. ### 400 Bad Request The request was malformed: invalid JSON, a missing required field, or a value the endpoint rejects. Fix the request; retrying it unchanged fails the same way. ### 401 Unauthorized The code is always `unauthorized`: the Bearer key is missing, malformed, unknown, expired, or revoked, and each case gets the same answer. Check the `Authorization` header and the key itself; verify it with [`GET /api/v1/me`](/docs/en/get-started/api-keys#verify-the-key). ### 403 Forbidden The key is genuine, but its account may not do this: | `code` | Meaning | | --- | --- | | `plan_required` | A developer API key on a plan without API access (Free). Move to a paid plan, or sign in instead. | | `model_not_in_plan` | Chat only: the account's plan does not include the tier the request named. It carries `model` and `plan`; send a tier from `models` on `GET /api/v1/limits`, or `auto`. See [Plan limits](/docs/en/build/plan-limits). | ### 429 Too Many Requests A limit was hit. The `code` tells you which: | `code` | Meaning | | --- | --- | | `rate_limited` | Requests are arriving too fast. Slow down, then retry. | | `budget_exhausted` | The account's budget is spent. Retrying won't clear it until the budget resets or is raised. | | `api_share_exhausted` | A developer API key: the account's developer keys have used the plan's API share, 25% of its monthly usage. It clears at `reset_at`; the signed-in credential is not refused. See [Plan limits](/docs/en/build/plan-limits). | | `file_limit_reached`, `image_limit_reached` | `POST /api/v1/files` only: the plan's file or image uploads for the month are stored. Nothing is stored until `reset_at`; see [Plan limits](/docs/en/build/plan-limits). | The two are distinct: `rate_limited` clears on its own once you ease off, while `budget_exhausted` is a spend ceiling that a retry alone won't resolve. [Rate limits and budgets](/docs/en/build/rate-limits) covers both, and the headers that tell you how much headroom is left. ## Device-login errors The device-login endpoints use their own OAuth-style codes on `400` (`authorization_pending`, `access_denied`, `expired_token`, `invalid_grant`) rather than the generic error shape above. Those are covered in [Get your API key](/docs/en/get-started/api-keys#device-login). ## Next steps - [Errors and retries](/docs/en/build/errors-and-retries): every error code, and how to retry. - [Authentication](/docs/en/get-started/authentication): resolve `401`s. - [Chat](/docs/en/build/chat): where these errors surface most. - [Changelog](/docs/en/reference/changelog): when the API version changes. ================================================================================ Page: API Reference URL: https://learn.cruxyai.com/docs/en/reference/api Markdown: https://learn.cruxyai.com/docs/en/reference/api.md ================================================================================ # API Reference The complete Cruxy API: every endpoint, typed and interactive. ## GET /api/health: Liveness probe health. Returns 200 as soon as the HTTP listener is up, and cannot return anything else. `commit` is the git commit the running binary was built from (`unknown` for a build that recorded none). Liveness only — it checks no database, schema, or upstream, so it is NOT suitable as a status-page component. Use GET /api/ready for deep readiness. ## GET /api/ready: Readiness probe health. Deep readiness a deploy gates on. Returns 200 only when the database is reachable AND the schema is at or beyond this binary's embedded version; otherwise 503. Distinct from the liveness GET /api/health. ## GET /api/status: Public platform status health. Public, unauthenticated status document for every platform component, the API, the database, each chat tier (by its pre-rename id kavi, vaani, mira, which status component ids keep until V1.1: a client displays them as Canto, Saga and Epos), and each auxiliary serving tier (cruxy-embed, cruxy-rerank, cruxy-guard), each built from active upstream probes rather than from live traffic. Every component carries checked_at and age_seconds; a component not measured recently enough reports "unknown" with a reason, and never a stale verdict. latency_target_ms is present only for the chat tiers (the same value GET /api/v1/models publishes) and is not a threshold. A model component is "degraded" when its median probe latency exceeds latency_degrade_above_ms, when its newest probe succeeded but took longer than latency_slow_above_ms, when its newest probe failed after a success, or, for a chat tier, when the circuit breaker is withholding traffic; it is "down" when its latest two probes both failed. The database is healthy or down. Returns 503 only when no model component has a fresh measurement (i.e. the document itself cannot be trusted); a component that is measurably down is a 200 carrying "down". Components is an array of self-describing rows and may grow, iterate it and read `kind` rather than indexing it. Never cached. ## POST /api/v1/auth/oauth/start: Start native OAuth login oauth-login. Begins a native in-app OAuth login ("Continue with Google/Microsoft/GitHub"). No auth, rate-limited. The CLIENT generates an RFC 7636 PKCE pair and sends the S256 code_challenge; the code_verifier must never be sent here. Open the returned authorization_url in the system browser (never an embedded webview), then POST the code that arrives on your redirect_uri to /api/v1/auth/oauth/token together with the verifier and this state. redirect_uri must be on the server's allowlist FOR THAT PROVIDER — the allowlist is per-provider, so a callback registered for one provider is rejected for another, and for Google it also selects which platform client (iOS or Android) the flow uses. The state is single-use and short-lived. ## POST /api/v1/auth/oauth/token: Complete native OAuth login oauth-login. Exchanges a provider authorization code for a Cruxy API key. Validates the single-use state and the RFC 7636 S256 PKCE verifier, exchanges the code with the provider server-side, resolves the existing Cruxy account from the provider's VERIFIED email (it never creates one: an email with no account is refused with account_required, and the person signs up at https://cruxy.ai/signup first), and mints a cxy_live_ key. The response is byte-identical to POST /api/v1/device/token, so one token-handling path serves both login methods - including `org`, the organization the credential is bound to and the tenant every subsequent request on this key acts in. A user in more than one organization cannot be signed in this way at all (`org_selection_required`): there is no step here where a human could choose. The key is returned exactly once. No cookie is set and no provider token is ever returned. ## POST /api/v1/chat: Chat completions chat. OpenAI-compatible chat completions. model is a public tier - canto (Deep), saga (Balanced) or epos (Fast) - or auto to let the server-side router pick the tier from the request. kavi, vaani and mira are deprecated aliases of canto, saga and epos: still accepted on input on every API version and served as the same tier. Responses name the served tier by its public id (canto, saga, epos) from Cruxy-Version 2026-10-18, and when no Cruxy-Version is sent; a request pinned to an earlier date is echoed the old id (kavi, vaani, mira). The canonical path for chat completions is this one, POST /api/v1/chat (native wire: POST /api/v2/chat); an unversioned POST /api/chat is the cruxy-app web BFF's own proxy route on its own origin, not a gateway endpoint - see the API description. stream is optional and false by default. With stream:true the response is OpenAI-style Server-Sent Events: a sequence of `chat.completion.chunk` events, each one object on a `data:` line. FRAME ORDER - a successful stream emits exactly these frames, in this order, and a client must tolerate all of them: (1) a ROLE PRIMER, always first and always before any model output, whose choices[0].delta is {"role":"assistant","content":""} - content is the empty string, not absent - and which carries the turn's cruxy.* block (routed_tier, request_id, reasoning_effort, plus memory_recall / rules_applied when they apply); (2) zero or more CONTENT or TOOL-CALL DELTAS, choices[0].delta carrying either a content fragment or tool_calls fragments (never both), each with finish_reason null, and, from Cruxy-Version 2026-11-12 (and when no Cruxy-Version is sent), zero or more REASONING FRAMES among them, one per fragment of a reasoning tier's thinking trace, whose choices[0].delta is an EMPTY object {} with finish_reason null and whose cruxy block is {"reasoning":""}, the native v2 wire's reasoning data: concatenate the fragments in order for the trace and never append them to content; a request pinned to an earlier date receives no reasoning frames; (3) exactly one FINISH_REASON frame, whose choices[0].delta is an EMPTY object {} and which sets finish_reason but carries NO usage - detect it by a non-null finish_reason, not by the empty delta, which a reasoning frame also has; (4) exactly one terminal USAGE frame, which has `choices: []` - an EMPTY ARRAY, no choices[0] to index - and carries the final usage object (and cruxy.memory_capture when the turn stored memory); then (5) the literal line `data: [DONE]`, which is NOT JSON and must not be parsed as such. The usage frame is intentional and contractually stable: it is OpenAI's include_usage convention, which is exactly why frames 3 and 4 are separate and are never combined - a strict OpenAI-compatible client reads usage only from the choices-empty chunk. Note usage.cost is an OBJECT ({amount, currency, input_unit, output_unit, cache_read_unit, tier}), not a number - read usage.cost.amount for a scalar. cost is present on every usage frame, while the additive INTEGER Cruxy usage fields (billable_input_tokens, cache_read_tokens, cache_write_tokens) are omitted when zero and prompt_tokens_details appears only with prompt-cache activity, so their absence means zero rather than an error. Changing SSE framing or frame order is a breaking change requiring a new dated Cruxy-Version, so a client may rely on the order above; new additive cruxy.* fields, however, ship WITHOUT a version bump, so ignore unknown JSON fields. A failure AFTER the stream opens carries no error frame - the 200 is already committed, so the gateway simply stops, ending the response WITHOUT frames 3-5 and WITHOUT the `data: [DONE]` terminator. `data: [DONE]` is therefore the ONLY success signal: treat a stream that ends before it (body closed, or a read returning EOF) as a failed, incomplete completion, and discard or retry the partial output rather than presenting it as a finished answer - the tokens delivered were real and are billed as a partial usage row, but the completion did not finish. For an explicit terminal failure frame instead of truncation, use the native v2 wire (POST /api/v2/chat), whose stream always ends with a named finish or error frame and has no [DONE] sentinel. With stream:false or stream omitted the response is Cruxy-flattened: the assistant reply is the top-level message with a sibling finish_reason, not an OpenAI choices[] array, and from Cruxy-Version 2026-11-12 (and when no Cruxy-Version is sent) a reasoning tier's whole thinking trace is cruxy.reasoning, never part of message. finish_reason is "stop", "tool_calls" (answer message.tool_calls and continue the turn), "length", or "content_filter". TIMEOUTS AND RETRIES. With stream:false the gateway makes ONE attempt at the model, bounded by the tier's deadline: canto 90s, saga 90s, epos 45s. An attempt that runs past it is cancelled and answered 504 upstream_timeout, and nothing is billed. The gateway does NOT retry a timeout, since a turn that needed longer needs longer again: send stream:true (a stream may run for up to five minutes), or ask for less with a lower max_tokens or reasoning_effort. Other upstream failures (an overloaded or failing model, a dropped connection) are retried inside the gateway a bounded number of times, with backoff, before it answers 503 upstream_overloaded or 503 model_unavailable; on stream:true that happens only while the stream is being opened, never after a byte has reached you. The gateway never moves a call to another tier once it is sent: model auto picks a healthy tier before the call, and an explicit tier that kept failing is refused at once with 503 model_unavailable while it cools down. REASONING SPENDS max_tokens: with reasoning_effort omitted each tier applies its default - canto high (thinking on), saga low, epos none; auto chooses per request - echoed as cruxy.reasoning_effort, and a reasoning tier generates its thinking inside the same max_tokens budget as the answer without returning it as content (from Cruxy-Version 2026-11-12 it is returned beside the answer as cruxy.reasoning, and billed exactly as before, inside output_tokens). A small max_tokens on canto can therefore be spent entirely on thinking, ending with finish_reason "length" and empty content; send reasoning_effort:"none" for a short direct answer, or leave max_tokens unset (the tier's cap) to keep reasoning. Cruxy-native fields are additive and namespaced under cruxy.*: the block carries routed_tier, request_id, and reasoning_effort, while token counts and cost live in the usage object (cost at usage.cost). WHICH CREDENTIALS USE MEMORY: memory recall and automatic capture are ON by default for a credential a person gets by signing in (the Cruxy web app, desktop, the CLI's device login, mobile) and OFF by default for a developer API key or a headless key, which opts in per request with memory:{"recall":true} and/or memory:{"capture":true} (see PER-REQUEST MEMORY CONTROLS below). A key minted by POST /api/v1/device/token or POST /api/v1/auth/oauth/token is a signed-in credential whichever client ran the flow, a third-party tool included, so it has memory and rules on; a server must use a developer API key instead (see BearerAuth). GET /api/v1/limits reports the kind as bucket: subscription is signed in, apikey and headless are not. An API key often serves people other than its owner, and recall would put the owner's stored memory into their turns while capture would store what they say, so neither happens unless the request asks. A key whose allowed_scopes omit the memory family can never use memory through chat - asking with true is 403 key_scope_forbidden (required_scope memory), refused before anything is billed - which makes it the key to issue for a service that must never see anyone's memory. When recall runs, relevant stored memories are recalled server-side and added to the turn as background context, drawn from the same resolved view GET /api/v1/memories lists: the caller's personal memory, their organization's, and the vaults they can read. The optional vault_id names the vault a chat is happening inside - it does not gate vault memory generally (a readable `default` vault's memory is recalled either way), it selects the ISOLATED case: inside a `vault_only` vault recall draws on ONLY that vault's memory, excluding personal and organization memory, and outside it that vault contributes nothing. A vault_id the caller cannot read is treated as none and never reported, so the request cannot be used to test whether a vault id exists. What was recalled is reported additively as cruxy.memory_recall (scope - personal, org, or vault - and key per memory; never the stored value), and a vault-scope memory names the vault it came from (vault_id, plus vault_name when it resolves). A turn may also REFERENCE vaults it is not inside with mentioned_vault_ids - the ids behind an "@VersionGate", resolved by your own picker, never by the gateway reading names out of the message. At most 3 are used; ids you cannot read, repeats, and the active vault_id are dropped silently, so the response is identical to one that never sent them and the field cannot be used to probe whether a vault id exists. An accepted mention adds that vault's memory to this turn's recall - sharing the same recall budget rather than enlarging it, and keeping each vault's isolation intact - without making the vault writable. WHICH CREDENTIALS GET STANDING RULES: the same default as memory. Your organization's standing rules are injected by default for a credential a person gets by signing in, and NOT for a developer API key or a headless key, whose rules are its owner's organization's guidance and which a visitor to whatever the key serves could ask the model to repeat. Such a key opts in per request with rules:true, or once, on the key, by being issued allowed_scopes that NAME the rules family (an unscoped key has every family but has not opted in). Any credential may send rules:false to decline them for a turn, which needs no scope since the user's own message already overrides them. A key whose allowed_scopes omit rules never gets them, and rules:true on it is 403 key_scope_forbidden (required_scope rules), refused before anything is billed. The switch covers the whole resolved ruleset, the organization's and, with vault_id, the vault's, so a turn gets exactly what GET /api/v1/rules/resolved returns or nothing. When rules apply and the caller's organization has configured them, they are resolved server-side and injected as guidance for the turn - as DEFAULTS the user's own message overrides, never as constraints that outrank the user - and the response signals this additively as cruxy.rules_applied (how many rules applied and from which rulesets; never the rule text, which is readable at GET /api/v1/rules/resolved). vault_id selects which rules apply too: inside a vault the turn gets that vault's own ruleset merged with the organization's per the vault's inherit_org_rules switch - the same answer GET /api/v1/rules/resolved gives for that vault - and rules_applied names each contributing scope (org, vault). A vault_id the caller cannot read is treated as none here as well, so the turn simply runs with organization-scope rules. Injected rule text is real upstream input and is counted in usage.input_tokens like any other. When capture runs, after a turn is answered the gateway also decides whether the exchange contained a durable fact worth remembering - a stated preference, a stable setting, a constraint about your work - and stores it automatically for future turns. EVERY such capture is reported in the same response as cruxy.memory_capture (how many memories were stored, and the scope and key of each; never the stored value), so nothing enters memory without the response naming it: no field means nothing was stored. Captured memory is written to your own personal memory, or - when the chat names a vault_id you may write - to that vault, so a fact learned in a shared space is remembered there; a vault you may only read demotes the capture to your own memory. It is NEVER written to organization-wide memory, whatever your role. Content carrying an email address, phone number, or card number is dropped before any write, on the same terms as the manual write endpoint. Capture cannot fail or delay a turn: if extraction is unavailable it simply stores nothing. Everything stored is listed by GET /api/v1/memories and removable with DELETE /api/v1/memories/{id}. PER-REQUEST MEMORY CONTROLS: an API key opts in with memory:{"recall":true} (inject the stored memories most relevant to this turn) and/or memory:{"capture":true} (allow a durable fact from this turn to be stored); any credential may send memory:{"recall":false} to inject no stored memory into this turn (no memory is read, mentioned_vault_ids are not consulted, no cruxy.memory_recall is returned, and input tokens fall by the size of the block that would have been injected), and memory:{"capture":false} to store nothing from it (no extraction, no write, no cruxy.memory_capture). The two sides are independent: {"capture":false} alone keeps the turn personalised by what is already stored while storing nothing new. A missing memory object, a missing key, or null means the credential's default (on for a signed-in client, off for a developer or headless API key), and a literal true or false states your choice. false needs no key scope, since it only makes the gateway do less for your own request; true needs a key whose allowed_scopes include memory (an unscoped key has every family). Standing rules are not memory, and this field never affects them: they have their own switch, rules (see WHICH CREDENTIALS GET STANDING RULES above). Pin Cruxy-Version 2026-09-26 on every request that relies on memory:false: unknown fields are ignored rather than refused, so a gateway that predates this field would answer 200 and capture anyway, and a pinned request is instead refused by such a gateway with 400 unknown_version before recall, the upstream call, billing or capture run. This is the one exception to the rule above that a dated Cruxy-Version is only for breaking changes: a date may gate an additive request field whose silent absence on an older gateway would make the response misrepresent what it used, whether a privacy promise (as here) or content the user supplied. It is not precedent for ordinary additive fields, which still ship without a version bump. ATTACHED FILES: a user message may carry file_ids, the ids of files you uploaded with POST /api/v1/files under the same organization and user as this credential, and the gateway reads each one into the turn. The request must pin Cruxy-Version 2026-10-05 or later: a request naming file_ids without that pin is 400 invalid_request (carrying required_version), because a gateway that predates the field would ignore it and answer without the files, and the pin is what makes such a gateway refuse instead. UTF-8 text files are read (plain text, markdown, CSV, JSON, source code), and so are PDFs and Word documents (.docx), as the text read out of them once, when they were uploaded (POST /api/v1/files reports it as text_status): a document is framed, measured against the caps and billed by its text exactly as a text file is, and is never parsed on a turn. A file of another type, or whose bytes are not UTF-8 text, is 400 file_not_text, and so is a document whose text could not be read, with a reason field saying why: no_text (no text found, such as a scanned PDF), encrypted (password-protected), corrupt, unreadable (reading it went past the time or memory allowed for one document), legacy_doc (a Word 97-2003 .doc) or not_extracted (uploaded before documents were read; upload it again). A file over the per-file token cap, or one that takes the request past the per-turn cap, is 400 file_too_large, and so is a PDF of more than 500 pages (bound pages) or over 64 MiB (bound bytes), which is not read; for a document the message advises attaching a shorter excerpt. Both name the file (file_id, filename, and for file_too_large bound, limit and tokens). An id that is not yours, whether another user's, one filed under another of your organizations, missing or malformed, is 404 file_not_found, the same answer in every case. A key whose allowed_scopes omit files is 403 key_scope_forbidden (required_scope files). All of these are answered before anything is sent upstream or billed. Each file's text goes in as a user-role block immediately before the message that named it, framed as material for that message and never as instructions to follow; it never enters the system prompt, recall does not search with it, and automatic capture does not read it. A file named on several messages is sent once, before its first mention. Its tokens are input like any other and are billed on EVERY request that sends the file, wherever its block sits: a file id you keep in a conversation's history is billed on each turn, not only the first. They count toward the tier's context window: a file on an earlier message that does not fit beside the conversation, with room left for the reply's max_tokens and a margin of a tenth of the window, is left out, oldest first, and listed in files_omitted with reason context_window, and a turn that does not fit even with every earlier file left out is 400 context_overflow. POST /v1/chat/completions refuses file_ids, and POST /api/v1/tokens/count does not count them. The additive fields never remove or alter the OpenAI-shaped message, so a vanilla OpenAI client keeps parsing. ## GET /api/v1/conversations: List conversations conversations. Lists the CALLER'S OWN conversations, most recently active first. **Private to their author**: this never returns a conversation authored by anyone else, whatever the caller's organization role and whatever vaults they share. Keyset-paginated like the request-log listing: pass `?limit` (default 50, max 100) and the opaque `?cursor` from a previous response's `next_cursor`, which is null on the last page. Filter with `?vault_id` (only conversations held in that vault; a vault the caller cannot read simply matches nothing), `?archived` (false, the default, lists live conversations; true lists the archived shelf), and `?source` (chat, the default, cli, or agent: only conversations that surface wrote, so a chat client that never names a source never sees a Cruxy Code session). Each entry carries `permissions`, resolved from the same predicate the write routes enforce. Messages are not included - fetch a conversation by id for those. ## POST /api/v1/conversations: Create a conversation conversations. Creates a conversation owned by the calling user. **Conversations are private to their author** - no other member of the organization, including an owner or admin, can read, list, or search it. Optional `title` and `model` are presentation only. Optional `vault_id` holds the conversation inside a vault: it then requires `can_write` on that vault, and it is visible thereafter only while the author can still read that vault. A vault the caller participates in but cannot write is 403 vault_forbidden; one in another organization, one that does not exist, and one the caller does not participate in are all 404 vault_not_found. Omitting `vault_id` creates a loose conversation, which is the normal case. Optional `source` says which surface is writing it: `chat` (the default) or `cli` for a Cruxy Code session; `agent` is 400 invalid_request, because only the gateway writes agent transcripts. Optional `meta` is a JSON object of at most 4096 bytes once compacted, stored and returned verbatim; anything else is 400 invalid_request. The 201 body is read back from the committed transaction, so it agrees field-for-field with the next GET - including `retention_until`, the deadline after which the conversation and its messages are deleted (365 days from last activity by default). ## GET /api/v1/conversations/counts: Count conversations on each shelf conversations. Counts the CALLER'S OWN conversations on each shelf of the listing: `live` is how many `GET /api/v1/conversations` pages through with `?archived=false` (the default), and `archived` how many with `?archived=true`. It is the listing's own predicate and filters, so a count never includes a conversation the list cannot return: never one authored by anyone else, whatever the caller's organization role and whatever vaults they share, and never one in a vault the caller cannot read. `?vault_id` and `?source` narrow exactly as they do on the listing (source defaults to chat, so a chat client never counts a Cruxy Code session). There is no `?archived`: both shelves are counted in one read. Pins are not a gateway concept and are not counted here. ## GET /api/v1/conversations/search: Search your own messages conversations. Full-text search over the CALLER'S OWN messages, most relevant first. **It can never see more than the listing can**: this route and GET /api/v1/conversations embed the identical visibility predicate, so a colleague's message - including an organization admin's view of a member's, and including in a vault they share - is not merely omitted from the results but never matched. `q` is parsed with `websearch_to_tsquery`, so quoted phrases, `or`, and a leading `-` to exclude all work, and no input is a syntax error. Each hit carries a `snippet`: an excerpt with matched terms delimited by the literal markers `[[hl]]` and `[[/hl]]`. **They are deliberately not HTML** - a snippet mixes raw user-authored text with the markers, so a client must escape the whole snippet first and substitute the markers afterwards; a client that does not want highlighting can simply strip them. Archived conversations are searched too, and so is every branch of a branched conversation: a message on a branch that is not active is still the caller's own text, so it is returned with `on_active_path` false rather than hidden. `on_active_path` is true for every message of a conversation that has never forked, and otherwise for the active leaf and its ancestors, the messages GET /api/v1/conversations/{id} reads. To open an off-path hit, POST its `message_id` to /api/v1/conversations/{id}/switch. `?source` (chat, the default, cli, or agent) searches only conversations that surface wrote, matching the listing's filter. `?limit` defaults to 20, max 50. ## DELETE /api/v1/conversations/{id}: Delete a conversation conversations. Deletes a conversation and every message in it. Irreversible and immediate - there is no trash, and archiving (PUT /api/v1/conversations/{id}/archive) is the reversible option. The deletion is recorded so it can be explained later (the same happens when a conversation reaches its retention deadline): the record is metadata only - the conversation id, its author, organization and vault, how many messages it held, when it was created, and the request's X-Request-Id - and never its title or any message text. Requires `permissions.can_write`; a conversation held in a vault the caller may read but not write is 403 conversation_forbidden, and one the caller cannot see at all is 404 conversation_not_found. **Attached chat attachments go with it**: every file a message of this conversation attached with purpose chat_attachment is deleted too, unless a message in another conversation still attaches it, in which case it stays until the last such message is gone. A file uploaded for any other purpose is never deleted by this route; it is only removed from this conversation's messages, and stays in the Files API until its owner deletes it or its expires_at passes. Each deleted file is recorded the same way the conversation is: metadata only, never its filename. A file no message attached is never touched. ## GET /api/v1/conversations/{id}: Get a conversation with its messages conversations. Returns one conversation and a page of its messages. **Private to its author**: a conversation authored by another member - including when the caller is an organization admin and a member of the same vault - is 404 conversation_not_found, indistinguishable from an id in another tenant and from one that never existed. A 403 would confirm the id is real. Messages are paginated independently of the conversation listing: `?message_limit` (default 100, max 200) and the opaque `?message_cursor` from `messages.next_cursor`, which is null on the last page. `?message_order` selects the direction: `asc` (the default, oldest first) or `desc`, which returns the NEWEST messages first - the tail of a long thread in one request, rather than paging forward through the whole of it. Ordering is ranking only and never changes which messages are visible. The page echoes the direction it was read in as `messages.order`. **A `message_cursor` may only be used with the `message_order` it was issued for**; the other direction is 400 invalid_request rather than a silently different page, because one anchor names two disjoint pages depending on direction. Each message carries `status` - `complete` (the model finished its answer), `incomplete` (the answer is not whole, however the stream ended: a dropped connection, a timeout, or a length cap, i.e. `finish_reason: "length"`, which ends the stream cleanly), or `cancelled` (a human stopped it) - so a partial reply is never rendered or replayed as a finished one. A conversation can branch, and the page is ONE PATH through it, read from `messages.leaf_id` back to the first message: the active branch on a first page. A `message_cursor` carries its page's leaf, so later pages stay on that branch even if the conversation is switched to another between requests. **`?message_branch` reads another branch without switching to it**: given a message id, the page is the branch through that message, from its deepest descendant by newest child, exactly the branch `POST /api/v1/conversations/{id}/switch` with that message would make active, while the conversation stays on its active branch for every device. It is a read, so it needs no write permission. Walking each message's `sibling_ids` this way, starting from the branch through `active_leaf_message_id` (the active leaf can have a child stored without moving it, which the plain read ends above), reads every branch of a conversation, which is how a client exports the whole tree. A `message_branch` that is not a message of this conversation is 404 message_not_found. It starts a read: later pages follow `messages.next_cursor`, which carries the branch, and sending it with `message_cursor` is 400 invalid_request. ## PATCH /api/v1/conversations/{id}: Rename or retag a conversation conversations. Changes a conversation's `title` and/or `model`. A title set here is a USER DECISION and outranks the automatic one: automatic titling only ever fills a null `title` or replaces one it derived itself (`title_source` `auto`), so a rename is permanent and no later message or generated title undoes it; the conversation reports `title_source: user`. Both are optional but at least one must be present; an omitted field is left unchanged, an explicit `null` clears it, and an empty patch is 400 invalid_request rather than a no-op 200 that would tell a client its request applied when it named nothing. `vault_id` is deliberately NOT patchable: moving a conversation between vaults changes who can see it, and that is a separate operation with its own authorization rather than a side effect of a rename. Requires `permissions.can_write` — false only when the conversation is held in a vault the caller may read but not write, which is 403 conversation_forbidden. A conversation the caller cannot see at all is 404 conversation_not_found. ## DELETE /api/v1/conversations/{id}/archive: Restore a conversation conversations. Clears a conversation's archive, returning it to the default listing. Idempotent: restoring a live conversation is 204. Requires `permissions.can_write`. ## PUT /api/v1/conversations/{id}/archive: Archive a conversation conversations. Archives the conversation: it leaves the default listing and appears only with `?archived=true`. The conversation and every message are untouched — archiving is not deletion, and archived conversations are still searched, because archiving means "stop showing me this", not "forget it". Idempotent: archiving an archived conversation is 204 and does not move the original archive instant. Archiving does NOT extend the retention deadline; shelving something is not activity. Requires `permissions.can_write`. ## POST /api/v1/conversations/{id}/messages: Append a message to a conversation conversations. Appends one message to a conversation. **Where it goes in the tree**: with no `parent_id` the message answers the current leaf (`active_leaf_message_id`, or the newest message while that is null), as every append always has; with one, it answers that message, which must belong to this conversation; with `root: true` it answers nothing, and is a new root beside the first message, which is how a client edits the first message. `root` and `parent_id` together are 400. Send `expected_leaf`, the leaf you believed was current, with any message that may arrive after the conversation has moved on (an edit, a regeneration, a streamed reply). If it still is current, or you omit it, the append moves the leaf to the new message; if not, the message is stored under its parent anyway, the leaf is left on the branch someone switched to, and `leaf_moved` is false. A stale `expected_leaf` never refuses an append. A `parent_id` or `expected_leaf` that is not a message of this conversation is 400. A conversation that has never branched keeps a null `active_leaf_message_id` for as long as every append answers its newest message. `role` is one of `system`, `user`, `assistant`, `tool`. `status` is `complete` (the default: the model finished its answer), `incomplete`, the answer is not whole however the stream ended (a dropped connection, a timeout, or a length cap: a reply that ended with `finish_reason: "length"` is `incomplete` even though its stream closed cleanly), or `cancelled`, a human stopping it deliberately; storing it is what keeps a partial reply from being rendered or replayed as a finished one. An `incomplete` message may also say why in `incomplete_reason`: `length`, `content_filter`, `error` (the stream ended in an error) or `connection` (it ended with no finish at all); any other value, or a reason on a message that is not `incomplete`, is 400, and every read returns it, omitting the key when none was stored. **An agentic turn must carry its tool fields**: `tool_calls` on the assistant message that requested them (same shape /chat returns), and `tool_call_id` on each tool result naming the call it answers. `content` may be empty on an assistant message that carries `tool_calls`, the calls are the message, and is required otherwise. `tool_calls` is valid only on role `assistant`, `tool_call_id` only on role `tool` and required there; anything else is 400. A message stored without them reads back blank and replays as a transcript /chat will not accept. The `sequence` is assigned SERVER-SIDE under a row lock, so concurrent appends cannot collide or reorder the transcript, and it is returned on the created message. **The first user message NAMES the conversation.** If `title` is still null it is derived from that message's content and set in the SAME transaction as the append, so the `conversation` echoed in this response already carries it, a title that landed later would land after a client had already rendered "Untitled chat". Derivation is mechanical: the first line, whitespace collapsed and control characters dropped, truncated to 80 characters on a word boundary with an ellipsis. It applies ONLY when `title` is null, a title you set at create or by PATCH is a decision and is never overwritten, and ONLY from a `user` message, since an assistant turn is the model's words rather than yours. **A reply then names it properly**: when the conversation is a `chat` written through a first-party login, the first complete `assistant` message queues a title generation that runs after the reply, never delaying it, and a few seconds later replaces the derived title with a 2-6 word one, `title_source` going from `auto` to `generated`. A greeting or other exchange with nothing to name is retried on the next reply, up to the third. It never replaces a title you set, and a failure leaves the derived title. Read the conversation again shortly after a reply to pick it up. Content carrying no letter, digit or symbol (`"..."`, `"???"`) leaves `title` null and the next user message that does carry words names the thread instead: a meaningless title looks like a name someone chose, where null correctly says the conversation has not been named. Appending advances the conversation's `updated_at` and re-stamps its retention deadline, so a conversation in use never ages out. **Send an `Idempotency-Key` header**: a retry with the same key and body replays the stored 201 rather than writing the turn twice, and the same key with a different body is 409 idempotency_conflict. **Attached files**: a `user` message may carry `file_ids`, files you uploaded with POST /api/v1/files, and the conversation keeps them: every read returns each message's `file_ids` in the order sent (an empty array when it attached none), which is what a client sends again as /chat's `file_ids` on later turns. The request must pin `Cruxy-Version: 2026-10-06` or later; without it, `file_ids` is 400 invalid_request with `required_version`, because a gateway that predates attachments would store the message without them and answer 201. At most 20 distinct files, a repeat attached once. Each must be a file of yours under this credential's organization, or a file held by a vault you read and are not held in, when that vault is the one the conversation is filed in or the one the request names in `vault_id` (the vault the chat is happening inside, as on /chat): another user's, one filed under another of your organizations, another vault's, one whose `expires_at` has passed, a missing id and a malformed one are all 404 file_not_found naming the id, and the append writes nothing. `vault_id` is never an error and never stored, and it does not file the conversation in the vault: a vault that does not exist, is another organization's or is closed to you is the same as naming none. A key whose `allowed_scopes` omit `files` is 403 key_scope_forbidden. Deleting the conversation, or its retention deadline passing, deletes every attached file that no message in another conversation still attaches; a file attached elsewhere lives until its last attaching message goes. Deleting a file yourself removes it from the messages that listed it. **The turn record**: an `assistant` message may carry `activity`, a JSON object of the client's own shape recording what the turn did (the steps a client drew while the reply streamed), so the client can show them again when the conversation is reopened. It is stored as sent, compacted, returned on every read of the message and omitted on one without it, never sent to a model, never changed after the append, and deleted with the message. On any other role, as anything but an object, or past 65,536 bytes of compact JSON it is 400 invalid_request; null is the same as omitted. No version pin: a gateway that predates it ignores the field. **How the reply was served**: an `assistant` message may also carry `routing_mode` (`explicit`, `auto` or `auto_degraded`, the stream's routing mode), `routed_tier` (the tier that answered, as the stream named it, in either spelling; stored as the tier and read back named as your `Cruxy-Version` names tiers) and `reply_ms` (your measure from sending the chat request to its last token, in milliseconds, 0 to 86,400,000), so a reopened chat can show which tier answered and how long it took, and `input_tokens` (the chat response's `usage.input_tokens` for the request that produced it, 0 to 16,777,216), so it can show how full the context window was against the `context_window` GET /api/v1/limits reports. Each is optional and independent, written once, omitted on reads when absent, and never read by billing or routing. On another role, outside its vocabulary or range, or `auto` as the routed tier, it is 400 invalid_request; null is the same as omitted. No version pin: a gateway that predates them ignores the fields. **Size**: `content` is at most 1,048,576 bytes of UTF-8 (400 invalid_request past that), and the request body at most 8,323,072 bytes (413 payload_too_large), which holds content and activity at their limits however they are escaped. Requires `permissions.can_write`. ## POST /api/v1/conversations/{id}/messages/batch: Append a run of messages to a conversation conversations. Appends up to 100 messages to a conversation in ONE transaction: either every message is stored or none is. Built for a client copying in a transcript it already has, such as a Cruxy Code session. Each message is validated exactly as `POST /api/v1/conversations/{id}/messages` validates one (role, status, content, `tool_calls` only on assistant messages, `tool_call_id` required on tool messages), and the batch is placed in the conversation as that many single appends would be. **The first message is an ordinary append**: its `parent_id`, `expected_leaf` and `root` mean what they mean on the single append. **Every later message answers the one before it** and may not set `parent_id`, `expected_leaf` or `root` (400 invalid_request). The leaf follows the first message: when the first moves the leaf, the run moves it along and it ends on the last message; when the first is stored under a stale `expected_leaf` and leaves the leaf where someone switched it, the whole run stays on its own branch, and `leaf_moved` is false. The first user message titles an untitled conversation, as on the single append. `file_ids` is not accepted here (400 invalid_request): attach files with the single append. The body is at most 1 MiB (413 payload_too_large); send a longer transcript as several batches, each answering the last. The response lists each stored message's `id`, `sequence`, `parent_id` and `role` in order, without its content. **Send an `Idempotency-Key` header**: a retry with the same key and body replays the stored 201 rather than storing the run twice, and the same key with a different body is 409 idempotency_conflict. The key is scoped to your API key, this conversation, and this route. Metered on its own rate bucket, separate from the conversation routes'. Requires `permissions.can_write`. ## POST /api/v1/conversations/{id}/switch: Switch a conversation to another branch conversations. Moves the conversation onto the branch through `message_id`, the message a version switcher picked (for example the sibling shown as "1 / 2"). The server resolves the **deepest descendant** of that message, following the newest child at each level, and makes it the conversation's active leaf, so switching back to a branch restores it with every message written on it since. The response carries that leaf as `leaf_id`; the next `GET /api/v1/conversations/{id}` reads the branch ending there. **The switch is shared state**: every device reads the branch it names, so it requires `permissions.can_write`, and a conversation held in a vault the caller may read but not write is 403 conversation_forbidden. A `message_id` that is not a message of this conversation is 404 message_not_found, whether it belongs to another conversation, another tenant, or nothing. Switching is **not activity**: `updated_at` and `retention_until` do not move, so a switch never reorders the conversation listing. A conversation that has never branched stays unbranched: every message of it resolves to its newest message, and `active_leaf_message_id` stays null. Switching to the branch already active changes nothing and still succeeds. The switch takes the same per-conversation lock an append takes and reads the tree after it, so a switch racing an append to the same branch always sees the appended message if the append committed first. ## POST /api/v1/device/code: Start device login device-login. Begins an RFC 8628 device-authorization flow (no auth, rate-limited). Returns the client's device_code, the human-typed user_code, and where to approve. Poll POST /api/v1/device/token with the device_code until approved. ## POST /api/v1/device/token: Poll device login device-login. The CLI polls with its device_code. Returns 200 with a freshly minted API key once a human has approved the flow, or an OAuth-style error (400) while pending/denied/expired/invalid. The key is returned exactly once. It is a SIGNED-IN CREDENTIAL, whichever client ran the flow: in chat it gets the person's memory recall, automatic memory capture and their organization's standing rules by default, it expires at expires_at (90 days after issue by default) and use does not renew it, and its holder cannot rotate it, and revokes it on sign-out with DELETE /api/v1/me/key. Keep it in the person's own tool. Do not deploy it in a server or in anything that serves other people: use a developer API key from the Cruxy Console there (see BearerAuth), or send memory:{"recall":false,"capture":false} and rules:false on every chat request. The 200 carries `org`: the organization the credential is bound to, with the signed-in user's role in it. Show it — a login binds to exactly one organization, and it is not always the one the previous login used. A 400 may additionally carry `reason` and `error_description`, both **additive** and both absent on most refusals; `error` and `code` are unchanged either way. The one `reason` today is `org_membership_revoked`: the authorization was approved for an organization the account no longer belongs to. Starting a new login will succeed, but it may bind to a **different** organization, so tell the user rather than retrying silently. ## POST /api/v1/embeddings: Create embeddings embeddings. OpenAI-compatible embeddings. model must be "cruxy-embed". input accepts a single string or an array of strings — at most 512 strings per request (more is 400 invalid_request), with the whole body ≤ 64 KiB (more is 413 payload_too_large). Each embedding is a fixed 1024-dimensional dense vector (size your vector store to 1024). The additive cruxy.* block carries the request id and cost; the OpenAI-shaped fields are unchanged. ## GET /api/v1/evals/runs/{id}: Get an eval run evals. Returns a run with its status and a summary of results so far: total cases, how many are completed, and the pass/fail split. Poll this after starting a run. A run id in another workspace or organization, or one that names nothing, returns `404 eval_run_not_found`. ## GET /api/v1/evals/runs/{id}/results: List a run's results evals. Lists the per-case results of a run: the model's output, the pass/fail verdict, and the latency of each completion, oldest first. A run id in another workspace or organization, or one that names nothing, returns `404 eval_run_not_found`. ## GET /api/v1/evals/suites: List eval suites evals. Lists the eval suites in the caller's workspace, each with its case count. Ordered oldest first. ## POST /api/v1/evals/suites: Create an eval suite evals. Creates an eval suite in the caller's workspace — a named container for prompt/expected cases. The workspace is the one the credential names; there is no workspace or org id in the path or body. `name` is required (1..128 bytes). `slug` is the stable, URL-safe handle and is optional: when omitted it is derived from the name; a slug already used in the workspace is `409 eval_suite_slug_exists`. `prompt_id` optionally links a stored prompt in the SAME workspace (a label only: a run never reads the prompt, and each case sends its own `input` verbatim; a prompt_id outside the workspace is `400 invalid_request`). Returns the created suite. ## DELETE /api/v1/evals/suites/{id}: Delete an eval suite evals. Deletes a suite and all of its cases, runs, and results (they cascade). A suite id in another workspace or organization, or one that names nothing, returns `404 eval_suite_not_found`. ## GET /api/v1/evals/suites/{id}: Get an eval suite evals. Returns one suite of the caller's workspace. A suite id in another workspace or organization, or one that names nothing, returns `404 eval_suite_not_found`. ## GET /api/v1/evals/suites/{id}/cases: List a suite's cases evals. Lists every case of a suite, oldest first. A suite id in another workspace or organization, or one that names nothing, returns `404 eval_suite_not_found`. ## POST /api/v1/evals/suites/{id}/cases: Add a case to a suite evals. Appends a case to a suite. `input` is the prompt sent upstream verbatim (1..102400 bytes); `expected` is the reference answer (1..102400 bytes); `match_mode` is `exact` (output equals expected, trimmed) or `contains` (output contains expected). A suite id in another workspace or organization, or one that names nothing, returns `404 eval_suite_not_found`. ## DELETE /api/v1/evals/suites/{id}/cases/{case_id}: Delete a case evals. Deletes one case of a suite. A case that is not in the suite, or a suite id in another workspace or organization, returns `404 eval_case_not_found`. ## POST /api/v1/evals/suites/{id}/runs: Start an eval run evals. Enqueues an asynchronous run of a suite against `model` (one of `canto`, `saga`, `epos`; the deprecated aliases `kavi`, `vaani` and `mira` are accepted and run as the same tier, and the run's `model` names it by its public id from Cruxy-Version 2026-10-18, or by the old id under an earlier pin) and returns immediately with the run in status `pending`; it does NOT block on execution. A background worker then runs the cases in order, oldest first, and the run **costs money**: every case is a billed completion charged to the credential that created the run, against the same budget, caps and plan as a chat call, and a run whose budget runs out stops there (status `failed`). **WHAT EACH CASE SENDS**, the same for every case of a run: one `user` message holding the case's `input` verbatim, and nothing else. There is no system prompt, no identity or rules block, no memory, no files and no tools. No `temperature` or `top_p` is sent, so the provider's defaults apply. `max_tokens` is the tier's maximum output. **Each case thinks as the tier does in chat**: it sends the tier's chat default `reasoning_effort` (by default canto `high`, saga `low`, epos `none`), or the `reasoning_effort` the request names, fixed when the run is created, and the run reports it in `reasoning_effort`. A run created before that field existed reports null and sent no reasoning control, so its cases ran with no thinking. The suite's `prompt_id` is not read: it is a label linking the suite to a stored prompt, and a case that should use that prompt must carry its text in `input`. A case passes when its output, trimmed, equals `expected` trimmed (`exact`), or contains `expected` as written (`contains`); a case whose completion fails is recorded as not passed, with empty output. **A run cannot be listed or cancelled**: there is no route for either, so keep the `id` this returns. A run, once enqueued, runs to `done` or `failed`. Poll `GET /api/v1/evals/runs/{id}` for status and results. `model: "auto"` is `400 invalid_request`, because an eval measures one fixed tier. A suite id in another workspace or organization, or one that names nothing, returns `404 eval_suite_not_found`. ## POST /api/v1/feedback: Submit feedback feedback. Inbound flywheel signal joined to a prior call by request_id. PRIVACY: a non-consented or opted-out event is dropped entirely (stored=false, no row); a consented event is stored with its payload redacted. `request_id` must be the `cruxy.request_id` of a call THIS account made; an id belonging to another account, or one that names no call at all, is one indistinguishable `404 request_not_found`. The opt-out is a durable account-level setting managed in the Cruxy app, independent of this request's `consent` flag; either a `consent:false` event or an active account opt-out is dropped. There is no public endpoint to read or change the opt-out. ## GET /api/v1/files: List files files. List the authenticated user's files, newest first. Keyset-paginated: pass ?limit (default 20, max 100) and the opaque ?cursor from a previous response's next_cursor. Only the caller's own files are ever returned. Returns {data:[…], next_cursor, total} where next_cursor is null on the last page and total is how many files the listing pages through, counted on every page. Each file carries conversations: the caller's conversations it is attached in, newest attachment first (at most 5 here, 20 on the single file read), and their total. A conversation is named only while the caller can read it, so one filed in a vault the caller is held from is neither named nor counted. ## POST /api/v1/files: Upload a file files. Upload a file as multipart/form-data. The file part is named "file"; an optional "purpose" text field labels it (short [A-Za-z0-9._-] token, default "general"). Content is stored opaquely under a generated id - never executed, never interpreted, never addressed by its original filename. Its media type is detected by the server from the content's first bytes, refined by the filename's extension only when the content already reads as UTF-8 text, and returned as content_type; the Content-Type on the multipart part is ignored. A JPEG, PNG or WebP image is recorded as image/jpeg, image/png or image/webp whatever its name, and chat shows it to a tier that reads images when a message names it in file_ids. A single file may be at most the plan's largest upload, under FILES_MAX_FILE_BYTES (default 512 MiB); exceeding it is 413 payload_too_large carrying limit. This endpoint is authenticated and per-key rate-limited but NOT billed. LIFETIME: an optional "expires_in" text field gives the file a lifetime in seconds, from 60 to 604800 (7 days), returned as expires_at. The moment it passes the file is gone to every read: it is not listed, its metadata and content are 404, it no longer counts against the quota, and chat cannot read it; the bytes are deleted from storage on the next sweep, within 15 minutes. A file uploaded from a temporary chat should always carry one. Setting it requires pinning Cruxy-Version 2026-10-07 or later, because a gateway that predates the field would keep the file forever and answer 201; without the pin, or with a value out of range, the upload is 400 invalid_request and nothing is stored. Without expires_in a file lives until you delete it, as before. UNATTACHED CHAT ATTACHMENTS: an upload with purpose "chat_attachment" exists to be attached to a conversation message (POST /api/v1/conversations/{id}/messages with file_ids). One that no message has attached 24 hours after upload is deleted, row and bytes, by the same sweep that enforces lifetimes, so a file picked in a chat and never sent does not live forever. An attached one is kept until the last message attaching it is deleted. No other purpose is ever deleted for being unattached. DOCUMENTS: a PDF, or a Word document (.docx, recognised from the zip's own content types and recorded as application/vnd.openxmlformats-officedocument.wordprocessingml.document), has its text read once, as part of the upload, so chat can read it like a text file (POST /api/v1/chat file_ids). The reading runs in a separate, bounded process (at most 15 seconds, 256 MiB, 500 pages and 64 MiB of document) and never fails the upload: the file is stored whatever it holds, and text_status reports what reading it found: extracted (text_tokens is its size, by the same characters/4 estimate chat's caps use), no_text (no text found, such as a scanned PDF), encrypted (it needs a password), corrupt (damaged, or a feature the reader does not support), too_long (over 1 MiB of text, which is not kept; text_tokens says how much there was), too_many_pages, too_big, failed (reading ran out of time or memory), or busy. Reading runs at most two documents at once; a document that arrives while both are busy waits in line for up to 30 seconds, behind at most 20 others, and only one that is still unread then is busy: nothing is wrong with the file, and the same file uploaded again is read. text_status and text_tokens are null for every other file. A legacy Word 97-2003 document is recognised from its bytes and recorded as application/msword, and is not read. A document's stored text counts toward the plan's storage pool and FILES_MAX_USER_BYTES beside its bytes. NO ROUTE RETURNS THE EXTRACTED TEXT: GET /api/v1/files/{id}/content serves the document as uploaded, and the text is read only by chat, as the file's content in a turn. It is deleted with the file. THE PLAN'S UPLOAD LIMITS: every plan but enterprise has a monthly allowance of stored files and another of stored images, a largest single upload, and a storage pool (the numbers, for every plan, are GET /api/v1/limits/plans; the caller's own are GET /api/v1/limits plan_limits; sizes are decimal, and Max has no monthly allowance). Which allowance an upload spends is decided from its detected media type: image/* is an image, anything else a file. The month is the account's own, the same one every other monthly limit runs over (see GET /api/v1/limits). An upload past its allowance is 429 file_limit_reached or image_limit_reached, refused before a byte is stored, with reset_at the end of the month, limit and used. Send an Idempotency-Key header on a retry: on this route it is read for the count alone (it is not a replay key: every attempt stores a file, and no 409 is produced), and a retry under the same key with the same content counts once. GET /api/v1/limits reports the month's counts as `files` and `images`, the pool as `storage`, and the plan's row as `plan_limits`. The file belongs to the ORGANIZATION the credential names as well as to the user, and the storage pool (the plan's, under FILES_MAX_USER_BYTES, default 2 GiB) is metered per (organization, user) - so for a member of more than one organization each tenant has its own pool, and a file uploaded with one organization's credential is not visible to another's. ## DELETE /api/v1/files/{id}: Delete a file files. Delete one of the authenticated user's files and its content. A file belonging to another user, or to another of your own organizations, is 404 — the same answer as a missing or malformed id, since a distinguishable response would confirm the id exists. Idempotent from the client's view: a repeat delete of an already-deleted id is 404. ## GET /api/v1/files/{id}: Get file metadata files. Fetch metadata for one of the authenticated user's files, within the organization the credential names. A file belonging to another user — or to another of your own organizations — returns 404 (never 403, which would confirm the id exists), as does a missing or malformed id. The file carries conversations: the caller's conversations it is attached in, newest attachment first (at most 20), and their total, naming only conversations the caller can open. ## GET /api/v1/files/{id}/content: Download file content files. Stream the raw bytes of one of the authenticated user's files. Always returned as application/octet-stream with Content-Disposition: attachment and X-Content-Type-Options: nosniff — content is never rendered inline. A file belonging to another user, or to another of your own organizations, is 404 — the same answer as a missing or malformed id, since a distinguishable response would confirm the id exists. ## GET /api/v1/invitations: List invitations addressed to me organization. Lists the live invitations addressed to the caller, across every organization — the pending offers to join somewhere. Settled and expired invitations are not listed. This route names no organization and takes none: it resolves through the caller's own account, so there is no parameter by which one person could read another's invitations. Each entry carries the inviting organization's name and the inviter's address, so the offer can be attributed before it is accepted. ## POST /api/v1/invitations/{invitation_id}/accept: Accept an invitation organization. Accepts an invitation addressed to the caller and joins that organization with the role the invitation offered. This is the only way a membership is created on a user credential's authority. An invitation that names somebody else, one that never existed, one that has expired, one already settled, and a malformed id are one `404 invitation_not_found` — there is deliberately no answer meaning "that invitation exists but is not yours". Joining an organization while already belonging to another means credential issuance can no longer resolve an organization implicitly; new credentials must name one (`org_selection_required`). Existing credentials are unaffected. ## POST /api/v1/invitations/{invitation_id}/decline: Decline an invitation organization. Declines an invitation addressed to the caller. Nothing is created and the invitation is settled, so it stops appearing in the inbox and stops being acceptable. Declining is exactly as private as accepting: an invitation that names somebody else, one that never existed, one that has expired, one already settled, and a malformed id are one `404 invitation_not_found`. The inviting organization sees the outcome on its own invitation list; it is not told anything else. ## GET /api/v1/limits: Get my limits and headroom limits. Returns the authenticated credential's tier, billing bucket, and current rate/budget limits with live remaining headroom, with every value read from the same limiter and budget state the chat path enforces on, so `remaining` here is exactly what the next request is gated against. **Credential-derived and workspace-scoped**: tier (`users.plan`), bucket, the per-key spend cap, and the per-key request-rate all come from the authenticated key; the workspace spend cap is for the workspace the key binds to. None of it is read from the request. **`rate_limits.chat`** carries the per-key and per-org chat request-rate ceilings (requests per 60s window) and their remaining count; `resets_at` is null when no request has opened the current window. **`token_pool`** (subscription and apikey buckets; a headless key reports `credits` instead) is the unit budget: the monthly cap over the account's own month (a paid plan's billing period, or a Free account's monthly anniversary of its creation; `starts_at` and `resets_at` say which) and the trailing-12h sliding burst cap, on every plan, Free included, each with used/remaining in units and `percent_used`, used over cap from 0 to 100 (one decimal place, rounded down, so 100 only once the cap is reached), so a client draws its bar without dividing. `api_share`, `files`, `images` and `storage` carry `percent_used` too. Every chat model draws on it, Epos included. `token_pool.org`, present when the credential's organization is on a Business or Enterprise plan, is that organization's cap for its billing period: an owner or admin of the organization reads its units and `percent_used`, and any other member reads only `state` (healthy or blocked) with `starts_at` and `resets_at`. **`api_share`** (on every plan with API access) is the developer-key share of that month: API keys together may use 25% of the plan's monthly units; past it a developer-key request is refused 429 api_share_exhausted, and the signed-in credential is not. **`rate_limits.chat.max_concurrent_per_key`** (developer keys only) is how many requests that key may have in flight at once. **`models`** (subscription and apikey buckets) is the chat models the plan includes: a request naming another is refused 403 model_not_in_plan, and model auto routes only among them. **`context_window`** is the plan's window (256,000 tokens on Free, 1,000,000 paid) and each included model's effective window, the smaller of the model's and the plan's; a request over it is refused 400 context_overflow. There is no message allowance: nothing counts messages. `mira` appears only while an operator's Epos request brake is on (the key keeps its historical name). blocked_models names tiers by their public ids (canto, saga, epos) from Cruxy-Version 2026-10-18; a request pinned to an earlier date reads the old ids (kavi, vaani, mira). **`credits`** (headless bucket only) is the dollar-credit pool. **`key_spend_cap`** / **`workspace_spend_cap`** appear only when a monthly micro-USD ceiling is set, reported in USD. There is deliberately no tokens-per-minute limit and no per-model daily cap: Cruxy enforces neither, so neither is invented here. No write, no cost. The endpoint is itself rate-limited and emits the standard `X-RateLimit-*` headers for its own bucket. ## GET /api/v1/limits/month: Get my month so far, day by day limits. Returns the authenticated credential's own month so far: one entry per UTC day from the day the month began to today, each with `percent_used`, the share of the month's limit used from the start of the month through the end of that day (through now, for today). It is the same measure as `token_pool.monthly.percent_used` on `GET /api/v1/limits`, by the same rule (0 to 100, one decimal place, rounded down, so 100 only once the limit is reached), over the same month (`starts_at` and `resets_at` are that window): today's entry equals that figure. The series has no gaps and never falls; a day with no usage repeats the day before. **No unit count, cap or remainder is returned.** Credential-derived, like `/limits`: nothing is read from the request, and the figures are the caller's own pool in the credential's organization. A credential with no unit pool (the headless bucket, which draws on dollar credit) gets `enforced: false` and an empty `days`. No write, no cost. The endpoint is itself rate-limited and emits the standard `X-RateLimit-*` headers for its own bucket. ## GET /api/v1/limits/plans: List every plan's limits limits. Returns the entitlements of every plan on sale, in the order the pricing page lists them: free, core, advanced, pro, max. Each entry carries the plan, its models (the chat models the plan includes, heaviest first, by the ids the request's Cruxy-Version names them: saga on free; saga and epos on core; canto, saga and epos on advanced, pro and max; a request naming any other is refused 403 model_not_in_plan), its context_window (the most input tokens a request may carry on the plan: 256,000 on free, 1,000,000 paid; a request is held to the smaller of this and its model's own window), its usage_multiple (its monthly usage allowance as a multiple of Advanced's: Advanced is 1, null on free, which is not sold as a multiple) and plan_limits, the plan's row of the limits table in the shape GET /api/v1/limits returns for the caller's own plan (a null count is unlimited). The values are the ones the gateway enforces, read from the same tables, so a client needs no copy of them. The same for every caller; it says nothing about the caller's own plan or usage (GET /api/v1/limits does). No write, no cost. The endpoint is itself rate-limited and emits the standard `X-RateLimit-*` headers for its own bucket. ## GET /api/v1/logs: List request logs organization. List request metadata for the caller's organization, newest first — one row per request the org's API keys made, drawn from the usage ledger. **Owner or admin only** (`logs_forbidden`): this is operator surface spanning every member's keys, not a per-user view. **Metadata only** — model, token counts, latency, lifecycle status (`success`/`error`/`partial`), the originating key and workspace, request id, and timestamp. Prompt and completion content are never stored and never returned. Keyset-paginated like the admin users list: pass `?limit` (default 50, max 100) and the opaque `?cursor` from a previous response's `next_cursor`. Filter with `?key_id`, `?workspace_id`, `?model`, `?status`, and an `?from`/`?to` RFC3339 time window (from inclusive, to exclusive). A `key_id` or `workspace_id` outside the caller's org simply matches nothing. Returns `{object:"list", data:[…], next_cursor}` where `next_cursor` is null on the last page. ## GET /api/v1/logs/{request_id}: Get request log organization. Fetch metadata for a single request by its `request_id` (the `cruxy.request_id` returned on chat/embeddings/rerank responses). **Owner or admin only** (`logs_forbidden`). **Metadata only** — never prompt or completion content. A request id in another organization, or one that names nothing, returns `404 log_not_found` — a 403 would confirm the id is real. A request id may map to more than one ledger row (a reused Idempotency-Key, or an error followed by a retried success); the most recent is returned. ## GET /api/v1/me: Current identity auth. Echoes the authenticated identity resolved from the Bearer key, proving the key pipeline works end to end. ## DELETE /api/v1/me/key: Revoke the current key auth. Revokes the API key that authenticates this request, and only that key. Call it when signing out: the key stops authenticating as soon as this returns, rather than when it expires. It takes no key id, so it cannot reach any other credential, and nothing else changes: other keys of the same account stay live, and usage already recorded against this key is kept. Any kind of key may revoke itself, including the key a device or native OAuth login issued. It needs the `account` endpoint family, and a read-only key cannot use it, because revoking is a change. Once it succeeds, every later request with this key, including a repeat of this one, is `401 unauthorized`. The revoke is recorded in the organization's audit trail (`key_revoked`). ## DELETE /api/v1/memories: Forget all my memory memory. Permanently deletes every `user`-scope memory belonging to the caller and reports how many rows were removed. This is a real delete, not a flag — the rows are gone and nothing resurrects them. It is scoped to the caller: an org-mate's memory, and every other tenant's, is untouched. **Shared memory is not included.** A vault's or an organization's contents belong to the container, not to whoever typed them, so removing one is a `DELETE /api/v1/memories/{id}` gated by `can_write` on that vault or by the organization owner/admin role — or, for a departed member's writes, `POST /api/v1/memories/departed/{user_id}`. `?scope=vault` and `?scope=org` are refused with `invalid_request` for that reason, rather than returning a misleading `deleted: 0`. ## GET /api/v1/memories: List memories memory. Returns the caller's effective memory — one entry per key, with the most specific scope winning (user beats vault beats org), merged across all three scopes. **Each resolved entry carries the `id` of the row that WON** — the row whose `value` is being shown, at the scope `resolved_from` names — and it is the id `DELETE /api/v1/memories/{id}` takes, so a review-and-forget surface can remove exactly what it is displaying without re-listing each scope's raw rows to work out which one supplied the value. Deleting it lets the next-most-specific scope surface on the following read. **The `id` is an address, not a permission**: delete authority is unchanged by its presence and is exactly write authority — your own `user` rows, a `vault` row where your membership grants `can_write` and is not held, an `org` row only if you are an owner or admin. A row you may read but not write returns **404** (not 403 — an id is never confirmed to a caller not entitled to act on it), so a client rendering a forget control should take the vault leg from that vault's own `permissions.can_write` (`resolved_from.vault_id` names it) and the org leg from `permissions.can_write` on `GET /api/v1/rules`, which any member may read and which reports the same organization-role predicate this delete gates on. The org leg covers organization-wide memory when the caller is still a member of the organization; the vault leg covers every vault whose membership grants the caller `can_read` without a hold, and when two readable vaults define the same key the most recently updated wins and `resolved_from.vault_id` reports which one. A vault whose `memory_scope` is `vault_only` is isolated and does not contribute to this general view — its memory surfaces only when resolving inside that vault. Precedence is resolved server-side; clients consume the result and never recompute it. Pass `?scope=user`, `?scope=org`, or `?scope=vault&vault_id=…`, to see the raw stored rows at one scope instead. ## PUT /api/v1/memories: Remember a value memory. Stores a memory under a key, replacing any existing value for that key at the same scope. Keys are case-insensitive, so "Timezone" and "timezone" are the same memory. **Content carrying obvious PII is refused, not redacted**: if the key or value contains an email address, a phone number, or a Luhn-valid card number, the request fails with `pii_rejected` and nothing is stored — memory has no expiry, so anything accepted is kept until it is explicitly deleted. The error names the category that matched and never echoes the matched text; rephrase without it and retry. The check is server-side and unconditional — no request field disables it, and it applies identically at every scope. `user` scope is private to the caller. `vault` scope requires a `vault_id` and a vault membership granting `can_write` — a held member, a non-member, and a vault in another organization all return 404. `org` scope writes memory shared with the whole organization and requires the **owner or admin** role; an ordinary member gets `org_forbidden`. The role is read from the credential's organization membership and can never be asserted in the request. ## POST /api/v1/memories/departed/{user_id}: Settle a departed member's shared memory memory. Decides what happens to the `org`- and `vault`-scope memory written by someone who has left the organization: `keep` retains every row and moves authorship to you, `purge` deletes them. Nothing happens automatically when a member is removed — their writes are retained and frozen (they lose access with their membership) until an owner or admin makes this call, so shared knowledge is never silently destroyed and never silently inherited. **Owner or admin only** (`org_forbidden`). The subject must actually have left: a current member is refused with `org_member_active`. A user who authored nothing in your organization returns `org_member_not_found` — as does a user id belonging to another tenant, and one that does not exist, so this route cannot be used to probe for accounts elsewhere. The subject's own private `user`-scope memory is never touched; it is theirs, and it is removed with their account. ## GET /api/v1/memories/suggestions: List organization memory suggestions memory. Returns suggestions in the credential's organization, newest first, at most 200. **An owner or admin sees every member's** (the review queue); **any other member sees only their own**. Pass `?status=pending` (or `approved`, `rejected`) to narrow the list. An approved suggestion names the organization memory it became in `memory_id`. ## POST /api/v1/memories/suggestions: Suggest an organization memory memory. Proposes a memory for the whole organization. **Any member may suggest; only an owner or admin can turn a suggestion into organization memory** (`POST /api/v1/memories/suggestions/{id}/approve`). A suggestion is not memory: it is never resolved, recalled or added to any turn until it is approved. Suggesting a key you already have pending replaces that pending value rather than adding a second one. The same checks as `PUT /api/v1/memories` apply: keys are case-insensitive and bounded, an empty value is refused, and **content carrying obvious PII is refused with `pii_rejected`**, naming the category and never echoing the text. The organization is the one the credential names. ## POST /api/v1/memories/suggestions/{id}/approve: Approve a memory suggestion memory. Turns a pending suggestion into organization memory, under its key, replacing any organization memory already stored for that key, exactly as `PUT /api/v1/memories` with `scope: org` would and with the same audit record, attributed to you. The write and the decision happen together: either both are stored or neither is. **Owner or admin only** (`org_forbidden` otherwise, decided before the id is looked at). A suggestion that is already decided, belongs to another organization, or does not exist is one answer: `memory_suggestion_not_found`. The response names the memory it wrote in `memory_id`. ## POST /api/v1/memories/suggestions/{id}/reject: Reject a memory suggestion memory. Declines a pending suggestion. Nothing is written to memory; the suggestion is kept as rejected, with who decided and when, and its author may suggest the key again. **Owner or admin only** (`org_forbidden` otherwise, decided before the id is looked at). A suggestion that is already decided, belongs to another organization, or does not exist is `memory_suggestion_not_found`. ## DELETE /api/v1/memories/{id}: Forget a memory memory. Deletes one memory by id. A caller may delete exactly what they may write: their own `user`-scope memories, `vault`-scope memories in a vault where their membership grants `can_write` and is not held, and `org`-scope memories if they are an organization owner or admin. Anything else — another tenant's id, another user's private memory, a vault they can only read, organization memory when they are an ordinary member — returns 404, identically to an id that does not exist: a 403 would confirm the id is real. ## GET /api/v1/models: List model tiers models. Returns the public tier catalog (OpenAI-discovery shape) so clients can discover tiers instead of hardcoding them. Never exposes upstream provider model ids. Each tier carries its public id (id: canto, saga, epos), its display name (label: Canto, Saga, Epos) and a one-word profile beside it (canto Deep, saga Balanced, epos Fast), all stable once shipped. A request pinned to a Cruxy-Version before 2026-10-18 is listed the deprecated ids and labels it was built against instead (kavi Kavi, vaani Vaani, mira Mira); those ids are still accepted wherever a model is named on input, as aliases of canto, saga and epos. Each tier's reasoning object gives the reasoning_effort a chat request on that tier gets when it omits one (default_effort) and whether low, medium and high are different depths there (graded; false means on/off, so low thinks as long as high). It is read from the configuration the chat endpoints apply, so it is the live default rather than a description of one. supports_structured_output says whether the tier honours response_format json_object and json_schema; it too is read from the configuration chat gates on, a structured request naming a tier where it is false is 422 structured_output_unsupported, and model auto routes a structured request only to a tier where it is true. cruxy.reasoning_summaries says whether this deployment sends thought lines (cruxy.reasoning_summary on POST /api/v1/chat, the reasoning_summary event on POST /api/v2/chat) at all: false means no turn gets them; true means a turn gets them when it is also a stream from a signed-in credential that pins Cruxy-Version 2026-11-13 or later, and never from a developer or headless key. It is read from the same switch the chat handler applies. GET /v1/models, the plain OpenAI listing, does not carry it. ## POST /api/v1/moderations: Classify content (moderations) moderations. OpenAI-compatible moderations. model must be "cruxy-guard". input accepts a single string or an array of strings — at most 512 strings per request (more is 400 invalid_request), with the whole body ≤ 64 KiB (more is 413 payload_too_large). NOTE: the guard model emits labels, not probabilities, so category_scores is binary (1.0/0.0), not calibrated. The response envelope mirrors OpenAI's moderations schema ({id, model, results}) and carries no top-level cruxy.* block: the per-call request_id rides the top-level id instead, formatted "modr-" — the same per-call id chat returns as cruxy.request_id. A FLAGGED result additionally carries an additive, OpenAI-inert cruxy block of its own — results[].cruxy.hazard_codes, the raw guard taxonomy codes (S-codes) behind the flag. It is present if and only if flagged is true, so an unflagged result is byte-identical to one from a gateway without the field, and absence must be read as "not flagged", never as "no codes". When present it is never null and may be EMPTY, meaning the guard flagged the input without naming a code. Five codes (S6 specialized advice, S7 privacy, S8 intellectual property, S13 elections, S14 code interpreter abuse) map to no OpenAI category, so a flagged result with every category false is explained by the codes rather than being indistinguishable from a bug. The OpenAI-shaped fields — flagged, categories, category_scores — are unchanged. ## GET /api/v1/org/invitations: List the organization's invitations organization. Lists the invitations the caller's organization has sent — live and settled — with each one's address, role and status. **Owner or admin only** (`org_forbidden`): this is management surface, the same authority that sends them. No invitee user id is reported, for any invitation, whether or not the address names an existing account. ## DELETE /api/v1/org/invitations/{invitation_id}: Revoke an invitation organization. Withdraws an invitation the caller's organization sent, before it is accepted. **Owner or admin only** (`org_forbidden`), resolved before existence — a caller who does not administer the organization is refused whether or not the id is real. An invitation in another organization, one that never existed, one already accepted, declined or revoked, and a malformed id are one `404 invitation_not_found`. ## GET /api/v1/org/members: List organization members organization. Lists the members of the caller's organization — the one their credential names; there is no way to address any other — with each member's role. **Owner or admin only** (`org_forbidden`): this is management surface, and an ordinary member is not entitled to enumerate the roster. ## POST /api/v1/org/members: Invite someone to the organization organization. Invites someone to the caller's organization, addressed by `email` or by `user_id` (exactly one). `role` defaults to `member` and may not be `owner` — ownership is granted with PATCH after the invitee joins. **Owner or admin only** (`org_forbidden`). This creates an INVITATION, not a membership: nobody joins an organization without accepting, and the membership row appears only when they call `POST /api/v1/invitations/{id}/accept`. The `202` response is deliberately identical whether or not the address names an existing account — the gateway never looks it up, so this endpoint cannot be used to discover whether someone has an account. Re-inviting an address that already has a live invitation returns that same invitation unchanged; one whose invitation has lapsed issues a fresh 14-day window. The only distinguishable outcome is `409 org_member_exists`, which tells the caller only what `GET /api/v1/org/members` already shows them about their own organization. ## DELETE /api/v1/org/members/{user_id}: Remove an organization member organization. Removes a member from the caller's organization. **Owner or admin only** (`org_forbidden`); a member whose role is `owner` cannot be removed by anyone. Removal ends access, it destroys nothing: the member's API keys bound to this organization are revoked in the same transaction, and their `org`- and `vault`-scope memory is retained and frozen — reachable by `POST /api/v1/memories/departed/{user_id}`, where an owner or admin decides `keep` or `purge`. Nothing is deleted or reassigned by the removal itself. A user id in another organization, or one that names nobody, returns `404 org_member_not_found`. ## PATCH /api/v1/org/members/{user_id}: Change an organization member's role organization. Changes a member's role. **Owner or admin only** (`org_forbidden`); granting `owner` additionally requires the caller to BE an owner, and the membership it creates is immediately immutable. A member whose role is `owner` cannot be changed by anyone — the org must always retain an owner, so ownership is never demotable. A user id in another organization, or one that names nobody, returns `404 org_member_not_found`. ## GET /api/v1/org/memberships: List the organizations I belong to organization. Lists the organizations the caller is a member of, with their role in each. It takes no organization and no user: the caller is the subject, so there is no parameter by which one person could read another's memberships. This is the list to show when credential issuance answers `org_selection_required`, and the list to read before leaving an organization with `DELETE /api/v1/org/memberships/{org_id}`. ## DELETE /api/v1/org/memberships/{org_id}: Leave an organization organization. Removes the CALLER'S OWN membership from the named organization. Any member may leave; no administrator's permission is involved, which is what makes an unwanted membership recoverable. The organization is named in the path rather than taken from the credential — the only route here that does — because leaving is by definition about an organization your current credential may not name. It can reach no membership but your own. Leaving revokes the caller's API keys bound to that organization, in the same transaction, exactly as removal by an administrator does. It destroys nothing else: memory the caller wrote at organization and vault scope is retained and frozen, for `POST /api/v1/memories/departed/{user_id}` to settle. An **owner** cannot leave (`org_forbidden`): owner rows are immutable so an organization always retains one, and this includes the personal organization every account owns. An organization the caller does not belong to, one that does not exist, and a malformed id are one `404 org_member_not_found`. ## GET /api/v1/org/plan: Read the organization's seat plan organization. Returns what the caller's organization bought and how much of it is assigned: the plan's status, how it is billed, the paid period, and for each seat type how many seats were bought and how many are assigned. `viewer_seat` is the caller's own seat, or null when they hold none. **Any member** may read it; it never says who holds the other seats. The organization is the one the credential names. An organization with no plan answers `org_plan_not_found`, and so does every organization while Business seats are switched off on this deployment. The gateway stores the paid period, not whether it is monthly or annual. ## GET /api/v1/org/seats: List the organization's seats organization. Lists who holds a seat of the caller's organization's plan. **An owner or admin sees every seat. Any other member sees only their own**, as a list of one, or an empty list when they hold none; the request is never refused for lacking a role. `member_cap_units` is a lower monthly ceiling an owner or admin set for that member, or null. An organization with no plan answers `org_plan_not_found`, and so does every organization while Business seats are switched off on this deployment. ## DELETE /api/v1/org/seats/{user_id}: Release a member's seat organization. Takes a member's seat away. **Owner or admin only** (`org_forbidden`). It takes effect at once: the member stays in the organization and keeps reading it, and their next model call there is refused `seat_required` until a seat is assigned again. Nothing is refunded and the seat is free to assign to someone else. A member who holds no seat is `org_seat_not_found`; a user id that is not a member of this organization is `org_member_not_found`. It works while the plan is past due or ended. While Business seats are switched off on this deployment it answers `org_plan_not_found`. ## PUT /api/v1/org/seats/{user_id}: Assign a seat to a member organization. Gives a member of the caller's organization a seat of the plan. **Owner or admin only** (`org_forbidden`). The seat is usable at once. It is idempotent: assigning the type the member already holds changes nothing and returns their seat. Assigning the other type changes the seat's type. Refused `no_seat_available` when every seat bought of that type is assigned, `org_plan_inactive` when the plan is past due or ended, and `org_plan_not_found` when the organization has no plan or Business seats are switched off on this deployment. A user id that is not a member of this organization, including one from another organization, is `org_member_not_found`. ## GET /api/v1/profile: Get my profile profile. Returns the authenticated user's account profile: their id, email, `work_type`, whether they have `completed_onboarding`, UTC created/updated timestamps, and the `org` this credential is bound to. `work_type` is `null` until the user answers; otherwise it is one of the closed vocabulary (`engineering`, `data_science`, `product`, `design`, `marketing`, `sales`, `finance`, `operations`, `people_hr`, `legal`, `student`, `other`). The profile is always the caller's own — it is addressed by the credential's subject, never by an id in the path or body — so there is no id to enumerate and no other user's profile this route can return. **`org` is the organization THIS CREDENTIAL is bound to**, with your role in it — not "your organization". A user may belong to several (`GET /api/v1/org/memberships` lists them all); a key names exactly one, stamped at issuance, and it is the one whose shared memory, rules and conversations this credential sees. ## PATCH /api/v1/profile: Update my profile profile. Updates the authenticated user's profile and returns the stored row, in the same shape `GET /api/v1/profile` returns — including the `org` this credential is bound to, which no field here can change. Accepts ONLY `work_type` and `completed_onboarding`, both optional: an **absent** field is left unchanged (it is not reset to a default), so a client can complete onboarding without touching `work_type` and vice versa. `work_type`, when present, must be one of the closed vocabulary (`engineering`, `data_science`, `product`, `design`, `marketing`, `sales`, `finance`, `operations`, `people_hr`, `legal`, `student`, `other`); any other value is `400 invalid_request` and **nothing is written**. An `id` or `email` in the body is ignored — the profile is addressed by the credential's subject, so the write can neither be retargeted to another user nor change identity. ## GET /api/v1/prompts: List prompts prompts. Lists the prompts in the caller's workspace — the one their credential names; there is no way to address any other — each with its slug, latest version number, and total version count (no content). Ordered oldest first. ## POST /api/v1/prompts: Create a prompt prompts. Creates a prompt in the caller's workspace — a named container whose first immutable version holds the given `content`. The workspace is the one the credential names; there is no workspace or org id in the path or body. `name` is required (1..128 bytes). `slug` is the stable, URL-safe handle used to address the prompt and is optional: when omitted it is derived from the name (lowercased, non-alphanumerics collapsed to hyphens); supply it explicitly if the name has no usable characters. A slug already used in the workspace is `409 prompt_slug_exists`. `content` is required (1..102400 bytes) and is stored at rest and returned verbatim — it is deliberately-authored template text and is not PII-filtered. Returns the prompt with its version 1 embedded. ## DELETE /api/v1/prompts/{id}: Delete a prompt prompts. Deletes a prompt and all of its versions (the versions cascade). A prompt id in another workspace or organization, or one that names nothing, returns `404 prompt_not_found`. ## GET /api/v1/prompts/{id}: Get a prompt prompts. Returns one prompt of the caller's workspace with a single version embedded: the latest by default, or the exact version named by `?version=N`. A prompt id in another workspace or organization, or one that names nothing, returns `404 prompt_not_found`. A `?version=N` that the prompt does not have returns `404 prompt_version_not_found` (distinct, because the caller can already see the prompt). ## GET /api/v1/prompts/{id}/versions: List prompt versions prompts. Lists every version of a prompt, newest first, each with its number, content, author, and timestamp. A prompt id in another workspace or organization, or one that names nothing, returns `404 prompt_not_found`. ## POST /api/v1/prompts/{id}/versions: Add a prompt version prompts. Appends a new immutable version to a prompt and returns it. The new version's number is the previous highest plus one; existing versions are never modified. `content` is required (1..102400 bytes). A prompt id in another workspace or organization, or one that names nothing, returns `404 prompt_not_found`. ## POST /api/v1/rerank: Rerank documents rerank. Cohere-style reranking (OpenAI-INCOMPATIBLE). model must be "cruxy-rerank". Scores each document in documents against query and returns them ranked by relevance_score (descending), optionally capped to top_n. At most 512 documents per request (more is 400 invalid_request), with the whole body ≤ 64 KiB (more is 413 payload_too_large) — pre-filter a larger candidate set before reranking. The additive cruxy.* block carries the request id and cost. ## DELETE /api/v1/rules: Delete organization or vault rules rules. Removes a ruleset entirely. **The `vault_id` query parameter selects the scope**: omit it to delete the organization's ruleset, or pass a vault id to delete that vault's - equivalent to `DELETE /api/v1/vaults/{id}/rules`. A `vault_id` that is malformed, names nothing, or belongs to another organization is `404 vault_not_found`; the deletion is never quietly applied to the organization's ruleset instead. **Owner or admin of the organization only**, at either scope; vault `can_write` does not grant it. The refusal is `rules_forbidden`. Idempotent: deleting a ruleset that does not exist succeeds, because the end state asked for already holds. Deleting the organization's ruleset leaves every vault's own rules untouched, as it does each vault's inheritance switch; deleting a vault's leaves the organization's untouched and does **not** reset that vault's `inherit_org_rules`. Afterwards the deleted scope contributes no rules to any chat - empty means empty, and no default ruleset takes its place. ## GET /api/v1/rules: Get organization or vault rules rules. Returns a stored ruleset - the ordered standing instructions the gateway prepends to turns in scope. **The `vault_id` query parameter selects the scope**: omit it for the organization's ruleset, or pass a vault id for that vault's own ruleset and its `inherit_org_rules` switch (equivalent to `GET /api/v1/vaults/{id}/rules`). This returns one stored ruleset, NOT the effective merge - for what actually applies to a chat, use `GET /api/v1/rules/resolved`. **Any member may read the organization's**: these instructions are added to the caller's own requests, so they are entitled to see them. A vault's is readable by a vault member granted `can_read` (and not held) and by any owner or admin of the organization; any other `vault_id`, including a malformed one and another tenant's, is `404 vault_not_found`. A scope that has never had rules written and one whose rules were deleted are the same answer, an empty `rules` array - there is no implicit default ruleset. The organization is always the one the credential names; there is no way to address another. **`permissions.can_write` says whether YOU may change this ruleset** - render the edit control from it instead of discovering the answer by attempting a write. It is resolved from the same authority that gates `PUT` and `DELETE` on the scope you selected: owner or admin of the organization, at either scope (vault `can_write` gates a vault's memory, not its rules), so `false` means those requests will be refused with `rules_forbidden` and `true` means they will be admitted. It is per-caller: two members of one organization legitimately see different values for the same ruleset. ## PUT /api/v1/rules: Replace organization or vault rules rules. Replaces a ruleset with the ordered list supplied. **The `vault_id` query parameter selects the scope**: omit it to replace the organization's ruleset, or pass a vault id to replace that vault's - the same scope selector `GET /api/v1/rules/resolved` takes, and the vault form is equivalent to `PUT /api/v1/vaults/{id}/rules`. A `vault_id` that is malformed, names nothing, or belongs to another organization is `404 vault_not_found`; a write is never quietly redirected to the organization's ruleset. **Authority depends on the scope selected.** Both are **owner or admin of the organization only**: the organization's ruleset is prepended to every colleague's every turn, and a vault's to every turn in that vault. Vault `can_write` gates the vault's memory, not its rules. The refusal is `rules_forbidden`, and for a vault the authority is resolved before the vault id is examined, so an unauthorized caller's denial never discloses whether the vault exists. This is a whole-set replace, not a merge: the array sent becomes the ruleset exactly, and sending `[]` clears it. `inherit_org_rules` may be sent only with a `vault_id`, and with one, `rules`, `inherit_org_rules`, or both may be sent; the two are applied in a single transaction. Each rule is one instruction; rules are trimmed of surrounding whitespace and an empty one is rejected. Three size caps apply and are enforced by the database, because rules are re-injected on every request in scope and so cost context and tokens on every call: at most 50 rules, at most 1000 characters per rule, and at most 8000 characters in total. Exceeding any of them is `400 rules_too_large`, naming which cap. **Content carrying obvious PII is refused, not redacted**: a rule containing an email address, a phone number, or a Luhn-valid card number fails with `pii_rejected` and nothing is stored - rules have no expiry and are transmitted on every request in scope. The error names the category and the rule's position, and never echoes the matched text. ## GET /api/v1/rules/resolved: Resolve the effective ruleset rules. Returns the rules that actually apply to a chat context, already merged - the single server-side answer, in a shape a client renders read-only. Pass `vault_id` for a chat inside a vault; omit it for a chat with none. The merge: with no vault, the organization's rules apply. Inside a vault that inherits (the default), the organization's rules apply first and then the vault's own. Inside a vault that does not inherit, only the vault's own rules apply. Every rule carries the `source` it came from (`org` or `vault`) so an unexpected instruction is traceable to the ruleset that contributed it. **Empty means empty** - every branch can legitimately return zero rules, and zero rules is a real answer, not a missing one; there is no implicit or default ruleset anywhere. Any member may call this. A `vault_id` the caller cannot read is `404 vault_not_found` and never a silent fallback to the organization's rules, so a mistyped id is reported rather than answered for the wrong context. ## GET /api/v1/service-token/self: Describe the calling service token auth. Returns the authority of the service token making the request — its service name, the endpoint families it may call, whether it is read-only, and when it expires. It describes ONLY the presented credential: the endpoint accepts no parameters, so there is no way to ask about another token, and it reveals nothing about any other token, user or organization. Intended as a preflight for long-running operator scripts that must not straddle their own credential's expiry. `allowed_scopes` is always the effective list and is never empty — a token issued without `--scopes` holds every family and lists them all. `expires_at` is null for a token that never expires, and is never in the past (an expired token cannot authenticate). To compute remaining lifetime without trusting the client clock, subtract the response's `Date` header from `expires_at`. ## POST /api/v1/tokens/count: Count input tokens tokens. **AVAILABILITY: on today's tiers this endpoint answers 503 count_unavailable for every model.** A count is produced only for a tier whose base model has a tokenizer vendored in the gateway, and none of the current lineup (DeepSeek V4 behind canto, saga and epos) has one; the endpoint fails closed rather than estimate, because an estimate could disagree with billing. Until that changes, read the input tokens a request was billed for from the chat response's usage.input_tokens. Returns the number of input tokens POST /api/v1/chat would bill for the same model, messages, and tools, computed locally with no upstream inference call, so this endpoint is not billed and records no usage. model is a tier only (canto, saga, or epos, or the deprecated aliases kavi, vaani and mira, counted as the same tier); "auto" and any base-model id are rejected. The response's model names the tier by its public id from Cruxy-Version 2026-10-18; a request pinned to an earlier date is echoed the old id. messages use the same shape as /chat, and `tools` (the same shape /chat accepts) IS counted: a tool harness is real billed input, so omitting it from the body returns a count for a request you are not making. `tool_choice` does not affect the count and is not read. The count includes the server-injected per-tier system prompt and the tier's chat-template scaffolding, including the generation prompt's reasoning block, which follows the tier's DEFAULT reasoning mode (what /chat sends when the client does not override reasoning_effort), so it matches /chat's usage.input_tokens (prompt_tokens) for the same input. It is EXACT for single-turn and user-only prompts on every tier, and for all shapes on saga and epos. It is a conservative UPPER bound, never an undercount, in two cases where the tier's template renders the prompt more compactly upstream than can be reproduced offline: a canto conversation with prior assistant turns (up to ~6 tokens per prior turn), and message content with leading or trailing whitespace on saga or epos (up to ~3 tokens per such message). A /chat request that overrides reasoning_effort shifts prompt_tokens by 1–2 tokens (the reasoning-block delta), which this parameter-free count does not model. Authenticated and rate-limited per API key (its own bucket), emitting the same X-RateLimit-* and Cruxy-Version headers as the other endpoints. Idempotency-Key is not honored (the endpoint is a pure function with no side effects). Counting is REFUSED, with 400 input_not_countable and no count in the body, for text carrying a single unbroken run of more than 1024 bytes (a run of letters, whitespace or punctuation with no word, digit or punctuation boundary in it) or for more than 262144 bytes of text in one request: tokenizing is quadratic in the length of one such run, and returning a partial count would be the undercount this endpoint promises never to return. Ordinary prose, source code, JSON and CJK text are far inside both bounds. ## GET /api/v1/vaults: List vaults memory. Lists the vaults the caller can use — those where they hold a membership that is not held. Each entry reports the caller's own permissions — including `can_administer`, the structural authority to delete the vault or hold its members, which is resolved from the same predicate as on GET /api/v1/vaults/{id} and cannot disagree with it — and whether the caller has pinned it. Organization admins are not listed into vaults they are not members of: administering an organization does not grant access to its teams' shared memory. Two optional filters, both resolved server-side: `scope` (all | owned | shared — owned means the caller owns it, shared means they participate but do not own it) and `archived` (false, the default, lists only live vaults; true lists only archived ones). With no parameters the listing is all non-archived vaults. ## POST /api/v1/vaults: Create a vault memory. Creates a shared-memory vault inside the caller's organization. The caller becomes the owner and is added as a member with read, write, and share; the returned `permissions` therefore reports all three, and `can_administer` true, since the owner may delete the vault and hold its members. Vault names are unique within an organization. Optional `description`, `icon`, `color`, and `memory_scope` may be set; an invalid icon, color, or memory_scope is rejected with 400 invalid_request. `memory_scope` is enforced in memory resolution: `vault_only` isolates the vault's memory both ways — its rows are withheld when resolving outside it, and a chat inside it resolves only that vault's memory (organization and user scope excluded). `default` participates in the normal organization > vault > user merge. The create is IDEMPOTENT when the request carries `external_id`, your own system's identifier for the vault: a second create naming an `external_id` this organization has already seen returns the existing vault with **200** and `created: false`, and writes nothing — not the name, so a create is never a rename. A first create answers **201** with `created: true`. Send it whenever a retry is possible: a duplicate NAME is refused with 409 vault_name_exists, which carries no vault id, so a client whose request timed out cannot learn which vault it made — and if the vault has been renamed since, the retry does not collide at all and creates a second one holding a slice of the same team's memory. Reusing an `external_id` that names a vault somebody else owns is 409 vault_external_id_conflict. ## DELETE /api/v1/vaults/{id}: Delete a vault memory. Deletes a vault, its membership list, and all memory stored in it. Owner or organization admin only; a member — even one with write and share — gets 403 vault_forbidden. This is exactly what `permissions.can_administer` reports on the vault reads: the field and this gate are the same predicate, so a caller that saw `can_administer: false` will be refused here, and one that saw true will not be refused for want of authority. ## GET /api/v1/vaults/{id}: Get a vault memory. Returns one vault and the caller's own permissions in it. `permissions` carries `can_read`, `can_write` and `can_share` — the caller's grants over the vault's CONTENT — plus `can_administer`, which is structural authority over the CONTAINER: whether they may delete this vault and hold or restore its members. The four do not imply one another: a member with all three grants does not administer the vault, and an organization admin administers it while possibly holding no grants at all. Every one is resolved from the same predicate that gates the corresponding request, so a client may gate its controls on this block and on nothing else. A vault in another organization, a vault the caller is not a member of, and a vault where the caller is held all return 404 — a 403 would confirm the id is real. ## PATCH /api/v1/vaults/{id}: Update a vault's metadata memory. Changes a vault's `name`, `description`, `icon`, `color`, and/or `memory_scope`. Every field is optional but at least one must be present; an omitted field is left unchanged, while an explicit `null` clears a nullable presentation field (`description`, `icon`, `color`). `name` and `memory_scope` are non-null and can only be set to a value. The same closed sets as create apply — `icon` and `color` from their fixed vocabularies, `memory_scope` in `default | vault_only`, `name` 1..128 bytes, `description` at most 2000 — and an invalid value is 400 invalid_request with nothing written. Renaming to a name already taken in the organization is 409 vault_name_exists. Requires `can_write`: a participant without it gets 403 vault_forbidden, and a non-member, held, or cross-organization caller gets 404 vault_not_found. Returns the enriched vault shape, with `updated_at` advanced and the caller's own `permissions` — including `can_administer` — re-resolved. ## DELETE /api/v1/vaults/{id}/archive: Restore a vault memory. Clears a vault's archive, returning it to the default list and reporting `archived: false`. Idempotent: restoring a live vault is 204. Requires `can_write`: a participant without it gets 403 vault_forbidden, and a non-member, held, or cross-organization caller gets 404 vault_not_found. ## PUT /api/v1/vaults/{id}/archive: Archive a vault memory. Archives the vault: it is hidden from the default vault list and appears only with `?archived=true`, and GET reports `archived: true`. The container and all its memory are untouched — archiving is not deletion. Idempotent: archiving an archived vault is 204 and does not move the original archive instant. Requires `can_write`: a participant without it gets 403 vault_forbidden, and a non-member, held, or cross-organization caller gets 404 vault_not_found. ## GET /api/v1/vaults/{id}/files: List a vault's files files. The files the vault holds, newest first, in the same keyset pages as GET /api/v1/files (?limit, default 20, at most 100; ?cursor from next_cursor) with total, how many the listing pages through. Each carries vault_id, uploaded_by (the uploader's user id, kept after they leave), retention_until (deleted then unless used again; 365 days from its last use) and shared_with (how many members can read the vault). Requires can_read: a non-member, a held member, an organization admin who is not a member, a member without can_read, and another organization's caller all get 404 vault_not_found. ## POST /api/v1/vaults/{id}/files: Upload a file into a vault files. Uploads a file the vault holds, for every member who can read the vault. It is the same multipart upload as POST /api/v1/files (a "file" part and an optional "purpose"), with the same detection, document reading, size cap, monthly allowance and storage pool, and the response carries the same fields plus vault_id, uploaded_by (you), retention_until and shared_with. Requires can_write on the vault: a participant without it gets 403 vault_forbidden; a non-member, a held member, an organization admin who is not a member, and another organization's caller get 404 vault_not_found. WHOSE POOL: the bytes count against YOUR storage pool in this organization (the seat's pool when the organization's plan assigns you one), and keep counting after you leave the vault or the organization, until the file is deleted or reaped. RETENTION: a vault file is kept 365 days from its last use. Uploading, sharing and downloading it each restart the 365 days, and retention_until says when it will be deleted unless it is used again. It cannot take expires_in, or the purpose chat_attachment; either is 400 invalid_request with nothing stored. Vault files are not scanned for personal data: what you put here is readable by every member who can read the vault (shared_with counts them). A vault file never appears in GET /api/v1/files and cannot be read by id through the personal Files API or chat's file_ids: it is the vault's, not yours. ## POST /api/v1/vaults/{id}/files/share: Share one of your files into a vault files. Copies one of your own files (file_id, in the organization the credential names) into the vault, as a new vault file with its own id. The copy has the original's name, bytes, content type and read document text; the original is unchanged and stays yours, and deleting either one never touches the other. Sharing is recorded in the file audit trail with you as the actor. The copy counts against your storage pool in this organization like an upload (413 storage_quota_exceeded if it does not fit) but spends no monthly upload allowance. Its retention starts now: 365 days from its last use. A purpose of chat_attachment on the original becomes general on the copy. Requires can_write on the vault (403 vault_forbidden for a participant without it; 404 vault_not_found for a non-member, a held member, a non-member organization admin, or another organization). A file_id that is not one of your live files in this organization, or is malformed, is 404 file_not_found. ## DELETE /api/v1/vaults/{id}/files/{file_id}: Delete a vault file files. Deletes a file the vault holds, for every member, and its content. Any member with can_write may delete any file in the vault, not only their own; the file audit trail records who did. Requires can_write (403 vault_forbidden for a participant without it; 404 vault_not_found for a non-member, a held member, a non-member organization admin or another organization). A file id that is not this vault's live file is 404 file_not_found, so a repeat delete is 404. A copy shared from someone's own file is deleted alone: their original is untouched. ## GET /api/v1/vaults/{id}/files/{file_id}: Get a vault file's metadata files. One file the vault holds. Requires can_read on the vault (404 vault_not_found otherwise, as for the listing). A file id that is not this vault's live file, or is malformed, is 404 file_not_found. Reading metadata is not a use: it does not restart retention. ## GET /api/v1/vaults/{id}/files/{file_id}/content: Download a vault file's content files. Streams the raw bytes of a file the vault holds, always as application/octet-stream with Content-Disposition: attachment and X-Content-Type-Options: nosniff. A download is a use: it restarts the file's 365 days of retention. Requires can_read on the vault (404 vault_not_found otherwise); a file id that is not this vault's live file is 404 file_not_found. ## GET /api/v1/vaults/{id}/members: List vault members memory. Lists the vault's members and each one's permissions, including any held members with their suspended permissions intact — the point of a reversible hold is that what it suspends stays visible to whoever may lift it. ## POST /api/v1/vaults/{id}/members: Add a vault member memory. Adds a member of the caller's organization to the vault with the given permissions. The vault owner and organization admins may grant anything; a member with `can_share` may grant only permissions they themselves hold — a member who cannot write cannot create a member who can. Permissions default to false, so omitting one grants nothing. A user id outside the caller's organization returns 404 user_not_found. ## DELETE /api/v1/vaults/{id}/members/{user_id}: Remove a vault member memory. Removes a member from the vault. Their access ends immediately — the next request reads the vault as if it did not exist. Owner, organization admin, or a member with `can_share`. The vault owner cannot be removed; delete the vault instead. ## PATCH /api/v1/vaults/{id}/members/{user_id}: Update a vault member's permissions memory. Changes a member's read/write/share permissions. Omitted fields keep their current value. The no-escalation rule is applied to the RESULTING permission set, not just the changed fields: a member with `can_share` but not `can_write` cannot edit a row that grants write, even if they are not the one who granted it. `held` is not accepted here — it is a separate authority with its own route. The vault owner's own membership cannot be modified by anyone. ## PUT /api/v1/vaults/{id}/members/{user_id}/held: Suspend or restore a vault member memory. Sets or clears a member's hold. While held, that member's read, write, and share are all inert regardless of their flags, and the vault reads to them as if it did not exist. The flags themselves are untouched, so clearing the hold restores exactly the permissions they had. Owner or organization admin only — suspending is the revocation of someone else's grant, not a grant, so `can_share` does not confer it. The owner cannot be held. This authority is reported as `permissions.can_administer` on the vault reads, from the same predicate that gates this route. ## DELETE /api/v1/vaults/{id}/pin: Unpin a vault memory. Removes the CALLING user's pin on the vault. Idempotent: unpinning a vault that was not pinned is 204. Requires only that the caller can read the vault; one they cannot read is 404 vault_not_found. Never affects another member's pin. ## PUT /api/v1/vaults/{id}/pin: Pin a vault memory. Pins the vault for the CALLING user — a personal bookmark that surfaces on the `pinned` field of GET and the vault list, and never visible to other members. Idempotent: pinning an already-pinned vault is 204, not a conflict. Requires only that the caller can read the vault (a bookmark is not an edit); a vault the caller cannot read — non-member, held, no `can_read`, or another organization — is 404 vault_not_found. ## DELETE /api/v1/vaults/{id}/rules: Delete a vault's rules rules. Removes a vault's own ruleset. **Requires owner or admin of the organization** (`rules_forbidden` otherwise), resolved before the vault id is examined. Vault `can_write` does not grant it. Idempotent: deleting a ruleset that does not exist succeeds. The vault's `inherit_org_rules` switch is deliberately **not** reset - clearing the rules a vault adds and changing whether it inherits the organization's are different intentions, and doing the second while asked for the first would silently start or stop applying the organization's rules to that vault. ## GET /api/v1/vaults/{id}/rules: Get a vault's rules rules. Returns a vault's own ruleset and its `inherit_org_rules` switch. Readable by any member of the vault granted `can_read` (and not held), and by any owner or admin of the organization (who may set it, and so can always read back what they set). A vault in another organization, one that does not exist, one the caller does not participate in, and one where the caller is held all return the same `404 vault_not_found`. `inherit_org_rules` is a property of the vault and is returned whether or not the vault has any rules of its own. **`permissions.can_write` says whether YOU may change this vault's rules** - render the edit control from it rather than inferring write access from a failed write. It is `true` for an owner or admin of the organization and `false` for everyone else; vault `can_write` gates the vault's memory, not its rules. It is resolved from the same predicate the `PUT` and `DELETE` use, so it cannot disagree with them. It is per-caller. ## PUT /api/v1/vaults/{id}/rules: Set a vault's rules and inheritance rules. Sets a vault's own ruleset and/or its `inherit_org_rules` switch. **Requires owner or admin of the organization** (`rules_forbidden` otherwise), for both halves of this request: a vault's rules and its inheritance switch. Vault `can_write` gates the vault's memory and does not grant it. Authority is resolved before the vault id is examined, so an unauthorized caller's denial never reveals whether the vault exists. Both fields are optional but at least one must be present, and **both are applied in a single transaction** - turning inheritance off and installing the vault's replacement rules is one change, and splitting it across two requests would leave a window in which chats in the vault run with no rules at all. `inherit_org_rules` true (the default for every vault) means the organization's rules apply **in addition to** this vault's, organization rules first; false narrows chats in this vault to its own rules, which may be none. It never makes the vault's own rules inert. The same caps and the same PII gate as the organization ruleset apply. ## GET /api/v1/workspaces: List workspaces organization. Lists the workspaces of the caller's organization — the one their credential names; there is no way to address any other — each with its slug, monthly spend cap (null when uncapped), and whether it is the reserved default. The default workspace is listed first. **Owner or admin only** (`workspace_forbidden`): this is management surface, not a directory. WHICH WORKSPACE A CREDENTIAL NAMES is fixed when the key is issued and is never read from a request: a key the Cruxy Console issues names the workspace it was issued into (the organization's default unless the Console chose another of that organization's workspaces), and a signed-in credential from device or OAuth login always names the organization's default. Rotating a key keeps its workspace; nothing moves a key to another one. Prompts, eval suites and their runs live in the workspace the credential names, and spend is counted against it. ## POST /api/v1/workspaces: Create a workspace organization. Creates a workspace inside the caller's organization — a team's isolated environment and spend budget under that org. **Owner or admin only** (`workspace_forbidden`). `name` is required (1..128 bytes). `slug` is the stable, URL-safe handle used to address the workspace and is optional: when omitted it is derived from the name (lowercased, non-alphanumerics collapsed to hyphens); supply it explicitly if the name has no usable characters. A slug already used in the organization is `409 workspace_slug_exists`, and the reserved `default` slug cannot be minted (`400 invalid_request`). `spend_cap_micros` is an optional monthly ceiling in micro-USD (positive; omit or null for uncapped) enforced by the chat/usage gates against the workspace's summed cost. ## DELETE /api/v1/workspaces/{id}: Delete a workspace organization. Deletes a workspace. **Owner or admin only** (`workspace_forbidden`). A workspace that holds — or has ever held — a credential is refused with `409 workspace_not_empty`: a credential's tenancy and its usage history must never be orphaned, so a workspace is deletable only while it never held a key. The reserved default workspace is never deletable (`409 workspace_is_default`). A workspace id in another organization, or one that names nothing, returns `404 workspace_not_found`. ## GET /api/v1/workspaces/{id}: Get a workspace organization. Returns one workspace of the caller's organization. **Owner or admin only** (`workspace_forbidden`). A workspace id in another organization, or one that names nothing, returns `404 workspace_not_found` — a 403 would confirm the id is real. ## PATCH /api/v1/workspaces/{id}: Rename or re-cap a workspace organization. Changes a workspace's `name` and/or its `spend_cap_micros`. Every field is optional but at least one must be present; an omitted field is left unchanged, an explicit `null` cap clears the cap (uncaps), and a positive cap sets it. The `slug` is a stable handle and is NOT changed here. Applies to any workspace including the default (only delete singles the default out). **Owner or admin only** (`workspace_forbidden`). A workspace id in another organization, or one that names nothing, returns `404 workspace_not_found`. Returns the updated workspace. ## POST /api/v2/chat: Chat completions (native v2) chat. Cruxy-native chat completions. model is a public tier - canto (Deep), saga (Balanced) or epos (Fast) - or auto to let the server-side router pick the tier from the request (accepted natively; no client-side shim). kavi, vaani and mira are deprecated aliases of canto, saga and epos: still accepted on input on every API version and served as the same tier. Responses name the served tier by its public id (canto, saga, epos) from Cruxy-Version 2026-10-18, and when no Cruxy-Version is sent; a request pinned to an earlier date is echoed the old id (kavi, vaani, mira). stream is optional and false by default. With stream:true the response is a text/event-stream of NAMED events: `start` (the served tier and how it was routed), zero or more `reasoning` (fragments of the model's thinking trace, only when the tier reasons - reasoning_effort above none; NOT answer content, no token count of its own, since usage output tokens already include it undivided; ignore it if you do not render thinking), one or more `delta` (each a text `content` fragment OR `tool_calls` fragments), then exactly one terminal frame - `finish` (finish_reason plus the final native usage) on success, or `error` (a stable, client-safe error code + message + request_id, from the same registry as the JSON error envelope) on a failure AFTER the stream opens. There is NO `[DONE]` sentinel and NO silent truncation: a v2 stream ALWAYS ends with a `finish` or an `error` frame. With stream:false or stream omitted the response is the native completion object - the assistant reply is the top-level message with a sibling finish_reason, a first-class routing object (tier, mode, reasoning_effort), a top-level request_id, usage carrying the native token counts and cost, and - only when the tier reasoned - a top-level reasoning string holding the thinking trace (kept out of message on purpose: do not send it back as conversation). TIMEOUTS AND RETRIES. With stream:false the gateway makes ONE attempt at the model, bounded by the tier's deadline: canto 90s, saga 90s, epos 45s. An attempt that runs past it is cancelled and answered 504 upstream_timeout, and nothing is billed. The gateway does NOT retry a timeout, since a turn that needed longer needs longer again: send stream:true (a stream may run for up to five minutes), or ask for less with a lower max_tokens or reasoning_effort. Other upstream failures (an overloaded or failing model, a dropped connection) are retried inside the gateway a bounded number of times, with backoff, before it answers 503 upstream_overloaded or 503 model_unavailable; on stream:true that happens only while the stream is being opened, never after a byte has reached you. The gateway never moves a call to another tier once it is sent: model auto picks a healthy tier before the call, and an explicit tier that kept failing is refused at once with 503 model_unavailable while it cools down. REASONING SPENDS max_tokens: with reasoning_effort omitted each tier applies its default - canto high (thinking on), saga low, epos none; auto chooses per request - reported as routing.reasoning_effort, and the thinking is generated inside the same max_tokens budget as the answer. A small max_tokens on canto can therefore be spent entirely on thinking, ending with finish_reason "length" and an empty message; send reasoning_effort:"none" for a short direct answer, or leave max_tokens unset (the tier's cap) to keep reasoning - no OpenAI choices[] array and no cruxy.* wrapper. WHICH CREDENTIALS USE MEMORY: memory recall and automatic capture are ON by default for a credential a person gets by signing in (the Cruxy web app, desktop, the CLI's device login, mobile) and OFF by default for a developer API key or a headless key, which opts in per request with memory:{"recall":true} and/or memory:{"capture":true} (see PER-REQUEST MEMORY CONTROLS below). A key minted by POST /api/v1/device/token or POST /api/v1/auth/oauth/token is a signed-in credential whichever client ran the flow, a third-party tool included, so it has memory and rules on; a server must use a developer API key instead (see BearerAuth). GET /api/v1/limits reports the kind as bucket: subscription is signed in, apikey and headless are not. An API key often serves people other than its owner, and recall would put the owner's stored memory into their turns while capture would store what they say, so neither happens unless the request asks. A key whose allowed_scopes omit the memory family can never use memory through chat - asking with true is 403 key_scope_forbidden (required_scope memory), refused before anything is billed - which makes it the key to issue for a service that must never see anyone's memory. When recall runs, relevant stored memories are recalled server-side and added to the turn as background context, drawn from the same resolved view GET /api/v1/memories lists: personal memory, the organization's, and readable vaults'. The optional vault_id names the vault a chat is happening inside and selects the ISOLATED case - inside a `vault_only` vault recall draws on ONLY that vault's memory, excluding personal and organization memory. A vault_id the caller cannot read is treated as none and never reported. What was recalled rides the `start` frame and the non-streaming body as a top-level memory_recall (scope - personal, org, or vault - and key per memory; never the stored value), with a vault-scope memory naming its source vault (vault_id, and vault_name when it resolves). mentioned_vault_ids lets a turn reference vaults it is not inside (at most 3, ids resolved by the client's picker); unreadable ids, repeats, and the active vault are dropped silently, and an accepted mention adds that vault's memory to the same recall budget without changing isolation or making the vault writable. WHICH CREDENTIALS GET STANDING RULES: the same default as memory. Your organization's standing rules are injected by default for a credential a person gets by signing in, and NOT for a developer API key or a headless key, whose rules are its owner's organization's guidance and which a visitor to whatever the key serves could ask the model to repeat. Such a key opts in per request with rules:true, or once, on the key, by being issued allowed_scopes that NAME the rules family (an unscoped key has every family but has not opted in). Any credential may send rules:false to decline them for a turn, which needs no scope since the user's own message already overrides them. A key whose allowed_scopes omit rules never gets them, and rules:true on it is 403 key_scope_forbidden (required_scope rules), refused before anything is billed. The switch covers the whole resolved ruleset, the organization's and, with vault_id, the vault's, so a turn gets exactly what GET /api/v1/rules/resolved returns or nothing. When rules apply and the caller's organization has configured them they are resolved server-side and injected as guidance for the turn - DEFAULTS the user's own message overrides - and both the `start` frame and the non-streaming body carry an additive top-level rules_applied signal (counts and sources, never rule text). vault_id selects which rules apply too: inside a vault the turn gets that vault's own ruleset merged with the organization's per the vault's inherit_org_rules switch - the same answer GET /api/v1/rules/resolved gives for that vault - and rules_applied names each contributing scope (org, vault). A vault_id the caller cannot read is treated as none here as well, so the turn simply runs with organization-scope rules. Injected rule text is counted in the usage input tokens like any other input. When capture runs, after a turn is answered the gateway may also capture a durable fact from the exchange into memory; every capture is reported additively as a top-level memory_capture - on the non-streaming body, and on the terminal `finish` frame when streaming, since what was captured is only knowable once the answer is complete. It names the scope and key of each stored memory and never the value, so nothing is stored that the response does not report. Capture writes personal memory, or the vault named by vault_id when you may write it (a read-only vault demotes to personal), never organization-wide memory; obvious personal data is dropped rather than stored; and a failed capture never affects the turn. PER-REQUEST MEMORY CONTROLS: an API key opts in with memory:{"recall":true} (inject the stored memories most relevant to this turn) and/or memory:{"capture":true} (allow a durable fact from this turn to be stored); any credential may send memory:{"recall":false} to inject no stored memory into this turn (no memory is read, mentioned_vault_ids are not consulted, no memory_recall is returned, and input tokens fall by the size of the block that would have been injected), and memory:{"capture":false} to store nothing from it (no extraction, no write, no memory_capture). The two sides are independent: {"capture":false} alone keeps the turn personalised by what is already stored while storing nothing new. A missing memory object, a missing key, or null means the credential's default (on for a signed-in client, off for a developer or headless API key), and a literal true or false states your choice. false needs no key scope, since it only makes the gateway do less for your own request; true needs a key whose allowed_scopes include memory (an unscoped key has every family). Standing rules are not memory, and this field never affects them: they have their own switch, rules (see WHICH CREDENTIALS GET STANDING RULES above). Pin Cruxy-Version 2026-09-26 on every request that relies on memory:false: unknown fields are ignored rather than refused, so a gateway that predates this field would answer 200 and capture anyway, and a pinned request is instead refused by such a gateway with 400 unknown_version before recall, the upstream call, billing or capture run. Dated versions are otherwise only for breaking changes; this date gates an additive field because its silent absence on an older gateway would make the response misrepresent what it used (here, a privacy promise; content the user supplied qualifies on the same terms), and it is not precedent for ordinary additive fields. ATTACHED FILES: a user message may carry file_ids, the ids of files you uploaded with POST /api/v1/files under the same organization and user as this credential, and the gateway reads each one into the turn. The request must pin Cruxy-Version 2026-10-05 or later: a request naming file_ids without that pin is 400 invalid_request (carrying required_version), because a gateway that predates the field would ignore it and answer without the files, and the pin is what makes such a gateway refuse instead. UTF-8 text files are read (plain text, markdown, CSV, JSON, source code), and so are PDFs and Word documents (.docx), as the text read out of them once, when they were uploaded (POST /api/v1/files reports it as text_status): a document is framed, measured against the caps and billed by its text exactly as a text file is, and is never parsed on a turn. A file of another type, or whose bytes are not UTF-8 text, is 400 file_not_text, and so is a document whose text could not be read, with a reason field saying why: no_text (no text found, such as a scanned PDF), encrypted (password-protected), corrupt, unreadable (reading it went past the time or memory allowed for one document), legacy_doc (a Word 97-2003 .doc) or not_extracted (uploaded before documents were read; upload it again). A file over the per-file token cap, or one that takes the request past the per-turn cap, is 400 file_too_large, and so is a PDF of more than 500 pages (bound pages) or over 64 MiB (bound bytes), which is not read; for a document the message advises attaching a shorter excerpt. Both name the file (file_id, filename, and for file_too_large bound, limit and tokens). An id that is not yours, whether another user's, one filed under another of your organizations, missing or malformed, is 404 file_not_found, the same answer in every case. A key whose allowed_scopes omit files is 403 key_scope_forbidden (required_scope files). All of these are answered before anything is sent upstream or billed. Each file's text goes in as a user-role block immediately before the message that named it, framed as material for that message and never as instructions to follow; it never enters the system prompt, recall does not search with it, and automatic capture does not read it. A file named on several messages is sent once, before its first mention. Its tokens are input like any other and are billed on EVERY request that sends the file, wherever its block sits: a file id you keep in a conversation's history is billed on each turn, not only the first. They count toward the tier's context window: a file on an earlier message that does not fit beside the conversation, with room left for the reply's max_tokens and a margin of a tenth of the window, is left out, oldest first, and listed in files_omitted with reason context_window, and a turn that does not fit even with every earlier file left out is 400 context_overflow. POST /v1/chat/completions refuses file_ids, and POST /api/v1/tokens/count does not count them. ## POST /v1/chat/completions: Chat completions (OpenAI-compatible) openai. OpenAI-compatible chat completions, request and response. Point any OpenAI client or evaluation harness at base URL https://api.cruxy.ai/v1 with your Cruxy API key as the bearer token and it works unmodified. `model` is a public Cruxy tier (canto, saga, or epos) or auto to let the server-side router pick; an upstream provider model is never accepted or returned. kavi, vaani and mira are deprecated aliases of canto, saga and epos: still accepted on input on every API version and served as the same tier. Responses name the served tier by its public id (canto, saga, epos) from Cruxy-Version 2026-10-18, and when no Cruxy-Version is sent; a request pinned to an earlier date is echoed the old id (kavi, vaani, mira). With stream:false the response is a standard chat.completion object: id, object, created, model, choices[0].message, and usage with prompt_tokens / completion_tokens / total_tokens. With stream:true it is OpenAI's SSE protocol: chat.completion.chunk frames (a role primer, content or tool_call deltas, then a frame carrying finish_reason), terminated by the literal `data: [DONE]`. The terminal choices:[] usage frame is emitted only if you send stream_options:{"include_usage":true}, exactly as OpenAI gates it. If the upstream fails AFTER the stream has opened, the stream ends with a `data: {"error":{...}}` frame instead of `[DONE]`, so a truncated answer is never mistaken for a finished one. Errors use OpenAI's envelope, {"error":{message,type,param,code}}, where `code` is the stable Cruxy error code; it carries no other field, so the per-code context /api/v1/chat adds to an error (tier, hazard_codes, reset_at, mira_available and the rest) is not sent here, and Retry-After, a header, is. `temperature`, `top_p`, `max_tokens`, `max_completion_tokens` and `reasoning_effort` are honoured (max_completion_tokens is OpenAI's newer name for max_tokens and is accepted as an alias of it; when a request sends both, max_completion_tokens is used and max_tokens is ignored; either is clamped to the tier's own output cap; reasoning_effort is one of none, low, medium, high). As on OpenAI's reasoning models, thinking is generated inside the max_tokens budget and is not returned as content, and canto reasons by default (reasoning_effort omitted means canto high, saga low, epos none): a small max_tokens on canto can be spent entirely on thinking and return finish_reason "length" with empty content. Send reasoning_effort:"none" for a short direct answer, or leave max_tokens unset. TIMEOUTS AND RETRIES. With stream:false the gateway makes ONE attempt at the model, bounded by the tier's deadline: canto 90s, saga 90s, epos 45s. An attempt that runs past it is cancelled and answered 504 upstream_timeout, and nothing is billed. The gateway does NOT retry a timeout, since a turn that needed longer needs longer again: send stream:true (a stream may run for up to five minutes), or ask for less with a lower max_tokens or reasoning_effort. Other upstream failures (an overloaded or failing model, a dropped connection) are retried inside the gateway a bounded number of times, with backoff, before it answers 503 upstream_overloaded or 503 model_unavailable; on stream:true that happens only while the stream is being opened, never after a byte has reached you. The gateway never moves a call to another tier once it is sent: model auto picks a healthy tier before the call, and an explicit tier that kept failing is refused at once with 503 model_unavailable while it cools down. Fields this gateway does not implement (n, stop, seed, presence_penalty, frequency_penalty, logit_bias, logprobs, user and the rest) are IGNORED rather than rejected, so a harness that sends them still runs. This endpoint deliberately carries none of the Cruxy-native chat features: no cruxy.* block, no vault_id, no memory recall, no automatic memory capture, and no injection of your organization's standing rules: a run here is your messages and the tier, nothing else, which is what makes it reproducible as a benchmark. For those features use POST /api/v1/chat (OpenAI-shaped SSE, Cruxy-flattened body) or POST /api/v2/chat (the Cruxy-native wire). Authentication, rate limits, the endpoint-scope check and billing are identical on all three: this route requires the `chat` endpoint family and its usage lands on the same ledger. ## GET /v1/models: List models (OpenAI-compatible) openai. OpenAI-compatible model listing, for clients and evaluation harnesses pointed at this gateway as an OpenAI endpoint (base URL https://api.cruxy.ai/v1). Returns {"object":"list","data":[{id, object, created, owned_by}]} and nothing else: the ids are the public Cruxy tiers (canto, saga, epos) and never an upstream provider model. A request pinned to a Cruxy-Version before 2026-10-18 is listed the deprecated ids kavi, vaani and mira instead; both spellings are accepted on input. For the richer catalog (context window, max output, tool support, per-tier pricing, latency targets and reasoning defaults), use GET /api/v1/models, which lists the same tiers with Cruxy's own discovery metadata. Errors on this path use OpenAI's envelope ({"error":{message,type,param,code}}); the /api/v1 surface keeps the Cruxy envelope. ================================================================================ Page: Get started with the CLI URL: https://learn.cruxyai.com/docs/en/cruxy-code Markdown: https://learn.cruxyai.com/docs/en/cruxy-code.md ================================================================================ # Get started with the CLI Install the cruxy coding agent from npm, check the Node.js version it needs, sign in, and run your first task from a terminal. Cruxy Code is the `cruxy` command, published on npm as `@cruxy/cli`. It is a coding agent that works in your repository from the terminal: it reads code, edits files, runs commands, and checks its own work. It asks for your approval before it writes a file or runs a shell command. Every model turn goes to the Cruxy API at `https://api.cruxy.ai`, and the model is a tier (`canto`, `saga`, or `epos`) or `auto`. This section documents `@cruxy/cli` 1.19.0. ## Requirements - **Node.js 20 or later.** The package declares `"node": ">=20"` in `engines`. - **Node.js 22.13 or later for a persistent codebase index.** On older Node.js, semantic search keeps its index in memory and rebuilds it each session, and `cruxy index` refuses to build one. - **A terminal to sign in.** `cruxy login` and `cruxy init` are interactive. In CI or a script, set `CRUXY_API_KEY` instead; see [Sign in from the CLI](/docs/en/cruxy-code/authentication). - **On Windows, Git Bash or PowerShell.** The CLI runs shell commands through one of them, or through the shell you name in `shell.executable`. ## Install ```bash npm install -g @cruxy/cli cruxy --version ``` `cruxy --version` prints the installed version. `cruxy --help` lists every command; [CLI command reference](/docs/en/cruxy-code/commands) documents each one. ## Run it for the first time 1. **Open your project** Start `cruxy` in the directory you want it to work in. That directory becomes the project root, and file access stays inside it. ```bash cd my-project cruxy ``` 2. **Sign in** With no key in the environment and none saved, the first run in a terminal walks you through device login: the CLI prints a link and a short code, you approve in a browser, and the CLI saves the credential to `~/.cruxy`. It then names the organization the credential is bound to and your role in it. See [Sign in from the CLI](/docs/en/cruxy-code/authentication). 3. **Carry on into your task** Once sign-in completes, the CLI carries on with what you asked for: `cruxy ""` runs the task, and a bare `cruxy` opens the session. With no task, it first offers a demo run that summarizes the repository from its README and structure; press Enter to run it, or `n` to skip. If you leave sign-in before it completes, the CLI stops there. 4. **Give it a task** Type a task into the session. Before any file write or shell command, the CLI shows you what it is about to do and waits for your answer. ## Ways to run it | Command | What it does | | --- | --- | | `cruxy` | Opens the full-screen interactive session. Where the full-screen session cannot run, it prints a short usage banner and exits `0`. | | `cruxy ""` | Opens the interactive session with the task as its first turn. Where the full-screen session cannot run, it runs the task once. | | `cruxy run ""` | Runs the task once and exits. A run that stops before it finishes exits `20`. | | `cruxy run` | Opens a line-based interactive session. It needs a terminal. | | `cruxy --resume [id]` | Resumes a saved session for this project. Without an id, it lets you pick from recent sessions. | The full-screen session needs an interactive terminal. It does not run when stdin or stdout is not a terminal (for example, when piped), when `TERM=dumb`, or in screen-reader mode (`CRUXY_SCREEN_READER` or `ACCESSIBLE`); there, use `cruxy run` for a line-based session. Inside a session, type `/help` for the session commands. In the full-screen session, Shift+Tab cycles the mode between `manual`, `auto-approve`, `plan`, and `full-auto`; see [Projects, permissions, and context](/docs/en/cruxy-code/projects-and-context#session-modes). ## Set up a project `cruxy init` prepares the current directory: it gets a key only if none is set, offers to write a `CRUXY.md`, and offers the demo run. ```bash cruxy init ``` `CRUXY.md` holds instructions for your project, such as conventions and how to build and test. The CLI reads it into every turn. If there is no `CRUXY.md`, it reads `AGENTS.md` instead. ## Run without a terminal In CI or a script, `cruxy run ""` reads the key from `CRUXY_API_KEY` and never stops to ask a question. An action that needs approval cannot be approved there, so the first file write or shell command ends the run with `CRUXY_E_APPROVAL_REQUIRED` and exit code `10`. A task the agent can finish with its read-only tools, such as explaining code, runs to the end. ```bash # CRUXY_API_KEY is set in the CI environment, never in the script. cruxy run "explain how requests are authenticated in src/" ``` ## Next steps - [Sign in from the CLI](/docs/en/cruxy-code/authentication): Device login, the signed-in credential it saves, when it expires, and how to replace it. - [CLI command reference](/docs/en/cruxy-code/commands): Every command, flag, and default, the session commands, and the exit codes. - [CLI configuration](/docs/en/cruxy-code/configuration): Config files, the order they merge in, environment variables, and the default settings. - [Projects, permissions, and context](/docs/en/cruxy-code/projects-and-context): What asks for approval, what stays on your machine, and what the CLI sends to the API. - [Troubleshoot the CLI](/docs/en/cruxy-code/troubleshooting): Read an error and its code, and fix the failures you are most likely to hit. ================================================================================ Page: Sign in from the CLI URL: https://learn.cruxyai.com/docs/en/cruxy-code/authentication Markdown: https://learn.cruxyai.com/docs/en/cruxy-code/authentication.md ================================================================================ # Sign in from the CLI Sign the cruxy CLI in with device login, know what the credential it saves can do, when it expires, and how to sign out and revoke it. The CLI signs in with device login: it shows you a link and a code, you approve in a browser, and the gateway issues a key that the CLI saves on your machine. For how device login works on the API side, see [Get your API key](/docs/en/get-started/api-keys). > **Warning:** Device login gives the CLI a signed-in credential, bound to one organization. > It expires 90 days after it is issued, and `cruxy logout` revokes it. ## Sign in with device login Run `cruxy login` in a terminal. The first `cruxy` run in a terminal with no key runs the same flow. 1. **Start the login** ```bash cruxy login ``` If a credential is already saved, the CLI says that this replaces it and that there is no undo. If `CRUXY_API_KEY` is set, it warns that the environment always wins: the new credential is saved, but requests keep using the environment variable until you unset it. 2. **Open the link and check the code** The CLI asks the gateway for a device code and prints where to approve it. The values come from the gateway; these are examples: ```text To sign in, open https://cruxy.ai/device?user_code=WDJB-MJHT and enter the code WDJB-MJHT waiting for approval (expires in 10 minutes)… ``` The link already carries the code when the gateway provides one; otherwise type the code on the page. The approval page names the CLI as the client, because the CLI sends `Cruxy-Client: cli/` when it starts the login. 3. **Approve in the browser** Approve the request before the code expires. The browser can be on another machine. While it waits, the CLI polls the gateway, and slows down when the gateway asks it to. 4. **Confirm it is saved** On approval, the CLI saves the credential to `~/.cruxy`, says it is signed in, names the organization the credential is bound to and your role in it, and prints the date the credential expires. The last two lines look like this: ```text organization: Acme (admin) it expires on 2027-01-25; run `cruxy login` again before then. ``` The organization decides whose memory, standing rules, and budget the session draws on, and a login does not always bind to the same organization as the last one. The CLI does not send a test request: the gateway issued the key on that same connection. On a first run, the CLI then carries on into the task or session you started. ## When sign-in does not finish Each of these leaves any saved credential untouched and suggests `cruxy login --paste`. Under `cruxy login`, the CLI then prints that the login was not completed and exits `1`. | The CLI says | What happened | What to do | | --- | --- | --- | | the sign-in was declined in the browser. | The request was declined on the approval page. | Run `cruxy login` again if that was a mistake. | | the code expired before it was approved. | Nobody approved it in time. | Run `cruxy login` for a new code. | | that sign-in could not be completed. | The gateway refused the device code. | Run `cruxy login` to start over. | | couldn't reach the gateway to sign in. | The login could not start, or the gateway gave an answer the CLI does not expect. Network drops while it waits for approval are retried until the code expires. | Check your connection and `cruxy.gatewayUrl`, then run `cruxy login` again. | Without a terminal, `cruxy login` does not start: it prints that it is interactive and exits `1`. The CLI sends a credential only over `https://`, and over plain `http://` only to `localhost`, `127.0.0.1`, or `[::1]`. With any other `cruxy.gatewayUrl`, `cruxy login`, `cruxy logout`, and every other command that calls the gateway fail before a request is made, with `CRUXY_E_CONFIG_INVALID` (exit `3`); see [Gateway URL](/docs/en/cruxy-code/configuration#gateway-url). ## Where the credential is stored The CLI writes the credential to `~/.cruxy/credentials.json`, never to a config file or to your project. Next to the key it records the expiry the gateway stated, the key's id, that it came from device login, and the organization and role it is bound to, so `cruxy logout` can name them. The file is readable only by you: mode `0600` in a `0700` directory on macOS and Linux, and an access-control list for your user alone on Windows. If the CLI cannot make it owner-only, for example on a FAT or exFAT drive, it refuses to write the key and fails with `CRUXY_E_CREDENTIALS_UNPROTECTED`. When the CLI reads a key from a file that other users can read, it first makes the file owner-only and warns once that anything in it may already have been copied: run `cruxy login` for a new key, revoke the old one in the Console, and issue any MCP tokens stored there again. If it cannot make the file owner-only, it refuses to read it and fails with `CRUXY_E_CREDENTIALS_UNPROTECTED`; set `CRUXY_API_KEY` instead. ## Which key the CLI uses 1. `CRUXY_API_KEY` in the environment, if it is set. 2. Otherwise, the credential saved in `~/.cruxy/credentials.json`. The environment always wins, and the CLI never reads a key from a config file. `cruxy config list --origin` shows whether a key is set. ## What a signed-in credential does A device-login credential is a signed-in credential. Its `bucket` in `GET /api/v1/limits` is `subscription`, and `cruxy limits` shows your plan's weighted-token pool and what is left of it. A developer API key, pasted or set in `CRUXY_API_KEY`, works only on a plan with API access, and `cruxy limits` shows its pool too once the gateway reports one. On a plan without API access, the CLI reports `CRUXY_E_PAID_PLAN_REQUIRED` and exits `22`. Whatever the key, the CLI states the gateway's memory and rules on every chat request in a session, so your config decides them and the kind of key does not: - **Memory recall** is on (`cruxy.memory.recall`). - **Memory capture** is off (`cruxy.memory.capture`). Turn it on in config, or for one run with `--memory-capture`. - **Your organization's standing rules** are on (`cruxy.rules`). `--no-memory` turns recall and capture off for one run. See [Gateway memory and rules](/docs/en/cruxy-code/projects-and-context#gateway-memory-and-rules) for the secret guard and the version pin, and [Memory](/docs/en/build/memory) and [Standing rules](/docs/en/build/rules) for what each one does. This gateway memory is separate from the CLI's own local memory; see [Projects, permissions, and context](/docs/en/cruxy-code/projects-and-context#local-memory). ## Use a key you already have `cruxy login --paste` takes an existing key instead of approving in a browser, for example on a machine with no browser to approve in. ```bash cruxy login --paste ``` The CLI points you to the Console's API keys page, `https://platform.cruxy.ai/keys`, to create a developer API key. It reads the key with masked input, checks it with one small chat request that sends memory off, and saves it only if the gateway accepts it. You get three tries. A key whose account's plan has no API access is not saved and not retried: the CLI reports `CRUXY_E_PAID_PLAN_REQUIRED` and exits `22`. A pasted key is saved with no expiry or organization, because the CLI is not told either. A developer API key from the Cruxy Console does not expire. ## Expiry A device-login credential stops working 90 days after it is issued. Using it does not extend it. - **At login,** the CLI prints the expiry date. - **In the last 7 days,** each run and each session start prints a notice that your sign-in expires in a given number of days, with `cruxy login` as the fix. - **After expiry,** requests fail with `CRUXY_E_AUTH_EXPIRED`, titled "your cruxy login has expired", and exit `4`. Run `cruxy login` for a new credential. The gateway answers an expired key with the same `401` it gives a wrong one. The CLI tells them apart only from the expiry it recorded at login, so an expired pasted key reports `CRUXY_E_AUTH_INVALID` instead. This check runs when a `401` ends the command, such as a one-shot `cruxy run`, and it reads the saved credential even when `CRUXY_API_KEY` is the key in use. Inside an interactive session, a turn the gateway rejects reports `CRUXY_E_AUTH_INVALID` either way. The expiry notice also reads the saved credential, whatever key is in use. ## Sign out ```bash cruxy logout ``` `cruxy logout` revokes the saved credential at the gateway with `DELETE /api/v1/me/key` (see [Revoke the current key](/docs/en/get-started/api-keys#revoke-the-current-key)), then removes it from `~/.cruxy/credentials.json`, and names the organization it signed out of: ```text ✓ signed out of Acme (admin) key : revoked at the gateway and removed from ~/.cruxy ``` A key the gateway already refuses, because it was revoked or has expired, also counts as signed out: the CLI removes it and says so. In both cases the command exits `0`. A pasted key has no organization recorded, so the first line says that instead of naming one. In every other case the credential stays saved, you are still signed in, and the command fails: | Outcome | Code | Exit | | --- | --- | --- | | The key is not allowed to revoke itself, such as a read-only or scoped key. Revoke it in the Console at `https://platform.cruxy.ai/keys`, then run `cruxy logout` again to remove it. | `CRUXY_E_AUTH_INVALID` | `4` | | The gateway cannot be reached. | `CRUXY_E_GATEWAY_UNREACHABLE` | `5` | | The gateway answered with an error after retries, or with a redirect, which the CLI does not follow with a credential. | `CRUXY_E_API` | `6` | When the gateway cannot be reached and you are at a terminal, the CLI asks whether to remove the credential from this machine anyway. Only `y` removes it, and then the key is not revoked: it stays valid until it expires or you revoke it in the Console, and the CLI warns you of that. Without a terminal it never asks, and keeps the credential. With no credential saved, `cruxy logout` says there is nothing to remove and exits `0`. It never revokes a key in `CRUXY_API_KEY`: if that variable is set, the CLI warns that it still uses it, and you finish signing out by unsetting it. MCP server tokens you stored with `cruxy mcp login` stay in the file. To replace the credential instead, run `cruxy login` again. The new credential overwrites the old one in `~/.cruxy/credentials.json`, and the old one stays valid until it expires or is revoked, so run `cruxy logout` first if you no longer want it to work. ## In CI and scripts `cruxy login` and `cruxy init` need a terminal. Elsewhere, set `CRUXY_API_KEY`. For a shared server or CI job, use a developer API key from the Cruxy Console, not your own signed-in credential: a signed-in credential is bound to you and your organization, and expires after 90 days. See [Get your API key](/docs/en/get-started/api-keys#two-kinds-of-key). ================================================================================ Page: CLI command reference URL: https://learn.cruxyai.com/docs/en/cruxy-code/commands Markdown: https://learn.cruxyai.com/docs/en/cruxy-code/commands.md ================================================================================ # CLI command reference Every cruxy command, subcommand, flag, and default as the 1.19.0 help prints them, plus the session commands, keys, and exit codes. This reference matches `cruxy --help` and each subcommand's `--help` in `@cruxy/cli` 1.19.0. Run `cruxy --help` for the same text in your terminal. Every command and subcommand also takes `-h, --help`, which is left out of the tables below. ## Global options These go before the command: `cruxy [options] [command]`. | Option | Description | | --- | --- | | `-v, --version` | Print the cruxy version. | | `-c, --config ` | Use a specific config file instead of the discovered project config. The file must exist. | | `--log-level ` | One of `debug`, `info`, `warn`, `error`, or `silent`. | | `--verbose` | Shorthand for `--log-level debug`. Errors also show the underlying error. | | `--resume [id]` | Resume a saved session by id. Omit the id to pick from recent sessions. | ## cruxy ```bash cruxy [options] [message...] ``` With no command, `cruxy` opens the full-screen interactive session, and a message becomes its first turn. The full-screen session needs an interactive terminal: it does not run when stdin or stdout is not a terminal (for example, when piped), when `TERM=dumb`, or in screen-reader mode. There, with no message, `cruxy` prints a short usage banner and exits `0`; with a message, it runs the message once. On a first run with no key, `cruxy` runs setup first and then carries on: with a message it runs the message, and without one it opens the session. A single word that is a near miss of a command name, such as `cruxy confg`, is refused with a suggestion instead of being sent as a task. | Option | Default | Description | | --- | --- | --- | | `--no-memory` | off | The gateway neither recalls nor captures memory for this run. | | `--memory-capture` | off | Let the gateway capture memory from this run's turns. Capture is off by default. | Both flags override `cruxy.memory.recall` and `cruxy.memory.capture` for one run; see [Projects, permissions, and context](/docs/en/cruxy-code/projects-and-context#gateway-memory-and-rules). Passing both fails with `CRUXY_E_USAGE` (exit `2`), because they contradict each other. ## run ```bash cruxy run [options] [prompt...] ``` Runs a task once, or starts a line-based interactive session when you omit the prompt. Without a terminal, the prompt is required. | Option | Default | Description | | --- | --- | --- | | `--plan` | off | Plan mode: propose a step-by-step plan for approval before executing. | | `--sandbox` | off | Run shell and test commands inside an isolated container. Fails if no container runtime is available. | | `--root ` | none | Declare a workspace root, as `name=path` or `path`. Repeatable; the first is the primary root. | | `--no-memory` | off | The gateway neither recalls nor captures memory for this run. | | `--memory-capture` | off | Let the gateway capture memory from this run's turns. Capture is off by default. | A one-shot run that ends before the task is finished, at the iteration cap, at a token budget, or because it was cancelled, exits `20` with `CRUXY_E_AGENT_INCOMPLETE`. ## login ```bash cruxy login [--paste] ``` Sets or replaces your credential, saved to `~/.cruxy`. It is interactive: without a terminal it exits `1`. After a browser sign-in, it names the organization the credential is bound to and your role in it. See [Sign in from the CLI](/docs/en/cruxy-code/authentication). | Option | Default | Description | | --- | --- | --- | | `--paste` | off | Paste an existing API key instead of approving in a browser. | ## logout ```bash cruxy logout ``` Revokes your saved credential at the gateway and removes it from `~/.cruxy`. It takes no options and does not need a terminal. | Outcome | Exit | | --- | --- | | The gateway revoked the key, or already refused it as revoked or expired. The key is removed. | `0` | | No credential is saved. Nothing changes. | `0` | | The key may not revoke itself (`CRUXY_E_AUTH_INVALID`). You stay signed in. | `4` | | The gateway cannot be reached (`CRUXY_E_GATEWAY_UNREACHABLE`). You stay signed in unless you answer `y` at the terminal prompt. | `5` | | The gateway answered with an error (`CRUXY_E_API`). You stay signed in. | `6` | A key in `CRUXY_API_KEY` is never revoked: the CLI warns that it is still in use. See [Sign out](/docs/en/cruxy-code/authentication#sign-out). ## init ```bash cruxy init ``` Sets up the current directory: a key if none is set, an optional `CRUXY.md`, and an optional first run. It is interactive: without a terminal it exits `1`. ## config ```bash cruxy config ``` Manages configuration. See [CLI configuration](/docs/en/cruxy-code/configuration). | Command | Description | | --- | --- | | `config list` (alias `ls`) | Print the fully resolved configuration. `--origin` shows where each value came from: a default, a config file, or the environment. | | `config get ` | Read one value by dot path, such as `model.temperature`. An unknown key exits `2`. | | `config set ` | Write a value by dot path to the global config. `-p, --project` writes the project config instead. | | `config path` | Show the config file locations in effect. | | `config init` | Write a default global config file, if none exists. | ## index ```bash cruxy index [options] ``` Builds or refreshes the local codebase search index. | Option | Default | Description | | --- | --- | --- | | `--status` | off | Show index status without building. | | `--force` | off | Re-embed every file, ignoring content hashes. | | `--install` | off | Install the local embedding runtime that semantic search needs. It prints what it downloads first. | | `--uninstall` | off | Remove the embedding runtime and its model cache. | Without the runtime, `cruxy index` offers to install it in a terminal and fails with `CRUXY_E_INDEX_EMBEDDER_NOT_INSTALLED` elsewhere. It writes a persistent index at `.cruxy/index.db`, so it needs Node.js 22.13 or later. ## skills ```bash cruxy skills [--status] ``` Lists the skills available to the agent. | Option | Default | Description | | --- | --- | --- | | `--status` | off | Show source directories and validation errors. | ## pr ```bash cruxy pr [options] ``` Opens a pull request from the current changes. The commit message and pull request text are generated, and the whole plan is shown for approval first. It needs a Cruxy key and a GitHub token from `GITHUB_TOKEN`, `GH_TOKEN`, or `gh auth token`. | Option | Default | Description | | --- | --- | --- | | `-b, --base ` | see description | Base branch to merge into. Defaults to `git.defaultBase`, then the repository's default branch, then `main`. | | `-t, --title ` | generated | Pull request title, as a conventional-commit subject. | | `--body <body>` | generated | Pull request body. | | `--draft` | off | Open the pull request as a draft. | ## checkpoint ```bash cruxy checkpoint list ``` Inspects working-tree checkpoints, the undo units behind `rollback`. `checkpoint list` lists restore points, one before each turn that changed files, newest first. ## rollback ```bash cruxy rollback [id] ``` Restores the working tree to before a turn, which undoes that turn and every newer one. `id` is a run id, job id, or checkpoint id. Without one, it lets you pick a restore point, with the newest selected, when there is more than one. It restores the most recent run directly when there is only one, or when the history spans more than one workspace root. It previews the change and asks for approval, so without a terminal it exits `10` with `CRUXY_E_ROLLBACK_APPROVAL_REQUIRED`. ## test ```bash cruxy test ``` Runs the project's test suite once and shows the parsed result. It runs `test.command` when that is set, and otherwise the `test` script in `package.json` through the project's package manager. It exits `1` when tests fail, and `2` with `CRUXY_E_TEST_COMMAND_NOT_FOUND` when there is no test command. ## hooks ```bash cruxy hooks <command> ``` Inspects and trusts hooks and custom slash commands. | Command | Description | | --- | --- | | `hooks list` | List configured hooks, custom commands, and load errors. | | `hooks trust <path>` | Trust a project's hooks after reviewing them. The decision is recorded. | ## memory ```bash cruxy memory <command> ``` Inspects and controls the CLI's local memory, recalled across sessions. | Command | Description | | --- | --- | | `memory list` | List saved memory entries and the project memory's trust status. | | `memory forget <id>` | Forget one saved memory entry by id. | | `memory clear [--scope <scope>]` | Clear saved entries in a scope: `user`, `project`, or `all`. Default `all`. Any other scope exits `2`. | | `memory trust [path]` | Trust this repository's project memory after reviewing it. The decision is recorded. | ## usage ```bash cruxy usage [options] ``` Shows token usage and cost for the session and recent runs, from the local usage record. Cost is the figure the gateway reported for each request, and requests it reported no cost for are counted as such. | Option | Default | Description | | --- | --- | --- | | `--session` | off | Only the most recent session's runs. | | `--last <n>` | off | Only the last `n` runs. | Pass one of `--session` or `--last`, not both. ## limits ```bash cruxy limits ``` Shows your plan's weighted-token pool and what is left of it, read from `GET /api/v1/limits`. With no usable key, it prints that you are not signed in. ## mcp ```bash cruxy mcp <command> ``` Inspects and controls MCP integrations. | Command | Description | | --- | --- | | `mcp list` | List configured MCP integrations and their trust status. | | `mcp trust [path]` | Trust this repository's MCP integrations. They run with your full privileges. | | `mcp login <server>` | Set a bearer credential for a remote MCP integration, stored owner-only in `~/.cruxy`. Needs a terminal. | | `mcp untrust [path]` | Clear MCP trust for this repository, so the CLI stops connecting. | ## sessions ```bash cruxy sessions <command> ``` Manages this project's saved sessions. | Command | Description | | --- | --- | | `sessions list [--all]` | List saved sessions, newest first. `--all` lists every session, not only the newest 20. | | `sessions prune [-n, --dry-run]` | Clear sessions past `sessions.retention` or `sessions.maxAgeDays`. `--dry-run` shows what would be deleted and deletes nothing. | | `sessions rm <id>` | Forget one session by id or an unambiguous id prefix. | ## logs ```bash cruxy logs [--all] [id] ``` Reads a finished background job's log. `id` is a job id or an unambiguous prefix; without it, the command lists retained logs. | Option | Default | Description | | --- | --- | --- | | `--all` | off | List every retained log, not only the newest 20. | A background job never outlives the session that started it: leaving a session cancels every live job. Logs of failed and interrupted jobs are kept; a job that finished cleanly has its log removed at the next start. ## Session commands Type these inside an interactive session. `/help` lists them. | Command | Description | | --- | --- | | `/help` | Show the session commands. | | `/clear` | Clear the conversation history and keep the session. | | `/compact` | Summarize older history now, to free up context. | | `/init` | Write a project `CRUXY.md` and load it. | | `/reload` | Re-read the project instructions (`CRUXY.md`). | | `/status` | Show what this session is set up to do. | | `/permissions [revoke <n>]` | Show what runs without asking, and drop a standing grant by number. | | `/diff [ref \| --since <checkpoint>]` | Show uncommitted changes in the workspace. | | `/undo-last` | Roll back the most recent checkpointed set of file changes. | | `/redact` | Mask secrets in this conversation so the model stops seeing them. | | `/export [path]` | Write this conversation to a markdown file. | | `/plan` | Toggle plan mode: propose a plan before executing. | | `/mode [manual \| auto-approve \| plan \| full-auto]` | Show or set the session mode. | | `/model [auto \| canto \| saga \| epos]` | Show or set the model for this session. | | `/context` | Show where the context budget is going, and what compaction would drop. | | `/usage [all \| last <n>]` | Show token usage, weighted tokens, and cost. | | `/budget [<n> \| off]` | Show or set this session's weighted-token budget. | | `/jobs` | List background jobs and their status. | | `/logs <id>` | Show a background job's log. | | `/cancel <id>` | Cancel a background job. | | `/add-root <name> <path>` | Check another workspace root and print the `--root` flag to relaunch with. The root is not added to the running session. | | `/exit`, `/quit` | Leave the session. | The full-screen session also takes these keys: | Key | Action | | --- | --- | | Tab | Complete a slash command. | | Ctrl+K | Open the command palette. | | Shift+Tab | Cycle the mode: `manual`, `auto-approve`, `plan`, `full-auto`. | | PgUp, PgDn | Scroll the pane. The mouse wheel does too. | | Esc | Return to the live tail. | | Enter during a turn | Queue the line to run when the current turn finishes. | | Ctrl+C | Clear the line. On an empty line, stop cruxy: with no turn running it leaves the session, and during a turn it ends the process (exit `130`). | | Ctrl+D | Leave cruxy, after any queued lines. | ## Exit codes Every error prints a stable code, such as `CRUXY_E_AUTH_MISSING_KEY`, and exits with its category's status, so a script can branch on why `cruxy` failed. [Troubleshoot the CLI](/docs/en/cruxy-code/troubleshooting) covers the codes you are most likely to see. | Exit | Category | Codes | | --- | --- | --- | | `0` | Success | None. `--help` and `--version` also exit `0`. | | `1` | Internal | `CRUXY_E_INTERNAL`. Also `login` or `init` without a terminal or not completed, `test` with failing tests, and `mcp login` refusals. | | `2` | Usage | `CRUXY_E_USAGE`, `CRUXY_E_INTERACTIVE_REQUIRED`, `CRUXY_E_CONFIG_KEY_UNKNOWN`, `CRUXY_E_PROVIDER_UNSUPPORTED`, `CRUXY_E_GIT_PROTECTED_BRANCH`, `CRUXY_E_PLAN_INVALID`, `CRUXY_E_PLAN_REVISION_LIMIT`, `CRUXY_E_CHECKPOINT_NOT_FOUND`, `CRUXY_E_ROUTING_TIER_UNAVAILABLE`, `CRUXY_E_SESSION_BUDGET_EXHAUSTED`, `CRUXY_E_SUBAGENT_DEPTH_EXCEEDED`, `CRUXY_E_SUBAGENT_SCOPE_OVERLAP`, `CRUXY_E_TEST_COMMAND_NOT_FOUND`, `CRUXY_E_USAGE_READ`, `CRUXY_E_JOB_LIMIT` | | `3` | Config | `CRUXY_E_CONFIG_PARSE`, `CRUXY_E_CONFIG_INVALID`, `CRUXY_E_CONFIG_NOT_FOUND` | | `4` | Auth | `CRUXY_E_AUTH_MISSING_KEY`, `CRUXY_E_AUTH_INVALID`, `CRUXY_E_AUTH_EXPIRED`, `CRUXY_E_FORGE_AUTH`, `CRUXY_E_CREDENTIALS_UNPROTECTED` | | `5` | Network | `CRUXY_E_GATEWAY_UNREACHABLE`, `CRUXY_E_GIT_PUSH_FAILED` | | `6` | API | `CRUXY_E_API`, `CRUXY_E_API_REQUEST_REJECTED`, `CRUXY_E_API_RATE_LIMIT`, `CRUXY_E_API_OVERLOADED`, `CRUXY_E_BUDGET_EXHAUSTED`, `CRUXY_E_FORGE_API` | | `7` | Filesystem | `CRUXY_E_FILE_NOT_FOUND`, `CRUXY_E_PERMISSION_DENIED`, `CRUXY_E_PATH_ESCAPE`, `CRUXY_E_CHECKPOINT_FAILED`, `CRUXY_E_FILE_CHANGED_SINCE_READ` | | `8` | Index | `CRUXY_E_INDEX_EMBEDDER_UNAVAILABLE`, `CRUXY_E_INDEX_EMBEDDER_NOT_INSTALLED`, `CRUXY_E_INDEX_EMBEDDER_INSTALL_FAILED`, `CRUXY_E_INDEX_EMBEDDER_DOWNLOAD_FAILED`, `CRUXY_E_INDEX_STORE_UNAVAILABLE`, `CRUXY_E_INDEX_FAILED` | | `9` | Skill | `CRUXY_E_SKILL_INVALID`, `CRUXY_E_SKILL_NOT_FOUND` | | `10` | Approval | `CRUXY_E_APPROVAL_REQUIRED`, `CRUXY_E_PLAN_APPROVAL_REQUIRED`, `CRUXY_E_ROLLBACK_APPROVAL_REQUIRED` | | `11` | Subagent and tests | `CRUXY_E_SUBAGENT_BUDGET`, `CRUXY_E_SUBAGENT_FAILED`, `CRUXY_E_SUBAGENT_CANCELLED`, `CRUXY_E_TEST_ITERATION_LIMIT` | | `12` | Sandbox | `CRUXY_E_SANDBOX_UNAVAILABLE`, `CRUXY_E_SANDBOX_IMAGE`, `CRUXY_E_SANDBOX_EXEC` | | `13` | Hooks | `CRUXY_E_HOOK_FAILED`, `CRUXY_E_HOOK_UNTRUSTED`, `CRUXY_E_HOOK_INVALID`, `CRUXY_E_SLASH_INVALID` | | `14` | Memory and stores | `CRUXY_E_MEMORY_INVALID`, `CRUXY_E_MEMORY_SECRET`, `CRUXY_E_MEMORY_STORE_UNLOADABLE`, `CRUXY_E_STORE_LOCKED` | | `15` | Language servers | `CRUXY_E_LSP_SERVER_NOT_FOUND`, `CRUXY_E_LSP_TIMEOUT`, `CRUXY_E_LSP_CRASHED` | | `16` | MCP | `CRUXY_E_MCP_UNTRUSTED`, `CRUXY_E_MCP_CONNECT`, `CRUXY_E_MCP_BLOCKED`, `CRUXY_E_MCP_AUTH`, `CRUXY_E_MCP_CONFIG` | | `17` | Web | `CRUXY_E_WEB_UNAVAILABLE`, `CRUXY_E_WEB_SEARCH`, `CRUXY_E_WEB_FETCH`, `CRUXY_E_WEB_BLOCKED_HOST` | | `18` | Workspace roots | `CRUXY_E_ROOT_UNKNOWN`, `CRUXY_E_ROOT_AMBIGUOUS`, `CRUXY_E_ROOT_OVERLAP`, `CRUXY_E_ROOT_ADD_REFUSED`, `CRUXY_E_MULTIROOT_WRITE_DEFERRED`, `CRUXY_E_CHECKPOINT_SET_INCOMPLETE`, `CRUXY_E_CHECKPOINT_SET_PARTIAL`, `CRUXY_E_VCS_REMOTE_CHANGED`, `CRUXY_E_VCS_CROSS_ROOT` | | `19` | Background jobs | `CRUXY_E_JOB_NOT_FOUND`, `CRUXY_E_JOBS_DISABLED` | | `20` | Incomplete run | `CRUXY_E_AGENT_INCOMPLETE` | | `21` | Host shell | `CRUXY_E_NO_SHELL` | | `22` | Paid plan required | `CRUXY_E_PAID_PLAN_REQUIRED` | Several codes, such as most subagent, language-server, MCP connect, and web codes, are reported to the agent inside a tool result and end the process only when they surface on their own. ================================================================================ Page: CLI configuration URL: https://learn.cruxyai.com/docs/en/cruxy-code/configuration Markdown: https://learn.cruxyai.com/docs/en/cruxy-code/configuration.md ================================================================================ # CLI configuration Where the cruxy CLI reads settings from, the order they merge in, the environment variables it honors, and the defaults for each setting. The CLI reads its settings from JSON config files and a few environment variables, merges them over built-in defaults, and validates the result before it does anything else. Your API key is never one of these settings: it comes from `CRUXY_API_KEY` or the credential that `cruxy login` saves; see [Sign in from the CLI](/docs/en/cruxy-code/authentication). ## Config files | File | Scope | How it is found | | --- | --- | --- | | `~/.cruxy/config.json` | Global: every project for your user. | Always read when it exists. | | `cruxy.config.json` or `.cruxy/config.json` | Project. | The first one found, checking the current directory and then each parent up to the filesystem root. `cruxy.config.json` is checked first in each directory. | | The file named by `--config <path>` | Explicit. | Replaces project discovery for that run. The path is resolved as given, and a missing file fails with `CRUXY_E_CONFIG_NOT_FOUND`. | Each file holds one JSON object. Unknown keys and out-of-range values fail with `CRUXY_E_CONFIG_INVALID`, which names each bad field and the file to start with, and malformed JSON fails with `CRUXY_E_CONFIG_PARSE`. Both exit `3`. `cruxy config path` prints the global config path, the project file it found (if any), and the file named by `--config` when there is one: ```bash cruxy config path ``` ## Precedence Later layers win: 1. Built-in defaults. 2. The global file, `~/.cruxy/config.json`. 3. The project file, or the file named by `--config`. 4. Environment variables that map to a setting. Objects merge key by key; an array or a single value replaces the earlier one. To see each resolved value and the layer it came from, run: ```bash cruxy config list --origin ``` ## Change a setting `cruxy config set` writes one value by its dot path. It validates the file before writing, and turns `true`, `false`, and numbers into JSON booleans and numbers. ```bash # Global: ~/.cruxy/config.json cruxy config set model.model saga # Project: the discovered project file, or ./cruxy.config.json if there is none cruxy config set --project test.command "pnpm test" ``` `cruxy config get <key>` reads one resolved value, and `cruxy config init` writes every default to `~/.cruxy/config.json` if that file does not exist yet. You can also edit the files by hand. ## Environment variables These override config or supply values the CLI reads only from the environment. | Variable | Effect | | --- | --- | | `CRUXY_API_KEY` | The API key. Wins over the saved credential. Never read from a config file. | | `CRUXY_MODEL` | Overrides `model.model`. | | `CRUXY_PROVIDER` | Overrides `model.provider`. The only accepted value is `cruxy`. | | `CRUXY_LOG_LEVEL` | Overrides `logLevel`. `debug` also makes errors show the underlying error. | | `DEBUG` | Any value other than empty, `0`, or `false` makes errors show the underlying error. | | `GITHUB_TOKEN`, `GH_TOKEN` | The GitHub token `cruxy pr` uses. Without either, it tries `gh auth token`. | | `TAVILY_API_KEY` | The web search key, when `web.enabled` is on. `web.apiKeyEnv` names a different variable. | | `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | Honored when the CLI downloads the embedding model for semantic search. | These change how the terminal output looks, not what the agent does. `TERM=dumb` and screen-reader mode also turn off the full-screen session, so `cruxy` falls back to plain output: | Variable | Effect | | --- | --- | | `NO_COLOR` | No ANSI color at all. | | `FORCE_COLOR` | Keep color when output is piped or redirected. | | `CRUXY_ASCII` | ASCII glyphs such as `[ok]` and `->` instead of Unicode marks. | | `CRUXY_SCREEN_READER`, `ACCESSIBLE` | Screen-reader mode: status marks are spoken as words, decorative marks are dropped, and animation is off. | | `NO_MOTION`, `CRUXY_REDUCED_MOTION`, `CRUXY_NO_SPINNER` | No animation: spinners draw their end state once. | | `CRUXY_NO_ALT_SCREEN` | Keep the full-screen session in the normal terminal buffer. | | `CRUXY_NO_MOUSE` | Leave the mouse to the terminal, so text selection works without Shift. | | `COLUMNS`, `LINES` | Override the terminal size. Each takes a positive integer. | | `TERM=dumb` | No color, no cursor control, and ASCII glyphs. | Except for `COLUMNS`, `LINES`, and `TERM`, any non-empty value turns a variable on, including `0` and `false`; unset it or set it to the empty string to turn it off. `COLUMNS` and `LINES` ignore a value that is not a positive integer. ## Model and routing `model.model` is the tier every turn asks for: `canto` (Deep), `saga` (Balanced), `epos` (Fast), or `auto`, the default, which lets the gateway pick the tier for each request. To compare the tiers, see [Choosing a tier](/docs/en/build/choosing-a-tier). ```bash cruxy config set model.model canto ``` `/model` changes it for the current session only. `routing` sends kinds of work to different tiers. Its keys are the task classes `main-turn`, `subagent`, `plan`, `commit-msg`, and `summarize`: ```json { "routing": { "default": "saga", "map": { "commit-msg": "epos", "summarize": "epos" } } } ``` A class not in `map` takes `routing.default`. With no `default`, it takes the tier `model.model` names, or goes out as `auto` when `model.model` is `auto`. A class mapped to a tier the gateway does not offer fails with `CRUXY_E_ROUTING_TIER_UNAVAILABLE`, never a silent substitute. ### Former tier names `model.model`, `routing.default`, and `routing.map` still accept the former names `kavi`, `vaani`, and `mira`, and load them as `canto`, `saga`, and `epos`; see [Deprecated aliases](/docs/en/reference/models#deprecated-aliases). The same goes for `CRUXY_MODEL` and for a name typed after `/model`, which switches to the new tier and names it. If your team shares a project `cruxy.config.json`, keep the former names in `routing.default` and `routing.map` until everyone runs 1.18.0 or later: 1.17 and earlier refuse to start on a config that sets them to `canto`, `saga`, or `epos`. ## Gateway URL `cruxy.gatewayUrl` is where every request goes, and defaults to `https://api.cruxy.ai`. A config that sets it to exactly `https://api.cruxy.in` (with or without a trailing slash), the legacy name of the same service, is resolved to `https://api.cruxy.ai` with a one-line warning; the file itself is not edited. The CLI sends a credential only over `https://`. Plain `http://` is allowed only to `localhost`, `127.0.0.1`, and `[::1]`, for a gateway on your own machine. Any other URL fails before a request is made, with `CRUXY_E_CONFIG_INVALID` (exit `3`) titled "cruxy.gatewayUrl is not https, so no credential was sent". This applies to every command that calls the gateway, including `cruxy login`, `cruxy logout`, `cruxy limits`, and `cruxy pr`. The config file still loads, so you can fix the value: ```bash cruxy config set cruxy.gatewayUrl https://api.cruxy.ai ``` `cruxy config path` lists the files in effect, if you are not sure which one sets it. ## Approval is not a setting `approval.mode` accepts only `prompt`. No config key or flag turns approvals off: `cruxy config set approval.mode auto` fails with `CRUXY_E_CONFIG_INVALID`. Running without prompts is a session mode that you switch on in the session it affects, and a session resumed with `--resume` comes back in the last mode you switched to during it; see [Projects, permissions, and context](/docs/en/cruxy-code/projects-and-context#session-modes). ## Settings you are most likely to change | Setting | Default | Description | | --- | --- | --- | | `model.model` | `auto` | The tier: `canto`, `saga`, `epos`, or `auto`. | | `model.maxTokens` | `8192` | The `max_tokens` sent on each chat request. | | `model.temperature` | `0` | The `temperature` sent on each chat request, from `0` to `2`. | | `cruxy.gatewayUrl` | `https://api.cruxy.ai` | The gateway every request goes to. `https://` only, except to `localhost`. | | `cruxy.memory.recall` | `true` | Let the gateway recall your memory into each turn. | | `cruxy.memory.capture` | `false` | Let the gateway capture memory from each turn. | | `cruxy.rules` | `true` | Let the gateway add your organization's standing rules to each turn. | | `cruxy.streamIdleTimeoutMs` | `90000` | How long a stream may go without a byte before it counts as dead. A stream that dies before its first token is retried; one that dies after it is not. `0` turns it off. | | `cruxy.maxRetries` | `4` | Retries of a request that failed before its stream opened: a `429`, a `5xx`, or a connection that never opened. | | `cruxy.streamRetries` | `2` | Retries of a stream that dropped before its first token. | | `agent.maxIterations` | `25` | Agent loop turns per message in an interactive session. | | `agent.maxIterationsOneShot` | `40` | Agent loop turns for a one-shot `cruxy run "<task>"`. | | `agent.maxTokensPerTurn` | `0` | A cap on input plus output tokens for one turn. `0` is off. | | `agent.planMode` | `false` | Start every session in plan mode. | | `tools.fileEdit` | `true` | `false` removes `write_file`, `edit_file`, and `apply_patch`. Reads stay. | | `tools.shell` | `true` | `false` removes `run_command` and `run_tests`. | | `shell.timeoutMs` | `120000` | Kill a command and its process tree after this many milliseconds. | | `shell.maxOutputBytes` | `102400` | Command output captured; the rest is truncated. | | `shell.executable` | unset | The shell to run commands through, overriding detection. | | `context.maxTokens` | `100000` | The approximate context budget, in tokens. | | `context.compactThreshold` | `0.75` | Summarize older history once it passes this fraction of `context.maxTokens`. | | `git.protectedBranches` | `[]` | Branches the CLI never commits or pushes to directly, added to `main` and `master`. | | `git.defaultBase` | unset | The base branch for generated pull requests. | | `test.command` | unset | The test command, instead of the `test` script in `package.json`. | | `checkpoint.enabled` | `true` | Snapshot the working tree before a run's first approved file change, shell command, test run, or pull request, which `cruxy rollback` restores. | | `checkpoint.retention` | `10` | Checkpoints to keep. | | `sessions.enabled` | `true` | Record sessions so they can be resumed. | | `sessions.retention` | `50` | Sessions to keep. The minimum is `10`. | | `sessions.maxAgeDays` | `30` | Prune sessions untouched for this many days. | | `memory.enabled` | `true` | The CLI's local memory: recall at session start and the `remember` tool. | | `memory.maxRecallTokens` | `1000` | Token budget for recalled local memory. | | `index.enabled` | `true` | `search_codebase` and `cruxy index`. | | `sandbox.enabled` | `false` | Run shell and test commands in a container, as `--sandbox` does. | | `sandbox.network` | `none` | Container network: `none`, `host-loopback`, or `full`. | | `hooks.enabled` | `false` | Run configured hooks. | | `mcp.enabled` | `false` | Connect configured MCP servers. | | `web.enabled` | `false` | Give the agent `web_search` and `web_fetch`. | | `usage.enabled` | `true` | Record token usage locally for `cruxy usage`. | | `usage.prices` | unset | No longer used: cost is the gateway's own figure. Still accepted, and `cruxy usage` notes that you can remove it. The same goes for `usage.currency`. | | `logLevel` | `info` | `debug`, `info`, `warn`, `error`, or `silent`. | ## Every default `cruxy config init` writes this file in 1.19.0. `cruxy config list` prints every key with its resolved value. ```json { "model": { "provider": "cruxy", "model": "auto", "maxTokens": 8192, "temperature": 0 }, "cruxy": { "gatewayUrl": "https://api.cruxy.ai", "streamIdleTimeoutMs": 90000, "maxRetries": 4, "minRetryDelayMs": 1000, "maxRetryDelayMs": 20000, "streamRetries": 2, "memory": { "recall": true, "capture": false }, "rules": true }, "agent": { "maxIterations": 25, "maxIterationsOneShot": 40, "maxTokensPerTurn": 0, "planMode": false }, "tools": { "fileEdit": true, "shell": true }, "git": { "autoCommit": false, "protectedBranches": [] }, "shell": { "timeoutMs": 120000, "maxOutputBytes": 102400 }, "context": { "maxTokens": 100000, "compactThreshold": 0.75, "reserveTokens": 4500, "keepRecentMessages": 6 }, "approval": { "mode": "prompt" }, "index": { "enabled": true, "embedder": "fastembed", "store": "auto", "maxFileBytes": 1048576, "chunk": { "windowLines": 60, "overlapLines": 15 }, "search": { "defaultK": 8, "tokenBudget": 1500, "maxSnippetLines": 40 } }, "lsp": { "enabled": false, "servers": {}, "startupTimeout": 15000, "requestTimeout": 10000, "maxServers": 4, "idleTimeout": 300000, "maxResults": 100 }, "checkpoint": { "enabled": true, "retention": 10 }, "sessions": { "enabled": true, "retention": 50, "maxAgeDays": 30 }, "subagent": { "maxDepth": 1, "maxConcurrency": 3, "defaultBudget": { "maxIterations": 10, "maxTokens": 32000 } }, "jobs": { "enabled": false, "maxJobs": 5, "logBufferLines": 1000, "logFileLines": 20000 }, "test": { "maxIterations": 4, "captureBytes": 65536 }, "sandbox": { "enabled": false, "image": "node:20-bookworm-slim", "network": "none", "memory": "512m", "pids": 512, "cpus": 1, "mounts": [] }, "hooks": { "enabled": false, "trustPrompt": true }, "routing": { "map": {} }, "memory": { "enabled": true, "maxRecallTokens": 1000 }, "usage": { "enabled": true, "retention": 50 }, "mcp": { "enabled": false, "servers": {}, "startupTimeout": 15000, "requestTimeout": 30000, "maxToolsPerServer": 32, "maxDescriptionChars": 1024, "maxSchemaBytes": 8192 }, "web": { "enabled": false, "provider": "tavily", "apiKeyEnv": "TAVILY_API_KEY", "maxResults": 5, "snippetMaxChars": 500, "fetchMaxBytes": 524288, "timeoutMs": 15000, "maxRedirects": 3, "allowPrivateHosts": false }, "logLevel": "info" } ``` Keys with no default appear only once you set them, such as `git.defaultBase`, `shell.executable`, `shell.dialect`, `test.command`, `routing.default`, `subagent.defaultBudget.timeoutMs`, `sandbox.timeout`, and `usage.prices`. Until then, `cruxy config get` on one of them fails with `CRUXY_E_CONFIG_KEY_UNKNOWN`, exit `2`. ================================================================================ Page: Projects, permissions, and context URL: https://learn.cruxyai.com/docs/en/cruxy-code/projects-and-context Markdown: https://learn.cruxyai.com/docs/en/cruxy-code/projects-and-context.md ================================================================================ # Projects, permissions, and context How the cruxy CLI scopes work to a project, what asks for your approval, what stays on your machine, and what it sends to the Cruxy API. The CLI works inside one project directory, reads it through a fixed set of tools, and asks before it changes anything. The sections below cover each part of that, and list exactly what leaves your machine on each request. ## The project root The directory you start `cruxy` in is the project root. File tools resolve every path against it and refuse a path that leaves it, whether through `../`, an absolute path elsewhere, or a symlink that points outside. A refused path fails with `CRUXY_E_PATH_ESCAPE`. Shell commands run with the project root as their working directory. To work across more than one directory, declare each as a root: ```bash cruxy run --root api=../api --root web=../web "rename the shared User type" ``` The first root is the primary one. Reads search every root. Writes reach every root when checkpoints are on, each root with its own checkpoint, and only the primary root when they are off. MCP servers load from the primary root only. In a session, `/add-root <name> <path>` checks a new root and prints the `--root` flag to relaunch with; the root becomes active only after you relaunch, and it starts untrusted. ## Project instructions The CLI reads `CRUXY.md` from the project root into every turn, or `AGENTS.md` when there is no `CRUXY.md`. It reads the first 32 KB and marks the rest as truncated. It does not look in parent directories for these files. `cruxy init` and `/init` write a starter `CRUXY.md`, and `/reload` re-reads it in a running session. ## How it reads the codebase The agent reads through tools. These are available by default: | Tool | Does | | --- | --- | | `read_file`, `list_files`, `glob` | Read a file, list a directory, match paths. | | `grep_files` | Search file contents. | | `git_status` | Read the repository's status. | | `search_codebase` | Semantic search over the local index. | | `list_skills`, `load_skill` | Find and load skills. | | `write_file`, `edit_file`, `apply_patch` | Change files. `tools.fileEdit: false` removes all three. | | `run_command`, `run_tests` | Run shell commands and tests. `tools.shell: false` removes both. | | `create_pull_request` | Open a pull request. | Some tools exist only when you turn them on: `remember` with local memory (on by default), the language-server tools with `lsp.enabled`, `web_search` and `web_fetch` with `web.enabled`, MCP server tools with `mcp.enabled` and a trusted server, `spawn_subagent` and `spawn_subagents` while `subagent.maxDepth` is above `0` (it is `1` by default), and `run_in_background` with `jobs.enabled`. ### Semantic search `search_codebase` reads from a local index that the CLI builds on your machine: - **Embeddings are computed locally.** The embedding runtime is not part of the install: `cruxy index --install` downloads it into `~/.cruxy/runtime/embedder` after telling you what it fetches, and the model is downloaded from `huggingface.co` once and cached in `~/.cruxy/models`. - **The index lives in the project,** at `.cruxy/index.db`, on Node.js 22.13 or later. On older Node.js it is kept in memory for the session. - **It skips files you would not want indexed:** anything matched by `.gitignore` or `.cruxyignore`, the `.git`, `node_modules`, and `.cruxy` directories, binary files, files over `index.maxFileBytes` (1 MB), and secret-bearing files such as `.env*`, SSH private keys, `.pem` and `.key` files, `.npmrc`, `.netrc`, and `.aws/credentials`. The secret-file rule applies to the index and to checkpoints. It does not stop `read_file`: a file the agent reads is sent to the API like any other tool result. ## Permissions Every action that changes something passes one approval gate before it runs, and the gate fails closed. - **Read-only tools never ask.** - **File writes, edits, and patches** show a diff preview and ask. A patch that deletes a file is marked destructive. - **Shell commands and test runs** show the command and ask. - **Pull requests, rollbacks, and MCP tool calls** show what will happen and ask. - **Without a terminal,** the gate cannot ask, so the first such action ends the run with `CRUXY_E_APPROVAL_REQUIRED` and exit `10`. It never approves on its own. At a prompt, `a` grants a standing permission for the rest of the session. The grant is narrow: for a shell command or test run, the same command in the same root; for a file change, the common directory of the changed files, or the one file when it sits directly in the project root. Some actions offer no standing grant, such as a command that uses shell operators. Irreversible actions, MCP calls among them, cannot be granted and always ask. `/permissions` lists what now runs without asking, and `/permissions revoke <n>` drops one. ### Irreversible actions An action the run's checkpoint cannot undo is marked irreversible, and it always asks, in every mode. That includes: - Commands that reach beyond the working tree, such as `curl`, `wget`, `ssh`, `scp`, `rsync`, `npx`, `bunx`, `pnpx`, `gh`, `docker`, `kubectl`, `terraform`, and the `aws`, `gcloud`, and `az` CLIs. - Commands that run with other privileges or change the machine, such as `sudo`, `su`, `systemctl`, `shutdown`, and `dd`. - Any `git` command except read-only ones such as `status`, `diff`, `log`, and `show`, because the checkpoint does not capture refs, the index, or the stash. - Package-manager commands other than `run` and `test`, such as `npm install` or `pnpm add`. - Commands that change what a snapshot does not record, such as `chmod`, `chown`, and `ln`. - Commands with a path argument that resolves outside the project root. - Commands that use shell features the CLI cannot analyze. - File writes, edits, and patches the checkpoint cannot restore: secret-bearing files, anything under the project root's `.git/`, `node_modules/`, or `.cruxy/`, `*.tfstate`, local database files, `*.local.*` files, targets outside the project root, and changes with no target the CLI can resolve. - Opening a pull request, MCP tool calls, and rollbacks. ### Session modes The mode sets how much runs without asking. Shift+Tab cycles through the modes in the full-screen session, and `/mode <name>` sets one. `cruxy run --plan`, or `agent.planMode: true`, starts in `plan`. | Mode | What it does | | --- | --- | | `manual` | Every action asks first. The default. | | `auto-approve` | Reversible actions run without asking. Irreversible ones still ask. | | `plan` | The agent proposes a plan for your approval, then asks before each action. | | `full-auto` | The agent proposes a plan, then runs it without asking. Irreversible actions still ask. | There is no flag or config key that starts a new session in `auto-approve` or `full-auto`, and `approval.mode` accepts only `prompt`. A session resumed with `--resume` comes back in the last mode you switched to during it. ### Checkpoints and rollback Before a turn's first approved change (a file change, shell command, test run, or pull request), the CLI snapshots the working tree, leaving out gitignored files and the secret-bearing files listed above. Each checkpoint's record lives in `.cruxy/checkpoints`. In a git repository the file contents go into git's object database without touching your branch, index, or stash; elsewhere they are copied into `.cruxy/checkpoints` too. `cruxy rollback` and `/undo-last` restore a snapshot after showing you what will change. A checkpoint covers working-tree files only: commits, pushes, and pull requests made during a run stay. ### Sandbox `cruxy run --sandbox`, or `sandbox.enabled: true`, runs shell and test commands in a container through Docker, with no network by default (`sandbox.network: none`). If the container runtime is not available, the run fails with `CRUXY_E_SANDBOX_UNAVAILABLE` rather than running on your machine. ### Hooks, MCP servers, and project memory A repository can carry hooks, MCP server config, and project memory written by someone else, so none of them runs until you trust it for that repository: `cruxy hooks trust <path>`, `cruxy mcp trust`, and `cruxy memory trust`. Trust decisions are stored in `~/.cruxy`, never in the repository, so a clone carries none. Hooks, MCP, and web access are off by default. An MCP server you trust runs its code on your machine with your full privileges, and is not sandboxed. A changed MCP config must be trusted again, and each of its tool calls still asks for approval. ## What it sends to the Cruxy API Every request goes to `cruxy.gatewayUrl`, by default `https://api.cruxy.ai`. | Request | When | | --- | --- | | `POST /api/v2/chat` | Every model turn. Also when the CLI compacts history, writes commit and pull request text, and checks a key pasted into `cruxy login --paste`. | | `GET /api/v1/limits` | At the start of each turn, in the background, to keep the session's budget current; after a successful reading, at most once every 15 seconds. Also for `cruxy limits`. | | `POST /api/v1/device/code`, `POST /api/v1/device/token` | During device login. | | `DELETE /api/v1/me/key` | `cruxy logout`, to revoke the saved credential. | Each chat request carries these headers: `Authorization: Bearer <key>`, `Cruxy-Client: cli/<version>`, `Cruxy-Version: 2026-09-26`, and an `Idempotency-Key` that is new for each request and the same on its retries. Its body has `model`, `messages`, `stream: true`, `max_tokens` (from `model.maxTokens`), `temperature` (from `model.temperature`), `tools`, and the `memory` and `rules` fields described in [Gateway memory and rules](#gateway-memory-and-rules). It sends no vault fields. `messages` holds: - **A system prompt** with the CLI's operating instructions; your working directory's absolute path, platform, today's date, and the model; the git branch and whether it has uncommitted changes; the names of the available tools; your `CRUXY.md` or `AGENTS.md`; and any recalled local memory. - **The conversation:** your messages, the model's replies, and every tool call with its result. Tool results include the contents of files the agent read, search results, and command output up to `shell.maxOutputBytes`. `tools` holds the name, description, and parameter schema of each available tool, including MCP server tools. Once the conversation passes `context.compactThreshold` of `context.maxTokens`, the CLI sends the older part in a separate chat request to be summarized, and replaces it with the summary. `/compact` does the same on demand. The CLI does not mask secrets before sending them; it only keeps them out of gateway memory capture, as described in [Gateway memory and rules](#gateway-memory-and-rules). If one lands in the conversation, `/redact` masks the secrets it recognizes so later requests no longer carry them. It does not change requests already sent, or the session log on disk. ### Gateway memory and rules The gateway can recall your saved memory into a turn, capture new memory from it, and add your organization's standing rules to it. The CLI states all three on every chat request in a session, so what happens follows your config and not the kind of key you use: | Setting | Default | Sent as | | --- | --- | --- | | `cruxy.memory.recall` | `true` | `memory.recall` | | `cruxy.memory.capture` | `false` | `memory.capture` | | `cruxy.rules` | `true` | `rules` | Capture is off by default in coding sessions, because a coding turn carries whatever the agent read: file contents, command output, and search results. For one run, `--no-memory` turns recall and capture off, and `--memory-capture` turns capture on with recall as configured. Both flags work on `cruxy` and `cruxy run`, and passing both fails with `CRUXY_E_USAGE`. The run header prints the result as `gateway: memory recall on, capture off; rules on`, and `/status` shows the same. With capture on, a request is still sent with capture off when it carries a secret: a secret-named path in a tool call, such as `.env*`, SSH private keys, `*.pem`, `*.key`, `.npmrc`, `.netrc`, `.pgpass`, or `.aws/credentials`, or secret-shaped content anywhere in the request, such as a private key, a provider token, a JWT, or `secret = <long value>`. The whole request is checked, so capture stays off until `/clear`, compaction, or `/redact` removes the secret. This check is a backstop: it catches known names and shapes, not every secret. Recall is not affected. Some requests send memory off whatever the config says: history compaction, commit and pull request text, and the key check in `cruxy login --paste`. Every chat request pins `Cruxy-Version: 2026-09-26`. A gateway too old to honor `memory.capture: false` refuses the pinned request instead of capturing. See [Memory](/docs/en/build/memory) and [Standing rules](/docs/en/build/rules) for what each feature does. ### Other places it connects to | Destination | When | | --- | --- | | The npm registry | `cruxy index --install`, through your npm config. | | `huggingface.co` | The first time semantic search needs the embedding model. | | GitHub's API and your git remote | `cruxy pr` and `create_pull_request`, which push a branch and open the pull request. | | Tavily | `web_search`, when `web.enabled` is on. | | The page being fetched | `web_fetch`, when `web.enabled` is on. Private and loopback hosts are refused unless `web.allowPrivateHosts` is on. | | Your MCP servers | When `mcp.enabled` is on and you trust them. | ## What stays on your machine | What | Where | | --- | --- | | Your credential | `~/.cruxy/credentials.json`, owner-only. | | Global config | `~/.cruxy/config.json`. | | Session logs | `~/.cruxy/projects/`, one folder per project, pruned by `sessions.retention` and `sessions.maxAgeDays`. | | Usage records | `~/.cruxy/usage/runs.json`. They are never sent anywhere. | | Local memory | `~/.cruxy/memory/entries.json` for you, and `.cruxy/memory/entries.json` in the project. | | Trust decisions | `~/.cruxy/trust.json`, `~/.cruxy/memory-trust.json`, and `~/.cruxy/mcp-trust.json`. | | Codebase index | `.cruxy/index.db` in the project. | | Checkpoints | `.cruxy/checkpoints` in the project, with file contents in git's object database inside a git repository. | | Embedding runtime and model | `~/.cruxy/runtime/embedder` and `~/.cruxy/models`. | ## Local memory The CLI keeps its own memory, separate from the gateway's. The agent saves a note with the `remember` tool, and the CLI refuses a note that looks like a secret. At the start of a session it adds the saved notes to the system prompt, up to `memory.maxRecallTokens`. Notes in your user scope are recalled in every project. Notes in a project's `.cruxy/memory` are recalled only after you run `cruxy memory trust`, because a cloned repository can bring them. `cruxy memory list`, `cruxy memory forget <id>`, and `cruxy memory clear` manage these local notes. They do not touch the gateway's memory; see [Gateway memory and rules](#gateway-memory-and-rules). ================================================================================ Page: Troubleshoot the CLI URL: https://learn.cruxyai.com/docs/en/cruxy-code/troubleshooting Markdown: https://learn.cruxyai.com/docs/en/cruxy-code/troubleshooting.md ================================================================================ # Troubleshoot the CLI Read a cruxy error and its code, then fix the sign-in, config, network, approval, and setup failures you are most likely to hit. Every failure the CLI reports has the same shape, and every one carries a stable code you can search for. Start with the code, then find its section below. For every code and its exit status, see [CLI command reference](/docs/en/cruxy-code/commands#exit-codes). ## Read an error An error prints a title, the cause when the CLI knows it, the next steps, and the code in brackets: ```text no API key for provider "cruxy" Cause: no key in the environment (CRUXY_API_KEY) or the credentials store Next steps: → run `cruxy login` to set a key interactively (saved to ~/.cruxy, owner-only) → or export CRUXY_API_KEY=… in your shell (env always wins; never written to config) [CRUXY_E_AUTH_MISSING_KEY] ``` Errors go to stderr, and the process exits with the code's category status, so a script can branch on it. To see the underlying error and its stack, add `--verbose`, or set `CRUXY_LOG_LEVEL=debug` or `DEBUG=1`: ```bash cruxy --verbose run "fix the failing test" ``` ## No API key `CRUXY_E_AUTH_MISSING_KEY`, exit `4`: "no API key for provider "cruxy"". Neither `CRUXY_API_KEY` nor the credential store holds a key. - In a terminal, run `cruxy login`. - In CI or a script, set `CRUXY_API_KEY`. A first run in a terminal starts sign-in on its own. A run without a terminal, or after setup was already completed once, reports this error instead. ## Credentials rejected `CRUXY_E_AUTH_INVALID`, exit `4`: "the provider rejected your credentials". The gateway answered `401` or `403`. - If `CRUXY_API_KEY` is set, check it first: it wins over the saved credential. - Otherwise run `cruxy login` to sign in again and replace the saved credential. A pasted key that has expired, or a key that was revoked, also lands here: the gateway gives them the same answer as a wrong key. ## API keys need a paid plan `CRUXY_E_PAID_PLAN_REQUIRED`, exit `22`: "API keys need a paid Cruxy plan. Upgrade at https://cruxy.ai/settings/billing, or run `cruxy login` to use your account's allowance." The key is genuine, but its account's plan has no API access. A run, `cruxy limits`, and `cruxy login --paste` report it, and `cruxy login --paste` does not save such a key. - Move to a paid plan, or - Run `cruxy login`. The credential it saves draws on your plan's own allowance, on every plan. ## Login expired `CRUXY_E_AUTH_EXPIRED`, exit `4`: "your cruxy login has expired". The device-login credential reached the expiry recorded when it was issued, 90 days after issue. Run `cruxy login` for a new one. In the 7 days before expiry, each run and each session start prints a notice that your sign-in expires soon. Signing in again before then avoids the failure. When a one-shot run fails this way with an expired device credential still saved, check `CRUXY_API_KEY` too: the check reads the saved credential's expiry even when the variable is the key in use. ## Login succeeded but nothing changed `cruxy login` saves the new credential, but `CRUXY_API_KEY` still wins over it. The login warns about this when the variable is set. Unset `CRUXY_API_KEY` to use the saved credential: ```bash unset CRUXY_API_KEY ``` ## Sign-in does not finish | The CLI says | What to do | | --- | --- | | cruxy login is interactive | Run it in a terminal, or set `CRUXY_API_KEY`. It exits `1`. | | the sign-in was declined in the browser. | Run `cruxy login` again and approve. | | the code expired before it was approved. | Run `cruxy login` for a new code, and approve before it expires. | | that sign-in could not be completed. | Run `cruxy login` to start over. | | couldn't reach the gateway to sign in. | Check your connection and `cruxy config get cruxy.gatewayUrl`, then try again. | If you cannot approve in a browser on any machine, use `cruxy login --paste` with an existing key. See [Sign in from the CLI](/docs/en/cruxy-code/authentication). ## The credential cannot be secured `CRUXY_E_CREDENTIALS_UNPROTECTED`, exit `4`: the CLI refuses to write a credential it cannot make readable only by you, or to read one from a store other users can read when it cannot make that store owner-only. This happens on filesystems without owner-only permissions, such as FAT or exFAT. - Set `CRUXY_API_KEY` instead. The environment is never written to disk. - Or keep your home directory on a filesystem that supports owner-only permissions, such as NTFS. When the CLI finds a store other users can read and can fix it, it makes the store owner-only and warns once that anything in it may already have been copied. Rotate what it held: run `cruxy login` for a new key, revoke the old one in the Console, and issue any MCP tokens stored there again. ## Cannot reach the gateway `CRUXY_E_GATEWAY_UNREACHABLE`, exit `5`: "could not reach the model gateway". 1. Check your connection. 2. Check the URL with `cruxy config get cruxy.gatewayUrl`. The default is `https://api.cruxy.ai`. 3. Retry. The CLI already retried transient failures `cruxy.maxRetries` times. A stream that delivers nothing for `cruxy.streamIdleTimeoutMs` (90 seconds by default) counts as dead. It is retried only if it died before its first token. If you see a warning that `cruxy.gatewayUrl` is the legacy gateway host, set it to `https://api.cruxy.ai` or remove it; the CLI already uses the current host. ## The gateway URL is not https `CRUXY_E_CONFIG_INVALID`, exit `3`: "cruxy.gatewayUrl is not https, so no credential was sent". The CLI sends a credential only over `https://`, and over plain `http://` only to `localhost`, `127.0.0.1`, or `[::1]`. No request was made. Set an `https://` URL, or remove the setting to use the default: ```bash cruxy config set cruxy.gatewayUrl https://api.cruxy.ai ``` `cruxy config path` lists the config files in effect. See [Gateway URL](/docs/en/cruxy-code/configuration#gateway-url). ## Rate limited, out of budget, or overloaded | Code | Title | What to do | | --- | --- | --- | | `CRUXY_E_API_RATE_LIMIT` | rate limited by the model provider | Wait the time it names, or a moment when it names none, then retry. | | `CRUXY_E_BUDGET_EXHAUSTED` | your Cruxy budget is exhausted, or a variant naming the window or cap, such as your 12h burst budget window has nothing left, or this API key's monthly spend cap is reached | Your plan's pool, a key's spend cap, or a workspace's spend cap ran out. Wait for the reset or recovery it names; `cruxy limits` shows what is left. If it suggests `/model epos`, `epos` is still available. A larger plan raises the pool; only an org admin raises a key or workspace spend cap. `/budget` does not help. | | `CRUXY_E_SESSION_BUDGET_EXHAUSTED` | this session's budget is used up | Only the session's own `/budget` ran out. Raise it with `/budget <weighted tokens>`, or clear it with `/budget off`; `/usage` shows what the session has drawn. | | `CRUXY_E_API_OVERLOADED` | the model provider is overloaded | Retry in a few moments. | | `CRUXY_E_API` | the model provider returned an error | Retry in a moment. | All but `CRUXY_E_SESSION_BUDGET_EXHAUSTED` exit `6`; that one exits `2`. `cruxy limits` shows what is left of your plan's pool. For the gateway's side of these limits, see [Rate limits and budgets](/docs/en/build/rate-limits). ## Request rejected `CRUXY_E_API_REQUEST_REJECTED`, exit `6`: the gateway refused the request as invalid, before any model ran. The same request fails the same way every time, so retrying does not help: it points to a defect in the CLI. Report it to support@cruxyai.com with the code and the cause line, or with the code and the tool name when the title names a tool. ## Sign out does not finish `cruxy logout` keeps your credential, and you stay signed in, whenever the key was not revoked: | Code | Title | What to do | | --- | --- | --- | | `CRUXY_E_AUTH_INVALID`, exit `4` | this key is not allowed to revoke itself, so you are still signed in | A read-only or scoped key cannot revoke itself. Revoke it in the Console at https://platform.cruxy.ai/keys, then run `cruxy logout` again to remove it. | | `CRUXY_E_GATEWAY_UNREACHABLE`, exit `5` | could not reach the gateway to revoke your key, so you are still signed in | Run `cruxy logout` again once the gateway is reachable, or revoke the key in the Console and then run it again. | | `CRUXY_E_API`, exit `6` | the gateway did not revoke your key (HTTP `<status>`), so you are still signed in | Retry in a moment, or revoke the key in the Console and then run it again. | See [Sign out](/docs/en/cruxy-code/authentication#sign-out). ## Config errors | Code | Cause | What to do | | --- | --- | --- | | `CRUXY_E_CONFIG_PARSE` | A config file is not valid JSON. | Fix the syntax, or delete the file to fall back to defaults. | | `CRUXY_E_CONFIG_INVALID` | A key is unknown or a value is out of range. The cause lists each field. | Correct the fields, starting with the file it names. `cruxy config path` shows the files in effect. | | `CRUXY_E_CONFIG_NOT_FOUND` | `--config` names a file that does not exist. | Check the path, which is relative to the current directory. | | `CRUXY_E_CONFIG_KEY_UNKNOWN` | `cruxy config get` was given a key that does not exist. | Run `cruxy config list` for the keys. | The config errors exit `3`, and `CRUXY_E_CONFIG_KEY_UNKNOWN` exits `2`. One common cause of `CRUXY_E_CONFIG_INVALID` is `approval.mode`, which accepts only `prompt`; see [CLI configuration](/docs/en/cruxy-code/configuration#approval-is-not-a-setting). ## It needs a terminal | Message or code | What to do | | --- | --- | | `cruxy run needs a prompt when stdin is not a terminal` (`CRUXY_E_USAGE`, exit `2`) | Pass the task: `cruxy run "<task>"`. | | `CRUXY_E_APPROVAL_REQUIRED`, exit `10`: this action needs your approval, but cruxy is running non-interactively | Run in a terminal to approve it, or give the run a task its read-only tools can finish. | | `CRUXY_E_ROLLBACK_APPROVAL_REQUIRED`, exit `10` | Run `cruxy rollback` in a terminal. | | `CRUXY_E_INTERACTIVE_REQUIRED`, exit `2` | Run the command in a terminal. | The CLI never approves an action on its own when it cannot ask. ## The run stopped before finishing `CRUXY_E_AGENT_INCOMPLETE`, exit `20`: a one-shot run stopped before the task was done. The work so far stays in the output above the error. | Title | What to do | | --- | --- | | cruxy stopped: iteration cap reached before the task finished | Narrow the task, or raise `agent.maxIterationsOneShot`. | | cruxy stopped: token budget reached before the task finished | Narrow the task, or raise or unset `agent.maxTokensPerTurn`. | | cruxy stopped: the run was cancelled before the task finished | Run it again. | ## A path is outside the project `CRUXY_E_PATH_ESCAPE`, exit `7`: a file tool was given a path that resolves outside the project root, directly or through a symlink. Start `cruxy` in a directory that contains everything the task touches, or declare more roots with `--root`; see [Projects, permissions, and context](/docs/en/cruxy-code/projects-and-context#the-project-root). ## Semantic search is not installed `CRUXY_E_INDEX_EMBEDDER_NOT_INSTALLED`, exit `8`: "semantic code search isn't installed", or a message that the runtime is out of date or was installed for another platform. ```bash cruxy index --install ``` It shows the download size and source before it starts. Until it is installed, the agent finds code with `grep_files`. If the model download fails (`CRUXY_E_INDEX_EMBEDDER_DOWNLOAD_FAILED`) behind a proxy or firewall, allow `huggingface.co` and its download CDN; `HTTPS_PROXY` and `NO_PROXY` are honored. ## Hooks, MCP servers, or memory are not trusted | Code | Title | What to do | | --- | --- | --- | | `CRUXY_E_HOOK_UNTRUSTED` | this project defines `<n>` hooks that are not trusted | Review them with `cruxy hooks list`, then run `cruxy hooks trust <path>`. | | `CRUXY_E_MCP_UNTRUSTED` | this project's MCP servers have not been trusted | Review them with `cruxy mcp list`, then run `cruxy mcp trust .`, or set `mcp.enabled` to `false`. | Untrusted project memory is not an error: the CLI skips it and prints that project memory was found but not trusted. Review it with `cruxy memory list`, then run `cruxy memory trust .` to recall it. A changed config or changed project memory must be trusted again. ## Other setup errors | Code | Title | What to do | | --- | --- | --- | | `CRUXY_E_TEST_COMMAND_NOT_FOUND` | no test command found for this project | Set `test.command`, or add a `test` script to `package.json`. | | `CRUXY_E_SANDBOX_UNAVAILABLE` | sandbox is enabled but the docker runtime is unavailable | Install Docker and start its daemon, or drop `--sandbox` and set `sandbox.enabled` to `false`. | | `CRUXY_E_NO_SHELL` | No usable shell found to run commands | On Windows, install Git for Windows for Git Bash, or set `shell.executable`. | | `CRUXY_E_FORGE_AUTH` | no github.com token available to open a pull request | Set `GITHUB_TOKEN` to a token with `repo` scope, or run `gh auth login`. | | `CRUXY_E_STORE_LOCKED` | another cruxy is writing `<file>` | Retry in a moment. If no other cruxy is running, remove the lock file it names. | ## Unexpected internal error `CRUXY_E_INTERNAL`, exit `1`: "an unexpected internal error occurred". Run the command again with `--verbose` to see the underlying error, and report it with the code and that output to support@cruxyai.com. Never include your API key or the contents of `~/.cruxy/credentials.json` in a report. ================================================================================ Page: Cookbook URL: https://learn.cruxyai.com/docs/en/resources/cookbook Markdown: https://learn.cruxyai.com/docs/en/resources/cookbook.md ================================================================================ # Cookbook Task-shaped recipes that combine Cruxy endpoints to do a real job: retrieval, tool loops, streaming, moderation, extraction, and evals. The guides document each endpoint on its own: what `POST /api/v1/rerank` returns, how `stream` changes the chat response. The cookbook is the other half: recipes that wire endpoints together to finish a real job. Each one runs end to end against `https://api.cruxy.ai` and reads from `CRUXY_API_KEY` in the environment. - [Retrieval-augmented generation](/docs/en/resources/cookbook/rag): Embed a corpus, rank it by cosine, reorder the shortlist with rerank, then ground a chat answer in the winners. - [Tutorial: build a tool-using agent](/docs/en/build/tool-agent): Run the full round-trip: send tools, execute the calls the model returns, feed results back by id, loop until it stops. - [Streaming chat in the browser](/docs/en/resources/cookbook/streaming-ui): Proxy the SSE stream past your key, render deltas without jank, and detect a stream that breaks after the 200. - [Moderation gate](/docs/en/resources/cookbook/moderation-gate): Screen input with cruxy-guard before it reaches chat, and branch on flagged, never on the uncalibrated scores. - [Structured JSON extraction](/docs/en/resources/cookbook/structured-extraction): Pick a tier that supports structured output, send a JSON schema in response_format, and validate what comes back. - [Retrieval over vault files](/docs/en/resources/cookbook/vault-retrieval): List a vault's files, download the text ones, rank their passages with embeddings and rerank, and ground a chat answer. - [Compare two prompt versions with evals](/docs/en/resources/cookbook/prompt-eval-loop): Build an eval suite per prompt version from the same cases, run both on one tier, and compare the pass counts. ## What counts as a recipe Every recipe here combines at least two endpoints, or solves a problem a single-endpoint guide cannot. Retrieval chains embeddings, rerank, and chat; the moderation gate puts one endpoint in front of another; the tool loop and the streaming UI each turn one endpoint into a working control flow the reference shape only hints at. When you need the exact fields instead, the guides, starting with [Chat](/docs/en/build/chat), document each endpoint once. The tool loop lives with the tool-calling pages in the Docs tab, next to [Define tools](/docs/en/build/tools) and [Handle tool calls](/docs/en/build/tool-calls). ================================================================================ Page: Retrieval-augmented generation URL: https://learn.cruxyai.com/docs/en/resources/cookbook/rag Markdown: https://learn.cruxyai.com/docs/en/resources/cookbook/rag.md ================================================================================ # Retrieval-augmented generation Embed a corpus, rank it by cosine, reorder the shortlist with rerank, then ground a chat answer in the winning passages. Retrieval-augmented generation answers a question from your own documents: find the passages that bear on the question, then hand them to a chat model as context. This recipe chains three endpoints: [Embeddings](/docs/en/build/embeddings) for a first-pass search, [Rerank](/docs/en/build/rerank) to sharpen the shortlist, and [Chat](/docs/en/build/chat) to write the answer. ## 1. Index the corpus Split your source material into chunks and embed them once. Store each vector beside the text it came from; you embed the corpus at index time, not per query. ```ts const BASE = 'https://api.cruxy.ai' const auth = { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', } async function embed(input: string[]): Promise<number[][]> { const res = await fetch(`${BASE}/api/v1/embeddings`, { method: 'POST', headers: auth, body: JSON.stringify({ model: 'cruxy-embed', input }), }) const { data } = await res.json() // One entry per input; data[i].index is the input's position. Sort by it // so the returned vectors line up with `input`, whatever order they arrive. return data.sort((a, b) => a.index - b.index).map((d) => d.embedding) } const chunks = [ 'The gateway resolves each public tier to an upstream model on the server.', 'Rerank scores every document against the query and returns them best-first.', 'Embeddings turn text into a vector you can compare with cosine similarity.', 'A bearer key authenticates every request against api.cruxy.ai.', // ...the rest of your corpus, one string per chunk ] const vectors = await embed(chunks) // persist these alongside `chunks` ``` ## 2. Retrieve by cosine Embed the query with the same model, then score it against every stored vector. Cosine similarity ranks the whole corpus cheaply; keep the top handful as candidates. ```ts function cosine(a: number[], b: number[]): number { let dot = 0 let na = 0 let nb = 0 for (let i = 0; i < a.length; i++) { dot += a[i] * b[i] na += a[i] * a[i] nb += b[i] * b[i] } return dot / (Math.sqrt(na) * Math.sqrt(nb)) } const query = 'How does the gateway decide which model runs?' const [queryVec] = await embed([query]) const CANDIDATES = 20 const shortlist = chunks .map((text, i) => ({ text, score: cosine(queryVec, vectors[i]) })) .sort((a, b) => b.score - a.score) .slice(0, CANDIDATES) ``` ## 3. Rerank the shortlist Cosine over embeddings is fast but coarse. Send the shortlist to rerank, which scores each candidate against the query directly and returns them ordered by relevance. Cap the result to the few passages you will actually pass on. ```ts const documents = shortlist.map((c) => c.text) const res = await fetch(`${BASE}/api/v1/rerank`, { method: 'POST', headers: auth, body: JSON.stringify({ model: 'cruxy-rerank', query, documents, top_n: 5 }), }) const { results } = await res.json() // Each result's `index` points into `documents` (the shortlist you sent), // NOT the original `chunks`. Map through `documents` to recover the text. const context = results.map((r) => documents[r.index]) ``` ## 4. Generate the answer Give the reranked passages to chat as context and constrain the model to answer from them. `stream: false` returns the reply as the top-level `message`. ```ts const res = await fetch(`${BASE}/api/v1/chat`, { method: 'POST', headers: auth, body: JSON.stringify({ model: 'canto', stream: false, messages: [ { role: 'system', content: 'Answer only from the provided context. If the answer is not in it, say you do not know.', }, { role: 'user', content: `Context:\n${context.join('\n\n')}\n\nQuestion: ${query}`, }, ], }), }) const { message } = await res.json() console.log(message.content) ``` ## Why rerank after vector search, not instead of it The two retrieval endpoints trade off differently, so the pipeline uses both. Embeddings compress a passage into a single vector, which makes cosine search cheap enough to run over a whole corpus, but that compression blurs fine distinctions, so the top cosine hit is not always the most relevant passage. Rerank scores each document against the query directly, which is far more discriminating, but it reads every candidate on every call, so running it over the full corpus does not scale. Chaining them keeps each in its lane: embeddings recall a broad shortlist cheaply, rerank orders that shortlist precisely. Rerank comes *after* vector search, never *instead of* it, because it ranks a candidate set you hand it; it does not index your corpus or retrieve from one. ## Mapping indices back Both retrieval endpoints return positions, not text, and they point into different arrays. An embedding's `data[i].index` is the position in the `input` you sent to `/embeddings`. A rerank result's `index` is the position in the `documents` you sent to `/rerank`: here, the shortlist, not the original corpus. Map each rerank `index` through `documents`; mapping it through `chunks` returns the wrong passage whenever the shortlist reordered the corpus, which is almost always. The [Rerank](/docs/en/build/rerank) guide flags this same trap for the single-endpoint case. ## Next steps - [Embeddings](/docs/en/build/embeddings): the vectors and the batch input shape. - [Rerank](/docs/en/build/rerank): the score ordering and `top_n`. - [Chat](/docs/en/build/chat): request options and the flattened response. ================================================================================ Page: Streaming chat in the browser URL: https://learn.cruxyai.com/docs/en/resources/cookbook/streaming-ui Markdown: https://learn.cruxyai.com/docs/en/resources/cookbook/streaming-ui.md ================================================================================ # Streaming chat in the browser Consume the OpenAI-style SSE stream in a browser, render deltas without jank, and recover when the connection breaks mid-response. A streaming chat UI reads tokens as the model writes them. This recipe proxies [Chat](/docs/en/build/chat) with `stream: true` through your own server (so the key never reaches the browser), then consumes the Server-Sent Events on the client, painting each delta as it arrives. ## 1. Proxy the stream past your key A browser must not hold `CRUXY_API_KEY`. Put a thin server route in front: it adds the bearer key, requests the stream from the gateway, and pipes the SSE body straight through to the client unchanged. ```ts // server route, e.g. POST /api/chat export async function POST(req: Request) { const { prompt } = await req.json() const upstream = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'canto', stream: true, messages: [{ role: 'user', content: prompt }], }), }) // Forward the raw event stream; the browser reads the same chunks the // gateway emitted, terminated by `data: [DONE]`. return new Response(upstream.body, { headers: { 'Content-Type': 'text/event-stream' }, }) } ``` ## 2. Consume the SSE in the browser Read the response body as a stream, split it on the blank line between events, and pull each token from `choices[0].delta.content`. Tokens land in a buffer that a single `requestAnimationFrame` flushes to the DOM, so a fast stream repaints once per frame instead of once per token. ```ts async function streamInto(el: HTMLElement, prompt: string) { const res = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt }), }) if (!res.ok || !res.body) throw new Error(`chat failed: ${res.status}`) const reader = res.body.getReader() const decoder = new TextDecoder() let buffer = '' let pending = '' let frame = 0 let done = false // Batch DOM writes: deltas accumulate in `pending`, one rAF flush paints. const flush = () => { if (pending) { el.textContent += pending pending = '' } frame = 0 } const schedule = () => { if (!frame) frame = requestAnimationFrame(flush) } try { while (true) { const { value, done: streamDone } = await reader.read() if (streamDone) break buffer += decoder.decode(value, { stream: true }) const events = buffer.split('\n\n') buffer = events.pop() ?? '' // keep the trailing partial event for (const event of events) { const line = event.replace(/^data: /, '').trim() if (!line) continue if (line === '[DONE]') { done = true continue } const chunk = JSON.parse(line) const delta = chunk.choices?.[0]?.delta?.content if (delta) { pending += delta schedule() } } } } catch { // The stream broke after the 200 arrived; see "handling mid-stream // failure" below. Surface what streamed so far, then let the caller retry. el.dataset.error = 'stream interrupted' } finally { if (frame) cancelAnimationFrame(frame) flush() // paint whatever landed before the stream ended } // A clean HTTP close is not the same as a complete answer: only `[DONE]` // marks completion. No sentinel means the response was cut short. if (!done) el.dataset.incomplete = 'true' } ``` ## The streaming shape differs from non-streaming A streaming chunk is not shaped like the non-streaming reply. With `stream: true`, each `chat.completion.chunk` carries an OpenAI `choices[]` array and the token lives at `choices[0].delta.content`. With `stream: false`, the gateway flattens the reply to a top-level `message` and there is no `choices[]` at all. Code written against the flattened `message.content` will not find a token in a stream chunk, and vice versa; [Chat](/docs/en/build/chat#stream-true) documents both shapes side by side. The first chunk is a role primer whose `delta.content` is an empty string; the `if (delta)` guard skips it. The final chunk before `[DONE]` carries a `usage` object and an empty `choices` array, which the optional chaining on `choices?.[0]` skips; read `usage` there if you want token counts and cost for the call. [Streaming](/docs/en/build/streaming) documents every frame in order. ## Rendering without jank The reader hands you tokens faster than a browser needs to repaint. Writing to the DOM on every delta forces a layout on each one and the text visibly stutters. Accumulating deltas in a buffer and flushing once per `requestAnimationFrame` collapses a burst of tokens into a single repaint, so the text advances smoothly however fast the stream runs. ## Handling mid-stream failure The response status resolves before any token streams. Once the gateway has sent `200`, a later failure (a dropped connection, an upstream cut) cannot change that status; it surfaces as `reader.read()` throwing or as the stream ending. Two signals cover it: the `try/catch` catches a thrown read, and the `[DONE]` sentinel confirms completion. A stream that ends without `[DONE]` delivered a partial answer even though nothing threw, so this recipe marks it incomplete. Treat either signal as a cue to keep the partial text and offer a retry. ## Next steps - [Streaming](/docs/en/build/streaming): the frame order and how to detect a failed stream. - [Chat](/docs/en/build/chat): the full request options and both response shapes. - [Tutorial: build a tool-using agent](/docs/en/build/tool-agent): drive multi-turn tool use. - [Errors](/docs/en/reference/errors): the `400`, `401`, and `429` bodies. ================================================================================ Page: Moderation gate URL: https://learn.cruxyai.com/docs/en/resources/cookbook/moderation-gate Markdown: https://learn.cruxyai.com/docs/en/resources/cookbook/moderation-gate.md ================================================================================ # Moderation gate Screen user input with cruxy-guard before it reaches chat, and act on the flagged boolean, not the uncalibrated category scores. A moderation gate runs [Moderations](/docs/en/build/moderations) in front of [Chat](/docs/en/build/chat): classify the input first, and only call the model if it comes back clean. This recipe wires the two together and shows the one decision the guard's response forces you to get right. ## The gate Classify the prompt with `cruxy-guard`. If the single result is `flagged`, refuse before spending a chat call; otherwise pass the prompt through to chat. ```ts const BASE = 'https://api.cruxy.ai' const auth = { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', } async function screen(text: string): Promise<{ flagged: boolean; requestId: string }> { const res = await fetch(`${BASE}/api/v1/moderations`, { method: 'POST', headers: auth, body: JSON.stringify({ model: 'cruxy-guard', input: text }), }) const body = await res.json() return { flagged: body.results[0].flagged, // Moderations carries no cruxy block; the request id is the top-level // `id`, prefixed "modr-". Strip the prefix to get the bare request_id. requestId: body.id.replace(/^modr-/, ''), } } async function guardedChat(prompt: string): Promise<string> { const gate = await screen(prompt) if (gate.flagged) { console.warn(`blocked input, request_id=${gate.requestId}`) return 'This request was blocked by the content filter.' } const res = await fetch(`${BASE}/api/v1/chat`, { method: 'POST', headers: auth, body: JSON.stringify({ model: 'canto', stream: false, messages: [{ role: 'user', content: prompt }], }), }) const { message } = await res.json() return message.content } ``` ## Branch on flagged, never on the scores The guard returns `category_scores` alongside the `categories` booleans, and it is tempting to threshold them. Do not: ```ts // WRONG: category_scores is not a calibrated probability. if (result.category_scores.violence > 0.7) block() ``` The guard model emits labels, not likelihoods, so every value in `category_scores` is exactly `1.0` or `0.0`, the same bit as the matching boolean in `categories`, written as a number. A threshold like `0.7` buys nothing: nothing ever lands between the two values, and reading a score as confidence reads a precision that is not there. Decide on `flagged` for an any-category gate, or on a specific `categories[name]` boolean when you only want to block one kind of content. The [Moderations](/docs/en/build/moderations#category_scores-is-binary) guide carries the same caveat for the endpoint on its own. ## Screening a batch or the output `input` also accepts an array, and `results` returns one entry per input in order; screen every message in a conversation with one call rather than one call each. The gate reads left to right, so you can run the same `screen` over the model's reply before you show it, and refuse on the way out as well as on the way in. ## Next steps - [Moderations](/docs/en/build/moderations): the categories, the response, and the binary-scores caveat. - [Chat](/docs/en/build/chat): the endpoint the gate protects. - [Errors](/docs/en/reference/errors): the `400`, `401`, and `429` bodies. ================================================================================ Page: Structured JSON extraction URL: https://learn.cruxyai.com/docs/en/resources/cookbook/structured-extraction Markdown: https://learn.cruxyai.com/docs/en/resources/cookbook/structured-extraction.md ================================================================================ # Structured JSON extraction Turn free text into JSON that matches your schema: pick a tier that supports structured output, send response_format, and validate the result. Extraction turns free text, such as a support email, into a record your code can use. Asking for JSON in prose gets you JSON most of the time. Sending a schema in `response_format` constrains the output to it. This recipe chains [Models](/docs/en/reference/models), to find a tier that supports structured output, and [Chat](/docs/en/build/chat), to run the extraction. ## The request The central call is one chat request with a `json_schema`: ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "saga", "stream": false, "messages": [ { "role": "system", "content": "Extract the ticket fields from the email." }, { "role": "user", "content": "Hi, I was charged twice for order 8841 on 3 November. Please refund one. Priya" } ], "response_format": { "type": "json_schema", "json_schema": { "name": "ticket", "schema": { "type": "object", "properties": { "category": { "type": "string", "enum": ["billing", "shipping", "account", "other"] }, "order_id": { "type": "string", "nullable": true }, "customer_name": { "type": "string", "nullable": true }, "summary": { "type": "string", "maxLength": 200 } }, "required": ["category", "order_id", "customer_name", "summary"], "additionalProperties": false } } } }' ``` ## The full recipe The script below reads the tier catalog, picks a tier whose `supports_structured_output` is `true`, runs the extraction, and checks the result before trusting it. ```ts title="TypeScript" const BASE = 'https://api.cruxy.ai' const auth = { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', } type Ticket = { category: 'billing' | 'shipping' | 'account' | 'other' order_id: string | null customer_name: string | null summary: string } const CATEGORIES = ['billing', 'shipping', 'account', 'other'] const ticketSchema = { type: 'object', properties: { category: { type: 'string', enum: CATEGORIES }, order_id: { type: 'string', nullable: true }, customer_name: { type: 'string', nullable: true }, summary: { type: 'string', maxLength: 200 }, }, required: ['category', 'order_id', 'customer_name', 'summary'], additionalProperties: false, } // 1. Find a tier that honours response_format. Read it; do not hardcode it. async function structuredTier(preferred: string[]): Promise<string> { const res = await fetch(`${BASE}/api/v1/models`, { headers: auth }) if (!res.ok) throw new Error(`models failed: ${res.status}`) const { data } = await res.json() const supported = new Set( data .filter((m: { supports_structured_output?: boolean }) => m.supports_structured_output) .map((m: { id: string }) => m.id), ) const tier = preferred.find((id) => supported.has(id)) if (!tier) throw new Error('no preferred tier supports structured output') return tier } // 2. Run the extraction. async function extract(model: string, email: string): Promise<Ticket> { const res = await fetch(`${BASE}/api/v1/chat`, { method: 'POST', headers: auth, body: JSON.stringify({ model, stream: false, messages: [ { role: 'system', content: 'Extract the ticket fields from the email.' }, { role: 'user', content: email }, ], response_format: { type: 'json_schema', json_schema: { name: 'ticket', schema: ticketSchema }, }, }), }) if (!res.ok) { const err = await res.json() // 422 structured_output_unsatisfied: the output did not match the schema. // The attempt was billed, and a retry may pass. Every other code here // describes the request, and fails the same way until you change it. throw new Error(`${res.status} ${err.code}: ${err.error} (request_id ${err.request_id})`) } const completion = await res.json() if (completion.finish_reason !== 'stop') { throw new Error(`extraction ended with finish_reason ${completion.finish_reason}`) } // 3. Parse and check in your own code as well. const ticket = JSON.parse(completion.message.content) as Ticket if (!CATEGORIES.includes(ticket.category) || typeof ticket.summary !== 'string') { throw new Error('extraction does not match the schema') } return ticket } const tier = await structuredTier(['saga', 'epos', 'canto']) const ticket = await extract( tier, 'Hi, I was charged twice for order 8841 on 3 November. Please refund one. Priya', ) console.log(tier, ticket) ``` ## What the gateway guarantees - **The schema is checked first.** A schema outside the supported keywords and limits is `400` `invalid_schema` before any model call. [Schema rules](/docs/en/best-practices/prompting#schema-rules) lists them. `$ref` and `$defs` are not supported, so write the schema flat. - **A named tier is never moved.** A structured request that names a tier without support is `422` `structured_output_unsupported`. With `model: "auto"`, the router sends it only to a tier that supports it. - **A non-streaming answer is re-validated.** Output that does not conform is `422` `structured_output_unsatisfied`. It is billed, and it may pass on a retry. - **A stream is not re-validated.** The constraint is enforced upstream, and the gateway does not check the assembled output, so validate it yourself. - **Reasoning is off.** Structured output turns reasoning off for the request. ## Why validate again The gateway's check covers the schema. It does not cover what your code needs beyond the schema: that an `order_id` exists in your system, or that a date is in range. It also cannot help when the answer is cut short: a `finish_reason` of `length` means the JSON may be truncated, which is why the recipe checks for `stop` before parsing. Keep the schema small, mark every property `required`, and use `nullable` for a value the text may not contain, so the model returns `null` instead of inventing one. ## Next steps - [Prompting basics](/docs/en/best-practices/prompting): the schema rules and which tiers support structured output. - [Models](/docs/en/reference/models): `supports_structured_output` and the rest of the catalog. - [Errors and retries](/docs/en/build/errors-and-retries): which `422` to retry. ================================================================================ Page: Retrieval over vault files URL: https://learn.cruxyai.com/docs/en/resources/cookbook/vault-retrieval Markdown: https://learn.cruxyai.com/docs/en/resources/cookbook/vault-retrieval.md ================================================================================ # Retrieval over vault files Answer a question from the text files a vault holds: list them, download and chunk the text, rank with embeddings and rerank, then ask chat. A vault holds files that every member who can read it shares. This recipe answers a question from those files: it lists the vault's files, downloads the text ones, ranks their passages against the question, and asks chat to answer from the best of them. It chains the vault file calls with [Embeddings](/docs/en/build/embeddings), [Rerank](/docs/en/build/rerank), and [Chat](/docs/en/build/chat). > **Note:** The download call returns a file's raw bytes, so this recipe indexes text > files only. For a PDF or Word document, attach the file to the chat message > with `file_ids` instead, and the gateway reads its text into the turn. ## The vault calls Two calls read a vault's files: one lists them, one downloads a file's content. Both need `can_read` on the vault. ```bash title="curl" # List the files the vault holds, newest first. curl "https://api.cruxy.ai/api/v1/vaults/$VAULT_ID/files?limit=100" \ -H "Authorization: Bearer $CRUXY_API_KEY" # Download one file's raw bytes. curl https://api.cruxy.ai/api/v1/vaults/$VAULT_ID/files/$FILE_ID/content \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -o handbook.md ``` ## The full recipe ```ts title="TypeScript" const BASE = 'https://api.cruxy.ai' const vaultId = process.env.VAULT_ID const auth = { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', } async function api(path: string, init?: RequestInit) { const res = await fetch(`${BASE}${path}`, { ...init, headers: auth }) if (!res.ok) throw new Error(`${path} failed: ${res.status} ${await res.text()}`) return res } type VaultFile = { id: string; filename: string; content_type: string | null } type Passage = { text: string; filename: string } // 1. List every file in the vault, following next_cursor. async function listVaultFiles(): Promise<VaultFile[]> { const files: VaultFile[] = [] let cursor: string | null = null do { const query = new URLSearchParams({ limit: '100' }) if (cursor) query.set('cursor', cursor) const page = await (await api(`/api/v1/vaults/${vaultId}/files?${query}`)).json() files.push(...page.data) cursor = page.next_cursor } while (cursor) return files } // 2. Download the text files and split them into passages. async function loadPassages(files: VaultFile[]): Promise<Passage[]> { const passages: Passage[] = [] for (const file of files) { if (!file.content_type?.startsWith('text/')) continue // raw bytes only: skip non-text const res = await api(`/api/v1/vaults/${vaultId}/files/${file.id}/content`) const text = await res.text() for (const part of text.split(/\n\s*\n/)) { const trimmed = part.trim() if (trimmed) passages.push({ text: trimmed, filename: file.filename }) } } return passages } // 3. Embed in batches. One request takes at most 512 inputs. async function embed(input: string[]): Promise<number[][]> { const vectors: number[][] = [] for (let i = 0; i < input.length; i += 512) { const res = await api('/api/v1/embeddings', { method: 'POST', body: JSON.stringify({ model: 'cruxy-embed', input: input.slice(i, i + 512) }), }) const { data } = await res.json() const batch = data as { index: number; embedding: number[] }[] vectors.push(...batch.sort((a, b) => a.index - b.index).map((d) => d.embedding)) } return vectors } function cosine(a: number[], b: number[]): number { let dot = 0 let na = 0 let nb = 0 for (let i = 0; i < a.length; i++) { dot += a[i] * b[i] na += a[i] * a[i] nb += b[i] * b[i] } return dot / (Math.sqrt(na) * Math.sqrt(nb)) } const question = 'Who do I hand the pager to at the end of an on-call shift?' const passages = await loadPassages(await listVaultFiles()) if (passages.length === 0) throw new Error('the vault holds no text files to search') // 4. Shortlist by cosine, then rerank the shortlist. const vectors = await embed(passages.map((p) => p.text)) const [queryVector] = await embed([question]) const shortlist = passages .map((passage, i) => ({ passage, score: cosine(queryVector, vectors[i]) })) .sort((a, b) => b.score - a.score) .slice(0, 20) .map((s) => s.passage) const reranked = await api('/api/v1/rerank', { method: 'POST', body: JSON.stringify({ model: 'cruxy-rerank', query: question, documents: shortlist.map((p) => p.text), top_n: 5, }), }) const { results } = await reranked.json() // A rerank index points into the shortlist you sent, not into `passages`. const context = (results as { index: number }[]).map((r) => shortlist[r.index]) // 5. Ask chat inside the vault, grounded in the winning passages. const chat = await api('/api/v1/chat', { method: 'POST', body: JSON.stringify({ model: 'saga', stream: false, vault_id: vaultId, messages: [ { role: 'system', content: 'Answer only from the provided context, and name the file each fact comes from. If the answer is not in it, say you do not know.', }, { role: 'user', content: `Context:\n${context.map((p) => `[${p.filename}]\n${p.text}`).join('\n\n')}\n\nQuestion: ${question}`, }, ], }), }) const completion = await chat.json() console.log(completion.message.content) ``` ## What to know before you run it - **Access is the caller's.** The list and the download both answer `404` `vault_not_found` unless the key's user is a member who can read the vault and is not held. An index you build is only as private as where you keep it: store it with the same access as the vault. - **A download is a use.** A vault file is kept 365 days from its last use, and each download restarts that clock. Reading a file's metadata does not. - **`vault_id` on the chat request** makes the turn a chat inside the vault, so the vault's memory and standing rules apply. It is optional here: the passages reach the model through the message, not through `vault_id`. - **Index once, not per question.** The script embeds the corpus on every run to stay short. In a real system, store the vectors beside the passages and embed only the question. List the vault again to pick up new files. - **Map indices back.** A rerank `index` points into the `documents` you sent, which here is the shortlist. [Retrieval-augmented generation](/docs/en/resources/cookbook/rag#mapping-indices-back) explains the trap. ## Documents and images For a PDF, a Word document, or an image the vault holds, skip the index and attach the file to the question. A vault file's id goes in `file_ids` like any other file's, on a request that pins `Cruxy-Version: 2026-10-05` or later, and the gateway reads it only while you are a member who reads that vault and is not held: ```ts const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', 'Cruxy-Version': '2026-10-05', }, body: JSON.stringify({ model: 'saga', stream: false, vault_id: process.env.VAULT_ID, messages: [ { role: 'user', content: 'Who do I hand the pager to at the end of an on-call shift?', file_ids: [process.env.FILE_ID], // a PDF the vault holds }, ], }), }) if (!res.ok) throw new Error(`chat failed: ${res.status} ${await res.text()}`) console.log((await res.json()).message.content) ``` A file attached this way is billed as input on every turn that sends it, so for a large corpus, retrieve the passages instead. ## Next steps - [Retrieval-augmented generation](/docs/en/resources/cookbook/rag): the same pipeline over a corpus you hold yourself. - [Embeddings](/docs/en/build/embeddings): the batch limits and the vector shape. - [Rerank](/docs/en/build/rerank): the score ordering and `top_n`. - [Memory](/docs/en/build/memory): what `vault_id` changes about recall. ================================================================================ Page: Compare two prompt versions with evals URL: https://learn.cruxyai.com/docs/en/resources/cookbook/prompt-eval-loop Markdown: https://learn.cruxyai.com/docs/en/resources/cookbook/prompt-eval-loop.md ================================================================================ # Compare two prompt versions with evals Decide between two versions of a stored prompt with data: build an eval suite for each from the same cases, run both on one tier, and compare. You revised a prompt. Is the new version better? This recipe answers with a measurement instead of a hunch. It reads two versions of a stored prompt, builds one eval suite for each from the same test cases, runs both on the same tier, and compares the pass counts. It chains the prompt calls with the eval calls. > **Warning:** Running this costs money. Every case in every run is a billed chat > completion, charged to the key that starts the run. Two versions and three > cases are six completions. ## How the pieces fit An eval run sends each case's `input` to the tier verbatim. It does not read a stored prompt: a suite's `prompt_id` is a label that records which prompt the suite tests. So the recipe renders each version itself. For every test case, it fills the version's template with the case's text and stores the result as the case `input`. The two suites then differ only in the prompt text, which is the one thing being compared. The call that starts each run: ```bash title="curl" curl https://api.cruxy.ai/api/v1/evals/suites/$SUITE_ID/runs \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "saga" }' ``` ## The full recipe ```ts title="TypeScript" const BASE = 'https://api.cruxy.ai/api/v1' const promptId = process.env.PROMPT_ID // a stored prompt with at least two versions const headers = { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', } async function call(method: string, path: string, body?: unknown) { const res = await fetch(`${BASE}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), }) if (!res.ok) throw new Error(`${method} ${path} failed: ${res.status} ${await res.text()}`) return res.json() } // The same tickets for both versions. `expected` is the label a correct // answer contains; the prompt must ask for a one-word label for this to work. const tickets = [ { ticket: 'I was charged twice for order 8841.', expected: 'billing' }, { ticket: 'My parcel has not moved in six days.', expected: 'shipping' }, { ticket: 'I cannot reset my password.', expected: 'account' }, ] // 1. Build a suite for one version: its template, filled with each ticket. async function suiteFor(version: number): Promise<string> { const prompt = await call('GET', `/prompts/${promptId}?version=${version}`) const template: string = prompt.version.content // for example: "...Ticket: {{ticket}}" const suite = await call('POST', '/evals/suites', { name: `${prompt.name} v${version}`, slug: `${prompt.slug}-v${version}-${Date.now()}`, // a slug is unique in the workspace prompt_id: prompt.id, }) for (const t of tickets) { await call('POST', `/evals/suites/${suite.id}/cases`, { input: template.replaceAll('{{ticket}}', t.ticket), expected: t.expected, match_mode: 'contains', }) } return suite.id } // 2. Start a run and wait for it. async function runSuite(suiteId: string, model: string) { let run = await call('POST', `/evals/suites/${suiteId}/runs`, { model }) while (run.status === 'pending' || run.status === 'running') { await new Promise((resolve) => setTimeout(resolve, 2000)) run = await call('GET', `/evals/runs/${run.id}`) } if (run.status === 'failed') throw new Error(`run ${run.id} failed: ${run.error}`) return run } // 3. Run both versions on the same tier, one after the other. const MODEL = 'saga' const versions = [1, 2] const report = [] for (const version of versions) { const suiteId = await suiteFor(version) const run = await runSuite(suiteId, MODEL) const results = await call('GET', `/evals/runs/${run.id}/results`) const latencies = results.data.map((r: { latency_ms: number }) => r.latency_ms) report.push({ version, passed: run.passed, total: run.total_cases, meanLatencyMs: Math.round( latencies.reduce((sum: number, ms: number) => sum + ms, 0) / Math.max(latencies.length, 1), ), failures: results.data .filter((r: { passed: boolean }) => !r.passed) .map((r: { case_id: string; actual: string }) => ({ case: r.case_id, got: r.actual })), }) } // 4. Compare. for (const r of report) { console.log(`v${r.version}: ${r.passed}/${r.total} passed, mean ${r.meanLatencyMs} ms`) for (const f of r.failures) console.log(` failed ${f.case}: ${f.got}`) } ``` ## Reading the result - **Pass counts compare the versions, on these cases only.** Three cases show the method; they do not decide anything. Use enough cases from your own product to see the spread, and include the inputs the old version got wrong. - **Read the failures, not only the count.** `actual` is the tier's output for a failed case. A version can fail because it is worse, or because it answers correctly in words your `expected` does not contain. - **`match_mode` compares text.** `contains` passes when the output contains `expected`, and `exact` when the trimmed output equals it. Both need a prompt that asks for a short, fixed answer. A prompt that asks for a paragraph cannot be scored this way. - **Hold everything else still.** Run both suites on the same tier. A run takes a tier and nothing else, and `auto` is refused, so the tier is the only setting to keep equal. - **Latency is per completion.** `latency_ms` is how long each case's completion took. A mean over a few cases is a rough guide, not a measurement of the tier. ## Clean up Each run of the script creates two suites. `DELETE /api/v1/evals/suites/{id}` deletes a suite with its cases, runs, and results. Keep the suites if you want the record: a suite's `prompt_id` shows which prompt it tested. ## Next steps - [Prompting basics](/docs/en/best-practices/prompting): what to change between versions. - [Tier and effort for cost and latency](/docs/en/best-practices/tiers-and-effort): run the same comparison across tiers. - [Usage and cost](/docs/en/build/usage-and-cost): what each completion in a run costs. ================================================================================ Page: Resources URL: https://learn.cruxyai.com/docs/en/resources Markdown: https://learn.cruxyai.com/docs/en/resources.md ================================================================================ # Resources Reference material, tools for models and agents, and help: the tier catalog, changelog, glossary, llms.txt, the Docs MCP server, and support. The Resources tab collects what you reach for around the guides, in three groups: reference material, the corpus published for models and agents, and help when something goes wrong. The cookbook and the API reference each have a tab of their own; the reference cards below link to both. ## Reference Open the glossary when a term is unfamiliar and the changelog when a version moves. - [Models](/docs/en/reference/models): The public tier catalog, read at runtime with GET /api/v1/models. - [Changelog](/docs/en/reference/changelog): What changed in the API and its docs, newest first, dated by API version. - [Glossary](/docs/en/resources/glossary): Definitions for tiers, the cruxy block, request_id, device login, and the 429 codes. - [Cookbook](/docs/en/resources/cookbook): Task-shaped recipes that combine endpoints: retrieval, a tool loop, a streaming UI, and a moderation gate. - [API Reference](/docs/en/reference/api): Every endpoint, typed and interactive. ## For models and agents The API is summarized on one page for a model to read, and the whole documentation corpus is published as plain text for ingestion and as an MCP server that an agent can query as tools. - [API guide for agents](/docs/en/resources/api-guide): Auth, tiers, chat, tools, embeddings, rerank, moderations, and errors on one dense page. - [Docs MCP server](/docs/en/resources/mcp-server): List, read, and search Cruxy Learn as MCP tools at learn.cruxyai.com/mcp. No key. - [/llms.txt](/llms.txt): The link index: one entry per page, each pointing at its raw markdown. - [/llms-full.txt](/llms-full.txt): Every page's markdown concatenated into one file, in navigation order. ## Help Check the known limitations before you build around a behavior, and contact support when a call fails in a way the docs do not explain. - [Known limitations](/docs/en/build/known-limitations): What the API does not do today, why it matters, and the workaround. - [Support](/docs/en/resources/support): Platform status at status.cruxyai.com, and what to send to support@cruxyai.com. ================================================================================ Page: Models URL: https://learn.cruxyai.com/docs/en/reference/models Markdown: https://learn.cruxyai.com/docs/en/reference/models.md ================================================================================ # Models Discover the public tier catalog at runtime with GET /api/v1/models. `GET /api/v1/models` returns the public tier catalog (the tiers you can pass as `model`, with their capabilities), so you read it at runtime instead of hardcoding tier strings. ```bash title="curl" curl https://api.cruxy.ai/api/v1/models \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/models', { headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}` }, }) const { data, cruxy } = await res.json() for (const model of data) { console.log(model.id, model.context_window, model.supports_tools) } console.log('thought lines:', cruxy.reasoning_summaries) ``` ```ts title="SDK" import { Cruxy } from '@cruxy/api' const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY }) const { result } = await cruxy.models.listModels() for (const model of result.data) { console.log(model.id, model.contextWindow, model.supportsTools) } ``` ## Tiers, never provider models The catalog lists Cruxy's **public tiers** (`canto`, `saga`, and `epos`) in the OpenAI discovery shape. Each entry's `id` is the tier string you pass as `model` to [Chat](/docs/en/build/chat). The response never exposes the upstream provider model behind a tier, so a tier is a stable id you can depend on even when the backing model changes. [Choosing a tier](/docs/en/build/choosing-a-tier) compares the tiers and when to use each. | | Canto | Saga | Epos | | --- | --- | --- | --- | | Model id | `canto` | `saga` | `epos` | | What it is | The most capable tier. | The balanced tier. | The fastest tier. | | Best for | The hardest tasks: deep reasoning over text. It does not read images. | Everyday calls: strong quality at lower latency and cost. | Short, high-volume calls where latency and cost matter most. | ## Deprecated aliases The tiers were renamed in API version 2026-10-18. Each former id is a deprecated alias of its new id: the gateway serves, bills, and records it as the same tier. | Deprecated alias | Public id | Profile | | --- | --- | --- | | `mira` | `epos` | Fast | | `vaani` | `saga` | Balanced | | `kavi` | `canto` | Deep | - **Requests accept both, on every version.** You can send `kavi`, `vaani`, or `mira` as `model` on any `Cruxy-Version`, and anywhere else a model is named on input, such as a key's allowed models. - **Responses name the tier by version.** From `Cruxy-Version: 2026-10-18`, and on any request that sends no `Cruxy-Version`, these response values use the new id: `model`, `cruxy.routed_tier`, `routing.tier`, `usage.cost.tier`, an error's `tier`, and the ids in this catalog. A request pinned to `2026-10-07` or earlier receives `kavi`, `vaani`, and `mira` there instead, whichever spelling it sent. - **Fields named for Epos have a new name beside the old one.** An error body carries `epos_available` next to `mira_available`, always with the same value, and `GET /api/v1/limits` carries `token_pool.epos` next to `token_pool.mira`, present together with the same value. Read the new names. The old ones stay, so code that reads them keeps working. - **Status components add `public_id`.** The chat tier components in `GET /api/status` keep the ids `kavi`, `vaani`, and `mira`, and each also carries `public_id`: `canto`, `saga`, or `epos`. On every other component, `public_id` equals `id`. Read `public_id` when it is present; see [Reliability](/docs/en/build/reliability#check-platform-status). - **Removing an old name takes a new version.** Dropping `mira_available` or `token_pool.mira`, or changing a status component's `id`, ships only under a new dated `Cruxy-Version`, listed in the [Changelog](/docs/en/reference/changelog). Switch your code to `canto`, `saga`, and `epos`, and compare a response's tier against the new ids once you send `Cruxy-Version: 2026-10-18` or later. See [Request IDs and metadata](/docs/en/build/request-ids#the-cruxy-version-header) for pinning a version. ## Response shape The envelope is a list of `model` objects, with a `cruxy` block beside it: ```json { "object": "list", "data": [ { "object": "model", "id": "canto", "label": "Canto", "profile": "Deep" } ], "cruxy": { "reasoning_summaries": false } } ``` `cruxy.reasoning_summaries` says whether this deployment sends thought lines at all, read from the same switch the chat handler applies. `false` means no turn gets them. `true` means a turn gets them only when it is a stream from a signed-in credential that pins `Cruxy-Version: 2026-11-13` or later; a developer or headless key never does. See [Streaming](/docs/en/build/streaming#thought-lines). Each entry describes one tier: | Field | Meaning | | --- | --- | | `id` | The tier string to pass as `model`, e.g. `canto`. | | `label` | The tier's display name: `Canto`, `Saga`, or `Epos`. | | `profile` | A one-word descriptor to show beside the label: `Deep` on `canto`, `Balanced` on `saga`, `Fast` on `epos`. It is display text, stable once shipped, and never a performance number. | | `object` | Always `"model"`. | | `created` | A fixed Unix time in seconds, the same on every call, so the listing can be cached and compared. With `owned_by` it completes the OpenAI model object, which OpenAI clients require. | | `owned_by` | Always `"cruxy"`, whatever model serves the tier. | | `context_window` | Maximum input size, in tokens. | | `max_output` | Maximum tokens the tier will generate. | | `latency_target_ms` | The tier's latency target, in milliseconds. | | `reasoning` | How the tier thinks when a request omits `reasoning_effort`. `default_effort` is the effort such a request gets, `none`, `low`, `medium`, or `high`, and the value echoed back as `cruxy.reasoning_effort`. `graded` says whether `low`, `medium`, and `high` are different depths on the tier; when it is `false` the control is on or off, so `low` thinks as long as `high`. See [Reasoning effort](/docs/en/build/reasoning-effort). | | `supports_tools` | Whether the tier supports tool calling; see [Define tools](/docs/en/build/tools). | | `supports_vision` | Whether the tier reads images: a chat message's `file_ids` may name a JPEG, PNG, or WebP image. A tier where it is `false` refuses a turn that attaches one, and `model: "auto"` routes a turn with images to a tier where it is `true`. | | `supports_structured_output` | Whether the tier honours `response_format` `json_object` and `json_schema`. A structured request that names a tier where it is `false` is `422` `structured_output_unsupported`, and `model: "auto"` routes a structured request only to a tier where it is `true`; see [Ask for structured output](/docs/en/best-practices/prompting#ask-for-structured-output). | | `pricing` | `currency`, `input_unit`, and `output_unit`: the tier's input and output rates per million tokens. Rates are account-specific. | Every field above is on every entry, and `pricing` and `reasoning` always carry all of theirs. Read the concrete values from the live response rather than assuming them; they can change as tiers evolve. `GET /v1/models`, the OpenAI wire's listing, returns the same tiers with `id`, `object`, `created`, and `owned_by` only, and no `cruxy` block. ## Errors `GET /api/v1/models` returns `401` if the key is missing or invalid. See [Errors](/docs/en/reference/errors). ## Next steps - [Chat](/docs/en/build/chat): use a tier id as `model`. - [Choosing a tier](/docs/en/build/choosing-a-tier): pick the tier for each call. - [Define tools](/docs/en/build/tools): for tiers where `supports_tools` is true. - [Changelog](/docs/en/reference/changelog): when the catalog's metadata changed. ================================================================================ Page: Changelog URL: https://learn.cruxyai.com/docs/en/reference/changelog Markdown: https://learn.cruxyai.com/docs/en/reference/changelog.md ================================================================================ # Changelog What changed in the Cruxy API and its docs, newest first: each dated release by its API version, plus the additive changes that need no pin. API version: 2026-11-13 The Cruxy API is date-versioned: `info.version` in the spec is a date, and every response echoes the version that served it in the `Cruxy-Version` header, so you can always confirm which version served a call. Send `Cruxy-Version: YYYY-MM-DD` to pin one; see [Request IDs and metadata](/docs/en/build/request-ids#the-cruxy-version-header). A new dated version ships for a breaking change, such as a change to streaming frame order. A date can also gate a new request field whose silent absence on an older gateway would make a response misrepresent what it used, and the four releases from 2026-09-26 to 2026-10-07 each do that. Ordinary additive fields ship without a new version, so the spec dates neither them nor the endpoints added alongside them; [Additive changes since 2026-10-18](#additive-changes-since-2026-10-18) and [Additive changes since 2026-06-13](#additive-changes-since-2026-06-13) list both. Entries use the [Keep a Changelog](https://keepachangelog.com) categories (Added, Changed, Fixed, and Deprecated), and a release lists only the categories it touched. ## 2026-11-13 The current version: a request that sends no `Cruxy-Version` is served 2026-11-13. ### Added - Thought lines on a chat stream: `cruxy.reasoning_summary` on `POST /api/v1/chat`, and a `reasoning_summary` event on `POST /api/v2/chat`. Each is a few words on one part of the thinking trace, with `index`, `text`, `start`, and `end`, on a frame of its own; a turn carries at most 12, and they are not billed. A turn gets them only when the deployment sends thought lines at all, which `cruxy.reasoning_summaries` on `GET /api/v1/models` reports, and the turn is a stream from a signed-in credential that pins `Cruxy-Version: 2026-11-13` or later. A developer or headless key never gets them, and neither does a request with no `Cruxy-Version`. See [Streaming](/docs/en/build/streaming#thought-lines). ## 2026-11-12 ### Added - `cruxy.reasoning` on `POST /api/v1/chat`: the tier's thinking trace, present only when the tier reasoned, and the same field as `reasoning` on `POST /api/v2/chat`. A non-streaming response carries the whole trace. A stream carries it on reasoning frames, one fragment each, whose `delta` is an empty object and whose `finish_reason` is `null`. It is sent from `Cruxy-Version: 2026-11-12` and when a request sends no `Cruxy-Version`; a request pinned to an earlier date never receives it. It changes no `usage` figure and no bill. If your stream reader takes an empty `delta` for the finish frame, pin `2026-10-18` until it checks for a non-null `finish_reason` instead. See [Streaming](/docs/en/build/streaming#reasoning-frames). ## V1, 31 October 2026 The V1 plans and the V1 model lineup, under API version 2026-10-18. No request field or frame changes, so nothing here needs a version pin, but what a plan may do and what each tier is changes on this day. See [Plan limits](/docs/en/build/plan-limits). ### Added - `models`, `context_window`, `api_share`, `plan_limits`, `files`, `images`, and `storage` in `GET /api/v1/limits`: the tiers your plan includes, its context window and each tier's effective one, the developer keys' share of the month, your plan's row of the limits table, this month's uploads against it, and what you hold against the storage pool. A developer key also reads `rate_limits.chat.max_concurrent_per_key`. - `GET /api/v1/limits/plans`: every plan on sale and what it includes, with `plan`, `models`, `context_window`, `usage_multiple`, and `plan_limits`, the same for every caller. See [Plan limits](/docs/en/build/plan-limits). - `403` `model_not_in_plan`: a chat request named a tier the plan does not include. It carries `model` and `plan`. - `429` `api_share_exhausted`: the account's developer keys have used the plan's API share, 25% of its monthly usage, until `reset_at`. - `429` `file_limit_reached` and `image_limit_reached` on `POST /api/v1/files`, once the month's allowance of that kind is stored. ### Changed - **Plans.** Free includes `saga`; Core adds `epos`; Advanced, Pro, and Max include all three, and `auto` routes only within the plan. A plan has a context window, 256,000 tokens on Free and 1,000,000 on a paid plan, and a turn is held to the smaller of it and the tier's. Developer API keys together may use 25% of the plan's monthly usage, and one key may have 4 chat requests in flight. The upload, storage, and file-size allowances are the V1 table. Every monthly allowance runs over the account's own month, never the calendar month, and every plan has a 12-hour window beside it. - **Tiers.** Every tier's `context_window` is 1,048,576 tokens, and `max_output` is 65,536 on `canto` and 131,072 on `saga` and `epos`; a `max_tokens` above the cap is clamped to it, as before. `canto` no longer reads images (`supports_vision: false`): an explicit `canto` turn that attaches one is `400` `image_not_supported`, an image on an earlier message is left out there as `no_vision`, and `auto` routes a turn with an image to `saga` or `epos`. `canto` is now graded (`reasoning.graded: true`); the defaults stay `canto` high, `saga` low, `epos` none. The chat request body may be 16 MiB. The default per-token rates in `usage.cost` change with the lineup; read them from `GET /api/v1/models`. - `POST /api/v1/tokens/count` answers `503` `count_unavailable` on every tier until a tokenizer for the V1 models is vendored; see [Known limitations](/docs/en/build/known-limitations#token-counting-answers-count_unavailable-for-now). ### Removed - The Free plan's message count, which ended on 2026-10-28. Nothing counts messages on any plan; `message_limit_reached` is never sent, and `GET /api/v1/limits` carries no `messages`. A spent Free allowance reads `budget_exhausted`, as on every other plan. ## Additive changes since 2026-10-18 These need no version pin, and the spec does not date them. ### Added - `epos_available` in an error body, next to `mira_available` and always with the same value, and `token_pool.epos` in `GET /api/v1/limits`, next to `token_pool.mira`, present together with the same values. The old names stay so existing code keeps working; read the new ones. See [Deprecated aliases](/docs/en/reference/models#deprecated-aliases). - `public_id` on every component in `GET /api/status`: `canto`, `saga`, or `epos` on a chat tier's component, whose `id` keeps its former name, and the same value as `id` on every other component. See [Reliability](/docs/en/build/reliability#check-platform-status). - `DELETE /api/v1/me/key` revokes the key that sends it, and only that key: `204` when revoked, `401` once it is unusable. A signed-in credential can now be revoked by its holder. See [Revoke the current key](/docs/en/get-started/api-keys#revoke-the-current-key). - `supports_structured_output` on each tier in `GET /api/v1/models`: whether the tier honours `response_format` `json_object` and `json_schema`. See [Ask for structured output](/docs/en/best-practices/prompting#ask-for-structured-output). - `max_completion_tokens` on `POST /v1/chat/completions`, an alias of `max_tokens` that wins when a request sends both. See [OpenAI SDK compatibility](/docs/en/migrate/openai-sdk-compatibility#request-parameters). - `GET /api/v1/limits/month`: your month so far, one entry per UTC day with `date` and `percent_used`, over the same month as `token_pool.monthly`. It returns no unit count, cap, or remainder. See [Rate limits and budgets](/docs/en/build/rate-limits#read-your-month-so-far). - `percent_used` on `token_pool.monthly` and `token_pool.burst` in `GET /api/v1/limits`, and on `api_share`, `files`, `images`, and `storage`: used over cap from 0 to 100, to one decimal place, rounded down. - `GET /api/v1/conversations/counts`: how many of your conversations are `live` and how many `archived`, under the listing's own visibility and its `vault_id` and `source` filters. See [Conversations](/docs/en/build/conversations#list-and-count). - `title_source` on every conversation: `auto`, `generated`, `user`, or `null`. The gateway now writes a `generated` title of 2 to 6 words a few seconds after the first reply of a `chat` conversation written through a first-party login, replacing an `auto` title and never one you set. - Facts about a stored reply, on `POST /api/v1/conversations/{id}/messages` and on every read of the message: `incomplete_reason` on an `incomplete` message, and `routed_tier`, `routing_mode`, `reply_ms`, `input_tokens`, and `activity` on an assistant message. See [Conversations](/docs/en/build/conversations#record-what-a-reply-did). - `improve_models` on `POST /api/v1/chat` and `POST /api/v1/conversations`: records the author's "Help improve Cruxy models" setting as `allowed` and the `policy` date it was made under. Omitted, nothing is recorded, which is excluded. The gateway never returns it. - `total` on `GET /api/v1/files`, how many files the listing pages through, and `conversations` on each listed file and on `GET /api/v1/files/{id}`: the conversations of yours the file is attached in, with their `total`. - Files a vault holds, readable by every member who can read the vault: `GET` and `POST /api/v1/vaults/{id}/files`, `POST /api/v1/vaults/{id}/files/share`, which copies one of your own files in, `GET` and `DELETE /api/v1/vaults/{id}/files/{file_id}`, and `GET /api/v1/vaults/{id}/files/{file_id}/content`. A vault file is kept 365 days from its last use. A conversation message can attach one in `file_ids`, and `vault_id` on `POST /api/v1/conversations/{id}/messages` names the vault a chat is happening inside so its files can be attached. - `400` `moderation_input_too_large` on chat: the input moderation gate reads the whole request, every message, tool-call arguments, and the text of attached files, and a turn that brings more new text than it reads in one request is refused. It carries `limit_bytes` (except on `POST /v1/chat/completions`) and is not billed. See [Errors and retries](/docs/en/build/errors-and-retries#400-bad-request). - `cruxy.reasoning_summaries` on `GET /api/v1/models`: whether the deployment sends thought lines at all. `GET /v1/models` does not carry it. See [Models](/docs/en/reference/models#response-shape). ### Changed - `model: "auto"` routes a structured-output request only to a tier that supports it, instead of answering `422` `structured_output_unsupported` when the router picked one that does not. - A conversation message's `content` may be up to 1,048,576 bytes of UTF-8; longer is `400` `invalid_request`. - The spec declares `413` `payload_too_large` on every route that caps its request body. - The spec marks every field of a `GET /api/v1/models` entry, and of its `pricing` and `reasoning` objects, as required. - The spec declares the `403`, `500`, `502`, `503`, and `504` responses of `POST /api/v1/embeddings`, `POST /api/v1/rerank`, and `POST /api/v1/moderations`, and the `503` of `POST /api/v1/files`. ## 2026-10-18 ### Changed - The chat tiers have new public ids: `canto` (Canto, Deep; was `kavi`), `saga` (Saga, Balanced; was `vaani`), and `epos` (Epos, Fast; was `mira`). From `Cruxy-Version: 2026-10-18`, and on any request that sends no `Cruxy-Version`, these response values use the new id: `model`, `cruxy.routed_tier`, `routing.tier`, every stream frame, `usage.cost.tier`, an error's `tier`, `model`, and `vision_tiers`, and the ids and labels in `GET /api/v1/models` and `GET /v1/models`. A request pinned to `2026-10-07` or earlier keeps receiving `kavi`, `vaani`, and `mira`, whichever spelling it sent. This is a breaking change to response values: if your code compares a response's tier against a string, pin `2026-10-07` until it handles the new ids. The `mira_available` error field and the `mira` key in `GET /api/v1/limits` keep their names, and the chat tier components in `GET /api/status` keep the ids `kavi`, `vaani`, and `mira` on every version. ### Deprecated - `kavi`, `vaani`, and `mira` as model ids. They stay accepted on input on every version, as deprecated aliases of `canto`, `saga`, and `epos`, served and billed as the same tier. Switch to the new ids; see [Deprecated aliases](/docs/en/reference/models#deprecated-aliases). ## 2026-10-07 ### Added - A lifetime for uploaded files. `POST /api/v1/files` takes an optional `expires_in`, from 60 to 604800 seconds (7 days), and returns the moment it ends as `expires_at`. Once it passes, the file is gone to every read, and its bytes are deleted within 15 minutes. Setting `expires_in` requires `Cruxy-Version: 2026-10-07` or later; without the pin the upload is `400` `invalid_request` and nothing is stored. A file uploaded without it lives until you delete it, as before. ## 2026-10-06 ### Added - Files on stored conversation messages. `POST /api/v1/conversations/{id}/messages` takes `file_ids` on a user message, at most 20 distinct files, and every read of the conversation returns them. It requires `Cruxy-Version: 2026-10-06` or later; without the pin, `file_ids` is `400` `invalid_request` with `required_version`. The date is one day later than chat's on purpose: a gateway that knows only 2026-10-05 reads `file_ids` in chat but would drop them from an append. ## 2026-10-05 ### Added - Files in a chat turn. A user message on `POST /api/v1/chat` or `POST /api/v2/chat` can carry `file_ids`, naming files you uploaded with `POST /api/v1/files`, and the gateway reads each one into the turn: UTF-8 text, PDF and Word (`.docx`) documents as the text read from them at upload, and JPEG, PNG, and WebP images on a tier that reads images. It requires `Cruxy-Version: 2026-10-05` or later; without the pin, `file_ids` is `400` `invalid_request` with `required_version`. A file's tokens are billed on every request that sends it, and `POST /v1/chat/completions` refuses `file_ids`. - `cruxy.files_omitted`, a top-level `files_omitted` on `POST /api/v2/chat`, lists the files on earlier messages that a turn left out, and why. - Three `400` codes for a file that cannot be read into a turn: `file_not_text`, `file_too_large`, and `image_not_supported`, which names the tiers that read images in `vision_tiers`. See [Errors and retries](/docs/en/build/errors-and-retries#400-bad-request). ## 2026-09-26 ### Added - Per-request memory controls on chat. `memory: {"recall": …, "capture": …}` on `POST /api/v1/chat` and `POST /api/v2/chat` turns automatic recall and capture on or off for one request; left out, each side follows the credential's default. Pin `Cruxy-Version: 2026-09-26` before relying on `false`: a gateway that predates the field ignores it and captures anyway, while a pinned request is refused by such a gateway instead. See [Memory](/docs/en/build/memory). ## Additive changes since 2026-06-13 These need no version pin, and the spec does not date them. Each is in the 2026-10-07 spec and was not in the 2026-06-13 spec. ### Added - The plain OpenAI wire: `POST /v1/chat/completions` and `GET /v1/models`, for OpenAI clients and evaluation harnesses. It carries none of the Cruxy-native chat features. - Conversations under `/api/v1/conversations`: history stored on the server, with search, archiving, and branches. - Standing rules: `GET`, `PUT`, and `DELETE /api/v1/rules`, `GET /api/v1/rules/resolved`, and a vault's own rules at `/api/v1/vaults/{id}/rules`, with the chat `rules` switch and `cruxy.rules_applied`. See [Standing rules](/docs/en/build/rules). - Chat request fields `tool_choice`, `vault_id`, and `mentioned_vault_ids`, and the response signals `cruxy.memory_recall`, `cruxy.memory_capture`, and `cruxy.undeclared_tool_replay`. See [Request IDs and metadata](/docs/en/build/request-ids#the-cruxy-block). - Eval suites, cases, and runs under `/api/v1/evals`. - Invitations and memberships: `/api/v1/invitations`, `/api/v1/org/invitations`, and `/api/v1/org/memberships`. - Native sign-in: `POST /api/v1/auth/oauth/start` and `POST /api/v1/auth/oauth/token`. A key minted this way is a signed-in credential, as from device login. - The `X-Request-Id` header, declared on every response: a correlation id that you can set on the request. See [Request IDs and metadata](/docs/en/build/request-ids#the-x-request-id-header). - A public status document at `GET /api/status`. See [Reliability](/docs/en/build/reliability#check-platform-status). - `GET /api/v1/service-token/self`, which describes the calling service token. - Tier catalog fields on `GET /api/v1/models`: `created`, `owned_by`, `profile`, `reasoning` (`default_effort` and `graded`), and `supports_vision`. - `results[].cruxy.hazard_codes` on a flagged moderation result. - `org` on the device-login token response: the organization the new key is bound to. - `content_type` on an uploaded file, plus `text_status` and `text_tokens` for a PDF or Word document, whose text is read once at upload. - Error codes: `client_closed_request`, `conversation_forbidden`, `conversation_not_found`, `eval_case_not_found`, `eval_run_not_found`, `eval_suite_not_found`, `eval_suite_slug_exists`, `input_not_countable`, `invalid_tool_schema`, `invitation_not_found`, `key_read_only`, `key_scope_forbidden`, `key_spend_cap_exceeded`, `limits_unavailable`, `message_not_found`, `model_not_allowed`, `moderation_rejected`, `provider_not_supported`, `redirect_uri_not_allowed`, `request_not_found`, `rules_forbidden`, `rules_too_large`, `server_shutting_down`, and `vault_external_id_conflict`. See [Errors and retries](/docs/en/build/errors-and-retries#error-codes). ### Changed - The production hostname is `https://api.cruxy.ai`. `https://api.cruxy.in` is the legacy hostname for the same service, and is still supported. - The spec documents each endpoint once, under `/api/v1`. Every public endpoint is also served under `/api/v2` by the same handler, with the same authentication, rate limit, and bodies. Chat is the exception: `POST /api/v2/chat` is the separate Cruxy-native wire. ### Deprecated - `scope_unsupported` is retired. It is never sent, and it stays in the error vocabulary so the string is never reused. ## 2026-06-13 This release types the surfaces you build against and documents the limits and failure modes the gateway already enforced. ### Added - Model catalog metadata on [Models](/docs/en/reference/models) (`GET /api/v1/models`): each tier advertises its `context_window`, `max_output`, `latency_target_ms`, and `pricing`, so you read a tier's limits at runtime instead of hardcoding them. Pricing is provisional; read it from the live response, never from a copy. - The full `finish_reason` enum on [Chat](/docs/en/build/chat) (`stop`, `tool_calls`, `length`, and `content_filter`) for both streaming and non-streaming responses, with `tool_calls` as the signal to answer `message.tool_calls` and continue the turn. - Per-request batch limits on the specialized endpoints: [Embeddings](/docs/en/build/embeddings), [Rerank](/docs/en/build/rerank), and [Moderations](/docs/en/build/moderations) accept at most 512 inputs, with the whole body capped at 64 KiB; exceeding either ceiling is a `400`. Batch a larger corpus across multiple requests. - Per-type feedback payloads on [Feedback](/docs/en/build/feedback): `type` fixes the shape of `payload`, and `thumbs`, `edit_accepted`/`edit_rejected`, and `test_result` each carry their own schema, so the reference documents the exact fields for each event. - Mid-stream failure behavior for streaming [Chat](/docs/en/build/chat): a response that ends without the `data: [DONE]` terminator is a failed, incomplete completion. The `200` is already committed, so no error frame follows; treat a stream that stops before `[DONE]` as a failure and retry it. ### Changed - The non-streaming chat response is now typed and flattened. [Chat](/docs/en/build/chat) with `stream: false` returns a `ChatCompletionResponse`: the assistant reply is the top-level `message` with a sibling `finish_reason`, not an OpenAI `choices[]` array; read `message.content` directly. Streaming responses are typed as `ChatCompletionChunk`. This replaces the previously untyped `200` body. - Feedback validation is stricter. [Feedback](/docs/en/build/feedback) rejects unknown payload keys, wrong types, and bad enum values with a `400`, and a stored event's payload is consent-gated and redacted rather than persisted verbatim. ## Next steps - [API Reference](/docs/en/reference/api): every endpoint, typed and interactive. - [Models](/docs/en/reference/models): the live tier catalog and its metadata. - [Errors](/docs/en/reference/errors): the `400`/`401`/`429` shape these changes reference. ================================================================================ Page: Glossary URL: https://learn.cruxyai.com/docs/en/resources/glossary Markdown: https://learn.cruxyai.com/docs/en/resources/glossary.md ================================================================================ # Glossary Definitions for the Cruxy vocabulary: tiers, the cruxy block, request_id, device login, and the 429 codes. Terms you meet across the guides and the API reference, defined once. Each entry links to where the term is used in full. ## Models and tiers ### Tier A public model you address by a stable name rather than by the provider model behind it. You pass a tier as `model`, and the gateway resolves it to an upstream provider model on the server; you never send or receive that upstream id. Because the name is stable, your code keeps working when the backing model changes. See [Models](/docs/en/reference/models). ### epos, saga, canto The three public chat tiers: `epos` (Fast), `saga` (Balanced), and `canto` (Deep). You pass one as `model` to [Chat](/docs/en/build/chat). To read the live catalog rather than hardcoding the strings, call [Models](/docs/en/reference/models). They were formerly named `mira`, `vaani`, and `kavi`, which the API still accepts; see [Deprecated aliases](/docs/en/reference/models#deprecated-aliases). ### cruxy-embed The embeddings model. You pass it as `model` to [Embeddings](/docs/en/build/embeddings) to turn text into vectors. ### cruxy-rerank The rerank model, and the only one the gateway offers for reranking. You pass it as `model` to [Rerank](/docs/en/build/rerank), which orders candidate documents against a query. ### cruxy-guard The moderation model, and the only one for moderation. You pass it as `model` to [Moderations](/docs/en/build/moderations), which classifies text against content-safety categories. ## Requests and responses ### OpenAI-compatible Requests and responses keep the OpenAI shape, so an existing OpenAI client needs little more than a new base URL and key; see [Migrate from OpenAI](/docs/en/migrate/from-openai). [Chat](/docs/en/build/chat), [Embeddings](/docs/en/build/embeddings), and [Moderations](/docs/en/build/moderations) follow it; [Rerank](/docs/en/build/rerank) does not; it uses a Cohere-style contract whose results carry indices into your input. ### The cruxy block An additive, namespaced `cruxy` key on responses. It never alters the OpenAI-shaped fields, so a vanilla OpenAI client parses the response unchanged and ignores the extra key. Its contents vary by endpoint: on chat it carries `request_id`, `routed_tier`, and `reasoning_effort` (cost and tokens live in `usage`); on embeddings and rerank it carries `request_id` and a `cost` object. Moderations has no top-level block, though a flagged result carries its own `cruxy.hazard_codes`. See [the cruxy block](/docs/en/build/request-ids#the-cruxy-block). ### request_id A UUID that identifies a single call, returned in the response's `cruxy.request_id`. You log it to identify the call in support requests, and you send it back to [Feedback](/docs/en/build/feedback) to attach an outcome to that call. [Request IDs and metadata](/docs/en/build/request-ids) shows where it appears on each endpoint. ### Rerank Scoring a set of candidate documents against a query and returning them best-first, so you order a shortlist by relevance. Each result carries an `index` into the documents you sent, not the text itself. See [Rerank](/docs/en/build/rerank). ### flagged The overall boolean in a [Moderations](/docs/en/build/moderations) result: `true` when any category matched. Check it first. The accompanying `category_scores` are binary (`1.0` or `0.0`), not calibrated probabilities, so you do not threshold them. ## Authentication ### Device login An [RFC 8628](https://datatracker.ietf.org/doc/html/rfc8628) device-authorization flow that mints a key: your client requests a code, a person approves it in a browser, and your client polls until a key is issued. The browser and the client can be different machines. See [Get your API key](/docs/en/get-started/api-keys). ### user_code and device_code The two codes in device login. `device_code` is the secret your client polls with and never shows the user; `user_code` is the short code the person confirms in the browser. See [Get your API key](/docs/en/get-started/api-keys). ### Bearer key A `cxy_live_` API key you send in the `Authorization: Bearer` header on every authenticated request. Device login returns it exactly once, so you store it on issue and treat it like a password. See [Authentication](/docs/en/get-started/authentication). ## Limits and budgets ### rate_limited The `429` `code` that means requests are arriving too fast. It clears on its own once you ease off, then retry. See [Rate limits and budgets](/docs/en/build/rate-limits). ### budget_exhausted The `429` `code` that means the account's budget is spent. A retry alone will not clear it until the budget resets or is raised, distinct from `rate_limited`, which eases on its own. See [Rate limits and budgets](/docs/en/build/rate-limits). ================================================================================ Page: API guide for agents URL: https://learn.cruxyai.com/docs/en/resources/api-guide Markdown: https://learn.cruxyai.com/docs/en/resources/api-guide.md ================================================================================ # API guide for agents A dense, single-page reference for calling the Cruxy API correctly: auth, tiers, chat, tool calling, embeddings, rerank, moderations, and errors. One page with everything a model needs to call the API correctly, and nothing else. The base URL is `https://api.cruxy.ai`. Every path below is under it. For the exhaustive per-field spec, see the [API Reference](/docs/en/reference/api); for the whole corpus as text, fetch `/llms-full.txt`. ## Auth Every endpoint except device login, native OAuth sign-in, and the status and health probes needs a Bearer key in the `Authorization` header. Keys carry the `cxy_live_` prefix. A missing or invalid key is `401`. ```bash curl https://api.cruxy.ai/api/v1/me \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` `GET /api/v1/me` echoes `{ api_key_id, user_id }`; use it to confirm a key works. ### Device login Get a key with an RFC 8628 device flow: no key required, since its job is to mint one. 1. `POST /api/v1/device/code` (no body, no auth) returns `{ device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval }`. 2. Send the user to `verification_uri_complete` to approve before `expires_in` seconds elapse. 3. `POST /api/v1/device/token` with `{ device_code }`, no more often than every `interval` seconds. While unresolved it returns `400` with a `code`: only `authorization_pending` means keep polling; `access_denied`, `expired_token`, and `invalid_grant` are terminal. On approval it returns `200` with `{ access_token, token_type, key_id, user_id, expires_at, org }`. `access_token` is the `cxy_live_` key, returned once; persist it immediately. ## Tiers `model` is a public tier: `canto`, `saga`, or `epos`. It also accepts `auto`, which the server-side router resolves to a tier per request, before billing and the upstream call; an `auto` request may be budget-downgraded to `epos`, so read `cruxy.routed_tier` on the response for the tier that served the call (see [Auto routing](/docs/en/build/auto-routing)). Never send an upstream provider id; tiers are the stable contract. Discover the catalog at runtime instead of hardcoding: ```bash curl https://api.cruxy.ai/api/v1/models \ -H "Authorization: Bearer $CRUXY_API_KEY" ``` `GET /api/v1/models` returns `{ object: "list", data: [...] }`, each entry `{ id, object, label, profile, context_window, max_output, latency_target_ms, reasoning, supports_tools, supports_vision, supports_structured_output, pricing, created, owned_by }`. Read `context_window`, `max_output`, and `supports_tools` from the response rather than assuming them. [Choosing a tier](/docs/en/build/choosing-a-tier) compares the tiers. ## Chat `POST /api/v1/chat`. The request is OpenAI-shaped: ```bash title="curl" curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "canto", "stream": false, "messages": [{ "role": "user", "content": "Hello" }] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'canto', stream: false, messages: [{ role: 'user', content: 'Hello' }], }), }) const completion = await res.json() ``` Request fields beyond `model` and `messages`: | Field | Type | Notes | | --- | --- | --- | | `messages` | array | Each `{ role, content }`; `role` is `system`, `user`, `assistant`, or `tool`. | | `stream` | boolean | `true` for SSE, `false` for one JSON object. Optional; `false` by default. | | `temperature` | number | 0–2, forwarded upstream unchanged. Omit for the model default. | | `max_tokens` | integer | Upper bound on generated tokens. Clamped to the tier cap: `canto` 65,536, `saga` and `epos` 131,072. | | `reasoning_effort` | string | `none`, `low`, `medium`, or `high`; `none` disables reasoning. Default per tier: `canto` high, `saga` low, `epos` none. Thinking spends `max_tokens`, so a small `max_tokens` on `canto` can end with `finish_reason: "length"` and empty content; send `none` for short answers. See [Reasoning effort](/docs/en/build/reasoning-effort). | | `tools` | array | Function tools; see below. | | `tool_choice` | string or object | `none`, `auto`, `required`, or `{ type: "function", function: { name } }`. | | `memory` | object | `{ recall, capture }`, each a boolean. Off by default for a developer key; `true` needs the `memory` scope. See [Memory](/docs/en/build/memory). | | `rules` | boolean | Standing-rules injection. Off by default for a developer key; `true` needs the `rules` scope. See [Standing rules](/docs/en/build/rules). | ### Response shape The non-streaming and streaming responses differ in shape; read the one that matches your `stream` value. `stream: false` returns a single object with the reply at the top level (not an OpenAI `choices[]` array): ```json { "id": "chatcmpl-8f3a1c2d", "model": "canto", "message": { "role": "assistant", "content": "Hi." }, "finish_reason": "stop", "usage": { "input_tokens": 12, "output_tokens": 48, "billable_input_tokens": 12, "cache_read_tokens": 0, "cache_write_tokens": 0, "cost": { "tier": "canto", "amount": "<amount>", "currency": "<currency>" } }, "cruxy": { "request_id": "…", "routed_tier": "canto", "reasoning_effort": "high" } } ``` `<amount>` and `<currency>` are placeholders; a real `amount` is a number. Amounts are specific to your account and shown in your Cruxy Console. `stream: true` is an OpenAI-style Server-Sent Events stream: each event is a `chat.completion.chunk` on a `data:` line, terminated by `data: [DONE]`. Chunks use the `choices[].delta` shape: ```text data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hi"}}]} data: [DONE] ``` ```ts const reader = res.body!.getReader() const decoder = new TextDecoder() let buffer = '' while (true) { const { value, done } = await reader.read() if (done) break buffer += decoder.decode(value, { stream: true }) const events = buffer.split('\n\n') buffer = events.pop() ?? '' for (const event of events) { const line = event.replace(/^data: /, '').trim() if (line === '[DONE]') break const chunk = JSON.parse(line) // choices[0].delta.content is the token } } ``` The final chunk carries `usage` as `{ prompt_tokens, completion_tokens, total_tokens, cost, … }`. ### Tool calling Pass `tools`, each `{ type: "function", function: { name, description, parameters } }` where `parameters` is a JSON Schema object. When the model calls one, the turn ends with `finish_reason: "tool_calls"` and the assistant message carries `tool_calls`: ```json { "id": "call_abc123", "type": "function", "function": { "name": "get_weather", "arguments": "{\"city\":\"Paris\"}" } } ``` `arguments` is a JSON-encoded string; parse it. Run the function, then continue the conversation with the assistant message that made the call, kept whole, followed by one tool result per call, tied back by `tool_call_id`, and send the same `tools` again: ```ts messages.push( message, // the assistant turn as returned, tool_calls included { role: 'tool', tool_call_id: 'call_abc123', content: JSON.stringify(result) }, ) ``` Repeat while `finish_reason` is `tool_calls`; the turn with `finish_reason: "stop"` carries the answer. [Handle tool calls](/docs/en/build/tool-calls) has the full loop. ## Embeddings `POST /api/v1/embeddings` with `model: "cruxy-embed"`. `input` is a string or an array of strings; one embedding is returned per input, in order. ```bash curl https://api.cruxy.ai/api/v1/embeddings \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "cruxy-embed", "input": ["hello", "world"] }' ``` Returns `{ object: "list", model, data: [{ object: "embedding", index, embedding: [...] }], usage: { prompt_tokens, total_tokens }, cruxy }`. ## Rerank `POST /api/v1/rerank` with `model: "cruxy-rerank"`, a `query`, and a `documents` array of candidate strings. Optional `top_n` caps how many results come back. ```bash curl https://api.cruxy.ai/api/v1/rerank \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "cruxy-rerank", "query": "What is the capital of France?", "documents": ["Paris is the capital of France.", "Berlin is in Germany."], "top_n": 3 }' ``` Returns `{ model, results: [{ index, relevance_score }], usage, cruxy }`, ranked by `relevance_score` descending. Each result's `index` points back into the `documents` you sent. ## Moderations `POST /api/v1/moderations` with `model: "cruxy-guard"`. `input` is a string or an array; one result is returned per input. ```bash curl https://api.cruxy.ai/api/v1/moderations \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "cruxy-guard", "input": "text to classify" }' ``` Returns `{ id, model, results: [{ flagged, categories, category_scores }] }`. `flagged` is the overall boolean; `categories` is a per-label boolean map over `harassment`, `hate`, `illicit`, `self-harm`, `sexual`, and `violence` (with their `/`-suffixed subtypes). `category_scores` mirrors it as numbers, but the guard model emits labels, so those are binary `1.0`/`0.0`, not calibrated probabilities. This endpoint returns no `cruxy` block and no `usage`. ## Errors Every failure is `{ code, error, request_id }`. Branch on `code`: it is stable; `error` is human text that may change. | Status | `code` | Meaning | | --- | --- | --- | | 400 | `invalid_request` | Malformed request. Fix it; a retry fails the same way. | | 400 | `context_overflow` | Chat input exceeded the context window: the smaller of the tier's and the plan's. | | 401 | `unauthorized` | Bearer key missing, malformed, unknown, expired, or revoked. | | 429 | `rate_limited` | Requests too fast. Back off, then retry. | | 429 | `budget_exhausted` | The plan's usage pool, monthly or 12-hour burst, is spent. A retry won't clear it until `reset_at`. | The device-login endpoints use OAuth-style `400` codes (`authorization_pending`, `access_denied`, `expired_token`, `invalid_grant`) instead of this shape. ## The cruxy block Cruxy-native fields are additive and namespaced under a `cruxy` key, so a vanilla OpenAI client ignores them and keeps parsing. What the block carries differs by endpoint: - Chat: `{ request_id, routed_tier, reasoning_effort }`. Token counts and `cost` live in the sibling `usage` object, not here. - Embeddings and rerank: `{ request_id, cost }`. - Moderations: no top-level block. The request id is the response's `id`, formatted `modr-<request_id>`, and a flagged result carries `results[].cruxy.hazard_codes`. `request_id` is a UUID for the call. Log it; it identifies the call in support requests. See [Request IDs and metadata](/docs/en/build/request-ids). ================================================================================ Page: Docs MCP server URL: https://learn.cruxyai.com/docs/en/resources/mcp-server Markdown: https://learn.cruxyai.com/docs/en/resources/mcp-server.md ================================================================================ # Docs MCP server Connect an MCP client to these docs at learn.cruxyai.com/mcp to list, read, and search every page as tools. Public and read-only, with no key. Cruxy Learn is also a Model Context Protocol (MCP) server, so the agent in your editor or chat app can look up a page while it works instead of guessing. It serves the same pages as this site, rebuilt on every deploy. It never calls the Cruxy API, takes no API key, and needs no account. ## Endpoint ```text https://learn.cruxyai.com/mcp ``` The server speaks MCP's Streamable HTTP transport, statelessly: every request is one JSON-RPC message sent with `POST`, answered with JSON, and there is no session id to keep. `GET` and `DELETE` answer `405`. There is no authentication and no cookie, and CORS allows any origin, so a browser-based client can connect too. ## Add it to your client Add it as a remote HTTP MCP server in your client, with the endpoint above as its URL. In Claude Code, the command is: ```bash claude mcp add --transport http cruxy-docs https://learn.cruxyai.com/mcp ``` To share it with your team through a project's `.mcp.json`, Claude Code reads this entry: ```json { "mcpServers": { "cruxy-docs": { "type": "http", "url": "https://learn.cruxyai.com/mcp" } } } ``` Both forms are from [Connect Claude Code to tools via MCP](https://code.claude.com/docs/en/mcp). For any other client, use its own setting for a remote HTTP server. ## Tools The server has three tools. All three are read-only and deterministic: the same input returns the same output until the next deploy. | Tool | Input | Returns | | --- | --- | --- | | `list_pages` | None | Every page in navigation order, each with `title`, `description`, `url`, `markdown_url`, and `section` (its tab). The same list as `/llms.txt`. | | `get_page` | `url_or_slug`, a string of up to 300 characters | The page as markdown, exactly as its `.md` URL serves it. | | `search_docs` | `query`, 1 to 200 characters; `limit`, 1 to 10, default 5 | `results`, best match first, each with `title`, `url`, `section`, and `snippet`, the passage that matches. | `get_page` accepts a page URL (`https://learn.cruxyai.com/docs/en/build/chat`, with or without `.md`), a site path (`/docs/en/build/chat`), or a slug (`build/chat`). A slug that ends only one page's URL works on its own, so `quickstart` finds the quickstart; one that ends two, such as `chat`, returns an error listing both URLs. `search_docs` matches keywords, not meaning: it ranks pages by the words they share with your query, with extra weight on words in the title. Use the words the docs would use, such as `rate limit 429` or `stream tool calls`. Each page is also an MCP resource, at its `.md` URL with the type `text/markdown`, for clients that browse resources rather than call tools. ## Call it without a client A tool call is one `POST`. The `Accept` header must list both `application/json` and `text/event-stream`, as the transport requires: ```bash title="curl" curl https://learn.cruxyai.com/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search_docs","arguments":{"query":"rate limit 429","limit":3}}}' ``` ```ts title="TypeScript" import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js' const client = new Client({ name: 'docs-lookup', version: '1.0.0' }) await client.connect( new StreamableHTTPClientTransport(new URL('https://learn.cruxyai.com/mcp')), ) const { tools } = await client.listTools() console.log(tools.map((tool) => tool.name)) const result = await client.callTool({ name: 'search_docs', arguments: { query: 'rate limit 429', limit: 3 }, }) console.log(result.structuredContent) await client.close() ``` The TypeScript sample uses the official MCP TypeScript SDK (`npm install @modelcontextprotocol/sdk`) and runs as an ES module. ## Limits | Limit | Value | Over it | | --- | --- | --- | | Requests per client IP | 60 per 5 minutes | `429` with `Retry-After` | | Request body | 16 KiB, one JSON-RPC message (no batches) | `413`, or `400` for a batch | | Time per request | 4 seconds | `503` with `Retry-After` | Connecting costs a client four or five requests (initialize, its follow-up notification, and the lists of tools and resources), and each tool call costs one more. A `429` clears on its own: wait the `Retry-After` seconds, then retry. ================================================================================ Page: Known limitations URL: https://learn.cruxyai.com/docs/en/build/known-limitations Markdown: https://learn.cruxyai.com/docs/en/build/known-limitations.md ================================================================================ # Known limitations What the Cruxy API does not do today, why each limit matters for your code, and the workaround to use until it changes. These are the limits you are most likely to hit when you build on the API. Each entry says what happens, why it matters, and what to do instead. When the API changes, the [Changelog](/docs/en/reference/changelog) records it by version. ## Canto's thinking spends max_tokens - **What:** `canto` reasons by default, at `reasoning_effort` `high`, and a reasoning tier writes its thinking inside the same `max_tokens` budget as its answer. `POST /api/v1/chat` returns the thinking beside the answer as `cruxy.reasoning`, from `Cruxy-Version: 2026-11-12` and when a request sends no `Cruxy-Version`, and `POST /api/v2/chat` returns it as a separate `reasoning` string. `POST /v1/chat/completions` does not return it. No wire reports a reasoning-token count. - **Why it matters:** A small `max_tokens` on `canto` can be spent entirely on thinking. The call ends with `finish_reason: "length"` and empty content, and no wire says how many of the output tokens the thinking used. - **Workaround:** For a short, direct answer, send `reasoning_effort: "none"`. To keep the reasoning, leave `max_tokens` unset, which gives the tier's cap (65,536 on `canto`). Treat `finish_reason: "length"` with empty content as a spent budget, not an empty answer. See [Reasoning effort](/docs/en/build/reasoning-effort). ```bash title="curl" # reasoning_effort "none" turns canto's thinking off, so the whole # max_tokens budget goes to the answer. curl https://api.cruxy.ai/api/v1/chat \ -H "Authorization: Bearer $CRUXY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "canto", "reasoning_effort": "none", "max_tokens": 256, "messages": [ { "role": "user", "content": "In one sentence, what is a monsoon?" } ] }' ``` ```ts title="TypeScript" const res = await fetch('https://api.cruxy.ai/api/v1/chat', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CRUXY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'canto', // Thinking off: the whole max_tokens budget goes to the answer. reasoning_effort: 'none', max_tokens: 256, messages: [{ role: 'user', content: 'In one sentence, what is a monsoon?' }], }), }) if (!res.ok) throw new Error(`chat failed: ${res.status} ${await res.text()}`) const completion = await res.json() if (completion.finish_reason === 'length' && !completion.message.content) { // The budget ran out before any answer was written. throw new Error(`no answer within max_tokens (request_id ${completion.cruxy.request_id})`) } console.log(completion.message.content) ``` ## Token counting answers count_unavailable for now - **What:** `POST /api/v1/tokens/count` answers `503` `count_unavailable` on every tier. The endpoint counts with a tokenizer vendored for the model behind a tier, and none is vendored for the V1 models yet, so it withholds the count rather than return one that could disagree with billing. - **Why it matters:** A client that sized requests with it before sending them gets no number back. Chat is unaffected: every call is billed on the provider's count and reports it in `usage`. - **Workaround:** Read `usage.input_tokens` from a real call, or `billable_input_tokens` for what was billed, and estimate from there. Treat `count_unavailable` as a fact of the deployment, not a fault to retry; the [Changelog](/docs/en/reference/changelog) will record the count coming back. ## Non-streaming calls have a 90-second ceiling - **What:** With `stream: false`, the gateway makes one attempt, bounded by the tier's deadline: 90 seconds on `canto` and `saga`, and 45 seconds on `epos`. Past it, the call is cancelled and answered `504` `upstream_timeout`. It is not billed, and the gateway does not retry it. - **Why it matters:** A long `canto` turn, with reasoning on and a large output, can need more than 90 seconds. The same request takes as long again on a retry, so retrying it unchanged times out every time. - **Workaround:** Stream long turns with `stream: true`: a stream may run for up to five minutes. Otherwise, ask for less with a lower `max_tokens` or `reasoning_effort`. See [Reliability](/docs/en/build/reliability#deadlines-and-timeouts). ## Signed-in keys expire in 90 days, and can't be rotated - **What:** A key from device login or native OAuth login is a signed-in credential. It stops working at its `expires_at`, 90 days after issue by default. Use does not extend it, there is no refresh grant, and it cannot be rotated. Its holder can revoke it with `DELETE /api/v1/me/key`. - **Why it matters:** A tool that stores one stops working the moment it expires, with `401` `unauthorized`, the same answer as a revoked key. - **Workaround:** On a server, use a developer API key, created in the Cruxy Console: it does not expire, and you rotate or revoke it there. In a person's own tool, store `expires_at` with the key and prompt for a new login before it passes. On sign-out, or if the key leaks, revoke it with `DELETE /api/v1/me/key`. See [Revoke the current key](/docs/en/get-started/api-keys#revoke-the-current-key). ## Tool-call IDs may not use OpenAI's call_ format - **What:** A tool call's `id` is a string with no documented format. It is not guaranteed to start with the `call_` prefix OpenAI uses, even though the examples in these docs show `call_abc123`. - **Why it matters:** Code that validates, parses, or generates ids on the `call_` pattern can reject a real call or fail to match its result. When the model makes several calls in one turn, `tool_call_id` is the only thing that says which result answers which call. - **Workaround:** Treat each `id` as opaque. Copy it unchanged into the `tool_call_id` of your result, key any lookup on the whole string, and never build an id yourself. See [Handle tool calls](/docs/en/build/tool-calls). ## No per-language list for Indic languages - **What:** Cruxy supports 20+ Indic languages, but it publishes no list of which ones, and the tier catalog at `GET /api/v1/models` has no language field. - **Why it matters:** Neither the docs nor the API can confirm that a specific language is supported, or how well each tier handles it. - **Workaround:** Before you launch in a language, test it on each tier you plan to use, with prompts from your own product. An eval suite under `/api/v1/evals/suites` runs the same cases against the tier you name; each case is billed as a chat completion. [Indic languages](/docs/en/build/indic-languages) covers encoding and token counts. ## Next steps - [Reliability](/docs/en/build/reliability): deadlines, retries, and confirming a stream finished. - [Reasoning effort](/docs/en/build/reasoning-effort): control how much a tier thinks. - [Get your API key](/docs/en/get-started/api-keys): choose between a signed-in key and a developer API key. - [Handle tool calls](/docs/en/build/tool-calls): answer each call by its `tool_call_id`. - [OpenAI SDK compatibility](/docs/en/migrate/openai-sdk-compatibility): what `POST /v1/chat/completions` supports, ignores, and rejects. ================================================================================ Page: Support URL: https://learn.cruxyai.com/docs/en/resources/support Markdown: https://learn.cruxyai.com/docs/en/resources/support.md ================================================================================ # Support Check platform status at status.cruxyai.com, look up an error, and email support@cruxyai.com with the IDs that let support find your request. When a call fails or behaves in a way you do not expect, work through these in order: check whether the platform is having a problem, look the behavior up, then write to support with what it needs to find your request. ## Check platform status [status.cruxyai.com](https://status.cruxyai.com) is the Cruxy status page. To read the same picture from your own monitoring, call `GET /api/status`, which takes no key; see [Reliability](/docs/en/build/reliability#check-platform-status). ## Look it up Most failures are described, with what to do about them, on one of these: - [Errors and retries](/docs/en/build/errors-and-retries): every error `code`, and which ones to retry. - [Rate limits and budgets](/docs/en/build/rate-limits): a `429`, and the headroom you have left. - [Reliability](/docs/en/build/reliability): deadlines, timeouts, and telling a finished stream from a failed one. - [Known limitations](/docs/en/build/known-limitations): what the API does not do today, and the workaround. ## Email support Write to [support@cruxyai.com](mailto:support@cruxyai.com). Send enough to find the call without a round of questions: - **The IDs,** whole and exactly as returned: the `X-Request-Id` header, and for a success its per-call `request_id` too. If you retried, the IDs of every attempt. - **The `Cruxy-Version`** the response named. - **The method and path,** such as `POST /api/v1/chat`, and whether `stream` was on. - **The HTTP status and the `code`.** The `error` message alone is not enough. - **When it happened,** in UTC. - **The `key_id`,** if the problem is with a key. Never send the key itself. [Request IDs and metadata](/docs/en/build/request-ids#report-a-problem) shows where each ID is in a response. ## If a key leaks - **A developer API key:** revoke it in the Cruxy Console, and issue a new one. - **A signed-in credential** from device login: revoke it with `DELETE /api/v1/me/key`, sent with that key. If you no longer hold it, email [support@cruxyai.com](mailto:support@cruxyai.com) with its `key_id` to have it revoked. See [Revoke the current key](/docs/en/get-started/api-keys#revoke-the-current-key). ## Tell Cruxy how a call went To report how a call turned out, rather than a fault, send [Feedback](/docs/en/build/feedback) joined to the call's `request_id`. ## Next steps - [Production checklist](/docs/en/best-practices/production-checklist): log what support will ask for before you need it. - [Request IDs and metadata](/docs/en/build/request-ids): where each ID is.