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

catalog.ts

410 lines12.4 KB

1/**
2 * modelschemas catalog rows for native-provider model-meta inserts.
3 *
4 * Native catalogs supply ids, activity, limits, modalities, pricing, and
5 * capabilities. OpenRouter rows on modelschemas fill a field only when the
6 * native row left it empty.
7 */
8​
9import { toModelConstName, toNativeProviderId } from './ids'
10import type { SyncedProvider } from './provider-supports'
11​
12export const OPENROUTER_PREFIX: Partial<Record<SyncedProvider, string>> = {
13 openai: 'openai/',
14 anthropic: 'anthropic/',
15 gemini: 'google/',
16 grok: 'x-ai/',
17 mistral: 'mistralai/',
19​
20const NON_CHAT_MODEL_PREFIXES = [
21 'lyria-',
22 'veo-',
23 'imagen-',
24 'sora-',
25 'dall-e-',
26 'tts-',
28​
29const DATED_SNAPSHOT = /-\d{8}$/
30​
31/** USD per million tokens, as modelschemas reports it. */
32export interface CatalogPricing {
33 inputPerMillion: number | undefined
34 outputPerMillion: number | undefined
36​
37export interface CatalogModel {
38 provider: string
39 rawId: string
40 activity: string | null
41 firstSeenAt: number | null
42 deprecatedAt: number | null
43 contextWindow: number | null
44 maxOutput: number | null
45 inputModalities: Array<string>
46 outputModalities: Array<string>
47 pricing: CatalogPricing
48 capabilities: Array<string>
49 /** `reasoning.mandatory`: thinking cannot be turned off (Claude Fable). */
50 reasoningMandatory: boolean
52​
53export interface SyncModel {
54 nativeId: string
55 contextWindow: number | null
56 maxOutput: number | null
57 inputModalities: Array<string>
58 outputModalities: Array<string>
59 pricing: CatalogPricing
60 supportedParameters: Array<string>
61 reasoningMandatory: boolean
63​
64export function isRecord(value: unknown): value is Record<string, unknown> {
65 return typeof value === 'object' && value !== null && !Array.isArray(value)
67​
68function asStringArray(value: unknown): Array<string> {
69 if (!Array.isArray(value)) return []
70 return value.filter((item): item is string => typeof item === 'string')
72​
73function asFiniteNumber(value: unknown): number | null {
74 return typeof value === 'number' && Number.isFinite(value) ? value : null
76​
77/** Most providers list parameter names; BytePlus sends a feature object. */
78function asSupportedParameters(value: unknown): Array<string> {
79 if (Array.isArray(value)) return asStringArray(value)
80 if (!isRecord(value)) return []
81 const params: Array<string> = []
82 const tools = isRecord(value.tools) ? value.tools : null
83 if (tools?.function_calling === true) {
84 params.push('tools', 'tool_choice')
85 }
86 const structured = isRecord(value.structured_outputs)
87 ? value.structured_outputs
88 : null
89 if (structured?.json_schema === true || structured?.json_object === true) {
90 params.push('structured_outputs', 'response_format')
91 }
92 if (
93 typeof value.maxReasoningTokens === 'number' &&
94 value.maxReasoningTokens > 0
95 ) {
96 params.push('reasoning', 'include_reasoning')
97 }
98 return params
100​
101function asPricing(value: unknown): CatalogPricing {
102 const record = isRecord(value) ? value : {}
103 return {
104 inputPerMillion: asFiniteNumber(record.inputPerMillion) ?? undefined,
105 outputPerMillion: asFiniteNumber(record.outputPerMillion) ?? undefined,
106 }
108​
109export function parseCatalogModel(value: unknown): CatalogModel | null {
110 if (!isRecord(value)) return null
111 if (typeof value.rawId !== 'string' || value.rawId.length === 0) return null
112 const modalities = isRecord(value.modalities) ? value.modalities : null
113 const reasoning = isRecord(value.reasoning) ? value.reasoning : null
114 return {
115 provider: typeof value.provider === 'string' ? value.provider : '',
116 rawId: value.rawId,
117 activity: typeof value.activity === 'string' ? value.activity : null,
118 firstSeenAt: asFiniteNumber(value.firstSeenAt),
119 deprecatedAt: asFiniteNumber(value.deprecatedAt),
120 contextWindow: asFiniteNumber(value.contextWindow),
121 maxOutput: asFiniteNumber(value.maxOutput),
122 inputModalities: asStringArray(modalities?.input),
123 outputModalities: asStringArray(modalities?.output),
124 pricing: asPricing(value.pricing),
125 capabilities: asSupportedParameters(value.capabilities),
126 reasoningMandatory: reasoning?.mandatory === true,
127 }
129​
130/**
131 * Parse a `listModels` payload. A changed payload shape must not look like
132 * "no new models", and a renamed `firstSeenAt` / `deprecatedAt` must not
133 * let the whole historical catalog through the age and deprecation checks.
134 */
135export function parseCatalogModels(data: unknown): Array<CatalogModel> {
136 const rows = isRecord(data) ? data.models : undefined
137 if (!Array.isArray(rows)) {
138 throw new Error('modelschemas listModels: no models array')
139 }
140 const models = rows
141 .map((row) => parseCatalogModel(row))
142 .filter((model): model is CatalogModel => model !== null)
143 if (rows.length === 0) return models
144 if (models.length === 0) {
145 throw new Error(
146 `modelschemas listModels: none of ${rows.length} rows has a rawId`,
147 )
148 }
149 if (!models.some((model) => model.firstSeenAt != null)) {
150 throw new Error('modelschemas listModels: no row has a firstSeenAt')
151 }
152 if (!rows.some((row) => isRecord(row) && 'deprecatedAt' in row)) {
153 throw new Error('modelschemas listModels: no row has a deprecatedAt key')
154 }
155 return models
157​
158/** OpenRouter dots Anthropic version suffixes (`4.5`); native ids use dashes. */
159function anthropicOpenRouterId(nativeId: string): string {
160 return nativeId.replace(/(\d)-(\d)/g, '$1.$2')
162​
163export function openRouterRawIdCandidates(
164 native: CatalogModel,
165 provider: SyncedProvider,
166): Array<string> {
167 const prefix = OPENROUTER_PREFIX[provider]
168 if (!prefix) return []
169 const ids = new Set<string>([native.rawId])
170 if (provider === 'anthropic') {
171 const undated = native.rawId.replace(DATED_SNAPSHOT, '')
172 ids.add(undated)
173 ids.add(anthropicOpenRouterId(native.rawId))
174 ids.add(anthropicOpenRouterId(undated))
175 }
176 return [...ids].map((id) => prefix + id)
178​
179export function findOpenRouterEnrichment(
180 native: CatalogModel,
181 provider: SyncedProvider,
182 openrouter: Array<CatalogModel>,
183): CatalogModel | undefined {
184 const wanted = new Set(openRouterRawIdCandidates(native, provider))
185 return openrouter.find((model) => wanted.has(model.rawId))
187​
188function pickList(
189 preferred: Array<string>,
190 fallback: Array<string> = [],
191): Array<string> {
192 return preferred.length > 0 ? preferred : fallback
194​
195/** Both prices known. OpenAI/Anthropic/Gemini/Grok ModelMeta require both. */
196export function hasFullPricing(pricing: CatalogPricing): boolean {
197 return pricing.inputPerMillion != null && pricing.outputPerMillion != null
199​
200/** Strips float noise: 0.09999999999999999 → 0.1. */
201function roundPrice(price: number): number {
202 return Math.round(price * 1e10) / 1e10
204​
205/**
206 * The `pricing` block of a generated model constant. A price the catalog
207 * does not have is left out, not written as `0` (which reads as "free").
208 */
209// ponytail: modelschemas has no cached-input price, so `cached` is never written.
210export function pricingLines(pricing: CatalogPricing): Array<string> {
211 const lines = [` pricing: {`]
212 if (pricing.inputPerMillion != null) {
213 lines.push(
214 ` input: {`,
215 ` normal: ${roundPrice(pricing.inputPerMillion)},`,
216 ` },`,
217 )
218 }
219 if (pricing.outputPerMillion != null) {
220 lines.push(
221 ` output: {`,
222 ` normal: ${roundPrice(pricing.outputPerMillion)},`,
223 ` },`,
224 )
225 }
226 lines.push(` },`)
227 return lines
229​
230export function toSyncModel(
231 native: CatalogModel,
232 enrich: CatalogModel | undefined,
233 provider: SyncedProvider,
234): SyncModel {
235 return {
236 nativeId: toNativeProviderId(native.rawId, provider),
237 contextWindow: native.contextWindow ?? enrich?.contextWindow ?? null,
238 maxOutput: native.maxOutput ?? enrich?.maxOutput ?? null,
239 inputModalities: pickList(native.inputModalities, enrich?.inputModalities),
240 outputModalities: pickList(
241 native.outputModalities,
242 enrich?.outputModalities,
243 ),
244 // Per side, so a native input price does not hide OpenRouter's output price.
245 pricing: {
246 inputPerMillion:
247 native.pricing.inputPerMillion ?? enrich?.pricing.inputPerMillion,
248 outputPerMillion:
249 native.pricing.outputPerMillion ?? enrich?.pricing.outputPerMillion,
250 },
251 supportedParameters: pickList(native.capabilities, enrich?.capabilities),
252 reasoningMandatory:
253 native.reasoningMandatory || enrich?.reasoningMandatory === true,
254 }
256​
257export function matchesSkipPattern(
258 rawId: string,
259 patterns: Array<string>,
260): boolean {
261 return patterns.some((pattern) => rawId.startsWith(pattern))
263​
264export function isNonChatFamily(rawId: string): boolean {
265 return (
266 rawId.includes('transcribe') ||
267 matchesSkipPattern(rawId, NON_CHAT_MODEL_PREFIXES)
268 )
270​
271export function isDatedAnthropicSnapshot(rawId: string): boolean {
272 return DATED_SNAPSHOT.test(rawId)
274​
275export function hasImageOutput(model: {
276 activity: string | null
277 outputModalities: Array<string>
278}): boolean {
279 return model.activity === 'image' || model.outputModalities.includes('image')
281​
282export function outputsText(
283 model: SyncModel,
284 activity: string | null,
285): boolean {
286 if (model.outputModalities.includes('text')) return true
287 if (
288 model.outputModalities.includes('image') ||
289 model.outputModalities.includes('video')
290 ) {
291 return false
292 }
293 return (
294 model.outputModalities.length === 0 &&
295 (activity === 'chat' || activity === null)
296 )
298​
299/**
300 * Why this native row should not be inserted. `null` means keep going.
301 */
302export function skipNativeModelReason(
303 model: CatalogModel,
304 provider: SyncedProvider,
305 skipPatterns: Array<string>,
306 cutoffTimestamp: number,
307 acceptedActivities: Array<string | null>,
308): string | null {
309 if (model.deprecatedAt != null) return 'deprecated'
310 if (!acceptedActivities.includes(model.activity)) {
311 return `activity ${model.activity}`
312 }
313 if (model.rawId.includes(':')) return 'routing variant'
314 if (isNonChatFamily(model.rawId)) return 'non-chat family'
315 if (matchesSkipPattern(model.rawId, skipPatterns)) return 'skip pattern'
316 if (provider === 'anthropic' && isDatedAnthropicSnapshot(model.rawId)) {
317 return 'dated snapshot'
318 }
319 if (model.firstSeenAt != null && model.firstSeenAt < cutoffTimestamp) {
320 return 'too old'
321 }
322 return null
324​
325export interface NativeInsertRules {
326 provider: SyncedProvider
327 skipPatterns: Array<string>
328 acceptedActivities: Array<string | null>
329 /**
330 * Hold a native id back until the modelschemas OpenRouter catalog has a
331 * matching row and both prices are known (from either row). The
332 * OpenAI/Anthropic/Gemini/Grok ModelMeta types require both prices.
333 */
334 requireOpenRouterEnrich: boolean
335 cutoffTimestamp: number
337​
338export interface NativeInsertSelection {
339 inserts: Array<{ model: SyncModel; activity: string | null }>
340 /** Raw ids skipped only because the price gate is not met yet. */
341 heldBack: Array<string>
342 /** Count of every other skip, by reason. */
343 skipped: Record<string, number>
345​
346/** Pick the catalog rows that become new model-meta constants. */
347export function selectNativeInserts(
348 rows: Array<CatalogModel>,
349 rules: NativeInsertRules,
350 openrouter: Array<CatalogModel>,
351 isSynced: (nativeId: string) => boolean,
352): NativeInsertSelection {
353 const selection: NativeInsertSelection = {
354 inserts: [],
355 heldBack: [],
356 skipped: {},
357 }
358 const skip = (reason: string) => {
359 selection.skipped[reason] = (selection.skipped[reason] ?? 0) + 1
360 }
361 for (const row of rows) {
362 const reason = skipNativeModelReason(
363 row,
364 rules.provider,
365 rules.skipPatterns,
366 rules.cutoffTimestamp,
367 rules.acceptedActivities,
368 )
369 if (reason) {
370 skip(reason)
371 continue
372 }
373 const enrich = findOpenRouterEnrichment(row, rules.provider, openrouter)
374 const model = toSyncModel(row, enrich, rules.provider)
375 if (isSynced(model.nativeId)) {
376 skip('already synced')
377 continue
378 }
379 if (
380 hasImageOutput({
381 activity: row.activity,
382 outputModalities: model.outputModalities,
383 })
384 ) {
385 skip('image output')
386 continue
387 }
388 if (
389 rules.requireOpenRouterEnrich &&
390 !(enrich && hasFullPricing(model.pricing))
391 ) {
392 selection.heldBack.push(row.rawId)
393 continue
394 }
395 selection.inserts.push({ model, activity: row.activity })
396 }
397 return selection
399​
400export function alreadySynced(
401 nativeId: string,
402 existingIds: Set<string>,
403 existingConstNames: Set<string>,
404): boolean {
405 const normalized = nativeId.replaceAll('.', '-')
406 return (
407 existingIds.has(normalized) ||
408 existingConstNames.has(toModelConstName(nativeId))
409 )