Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

gap-report.ts

192 lines5.9 KB

1/**
2 * Gap report: which facts `@tanstack/ai-models` needs are still missing,
3 * per provider and activity, with origin-link coverage. One HTTP request;
4 * no per-model detail calls.
5 *
6 * pnpm run gap:report # JSON
7 * pnpm run gap:report -- --table # readable, worst score first
8 * pnpm run gap:report -- --base http://localhost:3100
9 * pnpm run gap:report -- --check --providers grok,mistral --target 0.9
10 *
11 * `docs/source-silent/<provider>.md` lists facts a provider does not publish; those
12 * are left out of that provider's score and listed under `silent`. `flags`
13 * lists rows whose stored shape is wrong; flags do not change the score.
14 */
15import { existsSync, readFileSync, readdirSync } from 'node:fs'
16import { join } from 'node:path'
17import { parseArgs } from 'node:util'
18​
19import {
20 ACTIVITY_FACTS,
21 CHAT_FACT_KEYS,
22 FLAG_KEYS,
23 UNCLASSIFIED,
24 buildReport,
25 parseLedger,
26} from '../src/lib/completeness.ts'
27import type {
28 FactKey,
29 GapReport,
30 Ledger,
31 ModelRow,
32 ProviderReport,
33} from '../src/lib/completeness.ts'
34​
35// The scoring itself is shared with `GET /v1/status`.
36export * from '../src/lib/completeness.ts'
37​
38const LEDGER_DIR = join(import.meta.dirname, '..', 'docs', 'source-silent')
39​
40/** The on-disk ledger; the Worker bundles the same files (`source-silent.ts`). */
41export function readLedger(dir = LEDGER_DIR): Ledger | undefined {
42 if (!existsSync(dir)) return undefined
43 return parseLedger(
44 readdirSync(dir)
45 .filter((file) => file.endsWith('.md') && file !== 'README.md')
46 .map((file) => readFileSync(join(dir, file), 'utf8'))
47 .join('\n'),
48 )
50​
51/** Providers below `target`. With no `names`, every scored provider. */
52export function failing(
53 report: GapReport,
54 target: number,
55 names?: Array<string>,
56): Array<string> {
57 if (!names) {
58 return report.providers
59 .filter((p) => p.score != null && p.score < target)
60 .map((p) => p.provider)
61 }
62 const scores = new Map(report.providers.map((p) => [p.provider, p.score]))
63 // A named provider with no rows at all fails. A provider that does not
64 // has nothing scored scores null and is not below target.
65 return names.filter((name) => {
66 const score = scores.get(name)
67 if (score === undefined) return true
68 if (score === null) return false
69 return score < target
70 })
72​
73const MEDIA = ['image', 'video', 'audio'] as const
74const MEDIA_FACT_KEYS: ReadonlyArray<FactKey> = ACTIVITY_FACTS.image
75const pct = (score: number | null | undefined) =>
76 score == null ? 'n/a' : score.toFixed(2)
77​
78/** `have/need` summed over `activities`, or `silent`. */
79function factCell(
80 p: ProviderReport,
81 key: FactKey,
82 activities: ReadonlyArray<string>,
83): string {
84 if (p.silent.includes(key)) return 'silent'
85 let have = 0
86 let need = 0
87 let modelSilent = 0
88 for (const name of activities) {
89 const a = p.activities[name]
90 have += a?.facts?.[key]?.have ?? 0
91 need += a?.facts?.[key]?.need ?? 0
92 modelSilent += a?.modelSilent[key] ?? 0
93 }
94 return `${have}/${need}${modelSilent ? ` (${modelSilent} model-silent)` : ''}`
96​
97/** Rows in activities with no fact set, which are listed but not scored. */
98const unscoredRows = (p: ProviderReport) =>
99 Object.values(p.activities).reduce(
100 (sum, a) => sum + (a && a.facts === null ? a.rows : 0),
101 0,
102 )
103​
104export function formatTable(report: GapReport): string {
105 const header = [
106 'provider',
107 'score',
108 'rows',
109 'chat',
110 ...MEDIA,
111 'noAct',
112 'unscored',
113 'originLink',
114 'm.dev',
115 ...CHAT_FACT_KEYS,
116 ...MEDIA_FACT_KEYS.map((key) => `media.${key}`),
117 ...FLAG_KEYS,
118 ]
119 const body = report.providers.map((p) => [
120 p.provider,
121 pct(p.score),
122 String(p.rows),
123 ...(['chat', ...MEDIA] as const).map((name) => {
124 const a = p.activities[name]
125 return a ? `${pct(a.score)} (${a.rows})` : '-'
126 }),
127 String(p.activities[UNCLASSIFIED]?.rows ?? 0),
128 String(unscoredRows(p)),
129 p.silent.includes('originLink')
130 ? 'silent'
131 : `${p.originLink.have}/${p.originLink.need}`,
132 String(p.fromModelsDev),
133 ...CHAT_FACT_KEYS.map((key) => factCell(p, key, ['chat'])),
134 ...MEDIA_FACT_KEYS.map((key) => factCell(p, key, MEDIA)),
135 ...FLAG_KEYS.map((key) => String(p.flags[key].length)),
136 ])
137 const width = (i: number) =>
138 Math.max(...[header, ...body].map((line) => line[i]?.length ?? 0))
139 return [header, ...body]
140 .map((line) =>
141 line
142 .map((cell, i) =>
143 i === 0 ? cell.padEnd(width(i)) : cell.padStart(width(i)),
144 )
145 .join(' '),
146 )
147 .join('\n')
149​
150export async function main(
151 argv: Array<string> = process.argv.slice(2),
152): Promise<number> {
153 const { values } = parseArgs({
154 // pnpm 11 passes `pnpm run gap:report -- --table` through with the `--`.
155 args: argv[0] === '--' ? argv.slice(1) : argv,
156 options: {
157 base: { type: 'string', default: 'https://modelschemas.com' },
158 table: { type: 'boolean', default: false },
159 check: { type: 'boolean', default: false },
160 providers: { type: 'string' },
161 target: { type: 'string', default: '1' },
162 },
163 })
164 const target = Number(values.target)
165 if (!(target >= 0 && target <= 1)) {
166 throw new Error(`--target must be between 0 and 1, got "${values.target}"`)
167 }
168​
169 const url = new URL('/v1/models?pricing=1&limit=20000', values.base)
170 const response = await fetch(url)
171 if (!response.ok) throw new Error(`GET ${url.href} → ${response.status}`)
172 const { models } = (await response.json()) as { models: Array<ModelRow> }
173​
174 const report = buildReport(models, readLedger())
175​
176 console.log(
177 values.table ? formatTable(report) : JSON.stringify(report, null, 2),
178 )
179​
180 if (!values.check) return 0
181 const names = values.providers?.split(',').filter(Boolean)
182 const below = failing(report, target, names)
183 if (below.length > 0) {
184 console.error(`below target ${target}: ${below.join(', ')}`)
185 return 1
186 }
187 return 0
189​
190if (import.meta.main) {
191 process.exit(await main())