Evaluation Framework
Systematically evaluate LLM agents with @cogitator-ai/evals — dataset-driven testing, deterministic and LLM-as-judge metrics, assertions, A/B comparison, and CI-ready reporters.
Why Evaluate?
LLM outputs are non-deterministic. A prompt change that improves one response might degrade ten others. Without systematic evaluation, you're flying blind. @cogitator-ai/evals gives you a structured way to measure agent quality, catch regressions, and compare model configurations — all with statistical rigor.
Installation
pnpm add @cogitator-ai/evalsOptional dependencies: papaparse for CSV datasets, and @cogitator-ai/core for agent targets and LLM-as-judge metrics:
pnpm add papaparse
pnpm add @cogitator-ai/coreTo run suites as Vitest tests with describeEval from @cogitator-ai/evals/vitest, add vitest, an optional peer dependency:
pnpm add -D vitestQuick Start
import { Dataset, EvalSuite, exactMatch, contains, threshold } from '@cogitator-ai/evals';
const dataset = Dataset.from([
{ input: 'What is 2+2?', expected: '4' },
{ input: 'Capital of France?', expected: 'Paris' },
{ input: 'Largest planet?', expected: 'Jupiter' },
]);
const suite = new EvalSuite({
dataset,
target: {
fn: async (input) => {
// your agent or LLM call here
return 'some response';
},
},
metrics: [exactMatch(), contains()],
assertions: [threshold('exactMatch', 0.8)],
});
const result = await suite.run();
result.report('console');Architecture
┌──────────┐ ┌───────────┐ ┌─────────┐ ┌────────────┐
│ Dataset │───▶│ EvalSuite │───▶│ Metrics │───▶│ Assertions │
└──────────┘ └───────────┘ └─────────┘ └────────────┘
│ │
▼ ▼
┌───────────┐ ┌────────────┐
│ Target │ │ Reporters │
└───────────┘ └────────────┘Eval flow: Load test cases from a Dataset (JSONL, CSV, or programmatic) → EvalSuite runs each case against a Target (agent or function) with concurrency control → Metrics score each response → Scores are aggregated (mean, median, p95, etc.) → Assertions check thresholds and regressions → Reporters output results to console, JSON, CSV, CI, JUnit XML or a GitHub job summary.
EvalSuite
The core class that orchestrates evaluation runs.
import { EvalSuite, exactMatch, latency, threshold } from '@cogitator-ai/evals';
const suite = new EvalSuite({
dataset,
target: { fn: async (input) => answer(input) },
metrics: [exactMatch()],
statisticalMetrics: [latency()],
assertions: [threshold('exactMatch', 0.8)],
concurrency: 5,
timeout: 30000,
retries: 1,
onProgress: ({ completed, total }) => console.log(`${completed}/${total}`),
});| Option | Default | Description |
|---|---|---|
dataset | — | Dataset of cases |
target | — | What to evaluate — see Target |
metrics | [] | Per-case metrics |
statisticalMetrics | [] | Metrics over the whole run (latency(), cost(), tokenUsage(), passAtK()) |
judge | — | { model, temperature?, maxTokens?, cogitator?, cache?, concurrency?, samples? } (JudgeConfigInput, temperature defaults to 0), required for LLM metrics |
assertions | [] | Pass/fail checks |
concurrency | 5 | Cases run in parallel |
timeout | 30000 | Per-attempt timeout in ms (minimum 1000) |
retries | 0 | Extra attempts for a failed or timed-out case (max 10) |
trials | 1 | Runs of each case, each scored on its own, see Trials and pass@k |
onProgress | — | Called with { completed, total, currentCase } after each case |
Errors and timeouts are retried up to retries times. If every attempt fails, the case result has an empty output and an error message (for example Timed out after 30000ms), so a failed run is never mistaken for an empty answer. No metric scores it, so it costs no judge calls and does not count as a 0: the aggregates cover the cases that answered (count says how many), and stats.errors or the maxErrorRate assertion catch a run where many cases failed.
An agent target's case result also says how the run ended: truncated when the answer stopped at the output token limit, iterationLimitReached when tool calls used up maxIterations, and paused when the run waits for tool approvals. The reporters show them.
A timed-out attempt is cancelled, not abandoned: the suite aborts the attempt's AbortSignal, which stops an agent target's run, and waits for the attempt to stop (at most another timeout) before it retries. So a cancelled attempt does not keep running and paying in the background, attempts of one case never overlap, and concurrency holds. A fn target gets the signal as context.signal and should pass it on to its model call.
A failure never drops a case: a metric that throws or returns a score that is not a finite number (such as NaN) scores 0 for that case with the reason in score.error, and an onProgress callback that throws is reported as a process warning instead of crashing the run.
Target
The target defines what you're evaluating. Use fn for a simple function, or agent + cogitator for a full Cogitator agent:
import { Agent, Cogitator } from '@cogitator-ai/core';
import type { EvalTarget } from '@cogitator-ai/evals';
const fnTarget: EvalTarget = {
fn: async (input, { signal }) => myApp.answer(input, { signal }),
};
const cogitator = new Cogitator();
const agentTarget: EvalTarget = {
agent: new Agent({
name: 'support',
model: 'openai/gpt-5.5',
instructions: 'Answer support questions briefly.',
}),
cogitator,
};A target has either fn or both agent and cogitator, anything else throws when the suite is created. An agent target runs cogitator.run(agent, { input, context, signal, onToolResult }) with the case's context, and records the run's usage (tokens, cost), toolCalls, toolResults and the passages its tools retrieved on the case result. cost() and tokenUsage() read the usage, the agent metrics the rest, and an optional retrieval on the target reads passages out of your own tools' results. The usage is summed over every attempt that reported one, so an attempt that finished after it timed out still counts, and attempts says how many the case took. A fn target is called as fn(input, { signal, case, attempt, turn, history }) and only records the duration.
A case with turns is a conversation: an agent target runs every turn on one thread, so the Cogitator needs memory, and a fn target is called once per turn. See Multi-turn Cases.
Results
suite.run() returns EvalSuiteResult with everything you need:
const result = await suite.run();
result.results; // per-case { case, output, duration, error?, usage?, toolCalls?, toolResults?, retrieved?, turns?, trials?, scores }
result.aggregated; // { exactMatch: { mean, median, p95, ... }, ... }
result.assertions; // [{ name, passed, message }, ...]
result.stats; // { total, errors, metricErrors, duration (ms), cost, targetCost, judgeCost }
result.report('console');
result.report(['json', 'csv'], { path: './eval-report' });
result.saveBaseline('./baseline.json');stats.errors counts cases whose every attempt failed (with several trials, a case counts as errored when every trial errored), stats.metricErrors the metric scores that failed and count as 0. stats.cost is what the run spent, targetCost (the target, over all attempts) plus judgeCost (the LLM judge), so a budget assertion sees the judge too.
Results keep the dataset order regardless of concurrency. See Reporters and baselines.
To try a suite on a slice of the dataset, pass EvalRunOptions:
const smoke = await suite.run({ maxCases: 5 });Only the first maxCases cases run; results, aggregated, assertions, stats.total and the onProgress totals cover just those cases. maxCases must be a positive integer, otherwise run() throws.
To cancel a run, pass a signal:
const controller = new AbortController();
const running = suite.run({ signal: controller.signal });
controller.abort();The attempts in flight are aborted, no further case starts, and run() rejects with the signal's reason.
EvalBuilder
Fluent builder API as an alternative to direct EvalSuite construction:
import {
EvalBuilder,
Dataset,
exactMatch,
contains,
latency,
threshold,
} from '@cogitator-ai/evals';
const suite = new EvalBuilder()
.withDataset(dataset)
.withTarget({ fn: myFn })
.withMetrics([exactMatch(), contains()])
.withStatisticalMetrics([latency()])
.withAssertions([threshold('exactMatch', 0.9)])
.withConcurrency(10)
.withTimeout(15000)
.withRetries(1)
.withTrials(3)
.onProgress(({ completed, total }) => console.log(`${completed}/${total}`))
.build();
const result = await suite.run();Use .withJudge({ model, temperature?, cogitator }) when the metrics include LLM-as-judge metrics; build() throws without it, or without a dataset or target.
Agent Tool
evalTools(suite) returns a run_eval tool so an agent can run a suite and read the summary:
import { Agent, tool } from '@cogitator-ai/core';
import { evalTools } from '@cogitator-ai/evals';
const [runEval] = evalTools(suite);
const qaAgent = new Agent({
name: 'qa',
model: 'openai/gpt-5.5',
instructions: 'Run the eval suite and report regressions.',
tools: [tool(runEval)],
});The tool takes an optional maxCases and returns { success, total, duration, cost, metrics, assertionsPassed }, where metrics holds the mean of each metric. With maxCases the tool calls suite.run({ maxCases }), so only the first N cases run and total, metrics and assertionsPassed are computed from them. Errors come back as { success: false, error }. createRunEvalTool(suite) builds the same tool.
Next Steps
- Datasets — load test cases from JSONL, CSV, or build programmatically
- Metrics — deterministic, LLM-as-judge, statistical, and custom metrics
- Agent Evaluation - tool calls, trajectories, retrieval, multi-turn cases, trials and pass@k
- Assertions — threshold checks, regression detection, custom assertions
- A/B Comparison — compare two targets with statistical significance testing
- Experiment Tracking - save named runs as run files, keep them in a
RunStoreand compare them case by case withcompareRuns() - Reporters - console, JSON, CSV, JUnit, Markdown, HTML, GitHub Actions and CI output, plus
describeEvalfor Vitest
Twilio Phone Calls
Answer phone calls with a Cogitator agent through Twilio Media Streams - signed upgrades, one-time session tokens, μ-law audio, barge-in and memory of only what the caller heard.
Datasets
Load evaluation test cases from JSONL files, CSV files, or build them programmatically with filtering, sampling, and shuffling.