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

model-facts.ts

345 lines12.6 KB

1/**
2 * Shared helpers for catalog facts the native `/models` endpoints omit
3 * (issue #53): context window, max output, modalities, request-feature
4 * capabilities. Docs parses fail closed (zero rows throws). Parsed docs
5 * live in KV for six hours so cron isolates do not refetch every tick.
6 */
7import { errorMessage } from '#/server/errors.ts'
8import { noteIngest, parseRowsEvent } from '#/server/ingest/ingest-signals.ts'
9import { getJson, putJson } from '#/server/kv.ts'
10​
11import type { DocsFailures, ModelFact, ModelInfo } from './types.ts'
12​
13export type ModelFacts = Pick<
14 ModelInfo,
15 | 'contextWindow'
16 | 'maxOutput'
17 | 'modalities'
18 | 'capabilities'
19 | 'pricing'
20 | 'reasoning'
21 | 'serverTools'
22 | 'factSources'
24​
25export const NO_FACTS: ModelFacts = {
26 contextWindow: null,
27 maxOutput: null,
28 modalities: null,
29 capabilities: null,
30 pricing: null,
32​
33/**
34 * Snapshot ids fall back to their alias:
35 * `gpt-5-2025-08-07` → `gpt-5`, `claude-opus-4-5-20251101` → `claude-opus-4-5`.
36 */
37export function undatedId(rawId: string): string {
38 return rawId.replace(/-\d{4}-\d{2}-\d{2}$|-\d{8}$/, '')
40​
41const MONTHS = [
42 'january',
43 'february',
44 'march',
45 'april',
46 'may',
47 'june',
48 'july',
49 'august',
50 'september',
51 'october',
52 'november',
53 'december',
55​
56/** `December 31, 2026` → that day's UTC midnight, case-insensitive. */
57export function parseDay(text: string): number | null {
58 const match = text
59 .trim()
60 .toLowerCase()
61 .match(/^([a-z]+) (\d{1,2}), (\d{4})$/)
62 const month = match?.[1] ? MONTHS.indexOf(match[1]) : -1
63 if (!match || month < 0) return null
64 return Date.UTC(Number(match[3]), month, Number(match[2]))
66​
67/** `1,048,576` / `500k` / `1M` → number. */
68export function tokenCount(text: string | undefined): number | null {
69 const match = text?.match(/([\d,]*\.?\d+)\s*([kKmM])?/)
70 if (!match?.[1]) return null
71 const base = Number(match[1].replace(/,/g, ''))
72 const unit = match[2]?.toLowerCase()
73 return Math.round(base * (unit === 'm' ? 1e6 : unit === 'k' ? 1e3 : 1))
75​
76/**
77 * Every `| a | b |` row in a markdown document as trimmed cells, separator
78 * rows dropped. Callers pick rows by content; header rows come along.
79 */
80export function markdownTableRows(text: string): Array<Array<string>> {
81 const rows: Array<Array<string>> = []
82 // A cell may hold a newline ("Portrait: 720x1280\nLandscape: 1280x720"),
83 // splitting one row over two lines; join until the row closes, and give
84 // up on a line that carries no cell of its own.
85 let pending = ''
86 for (const line of text.split('\n')) {
87 if (pending === '') {
88 if (!line.startsWith('|')) continue
89 pending = line
90 } else if (line.includes('|')) {
91 pending = `${pending} ${line}`
92 } else {
93 pending = ''
94 continue
95 }
96 if (!pending.endsWith('|')) continue
97 const cells = pending
98 .slice(1, -1)
99 .split('|')
100 .map((cell) => cell.trim())
101 pending = ''
102 if (cells.every((cell) => /^:?-+:?$/.test(cell))) continue
103 rows.push(cells)
104 }
105 return rows
107​
108/**
109 * One `## <heading>` section of a markdown document, up to the next `## `.
110 * Empty when the heading is absent.
111 */
112export function markdownSection(text: string, heading: string): string {
113 const start = text.indexOf(`\n## ${heading}`)
114 if (start < 0) return ''
115 const rest = text.slice(start + 1)
116 const end = rest.indexOf('\n## ')
117 return end < 0 ? rest : rest.slice(0, end)
119​
120/**
121 * One page of a Mintlify `llms-full.txt`: each page opens with a `# <title>`
122 * line followed by `Source: <url>`, and runs to the next such pair. Throws
123 * unless exactly one page names `url`.
124 */
125export function llmsFullPage(text: string, url: string): string {
126 const lines = text.split('\n')
127 const opens = (index: number) =>
128 lines[index]?.startsWith('# ') === true &&
129 lines[index + 1]?.startsWith('Source: ') === true
130 const starts = lines.flatMap((_line, index) =>
131 opens(index) && lines[index + 1] === `Source: ${url}` ? [index] : [],
132 )
133 if (starts.length !== 1) {
134 throw new Error(
135 `llms-full.txt names ${url} ${String(starts.length)} times, not once`,
136 )
137 }
138 const start = starts[0] ?? 0
139 let end = start + 2
140 while (end < lines.length && !opens(end)) end += 1
141 return lines.slice(start, end).join('\n')
143​
144const DOCS_TTL_SECONDS = 6 * 60 * 60
145​
146/**
147 * Bumped whenever a parsed-docs shape changes. A deploy that changed the
148 * shape would otherwise read the old one back out of KV for six hours and
149 * see missing fields as missing facts.
150 */
151// v7: OpenAI model pages price the first token table and only the default
152// snapshot. A v6 entry would keep o3's batch table and gpt-4o's old snapshot.
153// v8: Grok model-page cache includes maxOutput (#119).
154// v9: BytePlus and Mistral cached docs include serverTools. A v8 entry
155// would keep the old card and leave tools null for six hours.
156// v10: BytePlus image and video cards copy published alias ids. A v9 entry
157// would leave those aliases unpriced for six hours.
158// v11: Grok maxOutput (#119) lands after v10 shipped; a v10 entry has no
159// maxOutput on Grok pages for six hours.
160// v12: Azure rows gain `tabulated` and the price doc gains `thresholds`. A
161// v11 entry written by the PR's preview build would drop every Azure row.
162// v13: MiniMax M2 rows store no maxOutput (the spec maximum is the context
163// window). A v12 entry would keep 204800 on them for six hours.
164// v14: Gemini and Mistral model pages gain `modalities`. A v13 entry has
165// none, and the schema walk that used to fill the field no longer does.
166// v15: open fill-gaps PRs #242 and #244. Do not reuse.
167// v16: Mistral model pages gain maxOutput and page pricing, and the pricing
168// doc stores the table without those pages. A v14 entry would keep Large 4's
169// sale row skipped and leave the new fields null for six hours.
170// v21: Azure rows gain effort lists, request maps, and the gpt-4 /
171// computer-use-preview meter match. A v16 entry would leave those null
172// for six hours.
173// v22: DashScope compat cache includes `scope`. A v21 entry has no scope,
174// so a chat id the page does not name would still get the compat map.
175// v23: Gemini's cached index is `{url, ids}` rows, thinking pages cache
176// budget bodies, and model pages cache per-id sections. Thinking-level
177// `mandatory` is true only when the page says that family cannot turn
178// thinking off. A v22 entry has none of that, so Gemini facts read from
179// it would stay null or mark every level column mandatory.
180// v24: Cerebras model pages include paid maxOutput. A v23 entry has no
181// maxOutput and would leave it null for six hours.
182// v25: Bedrock cards gain request maps, feature flags, and price-list
183// rates. A v24 entry would leave those null for six hours.
184// v26: Together reasoning pages and the serverless chat catalog cache
185// plain records. A v25 entry stored Maps, which JSON reads back as {},
186// and the next poll throws before any together row is written.
187// v27: native reasoning controls now distinguish published levels, mandatory
188// status and genuine source silence. Re-read cached parsed facts so earlier
189// guesses cannot survive the new parsers until the six-hour TTL expires.
190// v28: re-read native budget applicability and replay declarations after the
191// scoped guide enrichments and stricter normative-prose checks.
192// v30: DashScope China priced rows no longer carry absent.pricing 'cleared'.
193// A v29 entry would keep dropping every CNY card for six hours.
194// v31: the Gemini pricing entry gained `named`; a v30 entry has none.
195// v32: OpenAI "only supports" a non-none effort is mandatory true. A v31
196// model-page entry would keep gpt-5-pro at mandatory null for six hours.
197// v33: Vertex Claude card titles drop a leading "Anthropic's" (#390). A v32
198// entry keeps every row unpriced, so the poll refuses the clear for six hours.
199// v34: OpenAI pages add `file` input from `file_uploads` and Mistral pages from
200// `document-qna` (#407). A v33 entry would keep them without it for six hours.
201const DOCS_CACHE_VERSION = 'v34'
202​
203/**
204 * KV cache for parsed docs, keyed by source URL. A failed load is not
205 * stored, so the next poll retries. `kv` is omitted in unit tests that
206 * never hit the network.
207 */
208export async function cachedDocs<T>(
209 kv: KVNamespace | undefined,
210 url: string,
211 load: () => Promise<T>,
212): Promise<T> {
213 const key = `docs:${DOCS_CACHE_VERSION}:${url}`
214 if (kv) {
215 const hit = await getJson<T>(kv, key)
216 if (hit !== null) return hit
217 }
218 const value = await load()
219 if (kv) {
220 await putJson(kv, key, value, { expirationTtl: DOCS_TTL_SECONDS })
221 }
222 return value
224​
225/**
226 * Once one provider's failed docs loads have cost this much wall-clock time
227 * in a poll, nothing more is fetched for it: a docs host that is down would
228 * otherwise spend a timeout per document and stall every provider polled
229 * after it. Loads that overlap count once, so eight concurrent failures of
230 * 2.5 s cost 2.5 s. A host that hangs still costs one full round of its
231 * timeout (60 s for an NVIDIA card) before this can trip. A few pages that
232 * fail fast never reach it, so they do not stop the healthy ones loading.
233 */
234const DOCS_FAILURE_BUDGET_MS = 15_000
235​
236/** Failures kept in full per provider per poll; the rest are only counted. */
237const DOCS_FAILURES_KEPT = 5
238​
239/** One provider's docs loads in one poll. Make it with `docsRun()`. */
240export interface DocsRun extends DocsFailures {
241 /** Wall-clock time lost to failed loads so far. */
242 lostMs: number
243 /** When the latest failed load ended; where the next one's cost starts. */
244 lostUntil: number
246​
247export function docsRun(): DocsRun {
248 return { failed: 0, skipped: 0, first: [], lostMs: 0, lostUntil: 0 }
250​
251/** `ListModelsResult.docsFailures` for a finished run. */
252export function docsReport(run: DocsRun): DocsFailures {
253 return { failed: run.failed, skipped: run.skipped, first: run.first }
255​
256class DocsSkipped extends Error {}
257​
258/** `cachedDocs` that serves a KV hit and refuses to fetch. */
259const cachedOnly: typeof cachedDocs = (kv, url) =>
260 cachedDocs(kv, url, () => Promise.reject(new DocsSkipped()))
261​
262/**
263 * Load and parse one docs source for `listModels`. A throw is counted in
264 * `run` and returns null, so the listing and the other sources still poll.
265 * The caller gives the rows that source feeds `unavailable(...)` and
266 * returns `docsReport(run)` as `docsFailures`. Parsers stay strict: they
267 * throw, and only this catches. Never wrap the listing itself.
268 *
269 * `load` must fetch through the `cached` it is handed: once the failure
270 * budget is spent that one serves KV hits only, and a miss is counted as
271 * skipped rather than fetched.
272 */
273export async function tryDocs<T>(
274 run: DocsRun,
275 source: string,
276 load: (cached: typeof cachedDocs) => Promise<T>,
277): Promise<T | null> {
278 const started = Date.now()
279 try {
280 return await load(
281 run.lostMs >= DOCS_FAILURE_BUDGET_MS ? cachedOnly : cachedDocs,
282 )
283 } catch (error) {
284 if (error instanceof DocsSkipped) {
285 run.skipped++
286 return null
287 }
288 const ended = Date.now()
289 run.lostMs += Math.max(0, ended - Math.max(started, run.lostUntil))
290 run.lostUntil = Math.max(run.lostUntil, ended)
291 run.failed++
292 if (run.first.length < DOCS_FAILURES_KEPT) {
293 run.first.push({
294 source,
295 error: errorMessage(error),
296 elapsedMs: ended - started,
297 })
298 }
299 return null
300 }
302​
303/** Row patch: the source of these facts failed, keep what is stored. */
304export function unavailable(
305 ...facts: Array<ModelFact>
306): Pick<ModelInfo, 'absent'> {
307 return {
308 absent: Object.fromEntries(facts.map((fact) => [fact, 'unavailable'])),
309 }
311​
312/**
313 * Throw when a docs parse comes back empty — never silently null a catalog.
314 * A non-empty parse records one `parse_rows` event (`source`, `rows`).
315 * Cache hits do not emit, so the daily event count swings with the six-hour
316 * TTL and with deploys. The drop alert counts distinct `source` values on a
317 * finished UTC day and fires when that set shrinks. The zero-row throw is
318 * `ingest_failed` at the job boundary.
319 */
320export function assertParsed<T>(rows: Map<string, T>, source: string): void {
321 if (rows.size === 0) throw new Error(`${source}: parsed 0 model rows`)
322 noteIngest(parseRowsEvent(source, rows.size))
324​
325/** Bounded-concurrency map, order preserved. */
326export async function mapConcurrent<T, TResult>(
327 items: Array<T>,
328 limit: number,
329 fn: (item: T) => Promise<TResult>,
330): Promise<Array<TResult>> {
331 const results: Array<TResult> = new Array<TResult>(items.length)
332 let next = 0
333 const worker = async () => {
334 while (next < items.length) {
335 const index = next++
336 const item = items[index]
337 if (item === undefined) continue
338 results[index] = await fn(item)
339 }
340 }
341 await Promise.all(
342 Array.from({ length: Math.min(limit, items.length) }, () => worker()),
343 )
344 return results