Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ arguments and filters, for example `understudy workloads route --help`.
| `workloads` | `list`, `show`, `create`, `update`, `route` | Model tasks, capture settings, and explicit model traffic routes. |
| `models` | `list`, `show` | Models in your organization's catalog. |
| `benchmarks` | `list`, `show` | Read published workload benchmarks and model recommendations. |
| `experiments` | `list`, `show`, `results` | Read online model experiments and compare control and candidate through the workload's evaluator. Browser OAuth only. |
| `evaluators` | `list`, `show`, `summary`, `scores` | Read workload evaluators, their rubrics, and judged results. Browser OAuth only; `scores` requires an organization admin. |
| `keys` | `list`, `create`, `exec`, `revoke` | API key metadata, private key storage, and credential delivery to a child process. |

New workloads have capture disabled by default. Setting a model route enables
Expand Down
42 changes: 42 additions & 0 deletions docs/resource-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ accept an id. A selector that matches multiple resources is an error.
| `benchmarks list` | List workloads and their current published benchmark, if any. |
| `benchmarks show --project <project> --workload <workload>` | Summarize the current benchmark and its recommendation without printing the full report. |
| `benchmarks show --project <project> --workload <workload> --include-report --json` | Return the full published benchmark manifest, including any recommendation report and prompt diff. |
| `experiments list [--project <project> [--workload <workload>]] [--status <status>]` | List experiments visible to the organization, newest first. |
| `experiments show <experiment>` | Show one experiment's models, share, audience, and status. |
| `experiments results <experiment> [--from <time>] [--to <time>]` | Compare control and candidate using the workload's evaluator summary. |
| `evaluators list [--project <project> [--workload <workload>]]` | List visible evaluators with their last 30 days of judged results. |
| `evaluators show [<evaluator>] [--project <project> --workload <workload>]` | Show the active version, judge, and rubrics, by id or workload. |
| `evaluators summary <evaluator> [--from <time>] [--to <time>]` | Summarize judged traces by model, rubric, and experiment arm. |
| `evaluators scores <evaluator> [filters] [--include-reasons]` | Page per-trace verdicts; organization admins only. |
| `keys list` | Return the key metadata page exposed by the platform. |
| `keys create --name <name>` | Create a key and privately retain its one-time value. |
| `keys exec <reference> -- <command> [args...]` | Inject a stored key into a child environment without printing it. |
Expand Down Expand Up @@ -146,5 +153,40 @@ an individual benchmark. A report's prompt label and optional diff are not a
guaranteed, versioned deployable prompt artifact; check the application prompt
before planning an update.

`experiments` and `evaluators` read the organization's customer API
(`/customer/v1`), which accepts only browser OAuth. Organization keys are
refused before any request. These commands are read-only; they never create,
activate, stop, or change experiments or evaluators, and send no inference.

An experiment assigns each session with an `x-understudy-session-id` to its
control or candidate model; requests without a session ID are excluded.
Experiments have no results API of their own. `experiments results` finds the
workload's visible evaluator and reads its summary over the experiment's life,
from creation to now, bounded to the API's 90-day maximum and reported as
clamped when shortened. It reports each arm's judged, rated, and passed traces,
the trace pass rate with its 95% interval, the cost of the judged call per
trace, and the candidate-minus-control difference. Rates and the difference
are `null` until an arm has 30 rated traces; the CLI does not compute its own.
Results cover the evaluator's current version only, so activating another
version restarts the comparison. Arms group traces by assignment: a fallback
response still counts in its assigned arm. Without a visible evaluator, or for
a draft, the command explains that results cannot be measured.

`experiments list` filters the platform's newest 200 experiments locally and
sets `possiblyTruncated` when that page is full. Project and workload selectors
are exact and resolved like other workload commands; `--workload` requires
`--project`. Human output summarizes a tag audience by its value count; JSON
includes the values.

The platform shows an evaluator only when it is visible to customers and not a
draft, and only its active version. `evaluators summary` and `scores` accept ISO
dates or UTC datetimes, default to the last 30 days, and refuse ranges over 90
days before sending a request. `evaluators scores` pages 1-20 results; the
platform can extend a page so that one trace's rubric verdicts stay together. Judge
reasons can quote the organization's traces, so they are omitted from text and
JSON unless `--include-reasons` is given; code-check reasons are the rubric's
own wording. If saving them for agent review, follow the benchmark guidance
above for the application's ignored `.understudy/` directory.

These contracts are covered by invented fixtures and mocked HTTP responses.
Source contracts and local tests do not establish live deployment availability.
4 changes: 4 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { addBenchmarksCommands } from "./commands/benchmarks.js";
import { addBillingCommands } from "./commands/billing.js";
import { addCapturesCommands } from "./commands/captures.js";
import { addContextCommands } from "./commands/context.js";
import { addEvaluatorsCommands } from "./commands/evaluators.js";
import { addExperimentsCommands } from "./commands/experiments.js";
import { addKeysCommands } from "./commands/keys.js";
import { addMigrationCommands } from "./commands/migrations.js";
import { addProjectsCommands } from "./commands/projects.js";
Expand Down Expand Up @@ -47,6 +49,8 @@ export function createCli(
addBenchmarksCommands(program);
addCapturesCommands(program);
addContextCommands(program);
addEvaluatorsCommands(program);
addExperimentsCommands(program);
addKeysCommands(program);
addModelsCommand(program);
addMigrationCommands(program);
Expand Down
117 changes: 117 additions & 0 deletions src/commands/evaluators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { Command } from "commander";

import { createCredentialStore } from "../auth/credentials.js";
import { createEvaluatorsService, type EvaluatorsService, type EvaluatorShowResult } from "../evaluators/service.js";
import type { Summary } from "../evaluators/contracts.js";
import { formatOutput, formatRateInterval as rateText, shellQuote } from "../output.js";

export function addEvaluatorsCommands(
program: Command,
service: EvaluatorsService = createEvaluatorsService({ store: createCredentialStore() }),
output = (message: string) => process.stdout.write(`${message}\n`),
): void {
const evaluators = program.command("evaluators")
.description("Read workload evaluators, their rubrics, and judged results. Requires browser OAuth.");

evaluators.command("list")
.description("List evaluators visible to the organization with their last 30 days of results.")
.option("--project <selector>", "Exact project id, slug, or name.")
.option("--workload <selector>", "Exact workload id or name within --project.")
.action(async function (this: Command, options: { project?: string; workload?: string }) {
const result = await service.list(options);
output(formatOutput(this, result, result.evaluators.length === 0
? "No visible evaluators match."
: [
...result.evaluators.map((row) => {
const rate = row.stats.trace_pass_rate ? rateText(row.stats.trace_pass_rate) : "not enough rated traces";
return `${row.id} ${row.status.padEnd(6)} ${row.project_slug}/${row.workload_name} v${row.version.version} ${row.stats.traces_judged} judged ${rate} ${row.name}`;
}),
`${result.evaluators.length} evaluator(s). Results cover the last 30 days.`,
]));
});

evaluators.command("show [evaluator]")
.description("Show an evaluator's active version and rubrics, by id or by workload.")
.option("--project <selector>", "Exact project id, slug, or name; defaults to saved context.")
.option("--workload <selector>", "Exact workload id or name; defaults to saved context.")
.action(async function (this: Command, evaluator: string | undefined, options: { project?: string; workload?: string }) {
const result = await service.show({ ...options, ...(evaluator === undefined ? {} : { evaluator }) });
output(formatOutput(this, result, evaluatorLines(result)));
});

evaluators.command("summary <evaluator>")
.description("Summarize judged results by model, rubric, and experiment arm.")
.option("--from <time>", "Start of the trace window (ISO date or UTC datetime). Default: 30 days before --to.")
.option("--to <time>", "End of the trace window. Default: now. The range spans at most 90 days.")
.action(async function (this: Command, evaluator: string, options: { from?: string; to?: string }) {
const result = await service.summary({ evaluator, ...options });
output(formatOutput(this, result, summaryLines(result)));
});

evaluators.command("scores <evaluator>")
.description("List per-trace verdicts. Organization admins only. Judge reasons are omitted unless --include-reasons.")
.option("--verdict <verdict>", "pass, fail, or na.")
.option("--model <model>", "Public served model of the judged call.")
.option("--rubric <name>", "Rubric name.")
.option("--from <time>", "Start of the trace window. Default: 30 days before --to.")
.option("--to <time>", "End of the trace window. Default: now.")
.option("--limit <count>", "Page size from 1 to 20. A page can run past it to finish the last trace's rubrics.")
.option("--cursor <cursor>", "Continue from a previous page.")
.option("--include-reasons", "Include judge reasons, which can quote the organization's traces.")
.action(async function (this: Command, evaluator: string, options: {
verdict?: string; model?: string; rubric?: string; from?: string; to?: string;
limit?: string; cursor?: string; includeReasons?: boolean;
}) {
const result = await service.scores({ evaluator, ...options });
output(formatOutput(this, result, [
...result.scores.map((score) => [
`${score.trace_ended_at} ${score.request_id} ${score.model} ${score.rubric} ${score.verdict}`,
...(result.reasonsIncluded && score.reason ? [` reason: ${score.reason}`] : []),
]).flat(),
result.scores.length === 0 ? "No scores match." : `${result.scores.length} score(s).`,
// The server-provided cursor contains a space; quote it as one shell
// word so the hint is safe to paste whatever characters it holds.
...(result.nextCursor ? [`More results: --cursor ${shellQuote(result.nextCursor)}`] : []),
]));
});
}

function evaluatorLines(result: EvaluatorShowResult): string[] {
const { evaluator } = result;
return [
`Evaluator ${evaluator.name}`,
`Id ${evaluator.id}`,
`Status ${evaluator.status}`,
`Workload ${evaluator.project_slug}/${evaluator.workload_name}`,
`Scores from ${evaluator.score_from}`,
`Version v${evaluator.version.version} (${evaluator.version.id})`,
`Judge ${evaluator.version.judge_model ?? "none (code checks only)"}`,
"Rubrics",
...evaluator.version.rubrics.flatMap((rubric) => [
` ${rubric.name} [${rubric.implementation === "deterministic" ? `code check: ${String(rubric.check?.type ?? "unknown")}` : "judge"}]`,
` pass when: ${rubric.pass_when}`,
` fail when: ${rubric.fail_when}`,
...(rubric.na_when ? [` n/a when: ${rubric.na_when}`] : []),
]),
...(result.experiments.length === 0 ? ["Experiments none"] : [
"Experiments",
...result.experiments.map((row) => ` ${row.id} ${row.status} ${row.control_model} -> ${row.candidate_model} ${row.name}`),
]),
];
}

function summaryLines(summary: Summary): string[] {
const rate = (stats: Summary["total"]) => stats.trace_pass_rate ? rateText(stats.trace_pass_rate) : "not enough rated traces";
return [
`Evaluator ${summary.evaluator_id} v${summary.version}`,
`Range ${summary.from ?? "?"} -> ${summary.to ?? "?"}`,
`Total ${summary.total.traces_judged} judged, ${summary.total.rated_traces} rated, pass ${rate(summary.total)}`,
...summary.total.rubrics.map((rubric) =>
` ${rubric.rubric.padEnd(24)} pass ${rubric.pass} fail ${rubric.fail} n/a ${rubric.na}`),
...(summary.by_model.length ? ["By model", ...summary.by_model.map((group) =>
` ${group.model.padEnd(32)} rated ${group.rated_traces} pass ${rate(group)}`)] : []),
...(summary.by_variant.some((group) => group.experiment_id) ? ["By experiment arm", ...summary.by_variant
.filter((group) => group.experiment_id)
.map((group) => ` ${group.experiment_id} ${group.variant ?? "?"} rated ${group.rated_traces} pass ${rate(group)}`)] : []),
];
}
109 changes: 109 additions & 0 deletions src/commands/experiments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { Command } from "commander";

import { createCredentialStore } from "../auth/credentials.js";
import type { Experiment, Interval } from "../evaluators/contracts.js";
import {
createExperimentsService,
type ExperimentArm,
type ExperimentResults,
type ExperimentsService,
} from "../experiments/service.js";
import { formatOutput, formatRateInterval } from "../output.js";

export function addExperimentsCommands(
program: Command,
service: ExperimentsService = createExperimentsService({ store: createCredentialStore() }),
output = (message: string) => process.stdout.write(`${message}\n`),
): void {
const experiments = program.command("experiments")
.description("Read online model experiments and their measured results. Requires browser OAuth.");

experiments.command("list")
.description("List experiments visible to the organization, newest first.")
.option("--project <selector>", "Exact project id, slug, or name.")
.option("--workload <selector>", "Exact workload id or name within --project.")
.option("--status <status>", "draft, active, or stopped.")
.action(async function (this: Command, options: { project?: string; workload?: string; status?: string }) {
const result = await service.list(options);
output(formatOutput(this, result, result.experiments.length === 0
? "No experiments match."
: [
...result.experiments.map((row) =>
`${row.id} ${row.status.padEnd(7)} ${scopeLabel(row)} ${row.control_model} -> ${row.candidate_model} ${row.candidate_percent}% ${row.name}`),
`${result.experiments.length} experiment(s).`,
...(result.possiblyTruncated ? ["Understudy returned its maximum page; older experiments may be missing."] : []),
]));
});

experiments.command("show <experiment>")
.description("Show one experiment's configuration.")
.action(async function (this: Command, experiment: string) {
const result = await service.show({ experiment });
output(formatOutput(this, result, experimentLines(result)));
});

experiments.command("results <experiment>")
.description("Compare control and candidate using the workload's evaluator.")
.option("--from <time>", "Start of the trace window (ISO date or UTC datetime). Default: experiment creation, at most 90 days back.")
.option("--to <time>", "End of the trace window. Default: now.")
.action(async function (this: Command, experiment: string, options: { from?: string; to?: string }) {
const result = await service.results({ experiment, ...options });
output(formatOutput(this, result, resultLines(result)));
});
}

function scopeLabel(row: Experiment): string {
return `${row.project_slug}/${row.workload_name ?? `${row.workload_id} (deleted)`} [${row.request_environment}]`;
}

function audience(row: Experiment): string {
return row.target_tag === null
? "all sessions with a session id"
: `sessions tagged ${row.target_tag} with one of ${row.target_values!.length} value(s)`;
}

function experimentLines(row: Experiment): string[] {
return [
`Experiment ${row.name}`,
`Id ${row.id}`,
`Status ${row.status}`,
`Workload ${scopeLabel(row)}`,
`Control ${row.control_model}`,
`Candidate ${row.candidate_model} (${row.candidate_percent}% of sessions)`,
`Audience ${audience(row)}`,
`Created ${new Date(row.created_at_ms).toISOString()}`,
`Updated ${new Date(row.updated_at_ms).toISOString()}`,
];
}

function resultLines(result: ExperimentResults): string[] {
const row = result.experiment;
const lines = [
`Experiment ${row.name} (${row.status})`,
`Workload ${scopeLabel(row)}`,
];
if (result.evaluator && result.range) {
lines.push(
`Evaluator ${result.evaluator.name} v${result.evaluator.version} (${result.evaluator.status})`,
`Range ${result.range.from} -> ${result.range.to}`,
armLine("control", row.control_model, result.control, result.minimumRatedTraces),
armLine("candidate", row.candidate_model, result.candidate, result.minimumRatedTraces),
`Difference ${difference(result.candidateMinusControl)}`,
);
}
return [...lines, ...result.notes.map((note) => `Note: ${note}`)];
}

function armLine(label: string, model: string, arm: ExperimentArm | null, minimum: number): string {
const head = `${label.padEnd(11)} ${model}`;
if (!arm) return `${head} no judged traces`;
const rate = arm.trace_pass_rate ? `pass ${formatRateInterval(arm.trace_pass_rate)}` : `pass rate needs ${minimum} rated traces`;
const cost = arm.cost_per_trace_usd === null ? "cost unknown" : `$${arm.cost_per_trace_usd.toFixed(4)}/trace`;
return `${head} rated ${arm.rated_traces} ${rate} ${cost}`;
}

function difference(interval: Interval | null): string {
if (!interval) return "not enough rated traces in both arms";
const pts = (value: number) => `${value >= 0 ? "+" : ""}${(value * 100).toFixed(1)}`;
return `${pts(interval.value)} pts [${pts(interval.low)}, ${pts(interval.high)}] (candidate - control, 95% interval)`;
}
Loading
Loading