Use evaluators as a library
Run Fabric Experiments judges and code evaluators with your own model provider and gate the results in CI.
Use the @fabricorg/experiments-evals root export to score application outputs
in a TypeScript script or CI job. Supply a ModelClient for the judge and pass
in the outputs you want to evaluate. The runner returns results in memory, so
you can decide where to store them.
Run a judge and a code evaluator
This example uses Vercel AI SDK 7 with the OpenAI provider. Install the packages in a project running Node.js 22.19.0 or newer.
pnpm add \
@fabricorg/experiments-evals \
ai@7 \
@ai-sdk/openai@4Set OPENAI_API_KEY in your environment, save the example as evaluate.mts,
and run node evaluate.mts.
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';
import {
codeEvaluator,
runEvalGate,
qaCorrectnessJudge,
type ModelClient,
} from '@fabricorg/experiments-evals';
const modelId = 'gpt-4.1-mini';
const model: ModelClient = {
endpoint: modelId,
async complete(messages, options) {
const { text, usage } = await generateText({
model: openai.chat(modelId),
messages: [...messages],
temperature: options.temperature,
maxOutputTokens: options.maxOutputTokens,
maxRetries: 0,
});
const inputTokens = usage?.inputTokens;
const outputTokens = usage?.outputTokens;
if (inputTokens === undefined || outputTokens === undefined) {
throw new Error('Judge response is missing an input or output token count.');
}
return { text, tokens: { inputTokens, outputTokens } };
},
};
const nonEmpty = codeEvaluator('non-empty', '1.0.0', ({ output }) => ({
score: typeof output === 'string' && output.trim().length > 0 ? 1 : 0,
}));
const evaluators = [qaCorrectnessJudge, nonEmpty];
const result = await runEvalGate({
evaluators,
items: [
{
itemId: 'reset-mfa',
input: {
input: 'Where do I reset MFA?',
output: 'Open the security settings page.',
expectedOutput: 'Use the security settings page.',
},
},
],
model,
gates: "non-empty>=1,qa-correctness/mean>=0.9",
metadata: { judgeModel: modelId },
maxJudgeTokens: 2_000,
});
console.table(result.aggregates);
if (!result.passed) {
throw new Error(JSON.stringify(result.reasons));
}Wrap the OpenAI or Anthropic SDK directly using the same ModelClient contract.
Map the messages to the provider's format, pass the temperature and output-token
ceiling, and return the reply text with the provider's input and output counts.
Compare candidate variants
Use executePairwiseRun with pairwiseQualityJudge or your own
PairwiseJudge. This is a library API. The CLI, local gate, and MLflow export
have no pairwise integration.
import { executePairwiseRun, pairwiseQualityJudge } from '@fabricorg/experiments-evals';
const result = await executePairwiseRun({
judge: pairwiseQualityJudge,
ctx: { model, nowMs: () => performance.now() },
items: [
{
itemId: 'reset-mfa',
input: 'Where do I reset MFA?',
expectedOutput: 'Use the security settings page.',
outputs: {
baseline: 'Open your account settings.',
candidate: 'Open the security settings page and select MFA.',
},
},
],
concurrency: 2,
timeoutMs: 10_000,
maxJudgeTokens: 5_000,
});
console.table(result.aggregates);Provide unique item IDs and at least two nonempty variant names per item. A pair
uses only items that carry both variants. The judge sees the input, optional
reference, and candidates as first and second. Keep variant labels out of
the supplied content too. The built-in judge uses JSON-serializable content and
accepts a single PREFERENCE: first, PREFERENCE: second, or PREFERENCE: tie
reply after trimming surrounding whitespace.
The runner submits both presentation orders. A candidate wins if both verdicts
prefer it after mapping the positions back to variants. Other verdict
combinations tie. The order disagreement count tracks items whose two mapped
verdicts differ. For example, preferring the first position in both calls
produces a tie and an order disagreement. A missing verdict, failed call,
timeout, or budget skip makes the item-pair unscored and records the affected
call in failures.
The run reserves tokens per call, charges the full reservation on timeout, and
counts valid reported usage even when a reply has no verdict. Budgeted runs
admit canonical batches of up to concurrency calls and settle each batch
before admitting the next. A reservation that does not fit at admission is
skipped. onBudgetSkip and onFailure receive call-level records in canonical
order after judging.
Variants A and B are ordered by name using JavaScript string order. For each
pair, netPreference.point averages +1 for a win by A, 0 for a tie, and −1 for
a win by B. netPreference also carries a 95%
percentile bootstrap interval using seed 0 and 2,000 resamples. The item is the
sampling unit. The interval assumes independent, identically distributed
scored items and may give poor coverage with small or unrepresentative samples.
Unscored items are excluded. If none are scored, netPreference is null. The
seed fixes resampling; provider verdicts can vary across runs. Record the
dataset version, output-generation configuration, judge name and version, model
endpoint, and run options when retaining comparison results.
Account for judge tokens
Report real provider usage for both input and output. The built-in judge passes
temperature: 0 and an output ceiling of 256 tokens to ModelClient.complete.
When using DatabricksModelClient, the client extracts and concatenates
type: "text" entries from content-part arrays (ignoring reasoning parts and
failing on malformed parts or finish_reason: "length" with no answer text),
and supports omitTemperature: true for endpoints that reject temperature
(such as Anthropic Claude from Opus 4.7 onward, including Claude 5) — callers
still pass temperature and the client still validates it, but it is not sent;
repeatability is left to the endpoint, so record separately (for example by
endpoint) if you need to know it was not applied.
Its maxJudgeTokens(input) uses maxCompletionTokenUsage on the rendered
messages. That bound adds their UTF-8 content bytes, a framing allowance of
16 plus 16 per message, and the output ceiling.
The runner sizes each judge reservation using the larger of that bound and
reserveTokensPerCall, if supplied. With a run-level maxJudgeTokens, it skips
the judge call if spent tokens plus outstanding reservations plus the new
reservation would exceed the budget. Code evaluators reserve zero tokens and
continue after a budget skip. skippedForBudget counts affected items and
skippedEvaluationsForBudget counts skipped judge evaluations.
The built-in judge validates both token counts before adding them and rejects usage above its own bound. The runner also validates usage on returned scores and checks it against positive reservations. An LLM judge must return both counts, even if both are zero. Code and heuristic evaluators can omit usage.
Missing or invalid judge usage is recorded in failures. The runner releases
the reservation and excludes the score and its usage from the totals. These
checks happen after the provider call. Zero counts are valid, so report the
provider's actual usage and let the example's guard reject absent counts
instead of replacing them with zeros.
Bound evaluation and generation waits
Set timeoutMs on executeEvalRun to limit the wait for each evaluation trial
in milliseconds. The value must be a positive integer. Omit it to run without
a timer. A timeout records an evaluator failure, charges the full reservation
to the run budget, and allows remaining evaluations to continue. The model
call can still spend tokens after timeout. The runner discards late results.
For model-generated outputs, executeGenerationPhase defaults to one
completion at a time for durable executors. Set its positive integer
concurrency option to opt into concurrent waits. In-flight reservations
count toward maxTokens. Successes and failures are each returned in input
order. A true shouldStop result stops new completions from starting and
lets active workers record their outcomes. Use its positive integer
timeoutMs to bound each wait. A timed-out output is excluded from judging
and the full reservation counts as spent.
Repeat trials and summarize uncertainty
Set trials to a positive integer in executeEvalRun or runEvalGate.
The default is 1. Each item runs that many times per selected evaluator,
subject to the shared judge budget. Runner scores and failures include the
zero-based trial, and the runner passes it to onBudgetSkip as the third
argument. Progress still counts items.
Pass executeEvalRun's score rows to aggregateScoredItems to get
itemMeanInterval for binary and graded evaluators. It is a 95% percentile
bootstrap of the equally weighted item means, using seed 0 and 2,000
resamples. Trials of one item share the same resampling unit. Duplicate rows
for the same item, evaluator name and version, and trial throw. The interval
assumes independent, representative items and can give a narrow or point
interval with a small dataset. With no numeric scores, it returns null.
trialDisagreementShare is the fraction of items with different numeric scores
among items with at least two scored trials. It is null when no item qualifies.
Null, skipped, and failed trials contribute no value to the item mean or
disagreement share. The bare-score aggregateScores keeps its original fields.
meanScore and passRate.rate summarize numeric trial rows, so their values
can differ from the equally weighted item mean when items have different
numbers of scored trials. The legacy Wilson bounds assume independent score
rows. Use itemMeanInterval for uncertainty with repeated trials.
Gate a local run
Use runEvalGate from a script or assert result.passed in a Vitest test.
The library works in memory and needs only the evals package. With precomputed
outputs and pure code evaluators, the run makes no network call. An LLM judge
requires its configured ModelClient.
Supply unique item IDs. Duplicate IDs cause the local gate to throw before
generation or judging. Use evaluatorNames on an item to select its evaluators.
Omit it to apply the full list. An empty list fails the gate with an empty-evaluator-selection
reason containing the item ID. Unknown names produce unknown-evaluator
reasons, even when other selected evaluators run. Repeated names in a selection
specify one evaluator. For an item whose output is undefined, the optional async
produce(item) runs sequentially once per trial before evaluation. It can return
{ kind: 'output', output, metadata? } to share the output across the selected
evaluators, or { kind: 'could-not-evaluate', reason }. When metadata is a
plain object, the gate passes a shallow merge of the item's metadata and the
producer's metadata (producer keys winning) to the evaluators for that trial
without mutating the item; per-trial metadata is not written to the evidence.
Non-plain-object producer metadata, a generation refusal, or an exception records
a generation-error, fails the gate, and skips judging for that trial.
Precomputed outputs are reused across trials. The judge budget and concurrency apply to evaluation, and
timeoutMs bounds each evaluator trial. A timeout appears as an
evaluator-failure with that trial's sampleIndex in the v1 evidence.
Use <evaluator> or <evaluator>/mean for the mean of numeric scores.
Use <evaluator>/pass_rate for the share of binary scores equal to 1. That
metric is missing when there are no numeric scores or any numeric score
is neither exactly 0 nor exactly 1 (for example, 0.5). An exact evaluator name takes precedence over a suffix alias.
A null score counts toward maxUnscoredShare for that evaluator, which defaults
to zero. Generation errors, evaluator failures, budget skips, empty evaluator selections, unknown or unused
evaluators, empty datasets, missing metrics, and failed comparisons fail the gate.
LocalEvalResult validates the versioned JSON evidence emitted by the library
and the CLI.
| Field | Contents |
|---|---|
schemaVersion, samplesPerCase | Schema version 1 and the requested trial count. |
metadata | Dataset content hash, model under test, judge model, prompt ID and version, sampling settings, and string-valued labels when supplied. runEvalGate rejects unrecognized top-level metadata keys, symbol or non-enumerable keys on metadata or labels, and a label key named __proto__ before generation or judging; LocalEvalResult ignores unknown top-level keys when reading evidence. |
evaluators, aggregates | Evaluator identities and versions, scored and unscored trial counts, mean, binary pass rate with legacy Wilson bounds, item mean interval, trial disagreement share, label counts, token totals, and mean latency. |
cases | Item ID, evaluator identity and version, zero-based trial index (sampleIndex), score, and any label, rationale, or reported tokens. |
couldNotEvaluate | Generation errors, evaluator failures, and budget skips, with item ID, sampleIndex, and evaluator identity where applicable. |
gates, passed, reasons | Each comparison and its observed value, the gate verdict, and structured failure reasons. |
Pass a prior result to compareEvalBaseline(current, baseline, tolerance).
The comparison refuses invalid evidence, differing schema versions, missing or
different dataset hashes, and baseline evaluator identities missing from the
current run. It refuses a saved run with passed: false as
baseline-did-not-pass. It fails a mean drop greater than the tolerance or a
missing current mean for a previously scored evaluator.
Passed and failed comparisons include notCompared. Each entry reports the
evaluator name and version, with reason unscored-in-baseline for a null
prior mean or not-in-baseline for a current identity absent from the baseline.
Entries with null prior means follow baseline evaluator order, then additions
follow current evaluator order. The array is empty when all evaluators were
compared. The caller decides whether to compare an added evaluator against
other evidence. The current run's own gates judge its absolute quality.
Version 1 baselines can omit
itemMeanInterval and trialDisagreementShare. Valid run labels and
unrecognized metadata keys in baseline evidence do not affect the comparison.
A baseline whose labels are not string-valued, or that has a label key named
__proto__, is invalid evidence and is refused.
Choose an evaluation path
| Use | When |
|---|---|
| Experiments library | Run application-side checks in TypeScript with your own model provider, built-in judges, and judge token accounting. Use Experiments for versioned evaluation datasets. |
| Native MLflow scorers | Keep scoring in managed MLflow when the evaluation already runs there. Link the native run into Quality Center when you need a Fabric release gate. |
Harness fh test | Use @fabric-harness/evals to smoke-check an agent project with deterministic scorers and a simple judge. Use @fabricorg/experiments-harness-evals to adapt Experiments evaluators as Harness scorers or collect Harness cases for an Experiments run. |
Evaluate AI applications
Build reproducible, tenant-aware AI quality suites for Databricks Model Serving with TypeScript datasets, judges, prompts, traces, and warehouse evidence.
Databricks-native AI quality
Keep MLflow, Unity Catalog, Model Serving, and AI Gateway authoritative while Fabric adds TypeScript automation and cross-workload release gates.