Open History to see the last commit
1/**
2 * Turns modelschemas rows (`GET /v1/models?pricing=1`) into the `ModelRecord`s
3 * that each provider package exports at its `./models` subpath. Each fact
4 * comes from the row. A fact the row does not have stays `undefined`, and a
5 * value this file does not know throws, so a new shape fails the sync instead
6 * of writing a wrong record.
7 */
8
9import type {
10 Modality,
11 ModelPrices,
12 ModelRates,
13 ModelReasoning,
14 ModelRecord,
15 ReasoningLevel,
16 ReasoningLevels,
17} from '@tanstack/ai'
18import type { Model } from '@modelschemas/client'
19
20/** One catalog file: a modelschemas provider and the file it is written to. */
21export interface CatalogTarget {
22 /** The modelschemas provider id. */
23 source: string
24 name: string
25 /** The generated file, from the repo root. */
26 file: string
27}
28
29/** Only providers with an adapter package have a catalog. */
30export const CATALOGS: ReadonlyArray<CatalogTarget> = [
31 {
32 source: 'amazon-bedrock',
33 name: 'Amazon Bedrock',
34 file: 'packages/ai-bedrock/src/models.ts',
35 },
36 {
37 source: 'anthropic',
38 name: 'Anthropic',
39 file: 'packages/ai-anthropic/src/models.ts',
40 },
41 {
42 source: 'azure',
43 name: 'Azure OpenAI',
44 file: 'packages/ai-openai/src/azure-models.ts',
45 },
46 {
47 source: 'cloudflare-ai-gateway',
48 name: 'Cloudflare AI Gateway',
49 file: 'packages/ai-cloudflare/src/gateway-models.ts',
50 },
51 {
52 source: 'cloudflare-workers-ai',
53 name: 'Cloudflare Workers AI',
54 file: 'packages/ai-cloudflare/src/models.ts',
55 },
56 {
57 source: 'gemini',
58 name: 'Gemini',
59 file: 'packages/ai-gemini/src/models.ts',
60 },
61 {
62 source: 'google-vertex',
63 name: 'Vertex AI',
64 file: 'packages/ai-vertex/src/models.ts',
65 },
66 { source: 'grok', name: 'xAI', file: 'packages/ai-grok/src/models.ts' },
67 { source: 'groq', name: 'Groq', file: 'packages/ai-groq/src/models.ts' },
68 {
69 source: 'mistral',
70 name: 'Mistral',
71 file: 'packages/ai-mistral/src/models.ts',
72 },
73 {
74 source: 'openai',
75 name: 'OpenAI',
76 file: 'packages/ai-openai/src/models.ts',
77 },
78 {
79 source: 'openrouter',
80 name: 'OpenRouter',
81 file: 'packages/ai-openrouter/src/models.ts',
82 },
83 {
84 source: 'vercel',
85 name: 'Vercel AI Gateway',
86 file: 'packages/ai-vercel-gateway/src/models.ts',
87 },
88]
89
90/** The fields of a modelschemas row that the sync reads. */
91export type SchemaModel = Pick<
92 Model,
93 | 'provider'
94 | 'rawId'
95 | 'displayName'
96 | 'activity'
97 | 'deprecatedAt'
98 | 'aliases'
99 | 'contextWindow'
100 | 'maxOutput'
101 | 'modalities'
102 | 'capabilities'
103 | 'reasoning'
104 | 'requestMap'
105 | 'pricing'
106>
107
108/** A current chat model that writes text. */
109export function isChatModel(model: SchemaModel): boolean {
110 const output = model.modalities?.output
111 return (
112 model.activity === 'chat' &&
113 !model.deprecatedAt &&
114 (!output?.length || output.includes('text'))
115 )
116}
117
118const INPUTS: Readonly<Record<string, Modality>> = {
119 text: 'text',
120 image: 'image',
121 audio: 'audio',
122 video: 'video',
123 pdf: 'document',
124 file: 'document',
125}
126
127export function inputModalities(
128 model: SchemaModel,
129): ReadonlyArray<Modality> | undefined {
130 const kinds = model.modalities?.input
131 if (!kinds?.length) return undefined
132 return [
133 ...new Set(
134 kinds.map((kind) => {
135 const modality = INPUTS[kind]
136 if (!modality)
137 throw new Error(`${model.rawId}: unknown input modality '${kind}'`)
138 return modality
139 }),
140 ),
141 ]
142}
143
144const EFFORT_LEVELS: Readonly<Record<string, ReasoningLevel>> = {
145 none: 'off',
146 minimal: 'minimal',
147 low: 'low',
148 medium: 'medium',
149 high: 'high',
150 xhigh: 'xhigh',
151 max: 'max',
152}
153
154/**
155 * The reasoning data of a row:
156 * - `requestMap.thinking.levels`, when the row has it: each level with a value.
157 * - Else the `efforts`: each names its level (any case), and `none` is `off`.
158 * `default` (the provider's own default) is not a level.
159 * - Else no levels. `budget` says whether the model takes a token budget.
160 */
161export function reasoningFrom(model: SchemaModel): ModelReasoning {
162 const reasoning = model.reasoning
163 if (!reasoning?.mode && model.capabilities?.reasoning !== true) return false
164 const budget = reasoning?.mode === 'budget'
165 const map = model.requestMap?.thinking?.levels
166 if (map)
167 return {
168 levels: Object.fromEntries(
169 Object.entries(map).filter(([, value]) => typeof value === 'string'),
170 ),
171 budget,
172 }
173 const levels: ReasoningLevels = {}
174 for (const effort of reasoning?.efforts ?? []) {
175 if (effort === 'default') continue
176 const level = EFFORT_LEVELS[effort.toLowerCase()]
177 if (!level)
178 throw new Error(`${model.rawId}: unknown reasoning effort '${effort}'`)
179 levels[level] = effort
180 }
181 return { levels, budget }
182}
183
184/** Run a modelschemas price expression. Any other operator throws. */
185export function evaluatePrice(
186 expression: unknown,
187 vars: Readonly<Record<string, number>>,
188 tables: Readonly<Record<string, unknown>>,
189): number {
190 const run = (node: unknown): unknown => {
191 if (node === null || typeof node !== 'object') return node
192 if (Array.isArray(node)) return node.map(run)
193 const entries = Object.entries(node)
194 const [op, arg] = entries[0] ?? []
195 if (entries.length !== 1 || op === undefined)
196 throw new Error(`Price operator with ${entries.length} keys`)
197 const args: Array<unknown> = Array.isArray(arg) ? arg : [arg]
198 switch (op) {
199 case 'var':
200 return vars[String(args[0])] ?? 0
201 case '+':
202 return args.reduce<number>((sum, part) => sum + Number(run(part)), 0)
203 case '*':
204 return args.reduce<number>(
205 (product, part) => product * Number(run(part)),
206 1,
207 )
208 case '>':
209 return Number(run(args[0])) > Number(run(args[1]))
210 case 'if':
211 for (let i = 0; i + 1 < args.length; i += 2)
212 if (run(args[i])) return run(args[i + 1])
213 return args.length % 2 === 1 ? run(args[args.length - 1]) : 0
214 case 'currency':
215 return run(args[1])
216 case 'lookup': {
217 const { table, keys } = arg as { table: string; keys: Array<unknown> }
218 let value: unknown = tables[table]
219 for (const key of keys)
220 value =
221 value && typeof value === 'object'
222 ? (value as Record<string, unknown>)[String(run(key))]
223 : undefined
224 if (typeof value !== 'number')
225 throw new Error(
226 `Price lookup ${table}/${keys.join('/')} is not a number`,
227 )
228 return value
229 }
230 default:
231 throw new Error(`Unknown price operator '${op}'`)
232 }
233 }
234 return Number(run(expression))
235}
236
237/** The `var` names an expression reads. */
238function varsOf(node: unknown, names = new Set<string>()): Set<string> {
239 if (node && typeof node === 'object')
240 for (const [key, value] of Object.entries(node))
241 if (key === 'var')
242 names.add(String(Array.isArray(value) ? value[0] : value))
243 else varsOf(value, names)
244 return names
245}
246
247const RATE_VARS: Readonly<Record<keyof ModelRates, string>> = {
248 input: 'input_tokens',
249 output: 'output_tokens',
250 cacheRead: 'cache_read_tokens',
251 cacheWrite: 'cache_write_tokens',
252 cacheWrite1h: 'cache_write_1h_tokens',
253}
254
255/**
256 * The prices of a row per 1M tokens, from its price expression. Each rate is
257 * the cost of one more token on top of `inputTokens` input tokens. A rate the
258 * expression does not read stays `undefined`. No price expression: no prices.
259 */
260export function pricesFrom(model: SchemaModel): ModelPrices | undefined {
261 const card = model.pricing
262 if (!card) return undefined
263 // A compact summary comes only from a list call without `?pricing=1`.
264 if (!('price' in card))
265 throw new Error(`${model.rawId}: a price summary, not a rate card`)
266 const { price, tables } = card
267 const read = varsOf(price)
268 const ratesAt = (inputTokens: number): ModelRates => {
269 const at = (extra: Record<string, number>) =>
270 evaluatePrice(price, { input_tokens: inputTokens, ...extra }, tables)
271 const base = at({})
272 const rates: ModelRates = {}
273 for (const [field, name] of Object.entries(RATE_VARS) as Array<
274 [keyof ModelRates, string]
275 >)
276 if (read.has(name)) {
277 const more = name === 'input_tokens' ? inputTokens + 1 : 1
278 // Rounded to 1e-6 USD per 1M tokens, so float noise does not reach the files.
279 rates[field] = Number(((at({ [name]: more }) - base) * 1e6).toFixed(6))
280 }
281 return rates
282 }
283 const rate = tables.rate
284 const tiers = Object.keys(rate && typeof rate === 'object' ? rate : {})
285 .filter((key) => /^\d+$/.test(key))
286 .map(Number)
287 .sort((a, b) => a - b)
288 .map((above) => ({ inputTokensAbove: above, ...ratesAt(above + 1) }))
289 const currency =
290 price !== null && typeof price === 'object' && 'currency' in price
291 ? String((price as { currency: [unknown] }).currency[0])
292 : 'USD'
293 return {
294 currency,
295 ...ratesAt(0),
296 ...(tiers.length > 0 ? { tiers } : {}),
297 }
298}
299
300/** The records of one provider, sorted by id. An alias is a record of its own. */
301export function buildRecords(
302 rows: ReadonlyArray<SchemaModel>,
303): Array<ModelRecord> {
304 const records = new Map<string, ModelRecord>()
305 for (const model of rows) {
306 const record = {
307 name: model.displayName ?? model.rawId,
308 input: inputModalities(model),
309 reasoning: reasoningFrom(model),
310 prices: pricesFrom(model),
311 contextWindow: model.contextWindow ?? undefined,
312 maxOutputTokens: model.maxOutput ?? undefined,
313 }
314 for (const id of [model.rawId, ...(model.aliases ?? [])]) {
315 if (records.has(id)) throw new Error(`Two rows have the id '${id}'`)
316 records.set(id, { id, ...record })
317 }
318 }
319 return [...records.values()].sort((a, b) => a.id.localeCompare(b.id))
320}