@ai-sdk-tool/eval 0.1.1

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.js ADDED
@@ -0,0 +1,834 @@
1
+ // src/reporters/console.ts
2
+ var colors = {
3
+ reset: "\x1B[0m",
4
+ green: "\x1B[32m",
5
+ red: "\x1B[31m",
6
+ yellow: "\x1B[33m",
7
+ cyan: "\x1B[36m",
8
+ magenta: "\x1B[35m"
9
+ };
10
+ function printResult(result) {
11
+ const { model, benchmark, result: benchmarkResult } = result;
12
+ const status = benchmarkResult.success ? `${colors.green}\u2714 SUCCESS${colors.reset}` : `${colors.red}\u2716 FAILURE${colors.reset}`;
13
+ console.log(
14
+ `
15
+ ${colors.cyan}[${model}]${colors.reset} - ${colors.magenta}${benchmark}${colors.reset}`
16
+ );
17
+ console.log(
18
+ ` \u2514 ${status} | Score: ${colors.yellow}${benchmarkResult.score.toFixed(2)}${colors.reset}`
19
+ );
20
+ const metrics = Object.entries(benchmarkResult.metrics);
21
+ if (metrics.length > 0) {
22
+ console.log(" Metrics:");
23
+ for (const [key, value] of metrics) {
24
+ console.log(` - ${key}: ${value}`);
25
+ }
26
+ }
27
+ if (benchmarkResult.error) {
28
+ console.log(
29
+ ` ${colors.red}Error: ${benchmarkResult.error.message}${colors.reset}`
30
+ );
31
+ }
32
+ }
33
+ function consoleReporter(results) {
34
+ console.log("\n--- \u{1F4CA} Evaluation Report ---");
35
+ for (const result of results) {
36
+ printResult(result);
37
+ }
38
+ console.log("\n---------------------------\n");
39
+ }
40
+
41
+ // src/reporters/json.ts
42
+ function jsonReporter(results) {
43
+ const serializableResults = results.map((r) => ({
44
+ ...r,
45
+ result: {
46
+ ...r.result,
47
+ error: r.result.error?.message
48
+ }
49
+ }));
50
+ console.log(JSON.stringify(serializableResults, null, 2));
51
+ }
52
+
53
+ // src/reporters/index.ts
54
+ var reporters = {
55
+ console: consoleReporter,
56
+ json: jsonReporter
57
+ };
58
+
59
+ // src/evaluate.ts
60
+ async function runSingleBenchmark(model, benchmark) {
61
+ const modelId = typeof model === "object" && model !== null && "modelId" in model && typeof model.modelId === "string" ? model.modelId : "unknown-model";
62
+ try {
63
+ console.log(`[${modelId}] Running benchmark: ${benchmark.name}...`);
64
+ const result = await benchmark.run(model);
65
+ console.log(
66
+ `[${modelId}] Finished benchmark: ${benchmark.name}. Score: ${result.score}`
67
+ );
68
+ return {
69
+ model: modelId,
70
+ benchmark: benchmark.name,
71
+ result
72
+ };
73
+ } catch (error) {
74
+ console.error(
75
+ `[${modelId}] Error running benchmark: ${benchmark.name}`,
76
+ error
77
+ );
78
+ return {
79
+ model: modelId,
80
+ benchmark: benchmark.name,
81
+ result: {
82
+ score: 0,
83
+ success: false,
84
+ metrics: {},
85
+ error: error instanceof Error ? error : new Error(String(error))
86
+ }
87
+ };
88
+ }
89
+ }
90
+ async function evaluate(options) {
91
+ const { models, benchmarks, reporter = "console" } = options;
92
+ const modelsArray = Array.isArray(models) ? models : [models];
93
+ const allResults = [];
94
+ for (const model of modelsArray) {
95
+ for (const benchmark of benchmarks) {
96
+ const evaluationResult = await runSingleBenchmark(model, benchmark);
97
+ allResults.push(evaluationResult);
98
+ }
99
+ }
100
+ const report = reporters[reporter];
101
+ if (report) {
102
+ report(allResults);
103
+ } else {
104
+ console.warn(`Unknown reporter: '${reporter}'. Defaulting to console.`);
105
+ reporters.console(allResults);
106
+ }
107
+ return allResults;
108
+ }
109
+
110
+ // src/benchmarks/json-generation.ts
111
+ import { generateText } from "ai";
112
+ import Ajv from "ajv";
113
+ import { promises as fs2 } from "fs";
114
+ import path2 from "path";
115
+
116
+ // src/utils/paths.ts
117
+ import fs from "fs";
118
+ import path from "path";
119
+ import { fileURLToPath } from "url";
120
+ import { createRequire } from "module";
121
+ function resolveDataDir(fromModuleUrl) {
122
+ const moduleUrl = fromModuleUrl;
123
+ const override = process.env.BFCL_DATA_DIR;
124
+ if (override && override.trim().length > 0) {
125
+ return override;
126
+ }
127
+ try {
128
+ const baseForRequireEntry = typeof moduleUrl === "string" && moduleUrl || path.join(process.cwd(), "package.json");
129
+ const requireFromEntry = createRequire(baseForRequireEntry);
130
+ const entryPath = requireFromEntry.resolve("@ai-sdk-tool/eval");
131
+ const entryDir = path.dirname(entryPath);
132
+ const guessPkgRoot = fs.existsSync(path.join(entryDir, "..")) ? path.resolve(entryDir, "..") : entryDir;
133
+ const dataAtRoot = path.join(guessPkgRoot, "data");
134
+ if (fs.existsSync(dataAtRoot)) return dataAtRoot;
135
+ } catch {
136
+ }
137
+ try {
138
+ const baseForRequire = typeof moduleUrl === "string" && moduleUrl || path.join(process.cwd(), "package.json");
139
+ const require2 = createRequire(baseForRequire);
140
+ const pkgJsonPath = require2.resolve("@ai-sdk-tool/eval/package.json");
141
+ const pkgDir = path.dirname(pkgJsonPath);
142
+ const dataAtPkg = path.join(pkgDir, "data");
143
+ if (fs.existsSync(dataAtPkg)) return dataAtPkg;
144
+ } catch {
145
+ }
146
+ let startDir;
147
+ if (moduleUrl) {
148
+ try {
149
+ startDir = path.dirname(fileURLToPath(moduleUrl));
150
+ } catch {
151
+ startDir = process.cwd();
152
+ }
153
+ } else {
154
+ startDir = process.cwd();
155
+ }
156
+ let dir = startDir;
157
+ for (let i = 0; i < 6; i++) {
158
+ const dataCandidate = path.join(dir, "data");
159
+ if (fs.existsSync(dataCandidate)) return dataCandidate;
160
+ const parent = path.resolve(dir, "..");
161
+ if (parent === dir) break;
162
+ dir = parent;
163
+ }
164
+ const pkgRoot = path.resolve(startDir, "..", "..");
165
+ return path.join(pkgRoot, "data");
166
+ }
167
+
168
+ // src/benchmarks/json-generation.ts
169
+ function extractFirstJsonBlock(text) {
170
+ try {
171
+ return JSON.parse(text);
172
+ } catch {
173
+ }
174
+ const fenceMatch = text.match(/```json\s*([\s\S]*?)```/i) || text.match(/```\s*([\s\S]*?)```/i);
175
+ if (fenceMatch) {
176
+ const inner = fenceMatch[1].trim();
177
+ try {
178
+ return JSON.parse(inner);
179
+ } catch {
180
+ }
181
+ }
182
+ const startIdxObj = text.indexOf("{");
183
+ const startIdxArr = text.indexOf("[");
184
+ const start = [startIdxObj, startIdxArr].filter((i) => i >= 0).sort((a, b) => a - b)[0];
185
+ if (start === void 0) return void 0;
186
+ const open = text[start] === "{" ? "{" : "[";
187
+ const close = open === "{" ? "}" : "]";
188
+ let depth = 0;
189
+ for (let i = start; i < text.length; i++) {
190
+ const ch = text[i];
191
+ if (ch === open) depth++;
192
+ else if (ch === close) depth--;
193
+ if (depth === 0) {
194
+ const candidate = text.slice(start, i + 1);
195
+ try {
196
+ return JSON.parse(candidate);
197
+ } catch {
198
+ }
199
+ break;
200
+ }
201
+ }
202
+ return void 0;
203
+ }
204
+ function subsetMatch(expected, actual) {
205
+ if (expected === null || typeof expected !== "object") {
206
+ return expected === actual;
207
+ }
208
+ if (Array.isArray(expected)) {
209
+ if (!Array.isArray(actual)) return false;
210
+ for (let i = 0; i < expected.length; i++) {
211
+ if (!subsetMatch(expected[i], actual[i])) return false;
212
+ }
213
+ return true;
214
+ }
215
+ if (actual === null || typeof actual !== "object") return false;
216
+ const eObj = expected;
217
+ const aObj = actual;
218
+ for (const key of Object.keys(eObj)) {
219
+ if (!subsetMatch(eObj[key], aObj[key])) return false;
220
+ }
221
+ return true;
222
+ }
223
+ var jsonGenerationBenchmark = {
224
+ name: "json-generation",
225
+ version: "2.1.0",
226
+ description: "Evaluates schema-compliant JSON generation from natural language using JSON Schema prompts.",
227
+ async run(model) {
228
+ const logs = [];
229
+ const ajv = new Ajv({ allErrors: true, strict: false });
230
+ let schemaValidCount = 0;
231
+ let valueMatchCount = 0;
232
+ let correctCount = 0;
233
+ let tests = [];
234
+ const expectedMap = /* @__PURE__ */ new Map();
235
+ try {
236
+ const dataDir = resolveDataDir();
237
+ const testsJsonl = await fs2.readFile(
238
+ path2.join(dataDir, "json_generation_tests.jsonl"),
239
+ "utf-8"
240
+ );
241
+ const expectedJsonl = await fs2.readFile(
242
+ path2.join(dataDir, "json_generation_expected.jsonl"),
243
+ "utf-8"
244
+ );
245
+ tests = testsJsonl.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
246
+ const expecteds = expectedJsonl.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
247
+ for (const r of expecteds) expectedMap.set(r.id, r);
248
+ } catch (e) {
249
+ const msg = e instanceof Error ? e.message : String(e);
250
+ return {
251
+ score: 0,
252
+ success: false,
253
+ metrics: {},
254
+ logs: [`[FATAL] Failed to load json-generation datasets: ${msg}`],
255
+ error: e
256
+ };
257
+ }
258
+ for (const tc of tests) {
259
+ try {
260
+ const schemaStr = JSON.stringify(tc.schema, null, 2);
261
+ const messages = [
262
+ {
263
+ role: "system",
264
+ content: "You must output only a single JSON document that strictly conforms to the given JSON Schema. Do not include any extra text or code fences."
265
+ },
266
+ {
267
+ role: "user",
268
+ content: [
269
+ "Generate a JSON object that reflects the following facts.",
270
+ "JSON Schema:",
271
+ schemaStr,
272
+ "Facts:",
273
+ tc.promptFacts,
274
+ "Output must be a single JSON only, with no additional text."
275
+ ].join("\n\n")
276
+ }
277
+ ];
278
+ const { text } = await generateText({ model, messages });
279
+ let parsed;
280
+ try {
281
+ parsed = extractFirstJsonBlock(text);
282
+ } catch {
283
+ }
284
+ if (parsed === void 0) {
285
+ logs.push(`[FAIL] ${tc.id}: Unable to parse JSON from model output.`);
286
+ continue;
287
+ }
288
+ const validate = ajv.compile(tc.schema);
289
+ const valid = validate(parsed);
290
+ if (valid) schemaValidCount++;
291
+ else
292
+ logs.push(
293
+ `[INFO] ${tc.id}: Schema validation errors: ${(validate.errors || []).map((e) => `${e.instancePath} ${e.message}`).join(", ") || "unknown"}`
294
+ );
295
+ const expectedRec = expectedMap.get(tc.id);
296
+ if (!expectedRec) {
297
+ logs.push(
298
+ `[WARN] ${tc.id}: No expected record found. Skipping value match.`
299
+ );
300
+ }
301
+ const valuesOk = expectedRec ? subsetMatch(expectedRec.expected, parsed) : false;
302
+ if (valuesOk) valueMatchCount++;
303
+ if (valid && valuesOk) {
304
+ correctCount++;
305
+ logs.push(`[PASS] ${tc.id}`);
306
+ } else {
307
+ logs.push(
308
+ `[FAIL] ${tc.id}: schemaValid=${valid}, valuesOk=${valuesOk}. Output=${JSON.stringify(
309
+ parsed
310
+ )}`
311
+ );
312
+ }
313
+ } catch (e) {
314
+ const msg = e instanceof Error ? e.message : String(e);
315
+ logs.push(`[ERROR] ${tc.id}: ${msg}`);
316
+ }
317
+ }
318
+ const total = tests.length;
319
+ const score = correctCount / total;
320
+ return {
321
+ score,
322
+ success: score >= 0.8,
323
+ metrics: {
324
+ total_cases: total,
325
+ correct_count: correctCount,
326
+ schema_valid_count: schemaValidCount,
327
+ value_match_count: valueMatchCount,
328
+ accuracy: score
329
+ },
330
+ logs
331
+ };
332
+ }
333
+ };
334
+ var jsonGenerationSchemaOnlyBenchmark = {
335
+ name: "json-generation-schema-only",
336
+ version: "1.0.1",
337
+ description: "Evaluates whether model outputs strictly conform to the provided JSON Schema (structure only).",
338
+ async run(model) {
339
+ const logs = [];
340
+ const ajv = new Ajv({ allErrors: true, strict: false });
341
+ let tests = [];
342
+ try {
343
+ const dataDir = resolveDataDir();
344
+ const testsJsonl = await fs2.readFile(
345
+ path2.join(dataDir, "json_generation_tests.jsonl"),
346
+ "utf-8"
347
+ );
348
+ tests = testsJsonl.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
349
+ } catch (e) {
350
+ const msg = e instanceof Error ? e.message : String(e);
351
+ return {
352
+ score: 0,
353
+ success: false,
354
+ metrics: {},
355
+ logs: [`[FATAL] Failed to load schema-only tests: ${msg}`],
356
+ error: e
357
+ };
358
+ }
359
+ let schemaValidCount = 0;
360
+ for (const tc of tests) {
361
+ try {
362
+ const schemaStr = JSON.stringify(tc.schema, null, 2);
363
+ const messages = [
364
+ {
365
+ role: "system",
366
+ content: "You must output only a single JSON document that strictly conforms to the given JSON Schema. Do not include any extra text or code fences."
367
+ },
368
+ {
369
+ role: "user",
370
+ content: [
371
+ "Generate a JSON object that reflects the following facts.",
372
+ "JSON Schema:",
373
+ schemaStr,
374
+ "Facts:",
375
+ tc.promptFacts,
376
+ "Output must be a single JSON only, with no additional text."
377
+ ].join("\n\n")
378
+ }
379
+ ];
380
+ const { text } = await generateText({ model, messages });
381
+ let parsed;
382
+ try {
383
+ parsed = extractFirstJsonBlock(text);
384
+ } catch {
385
+ }
386
+ if (parsed === void 0) {
387
+ logs.push(`[FAIL] ${tc.id}: Could not parse JSON from model output.`);
388
+ continue;
389
+ }
390
+ const validate = ajv.compile(tc.schema);
391
+ const valid = validate(parsed);
392
+ if (valid) {
393
+ schemaValidCount++;
394
+ logs.push(`[PASS] ${tc.id}`);
395
+ } else {
396
+ logs.push(
397
+ `[FAIL] ${tc.id}: Schema validation errors: ${(validate.errors || []).map((e) => `${e.instancePath} ${e.message}`).join(", ") || "unknown"}`
398
+ );
399
+ }
400
+ } catch (e) {
401
+ const msg = e instanceof Error ? e.message : String(e);
402
+ logs.push(`[ERROR] ${tc.id}: ${msg}`);
403
+ }
404
+ }
405
+ const total = tests.length;
406
+ const score = total > 0 ? schemaValidCount / total : 0;
407
+ return {
408
+ score,
409
+ success: score >= 0.8,
410
+ metrics: {
411
+ total_cases: total,
412
+ schema_valid_count: schemaValidCount,
413
+ accuracy: score
414
+ },
415
+ logs
416
+ };
417
+ }
418
+ };
419
+
420
+ // src/benchmarks/bfcl.ts
421
+ import { generateText as generateText2, jsonSchema } from "ai";
422
+ import { promises as fs3 } from "fs";
423
+ import path3 from "path";
424
+
425
+ // src/benchmarks/bfcl/ast-checker.ts
426
+ function standardizeString(input) {
427
+ if (typeof input !== "string") return input;
428
+ const regex = /[ ,./\\-_*^]/g;
429
+ return input.replace(regex, "").toLowerCase().replace(/'/g, '"');
430
+ }
431
+ function checkStringValue(param, modelValue, possibleAnswers) {
432
+ const standardizedModelValue = standardizeString(modelValue);
433
+ const standardizedPossibleAnswers = possibleAnswers.map(
434
+ (ans) => standardizeString(ans)
435
+ );
436
+ if (!standardizedPossibleAnswers.includes(standardizedModelValue)) {
437
+ return {
438
+ valid: false,
439
+ error: `Invalid value for parameter '${param}': '${modelValue}'. Expected one of ${possibleAnswers.join(", ")}.`,
440
+ error_type: "value_error:string"
441
+ };
442
+ }
443
+ return { valid: true };
444
+ }
445
+ function simpleFunctionChecker(funcDescription, modelToolCall, possibleAnswer) {
446
+ const modelArgs = modelToolCall.args;
447
+ const modelFuncName = modelToolCall.toolName;
448
+ const expectedFuncName = funcDescription.name;
449
+ const expectedParams = funcDescription.parameters.properties;
450
+ const requiredParams = funcDescription.parameters.required;
451
+ if (modelFuncName !== expectedFuncName) {
452
+ return {
453
+ valid: false,
454
+ error: `Function name '${modelFuncName}' does not match expected '${expectedFuncName}'.`,
455
+ error_type: "simple_function_checker:wrong_func_name"
456
+ };
457
+ }
458
+ const possibleAnswerParams = possibleAnswer[Object.keys(possibleAnswer)[0]];
459
+ for (const param of requiredParams) {
460
+ if (!(param in modelArgs)) {
461
+ return {
462
+ valid: false,
463
+ error: `Missing required parameter: '${param}'.`,
464
+ error_type: "simple_function_checker:missing_required"
465
+ };
466
+ }
467
+ }
468
+ for (const paramName in modelArgs) {
469
+ const modelValue = modelArgs[paramName];
470
+ if (!(paramName in expectedParams) || !(paramName in possibleAnswerParams)) {
471
+ return {
472
+ valid: false,
473
+ error: `Unexpected parameter: '${paramName}'.`,
474
+ error_type: "simple_function_checker:unexpected_param"
475
+ };
476
+ }
477
+ const possibleValues = possibleAnswerParams[paramName];
478
+ if (typeof modelValue === "string") {
479
+ const result = checkStringValue(paramName, modelValue, possibleValues);
480
+ if (!result.valid) return result;
481
+ } else if (Array.isArray(modelValue)) {
482
+ const modelValueStr = JSON.stringify(
483
+ modelValue.map((v) => standardizeString(v.toString())).sort()
484
+ );
485
+ const hasMatch = possibleValues.some(
486
+ (p) => JSON.stringify(
487
+ p.map((v) => standardizeString(v.toString())).sort()
488
+ ) === modelValueStr
489
+ );
490
+ if (!hasMatch) {
491
+ return {
492
+ valid: false,
493
+ error: `Invalid value for list parameter '${paramName}'.`,
494
+ error_type: "value_error:list"
495
+ };
496
+ }
497
+ } else {
498
+ if (!possibleValues.includes(modelValue)) {
499
+ return {
500
+ valid: false,
501
+ error: `Invalid value for parameter '${paramName}': got '${modelValue}', expected one of '${possibleValues}'.`,
502
+ error_type: "value_error:other"
503
+ };
504
+ }
505
+ }
506
+ }
507
+ for (const paramName in possibleAnswerParams) {
508
+ if (!(paramName in modelArgs) && !possibleAnswerParams[paramName].includes("")) {
509
+ return {
510
+ valid: false,
511
+ error: `Missing optional parameter '${paramName}' which was not marked as optional.`,
512
+ error_type: "simple_function_checker:missing_optional"
513
+ };
514
+ }
515
+ }
516
+ return { valid: true };
517
+ }
518
+ function parallelFunctionCheckerNoOrder(funcDescriptions, modelToolCalls, possibleAnswers) {
519
+ if (modelToolCalls.length !== possibleAnswers.length) {
520
+ return {
521
+ valid: false,
522
+ error: `Wrong number of functions. Expected ${possibleAnswers.length}, got ${modelToolCalls.length}.`,
523
+ error_type: "parallel_function_checker_no_order:wrong_count"
524
+ };
525
+ }
526
+ const matchedModelCallIndices = /* @__PURE__ */ new Set();
527
+ for (const possibleAnswer of possibleAnswers) {
528
+ const expectedFuncName = Object.keys(possibleAnswer)[0];
529
+ const funcDescription = funcDescriptions.find(
530
+ (f) => f.name === expectedFuncName
531
+ );
532
+ if (!funcDescription) {
533
+ return {
534
+ valid: false,
535
+ error: `Could not find function description for '${expectedFuncName}'.`,
536
+ error_type: "parallel_function_checker_no_order:missing_func_desc"
537
+ };
538
+ }
539
+ let foundMatch = false;
540
+ for (let i = 0; i < modelToolCalls.length; i++) {
541
+ if (matchedModelCallIndices.has(i)) continue;
542
+ const checkerResult = simpleFunctionChecker(
543
+ funcDescription,
544
+ modelToolCalls[i],
545
+ possibleAnswer
546
+ );
547
+ if (checkerResult.valid) {
548
+ matchedModelCallIndices.add(i);
549
+ foundMatch = true;
550
+ break;
551
+ }
552
+ }
553
+ if (!foundMatch) {
554
+ return {
555
+ valid: false,
556
+ error: `Could not find a matching function call for '${expectedFuncName}'.`,
557
+ error_type: "parallel_function_checker_no_order:cannot_find_match"
558
+ };
559
+ }
560
+ }
561
+ return { valid: true };
562
+ }
563
+ function multipleFunctionChecker(funcDescriptions, modelToolCalls, possibleAnswers) {
564
+ if (modelToolCalls.length !== possibleAnswers.length) {
565
+ return {
566
+ valid: false,
567
+ error: `Wrong number of functions. Expected ${possibleAnswers.length}, got ${modelToolCalls.length}.`,
568
+ error_type: "multiple_function_checker:wrong_count"
569
+ };
570
+ }
571
+ const expectedFuncName = Object.keys(possibleAnswers[0])[0];
572
+ const funcDescription = funcDescriptions.find(
573
+ (f) => f.name === expectedFuncName
574
+ );
575
+ if (!funcDescription) {
576
+ return {
577
+ valid: false,
578
+ error: `Could not find function description for '${expectedFuncName}'.`,
579
+ error_type: "multiple_function_checker:missing_func_desc"
580
+ };
581
+ }
582
+ return simpleFunctionChecker(
583
+ funcDescription,
584
+ modelToolCalls[0],
585
+ possibleAnswers[0]
586
+ );
587
+ }
588
+
589
+ // src/benchmarks/bfcl.ts
590
+ function check(testCase, modelOutput, possibleAnswer) {
591
+ const category = testCase.id.split("_")[0];
592
+ try {
593
+ if (category === "simple") {
594
+ if (!modelOutput || modelOutput.length !== 1) {
595
+ return {
596
+ valid: false,
597
+ error: `Expected 1 function call, but got ${modelOutput?.length ?? 0}.`
598
+ };
599
+ }
600
+ return simpleFunctionChecker(
601
+ testCase.function[0],
602
+ modelOutput[0],
603
+ possibleAnswer.ground_truth[0]
604
+ );
605
+ } else if (category === "parallel") {
606
+ return parallelFunctionCheckerNoOrder(
607
+ testCase.function,
608
+ modelOutput,
609
+ possibleAnswer.ground_truth
610
+ );
611
+ } else if (category === "multiple") {
612
+ return multipleFunctionChecker(
613
+ testCase.function,
614
+ modelOutput,
615
+ possibleAnswer.ground_truth
616
+ );
617
+ } else if (category.includes("parallel-multiple")) {
618
+ return parallelFunctionCheckerNoOrder(
619
+ testCase.function,
620
+ modelOutput,
621
+ possibleAnswer.ground_truth
622
+ );
623
+ }
624
+ return { valid: true };
625
+ } catch (e) {
626
+ return { valid: false, error: `Checker Error: ${e.message}` };
627
+ }
628
+ }
629
+ function createBfclBenchmark(name, description, testDataFile, answerDataFile) {
630
+ return {
631
+ name,
632
+ version: "1.0.0",
633
+ description,
634
+ async run(model) {
635
+ const logs = [];
636
+ let correctCount = 0;
637
+ let testCases = [];
638
+ try {
639
+ const dataPath = resolveDataDir();
640
+ logs.push(`[INFO] Using data dir: ${dataPath}`);
641
+ const testCasesJson = await fs3.readFile(
642
+ path3.join(dataPath, testDataFile),
643
+ "utf-8"
644
+ );
645
+ const possibleAnswersJson = await fs3.readFile(
646
+ path3.join(dataPath, answerDataFile),
647
+ "utf-8"
648
+ );
649
+ testCases = testCasesJson.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
650
+ const possibleAnswers = possibleAnswersJson.split(/\r?\n/).filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
651
+ const possibleAnswersMap = new Map(
652
+ possibleAnswers.map((ans) => [ans.id, ans])
653
+ );
654
+ const limitEnv = process.env.BFCL_LIMIT;
655
+ const limit = limitEnv ? Number(limitEnv) : void 0;
656
+ if (limit && Number.isFinite(limit) && limit > 0) {
657
+ testCases = testCases.slice(0, limit);
658
+ logs.push(
659
+ `[INFO] Limiting test cases to ${limit} due to BFCL_LIMIT.`
660
+ );
661
+ }
662
+ const fixSchema = (schema) => {
663
+ if (!schema || typeof schema !== "object") return schema;
664
+ const copy = Array.isArray(schema) ? schema.map((v) => fixSchema(v)) : { ...schema };
665
+ if (copy.type) {
666
+ if (copy.type === "dict") copy.type = "object";
667
+ if (copy.type === "integer" || copy.type === "float")
668
+ copy.type = "number";
669
+ }
670
+ if (copy.properties && typeof copy.properties === "object") {
671
+ for (const k of Object.keys(copy.properties)) {
672
+ copy.properties[k] = fixSchema(copy.properties[k]);
673
+ }
674
+ }
675
+ if (copy.items) copy.items = fixSchema(copy.items);
676
+ return copy;
677
+ };
678
+ for (const testCase of testCases) {
679
+ const { function: tools, question: messages } = testCase;
680
+ try {
681
+ const flatMessages = Array.isArray(messages) && messages.some((m) => Array.isArray(m)) ? messages.flat(1) : messages;
682
+ const nameMap = /* @__PURE__ */ new Map();
683
+ const sanitizeName = (name2) => {
684
+ const s = name2.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
685
+ return s.length > 0 ? s : "tool";
686
+ };
687
+ const transformedTools = tools.map((t) => {
688
+ const fixed = fixSchema(t.parameters);
689
+ const inputSchema = fixed && typeof fixed === "object" && fixed.type === "object" ? fixed : { type: "object", properties: {} };
690
+ const sanitized = sanitizeName(t.name);
691
+ nameMap.set(sanitized, t.name);
692
+ return {
693
+ type: "function",
694
+ name: sanitized,
695
+ description: t.description,
696
+ // Mark as JSON schema explicitly to prevent Zod parsing
697
+ inputSchema: jsonSchema(inputSchema)
698
+ };
699
+ });
700
+ try {
701
+ const firstTool = transformedTools[0];
702
+ const schemaType = firstTool?.inputSchema?.type ?? firstTool?.inputSchema?.jsonSchema?.type;
703
+ logs.push(
704
+ `[DEBUG] ${testCase.id}: firstTool=${JSON.stringify(firstTool)}, schemaType=${schemaType}`
705
+ );
706
+ } catch (e) {
707
+ logs.push(
708
+ `[DEBUG] ${testCase.id}: failed to introspect tools: ${e.message}`
709
+ );
710
+ }
711
+ const { toolCalls, text, finishReason } = await generateText2({
712
+ model,
713
+ messages: flatMessages,
714
+ tools: transformedTools,
715
+ toolChoice: "required"
716
+ });
717
+ try {
718
+ logs.push(
719
+ `[DEBUG] ${testCase.id}: rawToolCalls=${JSON.stringify(toolCalls)}, finishReason=${finishReason}, text=${JSON.stringify(text)}`
720
+ );
721
+ } catch {
722
+ logs.push(
723
+ `[DEBUG] ${testCase.id}: failed to serialize toolCalls`
724
+ );
725
+ }
726
+ const possibleAnswer = possibleAnswersMap.get(testCase.id);
727
+ if (!possibleAnswer) {
728
+ throw new Error(`No possible answer for id: ${testCase.id}`);
729
+ }
730
+ const restoredCalls = (toolCalls || []).map((c) => {
731
+ const rawName = c.toolName ?? c.name;
732
+ const sanitizedFromIndex = typeof rawName === "string" && /^\d+$/.test(rawName) ? transformedTools[Number(rawName)]?.name ?? rawName : rawName;
733
+ const originalName = nameMap.get(sanitizedFromIndex) ?? sanitizedFromIndex;
734
+ const extractedArgs = c.args ?? c.arguments ?? c.input ?? c.params ?? c.parameters ?? void 0;
735
+ let parsedArgs = extractedArgs;
736
+ if (typeof parsedArgs === "string") {
737
+ try {
738
+ parsedArgs = JSON.parse(parsedArgs);
739
+ } catch {
740
+ }
741
+ }
742
+ return {
743
+ ...c,
744
+ toolName: originalName,
745
+ name: originalName,
746
+ args: parsedArgs ?? {}
747
+ };
748
+ });
749
+ const checkerResult = check(
750
+ testCase,
751
+ restoredCalls,
752
+ possibleAnswer
753
+ );
754
+ if (checkerResult.valid) {
755
+ correctCount++;
756
+ logs.push(`[PASS] ${testCase.id}`);
757
+ } else {
758
+ logs.push(`[FAIL] ${testCase.id}: ${checkerResult.error}`);
759
+ }
760
+ } catch (e) {
761
+ logs.push(
762
+ `[ERROR] ${testCase.id}: Model generation failed: ${e?.message}`
763
+ );
764
+ if (e?.stack) {
765
+ logs.push(`[STACK] ${testCase.id}: ${e.stack}`);
766
+ }
767
+ }
768
+ }
769
+ if (testCases.length === 0) {
770
+ return {
771
+ score: 0,
772
+ success: false,
773
+ metrics: {},
774
+ logs: ["No test cases found."]
775
+ };
776
+ }
777
+ const score = correctCount / testCases.length;
778
+ return {
779
+ score,
780
+ success: score > 0.95,
781
+ // High success threshold as requested
782
+ metrics: {
783
+ correct_count: correctCount,
784
+ total_cases: testCases.length,
785
+ accuracy: score
786
+ },
787
+ logs
788
+ };
789
+ } catch (e) {
790
+ return {
791
+ score: 0,
792
+ success: false,
793
+ metrics: {},
794
+ error: e,
795
+ logs: [`[FATAL] Failed to run benchmark ${name}: ${e.message}`]
796
+ };
797
+ }
798
+ }
799
+ };
800
+ }
801
+ var bfclSimpleBenchmark = createBfclBenchmark(
802
+ "bfcl-simple",
803
+ "BFCL Simple Function Calling",
804
+ "BFCL_v3_simple.json",
805
+ "BFCL_v3_simple_possible_answer.json"
806
+ );
807
+ var bfclParallelBenchmark = createBfclBenchmark(
808
+ "bfcl-parallel",
809
+ "BFCL Parallel Function Calling",
810
+ "BFCL_v3_parallel.json",
811
+ "BFCL_v3_parallel_possible_answer.json"
812
+ );
813
+ var bfclMultipleBenchmark = createBfclBenchmark(
814
+ "bfcl-multiple",
815
+ "BFCL Multiple Function Calling",
816
+ "BFCL_v3_multiple.json",
817
+ "BFCL_v3_multiple_possible_answer.json"
818
+ );
819
+ var bfclParallelMultipleBenchmark = createBfclBenchmark(
820
+ "bfcl-parallel-multiple",
821
+ "BFCL Parallel & Multiple Function Calling",
822
+ "BFCL_v3_parallel_multiple.json",
823
+ "BFCL_v3_parallel_multiple_possible_answer.json"
824
+ );
825
+ export {
826
+ bfclMultipleBenchmark,
827
+ bfclParallelBenchmark,
828
+ bfclParallelMultipleBenchmark,
829
+ bfclSimpleBenchmark,
830
+ evaluate,
831
+ jsonGenerationBenchmark,
832
+ jsonGenerationSchemaOnlyBenchmark
833
+ };
834
+ //# sourceMappingURL=index.js.map