Scores, datasets and experiments (TypeScript)
Use score to record judgements on traces, Client to manage datasets, and evaluate to run your code over a dataset and score the results.
Scores
Section titled “Scores”// The returned id is yours to keep: pass it back as `scoreId` to update.const id = score({ name: "helpful", value: 0.8, sessionId: "chat-42", reason: "human review" });return id;Scores are queued in the background and posted to /api/v1/scores in
batches (up to 10 000 buffered), with retries on 429/5xx and network errors.
The target is a traceId + spanId pair, a traceId, or a sessionId;
currentTraceId() / currentSpanId() give the ids of the running span.
Values map: boolean → boolean, number → numeric, string → categorical
label (or dataType: "text"). userId comes from the active
withContext unless passed.
Datasets and experiments
Section titled “Datasets and experiments”new Client() is the REST client for datasets and experiments. It reads
apiKey and baseUrl the way init() does (argument, then
CETRA_API_KEY / CETRA_BASE_URL, then the default), and throws
ConfigError without a key. Unlike tracing and scores, its calls reject on
failure (see Errors).
client.prompts manages prompts over the same client: get reads a prompt at a label or a version without the cache, list returns the prompt names, create and createVersion add a prompt and a version, and setLabel moves a label to a version. Its calls reject with ApiError on failure. Application code reads prompts with the cached getPrompt() instead. The Prompts page shows how the prompts are fetched and linked.
Datasets
Section titled “Datasets”import { Client } from "@cetra-ai/sdk";
const client = new Client(); // the key and URL come from the environment
let dataset = await client.datasets.create("faq-v1", { description: "FAQ questions" });dataset = await dataset.addItems([ { input: { q: "How do I cancel?" }, expectedOutput: { a: "Settings > Billing > Cancel" }, metadata: { topic: "billing" }, },]);dataset = await client.datasets.get("faq-v1", { version: 1 }); // the items of version 1console.log((await client.datasets.list()).map((info) => info.name));await client.datasets.delete("faq-v1"); // the dataset and its items- An item is
input(any JSON value, required),expectedOutput(optional) andmetadata(an object, default{}). Any other key throws aTypeErrorbefore a request is sent. addItemssends batches of 1,000 items, and each batch makes a new version. Versions are integers: a new dataset is at version 0 and has no items.addItemsresolves to the dataset at its latest version. If a later batch fails, the earlier batches are already stored (each made a version), and the promise rejects.get(nameOrId, { version })reads a version with all its items; withoutversionit reads the current one.create(name, { inputSchema, expectedSchema })takes JSON Schemas (Draft 2020-12). The server checks every item written afterwards against them; a refused item rejects with anApiError, and itserrorsarray names the failing fields.
Annotation queues
Section titled “Annotation queues”People review the traces, spans or sessions of a queue in the web UI; the SDK creates queues and fills them.
import { Client } from "@cetra-ai/sdk";
const client = new Client(); // the key and URL come from the environmentconst definitionId = "..."; // a score definition of the project, made in the web UI
const queue = await client.annotationQueues.create("Weekly review", { target: "trace", definitionIds: [definitionId],});const result = await client.annotationQueues.addItems(queue.id, { traceIds: ["4bf92f3577b34da6a3ce929d0e0e4736"],});console.log(result.added, result.existing, result.skipped); // skipped: index and messagecreate(name, { target, definitionIds, description, instructions })makes a queue whose items are"trace","span"or"session". The target cannot change later.definitionIdslists one to fifty score definitions, in review order.addItems(queueId, targets)takes exactly one oftraceIds,spans(a list of[traceId, spanId]pairs) orsessionIds, and aTypeErroris thrown before any request when it does not. It sends batches of 1,000. A target already in the queue counts asexisting. Each entry ofskippedhas theindexof a target in your list and amessage; the message never repeats the value.items(queueId, { status })lists the items, optionally only those with"pending","completed"or"skipped";list()andget(queueId)read the queues.update(queueId, { version, ... })changes the fields you pass.versionis the one you read, and a stale one is refused with anApiError(409). An empty string clearsdescriptionorinstructions.delete(queueId)removes the queue and its items.
Reviewers’ actions (taking a lease, completing or skipping an item) happen in the web UI only.
Experiments
Section titled “Experiments”evaluate runs your task on every item of a dataset version, scores each
run, and stores the results on the server. It needs init() first.
import { evaluate, init, type Score } from "@cetra-ai/sdk";
init(); // the key comes from CETRA_API_KEY
function exact({ output, expected }: { output: unknown; expected: unknown }): boolean { return String(output).trim() === (expected as { a: string }).a.trim();}
function lengthOk({ output }: { output: unknown }): Score { const text = String(output); return { value: text.length < 500, reason: `${text.length} chars` };}
const result = await evaluate({ dataset: "faq-v1", task: (input) => myApp.answer((input as { q: string }).q), scorers: [exact, lengthOk], experimentName: "gpt-5-mini prompt v3", metadata: { model: "gpt-5-mini", prompt: "v3" }, concurrency: 8, repetitions: 1,});console.log(result.summary());result.assertMin("exact", 0.8); // throws when the mean is below 0.8- Dataset. A name, an id or a
Datasetobject. ADatasetruns at the version it holds;datasetVersionpins another one. ADatasetat version 0 has no items, so no version is sent and the server uses its current version. - Task.
task(input, item)receivesitem.inputand theDatasetItem. It may return a promise. - Scorers. A scorer’s name is its function’s name: a named function or a
constworks, while an anonymous function or a duplicate name is refused with aTypeErrorbefore any request. It receives one object withinput,output,expected(the item’sexpectedOutput),metadata,traceIdanditem. - Scorer return values.
booleanis a boolean score,numbera numeric one (finite),stringa categorical label. AScore({ value, reason, dataType, metadata }) adds the reason and metadata;undefinedornullmeans no score. Anything else counts as a scorer error. - Concurrency and repetitions.
concurrencyis 1 to 64 (default 8);repetitionsis 1 to 20 (default 1). Each run records its 0-basedrepetition.experimentNameis 1 to 200 characters; by default it is the dataset name and the UTC time. - Result.
summary()prints one line per scorer with its mean and count, and the experiment id.errorCountcounts runs whose task threw;assertMin(name, threshold)throws when a score’s mean is below the threshold, which is what a CI gate needs.
What gets recorded
Section titled “What gets recorded”- Each run is one trace: its root span (kind
chain, named after the experiment) carries the input and the task’s output, and every span the task starts carries the experiment id, the dataset item id and the environmentexperiment. The default trace lists leave these traces out. - A score needs its trace, so with
sampleRatebelow 1 some runs have no trace and no score. Scores are queued and posted in batches, andawait flush()waits for them. - Nothing is scored on the server: a judge runs inside a scorer.
- Results are uploaded in batches; each upload is retried on transient failures.
The API key needs the ingest, read and write scopes.
Errors
Section titled “Errors”ConfigError names the option that is missing or invalid, never its value.
ApiError carries status, code, detail and errors (the field errors of
a refused dataset item). A task or scorer that throws does not stop the run:
the error is recorded on that run, and errorCount and the summary count it.