Judges and plugins
Grade output with an LLM judge whose verdicts are cached in the fixture, and add your own assertions as plugins.
Judges
Some output can only be graded by a model: tone, faithfulness, whether an answer addresses the question. The judge
matcher hands the value and a rubric to a judge, a function you provide:
(request) -> { passed, score?, reason? }. Evals never calls a model on its own and ships no provider dependency
for judging.
llm_judge(complete=...) / llmJudge({ complete }) builds a judge from any completion function. It sends a
grading prompt with the rubric and the value, and expects JSON back. The value sits between <value-NONCE> tags
with a fresh random nonce per call, the prompt says that content is data, not instructions, and any </value- in
the value is written <\/value-. Only the last JSON object in the answer counts, and it must carry passed (a
boolean) or score (a number), so a verdict the graded value plants earlier in the reply is ignored. An LLM judge
can still be swayed by what it grades: gate releases on deterministic checks and use judges for what only a model
can grade.
# Build a judge from any completion function. It gets the grading prompt and returns the model's text, which must
# be JSON: {"passed": true, "score": 0.9, "reason": "..."}.
def complete(prompt: str, _request: object) -> str:
# In your project: send `prompt` to your model and return its text.
assert "Apologizes and gives a refund id" in prompt
return '{"passed": true, "score": 0.9, "reason": "apologizes and names R-1001"}'
strict = llm_judge(complete=complete)// Build a judge from any completion function. It gets the grading prompt and returns the model's text, which must
// be JSON: {"passed": true, "score": 0.9, "reason": "..."}.
const strict = llmJudge({
complete: async (prompt) => {
// In your project: send `prompt` to your model and return its text.
assert.ok(prompt.includes("Apologizes and gives a refund id"));
return '{"passed": true, "score": 0.9, "reason": "apologizes and names R-1001"}';
},
});Use it in code by passing it to trace():
async def main() -> None:
with trace(judge=strict, allow_empty=True) as t:
t.output = "Sorry about that! Refund R-1001 is on its way."
check = await t.ameets({"output": judge("Apologizes and gives a refund id", threshold=0.8)})
assert check, check
# A judge that awaits IO needs ameets; t.meets raises evals.judge_needs_async when a judge suspends.
asyncio.run(main())const t = await trace(async () => "Sorry about that! Refund R-1001 is on its way.", {
judge: strict,
allowEmpty: true,
});
const check = await t.meets({ output: judge("Apologizes and gives a refund id", { threshold: 0.8 }) });
assert.ok(check.passed, check.message);The matcher takes rubric, an optional threshold (0 to 1; when both a threshold and a score exist, the score
decides), an optional judge name (default default) and free-form options passed to the judge. Register named
judges with judges in config. A judge that does not answer with the expected JSON fails with
evals.judge_invalid.
Cached verdicts
For YAML cases the runner caches every verdict in the fixture's judgments, keyed by judge, rubric, threshold and
value. A cache hit is used in every mode. A miss calls the judge in auto, record and live, and is
evals.judgment_missing in replay and rescore. CI runs replay by default, so judging costs money once,
locally, and a CI gate pays only when it opts into --mode live:
# In YAML: `output: { judge: { rubric: ..., threshold: 0.8 } }`. A fake judge stands in for the model here.
grader = fake_judge([{"passed": True, "score": 0.9, "reason": "polite, has the refund id"}])
cases = parse_case_file(
"""
id: polite-refund
input: "My order A-1001 arrived damaged."
expect:
output: { judge: { rubric: "Apologizes and gives a refund id", threshold: 0.8 } }
""",
"evals/polite-refund.yaml",
)
def support_agent(prompt: str) -> str:
"""One model call that answers the customer. The model is a script, so this runs with no keys."""
client = script(reply("Sorry about that! Refund R-1001 is on its way.")).anthropic()
msg = client.messages.create(
model="claude-sonnet-4-6", max_tokens=256, messages=[{"role": "user", "content": prompt}]
)
return msg.content[0].text
config = resolve_config(agent=support_agent, judges={"default": grader})
store = MemoryFixtureStore()
first = run_cases(cases, config=config, store=store, mode="auto", ci=False) # a local run
assert first["verdicts"][0]["status"] == "pass"
assert len(grader.requests) == 1 # judged once, verdict written to the fixture's `judgments`
ci = run_cases(cases, config=config, store=store, mode="replay", ci=True)
assert ci["verdicts"][0]["status"] == "pass"
assert len(grader.requests) == 1 # replay used the cached verdict: no judge call// In YAML: `output: { judge: { rubric: ..., threshold: 0.8 } }`. A fake judge stands in for the model here.
const grader = fakeJudge([{ passed: true, score: 0.9, reason: "polite, has the refund id" }]);
const cases = parseCaseFile(
`
id: polite-refund
input: "My order A-1001 arrived damaged."
expect:
output: { judge: { rubric: "Apologizes and gives a refund id", threshold: 0.8 } }
`,
"evals/polite-refund.yaml",
);
/** One model call that answers the customer. The model is a script, so this runs with no keys. */
async function supportAgent(prompt: string): Promise<string> {
const client = script(reply("Sorry about that! Refund R-1001 is on its way.")).anthropic();
const msg = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 256,
messages: [{ role: "user", content: prompt }],
});
return msg.content[0]?.type === "text" ? msg.content[0].text : "";
}
const config = resolveConfig({ agent: (input) => supportAgent(input.prompt), judges: { default: grader } });
const store = memoryFixtureStore();
const first = await runCases(cases, { config, store, mode: "auto", ci: false }); // a local run
assert.equal(first.verdicts[0]?.status, "pass");
assert.equal(grader.requests.length, 1); // judged once, verdict written to the fixture's `judgments`
const ci = await runCases(cases, { config, store, mode: "replay", ci: true });
assert.equal(ci.verdicts[0]?.status, "pass");
assert.equal(grader.requests.length, 1); // replay used the cached verdict: no judge callfake_judge / fakeJudge from the testing helpers returns scripted verdicts and records every request, for tests
of your own judge wiring.
Assertion plugins
A plugin is a named check over the whole trajectory, used from YAML under use:, by name or with options. Options
are validated when the case runs: a pydantic model in Python, any Standard Schema (zod, valibot, arktype) in
TypeScript. A plugin returns a boolean or an outcome with a message, sync or async.
# A pydantic model on the second parameter validates the options. Return a bool or an Outcome.
class MaxWords(BaseModel):
max: PositiveInt
@assertion("max-words")
def max_words(t: Trajectory, options: MaxWords) -> Outcome:
n = len(str(t.output or "").split())
return Outcome(n <= options.max, f"{n} words (max {options.max})")
@assertion("no-phone-numbers")
def no_phone_numbers(t: Trajectory, _options: None) -> bool:
return not re.search(r"\b\d{3}[-. ]\d{3}[-. ]\d{4}\b", str(t.output or ""))
// Options are validated with any Standard Schema (zod, valibot, arktype). Return a boolean or { passed, message }.
const maxWords = defineAssertion({
options: z.object({ max: z.number().int().positive() }),
check: ({ trajectory, options }) => {
const n = String(trajectory.output ?? "")
.split(/\s+/)
.filter(Boolean).length;
return { passed: n <= options.max, message: `${n} words (max ${options.max})` };
},
});
const noPhoneNumbers = defineAssertion({
check: ({ trajectory }) => !/\b\d{3}[-. ]\d{3}[-. ]\d{4}\b/.test(String(trajectory.output ?? "")),
});Register them: in Python the decorator registers on import, so put plugins in conftest.py or a module your agent
imports; in TypeScript list them under assertions in viewport.config.ts.
cases = parse_case_file(
"""
id: short-reply
input: "My order A-1001 arrived damaged."
expect:
use:
- max-words: { max: 20 }
- no-phone-numbers
""",
"evals/short-reply.yaml",
)
report = run_cases(cases, config=config, store=MemoryFixtureStore(), mode="auto")
for a in report["verdicts"][0]["runs"][0]["assertions"]:
print(f"{'pass' if a['passed'] else 'FAIL'} {a['name']}: {a['message']}")
# pass use:max-words: 12 words (max 20)
# FAIL use:no-phone-numbers: failed
assert report["verdicts"][0]["status"] == "fail"const cases = parseCaseFile(
`
id: short-reply
input: "My order A-1001 arrived damaged."
expect:
use:
- max-words: { max: 20 }
- no-phone-numbers
`,
"evals/short-reply.yaml",
);
const report = await runCases(cases, { config, store: memoryFixtureStore(), mode: "auto" });
const lines = report.verdicts[0]?.runs[0]?.assertions.map(
(a) => `${a.passed ? "pass" : "FAIL"} ${a.name}: ${a.message}`,
);
console.log(lines?.join("\n"));
// pass use:max-words: 12 words (max 20)
// FAIL use:no-phone-numbers: failed
assert.equal(report.verdicts[0]?.status, "fail");Each plugin produces an assertion named use:<name>. A plugin that throws is a failed assertion with the exception
message, never a crashed run. Invalid options fail with evals.plugin_options_invalid. A name that is not
registered in the running language raises evals.plugin_not_found, naming where to register it, so a case that uses
a plugin needs it registered in every language that runs the case.
Plugins run wherever expectations are evaluated: the CLI, the pytest plugin, describeCases, run_cases /
runCases, and t.meets in code, which sees the registered plugins (Python's decorator registry) or those passed
as trace(assertions=...) / trace(fn, { assertions }).
Next: conformance.