Open History to see the last commit
1/**
2 * modelschemas catalog rows for native-provider model-meta inserts.
3 *
4 * Each provider's own catalog supplies ids, activity, limits, modalities, and
5 * capabilities. A field the catalog leaves empty stays empty. There is no
6 * second source, and model-meta carries no prices (they change too often to
7 * ship in a package).
8 */
9
10import { toModelConstName, toNativeProviderId } from './ids'
11import type { SyncedProvider } from './provider-supports'
12
13const NON_CHAT_MODEL_PREFIXES = [
14 'lyria-',
15 'veo-',
16 'imagen-',
17 'sora-',
18 'dall-e-',
19 'tts-',
20]
21
22const DATED_SNAPSHOT = /-\d{8}$/
23
24export interface CatalogModel {
25 provider: string
26 rawId: string
27 activity: string | null
28 firstSeenAt: number | null
29 deprecatedAt: number | null
30 contextWindow: number | null
31 maxOutput: number | null
32 inputModalities: Array<string>
33 outputModalities: Array<string>
34 capabilities: Array<string>
35 /** `reasoning.mandatory`: thinking cannot be turned off (Claude Fable). */
36 reasoningMandatory: boolean
37}
38
39export interface SyncModel {
40 nativeId: string
41 contextWindow: number | null
42 maxOutput: number | null
43 inputModalities: Array<string>
44 outputModalities: Array<string>
45 supportedParameters: Array<string>
46 reasoningMandatory: boolean
47}
48
49export function isRecord(value: unknown): value is Record<string, unknown> {
50 return typeof value === 'object' && value !== null && !Array.isArray(value)
51}
52
53function asStringArray(value: unknown): Array<string> {
54 if (!Array.isArray(value)) return []
55 return value.filter((item): item is string => typeof item === 'string')
56}
57
58function asFiniteNumber(value: unknown): number | null {
59 return typeof value === 'number' && Number.isFinite(value) ? value : null
60}
61
62/**
63 * The parameter names a model is stated to support. modelschemas sends a map
64 * of flags (`{ tools: true }`): `true` keys only, because an absent key is
65 * unknown, not false. BytePlus sends a feature object instead.
66 */
67function asSupportedParameters(value: unknown): Array<string> {
68 if (Array.isArray(value)) return asStringArray(value)
69 if (!isRecord(value)) return []
70 const flags = Object.entries(value)
71 if (flags.every(([, flag]) => typeof flag === 'boolean')) {
72 return flags.filter(([, flag]) => flag).map(([name]) => name)
73 }
74 const params: Array<string> = []
75 const tools = isRecord(value.tools) ? value.tools : null
76 if (tools?.function_calling === true) {
77 params.push('tools', 'tool_choice')
78 }
79 const structured = isRecord(value.structured_outputs)
80 ? value.structured_outputs
81 : null
82 if (structured?.json_schema === true || structured?.json_object === true) {
83 params.push('structured_outputs', 'response_format')
84 }
85 if (
86 typeof value.maxReasoningTokens === 'number' &&
87 value.maxReasoningTokens > 0
88 ) {
89 params.push('reasoning', 'include_reasoning')
90 }
91 return params
92}
93
94export function parseCatalogModel(value: unknown): CatalogModel | null {
95 if (!isRecord(value)) return null
96 if (typeof value.rawId !== 'string' || value.rawId.length === 0) return null
97 const modalities = isRecord(value.modalities) ? value.modalities : null
98 const reasoning = isRecord(value.reasoning) ? value.reasoning : null
99 return {
100 provider: typeof value.provider === 'string' ? value.provider : '',
101 rawId: value.rawId,
102 activity: typeof value.activity === 'string' ? value.activity : null,
103 firstSeenAt: asFiniteNumber(value.firstSeenAt),
104 deprecatedAt: asFiniteNumber(value.deprecatedAt),
105 contextWindow: asFiniteNumber(value.contextWindow),
106 maxOutput: asFiniteNumber(value.maxOutput),
107 inputModalities: asStringArray(modalities?.input),
108 outputModalities: asStringArray(modalities?.output),
109 capabilities: asSupportedParameters(value.capabilities),
110 reasoningMandatory: reasoning?.mandatory === true,
111 }
112}
113
114/**
115 * Parse a `listModels` payload. A changed payload shape must not look like
116 * "no new models", and a renamed `firstSeenAt` / `deprecatedAt` must not
117 * let the whole historical catalog through the age and deprecation checks.
118 */
119export function parseCatalogModels(data: unknown): Array<CatalogModel> {
120 const rows = isRecord(data) ? data.models : undefined
121 if (!Array.isArray(rows)) {
122 throw new Error('modelschemas listModels: no models array')
123 }
124 const models = rows
125 .map((row) => parseCatalogModel(row))
126 .filter((model): model is CatalogModel => model !== null)
127 if (rows.length === 0) return models
128 if (models.length === 0) {
129 throw new Error(
130 `modelschemas listModels: none of ${rows.length} rows has a rawId`,
131 )
132 }
133 if (!models.some((model) => model.firstSeenAt != null)) {
134 throw new Error('modelschemas listModels: no row has a firstSeenAt')
135 }
136 if (!rows.some((row) => isRecord(row) && 'deprecatedAt' in row)) {
137 throw new Error('modelschemas listModels: no row has a deprecatedAt key')
138 }
139 return models
140}
141
142export function toSyncModel(
143 native: CatalogModel,
144 provider: SyncedProvider,
145): SyncModel {
146 return {
147 nativeId: toNativeProviderId(native.rawId, provider),
148 contextWindow: native.contextWindow,
149 maxOutput: native.maxOutput,
150 inputModalities: native.inputModalities,
151 outputModalities: native.outputModalities,
152 supportedParameters: native.capabilities,
153 reasoningMandatory: native.reasoningMandatory,
154 }
155}
156
157export function matchesSkipPattern(
158 rawId: string,
159 patterns: Array<string>,
160): boolean {
161 return patterns.some((pattern) => rawId.startsWith(pattern))
162}
163
164export function isNonChatFamily(rawId: string): boolean {
165 return (
166 rawId.includes('transcribe') ||
167 matchesSkipPattern(rawId, NON_CHAT_MODEL_PREFIXES)
168 )
169}
170
171export function isDatedAnthropicSnapshot(rawId: string): boolean {
172 return DATED_SNAPSHOT.test(rawId)
173}
174
175export function hasImageOutput(model: {
176 activity: string | null
177 outputModalities: Array<string>
178}): boolean {
179 return model.activity === 'image' || model.outputModalities.includes('image')
180}
181
182export function outputsText(
183 model: SyncModel,
184 activity: string | null,
185): boolean {
186 if (model.outputModalities.includes('text')) return true
187 if (
188 model.outputModalities.includes('image') ||
189 model.outputModalities.includes('video')
190 ) {
191 return false
192 }
193 return (
194 model.outputModalities.length === 0 &&
195 (activity === 'chat' || activity === null)
196 )
197}
198
199/**
200 * Why this native row should not be inserted. `null` means keep going.
201 */
202export function skipNativeModelReason(
203 model: CatalogModel,
204 provider: SyncedProvider,
205 skipPatterns: Array<string>,
206 cutoffTimestamp: number,
207 acceptedActivities: Array<string | null>,
208): string | null {
209 if (model.deprecatedAt != null) return 'deprecated'
210 if (!acceptedActivities.includes(model.activity)) {
211 return `activity ${model.activity}`
212 }
213 if (model.inputModalities.length === 0) return 'no modalities'
214 if (model.rawId.includes(':')) return 'routing variant'
215 if (isNonChatFamily(model.rawId)) return 'non-chat family'
216 if (matchesSkipPattern(model.rawId, skipPatterns)) return 'skip pattern'
217 if (provider === 'anthropic' && isDatedAnthropicSnapshot(model.rawId)) {
218 return 'dated snapshot'
219 }
220 if (model.firstSeenAt != null && model.firstSeenAt < cutoffTimestamp) {
221 return 'too old'
222 }
223 return null
224}
225
226export interface NativeInsertRules {
227 provider: SyncedProvider
228 skipPatterns: Array<string>
229 acceptedActivities: Array<string | null>
230 cutoffTimestamp: number
231}
232
233export interface NativeInsertSelection {
234 inserts: Array<{ model: SyncModel; activity: string | null }>
235 /** Count of every other skip, by reason. */
236 skipped: Record<string, number>
237}
238
239/** Pick the catalog rows that become new model-meta constants. */
240export function selectNativeInserts(
241 rows: Array<CatalogModel>,
242 rules: NativeInsertRules,
243 isSynced: (nativeId: string) => boolean,
244): NativeInsertSelection {
245 const selection: NativeInsertSelection = {
246 inserts: [],
247 skipped: {},
248 }
249 const skip = (reason: string) => {
250 selection.skipped[reason] = (selection.skipped[reason] ?? 0) + 1
251 }
252 for (const row of rows) {
253 const reason = skipNativeModelReason(
254 row,
255 rules.provider,
256 rules.skipPatterns,
257 rules.cutoffTimestamp,
258 rules.acceptedActivities,
259 )
260 if (reason) {
261 skip(reason)
262 continue
263 }
264 const model = toSyncModel(row, rules.provider)
265 if (isSynced(model.nativeId)) {
266 skip('already synced')
267 continue
268 }
269 if (
270 hasImageOutput({
271 activity: row.activity,
272 outputModalities: model.outputModalities,
273 })
274 ) {
275 skip('image output')
276 continue
277 }
278 selection.inserts.push({ model, activity: row.activity })
279 }
280 return selection
281}
282
283export function alreadySynced(
284 nativeId: string,
285 existingIds: Set<string>,
286 existingConstNames: Set<string>,
287): boolean {
288 const normalized = nativeId.replaceAll('.', '-')
289 return (
290 existingIds.has(normalized) ||
291 existingConstNames.has(toModelConstName(nativeId))
292 )
293}