@deepagents/evals 0.19.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 +218 -0
- package/dist/comparison/index.d.ts +41 -0
- package/dist/comparison/index.d.ts.map +1 -0
- package/dist/comparison/index.js +106 -0
- package/dist/comparison/index.js.map +7 -0
- package/dist/dataset/hf.d.ts +16 -0
- package/dist/dataset/hf.d.ts.map +1 -0
- package/dist/dataset/index.d.ts +17 -0
- package/dist/dataset/index.d.ts.map +1 -0
- package/dist/dataset/index.js +256 -0
- package/dist/dataset/index.js.map +7 -0
- package/dist/engine/index.d.ts +67 -0
- package/dist/engine/index.d.ts.map +1 -0
- package/dist/engine/index.js +332 -0
- package/dist/engine/index.js.map +7 -0
- package/dist/evaluate/index.d.ts +47 -0
- package/dist/evaluate/index.d.ts.map +1 -0
- package/dist/evaluate/index.js +977 -0
- package/dist/evaluate/index.js.map +7 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1763 -0
- package/dist/index.js.map +7 -0
- package/dist/reporters/console.d.ts +6 -0
- package/dist/reporters/console.d.ts.map +1 -0
- package/dist/reporters/csv.d.ts +6 -0
- package/dist/reporters/csv.d.ts.map +1 -0
- package/dist/reporters/format.d.ts +12 -0
- package/dist/reporters/format.d.ts.map +1 -0
- package/dist/reporters/html.d.ts +6 -0
- package/dist/reporters/html.d.ts.map +1 -0
- package/dist/reporters/index.d.ts +12 -0
- package/dist/reporters/index.d.ts.map +1 -0
- package/dist/reporters/index.js +447 -0
- package/dist/reporters/index.js.map +7 -0
- package/dist/reporters/json.d.ts +7 -0
- package/dist/reporters/json.d.ts.map +1 -0
- package/dist/reporters/markdown.d.ts +6 -0
- package/dist/reporters/markdown.d.ts.map +1 -0
- package/dist/reporters/shared.d.ts +11 -0
- package/dist/reporters/shared.d.ts.map +1 -0
- package/dist/reporters/types.d.ts +35 -0
- package/dist/reporters/types.d.ts.map +1 -0
- package/dist/scorers/index.d.ts +30 -0
- package/dist/scorers/index.d.ts.map +1 -0
- package/dist/scorers/index.js +175 -0
- package/dist/scorers/index.js.map +7 -0
- package/dist/store/index.d.ts +103 -0
- package/dist/store/index.d.ts.map +1 -0
- package/dist/store/index.js +361 -0
- package/dist/store/index.js.map +7 -0
- package/package.json +99 -0
|
@@ -0,0 +1,977 @@
|
|
|
1
|
+
// packages/evals/src/dataset/index.ts
|
|
2
|
+
import { createReadStream } from "node:fs";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { extname } from "node:path";
|
|
5
|
+
import { createInterface } from "node:readline";
|
|
6
|
+
var Dataset = class _Dataset {
|
|
7
|
+
#source;
|
|
8
|
+
constructor(source) {
|
|
9
|
+
this.#source = source;
|
|
10
|
+
}
|
|
11
|
+
map(fn) {
|
|
12
|
+
const source = this.#source;
|
|
13
|
+
return new _Dataset(async function* () {
|
|
14
|
+
for await (const item of source()) {
|
|
15
|
+
yield fn(item);
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
filter(fn) {
|
|
20
|
+
const source = this.#source;
|
|
21
|
+
return new _Dataset(async function* () {
|
|
22
|
+
for await (const item of source()) {
|
|
23
|
+
if (fn(item)) yield item;
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
limit(n) {
|
|
28
|
+
const source = this.#source;
|
|
29
|
+
return new _Dataset(async function* () {
|
|
30
|
+
let count = 0;
|
|
31
|
+
for await (const item of source()) {
|
|
32
|
+
if (count >= n) return;
|
|
33
|
+
yield item;
|
|
34
|
+
count++;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
shuffle() {
|
|
39
|
+
const source = this.#source;
|
|
40
|
+
return new _Dataset(async function* () {
|
|
41
|
+
const items = [];
|
|
42
|
+
for await (const item of source()) {
|
|
43
|
+
items.push(item);
|
|
44
|
+
}
|
|
45
|
+
for (let i = items.length - 1; i > 0; i--) {
|
|
46
|
+
const j = Math.floor(Math.random() * (i + 1));
|
|
47
|
+
const temp = items[i];
|
|
48
|
+
items[i] = items[j];
|
|
49
|
+
items[j] = temp;
|
|
50
|
+
}
|
|
51
|
+
yield* items;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
sample(n) {
|
|
55
|
+
const source = this.#source;
|
|
56
|
+
return new _Dataset(async function* () {
|
|
57
|
+
const items = [];
|
|
58
|
+
for await (const item of source()) {
|
|
59
|
+
items.push(item);
|
|
60
|
+
}
|
|
61
|
+
const count = Math.min(Math.max(0, n), items.length);
|
|
62
|
+
for (let i = items.length - 1; i > items.length - count - 1; i--) {
|
|
63
|
+
const j = Math.floor(Math.random() * (i + 1));
|
|
64
|
+
const temp = items[i];
|
|
65
|
+
items[i] = items[j];
|
|
66
|
+
items[j] = temp;
|
|
67
|
+
}
|
|
68
|
+
for (let i = items.length - count; i < items.length; i++) {
|
|
69
|
+
yield items[i];
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
async toArray() {
|
|
74
|
+
const result = [];
|
|
75
|
+
for await (const item of this.#source()) {
|
|
76
|
+
result.push(item);
|
|
77
|
+
}
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
[Symbol.asyncIterator]() {
|
|
81
|
+
return this.#source()[Symbol.asyncIterator]();
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
function parseCSVLine(line) {
|
|
85
|
+
const fields = [];
|
|
86
|
+
let current = "";
|
|
87
|
+
let inQuotes = false;
|
|
88
|
+
for (let i = 0; i < line.length; i++) {
|
|
89
|
+
const char = line[i];
|
|
90
|
+
if (inQuotes) {
|
|
91
|
+
if (char === '"') {
|
|
92
|
+
if (i + 1 < line.length && line[i + 1] === '"') {
|
|
93
|
+
current += '"';
|
|
94
|
+
i++;
|
|
95
|
+
} else {
|
|
96
|
+
inQuotes = false;
|
|
97
|
+
}
|
|
98
|
+
} else {
|
|
99
|
+
current += char;
|
|
100
|
+
}
|
|
101
|
+
} else {
|
|
102
|
+
if (char === '"' && current === "") {
|
|
103
|
+
inQuotes = true;
|
|
104
|
+
} else if (char === ",") {
|
|
105
|
+
fields.push(current);
|
|
106
|
+
current = "";
|
|
107
|
+
} else {
|
|
108
|
+
current += char;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
fields.push(current);
|
|
113
|
+
return fields;
|
|
114
|
+
}
|
|
115
|
+
function loadJSON(filePath) {
|
|
116
|
+
return async function* () {
|
|
117
|
+
const content = await readFile(filePath, "utf-8");
|
|
118
|
+
const data = JSON.parse(content);
|
|
119
|
+
if (!Array.isArray(data)) {
|
|
120
|
+
throw new Error(`JSON file "${filePath}" does not contain an array`);
|
|
121
|
+
}
|
|
122
|
+
yield* data;
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function loadJSONL(filePath) {
|
|
126
|
+
return async function* () {
|
|
127
|
+
const rl = createInterface({
|
|
128
|
+
input: createReadStream(filePath, "utf-8"),
|
|
129
|
+
crlfDelay: Infinity
|
|
130
|
+
});
|
|
131
|
+
try {
|
|
132
|
+
for await (const line of rl) {
|
|
133
|
+
const trimmed = line.trim();
|
|
134
|
+
if (trimmed) {
|
|
135
|
+
yield JSON.parse(trimmed);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
} finally {
|
|
139
|
+
rl.close();
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function loadCSV(filePath) {
|
|
144
|
+
return async function* () {
|
|
145
|
+
const rl = createInterface({
|
|
146
|
+
input: createReadStream(filePath, "utf-8"),
|
|
147
|
+
crlfDelay: Infinity
|
|
148
|
+
});
|
|
149
|
+
try {
|
|
150
|
+
let headers;
|
|
151
|
+
for await (const line of rl) {
|
|
152
|
+
const trimmed = line.trim();
|
|
153
|
+
if (!trimmed) continue;
|
|
154
|
+
const fields = parseCSVLine(trimmed);
|
|
155
|
+
if (!headers) {
|
|
156
|
+
headers = fields;
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const row = {};
|
|
160
|
+
for (let i = 0; i < headers.length; i++) {
|
|
161
|
+
row[headers[i]] = fields[i] ?? "";
|
|
162
|
+
}
|
|
163
|
+
yield row;
|
|
164
|
+
}
|
|
165
|
+
} finally {
|
|
166
|
+
rl.close();
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
function dataset(source) {
|
|
171
|
+
if (Array.isArray(source)) {
|
|
172
|
+
return new Dataset(async function* () {
|
|
173
|
+
yield* source;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
if (typeof source === "object" && Symbol.asyncIterator in source) {
|
|
177
|
+
return new Dataset(() => source);
|
|
178
|
+
}
|
|
179
|
+
const ext = extname(source).toLowerCase();
|
|
180
|
+
switch (ext) {
|
|
181
|
+
case ".json":
|
|
182
|
+
return new Dataset(loadJSON(source));
|
|
183
|
+
case ".jsonl":
|
|
184
|
+
return new Dataset(loadJSONL(source));
|
|
185
|
+
case ".csv":
|
|
186
|
+
return new Dataset(loadCSV(source));
|
|
187
|
+
default:
|
|
188
|
+
throw new Error(
|
|
189
|
+
`Unsupported file extension "${ext}" for dataset file "${source}". Supported: .json, .jsonl, .csv`
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// packages/evals/src/engine/index.ts
|
|
195
|
+
import { EventEmitter } from "node:events";
|
|
196
|
+
var EvalEmitter = class extends EventEmitter {
|
|
197
|
+
on(event, listener) {
|
|
198
|
+
return super.on(event, listener);
|
|
199
|
+
}
|
|
200
|
+
emit(event, data) {
|
|
201
|
+
return super.emit(event, data);
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
function errorMessage(err) {
|
|
205
|
+
if (err instanceof Error) {
|
|
206
|
+
return `${err.name}: ${err.message}`;
|
|
207
|
+
}
|
|
208
|
+
if (typeof err === "string") return err;
|
|
209
|
+
if (err == null) return "Unknown error";
|
|
210
|
+
try {
|
|
211
|
+
return JSON.stringify(err);
|
|
212
|
+
} catch {
|
|
213
|
+
return String(err);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function serializeError(err) {
|
|
217
|
+
if (err instanceof Error) {
|
|
218
|
+
return JSON.stringify({
|
|
219
|
+
name: err.name,
|
|
220
|
+
message: err.message,
|
|
221
|
+
stack: err.stack,
|
|
222
|
+
cause: err.cause instanceof Error ? {
|
|
223
|
+
name: err.cause.name,
|
|
224
|
+
message: err.cause.message
|
|
225
|
+
} : err.cause
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
if (typeof err === "string") return JSON.stringify({ message: err });
|
|
229
|
+
if (err == null) return JSON.stringify({ message: "Unknown error" });
|
|
230
|
+
try {
|
|
231
|
+
return JSON.stringify(err);
|
|
232
|
+
} catch {
|
|
233
|
+
return JSON.stringify({ message: String(err) });
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function failureScores(scorerNames, error) {
|
|
237
|
+
const reason = `Task failed: ${errorMessage(error)}`;
|
|
238
|
+
const scores = {};
|
|
239
|
+
for (const scorerName of scorerNames) {
|
|
240
|
+
scores[scorerName] = { score: 0, reason };
|
|
241
|
+
}
|
|
242
|
+
return scores;
|
|
243
|
+
}
|
|
244
|
+
function createSemaphore(maxConcurrency) {
|
|
245
|
+
let active = 0;
|
|
246
|
+
const queue = [];
|
|
247
|
+
return {
|
|
248
|
+
async acquire() {
|
|
249
|
+
if (active < maxConcurrency) {
|
|
250
|
+
active++;
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
return new Promise((resolve) => queue.push(resolve));
|
|
254
|
+
},
|
|
255
|
+
release() {
|
|
256
|
+
active--;
|
|
257
|
+
const next = queue.shift();
|
|
258
|
+
if (next) {
|
|
259
|
+
active++;
|
|
260
|
+
next();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
async function wrapTask(task, input, timeoutMs) {
|
|
266
|
+
const start = performance.now();
|
|
267
|
+
let timerId;
|
|
268
|
+
try {
|
|
269
|
+
const result = await Promise.race([
|
|
270
|
+
task(input),
|
|
271
|
+
new Promise((_, reject) => {
|
|
272
|
+
timerId = setTimeout(
|
|
273
|
+
() => reject(new Error("timeout exceeded")),
|
|
274
|
+
timeoutMs
|
|
275
|
+
);
|
|
276
|
+
})
|
|
277
|
+
]);
|
|
278
|
+
clearTimeout(timerId);
|
|
279
|
+
const latencyMs = Math.round(performance.now() - start);
|
|
280
|
+
return {
|
|
281
|
+
output: result.output,
|
|
282
|
+
latencyMs,
|
|
283
|
+
tokensIn: result.usage?.inputTokens ?? 0,
|
|
284
|
+
tokensOut: result.usage?.outputTokens ?? 0
|
|
285
|
+
};
|
|
286
|
+
} catch (err) {
|
|
287
|
+
clearTimeout(timerId);
|
|
288
|
+
const latencyMs = Math.round(performance.now() - start);
|
|
289
|
+
return {
|
|
290
|
+
output: "",
|
|
291
|
+
latencyMs,
|
|
292
|
+
tokensIn: 0,
|
|
293
|
+
tokensOut: 0,
|
|
294
|
+
error: err
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
function clampScore(score, scorerName) {
|
|
299
|
+
if (score < 0 || score > 1) {
|
|
300
|
+
console.warn(
|
|
301
|
+
`Scorer "${scorerName}" returned out-of-range score ${score}, clamping to 0..1`
|
|
302
|
+
);
|
|
303
|
+
return Math.max(0, Math.min(1, score));
|
|
304
|
+
}
|
|
305
|
+
return score;
|
|
306
|
+
}
|
|
307
|
+
async function runEval(config) {
|
|
308
|
+
const {
|
|
309
|
+
name,
|
|
310
|
+
model,
|
|
311
|
+
dataset: ds,
|
|
312
|
+
task,
|
|
313
|
+
scorers,
|
|
314
|
+
store,
|
|
315
|
+
suiteId,
|
|
316
|
+
maxConcurrency = 10,
|
|
317
|
+
batchSize,
|
|
318
|
+
timeout = 3e4,
|
|
319
|
+
trials = 1,
|
|
320
|
+
threshold = 0.5
|
|
321
|
+
} = config;
|
|
322
|
+
const emitter = config.emitter ?? new EvalEmitter();
|
|
323
|
+
const resolvedSuiteId = suiteId ?? store.createSuite(name).id;
|
|
324
|
+
const runId = store.createRun({
|
|
325
|
+
suite_id: resolvedSuiteId,
|
|
326
|
+
name,
|
|
327
|
+
model,
|
|
328
|
+
config: config.config
|
|
329
|
+
});
|
|
330
|
+
const items = [];
|
|
331
|
+
let idx = 0;
|
|
332
|
+
for await (const item of ds) {
|
|
333
|
+
items.push({ index: idx++, input: item });
|
|
334
|
+
}
|
|
335
|
+
emitter.emit("run:start", { runId, totalCases: items.length, name, model });
|
|
336
|
+
const semaphore = createSemaphore(maxConcurrency);
|
|
337
|
+
const scorerNames = Object.keys(scorers);
|
|
338
|
+
const allCaseScores = [];
|
|
339
|
+
const processItem = async ({ index, input }) => {
|
|
340
|
+
await semaphore.acquire();
|
|
341
|
+
try {
|
|
342
|
+
emitter.emit("case:start", { runId, index, input });
|
|
343
|
+
let finalResult;
|
|
344
|
+
let finalScores;
|
|
345
|
+
if (trials > 1) {
|
|
346
|
+
const trialResults = [];
|
|
347
|
+
for (let t = 0; t < trials; t++) {
|
|
348
|
+
const result = await wrapTask(task, input, timeout);
|
|
349
|
+
if (result.error) {
|
|
350
|
+
trialResults.push({
|
|
351
|
+
result,
|
|
352
|
+
scores: failureScores(scorerNames, result.error)
|
|
353
|
+
});
|
|
354
|
+
} else {
|
|
355
|
+
const scores = {};
|
|
356
|
+
for (const [sName, scorer] of Object.entries(scorers)) {
|
|
357
|
+
const sr = await scorer({
|
|
358
|
+
input,
|
|
359
|
+
output: result.output,
|
|
360
|
+
expected: input.expected
|
|
361
|
+
});
|
|
362
|
+
scores[sName] = {
|
|
363
|
+
score: clampScore(sr.score, sName),
|
|
364
|
+
reason: sr.reason
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
trialResults.push({ result, scores });
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const lastSuccessful = [...trialResults].reverse().find((t) => !t.result.error);
|
|
371
|
+
const baseResult = lastSuccessful?.result ?? trialResults[trialResults.length - 1].result;
|
|
372
|
+
finalResult = {
|
|
373
|
+
output: baseResult.output,
|
|
374
|
+
latencyMs: Math.round(
|
|
375
|
+
trialResults.reduce((sum, t) => sum + t.result.latencyMs, 0) / trials
|
|
376
|
+
),
|
|
377
|
+
tokensIn: Math.round(
|
|
378
|
+
trialResults.reduce((sum, t) => sum + t.result.tokensIn, 0) / trials
|
|
379
|
+
),
|
|
380
|
+
tokensOut: Math.round(
|
|
381
|
+
trialResults.reduce((sum, t) => sum + t.result.tokensOut, 0) / trials
|
|
382
|
+
),
|
|
383
|
+
error: lastSuccessful ? void 0 : baseResult.error
|
|
384
|
+
};
|
|
385
|
+
finalScores = {};
|
|
386
|
+
for (const sName of scorerNames) {
|
|
387
|
+
const meanScore = trialResults.reduce((sum, t) => sum + t.scores[sName].score, 0) / trials;
|
|
388
|
+
finalScores[sName] = {
|
|
389
|
+
score: meanScore,
|
|
390
|
+
reason: trialResults[trialResults.length - 1].scores[sName]?.reason
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
} else {
|
|
394
|
+
finalResult = await wrapTask(task, input, timeout);
|
|
395
|
+
if (finalResult.error) {
|
|
396
|
+
finalScores = failureScores(scorerNames, finalResult.error);
|
|
397
|
+
} else {
|
|
398
|
+
finalScores = {};
|
|
399
|
+
for (const [sName, scorer] of Object.entries(scorers)) {
|
|
400
|
+
const sr = await scorer({
|
|
401
|
+
input,
|
|
402
|
+
output: finalResult.output,
|
|
403
|
+
expected: input.expected
|
|
404
|
+
});
|
|
405
|
+
finalScores[sName] = {
|
|
406
|
+
score: clampScore(sr.score, sName),
|
|
407
|
+
reason: sr.reason
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
const caseId = crypto.randomUUID();
|
|
413
|
+
const caseData = {
|
|
414
|
+
id: caseId,
|
|
415
|
+
run_id: runId,
|
|
416
|
+
idx: index,
|
|
417
|
+
input,
|
|
418
|
+
output: finalResult.output || null,
|
|
419
|
+
expected: input.expected,
|
|
420
|
+
latency_ms: finalResult.latencyMs,
|
|
421
|
+
tokens_in: finalResult.tokensIn,
|
|
422
|
+
tokens_out: finalResult.tokensOut,
|
|
423
|
+
error: finalResult.error ? serializeError(finalResult.error) : void 0
|
|
424
|
+
};
|
|
425
|
+
store.saveCases([caseData]);
|
|
426
|
+
const scoreDataList = scorerNames.map((sName) => ({
|
|
427
|
+
id: crypto.randomUUID(),
|
|
428
|
+
case_id: caseId,
|
|
429
|
+
scorer_name: sName,
|
|
430
|
+
score: finalScores[sName].score,
|
|
431
|
+
reason: finalScores[sName].reason
|
|
432
|
+
}));
|
|
433
|
+
store.saveScores(scoreDataList);
|
|
434
|
+
allCaseScores.push({
|
|
435
|
+
index,
|
|
436
|
+
scores: Object.fromEntries(
|
|
437
|
+
scorerNames.map((sName) => [sName, finalScores[sName].score])
|
|
438
|
+
),
|
|
439
|
+
latencyMs: finalResult.latencyMs,
|
|
440
|
+
tokensIn: finalResult.tokensIn,
|
|
441
|
+
tokensOut: finalResult.tokensOut
|
|
442
|
+
});
|
|
443
|
+
if (finalResult.error) {
|
|
444
|
+
emitter.emit("case:error", {
|
|
445
|
+
runId,
|
|
446
|
+
index,
|
|
447
|
+
error: errorMessage(finalResult.error)
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
emitter.emit("case:scored", {
|
|
451
|
+
runId,
|
|
452
|
+
index,
|
|
453
|
+
input,
|
|
454
|
+
output: finalResult.output,
|
|
455
|
+
expected: input.expected,
|
|
456
|
+
scores: finalScores,
|
|
457
|
+
error: finalResult.error,
|
|
458
|
+
latencyMs: finalResult.latencyMs,
|
|
459
|
+
tokensIn: finalResult.tokensIn,
|
|
460
|
+
tokensOut: finalResult.tokensOut
|
|
461
|
+
});
|
|
462
|
+
} finally {
|
|
463
|
+
semaphore.release();
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
const batches = batchSize ? Array.from(
|
|
467
|
+
{ length: Math.ceil(items.length / batchSize) },
|
|
468
|
+
(_, i) => items.slice(i * batchSize, (i + 1) * batchSize)
|
|
469
|
+
) : [items];
|
|
470
|
+
try {
|
|
471
|
+
for (const batch of batches) {
|
|
472
|
+
await Promise.all(batch.map(processItem));
|
|
473
|
+
}
|
|
474
|
+
} catch (err) {
|
|
475
|
+
store.finishRun(runId, "failed");
|
|
476
|
+
throw err;
|
|
477
|
+
}
|
|
478
|
+
const summary = computeSummary(allCaseScores, scorerNames, threshold);
|
|
479
|
+
store.finishRun(runId, "completed", summary);
|
|
480
|
+
emitter.emit("run:end", { runId, summary });
|
|
481
|
+
return summary;
|
|
482
|
+
}
|
|
483
|
+
function computeSummary(cases, scorerNames, threshold) {
|
|
484
|
+
const totalCases = cases.length;
|
|
485
|
+
let passCount = 0;
|
|
486
|
+
let failCount = 0;
|
|
487
|
+
let totalLatencyMs = 0;
|
|
488
|
+
let totalTokensIn = 0;
|
|
489
|
+
let totalTokensOut = 0;
|
|
490
|
+
const scoreSums = {};
|
|
491
|
+
for (const name of scorerNames) {
|
|
492
|
+
scoreSums[name] = 0;
|
|
493
|
+
}
|
|
494
|
+
for (const c of cases) {
|
|
495
|
+
totalLatencyMs += c.latencyMs;
|
|
496
|
+
totalTokensIn += c.tokensIn;
|
|
497
|
+
totalTokensOut += c.tokensOut;
|
|
498
|
+
let allPass = true;
|
|
499
|
+
for (const name of scorerNames) {
|
|
500
|
+
const score = c.scores[name] ?? 0;
|
|
501
|
+
scoreSums[name] += score;
|
|
502
|
+
if (score < threshold) allPass = false;
|
|
503
|
+
}
|
|
504
|
+
if (allPass) passCount++;
|
|
505
|
+
else failCount++;
|
|
506
|
+
}
|
|
507
|
+
const meanScores = {};
|
|
508
|
+
for (const name of scorerNames) {
|
|
509
|
+
meanScores[name] = totalCases > 0 ? scoreSums[name] / totalCases : 0;
|
|
510
|
+
}
|
|
511
|
+
return {
|
|
512
|
+
totalCases,
|
|
513
|
+
passCount,
|
|
514
|
+
failCount,
|
|
515
|
+
meanScores,
|
|
516
|
+
totalLatencyMs,
|
|
517
|
+
totalTokensIn,
|
|
518
|
+
totalTokensOut
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// packages/evals/src/store/index.ts
|
|
523
|
+
import { mkdirSync } from "node:fs";
|
|
524
|
+
import { dirname } from "node:path";
|
|
525
|
+
import { DatabaseSync } from "node:sqlite";
|
|
526
|
+
|
|
527
|
+
// packages/evals/src/store/ddl.sqlite.sql
|
|
528
|
+
var ddl_sqlite_default = "PRAGMA journal_mode = WAL;\nPRAGMA synchronous = NORMAL;\nPRAGMA foreign_keys = ON;\n\nCREATE TABLE IF NOT EXISTS suites (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)\n);\n\nCREATE TABLE IF NOT EXISTS runs (\n id TEXT PRIMARY KEY,\n suite_id TEXT NOT NULL,\n name TEXT NOT NULL,\n model TEXT NOT NULL,\n config TEXT,\n started_at INTEGER NOT NULL,\n finished_at INTEGER,\n status TEXT NOT NULL DEFAULT 'running' CHECK(status IN ('running', 'completed', 'failed')),\n summary TEXT,\n FOREIGN KEY (suite_id) REFERENCES suites(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_runs_suite_id ON runs(suite_id);\nCREATE INDEX IF NOT EXISTS idx_runs_started_at ON runs(started_at);\n\nCREATE TABLE IF NOT EXISTS cases (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n idx INTEGER NOT NULL,\n input TEXT NOT NULL,\n output TEXT,\n expected TEXT,\n latency_ms INTEGER,\n tokens_in INTEGER,\n tokens_out INTEGER,\n error TEXT,\n FOREIGN KEY (run_id) REFERENCES runs(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_cases_run_id ON cases(run_id);\n\nCREATE TABLE IF NOT EXISTS scores (\n id TEXT PRIMARY KEY,\n case_id TEXT NOT NULL,\n scorer_name TEXT NOT NULL,\n score REAL NOT NULL,\n reason TEXT,\n FOREIGN KEY (case_id) REFERENCES cases(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_scores_case_id ON scores(case_id);\n\nCREATE TABLE IF NOT EXISTS prompts (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL UNIQUE,\n content TEXT NOT NULL,\n created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)\n);\n\nCREATE INDEX IF NOT EXISTS idx_prompts_created_at ON prompts(created_at);\n";
|
|
529
|
+
|
|
530
|
+
// packages/evals/src/store/index.ts
|
|
531
|
+
var RunStore = class {
|
|
532
|
+
#db;
|
|
533
|
+
#statements = /* @__PURE__ */ new Map();
|
|
534
|
+
#stmt(sql) {
|
|
535
|
+
let stmt = this.#statements.get(sql);
|
|
536
|
+
if (!stmt) {
|
|
537
|
+
stmt = this.#db.prepare(sql);
|
|
538
|
+
this.#statements.set(sql, stmt);
|
|
539
|
+
}
|
|
540
|
+
return stmt;
|
|
541
|
+
}
|
|
542
|
+
#transaction(fn) {
|
|
543
|
+
this.#db.exec("BEGIN TRANSACTION");
|
|
544
|
+
try {
|
|
545
|
+
const result = fn();
|
|
546
|
+
this.#db.exec("COMMIT");
|
|
547
|
+
return result;
|
|
548
|
+
} catch (error) {
|
|
549
|
+
this.#db.exec("ROLLBACK");
|
|
550
|
+
throw error;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
constructor(pathOrDb) {
|
|
554
|
+
if (pathOrDb instanceof DatabaseSync) {
|
|
555
|
+
this.#db = pathOrDb;
|
|
556
|
+
} else {
|
|
557
|
+
const dbPath = pathOrDb ?? ".evals/store.db";
|
|
558
|
+
mkdirSync(dirname(dbPath), { recursive: true });
|
|
559
|
+
this.#db = new DatabaseSync(dbPath);
|
|
560
|
+
}
|
|
561
|
+
this.#db.exec(ddl_sqlite_default);
|
|
562
|
+
this.#migrateRunsTableToSuiteRequired();
|
|
563
|
+
this.#migratePromptsTableIfNeeded();
|
|
564
|
+
this.#db.exec(
|
|
565
|
+
"CREATE INDEX IF NOT EXISTS idx_prompts_name_version ON prompts(name, version DESC)"
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
#migratePromptsTableIfNeeded() {
|
|
569
|
+
const columns = this.#stmt("PRAGMA table_info(prompts)").all();
|
|
570
|
+
if (columns.length === 0) return;
|
|
571
|
+
if (columns.some((column) => column.name === "version")) return;
|
|
572
|
+
this.#transaction(() => {
|
|
573
|
+
this.#db.exec("ALTER TABLE prompts RENAME TO prompts_legacy");
|
|
574
|
+
this.#db.exec(`
|
|
575
|
+
CREATE TABLE prompts (
|
|
576
|
+
id TEXT PRIMARY KEY,
|
|
577
|
+
name TEXT NOT NULL,
|
|
578
|
+
version INTEGER NOT NULL,
|
|
579
|
+
content TEXT NOT NULL,
|
|
580
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
|
|
581
|
+
UNIQUE(name, version)
|
|
582
|
+
)
|
|
583
|
+
`);
|
|
584
|
+
this.#db.exec(`
|
|
585
|
+
INSERT INTO prompts (id, name, version, content, created_at)
|
|
586
|
+
SELECT id, name, 1, content, created_at
|
|
587
|
+
FROM prompts_legacy
|
|
588
|
+
`);
|
|
589
|
+
this.#db.exec("DROP TABLE prompts_legacy");
|
|
590
|
+
this.#db.exec(
|
|
591
|
+
"CREATE INDEX IF NOT EXISTS idx_prompts_created_at ON prompts(created_at)"
|
|
592
|
+
);
|
|
593
|
+
this.#db.exec(
|
|
594
|
+
"CREATE INDEX IF NOT EXISTS idx_prompts_name_version ON prompts(name, version DESC)"
|
|
595
|
+
);
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
#migrateRunsTableToSuiteRequired() {
|
|
599
|
+
const runColumns = this.#stmt("PRAGMA table_info(runs)").all();
|
|
600
|
+
if (runColumns.length === 0) return;
|
|
601
|
+
const suiteColumn = runColumns.find((column) => column.name === "suite_id");
|
|
602
|
+
const hasNonNullSuite = suiteColumn?.notnull === 1;
|
|
603
|
+
const runForeignKeys = this.#stmt(
|
|
604
|
+
"PRAGMA foreign_key_list(runs)"
|
|
605
|
+
).all();
|
|
606
|
+
const suiteForeignKey = runForeignKeys.find(
|
|
607
|
+
(fk) => fk.from === "suite_id" && fk.table === "suites"
|
|
608
|
+
);
|
|
609
|
+
const hasCascadeDelete = suiteForeignKey?.on_delete === "CASCADE";
|
|
610
|
+
if (hasNonNullSuite && hasCascadeDelete) return;
|
|
611
|
+
this.#statements.clear();
|
|
612
|
+
this.#transaction(() => {
|
|
613
|
+
this.#db.exec(`
|
|
614
|
+
CREATE TABLE runs_next (
|
|
615
|
+
id TEXT PRIMARY KEY,
|
|
616
|
+
suite_id TEXT NOT NULL,
|
|
617
|
+
name TEXT NOT NULL,
|
|
618
|
+
model TEXT NOT NULL,
|
|
619
|
+
config TEXT,
|
|
620
|
+
started_at INTEGER NOT NULL,
|
|
621
|
+
finished_at INTEGER,
|
|
622
|
+
status TEXT NOT NULL DEFAULT 'running' CHECK(status IN ('running', 'completed', 'failed')),
|
|
623
|
+
summary TEXT,
|
|
624
|
+
FOREIGN KEY (suite_id) REFERENCES suites(id) ON DELETE CASCADE
|
|
625
|
+
)
|
|
626
|
+
`);
|
|
627
|
+
this.#db.exec("DELETE FROM runs WHERE suite_id IS NULL");
|
|
628
|
+
this.#db.exec(`
|
|
629
|
+
INSERT INTO runs_next (id, suite_id, name, model, config, started_at, finished_at, status, summary)
|
|
630
|
+
SELECT r.id, r.suite_id, r.name, r.model, r.config, r.started_at, r.finished_at, r.status, r.summary
|
|
631
|
+
FROM runs r
|
|
632
|
+
JOIN suites s ON s.id = r.suite_id
|
|
633
|
+
`);
|
|
634
|
+
this.#db.exec("DROP TABLE runs");
|
|
635
|
+
this.#db.exec("ALTER TABLE runs_next RENAME TO runs");
|
|
636
|
+
this.#db.exec(
|
|
637
|
+
"CREATE INDEX IF NOT EXISTS idx_runs_suite_id ON runs(suite_id)"
|
|
638
|
+
);
|
|
639
|
+
this.#db.exec(
|
|
640
|
+
"CREATE INDEX IF NOT EXISTS idx_runs_started_at ON runs(started_at)"
|
|
641
|
+
);
|
|
642
|
+
});
|
|
643
|
+
this.#statements.clear();
|
|
644
|
+
}
|
|
645
|
+
createSuite(name) {
|
|
646
|
+
const id = crypto.randomUUID();
|
|
647
|
+
const now = Date.now();
|
|
648
|
+
this.#stmt(
|
|
649
|
+
"INSERT INTO suites (id, name, created_at) VALUES (?, ?, ?)"
|
|
650
|
+
).run(id, name, now);
|
|
651
|
+
return { id, name, created_at: now };
|
|
652
|
+
}
|
|
653
|
+
createRun(run) {
|
|
654
|
+
const id = crypto.randomUUID();
|
|
655
|
+
const now = Date.now();
|
|
656
|
+
this.#stmt(
|
|
657
|
+
"INSERT INTO runs (id, suite_id, name, model, config, started_at) VALUES (?, ?, ?, ?, ?, ?)"
|
|
658
|
+
).run(
|
|
659
|
+
id,
|
|
660
|
+
run.suite_id,
|
|
661
|
+
run.name,
|
|
662
|
+
run.model,
|
|
663
|
+
run.config ? JSON.stringify(run.config) : null,
|
|
664
|
+
now
|
|
665
|
+
);
|
|
666
|
+
return id;
|
|
667
|
+
}
|
|
668
|
+
finishRun(runId, status, summary) {
|
|
669
|
+
this.#stmt(
|
|
670
|
+
"UPDATE runs SET finished_at = ?, status = ?, summary = ? WHERE id = ?"
|
|
671
|
+
).run(Date.now(), status, summary ? JSON.stringify(summary) : null, runId);
|
|
672
|
+
}
|
|
673
|
+
saveCases(cases) {
|
|
674
|
+
this.#transaction(() => {
|
|
675
|
+
const stmt = this.#stmt(
|
|
676
|
+
"INSERT INTO cases (id, run_id, idx, input, output, expected, latency_ms, tokens_in, tokens_out, error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
677
|
+
);
|
|
678
|
+
for (const c of cases) {
|
|
679
|
+
stmt.run(
|
|
680
|
+
c.id,
|
|
681
|
+
c.run_id,
|
|
682
|
+
c.idx,
|
|
683
|
+
JSON.stringify(c.input),
|
|
684
|
+
c.output,
|
|
685
|
+
c.expected != null ? JSON.stringify(c.expected) : null,
|
|
686
|
+
c.latency_ms,
|
|
687
|
+
c.tokens_in,
|
|
688
|
+
c.tokens_out,
|
|
689
|
+
c.error ?? null
|
|
690
|
+
);
|
|
691
|
+
}
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
saveScores(scores) {
|
|
695
|
+
this.#transaction(() => {
|
|
696
|
+
const stmt = this.#stmt(
|
|
697
|
+
"INSERT INTO scores (id, case_id, scorer_name, score, reason) VALUES (?, ?, ?, ?, ?)"
|
|
698
|
+
);
|
|
699
|
+
for (const s of scores) {
|
|
700
|
+
stmt.run(s.id, s.case_id, s.scorer_name, s.score, s.reason ?? null);
|
|
701
|
+
}
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
getRun(runId) {
|
|
705
|
+
const row = this.#stmt("SELECT * FROM runs WHERE id = ?").get(runId);
|
|
706
|
+
if (!row) return void 0;
|
|
707
|
+
return {
|
|
708
|
+
id: row.id,
|
|
709
|
+
suite_id: row.suite_id,
|
|
710
|
+
name: row.name,
|
|
711
|
+
model: row.model,
|
|
712
|
+
config: row.config ? JSON.parse(row.config) : null,
|
|
713
|
+
started_at: row.started_at,
|
|
714
|
+
finished_at: row.finished_at,
|
|
715
|
+
status: row.status,
|
|
716
|
+
summary: row.summary ? JSON.parse(row.summary) : null
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
listRuns(suiteId) {
|
|
720
|
+
const sql = suiteId ? "SELECT * FROM runs WHERE suite_id = ? ORDER BY started_at" : "SELECT * FROM runs ORDER BY started_at";
|
|
721
|
+
const rows = suiteId ? this.#stmt(sql).all(suiteId) : this.#stmt(sql).all();
|
|
722
|
+
return rows.map((row) => ({
|
|
723
|
+
id: row.id,
|
|
724
|
+
suite_id: row.suite_id,
|
|
725
|
+
name: row.name,
|
|
726
|
+
model: row.model,
|
|
727
|
+
config: row.config ? JSON.parse(row.config) : null,
|
|
728
|
+
started_at: row.started_at,
|
|
729
|
+
finished_at: row.finished_at,
|
|
730
|
+
status: row.status,
|
|
731
|
+
summary: row.summary ? JSON.parse(row.summary) : null
|
|
732
|
+
}));
|
|
733
|
+
}
|
|
734
|
+
getCases(runId) {
|
|
735
|
+
const rows = this.#stmt(
|
|
736
|
+
"SELECT * FROM cases WHERE run_id = ? ORDER BY idx"
|
|
737
|
+
).all(runId);
|
|
738
|
+
return rows.map((row) => ({
|
|
739
|
+
id: row.id,
|
|
740
|
+
run_id: row.run_id,
|
|
741
|
+
idx: row.idx,
|
|
742
|
+
input: JSON.parse(row.input),
|
|
743
|
+
output: row.output,
|
|
744
|
+
expected: row.expected ? JSON.parse(row.expected) : null,
|
|
745
|
+
latency_ms: row.latency_ms,
|
|
746
|
+
tokens_in: row.tokens_in,
|
|
747
|
+
tokens_out: row.tokens_out,
|
|
748
|
+
error: row.error
|
|
749
|
+
}));
|
|
750
|
+
}
|
|
751
|
+
getFailingCases(runId, threshold = 0.5) {
|
|
752
|
+
const rows = this.#stmt(
|
|
753
|
+
`SELECT c.*, s.scorer_name, s.score, s.reason as score_reason
|
|
754
|
+
FROM cases c
|
|
755
|
+
JOIN scores s ON s.case_id = c.id
|
|
756
|
+
WHERE c.run_id = ? AND s.score < ?
|
|
757
|
+
ORDER BY c.idx`
|
|
758
|
+
).all(runId, threshold);
|
|
759
|
+
const caseMap = /* @__PURE__ */ new Map();
|
|
760
|
+
for (const row of rows) {
|
|
761
|
+
let c = caseMap.get(row.id);
|
|
762
|
+
if (!c) {
|
|
763
|
+
c = {
|
|
764
|
+
id: row.id,
|
|
765
|
+
run_id: row.run_id,
|
|
766
|
+
idx: row.idx,
|
|
767
|
+
input: JSON.parse(row.input),
|
|
768
|
+
output: row.output,
|
|
769
|
+
expected: row.expected ? JSON.parse(row.expected) : null,
|
|
770
|
+
latency_ms: row.latency_ms,
|
|
771
|
+
tokens_in: row.tokens_in,
|
|
772
|
+
tokens_out: row.tokens_out,
|
|
773
|
+
error: row.error,
|
|
774
|
+
scores: []
|
|
775
|
+
};
|
|
776
|
+
caseMap.set(row.id, c);
|
|
777
|
+
}
|
|
778
|
+
c.scores.push({
|
|
779
|
+
scorer_name: row.scorer_name,
|
|
780
|
+
score: row.score,
|
|
781
|
+
reason: row.score_reason
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
return Array.from(caseMap.values());
|
|
785
|
+
}
|
|
786
|
+
getRunSummary(runId, threshold = 0.5) {
|
|
787
|
+
const totals = this.#stmt(
|
|
788
|
+
`SELECT
|
|
789
|
+
COUNT(DISTINCT c.id) as totalCases,
|
|
790
|
+
COALESCE(SUM(c.latency_ms), 0) as totalLatencyMs,
|
|
791
|
+
COALESCE(SUM(c.tokens_in), 0) as totalTokensIn,
|
|
792
|
+
COALESCE(SUM(c.tokens_out), 0) as totalTokensOut
|
|
793
|
+
FROM cases c WHERE c.run_id = ?`
|
|
794
|
+
).get(runId);
|
|
795
|
+
const scorerMeans = this.#stmt(
|
|
796
|
+
`SELECT s.scorer_name, AVG(s.score) as meanScore
|
|
797
|
+
FROM scores s
|
|
798
|
+
JOIN cases c ON c.id = s.case_id
|
|
799
|
+
WHERE c.run_id = ?
|
|
800
|
+
GROUP BY s.scorer_name`
|
|
801
|
+
).all(runId);
|
|
802
|
+
const meanScores = {};
|
|
803
|
+
for (const row of scorerMeans) {
|
|
804
|
+
meanScores[row.scorer_name] = row.meanScore;
|
|
805
|
+
}
|
|
806
|
+
const passFail = this.#stmt(
|
|
807
|
+
`SELECT c.id,
|
|
808
|
+
MIN(s.score) as minScore
|
|
809
|
+
FROM cases c
|
|
810
|
+
JOIN scores s ON s.case_id = c.id
|
|
811
|
+
WHERE c.run_id = ?
|
|
812
|
+
GROUP BY c.id`
|
|
813
|
+
).all(runId);
|
|
814
|
+
let passCount = 0;
|
|
815
|
+
let failCount = 0;
|
|
816
|
+
for (const row of passFail) {
|
|
817
|
+
if (row.minScore >= threshold) passCount++;
|
|
818
|
+
else failCount++;
|
|
819
|
+
}
|
|
820
|
+
return {
|
|
821
|
+
totalCases: totals.totalCases,
|
|
822
|
+
passCount,
|
|
823
|
+
failCount,
|
|
824
|
+
meanScores,
|
|
825
|
+
totalLatencyMs: totals.totalLatencyMs,
|
|
826
|
+
totalTokensIn: totals.totalTokensIn,
|
|
827
|
+
totalTokensOut: totals.totalTokensOut
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
listSuites() {
|
|
831
|
+
const rows = this.#stmt(
|
|
832
|
+
"SELECT * FROM suites ORDER BY created_at DESC"
|
|
833
|
+
).all();
|
|
834
|
+
return rows.map((row) => ({
|
|
835
|
+
id: row.id,
|
|
836
|
+
name: row.name,
|
|
837
|
+
created_at: row.created_at
|
|
838
|
+
}));
|
|
839
|
+
}
|
|
840
|
+
createPrompt(name, content) {
|
|
841
|
+
const id = crypto.randomUUID();
|
|
842
|
+
const now = Date.now();
|
|
843
|
+
const latest = this.#stmt(
|
|
844
|
+
"SELECT MAX(version) as latestVersion FROM prompts WHERE name = ?"
|
|
845
|
+
).get(name);
|
|
846
|
+
const version = (latest?.latestVersion ?? 0) + 1;
|
|
847
|
+
this.#stmt(
|
|
848
|
+
"INSERT INTO prompts (id, name, version, content, created_at) VALUES (?, ?, ?, ?, ?)"
|
|
849
|
+
).run(id, name, version, content, now);
|
|
850
|
+
return { id, name, version, content, created_at: now };
|
|
851
|
+
}
|
|
852
|
+
listPrompts() {
|
|
853
|
+
const rows = this.#stmt(
|
|
854
|
+
"SELECT * FROM prompts ORDER BY name COLLATE NOCASE ASC, version DESC"
|
|
855
|
+
).all();
|
|
856
|
+
return rows.map((row) => ({
|
|
857
|
+
id: row.id,
|
|
858
|
+
name: row.name,
|
|
859
|
+
version: row.version,
|
|
860
|
+
content: row.content,
|
|
861
|
+
created_at: row.created_at
|
|
862
|
+
}));
|
|
863
|
+
}
|
|
864
|
+
getPrompt(id) {
|
|
865
|
+
const row = this.#stmt("SELECT * FROM prompts WHERE id = ?").get(id);
|
|
866
|
+
if (!row) return void 0;
|
|
867
|
+
return {
|
|
868
|
+
id: row.id,
|
|
869
|
+
name: row.name,
|
|
870
|
+
version: row.version,
|
|
871
|
+
content: row.content,
|
|
872
|
+
created_at: row.created_at
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
deletePrompt(id) {
|
|
876
|
+
this.#stmt("DELETE FROM prompts WHERE id = ?").run(id);
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
|
|
880
|
+
// packages/evals/src/evaluate/index.ts
|
|
881
|
+
async function evaluate(options) {
|
|
882
|
+
if ("models" in options) {
|
|
883
|
+
return evaluateEach(options);
|
|
884
|
+
}
|
|
885
|
+
return evaluateSingle(options);
|
|
886
|
+
}
|
|
887
|
+
function resolveStore(store) {
|
|
888
|
+
return store instanceof RunStore ? store : new RunStore(store);
|
|
889
|
+
}
|
|
890
|
+
function wireReporters(reporters) {
|
|
891
|
+
const emitter = new EvalEmitter();
|
|
892
|
+
const cases = [];
|
|
893
|
+
let runId = "";
|
|
894
|
+
emitter.on("run:start", (data) => {
|
|
895
|
+
runId = data.runId;
|
|
896
|
+
for (const r of reporters) r.onRunStart?.(data);
|
|
897
|
+
});
|
|
898
|
+
emitter.on("case:scored", (data) => {
|
|
899
|
+
const result = {
|
|
900
|
+
runId: data.runId,
|
|
901
|
+
index: data.index,
|
|
902
|
+
input: data.input,
|
|
903
|
+
output: data.output,
|
|
904
|
+
expected: data.expected,
|
|
905
|
+
scores: data.scores,
|
|
906
|
+
error: data.error ?? null,
|
|
907
|
+
latencyMs: data.latencyMs,
|
|
908
|
+
tokensIn: data.tokensIn,
|
|
909
|
+
tokensOut: data.tokensOut
|
|
910
|
+
};
|
|
911
|
+
cases.push(result);
|
|
912
|
+
for (const r of reporters) r.onCaseEnd?.(result);
|
|
913
|
+
});
|
|
914
|
+
return { emitter, cases, getRunId: () => runId };
|
|
915
|
+
}
|
|
916
|
+
async function notifyRunEnd(reporters, data) {
|
|
917
|
+
data.cases.sort((a, b) => a.index - b.index);
|
|
918
|
+
await Promise.all(reporters.map((r) => r.onRunEnd?.(data)));
|
|
919
|
+
}
|
|
920
|
+
async function evaluateSingle(options) {
|
|
921
|
+
const store = resolveStore(options.store);
|
|
922
|
+
const threshold = options.threshold ?? 0.5;
|
|
923
|
+
const { emitter, cases, getRunId } = wireReporters(options.reporters);
|
|
924
|
+
const summary = await runEval({
|
|
925
|
+
name: options.name,
|
|
926
|
+
model: options.model,
|
|
927
|
+
dataset: options.dataset,
|
|
928
|
+
task: options.task,
|
|
929
|
+
scorers: options.scorers,
|
|
930
|
+
store,
|
|
931
|
+
emitter,
|
|
932
|
+
suiteId: options.suiteId,
|
|
933
|
+
maxConcurrency: options.maxConcurrency,
|
|
934
|
+
timeout: options.timeout,
|
|
935
|
+
trials: options.trials,
|
|
936
|
+
threshold: options.threshold
|
|
937
|
+
});
|
|
938
|
+
await notifyRunEnd(options.reporters, {
|
|
939
|
+
runId: getRunId(),
|
|
940
|
+
name: options.name,
|
|
941
|
+
model: options.model,
|
|
942
|
+
summary,
|
|
943
|
+
cases,
|
|
944
|
+
threshold
|
|
945
|
+
});
|
|
946
|
+
return summary;
|
|
947
|
+
}
|
|
948
|
+
async function evaluateEach(options) {
|
|
949
|
+
const store = resolveStore(options.store);
|
|
950
|
+
const items = [];
|
|
951
|
+
for await (const item of options.dataset) {
|
|
952
|
+
items.push(item);
|
|
953
|
+
}
|
|
954
|
+
const suite = store.createSuite(options.name);
|
|
955
|
+
return Promise.all(
|
|
956
|
+
options.models.map(
|
|
957
|
+
(variant) => evaluateSingle({
|
|
958
|
+
name: `${options.name} [${variant.name}]`,
|
|
959
|
+
model: variant.name,
|
|
960
|
+
dataset: dataset(items),
|
|
961
|
+
task: (input) => options.task(input, variant),
|
|
962
|
+
scorers: options.scorers,
|
|
963
|
+
reporters: options.reporters,
|
|
964
|
+
store,
|
|
965
|
+
suiteId: suite.id,
|
|
966
|
+
maxConcurrency: options.maxConcurrency,
|
|
967
|
+
timeout: options.timeout,
|
|
968
|
+
trials: options.trials,
|
|
969
|
+
threshold: options.threshold
|
|
970
|
+
})
|
|
971
|
+
)
|
|
972
|
+
);
|
|
973
|
+
}
|
|
974
|
+
export {
|
|
975
|
+
evaluate
|
|
976
|
+
};
|
|
977
|
+
//# sourceMappingURL=index.js.map
|