Stop Judging Every AI Assertion With Another LLM

Table of Contents
Your AI feature emits free text, so toContainText is useless and you reached for the obvious fix: call a big model to grade the output. It works in the demo. Then the suite grows to 200 AI assertions, each one is a paid API round-trip that takes two seconds and returns a slightly different verdict every run — and you’ve built a non-deterministic oracle to test a non-deterministic system. That’s two dice, not one.
For roughly 80% of the assertions a Sr SDET actually writes against AI output — “did the summary mention the refund,” “is this answer semantically the golden answer,” “did the reply stay on topic” — you don’t need a reasoning model. You need a distance function. A precomputed golden embedding plus cosine similarity, wrapped in a Playwright custom matcher, is faster, ~125x cheaper per assertion, and deterministic given a pinned embedding model. Reserve the judge model for the genuinely subjective 20%. Here’s how to build the matcher, how to calibrate its threshold without guessing, and the one failure mode that will silently pass a wrong answer if you don’t guard for it.
Why is LLM-as-judge the wrong default?
Because you’re grading a probabilistic system with a probabilistic grader, and the errors compound. An empirical study of LLM-as-a-judge across 21 models and 541,000 judgments found four independent layers of uncertainty: stochastic instability (the same judge flips its verdict across identical runs), systematic position and verbosity bias, protocol dependence on the prompt template, and judge-identity dependence where two judge models simply disagree. Braintrust’s own guidance is blunt about the tradeoff — use deterministic evals wherever the check can be deterministic, and save the judge for what genuinely needs judgment.
Now stack the operational cost on top. Every judge assertion is a chat completion, and chat completions are expensive and slow relative to an embedding lookup.
~125x
Cheaper
text-embedding-3-small at $0.02/1M vs GPT-4o input at $2.50/1M
0
Extra flake
Cosine similarity is deterministic for a pinned model
4
Judge uncertainty layers
Stochastic, bias, protocol, judge-identity
At $0.02 per million tokens for text-embedding-3-small against $2.50 per million input tokens for GPT-4o, the embedding call is roughly two orders of magnitude cheaper before you even count the judge’s output tokens. I’ve watched an AI eval suite quietly become the most expensive job in the pipeline — not the model under test, the grader. That’s the tell that you’ve over-reached for the judge.
What does the embedding matcher actually assert?
That the response lands within a calibrated distance of a known-good answer, in meaning rather than in characters. You embed a reference answer once, store the vector, and at assert time you embed the actual output and take the cosine similarity. If it clears your threshold, the meanings match closely enough; if it doesn’t, they’ve drifted. This is the same instinct behind answer grounding checks for RAG, pushed down into a reusable expect matcher so every test can use it in one line.
Build the matcher with expect.extend
The whole thing is a pure function plus one API (or local model) call. Playwright’s expect.extend gives you the matcher shell:
import { expect as baseExpect } from '@playwright/test';import { embed, cosineSim } from '../helpers/embeddings';
export const expect = baseExpect.extend({ async toBeSemanticallyClose(received: string, golden: number[], threshold: number) { const actual = await embed(received); // pinned embedding model const score = cosineSim(actual, golden); // pure, deterministic const pass = score >= threshold; return { pass, message: () => `semantic similarity ${score.toFixed(3)} ${pass ? '≥' : '<'} threshold ${threshold}`, }; },});Use it against a stored golden vector
Note the golden is a number[] — a stored vector, not a string you re-embed on every run. Re-embedding the reference at assert time doubles your API calls and re-introduces the provider dependency you’re trying to shrink. Compute it once, check it in, load it.
import { expect } from '../matchers/semantic';import goldens from './goldens/summary.json'; // { refund: number[] }
test('refund summary is semantically the golden answer', async ({ page }) => { await page.goto('/tickets/8842'); const text = await page.getByTestId('summary').innerText();
// One line. No judge call. Deterministic given a pinned model. await expect(text).toBeSemanticallyClose(goldens.refund, 0.82);});How do you pick the threshold without guessing?
Not by typing 0.8 because it feels round — calibrate it against a small labeled set and let the numbers choose. Collect maybe 15–20 known-good outputs and 15–20 known-bad ones for the assertion, score them all against the golden, and pick the threshold that best separates the two clouds. A quick way is the midpoint between the lowest good score and the highest bad score; a better way is whatever maximizes F1 on that set.
Gather a labeled mini-set
Pull 15–20 real good outputs (accepted answers, prod logs) and 15–20 bad ones (topic drift, wrong entity, refusals). You need both clouds — a threshold picked from good examples alone has no idea where wrong lives.
Score every example against the golden vector
Run the same cosineSim your matcher uses. Print the two score distributions. If they overlap heavily, cosine alone can’t separate this assertion — that’s a signal to escalate it to the judge, not to fudge the threshold.
Choose the threshold that maximizes separation
Midpoint of (min good, max bad) as a floor; F1-optimal if you want to be principled. Write the number and the date into the golden file so the next engineer knows it was measured, not invented.
Re-run calibration on any embedding model change
Pin the embedding model. The moment you upgrade it, the whole similarity distribution shifts and last quarter’s 0.82 is now meaningless.
What’s the failure mode that passes a wrong answer?
Negation. This is the one that bites, and it’s structural: cosine similarity treats “the refund was approved” and “the refund was denied” as nearly identical because they share almost every token and live in the same semantic neighborhood. Research on sentence similarity has measured this directly — average cosine similarities for negation and antonym pairs came out higher than for genuinely similar sentence pairs, because antonyms are dissimilar and similar at once (love and hate are opposites, but both are emotions in the same context). Your matcher will happily pass “denied” against a golden that says “approved.”
Add a keyword guard for inverted outcomes
So the embedding matcher catches topic drift — it does not catch factual inversion. You pair it with a cheap keyword guard for the assertions where a flipped outcome is the whole risk:
const INVERSION_TRAPS = [/\bnot\b/i, /\bdenied\b/i, /\bunable\b/i, /\bcannot\b/i, /\bfailed\b/i];
async toBeSemanticallyClose(received, golden, threshold, opts?: { forbid?: RegExp[] }) { // Fail fast on an inverted outcome the cosine score would sail right past. for (const trap of opts?.forbid ?? []) { if (trap.test(received)) return { pass: false, message: () => `inversion token matched: ${trap}` }; } const score = cosineSim(await embed(received), golden); return { pass: score >= threshold, message: () => `similarity ${score.toFixed(3)} vs ${threshold}` };}The guard is deliberately dumb — a regex, not a model. When the only thing that separates pass from fail is a logical flip that embeddings can’t see, that’s exactly the assertion you promote to an LLM-as-judge, which I wrote about as a flaky-test tool in its own right. The decision rule I use: cosine for “is this on topic and close in meaning,” keyword guard for “did the outcome invert,” judge for “is this subtly, arguably wrong in a way only reasoning catches.”
Doesn’t the embedding call re-introduce non-determinism?
No — and this is the property that makes the whole approach worth it. An embedding model at a fixed version is a deterministic function: the same string maps to the same vector, so cosineSim returns the same score every run, and your gate can block a merge without flaking. That’s categorically different from a judge, whose stochastic instability means the same input earns different verdicts across trials. If you want the assertion fully offline and free per-call, run a small local embedding model instead of an API — then there’s no network, no rate limit, and no per-assertion bill at all, which composes nicely with a two-lane mock-in-CI, evals-nightly setup.
This is a different guarantee than pinning temperature: 0 on the feature, which — as I’ve argued — still doesn’t buy you determinism because sampling isn’t the only source of variance. The matcher sidesteps that entirely: the feature can be as non-deterministic as it likes, and your oracle stays fixed.
When should you still reach for the judge?
When the thing you’re asserting is genuinely a matter of judgment — tone, helpfulness, whether a multi-paragraph explanation is pedagogically sound, whether a rewrite preserved nuance. Cosine can’t rank those and a regex certainly can’t. The point of this post isn’t “never use a judge”; it’s “stop using the most expensive, least deterministic oracle you own as the default for checks a distance function handles.” Steel-manning the other side: a judge model needs no golden dataset and no calibration, so for a brand-new feature with no labeled examples yet, an LLM-judge is a faster way to get some signal on day one. Just don’t let the day-one crutch become the permanent architecture.
What I’d do differently
I’d have built the calibration harness before the matcher, not after. We shipped toBeSemanticallyClose with a hand-picked 0.85, watched it flake on legitimate paraphrases, dropped it to 0.75, and then watched it pass a wrong-entity answer — because we were tuning a number against vibes instead of a labeled set. Twenty labeled examples per assertion would have handed us the threshold in an afternoon and told us, for two of the assertions, that cosine couldn’t separate the classes and those belonged with the judge from the start.
I’d also have versioned the golden vectors from commit one. We stored golden strings and re-embedded them at runtime “for now,” which quietly meant every assertion made two embedding calls and every embedding-model bump silently re-baselined our own reference. Store the vector, pin the model beside it, review it like code.
Your one concrete next step: take your single most expensive AI assertion — the judge call you run most often — embed its reference answer once, and replace the judge with toBeSemanticallyClose behind a calibrated threshold. Measure the pipeline minutes and the API bill before and after. If it’s an assertion where a flipped outcome is the real risk, add the five-line inversion guard and keep the judge only for the cases that overlap. For the deeper question of how many samples you need before a threshold is trustworthy, see choosing eval sample size for AI test gates.
Is cosine similarity deterministic?
Yes — given a pinned embedding model. The same string produces the same vector at a fixed model version, so cosineSim returns the same score every run and the assertion can block a merge without flaking. That guarantee vanishes the instant you upgrade the embedding model, which relocates the whole score distribution. Pin the version and store it next to your golden vectors.
When should I use an LLM-as-judge instead of an embedding matcher?
Use a judge for genuinely subjective checks — tone, helpfulness, whether nuance survived a rewrite. Use the embedding matcher for “on topic and close in meaning.” Use a cheap keyword guard when a flipped outcome (approved vs denied) is the whole risk, because embeddings rate negations and antonyms as highly similar.
Why do embeddings fail on negation?
Antonyms and negated phrases share most of their tokens and occur in similar contexts, so their vectors land close together. Research has measured average cosine similarity for negation and antonym pairs coming out higher than for genuinely similar sentences. The matcher catches topic drift, not factual inversion — guard outcome-sensitive assertions with a regex.
How do I choose the similarity threshold?
Calibrate against a labeled set of ~15–20 good and ~15–20 bad outputs instead of guessing. Score them against the golden, then pick the threshold that best separates the clouds — midpoint of (min good, max bad) as a floor, F1-optimal if you want to be principled. Re-run calibration on every embedding-model change.
Should I store golden answers as text or as vectors?
As vectors. Re-embedding a golden string at assert time doubles your embedding calls and re-introduces the provider dependency you’re shrinking. Compute the golden vector once, check the JSON into the repo, pin the embedding model version beside it, and load the vector directly.
