Scores, datasets and experiments (Python)
Use score to record judgements on traces, cetra.Client to manage datasets, and evaluate to run your code over a dataset and score the results.
Scores
Section titled “Scores”cetra.score(...) attaches a score to a trace, a span or a session. It
returns the score id — a UUIDv7 minted in the SDK — or None when nothing was
queued. Passing score_id updates that score instead of creating one, which
makes retries idempotent.
import cetra
cetra.init(api_key="sk-cetra-test")
with cetra.span("answer", input="why?") as s: s.set_output("It is 42.") score_id = cetra.score( trace_id=cetra.current_trace_id(), name="correct", value=True, reason="matches the reference answer", )
cetra.flush() # also waits for pending scores- Target (one of):
trace_id+span_id(a span),trace_idalone (a trace), orsession_id(a session). Ids are the lowercase hex stringscetra.current_trace_id()/cetra.current_span_id()return. - Value:
True/Falseis boolean, a number is numeric (must be finite), a string is categorical with the string as label, or passdata_type="text"for free text.data_typemay also forcenumeric,booleanorcategoricaland must match the value’s type. reason,user_id(taken from the activecontext()unless passed) andmetadataare optional. Metadata values are strings, or any other value serialized to compact JSON.- Invalid input logs one warning —
cetra: score not queued: <reason>— and returnsNone; nothing is queued and nothing raises. - Scores are buffered (up to 10 000; a full buffer drops with a warning that
counts the drops) and posted in batches of up to 1000 every second by a
background thread.
429,5xx, network errors and timeouts retry up to 3 more times, honouring an integerRetry-After(capped at 30 s, else 1 s, 2 s, 4 s); any other status drops the batch at once. flush()waits for pending scores too.cetra.uuid7()is exported if you need your own idempotent ids.
Datasets and experiments
Section titled “Datasets and experiments”cetra.Client is the REST client for datasets, experiments and annotation
queues. It reads api_key and base_url the way init() does (argument, then
CETRA_API_KEY / CETRA_BASE_URL, then the default), and raises
ConfigError without a key. Unlike tracing and scoring, its calls raise on
failure (see Errors).
Datasets
Section titled “Datasets”import cetra
client = cetra.Client() # the key and URL come from the environment
ds = client.datasets.create("faq-v1", description="FAQ questions")ds = ds.add_items( [ { "input": {"q": "How do I cancel?"}, "expected_output": {"a": "Settings > Billing > Cancel"}, "metadata": {"topic": "billing"}, } ])ds = client.datasets.get("faq-v1", version=1) # the items of version 1print([info.name for info in client.datasets.list()])client.datasets.delete("faq-v1") # the dataset and its items- An item is
input(any JSON value, required),expected_output(optional) andmetadata(a mapping, default{}). Any other key raisesValueErrorbefore a request is sent. add_itemssends 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.add_itemsreturns the dataset at its latest version. If a later batch fails, the earlier batches are already stored (each made a version), and the error is raised.get(name_or_id, version=...)reads a version with all its items; withoutversionit reads the current one.create(..., input_schema=..., expected_schema=...)takes JSON Schemas (Draft 2020-12). The server checks every item written afterwards against them; a refused item raisesApiError, and itserrorslist names the failing fields.
Annotation queues
Section titled “Annotation queues”Members review the items of a queue in the UI. The SDK creates queues and fills them with traces, spans or sessions.
import cetra
client = cetra.Client() # the key and URL come from the environmentdefinition_id = "01900000-0000-7000-8000-000000000600" # a score definition's id
queue = client.annotation_queues.create( "Weekly review", target="trace", definition_ids=[definition_id])result = client.annotation_queues.add_items( queue.id, trace_ids=["4bf92f3577b34da6a3ce929d0e0e4736"])print(result.added, result.existing)for skip in result.skipped: # skip.index is the position in the list you passed print(skip.index, skip.message)- Target.
targetis"trace","span"or"session". It is fixed for the queue’s life.definition_idsare the score definitions a review fills in, in order (1 to 50, all distinct). - Adding.
add_itemstakes exactly one oftrace_ids,spans(pairs of(trace_id, span_id)) orsession_ids. It sends batches of 1,000. A target already in the queue counts asexistingand keeps its review state. The server skips a target it cannot add, such as an unknown or hidden one, andskipped[].indexis its position in your list. - Methods.
get(queue_id),create(name, target=..., definition_ids=...),update(queue_id, version=...),delete(queue_id),list()anditems(queue_id, status=...).updatetakes theversionyou read; a stale one raisesApiErrorwith status409.deleteremoves the queue and its items, and the scores stay. - Reviews. Taking, completing and skipping items is done in the UI only.
The key needs the
writescope to manage queues and items.
Experiments
Section titled “Experiments”cetra.evaluate runs your task on every item of a dataset version, scores
each run, and stores the results on the server. It needs cetra.init()
first.
import cetra
cetra.init() # the key comes from CETRA_API_KEY
def task(input: dict) -> str: # receives item.input; may also take (input, item) return my_app.answer(input["q"])
def exact(output: str, expected: dict) -> bool: # scorers take any of the names below return output.strip() == expected["a"].strip()
def length_ok(output: str) -> cetra.Score: # a Score carries a reason return cetra.Score(value=len(output) < 500, reason=f"{len(output)} chars")
result = cetra.evaluate( dataset="faq-v1", task=task, scorers=[exact, length_ok], experiment_name="gpt-5-mini prompt v3", metadata={"model": "gpt-5-mini", "prompt": "v3"}, concurrency=8, repetitions=1,)print(result.summary())result.assert_min("exact", 0.8) # raises AssertionError when the mean is below 0.8- Dataset. A name, an id or a
Datasetobject. ADatasetruns at the version it holds;dataset_version=pins another one. ADatasetat version 0 has no items, so nodataset_versionis sent and the server uses its current version. - Task.
task(input)when it takes one positional parameter, ortask(input, item)when it takes two or more (itemis theDatasetItem). Async tasks go throughaevaluate:await cetra.aevaluate(...).evaluaterefuses a coroutine function. - Scorers. Each scorer’s name is its function’s name; lambdas, partials
and duplicate names are refused before any request. Its parameters are
chosen by name from
input,output,expected(the item’sexpected_output),metadata,trace_idanditem; a**kwargsparameter receives all of them. A required parameter with another name is refused. - Scorer return values.
boolis a boolean score,int/floata numeric one (finite),stra categorical label.cetra.Score(value=..., reason=..., data_type=..., metadata=...)adds the reason and metadata;Nonemeans 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 row records its 0-basedrepetition.experiment_nameis 1 to 200 characters; by default it is the dataset name and the UTC time. summary()prints one block per experiment: the run and error counts, then per scorer the mean of numeric and boolean values (booleans count as 0 and 1), or the label counts of a categorical one, and its scorer errors.assert_min(name, threshold)raisesAssertionErrorwhen the mean of a numeric or boolean scorer is belowthreshold, or when it has no such values. Use it to gate CI.ExperimentResultholdsexperiment_id,runs(oneRunper item and repetition, in item order:dataset_item_id,repetition,input,expected_output,output,error,trace_id,latency_ns,scores),error_countandscorer_errors.
What gets recorded
Section titled “What gets recorded”- Each run is one trace. Its root span is named after the experiment, has
kind
chainand the item’s input, and every span started inside it, the instrumentors’ included, carries the experiment and dataset item ids with environmentexperiment, whateverinit()set. Experiment traces are excluded from the default trace lists. - A task exception ends that run’s span with the error and sets the run’s
errorto"<ExceptionName>: <message>"; a scorer exception gives that run no score. Neither aborts the experiment. - Scores go through the score queue, attached to the run’s trace. A run
without a trace (sampling below 1 drops its root span) keeps its scores in
the local result only, and
evaluatewarns once. - Scorers run in your process; the server never scores experiments. A judge is a scorer that calls a model.
- Results are uploaded in batches of up to 500 rows or 32 MiB. An output over 256 KiB (its JSON) is cut to 260,000 bytes and marked as truncated.
- When the monthly units cap pauses score uploads, the scores are dropped with a warning; the run continues, and the local result still holds them.
summary()prints the experiment id, not a link to the UI.
Prompts
Section titled “Prompts”client.prompts manages the prompt registry from scripts and CI: get(name, label=..., version=...) reads a prompt version without the SDK’s cache, list() returns the prompt names, create adds a prompt with its first version, create_version adds a version, and set_label(name, label, version) moves a label to a version. The label production is the default for get. Each call raises ApiError on an error answer, like the dataset calls. Writes are sent once and never retried; reads retry like the other client reads. The Prompts page shows how the prompts are fetched and linked.
The key needs the read, write and ingest scopes. read covers listing
and reading datasets and experiments, write creates datasets, items and
experiments and uploads their results, and ingest sends spans and scores.
A key without one of them gets a 403, which raises ApiError.
Errors
Section titled “Errors”ConfigError: no API key, orevaluatebeforecetra.init().ValueError(TypeErrorfor a wrong type) for a bad argument, named in the message. Nothing is sent.ApiErrorfor an error answer from the API. Itsstatus,codeanddetailcome from the server’s problem,errorsholds the field errors. The message is the method, the route template (/datasets/{dataset}/items, never a name), the status and, when the server sends them, the code and the detail. The server never puts item content in a detail.- Retries: network errors, timeouts,
429and5xxare retried up to three times for reads, deletes, result uploads andfinish. Creates and item writes are sent once, so a failure there is never retried silently. evaluateraises the firstApiErrorwhen a result upload fails. It stops the new runs, finishes the experiment with the errorresults upload failed, and raises.