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.
Requirements
@cruxy/api2.2.0 or later. 2.2.0 addsauth.revokeCurrentKeyand each tier'ssupportsStructuredOutput. 2.1.0 is the first release that accepts the tier idscanto,saga, andepos; an older release rejects them before the request is sent. Since 2.1.2, every request pins aCruxy-Versionthat reads them back, so every response names the tier by its current id; see 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.
Install
npm install @cruxy/api@^2.2.0The 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
import { Cruxy } from '@cruxy/api'
const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY })bearerAuth is your API key, sent as Authorization: Bearer <key> 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.
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. |
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. |
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 |
chat.stream | POST /api/v2/chat with stream: true | Chat with the TypeScript SDK |
embeddings.createEmbeddings | POST /api/v1/embeddings | Embeddings, rerank, and more with the SDK |
rerank.rerankDocuments | POST /api/v1/rerank | Embeddings, rerank, and more with the SDK |
moderations.createModeration | POST /api/v1/moderations | Embeddings, rerank, and more with the SDK |
models.listModels | GET /api/v1/models | Embeddings, rerank, and more with the SDK |
auth.getCurrentIdentity, auth.revokeCurrentKey | GET /api/v1/me, DELETE /api/v1/me/key | Embeddings, rerank, and more with the SDK |
deviceLogin.startDeviceLogin, deviceLogin.pollDeviceToken | POST /api/v1/device/code, POST /api/v1/device/token | Embeddings, rerank, and more with the SDK |
feedback.submitFeedback | POST /api/v1/feedback | Embeddings, rerank, and more with the SDK |
tokens.countTokens | POST /api/v1/tokens/count | Embeddings, rerank, and more with the SDK |
files.uploadFile, files.listFiles, files.getFile, files.downloadFileContent, files.deleteFile | /api/v1/files | 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:
idempotencyKeysendsIdempotency-Keyon the methods that take one:chat.createChatCompletion,chat.stream,embeddings.createEmbeddings,rerank.rerankDocuments,moderations.createModeration, andfiles.uploadFile. See SDK errors, retries, and timeouts.cruxyVersionsets theCruxy-Versiona request pins, on every method; see Request IDs and metadata. Without it, every request pins the version the SDK was generated against; see 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.
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.
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, andepos. The SDK still accepts the former ids, but responses name the tier by its new id; see Deprecated aliases. - Paths and server. Every method except chat calls its
/api/v1/path, and the default server ishttps://api.cruxy.ai, so you can dropserverURL. The responses are the same. - Required fields. Fields the gateway always required are now required in
the types. An assistant message that carries only
toolCallsmust sendcontent: ''. - Errors. Every method throws
CruxyError, with a parsedcode, for every error status. See Error classes. - Retries follow the gateway's per-code contract, so budget and spend-cap
429s are not retried, andchat.streamuses the client'sretryConfig. - Stream timeouts.
timeoutMsno longer cuts off a stream that is still sending. To cap a whole stream, passtotalTimeoutMs. - Chat fields. The request takes
memory,rules,toolChoice,vaultId,mentionedVaultIds, andfileIdson a message, and the response carriesreasoning.
Next steps
Send a chat request, stream the reply, call tools, and control memory, rules, and files per request.
Embeddings, rerank, moderations, models, token counting, your key's identity, device login, and feedback.
The error classes, retries and the codes they skip, timeouts, idempotency, and request IDs.