# Scores, datasets and experiments (TypeScript) Attach scores to traces, manage datasets with the REST client and run experiments with evaluate. 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 ```ts // 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 `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](#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](https://cetra.sh/docs/evaluation/prompts/) page shows how the prompts are fetched and linked. ### Datasets ```ts 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 1 console.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) and `metadata` (an object, default `{}`). Any other key throws a `TypeError` before a request is sent. - `addItems` sends 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. `addItems` resolves 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; without `version` it 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 an `ApiError`, and its `errors` array names the failing fields. ### Annotation queues People review the traces, spans or sessions of a queue in the web UI; the SDK creates queues and fills them. ```ts import { Client } from "@cetra-ai/sdk"; const client = new Client(); // the key and URL come from the environment const 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 message ``` - `create(name, { target, definitionIds, description, instructions })` makes a queue whose items are `"trace"`, `"span"` or `"session"`. The target cannot change later. `definitionIds` lists one to fifty score definitions, in review order. - `addItems(queueId, targets)` takes exactly one of `traceIds`, `spans` (a list of `[traceId, spanId]` pairs) or `sessionIds`, and a `TypeError` is thrown before any request when it does not. It sends batches of 1,000. A target already in the queue counts as `existing`. Each entry of `skipped` has the `index` of a target in your list and a `message`; the message never repeats the value. - `items(queueId, { status })` lists the items, optionally only those with `"pending"`, `"completed"` or `"skipped"`; `list()` and `get(queueId)` read the queues. - `update(queueId, { version, ... })` changes the fields you pass. `version` is the one you read, and a stale one is refused with an `ApiError` (`409`). An empty string clears `description` or `instructions`. - `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 `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. ```ts 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 `Dataset` object. A `Dataset` runs at the version it holds; `datasetVersion` pins another one. A `Dataset` at version 0 has no items, so no version is sent and the server uses its current version. - **Task.** `task(input, item)` receives `item.input` and the `DatasetItem`. It may return a promise. - **Scorers.** A scorer's name is its function's name: a named function or a `const` works, while an anonymous function or a duplicate name is refused with a `TypeError` before any request. It receives one object with `input`, `output`, `expected` (the item's `expectedOutput`), `metadata`, `traceId` and `item`. - **Scorer return values.** `boolean` is a boolean score, `number` a numeric one (finite), `string` a categorical label. A `Score` (`{ value, reason, dataType, metadata }`) adds the reason and metadata; `undefined` or `null` means no score. Anything else counts as a scorer error. - **Concurrency and repetitions.** `concurrency` is 1 to 64 (default 8); `repetitions` is 1 to 20 (default 1). Each run records its 0-based `repetition`. `experimentName` is 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. `errorCount` counts 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 - 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 environment `experiment`. The default trace lists leave these traces out. - A score needs its trace, so with `sampleRate` below 1 some runs have no trace and no score. Scores are queued and posted in batches, and `await 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. ### Keys The API key needs the `ingest`, `read` and `write` scopes. ### 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.