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/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.
  • 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.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

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

OptionDefaultWhat it does
bearerAuthCRUXY_BEARER_AUTHThe API key, or an async function that returns it.
serverURLhttps://api.cruxy.aiThe API host.
retryConfigno retriesRetry policy for every method, chat.stream included; see SDK errors, retries, and timeouts.
timeoutMsno timeoutAbort a request that takes longer, in milliseconds. On chat.stream it bounds only the wait for response headers; see SDK errors, retries, and timeouts.
httpClientfetchA custom HTTPClient, for hooks around every request.
userAgentthe SDK's ownOverrides the User-Agent header.
debugLoggernoneA 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:

MethodRequestGuide
chat.createChatCompletionPOST /api/v2/chatChat with the TypeScript SDK
chat.streamPOST /api/v2/chat with stream: trueChat with the TypeScript SDK
embeddings.createEmbeddingsPOST /api/v1/embeddingsEmbeddings, rerank, and more with the SDK
rerank.rerankDocumentsPOST /api/v1/rerankEmbeddings, rerank, and more with the SDK
moderations.createModerationPOST /api/v1/moderationsEmbeddings, rerank, and more with the SDK
models.listModelsGET /api/v1/modelsEmbeddings, rerank, and more with the SDK
auth.getCurrentIdentity, auth.revokeCurrentKeyGET /api/v1/me, DELETE /api/v1/me/keyEmbeddings, rerank, and more with the SDK
deviceLogin.startDeviceLogin, deviceLogin.pollDeviceTokenPOST /api/v1/device/code, POST /api/v1/device/tokenEmbeddings, rerank, and more with the SDK
feedback.submitFeedbackPOST /api/v1/feedbackEmbeddings, rerank, and more with the SDK
tokens.countTokensPOST /api/v1/tokens/countEmbeddings, rerank, and more with the SDK
files.uploadFile, files.listFiles, files.getFile, files.downloadFileContent, files.deleteFile/api/v1/filesAttach 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.
  • cruxyVersion sets the Cruxy-Version a 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, and epos. 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 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.
  • Retries follow the gateway's per-code contract, so budget and spend-cap 429s 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

Send a chat request, stream the reply, call tools, and control memory, rules, and files per request.

Embeddings, rerank, and more with the SDK

Embeddings, rerank, moderations, models, token counting, your key's identity, device login, and feedback.

SDK errors, retries, and timeouts

The error classes, retries and the codes they skip, timeouts, idempotency, and request IDs.

Was this page helpful?