-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathevaluate-models.ts
More file actions
440 lines (388 loc) · 13.5 KB
/
evaluate-models.ts
File metadata and controls
440 lines (388 loc) · 13.5 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#!/usr/bin/env tsx
/**
* Featherless Model Tool Calling Evaluator
*
* Usage:
* npx tsx evaluate-models.ts "reposcroll/RWKV-6-14B" "Qwen/QwQ-32B"
* npx tsx evaluate-models.ts --file models.json
* npx tsx evaluate-models.ts --config custom-config.json
*
* Input formats:
* - Model ID: "org/model-name"
* - URL: "https://featherless.ai/models/org/model-name"
*
* Config file (JSON):
* {
* "models": [
* { "id": "org/model", "params": { "temperature": 0.7, "top_p": 0.95 } }
* ],
* "scenarios": ["hello", "read", "json", "selfcontrol", "pipeline", "calc"],
* "output": "results/run-20250101.json"
* }
*/
import { config } from 'dotenv';
config();
import OpenAI from 'openai';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { join } from 'path';
const API_KEY = process.env.FEATHERLESS_API_KEY;
if (!API_KEY) {
console.error('Missing FEATHERLESS_API_KEY');
process.exit(1);
}
const client = new OpenAI({ apiKey: API_KEY, baseURL: 'https://api.featherless.ai/v1' });
// ============================================================================
// CONFIGURATION
// ============================================================================
type ModelParams = {
temperature?: number;
top_p?: number;
max_tokens?: number;
[key: string]: any;
};
interface ModelEntry {
id: string;
params?: ModelParams;
label?: string; // custom display name
}
interface EvaluationConfig {
models: ModelEntry[];
scenarios?: string[]; // filter which scenarios to run
outputDir?: string;
verbose?: boolean;
}
const DEFAULT_PARAMS: ModelParams = {
temperature: 0.7,
top_p: 1.0,
max_tokens: 500,
};
const SCENARIOS = {
hello: {
user: "Run: echo hello",
expectedTool: "bash",
check: (tc: any[]) => {
const call = tc.find(t => t.function.name === 'bash');
if (!call) return false;
try { const args = JSON.parse(call.function.arguments); return args.command?.includes('echo hello'); } catch { return false; }
},
},
read: {
user: "Read /etc/hostname",
expectedTool: "read_file",
check: (tc: any[]) => {
const call = tc.find(t => t.function.name === 'read_file');
if (!call) return false;
try { const args = JSON.parse(call.function.arguments); return args.path === '/etc/hostname'; } catch { return false; }
},
},
json: {
user: 'Write config.json with {"port":3000,"host":"0.0.0.0"}',
expectedTool: "write_file",
check: (tc: any[]) => {
const call = tc.find(t => t.function.name === 'write_file');
if (!call) return false;
try { const args = JSON.parse(call.function.arguments); return args.path?.endsWith('config.json'); } catch { return false; }
},
},
selfcontrol: {
user: "What is 2+2?",
expectedTool: "calculator",
check: (tc: any[]) => tc.some(t => t.function.name === 'calculator'),
},
pipeline: {
user: "Count .txt files in /tmp: ls /tmp/*.txt | wc -l",
expectedTool: "bash",
check: (tc: any[]) => {
const call = tc.find(t => t.function.name === 'bash');
if (!call) return false;
try { const args = JSON.parse(call.function.arguments); return args.command?.includes('wc -l'); } catch { return false; }
},
},
calc: {
user: "Calculate 15 * 23",
expectedTool: "calculator",
check: (tc: any[]) => tc.some(t => t.function.name === 'calculator'),
},
} as const;
type ScenarioKey = keyof typeof SCENARIOS;
const TOOLS = [
{
type: "function",
function: {
name: "bash",
description: "Execute bash command",
parameters: {
type: "object",
properties: { command: { type: "string" } },
required: ["command"],
},
},
},
{
type: "function",
function: {
name: "read_file",
description: "Read file content",
parameters: {
type: "object",
properties: { path: { type: "string" } },
required: ["path"],
},
},
},
{
type: "function",
function: {
name: "write_file",
description: "Write content to file",
parameters: {
type: "object",
properties: {
path: { type: "string" },
content: { type: "string" }
},
required: ["path", "content"],
},
},
},
{
type: "function",
function: {
name: "calculator",
description: "Evaluate mathematical expression",
parameters: {
type: "object",
properties: { expression: { type: "string" } },
required: ["expression"],
},
},
},
];
// ============================================================================
// LOGIC
// ============================================================================
interface ScenarioResult {
scenario: ScenarioKey;
passed: boolean;
toolCalls: any[];
content?: string;
error?: string;
durationMs: number;
}
interface ModelResult {
model: string;
label?: string;
params: ModelParams;
scenarios: ScenarioResult[];
overall: {
passed: number;
total: number;
percentage: number;
avgDurationMs: number;
};
error?: string;
}
function parseModelInput(input: string): ModelEntry {
// Strip URL prefix if present
const id = input.replace(/^https?:\/\/featherless\.ai\/models\//, '');
// Extract short label
const label = id.split('/').pop()?.replace(/-/g, ' ');
return { id, label: label || id };
}
async function runScenario(modelId: string, scenario: ScenarioKey, params: ModelParams): Promise<ScenarioResult> {
const start = Date.now();
try {
const res = await client.chat.completions.create({
model: modelId,
messages: [{ role: "user", content: SCENARIOS[scenario].user }],
tools: TOOLS,
max_tokens: params.max_tokens ?? 500,
temperature: params.temperature ?? 0.7,
top_p: params.top_p ?? 1.0,
});
const msg = res.choices[0].message;
const toolCalls = msg.tool_calls || [];
const content = msg.content || "";
const passed = SCENARIOS[scenario].check(toolCalls);
return {
scenario,
passed,
toolCalls,
content: content.slice(0, 200),
durationMs: Date.now() - start,
};
} catch (e: any) {
return {
scenario,
passed: false,
toolCalls: [],
error: e.message?.slice(0, 100) || String(e),
durationMs: Date.now() - start,
};
}
}
async function evaluateModel(entry: ModelEntry, scenarioFilter?: ScenarioKey[]): Promise<ModelResult> {
const scenariosToRun: ScenarioKey[] = scenarioFilter
? scenarioFilter
: (Object.keys(SCENARIOS) as ScenarioKey[]);
const results: ScenarioResult[] = [];
for (const scenario of scenariosToRun) {
const result = await runScenario(entry.id, scenario, entry.params ?? DEFAULT_PARAMS);
results.push(result);
}
const passed = results.filter(r => r.passed).length;
const total = results.length;
const avgDuration = results.reduce((sum, r) => sum + r.durationMs, 0) / total;
return {
model: entry.id,
label: entry.label,
params: entry.params ?? DEFAULT_PARAMS,
scenarios: results,
overall: { passed, total, percentage: Math.round((passed / total) * 100), avgDurationMs: Math.round(avgDuration) },
};
}
// ============================================================================
// INPUT HANDLING
// ============================================================================
function loadConfigFromArgs(): EvaluationConfig | null {
const args = process.argv.slice(2);
if (args.length === 0) return null;
// Remove any option flags (starting with --)
const cleanArgs = args.filter(a => !a.startsWith('--'));
// Check for config file via --config FILE or --config=FILE
const configFlagIdx = args.findIndex(a => a === '--config' || a === '--file');
if (configFlagIdx >= 0) {
const file = args[configFlagIdx + 1];
if (!file || !existsSync(file)) {
console.error(`Config file not found after ${args[configFlagIdx]}`);
process.exit(1);
}
const config = JSON.parse(readFileSync(file, 'utf-8'));
// Append any additional positional args as models
if (cleanArgs.length > 0) {
config.models = config.models || [];
config.models.push(...cleanArgs.map(parseModelInput));
}
return config;
}
const configEqual = args.find(a => a.startsWith('--config='))?.split('=')[1] || args.find(a => a.startsWith('--file='))?.split('=')[1];
if (configEqual) {
if (!existsSync(configEqual)) {
console.error(`Config file not found: ${configEqual}`);
process.exit(1);
}
return JSON.parse(readFileSync(configEqual, 'utf-8'));
}
// Default: all non-flag args are model IDs
if (cleanArgs.length === 0) {
console.error('No models specified.');
process.exit(1);
}
return { models: cleanArgs.map(parseModelInput) };
}
// ============================================================================
// OUTPUT
// ============================================================================
function generateMarkdownReport(results: ModelResult[]): string {
let md = `# Tool Calling Evaluation Report\n\n`;
md += `**Date:** ${new Date().toISOString().split('T')[0]}\n\n`;
md += `**Models evaluated:** ${results.length}\n\n`;
md += `## Summary\n\n`;
md += `| Model | Pass Rate | Avg Time |\n`;
md += `|-------|-----------|----------|\n`;
for (const r of results) {
const label = r.label || r.model.split('/').pop();
md += `| ${label} | ${r.overall.passed}/${r.overall.total} (${r.overall.percentage}%) | ${(r.overall.avgDurationMs/1000).toFixed(1)}s |\n`;
}
md += `\n## Detailed Results\n\n`;
for (const r of results) {
md += `### ${r.label || r.model}\n\n`;
md += `**Parameters:** temp=${r.params.temperature}, top_p=${r.params.top_p}\n\n`;
md += `| Scenario | Pass | Duration | Details |\n`;
md += `|----------|------|----------|----------|\n`;
for (const s of r.scenarios) {
const status = s.passed ? '✅' : '❌';
const time = (s.durationMs/1000).toFixed(2);
let details = '';
if (s.error) {
details = `Error: ${s.error}`;
} else if (s.toolCalls.length > 0) {
const toolName = s.toolCalls[0].function.name;
const args = typeof s.toolCalls[0].function.arguments === 'string'
? s.toolCalls[0].function.arguments
: JSON.stringify(s.toolCalls[0].function.arguments);
details = s.passed ? `✅ ${toolName}` : `❌ ${toolName} - ${args.slice(0, 40)}`;
} else if (s.content) {
details = `"${s.content.trim().replace(/|/g, '').slice(0, 50)}..."`;
}
md += `| ${s.scenario} | ${status} | ${time}s | ${details} |\n`;
}
md += `\n`;
}
return md;
}
function saveResults(results: ModelResult[], config: EvaluationConfig) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const outputDir = config.outputDir || 'results';
if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
const jsonPath = join(outputDir, `bench-${timestamp}.json`);
const mdPath = join(outputDir, `bench-${timestamp}.md`);
const reportData = {
timestamp: new Date().toISOString(),
config: config,
results,
};
writeFileSync(jsonPath, JSON.stringify(reportData, null, 2));
writeFileSync(mdPath, generateMarkdownReport(results));
console.log(`\n💾 Results saved:`);
console.log(` JSON: ${jsonPath}`);
console.log(` Markdown: ${mdPath}`);
}
// ============================================================================
// MAIN
// ============================================================================
(async () => {
console.log("\n" + "=".repeat(80));
console.log(" FEATHERLESS MODEL EVALUATOR");
console.log("=".repeat(80) + "\n");
const config = loadConfigFromArgs();
if (!config || config.models.length === 0) {
console.error("No models specified. Provide model IDs as arguments or use --file/--config.");
console.error("\nExamples:");
console.error(" npx tsx evaluate-models.ts \"org/model\" \"another/model\"");
console.error(" npx tsx evaluate-models.ts --file models.json");
console.error(" npx tsx evaluate-models.ts --config custom.json --scenarios hello,read");
process.exit(1);
}
console.log(`Evaluating ${config.models.length} model(s)...`);
console.log(`Scenarios: ${config.scenarios?.join(', ') || 'all (6)'}\n`);
const results: ModelResult[] = [];
let completed = 0;
for (const entry of config.models) {
console.log(`[${completed + 1}/${config.models.length}] Evaluating: ${entry.label || entry.id}`);
if (entry.params) {
console.log(` ⚙️ Params: temp=${entry.params.temperature}, top_p=${entry.params.top_p}`);
}
const result = await evaluateModel(entry, config.scenarios as ScenarioKey[]);
results.push(result);
const score = `${result.overall.passed}/${result.overall.total} (${result.overall.percentage}%)`;
console.log(` ✅ Score: ${score.padEnd(12)} Avg: ${(result.overall.avgDurationMs/1000).toFixed(1)}s`);
if (result.error) {
console.log(` ⚠️ Error: ${result.error}`);
}
completed++;
}
console.log("\n" + "-".repeat(80));
console.log(" FINAL SCORES");
console.log("-".repeat(80));
const sorted = results.sort((a, b) => b.overall.percentage - a.overall.percentage);
for (const r of sorted) {
const label = r.label || r.model;
console.log(`${r.overall.percentage.toString().padStart(3)}% ${label.padEnd(40)} ${r.overall.passed}/${r.overall.total} ${(r.overall.avgDurationMs/1000).toFixed(1)}s`);
}
saveResults(results, config);
console.log("\n🎉 Done.\n");
})().catch((e) => {
console.error("\nFatal error:", e);
process.exit(1);
});