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