@fabricorg/experiments-evals 0.2.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/README.md +43 -0
- package/dist/databricks.cjs +216 -0
- package/dist/databricks.cjs.map +1 -1
- package/dist/databricks.d.cts +45 -185
- package/dist/databricks.d.ts +45 -185
- package/dist/databricks.js +215 -1
- package/dist/databricks.js.map +1 -1
- package/dist/index.d.cts +3 -134
- package/dist/index.d.ts +3 -134
- package/dist/runner-Kga7ABQA.d.cts +359 -0
- package/dist/runner-Kga7ABQA.d.ts +359 -0
- package/package.json +6 -6
- package/templates/databricks/mlflow_evaluate_records.py +200 -0
- package/dist/model-client-B7yk_i1s.d.cts +0 -601
- package/dist/model-client-B7yk_i1s.d.ts +0 -601
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
declare const EvaluatorKind: z.ZodEnum<{
|
|
4
|
+
"llm-judge": "llm-judge";
|
|
5
|
+
code: "code";
|
|
6
|
+
heuristic: "heuristic";
|
|
7
|
+
}>;
|
|
8
|
+
type EvaluatorKind = z.infer<typeof EvaluatorKind>;
|
|
9
|
+
declare const TokenUsage: z.ZodObject<{
|
|
10
|
+
inputTokens: z.ZodNumber;
|
|
11
|
+
outputTokens: z.ZodNumber;
|
|
12
|
+
}, z.core.$strip>;
|
|
13
|
+
type TokenUsage = z.infer<typeof TokenUsage>;
|
|
14
|
+
/**
|
|
15
|
+
* One evaluator's verdict on one example (or, later, one span). `score` is
|
|
16
|
+
* normalized to [0, 1] where defined; `label` carries the categorical verdict
|
|
17
|
+
* ("hallucinated", "correct", …). Provenance fields are mandatory — every
|
|
18
|
+
* score must be traceable to evaluator name+version and, for judges, the
|
|
19
|
+
* prompt hash and model endpoint (governance: evals-judge-provenance).
|
|
20
|
+
*/
|
|
21
|
+
declare const EvalScore: z.ZodObject<{
|
|
22
|
+
evaluatorName: z.ZodString;
|
|
23
|
+
evaluatorVersion: z.ZodString;
|
|
24
|
+
label: z.ZodOptional<z.ZodString>;
|
|
25
|
+
score: z.ZodNullable<z.ZodNumber>;
|
|
26
|
+
explanation: z.ZodOptional<z.ZodString>;
|
|
27
|
+
promptHash: z.ZodOptional<z.ZodString>;
|
|
28
|
+
modelEndpoint: z.ZodOptional<z.ZodString>;
|
|
29
|
+
tokens: z.ZodOptional<z.ZodObject<{
|
|
30
|
+
inputTokens: z.ZodNumber;
|
|
31
|
+
outputTokens: z.ZodNumber;
|
|
32
|
+
}, z.core.$strip>>;
|
|
33
|
+
latencyMs: z.ZodNumber;
|
|
34
|
+
}, z.core.$strip>;
|
|
35
|
+
type EvalScore = z.infer<typeof EvalScore>;
|
|
36
|
+
declare const EvalRunStatus: z.ZodEnum<{
|
|
37
|
+
pending: "pending";
|
|
38
|
+
running: "running";
|
|
39
|
+
succeeded: "succeeded";
|
|
40
|
+
failed: "failed";
|
|
41
|
+
cancelled: "cancelled";
|
|
42
|
+
}>;
|
|
43
|
+
type EvalRunStatus = z.infer<typeof EvalRunStatus>;
|
|
44
|
+
/** Target of a run: a frozen dataset version, or a live experiment's variants. */
|
|
45
|
+
declare const EvalRunTarget: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
46
|
+
kind: z.ZodLiteral<"dataset">;
|
|
47
|
+
datasetId: z.ZodString;
|
|
48
|
+
version: z.ZodNumber;
|
|
49
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
50
|
+
kind: z.ZodLiteral<"experiment">;
|
|
51
|
+
experimentId: z.ZodString;
|
|
52
|
+
metricEventName: z.ZodOptional<z.ZodString>;
|
|
53
|
+
}, z.core.$strip>], "kind">;
|
|
54
|
+
type EvalRunTarget = z.infer<typeof EvalRunTarget>;
|
|
55
|
+
/** One rendered conversation the generation phase completes through the model. */
|
|
56
|
+
declare const GenerationSignalItem: z.ZodObject<{
|
|
57
|
+
itemId: z.ZodString;
|
|
58
|
+
messages: z.ZodArray<z.ZodObject<{
|
|
59
|
+
role: z.ZodEnum<{
|
|
60
|
+
system: "system";
|
|
61
|
+
user: "user";
|
|
62
|
+
assistant: "assistant";
|
|
63
|
+
}>;
|
|
64
|
+
content: z.ZodString;
|
|
65
|
+
}, z.core.$strip>>;
|
|
66
|
+
}, z.core.$strip>;
|
|
67
|
+
type GenerationSignalItem = z.infer<typeof GenerationSignalItem>;
|
|
68
|
+
/**
|
|
69
|
+
* Generation phase of a playground-replay run (rendered prompt version per
|
|
70
|
+
* example). Rendering happens at dispatch time (pure); the model calls
|
|
71
|
+
* happen in the durable executor, and their tokens count inside
|
|
72
|
+
* `maxJudgeTokens` — the run's SHARED budget (review fix: generation must
|
|
73
|
+
* not occur outside the budget or the request-side lifecycle).
|
|
74
|
+
*/
|
|
75
|
+
declare const GenerationSignal: z.ZodObject<{
|
|
76
|
+
promptId: z.ZodString;
|
|
77
|
+
promptVersion: z.ZodNumber;
|
|
78
|
+
reserveTokensPerCall: z.ZodNumber;
|
|
79
|
+
maxOutputTokens: z.ZodNumber;
|
|
80
|
+
temperature: z.ZodNumber;
|
|
81
|
+
items: z.ZodArray<z.ZodObject<{
|
|
82
|
+
itemId: z.ZodString;
|
|
83
|
+
messages: z.ZodArray<z.ZodObject<{
|
|
84
|
+
role: z.ZodEnum<{
|
|
85
|
+
system: "system";
|
|
86
|
+
user: "user";
|
|
87
|
+
assistant: "assistant";
|
|
88
|
+
}>;
|
|
89
|
+
content: z.ZodString;
|
|
90
|
+
}, z.core.$strip>>;
|
|
91
|
+
}, z.core.$strip>>;
|
|
92
|
+
}, z.core.$strip>;
|
|
93
|
+
type GenerationSignal = z.infer<typeof GenerationSignal>;
|
|
94
|
+
declare const EvalRunSpec: z.ZodObject<{
|
|
95
|
+
runId: z.ZodString;
|
|
96
|
+
tenantId: z.ZodString;
|
|
97
|
+
target: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
98
|
+
kind: z.ZodLiteral<"dataset">;
|
|
99
|
+
datasetId: z.ZodString;
|
|
100
|
+
version: z.ZodNumber;
|
|
101
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
102
|
+
kind: z.ZodLiteral<"experiment">;
|
|
103
|
+
experimentId: z.ZodString;
|
|
104
|
+
metricEventName: z.ZodOptional<z.ZodString>;
|
|
105
|
+
}, z.core.$strip>], "kind">;
|
|
106
|
+
generation: z.ZodOptional<z.ZodObject<{
|
|
107
|
+
promptId: z.ZodString;
|
|
108
|
+
promptVersion: z.ZodNumber;
|
|
109
|
+
reserveTokensPerCall: z.ZodNumber;
|
|
110
|
+
maxOutputTokens: z.ZodNumber;
|
|
111
|
+
temperature: z.ZodNumber;
|
|
112
|
+
items: z.ZodArray<z.ZodObject<{
|
|
113
|
+
itemId: z.ZodString;
|
|
114
|
+
messages: z.ZodArray<z.ZodObject<{
|
|
115
|
+
role: z.ZodEnum<{
|
|
116
|
+
system: "system";
|
|
117
|
+
user: "user";
|
|
118
|
+
assistant: "assistant";
|
|
119
|
+
}>;
|
|
120
|
+
content: z.ZodString;
|
|
121
|
+
}, z.core.$strip>>;
|
|
122
|
+
}, z.core.$strip>>;
|
|
123
|
+
}, z.core.$strip>>;
|
|
124
|
+
evaluatorNames: z.ZodArray<z.ZodString>;
|
|
125
|
+
maxJudgeTokens: z.ZodOptional<z.ZodNumber>;
|
|
126
|
+
reserveTokensPerCall: z.ZodOptional<z.ZodNumber>;
|
|
127
|
+
createdAtIso: z.ZodString;
|
|
128
|
+
}, z.core.$strip>;
|
|
129
|
+
type EvalRunSpec = z.infer<typeof EvalRunSpec>;
|
|
130
|
+
declare const EvalRun: z.ZodObject<{
|
|
131
|
+
runId: z.ZodString;
|
|
132
|
+
tenantId: z.ZodString;
|
|
133
|
+
target: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
134
|
+
kind: z.ZodLiteral<"dataset">;
|
|
135
|
+
datasetId: z.ZodString;
|
|
136
|
+
version: z.ZodNumber;
|
|
137
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
138
|
+
kind: z.ZodLiteral<"experiment">;
|
|
139
|
+
experimentId: z.ZodString;
|
|
140
|
+
metricEventName: z.ZodOptional<z.ZodString>;
|
|
141
|
+
}, z.core.$strip>], "kind">;
|
|
142
|
+
generation: z.ZodOptional<z.ZodObject<{
|
|
143
|
+
promptId: z.ZodString;
|
|
144
|
+
promptVersion: z.ZodNumber;
|
|
145
|
+
reserveTokensPerCall: z.ZodNumber;
|
|
146
|
+
maxOutputTokens: z.ZodNumber;
|
|
147
|
+
temperature: z.ZodNumber;
|
|
148
|
+
items: z.ZodArray<z.ZodObject<{
|
|
149
|
+
itemId: z.ZodString;
|
|
150
|
+
messages: z.ZodArray<z.ZodObject<{
|
|
151
|
+
role: z.ZodEnum<{
|
|
152
|
+
system: "system";
|
|
153
|
+
user: "user";
|
|
154
|
+
assistant: "assistant";
|
|
155
|
+
}>;
|
|
156
|
+
content: z.ZodString;
|
|
157
|
+
}, z.core.$strip>>;
|
|
158
|
+
}, z.core.$strip>>;
|
|
159
|
+
}, z.core.$strip>>;
|
|
160
|
+
evaluatorNames: z.ZodArray<z.ZodString>;
|
|
161
|
+
maxJudgeTokens: z.ZodOptional<z.ZodNumber>;
|
|
162
|
+
reserveTokensPerCall: z.ZodOptional<z.ZodNumber>;
|
|
163
|
+
createdAtIso: z.ZodString;
|
|
164
|
+
status: z.ZodEnum<{
|
|
165
|
+
pending: "pending";
|
|
166
|
+
running: "running";
|
|
167
|
+
succeeded: "succeeded";
|
|
168
|
+
failed: "failed";
|
|
169
|
+
cancelled: "cancelled";
|
|
170
|
+
}>;
|
|
171
|
+
scoredExamples: z.ZodNumber;
|
|
172
|
+
totalExamples: z.ZodNumber;
|
|
173
|
+
tokensSpent: z.ZodNumber;
|
|
174
|
+
costUsd: z.ZodNullable<z.ZodNumber>;
|
|
175
|
+
startedAtIso: z.ZodOptional<z.ZodString>;
|
|
176
|
+
finishedAtIso: z.ZodOptional<z.ZodString>;
|
|
177
|
+
error: z.ZodOptional<z.ZodString>;
|
|
178
|
+
}, z.core.$strip>;
|
|
179
|
+
type EvalRun = z.infer<typeof EvalRun>;
|
|
180
|
+
|
|
181
|
+
interface ChatMessage {
|
|
182
|
+
role: 'system' | 'user' | 'assistant';
|
|
183
|
+
content: string;
|
|
184
|
+
}
|
|
185
|
+
interface ModelResponse {
|
|
186
|
+
text: string;
|
|
187
|
+
tokens: TokenUsage;
|
|
188
|
+
}
|
|
189
|
+
interface ModelCompletionOptions {
|
|
190
|
+
/** Judges must be deterministic unless a caller explicitly builds another evaluator. */
|
|
191
|
+
temperature: number;
|
|
192
|
+
/** Provider-enforced completion ceiling used by the run budget reservation. */
|
|
193
|
+
maxOutputTokens: number;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* The only surface through which evaluators reach a model. Production ships
|
|
197
|
+
* a Databricks Model Serving adapter at the explicit `/databricks` package
|
|
198
|
+
* subpath; the provider-neutral root never imports a provider client. Tests
|
|
199
|
+
* use `StaticModelClient`.
|
|
200
|
+
*/
|
|
201
|
+
interface ModelClient {
|
|
202
|
+
/** Identifier recorded in EvalScore.modelEndpoint for provenance. */
|
|
203
|
+
readonly endpoint: string;
|
|
204
|
+
complete(messages: readonly ChatMessage[], options: ModelCompletionOptions): Promise<ModelResponse>;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Deterministic client for unit tests and `fx dev`: responses are matched by
|
|
208
|
+
* substring of the last user message, mirroring the frozen-vector discipline
|
|
209
|
+
* in `@fabricorg/experiments-testkit`.
|
|
210
|
+
*/
|
|
211
|
+
declare class StaticModelClient implements ModelClient {
|
|
212
|
+
private readonly rules;
|
|
213
|
+
private readonly fallback;
|
|
214
|
+
readonly endpoint = "static-test-endpoint";
|
|
215
|
+
constructor(rules: Array<{
|
|
216
|
+
match: string;
|
|
217
|
+
respond: string;
|
|
218
|
+
}>, fallback?: string);
|
|
219
|
+
complete(messages: readonly ChatMessage[], options: ModelCompletionOptions): Promise<ModelResponse>;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Conservative provider-independent upper bound used before a judge call.
|
|
223
|
+
* A tokenizer cannot emit more tokens than the UTF-8 bytes representing the
|
|
224
|
+
* message content; the fixed allowance covers chat framing and role markers.
|
|
225
|
+
*/
|
|
226
|
+
declare function maxCompletionTokenUsage(messages: readonly ChatMessage[], options: ModelCompletionOptions): number;
|
|
227
|
+
|
|
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": "
|
|
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",
|
|
@@ -38,13 +38,13 @@
|
|
|
38
38
|
"clean": "rm -rf dist"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@fabricorg/experiments-datasets": "^
|
|
42
|
-
"@fabricorg/experiments-stats": "^0.0
|
|
43
|
-
"zod": "^
|
|
41
|
+
"@fabricorg/experiments-datasets": "^1.0.0",
|
|
42
|
+
"@fabricorg/experiments-stats": "^1.0.0",
|
|
43
|
+
"zod": "^4.6.7"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
46
|
"tsup": "^8.3.5",
|
|
47
47
|
"typescript": "^5.8.3",
|
|
48
|
-
"vitest": "^
|
|
48
|
+
"vitest": "^4.1.12"
|
|
49
49
|
}
|
|
50
50
|
}
|
|
@@ -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()
|