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 and Streaming.

Send a request

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.

Request fields

These are the body fields 2.2.0 sends, with their names on the wire:

SDK fieldWire fieldNotes
modelmodelcanto, saga, epos, or auto. Required.
messagesmessagesRequired. 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.
maxTokensmax_tokensThe output cap.
temperaturetemperature
reasoningEffortreasoning_effortnone, low, medium, or high; see Reasoning effort.
responseFormatresponse_format{ type: 'json_schema', jsonSchema: { name, schema, strict } }, or type text or json_object.
toolstoolsFunction tools; see Call tools.
toolChoicetool_choicenone, auto, required, or { type: 'function', function: { name } }.
memorymemory{ recall, capture }, each true or false; see Memory and rules.
rulesrulestrue or false; see Memory and rules.
vaultIdvault_idThe vault this chat runs inside.
mentionedVaultIdsmentioned_vault_idsVaults this turn references without being inside them.
streamstreamSet 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.

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.

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.

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 and Standing 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.

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:

FieldWhat it holds
messageThe reply: role, content, and toolCalls when the model called tools.
finishReasonstop, tool_calls, length, or content_filter.
routingThe served tier, how it was chosen in mode (explicit, auto, or auto_degraded), and reasoningEffort.
usageinputTokens, outputTokens, billableInputTokens, the cache counters, and cost.
requestIdThe call's request ID; see Request IDs.
id, modelThe completion's ID and the tier that served it.
reasoningA reasoning tier's thinking trace, when it thought. It is never part of message.content.
memoryRecall, memoryCapture, rulesAppliedWhat memory was recalled and stored, and which rules were applied, when any were.
filesOmitted, undeclaredToolReplayFiles 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.

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:

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:

PropertyFilled from
routing, id, model, requestIdThe start frame, before the first delta.
startThe whole start frame, with memoryRecall, rulesApplied, filesOmitted, and undeclaredToolReplay.
contentEvery delta so far, joined.
reasoningEvery reasoning frame so far, joined. Empty unless the tier thinks, and never mixed into content.
toolCallsTool-call fragments so far, assembled by index into { index, id, type, name, arguments }.
finishReason, usageThe finish frame.
finishThe whole finish frame, with memoryCapture.
completedtrue 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:

OptionBoundsDefault
timeoutMsThe wait for response headers, on each attempt.The client's timeoutMs.
idleTimeoutMsThe 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.
totalTimeoutMsThe whole call, connect included.None.
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.

Stream errors

A stream that fails throws. Wrap the request and the loop together:

ErrorWhen
CruxyErrorThe request failed before the stream opened, with any 4xx or 5xx. The same class, with the same fields, that chat.createChatCompletion throws.
ChatStreamFrameErrorThe stream ended with an error frame. It carries code, requestId, partialContent, usage when the frame reports it, and retryable.
IncompleteChatStreamErrorThe 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.
ChatStreamTimeoutErroridleTimeoutMs or totalTimeoutMs passed. A subclass of IncompleteChatStreamError, with timeout (idle or total) and timeoutMs.
MalformedChatStreamErrorA frame did not parse, or was missing a required field.
RequestAbortedErrorYour 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.

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.

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:

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.

Was this page helpful?