Files
Kaname/src/lib/quality.ts
T
Pascal LinxweilerandClaude Opus 5.5 6b67c653b5
Release / release (push) Successful in 3m17s
Release 0.14.0: quality eval
A deterministic quality eval as a run type next to BetterBench: tool
calling (12 requests), coding (8 Python functions checked by unit tests
in a locked-down sandbox container) and long-context retrieval (needle at
3 depths in 3 lengths up to the context). Versioned eval set in
src/evals/v1, score stored per run, shown on the run page, in compare
views, the benchmark list and sweep tables (optional eval per variant);
API kind "eval", quality in run/sweep/compare answers; skill updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:24:36 +02:00

176 lines
8.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// The quality eval: a small, deterministic check of what a deployment produces (not how fast), so
// launch options that change the output (quant, KV cache type, context, sampling bugs in a build)
// show up next to the speed numbers. Pure: the eval set, prompt building and scoring; the worker
// (src/worker/quality.ts) talks to the server and the code sandbox.
import type { QualityResult } from "@/lib/db/schema";
import coding from "@/evals/v1/coding.json";
import retrieval from "@/evals/v1/retrieval.json";
import tools from "@/evals/v1/tools.json";
/** Bump with any change to the eval set or the scoring: results are only comparable within a version. */
export const EVAL_SET_VERSION = "kaname-eval-1";
export const EVAL_SEED = 1;
export type ArgRule = string | number | boolean | { contains: string } | { oneOf: (string | number)[] } | { matches: string };
export type ToolItem = { id: string; tools: string[]; prompt: string; expect: { name: string; args: Record<string, ArgRule> } };
export type CodingItem = { id: string; prompt: string; tests: string[] };
export const EVAL_SET = {
version: EVAL_SET_VERSION,
tools: tools as unknown as { tools: Record<string, { description: string; parameters: Record<string, unknown> }>; items: ToolItem[] },
coding: coding as { instructions: string; items: CodingItem[] },
retrieval: retrieval as {
lengths: number[];
positions: number[];
reserveTokens: number;
seed: number;
needle: string;
question: string;
colors: string[];
filler: string[];
},
};
// --- tool calling ---------------------------------------------------------------------------
/** The OpenAI `tools` array for an item. */
export function toolDefs(item: ToolItem) {
return item.tools.map((name) => ({ type: "function" as const, function: { name, ...EVAL_SET.tools.tools[name] } }));
}
const norm = (v: unknown) => (typeof v === "string" ? v.trim().toLowerCase() : v);
/** One argument against its rule: strings case-insensitively, numbers by value. */
export function argMatches(value: unknown, rule: ArgRule): boolean {
if (value === undefined || value === null) return false;
if (typeof rule === "object") {
if ("contains" in rule) return typeof value === "string" && value.toLowerCase().includes(rule.contains.toLowerCase());
if ("oneOf" in rule) return rule.oneOf.some((r) => argMatches(value, r));
if ("matches" in rule) return typeof value === "string" && new RegExp(rule.matches, "i").test(value);
}
if (typeof rule === "number") return Number(value) === rule;
return norm(value) === norm(rule);
}
export type ToolCall = { name: string; arguments: string };
/**
* A tool call is right when there is exactly one, its arguments are valid JSON, the function is the
* expected one and every expected argument matches (extra arguments are fine).
*/
export function scoreToolCall(calls: ToolCall[] | null | undefined, expect: ToolItem["expect"]): { pass: boolean; detail: string } {
if (!calls || calls.length === 0) return { pass: false, detail: "no tool call" };
if (calls.length > 1) return { pass: false, detail: `${calls.length} tool calls, expected one` };
const [c] = calls;
let args: Record<string, unknown>;
try {
const parsed = JSON.parse(c.arguments || "{}");
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { pass: false, detail: "arguments aren't a JSON object" };
args = parsed as Record<string, unknown>;
} catch {
return { pass: false, detail: `invalid JSON arguments: ${c.arguments.slice(0, 120)}` };
}
if (c.name !== expect.name) return { pass: false, detail: `called ${c.name}, expected ${expect.name}` };
const wrong = Object.entries(expect.args).filter(([k, rule]) => !argMatches(args[k], rule));
if (wrong.length) return { pass: false, detail: `wrong ${wrong.map(([k]) => `${k}=${JSON.stringify(args[k])}`).join(", ")}` };
return { pass: true, detail: `${c.name}(${JSON.stringify(args)})` };
}
// --- coding -------------------------------------------------------------------------------
/** The last ```python block of a reply (or the only fenced block); null without one. */
export function extractCode(reply: string): string | null {
const blocks = [...reply.matchAll(/```(?:python|py)?[ \t]*\r?\n([\s\S]*?)```/gi)].map((m) => m[1]);
if (blocks.length) return blocks[blocks.length - 1].trim() || null;
// Some models answer with bare code.
return /^\s*(def|import|from)\s/m.test(reply) ? reply.trim() : null;
}
/** The program the sandbox runs: the model's code, then the tests; prints OK when all pass. */
export function testProgram(code: string, tests: string[]): string {
return `${code}\n\n# --- tests ---\n${tests.join("\n")}\nprint("KANAME-OK")\n`;
}
// --- long-context retrieval ---------------------------------------------------------------
/** A small, seeded PRNG (mulberry32): the haystacks are the same every run. */
export function prng(seed: number) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export type NeedleCase = { id: string; targetTokens: number; position: number; color: string; code: string };
/** The cases for a context of `contextTokens`: each length × each needle position, deduplicated. */
export function retrievalCases(contextTokens: number): NeedleCase[] {
const r = EVAL_SET.retrieval;
const usable = Math.max(0, contextTokens - r.reserveTokens);
const rand = prng(r.seed);
const out: NeedleCase[] = [];
const seen = new Set<number>();
let i = 0;
for (const len of r.lengths) {
const target = Math.floor(usable * len);
if (target < 256 || seen.has(target)) continue;
seen.add(target);
for (const position of r.positions) {
out.push({
id: `${Math.round(target / 100) / 10}k@${Math.round(position * 100)}%`,
targetTokens: target,
position,
color: r.colors[i++ % r.colors.length],
code: String(100000 + Math.floor(rand() * 900000)),
});
}
}
return out;
}
/**
* The haystack for a case: filler sentences in a seeded order up to about `targetTokens` (measured
* with the server's own tokenizer as characters per token), the needle at `position`, then the
* question.
*/
export function buildHaystack(c: NeedleCase, charsPerToken: number): string {
const r = EVAL_SET.retrieval;
const rand = prng(r.seed + c.targetTokens);
const targetChars = Math.floor(c.targetTokens * charsPerToken * 0.97);
const parts: string[] = [];
let len = 0;
while (len < targetChars) {
const s = r.filler[Math.floor(rand() * r.filler.length)];
parts.push(s);
len += s.length + 1;
}
const needle = r.needle.replace("{color}", c.color).replace("{code}", c.code);
parts.splice(Math.round(parts.length * c.position), 0, needle);
return `${parts.join(" ")}\n\n${r.question.replace("{color}", c.color)}`;
}
/** Did the answer give the code (the six digits, anywhere)? */
export function scoreNeedle(answer: string, c: NeedleCase): { pass: boolean; detail: string } {
const found: string[] = answer.match(/\d{6}/g) ?? [];
return found.includes(c.code) ? { pass: true, detail: c.code } : { pass: false, detail: `expected ${c.code}, got ${JSON.stringify(answer.trim().slice(0, 80))}` };
}
// --- score --------------------------------------------------------------------------------
/** Section pass rates and the overall score (mean of the sections that could run), 0–100. */
export function summarize(
sections: QualityResult["sections"],
): Pick<QualityResult, "score" | "sections"> {
const counted = sections.filter((s) => !s.unsupported && s.total > 0);
const withScore = sections.map((s) => ({ ...s, score: !s.unsupported && s.total > 0 ? Math.round((s.passed / s.total) * 1000) / 10 : null }));
const score = counted.length ? Math.round((counted.reduce((n, s) => n + s.passed / s.total, 0) / counted.length) * 1000) / 10 : null;
return { score, sections: withScore };
}
export { SECTION_LABEL } from "@/lib/quality-view";