@fabricorg/experiments-evals 1.0.0 → 1.1.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/dist/index.d.ts CHANGED
@@ -1,64 +1,7 @@
1
- import { E as EvaluatorKind, M as ModelClient, a as EvalScore, C as ChatMessage } from './model-client-_mOEKGN7.js';
2
- export { b as EvalRun, c as EvalRunSpec, d as EvalRunStatus, e as EvalRunTarget, G as GenerationSignal, f as GenerationSignalItem, g as ModelCompletionOptions, h as ModelResponse, S as StaticModelClient, T as TokenUsage, m as maxCompletionTokenUsage } from './model-client-_mOEKGN7.js';
1
+ import { E as Evaluator, a as EvalScore, C as ChatMessage, b as EvalInput, M as ModelClient, R as RunItem } from './runner-Kga7ABQA.js';
2
+ export { c as EvalContext, d as EvalRun, e as EvalRunSpec, f as EvalRunStatus, g as EvalRunTarget, h as EvaluatorKind, i as ExecuteOptions, j as ExecuteResult, G as GenerationSignal, k as GenerationSignalItem, I as ITEM_CONTENT_TOKEN_ALLOWANCE, J as JUDGE_COMPLETION_TOKEN_CAP, l as JudgeTemplate, m as ModelCompletionOptions, n as ModelResponse, S as ScoredItem, o as StaticModelClient, T as TokenUsage, p as codeEvaluator, q as deriveReserveTokensPerCall, r as executeEvalRun, s as llmJudge, t as maxCompletionTokenUsage, u as parseJudgeResponse, v as render } from './runner-Kga7ABQA.js';
3
3
  import 'zod';
4
4
 
5
- /** What an evaluator sees: the example under test plus the produced output. */
6
- interface EvalInput {
7
- input: unknown;
8
- output: unknown;
9
- expectedOutput?: unknown;
10
- /** Retrieved context for RAG-style judges (documents, tool results). */
11
- context?: unknown;
12
- metadata?: Record<string, unknown>;
13
- }
14
- interface EvalContext {
15
- model: ModelClient;
16
- nowMs: () => number;
17
- }
18
- interface Evaluator {
19
- readonly kind: EvaluatorKind;
20
- readonly name: string;
21
- readonly version: string;
22
- /** Worst-case judge usage reserved before IO; absent for token-free evaluators. */
23
- maxJudgeTokens?(input: EvalInput): number;
24
- /**
25
- * The judge's prompt template, when the evaluator is an LLM judge. Exposed
26
- * so budget derivation (deriveReserveTokensPerCall) can size worst-case
27
- * per-call token reservations from the actual prompt text.
28
- */
29
- readonly promptTemplate?: Pick<JudgeTemplate, 'system' | 'user'>;
30
- evaluate(input: EvalInput, ctx: EvalContext): Promise<EvalScore>;
31
- }
32
- interface JudgeTemplate {
33
- name: string;
34
- version: string;
35
- /** Labels the judge may answer with, mapped to normalized scores. */
36
- labels: Record<string, number>;
37
- system: string;
38
- /** Rendered with {{input}}, {{output}}, {{expectedOutput}}, {{context}}. */
39
- user: string;
40
- /** Deterministic provider-enforced response ceiling. Default: 256. */
41
- maxOutputTokens?: number;
42
- }
43
- /**
44
- * Build an LLM-judge evaluator from a template. Response contract: the model
45
- * answers `LABEL: <label>` on the first line, free-form explanation after —
46
- * a portable explanation-bearing format that remains easy to import/export.
47
- */
48
- declare function llmJudge(template: JudgeTemplate): Evaluator;
49
- /** Build a deterministic code evaluator from a pure function. */
50
- declare function codeEvaluator(name: string, version: string, fn: (input: EvalInput) => {
51
- label?: string;
52
- score: number | null;
53
- explanation?: string;
54
- }): Evaluator;
55
- declare function render(template: string, input: EvalInput): string;
56
- declare function parseJudgeResponse(text: string, labels: Record<string, number>): {
57
- label?: string;
58
- score: number | null;
59
- explanation?: string;
60
- };
61
-
62
5
  /**
63
6
  * Built-in judge library. Prompts use a portable binary-label + explanation
64
7
  * contract and are versioned independently — bump the version on ANY prompt
@@ -101,80 +44,6 @@ interface EvaluatorAggregate {
101
44
  /** Pure aggregation over a run's scores, grouped by evaluator name+version. */
102
45
  declare function aggregateScores(scores: readonly EvalScore[]): EvaluatorAggregate[];
103
46
 
104
- interface RunItem {
105
- /** Dataset exampleId or span id — opaque to the runner. */
106
- itemId: string;
107
- input: EvalInput;
108
- }
109
- interface ScoredItem {
110
- itemId: string;
111
- score: EvalScore;
112
- }
113
- interface ExecuteOptions {
114
- evaluators: readonly Evaluator[];
115
- items: readonly RunItem[];
116
- ctx: EvalContext;
117
- /**
118
- * Hard token budget (governance: eval-cost-controls). Enforced by
119
- * reservation: a judge call only starts if `spent + reserved +
120
- * reserveTokensPerCall` still fits, so concurrent workers can never
121
- * collectively overshoot by racing the check.
122
- */
123
- maxJudgeTokens?: number;
124
- /**
125
- * Optional minimum reservation per judge call. The runner always takes the
126
- * larger of this value and the evaluator's input-specific worst-case bound.
127
- * Code and heuristic evaluators reserve zero tokens and continue after a
128
- * judge budget is exhausted.
129
- */
130
- reserveTokensPerCall?: number;
131
- concurrency?: number;
132
- /** Called after each item completes — the agent checkpoints here. */
133
- onProgress?: (done: number, total: number, tokensSpent: number) => void;
134
- }
135
- interface ExecuteResult {
136
- scores: ScoredItem[];
137
- tokensSpent: number;
138
- /** Items fully or partially skipped because the token budget was exhausted. */
139
- skippedForBudget: number;
140
- /** Individual judge evaluations skipped because their reservation did not fit. */
141
- skippedEvaluationsForBudget: number;
142
- /** Per-item evaluator failures (item kept; other evaluators still ran). */
143
- failures: Array<{
144
- itemId: string;
145
- evaluatorName: string;
146
- message: string;
147
- }>;
148
- }
149
- /**
150
- * Completion cap assumed per judge call when sizing reservations. Judges
151
- * answer `LABEL: <label>` plus a brief explanation — 512 tokens is a generous
152
- * ceiling for that contract.
153
- */
154
- declare const JUDGE_COMPLETION_TOKEN_CAP = 512;
155
- /**
156
- * Prompt-token allowance for the item content rendered into the template
157
- * ({{input}}/{{output}}/{{expectedOutput}}/{{context}}). A worst-case bound
158
- * for typical dataset examples; oversized examples only weaken the guarantee
159
- * to "caps the number of calls started" (see reserveTokensPerCall docs).
160
- */
161
- declare const ITEM_CONTENT_TOKEN_ALLOWANCE = 1024;
162
- /**
163
- * Worst-case tokens one judge call may consume, derived from the largest
164
- * prompt template among the run's evaluators (chars/4 heuristic) plus the
165
- * item-content allowance and the completion cap. Threaded from run creation
166
- * into ExecuteOptions.reserveTokensPerCall so the hard budget is enforced by
167
- * reservation rather than after-the-fact accounting.
168
- */
169
- declare function deriveReserveTokensPerCall(evaluators: readonly Evaluator[]): number;
170
- /**
171
- * Pure orchestration: evaluate every item with every evaluator under a hard
172
- * token budget, bounded concurrency, and per-evaluator error isolation. IO
173
- * happens only through the injected ModelClient; persistence is the caller's
174
- * job (the eval-runner agent writes to the warehouse between batches).
175
- */
176
- declare function executeEvalRun(opts: ExecuteOptions): Promise<ExecuteResult>;
177
-
178
47
  /**
179
48
  * Generation phase for playground-replay eval runs (review fix: replay must
180
49
  * not call the model inside the API request lifecycle). The run executor —
@@ -254,4 +123,4 @@ interface GenerationPhaseResult {
254
123
  */
255
124
  declare function executeGenerationPhase(opts: GenerationPhaseOptions): Promise<GenerationPhaseResult>;
256
125
 
257
- export { BUILT_IN_EVALUATORS, ChatMessage, type EvalContext, type EvalInput, EvalScore, type Evaluator, type EvaluatorAggregate, EvaluatorKind, type ExecuteOptions, type ExecuteResult, GENERATION_COMPLETION_TOKEN_CAP, type GenerationItem, type GenerationPhaseOptions, type GenerationPhaseResult, ITEM_CONTENT_TOKEN_ALLOWANCE, JUDGE_COMPLETION_TOKEN_CAP, type JudgeTemplate, ModelClient, NO_REFERENCE_MARKER, type RunItem, type ScoredItem, aggregateScores, codeEvaluator, deriveReserveTokensPerCall, deriveReserveTokensPerGeneration, executeEvalRun, executeGenerationPhase, getEvaluator, hallucinationJudge, llmJudge, parseJudgeResponse, qaCorrectnessJudge, qaCorrectnessReferenceJudge, relevanceJudge, render, summarizationJudge, toxicityJudge, trajectoryCoherenceJudge };
126
+ export { BUILT_IN_EVALUATORS, ChatMessage, EvalInput, EvalScore, Evaluator, type EvaluatorAggregate, GENERATION_COMPLETION_TOKEN_CAP, type GenerationItem, type GenerationPhaseOptions, type GenerationPhaseResult, ModelClient, NO_REFERENCE_MARKER, RunItem, aggregateScores, deriveReserveTokensPerGeneration, executeGenerationPhase, getEvaluator, hallucinationJudge, qaCorrectnessJudge, qaCorrectnessReferenceJudge, relevanceJudge, summarizationJudge, toxicityJudge, trajectoryCoherenceJudge };
@@ -225,4 +225,135 @@ declare class StaticModelClient implements ModelClient {
225
225
  */
226
226
  declare function maxCompletionTokenUsage(messages: readonly ChatMessage[], options: ModelCompletionOptions): number;
227
227
 
228
- export { type ChatMessage as C, EvaluatorKind as E, GenerationSignal as G, type ModelClient as M, StaticModelClient as S, TokenUsage as T, EvalScore as a, EvalRun as b, EvalRunSpec as c, EvalRunStatus as d, EvalRunTarget as e, GenerationSignalItem as f, type ModelCompletionOptions as g, type ModelResponse as h, maxCompletionTokenUsage as m };
228
+ /** What an evaluator sees: the example under test plus the produced output. */
229
+ interface EvalInput {
230
+ input: unknown;
231
+ output: unknown;
232
+ expectedOutput?: unknown;
233
+ /** Retrieved context for RAG-style judges (documents, tool results). */
234
+ context?: unknown;
235
+ metadata?: Record<string, unknown>;
236
+ }
237
+ interface EvalContext {
238
+ model: ModelClient;
239
+ nowMs: () => number;
240
+ }
241
+ interface Evaluator {
242
+ readonly kind: EvaluatorKind;
243
+ readonly name: string;
244
+ readonly version: string;
245
+ /** Worst-case judge usage reserved before IO; absent for token-free evaluators. */
246
+ maxJudgeTokens?(input: EvalInput): number;
247
+ /**
248
+ * The judge's prompt template, when the evaluator is an LLM judge. Exposed
249
+ * so budget derivation (deriveReserveTokensPerCall) can size worst-case
250
+ * per-call token reservations from the actual prompt text.
251
+ */
252
+ readonly promptTemplate?: Pick<JudgeTemplate, 'system' | 'user'>;
253
+ evaluate(input: EvalInput, ctx: EvalContext): Promise<EvalScore>;
254
+ }
255
+ interface JudgeTemplate {
256
+ name: string;
257
+ version: string;
258
+ /** Labels the judge may answer with, mapped to normalized scores. */
259
+ labels: Record<string, number>;
260
+ system: string;
261
+ /** Rendered with {{input}}, {{output}}, {{expectedOutput}}, {{context}}. */
262
+ user: string;
263
+ /** Deterministic provider-enforced response ceiling. Default: 256. */
264
+ maxOutputTokens?: number;
265
+ }
266
+ /**
267
+ * Build an LLM-judge evaluator from a template. Response contract: the model
268
+ * answers `LABEL: <label>` on the first line, free-form explanation after —
269
+ * a portable explanation-bearing format that remains easy to import/export.
270
+ */
271
+ declare function llmJudge(template: JudgeTemplate): Evaluator;
272
+ /** Build a deterministic code evaluator from a pure function. */
273
+ declare function codeEvaluator(name: string, version: string, fn: (input: EvalInput) => {
274
+ label?: string;
275
+ score: number | null;
276
+ explanation?: string;
277
+ }): Evaluator;
278
+ declare function render(template: string, input: EvalInput): string;
279
+ declare function parseJudgeResponse(text: string, labels: Record<string, number>): {
280
+ label?: string;
281
+ score: number | null;
282
+ explanation?: string;
283
+ };
284
+
285
+ interface RunItem {
286
+ /** Dataset exampleId or span id — opaque to the runner. */
287
+ itemId: string;
288
+ input: EvalInput;
289
+ }
290
+ interface ScoredItem {
291
+ itemId: string;
292
+ score: EvalScore;
293
+ }
294
+ interface ExecuteOptions {
295
+ evaluators: readonly Evaluator[];
296
+ items: readonly RunItem[];
297
+ ctx: EvalContext;
298
+ /**
299
+ * Hard token budget (governance: eval-cost-controls). Enforced by
300
+ * reservation: a judge call only starts if `spent + reserved +
301
+ * reserveTokensPerCall` still fits, so concurrent workers can never
302
+ * collectively overshoot by racing the check.
303
+ */
304
+ maxJudgeTokens?: number;
305
+ /**
306
+ * Optional minimum reservation per judge call. The runner always takes the
307
+ * larger of this value and the evaluator's input-specific worst-case bound.
308
+ * Code and heuristic evaluators reserve zero tokens and continue after a
309
+ * judge budget is exhausted.
310
+ */
311
+ reserveTokensPerCall?: number;
312
+ concurrency?: number;
313
+ /** Called after each item completes — the agent checkpoints here. */
314
+ onProgress?: (done: number, total: number, tokensSpent: number) => void;
315
+ }
316
+ interface ExecuteResult {
317
+ scores: ScoredItem[];
318
+ tokensSpent: number;
319
+ /** Items fully or partially skipped because the token budget was exhausted. */
320
+ skippedForBudget: number;
321
+ /** Individual judge evaluations skipped because their reservation did not fit. */
322
+ skippedEvaluationsForBudget: number;
323
+ /** Per-item evaluator failures (item kept; other evaluators still ran). */
324
+ failures: Array<{
325
+ itemId: string;
326
+ evaluatorName: string;
327
+ message: string;
328
+ }>;
329
+ }
330
+ /**
331
+ * Completion cap assumed per judge call when sizing reservations. Judges
332
+ * answer `LABEL: <label>` plus a brief explanation — 512 tokens is a generous
333
+ * ceiling for that contract.
334
+ */
335
+ declare const JUDGE_COMPLETION_TOKEN_CAP = 512;
336
+ /**
337
+ * Prompt-token allowance for the item content rendered into the template
338
+ * ({{input}}/{{output}}/{{expectedOutput}}/{{context}}). A worst-case bound
339
+ * for typical dataset examples; oversized examples only weaken the guarantee
340
+ * to "caps the number of calls started" (see reserveTokensPerCall docs).
341
+ */
342
+ declare const ITEM_CONTENT_TOKEN_ALLOWANCE = 1024;
343
+ /**
344
+ * Worst-case tokens one judge call may consume, derived from the largest
345
+ * prompt template among the run's evaluators (chars/4 heuristic) plus the
346
+ * item-content allowance and the completion cap. Threaded from run creation
347
+ * into ExecuteOptions.reserveTokensPerCall so the hard budget is enforced by
348
+ * reservation rather than after-the-fact accounting.
349
+ */
350
+ declare function deriveReserveTokensPerCall(evaluators: readonly Evaluator[]): number;
351
+ /**
352
+ * Pure orchestration: evaluate every item with every evaluator under a hard
353
+ * token budget, bounded concurrency, and per-evaluator error isolation. IO
354
+ * happens only through the injected ModelClient; persistence is the caller's
355
+ * job (the eval-runner agent writes to the warehouse between batches).
356
+ */
357
+ declare function executeEvalRun(opts: ExecuteOptions): Promise<ExecuteResult>;
358
+
359
+ export { type ChatMessage as C, type Evaluator as E, GenerationSignal as G, ITEM_CONTENT_TOKEN_ALLOWANCE as I, JUDGE_COMPLETION_TOKEN_CAP as J, type ModelClient as M, type RunItem as R, type ScoredItem as S, TokenUsage as T, EvalScore as a, type EvalInput as b, type EvalContext as c, EvalRun as d, EvalRunSpec as e, EvalRunStatus as f, EvalRunTarget as g, EvaluatorKind as h, type ExecuteOptions as i, type ExecuteResult as j, GenerationSignalItem as k, type JudgeTemplate as l, type ModelCompletionOptions as m, type ModelResponse as n, StaticModelClient as o, codeEvaluator as p, deriveReserveTokensPerCall as q, executeEvalRun as r, llmJudge as s, maxCompletionTokenUsage as t, parseJudgeResponse as u, render as v };
@@ -225,4 +225,135 @@ declare class StaticModelClient implements ModelClient {
225
225
  */
226
226
  declare function maxCompletionTokenUsage(messages: readonly ChatMessage[], options: ModelCompletionOptions): number;
227
227
 
228
- export { type ChatMessage as C, EvaluatorKind as E, GenerationSignal as G, type ModelClient as M, StaticModelClient as S, TokenUsage as T, EvalScore as a, EvalRun as b, EvalRunSpec as c, EvalRunStatus as d, EvalRunTarget as e, GenerationSignalItem as f, type ModelCompletionOptions as g, type ModelResponse as h, maxCompletionTokenUsage as m };
228
+ /** What an evaluator sees: the example under test plus the produced output. */
229
+ interface EvalInput {
230
+ input: unknown;
231
+ output: unknown;
232
+ expectedOutput?: unknown;
233
+ /** Retrieved context for RAG-style judges (documents, tool results). */
234
+ context?: unknown;
235
+ metadata?: Record<string, unknown>;
236
+ }
237
+ interface EvalContext {
238
+ model: ModelClient;
239
+ nowMs: () => number;
240
+ }
241
+ interface Evaluator {
242
+ readonly kind: EvaluatorKind;
243
+ readonly name: string;
244
+ readonly version: string;
245
+ /** Worst-case judge usage reserved before IO; absent for token-free evaluators. */
246
+ maxJudgeTokens?(input: EvalInput): number;
247
+ /**
248
+ * The judge's prompt template, when the evaluator is an LLM judge. Exposed
249
+ * so budget derivation (deriveReserveTokensPerCall) can size worst-case
250
+ * per-call token reservations from the actual prompt text.
251
+ */
252
+ readonly promptTemplate?: Pick<JudgeTemplate, 'system' | 'user'>;
253
+ evaluate(input: EvalInput, ctx: EvalContext): Promise<EvalScore>;
254
+ }
255
+ interface JudgeTemplate {
256
+ name: string;
257
+ version: string;
258
+ /** Labels the judge may answer with, mapped to normalized scores. */
259
+ labels: Record<string, number>;
260
+ system: string;
261
+ /** Rendered with {{input}}, {{output}}, {{expectedOutput}}, {{context}}. */
262
+ user: string;
263
+ /** Deterministic provider-enforced response ceiling. Default: 256. */
264
+ maxOutputTokens?: number;
265
+ }
266
+ /**
267
+ * Build an LLM-judge evaluator from a template. Response contract: the model
268
+ * answers `LABEL: <label>` on the first line, free-form explanation after —
269
+ * a portable explanation-bearing format that remains easy to import/export.
270
+ */
271
+ declare function llmJudge(template: JudgeTemplate): Evaluator;
272
+ /** Build a deterministic code evaluator from a pure function. */
273
+ declare function codeEvaluator(name: string, version: string, fn: (input: EvalInput) => {
274
+ label?: string;
275
+ score: number | null;
276
+ explanation?: string;
277
+ }): Evaluator;
278
+ declare function render(template: string, input: EvalInput): string;
279
+ declare function parseJudgeResponse(text: string, labels: Record<string, number>): {
280
+ label?: string;
281
+ score: number | null;
282
+ explanation?: string;
283
+ };
284
+
285
+ interface RunItem {
286
+ /** Dataset exampleId or span id — opaque to the runner. */
287
+ itemId: string;
288
+ input: EvalInput;
289
+ }
290
+ interface ScoredItem {
291
+ itemId: string;
292
+ score: EvalScore;
293
+ }
294
+ interface ExecuteOptions {
295
+ evaluators: readonly Evaluator[];
296
+ items: readonly RunItem[];
297
+ ctx: EvalContext;
298
+ /**
299
+ * Hard token budget (governance: eval-cost-controls). Enforced by
300
+ * reservation: a judge call only starts if `spent + reserved +
301
+ * reserveTokensPerCall` still fits, so concurrent workers can never
302
+ * collectively overshoot by racing the check.
303
+ */
304
+ maxJudgeTokens?: number;
305
+ /**
306
+ * Optional minimum reservation per judge call. The runner always takes the
307
+ * larger of this value and the evaluator's input-specific worst-case bound.
308
+ * Code and heuristic evaluators reserve zero tokens and continue after a
309
+ * judge budget is exhausted.
310
+ */
311
+ reserveTokensPerCall?: number;
312
+ concurrency?: number;
313
+ /** Called after each item completes — the agent checkpoints here. */
314
+ onProgress?: (done: number, total: number, tokensSpent: number) => void;
315
+ }
316
+ interface ExecuteResult {
317
+ scores: ScoredItem[];
318
+ tokensSpent: number;
319
+ /** Items fully or partially skipped because the token budget was exhausted. */
320
+ skippedForBudget: number;
321
+ /** Individual judge evaluations skipped because their reservation did not fit. */
322
+ skippedEvaluationsForBudget: number;
323
+ /** Per-item evaluator failures (item kept; other evaluators still ran). */
324
+ failures: Array<{
325
+ itemId: string;
326
+ evaluatorName: string;
327
+ message: string;
328
+ }>;
329
+ }
330
+ /**
331
+ * Completion cap assumed per judge call when sizing reservations. Judges
332
+ * answer `LABEL: <label>` plus a brief explanation — 512 tokens is a generous
333
+ * ceiling for that contract.
334
+ */
335
+ declare const JUDGE_COMPLETION_TOKEN_CAP = 512;
336
+ /**
337
+ * Prompt-token allowance for the item content rendered into the template
338
+ * ({{input}}/{{output}}/{{expectedOutput}}/{{context}}). A worst-case bound
339
+ * for typical dataset examples; oversized examples only weaken the guarantee
340
+ * to "caps the number of calls started" (see reserveTokensPerCall docs).
341
+ */
342
+ declare const ITEM_CONTENT_TOKEN_ALLOWANCE = 1024;
343
+ /**
344
+ * Worst-case tokens one judge call may consume, derived from the largest
345
+ * prompt template among the run's evaluators (chars/4 heuristic) plus the
346
+ * item-content allowance and the completion cap. Threaded from run creation
347
+ * into ExecuteOptions.reserveTokensPerCall so the hard budget is enforced by
348
+ * reservation rather than after-the-fact accounting.
349
+ */
350
+ declare function deriveReserveTokensPerCall(evaluators: readonly Evaluator[]): number;
351
+ /**
352
+ * Pure orchestration: evaluate every item with every evaluator under a hard
353
+ * token budget, bounded concurrency, and per-evaluator error isolation. IO
354
+ * happens only through the injected ModelClient; persistence is the caller's
355
+ * job (the eval-runner agent writes to the warehouse between batches).
356
+ */
357
+ declare function executeEvalRun(opts: ExecuteOptions): Promise<ExecuteResult>;
358
+
359
+ export { type ChatMessage as C, type Evaluator as E, GenerationSignal as G, ITEM_CONTENT_TOKEN_ALLOWANCE as I, JUDGE_COMPLETION_TOKEN_CAP as J, type ModelClient as M, type RunItem as R, type ScoredItem as S, TokenUsage as T, EvalScore as a, type EvalInput as b, type EvalContext as c, EvalRun as d, EvalRunSpec as e, EvalRunStatus as f, EvalRunTarget as g, EvaluatorKind as h, type ExecuteOptions as i, type ExecuteResult as j, GenerationSignalItem as k, type JudgeTemplate as l, type ModelCompletionOptions as m, type ModelResponse as n, StaticModelClient as o, codeEvaluator as p, deriveReserveTokensPerCall as q, executeEvalRun as r, llmJudge as s, maxCompletionTokenUsage as t, parseJudgeResponse as u, render as v };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabricorg/experiments-evals",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "LLM and code evaluators for Fabric Experiments: judge library, ModelClient contract, run aggregation.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -30,7 +30,7 @@
30
30
  }
31
31
  }
32
32
  },
33
- "files": ["dist"],
33
+ "files": ["dist", "templates/databricks/mlflow_evaluate_records.py"],
34
34
  "scripts": {
35
35
  "build": "tsup",
36
36
  "type-check": "tsc --noEmit",
@@ -0,0 +1,200 @@
1
+ """Score precomputed Fabric evaluation records in a Databricks Python script task."""
2
+
3
+ import argparse
4
+ import json
5
+ import math
6
+ import re
7
+ from collections import defaultdict
8
+ from statistics import mean
9
+
10
+ import mlflow
11
+ from mlflow.genai.scorers import Correctness, Safety, get_scorer
12
+
13
+
14
+ FORMAT_TAG = "fabric.record_format_version"
15
+ FORMAT_VERSION = "1"
16
+ MLFLOW_VERSION = "3.18.0"
17
+ COVERAGE_TAG = "fabric.coverage_row"
18
+
19
+
20
+ def reject_json_constant(value):
21
+ raise ValueError(f"Invalid JSON constant: {value}")
22
+
23
+
24
+ def read_records(path):
25
+ records = []
26
+ with open(path, encoding="utf-8") as stream:
27
+ for number, line in enumerate(stream, 1):
28
+ try:
29
+ record = json.loads(line, parse_constant=reject_json_constant)
30
+ except ValueError as error:
31
+ raise ValueError(f"Invalid JSON on record line {number}") from error
32
+ if not isinstance(record, dict):
33
+ raise ValueError(f"Expected an object on record line {number}")
34
+ tags = record.get("tags")
35
+ if not isinstance(tags, dict) or tags.get(FORMAT_TAG) != FORMAT_VERSION:
36
+ raise ValueError(f"Unsupported record format version on line {number}")
37
+ if not isinstance(record.get("inputs"), dict) or "outputs" not in record:
38
+ raise ValueError(f"Expected inputs object and outputs on record line {number}")
39
+ validate_fields(record, tags, number)
40
+ records.append(record)
41
+ if not records:
42
+ raise ValueError("Expected at least one evaluation record")
43
+ return records
44
+
45
+
46
+ def validate_fields(record, tags, number):
47
+ if COVERAGE_TAG in tags or any(not isinstance(value, str) for value in tags.values()):
48
+ raise ValueError(f"Expected string tags without the reserved coverage tag on line {number}")
49
+ if "expectations" in record and not isinstance(record["expectations"], dict):
50
+ raise ValueError(f"Expected an expectations object on line {number}")
51
+ metadata = record.get("metadata", {})
52
+ if not isinstance(metadata, dict) or not isinstance(metadata.get("scores", []), list):
53
+ raise ValueError(f"Expected a metadata object with an optional score list on line {number}")
54
+ names = set()
55
+ for score in metadata.get("scores", []):
56
+ if not isinstance(score, dict) or not isinstance(score.get("evaluatorName"), str):
57
+ raise ValueError(f"Expected a named caller score on line {number}")
58
+ name = score["evaluatorName"]
59
+ if name in names:
60
+ raise ValueError(f"Duplicate caller evaluator on line {number}")
61
+ names.add(name)
62
+ if not isinstance(score.get("evaluatorVersion"), str) or "score" not in score:
63
+ raise ValueError(f"Expected caller score version and value on line {number}")
64
+ value = score["score"]
65
+ if value is not None and (type(value) not in (int, float) or not math.isfinite(value)):
66
+ raise ValueError(f"Expected a finite or null caller score on line {number}")
67
+ if "pass" in score and (type(score["pass"]) is not bool or (value is None and score["pass"])):
68
+ raise ValueError(f"Invalid caller pass value on line {number}")
69
+
70
+
71
+ def evaluation_data(records):
72
+ data = []
73
+ for index, record in enumerate(records):
74
+ row = {key: record[key] for key in ("inputs", "outputs", "expectations") if key in record}
75
+ row["tags"] = {**record["tags"], COVERAGE_TAG: str(index)}
76
+ data.append(row)
77
+ return data
78
+
79
+
80
+ def caller_metrics(records):
81
+ scores = defaultdict(list)
82
+ for record in records:
83
+ for result in record.get("metadata", {}).get("scores", []):
84
+ scores[result["evaluatorName"]].append(result)
85
+
86
+ metrics = {}
87
+ for name, results in scores.items():
88
+ metric_name = name
89
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+", name):
90
+ metric_name = f"utf8/{name.encode('utf-8', errors='surrogatepass').hex()}"
91
+ prefix = f"caller/{metric_name}"
92
+ values = [result["score"] for result in results if result["score"] is not None]
93
+ metrics[f"{prefix}/scored"] = len(values)
94
+ metrics[f"{prefix}/unscored"] = len(results) - len(values)
95
+ metrics[f"{prefix}/missing"] = len(records) - len(results)
96
+ if values:
97
+ metrics[f"{prefix}/mean"] = mean(values)
98
+ if any("pass" in result for result in results):
99
+ metrics[f"{prefix}/pass_rate"] = sum(result.get("pass", False) for result in results) / len(records)
100
+ return metrics
101
+
102
+
103
+ def require_native_coverage(result, scorers, record_count):
104
+ # MLflow 3.18.0 exposes trace tags and raw assessment dictionaries in result_df.
105
+ if not result.metrics:
106
+ raise RuntimeError("MLflow evaluation returned no aggregate metrics")
107
+ names = {metric.rpartition("/")[0] for metric in result.metrics}
108
+ if "" in names or not {scorer.name for scorer in scorers} <= names:
109
+ raise RuntimeError("MLflow native coverage requires a named aggregate for each selected scorer")
110
+ if any(metric.startswith("caller/") for metric in result.metrics):
111
+ raise RuntimeError("MLflow native metrics cannot use the reserved caller/ prefix")
112
+
113
+ frame = getattr(result, "result_df", None)
114
+ if not {"tags", "assessments"} <= set(getattr(frame, "columns", ())):
115
+ raise RuntimeError("Unsupported MLflow result layout: expected tags and assessments")
116
+ missing_rows = {str(index) for index in range(record_count)}
117
+ for row in frame.to_dict("records"):
118
+ tags, assessments = row["tags"], row["assessments"]
119
+ if not isinstance(tags, dict) or not isinstance(assessments, list):
120
+ raise RuntimeError("Unsupported MLflow result layout: expected trace tags and an assessment list")
121
+ row_id = tags.get(COVERAGE_TAG)
122
+ if not isinstance(row_id, str) or row_id not in missing_rows:
123
+ raise RuntimeError("MLflow native coverage has an unknown or duplicate record")
124
+ missing_rows.remove(row_id)
125
+ scored = set()
126
+ for assessment in assessments:
127
+ if not isinstance(assessment, dict) or not isinstance(assessment.get("assessment_name"), str):
128
+ raise RuntimeError("Unsupported MLflow result layout: expected a named assessment")
129
+ if "feedback" not in assessment:
130
+ continue
131
+ feedback = assessment["feedback"]
132
+ if not isinstance(feedback, dict) or "value" not in feedback:
133
+ raise RuntimeError("Unsupported MLflow result layout: expected feedback with a value")
134
+ name = assessment["assessment_name"]
135
+ if feedback.get("error") is not None:
136
+ raise RuntimeError(f"MLflow native coverage failed for scorer {name} on record {row_id}")
137
+ if name not in names:
138
+ continue
139
+ value = feedback["value"]
140
+ numeric = isinstance(value, (int, float)) and math.isfinite(value)
141
+ categorical = isinstance(value, str) and value.lower() in ("yes", "no")
142
+ if name in scored or not (numeric or categorical):
143
+ raise RuntimeError(f"MLflow native coverage needs one aggregatable {name} value on record {row_id}")
144
+ scored.add(name)
145
+ if scored != names:
146
+ raise RuntimeError(f"MLflow native coverage is missing {sorted(names - scored)} on record {row_id}")
147
+ if missing_rows:
148
+ raise RuntimeError(f"MLflow native coverage is missing {len(missing_rows)} record(s)")
149
+
150
+
151
+ def select_scorers(selection):
152
+ builtins = {"correctness": Correctness, "safety": Safety}
153
+ scorers = []
154
+ for entry in selection.split(","):
155
+ name = entry.strip()
156
+ if name in builtins:
157
+ scorers.append(builtins[name]())
158
+ elif name.startswith("registered:"):
159
+ scorers.append(get_scorer(name=name.removeprefix("registered:")))
160
+ else:
161
+ raise ValueError(f"Unknown scorer selection: {name}")
162
+ return scorers
163
+
164
+
165
+ def evaluate_records(path, experiment, run_name, selection):
166
+ if mlflow.__version__ != MLFLOW_VERSION:
167
+ raise RuntimeError(f"This template requires MLflow {MLFLOW_VERSION} to verify scoring coverage")
168
+ records = read_records(path)
169
+ data = evaluation_data(records)
170
+ metrics = caller_metrics(records)
171
+ tags = {
172
+ key: value
173
+ for key, value in records[0]["tags"].items()
174
+ if all(record["tags"].get(key) == value for record in records)
175
+ }
176
+ mlflow.set_tracking_uri("databricks")
177
+ mlflow.set_experiment(experiment)
178
+ scorers = select_scorers(selection)
179
+ with mlflow.start_run(run_name=run_name, tags=tags) as run:
180
+ mlflow.log_metrics(metrics)
181
+ result = mlflow.genai.evaluate(data=data, scorers=scorers)
182
+ require_native_coverage(result, scorers, len(records))
183
+ if any(value for key, value in metrics.items() if key.endswith(("/unscored", "/missing"))):
184
+ raise RuntimeError("Caller scoring coverage is incomplete; see the unscored and missing run metrics")
185
+ return run.info.run_id
186
+
187
+
188
+ def main():
189
+ parser = argparse.ArgumentParser(description=__doc__)
190
+ parser.add_argument("--records-path", required=True)
191
+ parser.add_argument("--experiment", required=True)
192
+ parser.add_argument("--run-name", required=True)
193
+ parser.add_argument("--scorers", required=True)
194
+ args = parser.parse_args()
195
+ run_id = evaluate_records(args.records_path, args.experiment, args.run_name, args.scorers)
196
+ print(run_id)
197
+
198
+
199
+ if __name__ == "__main__":
200
+ main()