@crowandraven/evalkeeper 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/types.ts CHANGED
@@ -284,13 +284,15 @@ export type ActivityDraft<Input, Label> = {
284
284
  /**
285
285
  * One field of a suite's add/edit form. `name` is the form key (and the
286
286
  * input or answer property it fills). "lines": one item per line, read as
287
- * a list.
287
+ * a list. "json": a structured value (a list of objects, a nested shape)
288
+ * edited as JSON in a monospace box, checked against the suite's schema
289
+ * when saved.
288
290
  */
289
291
  export type FormField = {
290
292
  name: string;
291
293
  label: string;
292
294
  help: string;
293
- kind: "text" | "textarea" | "select" | "lines";
295
+ kind: "text" | "textarea" | "select" | "lines" | "json";
294
296
  /** For "select". */
295
297
  options?: readonly string[];
296
298
  required?: boolean;
@@ -316,6 +318,8 @@ export function fieldValue(field: FormField, value: unknown): string {
316
318
  value && typeof value === "object"
317
319
  ? (value as Record<string, unknown>)[field.name]
318
320
  : undefined;
321
+ if (field.kind === "json")
322
+ return v === undefined || v === null ? "" : JSON.stringify(v, null, 2);
319
323
  if (Array.isArray(v)) return v.map(asText).join("\n");
320
324
  return asText(v);
321
325
  }
@@ -348,6 +352,24 @@ export function isInjectionSuite(
348
352
  return "base" in suite && "attackCase" in suite;
349
353
  }
350
354
 
355
+ /**
356
+ * The injection suites that attack a suite: the ones whose base it is.
357
+ * Their results belong with the base suite's, since both test the same
358
+ * feature and one choice of model serves both.
359
+ *
360
+ * @param suites - Every registered suite.
361
+ * @param baseKey - The base suite's key.
362
+ */
363
+ export function injectionSuitesOf(
364
+ suites: readonly AnySuite[],
365
+ baseKey: string,
366
+ ): (AnySuite & { base: AnySuite })[] {
367
+ return suites.filter(
368
+ (s): s is AnySuite & { base: AnySuite } =>
369
+ isInjectionSuite(s) && s.base.key === baseKey,
370
+ );
371
+ }
372
+
351
373
  /** Where a zod issue sits, in plain words: "facts, item 2, name". */
352
374
  function issuePath(path: readonly (string | number)[]): string {
353
375
  return path
@@ -355,28 +377,20 @@ function issuePath(path: readonly (string | number)[]): string {
355
377
  .join(", ");
356
378
  }
357
379
 
358
- /**
359
- * Reads one form field as JSON and checks it with a schema; throws a
360
- * plain error when the field is empty, isn't JSON, or doesn't fit (naming
361
- * the first part that doesn't).
362
- */
363
- function readJson<T>(
364
- form: FormData,
365
- field: string,
366
- what: string,
367
- schema: z.ZodType<T>,
368
- ): T {
369
- const text = formText(form, field);
370
- if (!text) throw new Error(`${what} is empty: fill in the "${field}" field`);
371
- let value: unknown;
380
+ /** Text as JSON, with a plain error naming what it was. */
381
+ function parseJson(text: string, what: string): unknown {
372
382
  try {
373
- value = JSON.parse(text);
383
+ return JSON.parse(text) as unknown;
374
384
  } catch (e) {
375
385
  throw new Error(
376
386
  `${what} isn't valid JSON: ${e instanceof Error ? e.message : String(e)}`,
377
387
  { cause: e },
378
388
  );
379
389
  }
390
+ }
391
+
392
+ /** A value checked with a schema, with a plain error naming the first misfit. */
393
+ function fit<T>(value: unknown, schema: z.ZodType<T>, what: string): T {
380
394
  const parsed = schema.safeParse(value);
381
395
  if (parsed.success) return parsed.data;
382
396
  const issue = parsed.error.issues[0];
@@ -389,6 +403,22 @@ function readJson<T>(
389
403
  );
390
404
  }
391
405
 
406
+ /**
407
+ * Reads one form field as JSON and checks it with a schema; throws a
408
+ * plain error when the field is empty, isn't JSON, or doesn't fit (naming
409
+ * the first part that doesn't).
410
+ */
411
+ function readJson<T>(
412
+ form: FormData,
413
+ field: string,
414
+ what: string,
415
+ schema: z.ZodType<T>,
416
+ ): T {
417
+ const text = formText(form, field);
418
+ if (!text) throw new Error(`${what} is empty: fill in the "${field}" field`);
419
+ return fit(parseJson(text, what), schema, what);
420
+ }
421
+
392
422
  /**
393
423
  * A suite's `inputFromForm` for fixture suites (`caseKind: "fixture"`),
394
424
  * whose cases are edited as JSON in one textarea. Reads the field, parses
@@ -432,3 +462,101 @@ export function labelFromJson<T>(
432
462
  ): (form: FormData) => T {
433
463
  return (form) => readJson(form, field, "Answer", schema);
434
464
  }
465
+
466
+ /**
467
+ * A form's values for a suite's fields, each read by its kind: text as it
468
+ * is, "lines" as a list, "json" parsed (with a plain error naming the
469
+ * field when it isn't valid JSON; empty reads as null). Pure.
470
+ *
471
+ * @param fields - The suite's input or answer fields.
472
+ * @param form - The submitted form.
473
+ */
474
+ export function valuesFromFields(
475
+ fields: readonly FormField[],
476
+ form: FormData,
477
+ ): Record<string, unknown> {
478
+ const out: Record<string, unknown> = {};
479
+ for (const f of fields) {
480
+ if (f.kind === "lines") out[f.name] = linesOf(form, f.name);
481
+ else if (f.kind === "json") {
482
+ const text = formText(form, f.name);
483
+ out[f.name] = text ? parseJson(text, f.label) : null;
484
+ } else out[f.name] = formText(form, f.name);
485
+ }
486
+ return out;
487
+ }
488
+
489
+ /**
490
+ * A suite's `inputFromForm` from its fields, any kinds: reads each field
491
+ * by kind (`valuesFromFields`) and checks the whole with the schema,
492
+ * throwing a plain error that names the first part that doesn't fit.
493
+ *
494
+ * @param schema - The suite's input schema.
495
+ * @param fields - The suite's input fields (`fields.input`).
496
+ * @returns A form reader to use as the suite's `inputFromForm`.
497
+ */
498
+ export function inputFromFields<T>(
499
+ schema: z.ZodType<T>,
500
+ fields: readonly FormField[],
501
+ ): (form: FormData) => T {
502
+ return (form) => fit(valuesFromFields(fields, form), schema, "Input");
503
+ }
504
+
505
+ /**
506
+ * A suite's `labelFromForm` from its answer fields, like `inputFromFields`.
507
+ *
508
+ * @param schema - The suite's answer schema (`labelValue`).
509
+ * @param fields - The suite's answer fields (`fields.label`).
510
+ * @returns A form reader to use as the suite's `labelFromForm`.
511
+ */
512
+ export function labelFromFields<T>(
513
+ schema: z.ZodType<T>,
514
+ fields: readonly FormField[],
515
+ ): (form: FormData) => T {
516
+ return (form) => fit(valuesFromFields(fields, form), schema, "Answer");
517
+ }
518
+
519
+ /**
520
+ * The form field an answer editor submits its answer under, as JSON
521
+ * (see `AnswerEditorProps`).
522
+ */
523
+ export const ANSWER_JSON_FIELD = "answerJson";
524
+
525
+ /**
526
+ * What an app's own answer editor gets, for answers plain fields can't
527
+ * edit well (a list of facts with a category each, a verdict with
528
+ * reasons). The editor is a client component that renders its own
529
+ * controls and keeps the whole answer, as JSON, in a form field named
530
+ * `name` (a hidden input). Register it in your wiring module's
531
+ * `answerEditors`, keyed by suite; the copied answer key, "Add a case",
532
+ * and blind rating use it in place of the suite's answer fields, and the
533
+ * actions check what it submits against the suite's `labelValue`.
534
+ */
535
+ export type AnswerEditorProps = {
536
+ /** The form field to submit the answer under, as JSON. */
537
+ name: string;
538
+ /** Prefix for element ids, unique on the page. */
539
+ idPrefix: string;
540
+ /** The case's input, when there is one yet (null on "Add a case"). */
541
+ input: unknown;
542
+ /** The current answer, or null for a new one. */
543
+ value: unknown;
544
+ /** The suite's answer fields, for their labels and help. */
545
+ fields: readonly FormField[];
546
+ };
547
+
548
+ /**
549
+ * The answer a form submits for a suite: from an answer editor (JSON in
550
+ * `ANSWER_JSON_FIELD`, checked against the suite's `labelValue`) when the
551
+ * form has one, otherwise the suite's own `labelFromForm`. Throws a plain
552
+ * error when the suite has neither, or the answer doesn't fit.
553
+ *
554
+ * @param suite - The suite the answer is for.
555
+ * @param form - The submitted form.
556
+ */
557
+ export function answerFromForm(suite: AnySuite, form: FormData): unknown {
558
+ if (formText(form, ANSWER_JSON_FIELD))
559
+ return readJson(form, ANSWER_JSON_FIELD, "Answer", suite.labelValue);
560
+ if (suite.labelFromForm) return suite.labelFromForm(form);
561
+ throw new Error("This suite has no answer form");
562
+ }
package/starter/index.ts CHANGED
@@ -3,10 +3,12 @@
3
3
  import "server-only";
4
4
  import {
5
5
  createSettings,
6
+ type AnswerEditorProps,
6
7
  type AnySuite,
7
8
  type ModelCatalog,
8
9
  type Settings,
9
10
  } from "@crowandraven/evalkeeper";
11
+ import type { ComponentType } from "react";
10
12
  import { createRunner, type Route } from "@crowandraven/evalkeeper/runner";
11
13
  import {
12
14
  prismaFeedbackStore,
@@ -39,6 +41,15 @@ export const SUITE_BY_KEY: Record<string, AnySuite> = Object.fromEntries(
39
41
  SUITES.map((s) => [s.key, s]),
40
42
  );
41
43
 
44
+ /**
45
+ * Your own editors for answers plain fields can't edit well, keyed by
46
+ * suite (see `AnswerEditorProps`). The answer key, "Add a case", and blind
47
+ * rating use them in place of the suite's answer fields. Empty is fine.
48
+ */
49
+ export const answerEditors: Partial<
50
+ Record<string, ComponentType<AnswerEditorProps>>
51
+ > = {};
52
+
42
53
  /**
43
54
  * TODO: each feature's instructions hash (instructionsHash from
44
55
  * @crowandraven/evalkeeper-ai-sdk), so editing a prompt marks older tests out of date.
@@ -3,7 +3,10 @@ import Link from "next/link";
3
3
  import { notFound } from "next/navigation";
4
4
  import {
5
5
  FAVOR_TEXT,
6
+ attackMistakes,
7
+ attacksFrom,
6
8
  checkBar,
9
+ isInjectionSuite,
7
10
  meanCalibrationError,
8
11
  money,
9
12
  probabilityQuality,
@@ -19,6 +22,7 @@ import { IconSubmit, Spinner, Submit } from "@/components/evalkeeper/Submit";
19
22
  import { RotateCw } from "lucide-react";
20
23
  import { BackLink, Card, Chip, Score, pct } from "@/components/evalkeeper/ui";
21
24
  import {
25
+ answerEditors,
22
26
  MODELS,
23
27
  requireAdmin,
24
28
  runner,
@@ -69,20 +73,33 @@ export default async function SuitePage({
69
73
  if (!operation) notFound();
70
74
  // The board and the settings load together: on a remote database each
71
75
  // waits on round trips, so one after the other doubles the wait.
72
- const [b, [history, liveSettings], inInstructions] = await Promise.all([
73
- runner.board(key),
74
- // Records a deploy if the instructions changed under the live
75
- // settings, before reading them.
76
- settings
77
- .syncPrompt(operation)
78
- .then(() =>
79
- Promise.all([settings.history(operation), settings.current(operation)]),
80
- ),
81
- runner.casesInInstructions(key),
82
- ]);
76
+ const [b, attackBoards, [history, liveSettings], inInstructions] =
77
+ await Promise.all([
78
+ runner.board(key),
79
+ // Injection suites that attack this feature: their results count here.
80
+ runner.attackBoards(key),
81
+ // Records a deploy if the instructions changed under the live
82
+ // settings, before reading them.
83
+ settings
84
+ .syncPrompt(operation)
85
+ .then(() =>
86
+ Promise.all([
87
+ settings.history(operation),
88
+ settings.current(operation),
89
+ ]),
90
+ ),
91
+ runner.casesInInstructions(key),
92
+ ]);
83
93
  const { suite, rows } = b;
84
- const s = suggest(rows, suite.checks, suite.priority, MODELS);
85
- const testing = rows.some((r) => r.testing);
94
+ const attacks = attacksFrom(attackBoards);
95
+ // An injection suite's models are chosen on its base suite's page.
96
+ const choosesHere = !isInjectionSuite(suite);
97
+ const s = choosesHere
98
+ ? suggest(rows, suite.checks, suite.priority, MODELS, { attacks })
99
+ : null;
100
+ const testing =
101
+ rows.some((r) => r.testing) ||
102
+ attackBoards.some((a) => a.rows.some((r) => r.testing));
86
103
  // What testing each model would cost now, counting answers it would reuse.
87
104
  const estimates = new Map(
88
105
  await Promise.all(
@@ -97,6 +114,22 @@ export default async function SuitePage({
97
114
  ),
98
115
  ),
99
116
  );
117
+ // What testing each untested model against the attacks would cost.
118
+ const attackEstimates = new Map(
119
+ await Promise.all(
120
+ attackBoards.flatMap((a) =>
121
+ rows
122
+ .filter((r) => !r.variant)
123
+ .map(
124
+ async (r) =>
125
+ [
126
+ `${a.suite.key}|${r.key}`,
127
+ await runner.estimateRun(a.suite.key, r.model, "ALL", 1),
128
+ ] as const,
129
+ ),
130
+ ),
131
+ ),
132
+ );
100
133
  const live = rows.find((r) => r.live);
101
134
 
102
135
  return (
@@ -112,6 +145,27 @@ export default async function SuitePage({
112
145
  </p>
113
146
  </div>
114
147
 
148
+ {isInjectionSuite(suite) && (
149
+ <Card className="space-y-2">
150
+ <h2 className="font-semibold">
151
+ Models are chosen on {suite.base.label}
152
+ <InfoTip term="attackResults" />
153
+ </h2>
154
+ <p className="readable text-sm text-muted">
155
+ This suite tests the same feature as {suite.base.label}, so one
156
+ choice of model serves both. Its results show there as Under attack,
157
+ and the suggestion there never picks a model with more serious
158
+ mistakes under attack than live.
159
+ </p>
160
+ <Link
161
+ href={evalsPath(suite.base.key)}
162
+ className="inline-block text-sm text-accent hover:underline"
163
+ >
164
+ Choose models on {suite.base.label}
165
+ </Link>
166
+ </Card>
167
+ )}
168
+
115
169
  {/* Shown when nothing would change too, so a higher score that
116
170
  isn't enough to switch for comes with its reason. */}
117
171
  {s && (
@@ -201,6 +255,13 @@ export default async function SuitePage({
201
255
  Serious mistakes
202
256
  </Tip>
203
257
  </th>
258
+ {attackBoards.length > 0 && (
259
+ <th className="p-3 font-normal">
260
+ <Tip term="underAttack" side="bottom">
261
+ Under attack
262
+ </Tip>
263
+ </th>
264
+ )}
204
265
  <th className="p-3 font-normal">
205
266
  <Tip term="time" side="bottom" align="end">
206
267
  Time
@@ -318,6 +379,26 @@ export default async function SuitePage({
318
379
  <td className="p-3 tabular-nums">
319
380
  {r.test ? seriousMistakes(r, suite.checks) : "—"}
320
381
  </td>
382
+ {attackBoards.length > 0 && (
383
+ <td className="p-3">
384
+ <div className="flex flex-col gap-1">
385
+ {attackBoards.map((a) => (
386
+ <UnderAttack
387
+ key={a.suite.key}
388
+ attackSuite={a.suite.key}
389
+ attackLabel={a.suite.label}
390
+ row={a.rows.find((x) => x.key === r.key)}
391
+ mistakes={attackMistakes(r.key, attacksFrom([a]))}
392
+ model={r.model}
393
+ variant={r.variant}
394
+ estimate={attackEstimates.get(
395
+ `${a.suite.key}|${r.key}`,
396
+ )}
397
+ />
398
+ ))}
399
+ </div>
400
+ </td>
401
+ )}
321
402
  <td className="p-3 tabular-nums">
322
403
  {r.test ? seconds(r.test.avgMs) : "—"}
323
404
  </td>
@@ -354,14 +435,14 @@ export default async function SuitePage({
354
435
  <td className="p-3">
355
436
  <div className="flex flex-col items-end gap-0.5">
356
437
  <div className="flex justify-end gap-2">
357
- {r.canMakeFallback && (
438
+ {choosesHere && r.canMakeFallback && (
358
439
  <form action={makeFallback}>
359
440
  <input type="hidden" name="suite" value={key} />
360
441
  <input type="hidden" name="model" value={r.model} />
361
442
  <Submit variant="quiet">Make fallback</Submit>
362
443
  </form>
363
444
  )}
364
- {!r.live && r.canMakeLive && (
445
+ {choosesHere && !r.live && r.canMakeLive && (
365
446
  <form action={makeLive}>
366
447
  <input type="hidden" name="suite" value={key} />
367
448
  <input type="hidden" name="model" value={r.model} />
@@ -411,13 +492,15 @@ export default async function SuitePage({
411
492
  </Card>
412
493
  </section>
413
494
 
414
- <SettingsHistory
415
- suite={key}
416
- entries={history}
417
- liveId={liveSettings.version?.id ?? null}
418
- label={(m) => MODELS[m]?.label ?? m}
419
- defaults={liveSettings.settings}
420
- />
495
+ {choosesHere && (
496
+ <SettingsHistory
497
+ suite={key}
498
+ entries={history}
499
+ liveId={liveSettings.version?.id ?? null}
500
+ label={(m) => MODELS[m]?.label ?? m}
501
+ defaults={liveSettings.settings}
502
+ />
503
+ )}
421
504
 
422
505
  <section className="space-y-3">
423
506
  <h2 className="text-lg font-semibold">
@@ -479,16 +562,17 @@ export default async function SuitePage({
479
562
  }
480
563
  tools={
481
564
  <>
482
- {suite.caseKind === "imported" && suite.labelFromForm && (
483
- <Tip control term="rateBlind" side="bottom" align="end">
484
- <Link
485
- href={evalsPath(key, "rate")}
486
- className="inline-flex items-center rounded-md border border-accent/40 bg-card px-3 py-1.5 text-sm text-accent hover:bg-accent/10"
487
- >
488
- Rate blind
489
- </Link>
490
- </Tip>
491
- )}
565
+ {suite.caseKind === "imported" &&
566
+ (suite.labelFromForm || answerEditors[key]) && (
567
+ <Tip control term="rateBlind" side="bottom" align="end">
568
+ <Link
569
+ href={evalsPath(key, "rate")}
570
+ className="inline-flex items-center rounded-md border border-accent/40 bg-card px-3 py-1.5 text-sm text-accent hover:bg-accent/10"
571
+ >
572
+ Rate blind
573
+ </Link>
574
+ </Tip>
575
+ )}
492
576
  <form action={rescore}>
493
577
  <input type="hidden" name="suite" value={key} />
494
578
  <Tip control term="rescore" side="bottom" align="end">
@@ -532,3 +616,72 @@ function EstimateNote({
532
616
  </Tip>
533
617
  );
534
618
  }
619
+
620
+ /**
621
+ * A model's serious mistakes on one injection suite, linked to that test,
622
+ * or a button to test it there. Out of date and failed tests say so: the
623
+ * suggestion counts only current, complete ones.
624
+ */
625
+ function UnderAttack({
626
+ attackSuite,
627
+ attackLabel,
628
+ row,
629
+ mistakes,
630
+ model,
631
+ variant,
632
+ estimate,
633
+ }: {
634
+ attackSuite: string;
635
+ attackLabel: string;
636
+ row:
637
+ | {
638
+ key: string;
639
+ testing: boolean;
640
+ test: { runId: string; stale: boolean; failedAnswers: number } | null;
641
+ }
642
+ | undefined;
643
+ mistakes: number | null;
644
+ model: string;
645
+ variant: boolean;
646
+ estimate:
647
+ { answers: number; reused: number; costUsd: number | null } | undefined;
648
+ }) {
649
+ if (row?.testing)
650
+ return (
651
+ <span role="status" title="Testing" className="inline-flex text-accent">
652
+ <Spinner />
653
+ </span>
654
+ );
655
+ if (row?.test)
656
+ return (
657
+ <Link
658
+ href={evalsPath(attackSuite, "runs", row.test.runId)}
659
+ title={attackLabel}
660
+ className="tabular-nums"
661
+ >
662
+ {mistakes ?? "—"}
663
+ {row.test.stale
664
+ ? " · out of date"
665
+ : row.test.failedAnswers
666
+ ? " · answers failed"
667
+ : ""}
668
+ </Link>
669
+ );
670
+ // Settings rows are tested on the base suite only.
671
+ if (variant) return <span className="text-muted">—</span>;
672
+ return (
673
+ <form action={testModel} className="flex flex-col items-start gap-0.5">
674
+ <input type="hidden" name="suite" value={attackSuite} />
675
+ <input type="hidden" name="model" value={model} />
676
+ <Tip
677
+ control
678
+ id={`attack-${attackSuite}-${row?.key ?? model}`}
679
+ text={`Test this model on ${attackLabel}, every attack case in use.`}
680
+ side="bottom"
681
+ >
682
+ <Submit variant="quiet">Test attacks</Submit>
683
+ </Tip>
684
+ <EstimateNote id={`attack-${attackSuite}-${model}`} estimate={estimate} />
685
+ </form>
686
+ );
687
+ }
@@ -2,11 +2,16 @@ import type { Metadata } from "next";
2
2
  import Link from "next/link";
3
3
  import { notFound } from "next/navigation";
4
4
  import { rateQueue } from "@crowandraven/evalkeeper";
5
- import { FieldValues, Fields } from "@/components/evalkeeper/Fields";
5
+ import { AnswerInput, FieldValues } from "@/components/evalkeeper/Fields";
6
6
  import { Submit } from "@/components/evalkeeper/Submit";
7
7
  import { InfoTip, Tip } from "@/components/evalkeeper/Tip";
8
8
  import { BackLink, Card } from "@/components/evalkeeper/ui";
9
- import { requireAdmin, SUITE_BY_KEY, store } from "@/lib/evalkeeper";
9
+ import {
10
+ answerEditors,
11
+ requireAdmin,
12
+ SUITE_BY_KEY,
13
+ store,
14
+ } from "@/lib/evalkeeper";
10
15
  import { rateBlind, skipCase } from "@/lib/evalkeeper/actions";
11
16
  import { evalsPath } from "@/lib/evalkeeper/paths";
12
17
 
@@ -40,7 +45,7 @@ export default async function RateBlindPage({
40
45
  !suite ||
41
46
  suite.caseKind !== "imported" ||
42
47
  !fields ||
43
- !suite.labelFromForm
48
+ !(suite.labelFromForm || answerEditors[key])
44
49
  )
45
50
  notFound();
46
51
  const queue = rateQueue(await store.listCases(key), admin.id);
@@ -90,7 +95,12 @@ export default async function RateBlindPage({
90
95
  <form key={next.id} action={rateBlind} className="space-y-4">
91
96
  <input type="hidden" name="suite" value={key} />
92
97
  <input type="hidden" name="case" value={next.id} />
93
- <Fields fields={fields.label} prefix="rate-" />
98
+ <AnswerInput
99
+ fields={fields.label}
100
+ editor={answerEditors[key]}
101
+ input={next.input}
102
+ prefix="rate-"
103
+ />
94
104
  <div className="space-y-1">
95
105
  <label
96
106
  htmlFor="rate-reason"