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

completeness.ts

384 lines12.2 KB

1/**
2 * Completeness: the share of the chat facts `@tanstack/ai-models` needs that
3 * a provider's rows carry. The one definition behind `pnpm run gap:report`
4 * (`scripts/gap-report.ts`) and `completeness` on `GET /v1/status`, so the
5 * CLI and the site cannot disagree. No Node or Workers dependencies.
6 *
7 * `docs/source-silent/<provider>.md` lists facts a provider does not publish;
8 * those are left out of that provider's score and listed under `silent`.
9 */
10import { isCapabilityMap, supportedFlags } from './capabilities.ts'
11import { modelLedgerScope, parseLedgerEntry } from './source-silence-ledger.ts'
12​
13export const FACT_KEYS = [
14 'contextWindow',
15 'maxOutput',
16 'modalities',
17 'priced',
18 'cacheRead',
19 'capabilities',
20 'reasoning',
21 'efforts',
22 'requestMap',
23 'endpoint',
24 'replayReasoningContent',
25] as const
26​
27export type FactKey = (typeof FACT_KEYS)[number]
28​
29/**
30 * Row shapes `@tanstack/ai-models` cannot read correctly, counted apart from
31 * the score (issue #323). The score counts a fact as filled; a flag says the
32 * stored value still leaves the catalog to guess.
33 */
34export const FLAG_KEYS = [
35 'mandatoryUnknown',
36 'reasoningUnknown',
37 'outputModalitiesEmpty',
38 'mandatoryWithNone',
39] as const
40​
41export type FlagKey = (typeof FLAG_KEYS)[number]
42​
43/** The fields of a `/v1/models` row the report reads. */
44export type ModelRow = {
45 provider: string
46 /** Exact native model id, never the slugged catalog id. */
47 rawId?: string
48 activity?: string | null
49 contextWindow?: number | null
50 maxOutput?: number | null
51 modalities?: { input?: unknown; output?: unknown } | null
52 pricing?: {
53 tables?: { rate?: Record<string, unknown> }
54 source?: { url?: string }
55 } | null
56 capabilities?: unknown
57 reasoning?: {
58 mode?: string
59 mandatory?: boolean | null
60 efforts?: Array<string>
61 } | null
62 requestMap?: unknown
63 schemaEndpointId?: string | null
64 /**
65 * `cacheRead.path === 'not-offered'` is a stated absence: the provider's
66 * pricing table shows a cached-input cell that is "-" or blank. That
67 * fills the fact. It is not a price.
68 */
69 factSources?: {
70 cacheRead?: { path?: string } | null
71 } | null
73​
74export type ProviderReport = {
75 provider: string
76 rows: number
77 chat: number
78 noActivity: number
79 fromModelsDev: number
80 facts: Record<FactKey, { have: number; need: number }>
81 silent: Array<FactKey>
82 /** Applicable missing rows excluded by exact model-scoped evidence. */
83 modelSilent?: Partial<Record<FactKey, number>>
84 /**
85 * 0 to 1. Null when the provider does not serve chat: every row has a
86 * non-chat activity. 0 when it serves chat but classification produced
87 * no chat rows (an activity is null).
88 */
89 score: number | null
90 /** Raw ids of the chat rows each flag matches. */
91 flags: Record<FlagKey, Array<string>>
93​
94export type GapReport = {
95 generatedAt: string
96 providers: Array<ProviderReport>
98​
99/** Provider id or provider/exact-raw-id → facts its sources do not publish. */
100export type Ledger = Map<string, Set<FactKey>>
101​
102function isFactKey(value: string): value is FactKey {
103 return (FACT_KEYS as ReadonlyArray<string>).includes(value)
105​
106/** Ledger entries are list lines: `- <provider>: <fact> — <why>`. */
107export function parseLedger(markdown: string): Ledger {
108 const ledger: Ledger = new Map()
109 for (const line of markdown.split('\n')) {
110 const entry = parseLedgerEntry(line)
111 if (!entry) continue
112 const { scope, fact } = entry
113 if (!isFactKey(fact)) {
114 throw new Error(
115 `source-silent ledger: unknown fact "${fact}" in: ${line}`,
116 )
117 }
118 const facts = ledger.get(scope) ?? new Set<FactKey>()
119 facts.add(fact)
120 ledger.set(scope, facts)
121 }
122 return ledger
124​
125/**
126 * Public endpoint id, query and leading slash stripped. The route's wire
127 * is this path. There is no provider list.
128 */
129function endpointPath(endpointId: string | null | undefined): string {
130 if (!endpointId) return ''
131 return endpointId.split('?')[0]?.replace(/^\/+/, '') ?? ''
133​
134/**
135 * OpenAI-compatible chat wire: `chat/completions`, `completions`, or
136 * `responses`. `ChatRequestMap` describes that wire.
137 */
138function openAiCompatRoute(row: ModelRow): boolean {
139 return /(?:^|\/)(?:chat\/completions|responses|completions)$/.test(
140 endpointPath(row.schemaEndpointId),
141 )
143​
144/**
145 * `reasoning_content` is the chat-completions field. Anthropic thinking
146 * blocks, Gemini thought signatures, Responses reasoning items, and
147 * Converse replay on other paths, so those routes are not scored.
148 */
149function reasoningContentRoute(row: ModelRow): boolean {
150 return /(?:^|\/)chat\/completions$/.test(endpointPath(row.schemaEndpointId))
152​
153function reasons(row: ModelRow): boolean {
154 return (
155 row.reasoning != null ||
156 supportedFlags(row.capabilities).includes('reasoning')
157 )
159​
160/** A null activity is an unclassified chat candidate, not a speech or image API. */
161function servesChat(group: Array<ModelRow>): boolean {
162 return group.some((row) => row.activity === 'chat' || row.activity == null)
164​
165function isModelsDev(row: ModelRow): boolean {
166 const url = row.pricing?.source?.url
167 if (!url) return false
168 try {
169 const { hostname } = new URL(url)
170 return hostname === 'models.dev' || hostname.endsWith('.models.dev')
171 } catch {
172 return false
173 }
175​
176/**
177 * The rate rows a lever must appear in: the base row, or, for a card with
178 * no base (BytePlus off-peak/peak, picked by a required lever), every row.
179 * Empty when absent or a models.dev price.
180 */
181function rateRows(row: ModelRow): Array<Record<string, unknown>> {
182 if (isModelsDev(row)) return []
183 const rate = row.pricing?.tables?.rate
184 if (!rate) return []
185 const rows = 'base' in rate ? [rate.base] : Object.values(rate)
186 return rows.every((r) => typeof r === 'object' && r !== null)
187 ? (rows as Array<Record<string, unknown>>)
188 : []
190​
191// Listing-compiled cards use OpenRouter's key names, parsed cards ours.
192function hasRate(row: ModelRow, ...keys: Array<string>): boolean {
193 const rows = rateRows(row)
194 return (
195 rows.length > 0 &&
196 rows.every((r) => keys.some((key) => typeof r[key] === 'number'))
197 )
199​
200/** `need`: the fact applies to this row. `have`: the row carries it. */
201const FACTS: Record<
202 FactKey,
203 { need?: (row: ModelRow) => boolean; have: (row: ModelRow) => boolean }
204> = {
205 contextWindow: { have: (row) => row.contextWindow != null },
206 maxOutput: { have: (row) => row.maxOutput != null },
207 modalities: {
208 have: (row) => {
209 const input = row.modalities?.input
210 return Array.isArray(input) && input.length > 0
211 },
212 },
213 priced: {
214 have: (row) =>
215 hasRate(row, 'input_tokens', 'prompt') &&
216 hasRate(row, 'output_tokens', 'completion'),
217 },
218 cacheRead: {
219 have: (row) =>
220 hasRate(row, 'cache_read_tokens', 'input_cache_read') ||
221 row.factSources?.cacheRead?.path === 'not-offered',
222 },
223 capabilities: { have: (row) => isCapabilityMap(row.capabilities) },
224 // Filled by any stored object, whatever its `mandatory`: null there means
225 // the source is silent on turning thinking off, which is a stored fact.
226 reasoning: {
227 need: (row) =>
228 row.reasoning != null ||
229 supportedFlags(row.capabilities).includes('reasoning'),
230 have: (row) => row.reasoning != null,
231 },
232 // Only `effort` and `adaptive` rows need effort names; a `toggle` or
233 // `budget` row needs none. `mandatory` plays no part: efforts with
234 // `mandatory: null` is filled, and the `mandatoryUnknown` flag counts it.
235 efforts: {
236 need: (row) =>
237 row.reasoning?.mode === 'effort' || row.reasoning?.mode === 'adaptive',
238 have: (row) => (row.reasoning?.efforts?.length ?? 0) > 0,
239 },
240 requestMap: {
241 need: openAiCompatRoute,
242 have: (row) => row.requestMap != null,
243 },
244 endpoint: { have: (row) => row.schemaEndpointId != null },
245 replayReasoningContent: {
246 need: (row) => reasoningContentRoute(row) && reasons(row),
247 have: (row) =>
248 typeof row.requestMap === 'object' &&
249 row.requestMap !== null &&
250 !Array.isArray(row.requestMap) &&
251 typeof (row.requestMap as Record<string, unknown>)
252 .replayReasoningContent === 'boolean',
253 },
255​
256/**
257 * `reasoningUnknown` is the `reasoning` gap, so a `reasoning` ledger entry
258 * for the provider or the exact model clears it. No ledger entry clears
259 * the other flags: each is a stored value in the wrong shape.
260 */
261const FLAGS: Record<
262 FlagKey,
263 { silencedBy?: FactKey; match: (row: ModelRow) => boolean }
264> = {
265 // The catalog cannot tell if it can offer an off level.
266 mandatoryUnknown: {
267 match: (row) =>
268 row.reasoning?.mode === 'effort' && row.reasoning.mandatory === null,
269 },
270 // The catalog has to guess the mode and the levels.
271 reasoningUnknown: {
272 silencedBy: 'reasoning',
273 match: (row) =>
274 FACTS.reasoning.need?.(row) === true && !FACTS.reasoning.have(row),
275 },
276 // The catalog reads `[]` as unknown; an unknown list is stored as null.
277 outputModalitiesEmpty: {
278 match: (row) => {
279 const output = row.modalities?.output
280 return Array.isArray(output) && output.length === 0
281 },
282 },
283 // Thinking cannot be turned off, yet `none` turns it off.
284 mandatoryWithNone: {
285 match: (row) =>
286 row.reasoning?.mandatory === true &&
287 (row.reasoning.efforts?.includes('none') ?? false),
288 },
290​
291/** Facts filled and facts needed across a provider, ledgered ones left out. */
292export function scoredFacts(
293 report: Pick<ProviderReport, 'facts' | 'silent' | 'modelSilent'>,
294): {
295 have: number
296 need: number
297} {
298 let have = 0
299 let need = 0
300 for (const key of FACT_KEYS) {
301 if (report.silent.includes(key)) continue
302 have += report.facts[key].have
303 need += report.facts[key].need - (report.modelSilent?.[key] ?? 0)
304 }
305 return { have, need }
307​
308export function buildReport(
309 rows: Array<ModelRow>,
310 ledger: Ledger = new Map(),
311 now: Date = new Date(),
312): GapReport {
313 const byProvider = new Map<string, Array<ModelRow>>()
314 for (const row of rows) {
315 const group = byProvider.get(row.provider)
316 if (group) group.push(row)
317 else byProvider.set(row.provider, [row])
318 }
319​
320 const providers = [...byProvider].map(([provider, group]): ProviderReport => {
321 const chat = group.filter((row) => row.activity === 'chat')
322 const silent = FACT_KEYS.filter((key) => ledger.get(provider)?.has(key))
323 const modelSilent: Partial<Record<FactKey, number>> = {}
324 const modelLedgered = (row: ModelRow, key: FactKey) =>
325 row.rawId !== undefined &&
326 ledger.get(modelLedgerScope(provider, row.rawId))?.has(key)
327 const facts = Object.fromEntries(
328 FACT_KEYS.map((key) => {
329 const { need, have } = FACTS[key]
330 const needed = need ? chat.filter(need) : chat
331 const scoped = silent.includes(key)
332 ? 0
333 : needed.filter((row) => !have(row) && modelLedgered(row, key)).length
334 if (scoped > 0) modelSilent[key] = scoped
335 return [key, { have: needed.filter(have).length, need: needed.length }]
336 }),
337 ) as ProviderReport['facts']
338 const { have, need } = scoredFacts({ facts, silent, modelSilent })
339 const flags = Object.fromEntries(
340 FLAG_KEYS.map((key) => {
341 const { silencedBy, match } = FLAGS[key]
342 const isSilent = (row: ModelRow) =>
343 silencedBy !== undefined &&
344 (silent.includes(silencedBy) || modelLedgered(row, silencedBy))
345 return [
346 key,
347 chat
348 .filter((row) => match(row) && !isSilent(row))
349 .map((row) => row.rawId ?? ''),
350 ]
351 }),
352 ) as ProviderReport['flags']
353​
354 return {
355 provider,
356 rows: group.length,
357 chat: chat.length,
358 noActivity: group.filter((row) => row.activity == null).length,
359 fromModelsDev: group.filter(isModelsDev).length,
360 facts,
361 silent,
362 modelSilent,
363 // No classified chat rows on a provider that serves chat is a gap.
364 // A provider whose every row is image, audio, or video has nothing
365 // to score. Chat rows with every needed fact on the ledger score 1.
366 score:
367 need === 0
368 ? chat.length > 0
369 ? 1
370 : servesChat(group)
371 ? 0
372 : null
373 : have / need,
374 flags,
375 }
376 })
377​
378 const rank = (score: number | null) => score ?? Number.POSITIVE_INFINITY
379 providers.sort(
380 (a, b) =>
381 rank(a.score) - rank(b.score) || a.provider.localeCompare(b.provider),
382 )
383 return { generatedAt: now.toISOString(), providers }