-
Notifications
You must be signed in to change notification settings - Fork 893
Expand file tree
/
Copy pathindex.ts
More file actions
363 lines (327 loc) · 11.4 KB
/
index.ts
File metadata and controls
363 lines (327 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*
Copyright 2025 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { componentGeneratorFlow, ai } from "./flows";
import * as fs from "fs";
import * as path from "path";
import { modelsToTest } from "./models";
import { prompts, TestPrompt } from "./prompts";
import { validateSchema } from "./validator";
interface InferenceResult {
modelName: string;
prompt: TestPrompt;
component: any;
error: any;
latency: number;
validationResults: string[];
runNumber: number;
}
function generateSummary(
resultsByModel: Record<string, InferenceResult[]>,
results: InferenceResult[],
): string {
const promptNameWidth = 40;
const latencyWidth = 20;
const failedRunsWidth = 15;
const toolErrorRunsWidth = 20;
let summary = "# Evaluation Summary";
for (const modelName in resultsByModel) {
summary += `\n\n## Model: ${modelName}\n\n`;
const header = `| ${"Prompt Name".padEnd(
promptNameWidth,
)} | ${"Avg Latency (ms)".padEnd(latencyWidth)} | ${"Failed Runs".padEnd(
failedRunsWidth,
)} | ${"Tool Error Runs".padEnd(toolErrorRunsWidth)} |`;
const divider = `|${"-".repeat(promptNameWidth + 2)}|${"-".repeat(
latencyWidth + 2,
)}|${"-".repeat(failedRunsWidth + 2)}|${"-".repeat(
toolErrorRunsWidth + 2,
)}|`;
summary += header;
summary += `\n${divider}`;
const promptsInModel = resultsByModel[modelName].reduce(
(acc, result) => {
if (!acc[result.prompt.name]) {
acc[result.prompt.name] = [];
}
acc[result.prompt.name].push(result);
return acc;
},
{} as Record<string, InferenceResult[]>,
);
let totalModelFailedRuns = 0;
for (const promptName in promptsInModel) {
const runs = promptsInModel[promptName];
const totalRuns = runs.length;
const errorRuns = runs.filter((r) => r.error).length;
const failedRuns = runs.filter(
(r) => r.error || r.validationResults.length > 0,
).length;
const totalLatency = runs.reduce((acc, r) => acc + r.latency, 0);
const avgLatency = (totalLatency / totalRuns).toFixed(0);
totalModelFailedRuns += failedRuns;
const failedRunsStr =
failedRuns > 0 ? `${failedRuns} / ${totalRuns}` : "";
const errorRunsStr = errorRuns > 0 ? `${errorRuns} / ${totalRuns}` : "";
summary += `\n| ${promptName.padEnd(
promptNameWidth,
)} | ${avgLatency.padEnd(latencyWidth)} | ${failedRunsStr.padEnd(
failedRunsWidth,
)} | ${errorRunsStr.padEnd(toolErrorRunsWidth)} |`;
}
const totalRunsForModel = resultsByModel[modelName].length;
summary += `\n\n**Total failed runs:** ${totalModelFailedRuns} / ${totalRunsForModel}`;
}
summary += "\n\n---\n\n## Overall Summary\n";
const totalRuns = results.length;
const totalToolErrorRuns = results.filter((r) => r.error).length;
const totalRunsWithAnyFailure = results.filter(
(r) => r.error || r.validationResults.length > 0,
).length;
const modelsWithFailures = [
...new Set(
results
.filter((r) => r.error || r.validationResults.length > 0)
.map((r) => r.modelName),
),
].join(", ");
summary += `\n- **Number of tool error runs:** ${totalToolErrorRuns} / ${totalRuns}`;
summary += `\n- **Number of runs with any failure (tool error or validation):** ${totalRunsWithAnyFailure} / ${totalRuns}`;
const latencies = results.map((r) => r.latency).sort((a, b) => a - b);
const totalLatency = latencies.reduce((acc, l) => acc + l, 0);
const meanLatency = (totalLatency / totalRuns).toFixed(0);
let medianLatency = 0;
if (latencies.length > 0) {
const mid = Math.floor(latencies.length / 2);
if (latencies.length % 2 === 0) {
medianLatency = (latencies[mid - 1] + latencies[mid]) / 2;
} else {
medianLatency = latencies[mid];
}
}
summary += `\n- **Mean Latency:** ${meanLatency} ms`;
summary += `\n- **Median Latency:** ${medianLatency} ms`;
if (modelsWithFailures) {
summary += `\n- **Models with at least one failure:** ${modelsWithFailures}`;
}
return summary;
}
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
// Run the flow
async function main() {
const argv = await yargs(hideBin(process.argv))
.option("verbose", {
alias: "v",
type: "boolean",
description: "Run with verbose logging",
default: false,
})
.option("keep", {
type: "string",
description:
"Directory to keep output files. If no path is provided, a temporary directory will be created.",
coerce: (arg) => (arg === undefined ? true : arg),
})
.option("runs-per-prompt", {
type: "number",
description: "Number of times to run each prompt",
default: 1,
})
.option("model", {
type: "string",
array: true,
description: "Filter models by exact name",
default: [],
choices: modelsToTest.map((m) => m.name),
})
.option("prompt", {
type: "string",
description: "Filter prompts by name prefix",
})
.help()
.alias("h", "help").argv;
const verbose = argv.verbose;
const keep = argv.keep;
let outputDir: string | null = null;
if (keep) {
if (typeof keep === "string") {
outputDir = keep;
} else {
outputDir = fs.mkdtempSync(path.join(process.cwd(), "a2ui-eval-"));
}
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
console.log(`Keeping output in: ${outputDir}`);
}
const runsPerPrompt = argv["runs-per-prompt"];
let filteredModels = modelsToTest;
if (argv.model && argv.model.length > 0) {
const modelNames = argv.model as string[];
filteredModels = modelsToTest.filter((m) => modelNames.includes(m.name));
if (filteredModels.length === 0) {
console.error(`No models found matching: ${modelNames.join(", ")}.`);
process.exit(1);
}
}
let filteredPrompts = prompts;
if (argv.prompt) {
filteredPrompts = prompts.filter((p) =>
p.name.startsWith(argv.prompt as string)
);
if (filteredPrompts.length === 0) {
console.error(`No prompt found with prefix "${argv.prompt}".`);
process.exit(1);
}
}
const generationPromises: Promise<InferenceResult>[] = [];
for (const prompt of filteredPrompts) {
const schemaString = fs.readFileSync(
path.join(__dirname, prompt.schemaPath),
"utf-8"
);
const schema = JSON.parse(schemaString);
for (const modelConfig of filteredModels) {
const modelDirName = modelConfig.name.replace(/[\/:]/g, "_");
const modelOutputDir = outputDir
? path.join(outputDir, modelDirName)
: null;
if (modelOutputDir && !fs.existsSync(modelOutputDir)) {
fs.mkdirSync(modelOutputDir, { recursive: true });
}
for (let i = 1; i <= runsPerPrompt; i++) {
console.log(
`Queueing generation for model: ${modelConfig.name}, prompt: ${prompt.name} (run ${i})`
);
const startTime = Date.now();
generationPromises.push(
componentGeneratorFlow({
prompt: prompt.promptText,
model: modelConfig.model,
config: modelConfig.config,
schema,
})
.then((component) => {
if (modelOutputDir) {
const inputPath = path.join(
modelOutputDir,
`${prompt.name}.input.txt`
);
fs.writeFileSync(inputPath, prompt.promptText);
const outputPath = path.join(
modelOutputDir,
`${prompt.name}.output.json`
);
fs.writeFileSync(
outputPath,
JSON.stringify(component, null, 2)
);
}
const validationResults = validateSchema(
component,
prompt.schemaPath,
prompt.matchers
);
return {
modelName: modelConfig.name,
prompt,
component,
error: null,
latency: Date.now() - startTime,
validationResults,
runNumber: i,
};
})
.catch((error) => {
if (modelOutputDir) {
const inputPath = path.join(
modelOutputDir,
`${prompt.name}.input.txt`
);
fs.writeFileSync(inputPath, prompt.promptText);
const errorPath = path.join(
modelOutputDir,
`${prompt.name}.error.json`
);
const errorOutput = {
message: error.message,
stack: error.stack,
...error,
};
fs.writeFileSync(
errorPath,
JSON.stringify(errorOutput, null, 2)
);
}
return {
modelName: modelConfig.name,
prompt,
component: null,
error,
latency: Date.now() - startTime,
validationResults: [],
runNumber: i,
};
})
);
}
}
}
const results = await Promise.all(generationPromises);
const resultsByModel: Record<string, InferenceResult[]> = {};
for (const result of results) {
if (!resultsByModel[result.modelName]) {
resultsByModel[result.modelName] = [];
}
resultsByModel[result.modelName].push(result);
}
console.log("\n--- Generation Results ---");
for (const modelName in resultsByModel) {
for (const result of resultsByModel[modelName]) {
const hasError = !!result.error;
const hasValidationFailures = result.validationResults.length > 0;
const hasComponent = !!result.component;
if (hasError || hasValidationFailures || (verbose && hasComponent)) {
console.log(`\n----------------------------------------`);
console.log(`Model: ${modelName}`);
console.log(`----------------------------------------`);
console.log(`\nQuery: ${result.prompt.name} (run ${result.runNumber})`);
if (hasError) {
console.error("Error generating component:", result.error);
} else if (hasComponent) {
if (hasValidationFailures) {
console.log("Validation Failures:");
result.validationResults.forEach((failure) =>
console.log(`- ${failure}`)
);
}
if (verbose) {
if (hasValidationFailures) {
console.log("Generated schema:");
console.log(JSON.stringify(result.component, null, 2));
}
}
}
}
}
}
const summary = generateSummary(resultsByModel, results);
console.log(summary);
if (outputDir) {
const summaryPath = path.join(outputDir, "summary.md");
fs.writeFileSync(summaryPath, summary);
}
}
if (require.main === module) {
main().catch(console.error);
}