Open History to see the last commit
1/**
2 * Code-mode models eval: run each configured model on the database-demo gold prompt,
3 * then judge vs gold report (Anthropic Opus + structured scores).
4 *
5 * Usage (from repo root):
6 * pnpm --filter @tanstack/ai-code-mode-models-eval eval
7 * pnpm --filter @tanstack/ai-code-mode-models-eval eval -- --ollama-only
8 * pnpm --filter @tanstack/ai-code-mode-models-eval eval -- --models openai:gpt-4o,groq:qwen/qwen3-32b
9 * cd packages/ai-code-mode/models-eval && pnpm eval -- --no-judge
10 *
11 * Env:
12 * ANTHROPIC_API_KEY — required for judging (unless --no-judge); auto-loaded from
13 * examples/ts-code-mode-web/.env.local (or repo-root .env.local) if present
14 * OPENAI_API_KEY — for OpenAI eval models
15 * GOOGLE_GENERATIVE_AI_API_KEY — for Gemini eval models
16 * XAI_API_KEY — for Grok (xAI) eval models
17 * GROQ_API_KEY — for Groq eval models
18 *
19 * Each run log JSON under models-eval/log/ includes `messages` (full UIMessage[] from
20 * StreamProcessor: user prompt, assistant text, tool-call parts, tool results).
21 */
22
23import {
24 existsSync,
25 mkdirSync,
26 readFileSync,
27 readdirSync,
28 writeFileSync,
29} from 'node:fs'
30import { dirname, join, relative } from 'node:path'
31import { fileURLToPath } from 'node:url'
32
33import { config as loadDotenv } from 'dotenv'
34
35import {
36 StreamProcessor,
37 chat,
38 fromSpecTokenUsage,
39 generateMessageId,
40 maxIterations,
41 normalizeToUIMessage,
42} from '@tanstack/ai'
43import { anthropicText } from '@tanstack/ai-anthropic'
44import { geminiText } from '@tanstack/ai-gemini'
45import { grokText } from '@tanstack/ai-grok'
46import { groqText } from '@tanstack/ai-groq'
47import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
48import { ollamaText } from '@tanstack/ai-ollama'
49import { openaiText } from '@tanstack/ai-openai'
50import { createCodeMode } from '@tanstack/ai-code-mode'
51
52import { databaseTools, getSchemaInfoTool } from './database-tools'
53import { EVAL_MODELS, getModelCategory, parseModelId } from './eval-config'
54import { judgeReports } from './judge'
55import {
56 computeMetrics,
57 computeStarRating,
58 formatTypescriptEvidence,
59} from './metrics'
60import type { JudgeResult } from './judge'
61import type { AnyTextAdapter, StreamChunk, UIMessage } from '@tanstack/ai'
62import type { EvalProvider, ModelCategory } from './eval-config'
63
64const __dirname = dirname(fileURLToPath(import.meta.url))
65
66/** Per-run JSON logs (gitignored); inspect candidate text vs gold when scores look wrong. */
67const LOG_DIR = join(__dirname, 'log')
68
69const repoRoot = join(__dirname, '../../../')
70
71function loadEnvLocalFiles() {
72 const paths = [
73 join(repoRoot, 'examples/ts-code-mode-web/.env.local'),
74 join(repoRoot, 'examples/ts-code-mode-web/.env'),
75 join(repoRoot, '.env.local'),
76 join(repoRoot, '.env'),
77 join(repoRoot, 'packages/ai-code-mode/.env.local'),
78 join(__dirname, '.env.local'),
79 ]
80 for (const path of paths) {
81 if (existsSync(path)) {
82 loadDotenv({ path, override: false })
83 }
84 }
85}
86
87loadEnvLocalFiles()
88
89/**
90 * Code-mode–accurate copy: top-level tools are only getSchemaInfo + execute_typescript.
91 * The web demo's direct-tools prompt incorrectly names `queryTable` as a top-level tool;
92 * in code mode, querying happens via external_queryTable *inside* execute_typescript.
93 */
94const DATABASE_DEMO_SYSTEM_PROMPT = `You are a helpful data analyst assistant working with an in-memory database: tables **customers**, **products**, and **purchases**.
95
96## Top-level tools (these are the only tools you can invoke)
97
981. **getSchemaInfo** — Returns schema and row counts. Prefer **one call with no table argument** so you receive customers, products, and purchases together.
99
1002. **execute_typescript** — Runs TypeScript in a sandbox. Inside the sandbox you call **external_queryTable** and **external_getSchemaInfo** (same behavior as querying the DB). Use this for every multi-table join, filter, aggregation, and analysis.
101
102## Tables
103
104- **customers** — id, name, email, city, joined
105- **products** — id, name, category, price, stock
106- **purchases** — id, customer_id, product_id, quantity, total, purchased_at
107
108**Joins:** \`purchases\` does **not** have \`category\`. Category is only on \`products\`. Load \`purchases\` and \`products\`, then join in code with \`product_id\` → \`products.id\` to know each purchase’s category. If you \`external_queryTable({ table: 'purchases', columns: ['category'] })\`, every row will be \`{}\` — that is wrong.
109
110## Strategy
111
112- Call getSchemaInfo once (omit \`table\`) unless you truly need a single table only.
113- Use **execute_typescript** with TypeScript that calls \`external_queryTable\` / \`external_getSchemaInfo\` to load rows, join across tables, and compute answers. Do not try to answer from schema alone.
114- After the script returns, write a clear final answer (tables, numbers, short summary).
115- If something is ambiguous, state assumptions briefly.
116
117## Critical: \`external_queryTable\` (read this — common failures)
118
119This is **not** SQL and **not** a raw string. You must pass a single **object** with a \`table\` field:
120
121\`\`\`typescript
122const purchases = await external_queryTable({ table: 'purchases' })
123// Result shape: { rows: Array<Record<string, unknown>>, totalMatchingRows: number }
124for (const row of purchases.rows) { /* ... */ }
125\`\`\`
126
127- Valid \`table\` values: \`customers\` | \`products\` | \`purchases\` only.
128- **Never** pass SQL, \`query:\`, \`sql:\`, or iterate the return value directly — use \`.rows\`.
129- \`external_getSchemaInfo\` takes \`{}\` for all tables or \`{ table: 'products' }\` for one table.
130
131Put **only valid TypeScript** in \`typescriptCode\`: no markdown fences (\`\`\`), no \`**\` headings inside the code string.`
132
133interface GoldMessagePart {
134 type: string
135 content?: string
136}
137
138interface GoldMessage {
139 role: string
140 parts?: Array<GoldMessagePart>
141}
142
143interface GoldFile {
144 prompt: string
145 messages: Array<GoldMessage>
146}
147
148function loadGoldFile(): GoldFile {
149 const path = join(__dirname, 'gold-results', 'db-gold-messages-1.json')
150 const raw = readFileSync(path, 'utf8')
151 return JSON.parse(raw) as GoldFile
152}
153
154function extractReportTextFromGold(messages: Array<GoldMessage>): string {
155 return messages
156 .filter((m) => m.role === 'assistant')
157 .flatMap((m) =>
158 (m.parts ?? [])
159 .filter((p) => p.type === 'text' && p.content)
160 .map((p) => p.content as string),
161 )
162 .join('\n\n')
163}
164
165/** Same text extraction as the web demo / gold file, from StreamProcessor UIMessages. */
166function extractAssistantReportText(messages: Array<UIMessage>): string {
167 return messages
168 .filter((m) => m.role === 'assistant')
169 .flatMap((m) =>
170 m.parts.filter((p) => p.type === 'text').map((p) => p.content),
171 )
172 .join('\n\n')
173}
174
175let codeModeCache: {
176 tool: ReturnType<typeof createCodeMode>['tool']
177 systemPrompt: string
178} | null = null
179
180function getCodeModeTools() {
181 if (!codeModeCache) {
182 const driver = createNodeIsolateDriver()
183 const { tool, systemPrompt } = createCodeMode({
184 driver,
185 tools: databaseTools,
186 timeout: 60000,
187 memoryLimit: 128,
188 })
189 codeModeCache = { tool, systemPrompt }
190 }
191 return codeModeCache
192}
193
194function getTextAdapter(
195 provider: EvalProvider,
196 modelId: string,
197): AnyTextAdapter {
198 switch (provider) {
199 case 'ollama':
200 return ollamaText(modelId)
201 case 'openai':
202 return openaiText(modelId as 'gpt-4o-mini')
203 case 'anthropic':
204 return anthropicText(modelId as 'claude-haiku-4-5')
205 case 'gemini':
206 return geminiText(modelId as 'gemini-2.5-flash')
207 case 'grok':
208 return grokText(modelId as 'grok-build-0.1')
209 case 'groq':
210 return groqText(modelId as 'llama-3.3-70b-versatile')
211 }
212}
213
214/**
215 * The max-output-tokens cap lives in provider-native `modelOptions` keys (the
216 * root `maxTokens` field was removed from core `TextOptions`). The key name
217 * differs per provider. Ollama also keeps its larger context window via
218 * `num_ctx`.
219 */
220function maxTokensModelOptions(
221 provider: EvalProvider,
222 maxTokens: number,
223): Record<string, unknown> {
224 switch (provider) {
225 case 'ollama':
226 // Ollama reads sampling/runner params from the nested `options` key, not
227 // the top level of `modelOptions`. Flat keys here would be silently
228 // dropped at the wire.
229 return { options: { num_predict: maxTokens, num_ctx: 32768 } }
230 case 'openai':
231 case 'grok':
232 return { max_output_tokens: maxTokens }
233 case 'anthropic':
234 return { max_tokens: maxTokens }
235 case 'gemini':
236 return { maxOutputTokens: maxTokens }
237 case 'groq':
238 return { max_completion_tokens: maxTokens }
239 }
240}
241
242interface EvalRow {
243 name: string
244 /** Full `provider:model` id */
245 model: string
246 provider: EvalProvider
247 modelId: string
248 modelCategory: ModelCategory
249 durationMs: number
250 ttftMs?: number
251 promptTokens: number
252 completionTokens: number
253 totalTokens: number
254 tokenEfficiency?: number
255 speedTier: number
256 tokenEfficiencyTier: number
257 stabilityTier: number
258 stabilityRate: number
259 stabilitySampleSize: number
260 totalToolCalls: number
261 totalExecuteCalls: number
262 successfulExecuteCalls: number
263 compilationFailures: number
264 runtimeFailures: number
265 redundantSchemaChecks: number
266 stars?: 1 | 2 | 3
267 weightedScore?: number
268 error?: string
269 judge?: JudgeResult
270}
271
272function parseArgs(argv: Array<string>): {
273 ollamaOnly: boolean
274 noJudge: boolean
275 captureOnly: boolean
276 judgeLatest: boolean
277 rejudge: boolean
278 /** If set, only run entries whose \`model\` is in this list */
279 modelFilter: Set<string> | null
280} {
281 let ollamaOnly = false
282 let noJudge = false
283 let captureOnly = false
284 let judgeLatest = false
285 let rejudge = false
286 let modelFilter: Set<string> | null = null
287
288 for (let i = 0; i < argv.length; i++) {
289 const a = argv[i]
290 if (a === '--ollama-only' || a === '--ollama') ollamaOnly = true
291 if (a === '--no-judge') noJudge = true
292 if (a === '--capture-only') captureOnly = true
293 if (a === '--judge-latest') judgeLatest = true
294 if (a === '--rejudge') rejudge = true
295 if (a === '--models' || a === '--model') {
296 const raw = argv[i + 1]
297 if (raw && !raw.startsWith('--')) {
298 i += 1
299 const ids = raw
300 .split(',')
301 .map((s) => s.trim())
302 .filter(Boolean)
303 modelFilter = new Set(ids)
304 }
305 }
306 if (a === '--help' || a === '-h') {
307 console.log(`
308@tanstack/ai-code-mode-models-eval (pnpm eval from this folder, or pnpm --filter @tanstack/ai-code-mode-models-eval eval)
309
310 --ollama-only Only run Ollama models from eval-config
311 --models <id> Comma-separated provider:model ids (e.g. openai:gpt-4o,groq:qwen/qwen3-32b)
312 --capture-only Run models and write logs without LLM judging
313 --judge-latest Judge latest captured session from logs (no model runs)
314 --rejudge Re-judge logs even if judge fields already exist
315 --no-judge Skip LLM judging (no ANTHROPIC_API_KEY needed)
316 --help This message
317`)
318 process.exit(0)
319 }
320 }
321 return {
322 ollamaOnly,
323 noJudge,
324 captureOnly,
325 judgeLatest,
326 rejudge,
327 modelFilter,
328 }
329}
330
331function slugForFilename(model: string): string {
332 return model.replace(/[/\\:*?"<>|]/g, '-').replace(/\s+/g, '_')
333}
334
335interface RunLogPayload {
336 writtenAt: string
337 sessionStartedAt: string
338 entry: { name: string; model: string }
339 query: string
340 durationMs: number
341 ttftMs?: number
342 modelCategory: ModelCategory
343 promptTokens: number
344 completionTokens: number
345 totalTokens: number
346 tokenEfficiency?: number
347 speedTier: number
348 tokenEfficiencyTier: number
349 stabilityTier: number
350 stabilityRate: number
351 stabilitySampleSize: number
352 totalToolCalls: number
353 totalExecuteCalls: number
354 successfulExecuteCalls: number
355 compilationFailures: number
356 runtimeFailures: number
357 redundantSchemaChecks: number
358 stars?: 1 | 2 | 3
359 weightedScore?: number
360 candidateReportChars: number
361 candidateReportEmpty: boolean
362 goldReportChars: number
363 error?: string
364 judge?: JudgeResult
365 noJudge: boolean
366 goldReport: string
367 candidateReport: string
368 /** Full conversation as UIMessage[] (user + assistant turns, tool calls, tool results). */
369 messages: Array<UIMessage>
370}
371
372interface CanonicalResultsFile {
373 generatedAt: string
374 sessionStartedAt: string
375 methodology: {
376 benchmark: string
377 scoring: Array<string>
378 stability: string
379 starWeights: Record<string, number>
380 }
381 models: Array<EvalRow>
382}
383
384function writeRunLog(payload: RunLogPayload): string {
385 mkdirSync(LOG_DIR, { recursive: true })
386 const stamp = new Date().toISOString().replace(/[:.]/g, '-')
387 const fileName = `${stamp}_${slugForFilename(payload.entry.model)}.json`
388 const filePath = join(LOG_DIR, fileName)
389 writeFileSync(filePath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
390 return filePath
391}
392
393function toEvalRow(payload: RunLogPayload): EvalRow {
394 const { provider, modelId } = parseModelId(payload.entry.model)
395 return {
396 name: payload.entry.name,
397 model: payload.entry.model,
398 provider,
399 modelId,
400 modelCategory: payload.modelCategory,
401 durationMs: payload.durationMs,
402 ttftMs: payload.ttftMs,
403 promptTokens: payload.promptTokens,
404 completionTokens: payload.completionTokens,
405 totalTokens: payload.totalTokens,
406 tokenEfficiency: payload.tokenEfficiency,
407 speedTier: payload.speedTier,
408 tokenEfficiencyTier: payload.tokenEfficiencyTier,
409 stabilityTier: payload.stabilityTier,
410 stabilityRate: payload.stabilityRate,
411 stabilitySampleSize: payload.stabilitySampleSize,
412 totalToolCalls: payload.totalToolCalls,
413 totalExecuteCalls: payload.totalExecuteCalls,
414 successfulExecuteCalls: payload.successfulExecuteCalls,
415 compilationFailures: payload.compilationFailures,
416 runtimeFailures: payload.runtimeFailures,
417 redundantSchemaChecks: payload.redundantSchemaChecks,
418 stars: payload.stars,
419 weightedScore: payload.weightedScore,
420 error: payload.error,
421 judge: payload.judge,
422 }
423}
424
425function isStableRun(payload: RunLogPayload): boolean {
426 if (payload.error) return false
427 if (payload.candidateReportEmpty) return false
428 return payload.successfulExecuteCalls > 0
429}
430
431function applyStability(rows: Array<EvalRow>, allLogs: Array<RunLogPayload>) {
432 const byModel = new Map<string, Array<RunLogPayload>>()
433 for (const log of allLogs) {
434 const list = byModel.get(log.entry.model) ?? []
435 list.push(log)
436 byModel.set(log.entry.model, list)
437 }
438
439 for (const row of rows) {
440 const history = (byModel.get(row.model) ?? [])
441 .sort((a, b) => b.writtenAt.localeCompare(a.writtenAt))
442 .slice(0, 5)
443 const sampleSize = history.length
444 const stableCount = history.filter(isStableRun).length
445 const rate = sampleSize > 0 ? stableCount / sampleSize : 0
446 const tier = Math.max(1, Math.min(5, Math.round(rate * 4 + 1)))
447 row.stabilitySampleSize = sampleSize
448 row.stabilityRate = Number(rate.toFixed(2))
449 row.stabilityTier = tier
450 }
451}
452
453function finalizeRows(rows: Array<EvalRow>, allLogs: Array<RunLogPayload>) {
454 applyStability(rows, allLogs)
455
456 bucketedTiers(
457 rows,
458 (row) => row.durationMs,
459 (row, tier) => {
460 row.speedTier = tier
461 },
462 true,
463 )
464 bucketedTiers(
465 rows,
466 (row) => row.tokenEfficiency,
467 (row, tier) => {
468 row.tokenEfficiencyTier = tier
469 },
470 true,
471 )
472
473 for (const row of rows) {
474 if (!row.judge) continue
475 const rating = computeStarRating({
476 accuracy: row.judge.accuracy,
477 comprehensiveness: row.judge.comprehensiveness,
478 typescriptQuality: row.judge.typescriptQuality,
479 codeModeEfficiency: row.judge.codeModeEfficiency,
480 speedTier: row.speedTier,
481 tokenEfficiencyTier: row.tokenEfficiencyTier,
482 stabilityTier: row.stabilityTier,
483 compilationFailures: row.compilationFailures,
484 runtimeFailures: row.runtimeFailures,
485 totalExecuteCalls: row.totalExecuteCalls,
486 })
487 row.stars = rating.stars
488 row.weightedScore = rating.weightedScore
489 }
490}
491
492function listRunLogFiles(): Array<string> {
493 if (!existsSync(LOG_DIR)) return []
494 return readdirSync(LOG_DIR)
495 .filter(
496 (name) => name.endsWith('.json') && !name.startsWith('results-summary-'),
497 )
498 .map((name) => join(LOG_DIR, name))
499}
500
501function readRunLog(path: string): RunLogPayload | null {
502 try {
503 const raw = readFileSync(path, 'utf8')
504 return JSON.parse(raw) as RunLogPayload
505 } catch {
506 return null
507 }
508}
509
510async function judgeLatestSession(rejudge: boolean): Promise<void> {
511 const files = listRunLogFiles()
512 const payloads = files
513 .map((path) => ({ path, payload: readRunLog(path) }))
514 .filter(
515 (entry): entry is { path: string; payload: RunLogPayload } =>
516 !!entry.payload,
517 )
518
519 if (payloads.length === 0) {
520 console.error('[models-eval] No run logs found to judge.')
521 process.exit(1)
522 }
523
524 const latestSession = payloads
525 .map((entry) => entry.payload.sessionStartedAt)
526 .sort()
527 .at(-1)
528 if (!latestSession) {
529 console.error('[models-eval] Could not determine latest session.')
530 process.exit(1)
531 }
532
533 const sessionPayloads = payloads.filter(
534 (entry) => entry.payload.sessionStartedAt === latestSession,
535 )
536 const rows: Array<EvalRow> = []
537
538 for (const entry of sessionPayloads) {
539 const payload = entry.payload
540 if (payload.error) {
541 rows.push(toEvalRow(payload))
542 continue
543 }
544 if (payload.judge && !rejudge) {
545 rows.push(toEvalRow(payload))
546 continue
547 }
548
549 const computed = computeMetrics(payload.messages)
550 const judged = await judgeReports({
551 query: payload.query,
552 goldReport: payload.goldReport,
553 candidateReport: payload.candidateReport,
554 typescriptEvidence: formatTypescriptEvidence(computed.typeScriptAttempts),
555 })
556 payload.judge = judged
557 payload.noJudge = false
558
559 writeFileSync(entry.path, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
560 rows.push(toEvalRow(payload))
561 console.log(` ✓ judged from log: ${payload.entry.model}`)
562 }
563
564 finalizeRows(
565 rows,
566 payloads.map((p) => p.payload),
567 )
568 const summaryPath = writeResultsSummary(rows, latestSession)
569 const canonicalPath = writeCanonicalResults(rows, latestSession)
570 printTable(rows)
571 console.log(
572 `[models-eval] Summary JSON → ${relative(process.cwd(), summaryPath) || summaryPath}`,
573 )
574 console.log(
575 `[models-eval] Canonical results → ${relative(process.cwd(), canonicalPath) || canonicalPath}`,
576 )
577}
578
579function writeResultsSummary(
580 rows: Array<EvalRow>,
581 sessionStartedAt: string,
582): string {
583 const path = join(
584 LOG_DIR,
585 `results-summary-${sessionStartedAt.replace(/[:.]/g, '-')}.json`,
586 )
587 writeFileSync(
588 path,
589 `${JSON.stringify(
590 {
591 sessionStartedAt,
592 createdAt: new Date().toISOString(),
593 rows,
594 },
595 null,
596 2,
597 )}\n`,
598 'utf8',
599 )
600 return path
601}
602
603function writeCanonicalResults(
604 rows: Array<EvalRow>,
605 sessionStartedAt: string,
606): string {
607 const path = join(__dirname, 'results.json')
608 const payload: CanonicalResultsFile = {
609 generatedAt: new Date().toISOString(),
610 sessionStartedAt,
611 methodology: {
612 benchmark:
613 'Single benchmark prompt over in-memory customers/products/purchases dataset with code-mode execute_typescript tooling.',
614 scoring: [
615 'accuracy (1-10): factual correctness vs gold reference',
616 'comprehensiveness (1-10): complete coverage of user request',
617 'typescriptQuality (1-10): quality and clarity of generated TypeScript',
618 'codeModeEfficiency (1-10): effectiveness and step efficiency in tool/code usage',
619 'speedTier (1-5): relative wall-clock performance bucketed by local/cloud',
620 'tokenEfficiencyTier (1-5): relative tokens-per-successful-execution bucketed by local/cloud',
621 'stabilityTier (1-5): success consistency over latest 5 logged runs per model',
622 ],
623 stability:
624 'Stable run means: no top-level error, non-empty candidate report, and at least one successful execute_typescript call.',
625 starWeights: {
626 accuracy: 0.25,
627 comprehensiveness: 0.15,
628 typescriptQuality: 0.15,
629 codeModeEfficiency: 0.1,
630 speedTier: 0.1,
631 tokenEfficiencyTier: 0.1,
632 stabilityTier: 0.15,
633 },
634 },
635 models: rows,
636 }
637 writeFileSync(path, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
638 return path
639}
640
641function teeStream(
642 stream: AsyncIterable<StreamChunk>,
643 onChunk: (chunk: StreamChunk) => void,
644): AsyncIterable<StreamChunk> {
645 return {
646 async *[Symbol.asyncIterator]() {
647 for await (const chunk of stream) {
648 onChunk(chunk)
649 yield chunk
650 }
651 },
652 }
653}
654
655function bucketedTiers(
656 rows: Array<EvalRow>,
657 getter: (row: EvalRow) => number | undefined,
658 setter: (row: EvalRow, tier: number) => void,
659 lowerIsBetter: boolean,
660) {
661 for (const category of ['local', 'cloud'] as const) {
662 const bucket = rows.filter((r) => r.modelCategory === category)
663 const values = bucket
664 .map((r) => ({ row: r, value: getter(r) }))
665 .filter(
666 (r): r is { row: EvalRow; value: number } =>
667 typeof r.value === 'number',
668 )
669
670 if (values.length === 0) continue
671 const min = Math.min(...values.map((v) => v.value))
672 const max = Math.max(...values.map((v) => v.value))
673
674 for (const entry of values) {
675 if (max === min) {
676 setter(entry.row, 5)
677 continue
678 }
679 const normalized = lowerIsBetter
680 ? (max - entry.value) / (max - min)
681 : (entry.value - min) / (max - min)
682 const tier = Math.round(1 + normalized * 4)
683 setter(entry.row, Math.max(1, Math.min(5, tier)))
684 }
685 }
686}
687
688function printTable(rows: Array<EvalRow>) {
689 console.log('\n=== Results ===\n')
690 const nameW = 22
691 const modelW = 38
692 const starsW = 5
693 const accW = 4
694 const compW = 4
695 const tsW = 3
696 const cmW = 3
697 const msW = 8
698
699 const header = `${'Model'.padEnd(nameW)} ${'Id'.padEnd(modelW)} ${'★'.padStart(starsW)} ${'ms'.padStart(msW)} ${'Acc'.padStart(accW)} ${'Cmp'.padStart(compW)} ${'TS'.padStart(tsW)} ${'CME'.padStart(cmW)} ${'Spd'.padStart(3)} ${'Tok'.padStart(3)} ${'Stb'.padStart(3)} Error / summary`
700 console.log(header)
701 console.log('-'.repeat(header.length + 10))
702
703 for (const r of rows) {
704 const acc = r.judge?.accuracy !== undefined ? String(r.judge.accuracy) : '-'
705 const comp =
706 r.judge?.comprehensiveness !== undefined
707 ? String(r.judge.comprehensiveness)
708 : '-'
709 const tsq =
710 r.judge?.typescriptQuality !== undefined
711 ? String(r.judge.typescriptQuality)
712 : '-'
713 const cme =
714 r.judge?.codeModeEfficiency !== undefined
715 ? String(r.judge.codeModeEfficiency)
716 : '-'
717 const stars = r.stars
718 ? `${'★'.repeat(r.stars)}${'☆'.repeat(3 - r.stars)}`
719 : '-'
720 const err = r.error || ''
721 const summary = r.judge?.summary
722 ? r.judge.summary.replace(/\s+/g, ' ').slice(0, 120)
723 : ''
724 const tail = err || summary
725 console.log(
726 `${r.name.slice(0, nameW - 1).padEnd(nameW)} ${r.model.slice(0, modelW - 1).padEnd(modelW)} ${stars.padStart(starsW)} ${String(r.durationMs).padStart(msW)} ${acc.padStart(accW)} ${comp.padStart(compW)} ${tsq.padStart(tsW)} ${cme.padStart(cmW)} ${String(r.speedTier).padStart(3)} ${String(r.tokenEfficiencyTier).padStart(3)} ${String(r.stabilityTier).padStart(3)} ${tail}`,
727 )
728 }
729 console.log('')
730}
731
732async function main() {
733 const {
734 ollamaOnly,
735 noJudge,
736 captureOnly,
737 judgeLatest,
738 rejudge,
739 modelFilter,
740 } = parseArgs(process.argv.slice(2))
741
742 mkdirSync(LOG_DIR, { recursive: true })
743 if (judgeLatest) {
744 await judgeLatestSession(rejudge)
745 return
746 }
747
748 const effectiveNoJudge = noJudge || captureOnly
749 const sessionStartedAt = new Date().toISOString()
750 console.log(
751 `[models-eval] Run logs → ${relative(process.cwd(), LOG_DIR) || LOG_DIR} (gitignored)`,
752 )
753
754 if (!effectiveNoJudge && !process.env.ANTHROPIC_API_KEY) {
755 console.warn(
756 '[models-eval] ANTHROPIC_API_KEY is not set; judging will fail. Use --no-judge to skip, or set the key.',
757 )
758 }
759
760 const gold = loadGoldFile()
761 const query = gold.prompt
762 const goldReport = extractReportTextFromGold(gold.messages)
763
764 const { tool, systemPrompt } = getCodeModeTools()
765 const tools = [tool, getSchemaInfoTool]
766 const systemPrompts = [DATABASE_DEMO_SYSTEM_PROMPT, systemPrompt]
767
768 let models = ollamaOnly
769 ? EVAL_MODELS.filter((m) => m.model.startsWith('ollama:'))
770 : EVAL_MODELS
771
772 if (modelFilter && modelFilter.size > 0) {
773 models = models.filter((m) => modelFilter.has(m.model))
774 if (models.length === 0) {
775 console.error(
776 '[models-eval] No models matched --models filter. Check eval-config model ids.',
777 )
778 process.exit(1)
779 }
780 }
781
782 const rows: Array<EvalRow> = []
783
784 for (const entry of models) {
785 const { provider, modelId } = parseModelId(entry.model)
786 const modelCategory = getModelCategory(entry.model)
787 console.log(`\n→ Running: ${entry.name} (${entry.model})`)
788 const adapter = getTextAdapter(provider, modelId)
789 const t0 = Date.now()
790 let durationMs = 0
791 let ttftMs: number | undefined
792 let promptTokens = 0
793 let completionTokens = 0
794 let totalTokens = 0
795 let candidateReport = ''
796 let messagesLog: Array<UIMessage> = []
797 let error: string | undefined
798
799 const userMessage = normalizeToUIMessage(
800 { role: 'user', content: query },
801 generateMessageId,
802 )
803 const processor = new StreamProcessor({
804 initialMessages: [userMessage],
805 })
806
807 try {
808 const stream = chat({
809 adapter,
810 messages: [
811 {
812 role: 'user',
813 content: query,
814 },
815 ],
816 tools,
817 systemPrompts,
818 agentLoopStrategy: maxIterations(15),
819 // Sampling now lives in provider-native `modelOptions` keys rather
820 // than the removed root `maxTokens`. The max-output-tokens key name
821 // differs per provider.
822 modelOptions: maxTokensModelOptions(provider, 8192),
823 })
824 await processor.process(
825 teeStream(stream, (chunk) => {
826 if (chunk.type === 'TEXT_MESSAGE_CONTENT' && ttftMs === undefined) {
827 ttftMs = Date.now() - t0
828 }
829 if (chunk.type === 'RUN_FINISHED' && chunk.usage) {
830 // Usage is now either the spec `usage[]` array or a TokenUsage.
831 // Normalize both to TokenUsage before summing.
832 const usage = Array.isArray(chunk.usage)
833 ? fromSpecTokenUsage(chunk.usage)
834 : chunk.usage
835 if (usage) {
836 promptTokens += usage.promptTokens
837 completionTokens += usage.completionTokens
838 totalTokens += usage.totalTokens
839 }
840 }
841 }),
842 )
843 messagesLog = processor.getMessages()
844 candidateReport = extractAssistantReportText(messagesLog)
845 durationMs = Date.now() - t0
846 } catch (e) {
847 durationMs = Date.now() - t0
848 messagesLog = processor.getMessages()
849 error = e instanceof Error ? e.message : String(e)
850 console.error(` ✗ ${error}`)
851 }
852
853 const computed = computeMetrics(messagesLog)
854 const tokenEfficiency =
855 computed.successfulExecuteCalls > 0
856 ? Number((totalTokens / computed.successfulExecuteCalls).toFixed(2))
857 : undefined
858
859 let judge: JudgeResult | undefined
860 if (!error && !effectiveNoJudge) {
861 try {
862 judge = await judgeReports({
863 query,
864 goldReport,
865 candidateReport,
866 typescriptEvidence: formatTypescriptEvidence(
867 computed.typeScriptAttempts,
868 ),
869 })
870 console.log(
871 ` ✓ judged: accuracy=${judge.accuracy} comprehensiveness=${judge.comprehensiveness} typescriptQuality=${judge.typescriptQuality} codeModeEfficiency=${judge.codeModeEfficiency} (${durationMs}ms)`,
872 )
873 } catch (e) {
874 const msg = e instanceof Error ? e.message : String(e)
875 error = error ? `${error}; judge: ${msg}` : `judge: ${msg}`
876 console.error(` ✗ judge failed: ${msg}`)
877 }
878 } else if (!error && effectiveNoJudge) {
879 console.log(
880 ` ✓ done (${durationMs}ms, ${captureOnly ? '--capture-only' : '--no-judge'})`,
881 )
882 }
883
884 const logPayload: RunLogPayload = {
885 writtenAt: new Date().toISOString(),
886 sessionStartedAt,
887 entry: {
888 name: entry.name,
889 model: entry.model,
890 },
891 query,
892 durationMs,
893 ttftMs,
894 modelCategory,
895 promptTokens,
896 completionTokens,
897 totalTokens,
898 tokenEfficiency,
899 speedTier: 1,
900 tokenEfficiencyTier: 1,
901 stabilityTier: 1,
902 stabilityRate: 0,
903 stabilitySampleSize: 0,
904 totalToolCalls: computed.totalToolCalls,
905 totalExecuteCalls: computed.totalExecuteCalls,
906 successfulExecuteCalls: computed.successfulExecuteCalls,
907 compilationFailures: computed.compilationFailures,
908 runtimeFailures: computed.runtimeFailures,
909 redundantSchemaChecks: computed.redundantSchemaChecks,
910 candidateReportChars: candidateReport.length,
911 candidateReportEmpty: candidateReport.trim().length === 0,
912 goldReportChars: goldReport.length,
913 error,
914 judge,
915 noJudge: effectiveNoJudge,
916 goldReport,
917 candidateReport,
918 messages: messagesLog,
919 }
920
921 const logPath = writeRunLog(logPayload)
922 const logRel = relative(process.cwd(), logPath) || logPath
923 console.log(` 📄 ${logRel}`)
924
925 rows.push({
926 name: entry.name,
927 model: entry.model,
928 provider,
929 modelId,
930 modelCategory,
931 durationMs,
932 ttftMs,
933 promptTokens,
934 completionTokens,
935 totalTokens,
936 tokenEfficiency,
937 speedTier: 1,
938 tokenEfficiencyTier: 1,
939 stabilityTier: 1,
940 stabilityRate: 0,
941 stabilitySampleSize: 0,
942 totalToolCalls: computed.totalToolCalls,
943 totalExecuteCalls: computed.totalExecuteCalls,
944 successfulExecuteCalls: computed.successfulExecuteCalls,
945 compilationFailures: computed.compilationFailures,
946 runtimeFailures: computed.runtimeFailures,
947 redundantSchemaChecks: computed.redundantSchemaChecks,
948 error,
949 judge,
950 })
951 }
952
953 const allLogs = listRunLogFiles()
954 .map((path) => readRunLog(path))
955 .filter((log): log is RunLogPayload => !!log)
956 finalizeRows(rows, allLogs)
957 const summaryPath = writeResultsSummary(rows, sessionStartedAt)
958 const canonicalPath = writeCanonicalResults(rows, sessionStartedAt)
959 printTable(rows)
960 console.log(
961 `[models-eval] Summary JSON → ${relative(process.cwd(), summaryPath) || summaryPath}`,
962 )
963 console.log(
964 `[models-eval] Canonical results → ${relative(process.cwd(), canonicalPath) || canonicalPath}`,
965 )
966}
967
968main().catch((e) => {
969 console.error(e)
970 process.exit(1)
971})