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

mistral-pricing.ts

1,222 lines39.3 KB

1/**
2 * Mistral prices from the docs pricing page (issue #73, unit rows #116).
3 * Sections marked "Prices /M Tokens" are standard per-million rates (input,
4 * cached input, output). Batch and priority live in other tabs and are not
5 * in that table. A cell with a unit ("$4 /1000 Pages", "$0.003 /Min",
6 * "$16 /M Chars") is a unit rate, not a token rate. A row is one unit card
7 * when every priced cell names that same unit. Several positive prices of
8 * that unit (input and cached pages) are separate usage meters. A zero
9 * amount is not a meter. Mixed units, an unknown unit, or "Free" is no card.
10 *
11 * The table keys docs slugs (`mistral-large-3-25-12`). The model page names
12 * the API ids that slug serves (`mistral-large-2512`, `mistral-large-latest`).
13 * An API id named by two slugs at different rates gets no card.
14 *
15 * A cell that strikes through a price (`<del>`) is a promotion. The standard
16 * tier is the struck-through amount. The `<ins>` sale price is not stored.
17 *
18 * The same model page states modalities (one tooltip per medium), a "Max
19 * output" stat when Mistral publishes one, and a pricing widget for models
20 * the token table does not list. `k` and `M` on that stat are 1024, the same
21 * scale the listing uses (262144 shown as 256k).
22 */
23import {
24 cardPrice,
25 compileTokenCard,
26 compileUnitCard,
27} from '@modelschemas/rate-card'
28import type { Expr, RateCard } from '@modelschemas/rate-card'
29​
30import { tagDocsFacts } from './fact-sources.ts'
31import { assertParsed, cachedDocs, mapConcurrent } from './model-facts.ts'
32import { parseMistralPageTools } from './server-tools.ts'
33import { fetchText, sha256Text } from './types.ts'
34import type { ModelInfo } from './types.ts'
35​
36export const MISTRAL_PRICING_URL = 'https://docs.mistral.ai/inference/pricing'
37export const MISTRAL_CHANGELOG_URL =
38 'https://docs.mistral.ai/resources/changelogs'
39const MISTRAL_MODEL_PAGE = (slug: string) =>
40 `https://docs.mistral.ai/models/${slug}`
41​
42export interface MistralTokenRates {
43 kind: 'tokens'
44 rates: Record<string, number>
46​
47/** One billed quantity. Cached meters default to 0; the primary does not. */
48export interface MistralUnitMeter {
49 param: string
50 /** USD per one unit (one page, one minute, one character). */
51 rate: number
52 default?: number
54​
55export interface MistralUnitRates {
56 kind: 'unit'
57 meters: Array<MistralUnitMeter>
59​
60export type MistralListedPrice = MistralTokenRates | MistralUnitRates
61​
62const UNIT_PARAMS = {
63 pages: ['pages', 'cached_pages', 'output_pages'],
64 audio_minutes: [
65 'audio_minutes',
66 'cached_audio_minutes',
67 'output_audio_minutes',
68 ],
69 characters: ['characters', 'cached_characters', 'output_characters'],
70} as const
71​
72type MistralUnit = keyof typeof UNIT_PARAMS
73​
74/** `$4 /1000 Pages`, `$0.003 /Min`, `$16 /M Chars`. `undefined` is `—`. */
75function unitCell(
76 cell: string,
77): { unit: MistralUnit; rate: number } | null | undefined {
78 if (cell === '—' || cell === '–' || cell === '-' || cell === '') {
79 return undefined
80 }
81 const match = cell.match(
82 /^\$([\d,]+(?:\.\d+)?)\s*\/\s*(?:(\d[\d,]*)\s+)?(.+)$/,
83 )
84 if (!match?.[1] || !match[3]) return null
85 const amount = Number(match[1].replace(/,/g, ''))
86 const count = match[2] ? Number(match[2].replace(/,/g, '')) : 1
87 const label = match[3].trim().toLowerCase()
88 const unit: MistralUnit | null =
89 label === 'page' || label === 'pages'
90 ? 'pages'
91 : label === 'min' ||
92 label === 'mins' ||
93 label === 'minute' ||
94 label === 'minutes'
95 ? 'audio_minutes'
96 : label === 'm char' || label === 'm chars' || label === 'm characters'
97 ? 'characters'
98 : null
99 if (
100 !unit ||
101 !Number.isFinite(amount) ||
102 !Number.isFinite(count) ||
103 count <= 0
104 ) {
105 return null
106 }
107 const rate = unit === 'characters' ? amount / 1e6 / count : amount / count
108 return { unit, rate }
110​
111function cellText(html: string): string {
112 return html
113 .replace(/<[^>]+>/g, '')
114 .replace(/&amp;/g, '&')
115 .replace(/&#39;/g, "'")
116 .replace(/\s+/g, ' ')
117 .trim()
119​
120/** Current billed amount. A crossed-out quote cannot substitute for a sale. */
121function currentCell(raw: string): string {
122 const sale = [...raw.matchAll(/<ins\b[^>]*>([\s\S]*?)<\/ins>/gi)]
123 if (!/<(?:del|ins)\b/i.test(raw)) return cellText(raw)
124 if (sale.length !== 1) {
125 throw new Error('mistral pricing: missing or repeated current sale price')
126 }
127 const text = cellText(sale[0]?.[1] ?? '').replace(/^Sale price:\s*/i, '')
128 if (!/^\$[\d,]+(?:\.\d+)?(?:\s*\/.+)?$/.test(text)) {
129 throw new Error('mistral pricing: unreadable current sale price')
130 }
131 return text
133​
134/** `$0.5` per million tokens. `undefined` is an absent lever (`—`). */
135function perMillion(cell: string): number | null | undefined {
136 if (cell === '—' || cell === '–' || cell === '-' || cell === '') {
137 return undefined
138 }
139 const amount = cell.match(/^\$([\d,]+(?:\.\d+)?)$/)?.[1]
140 if (amount === undefined) return null
141 return Number(amount.replace(/,/g, '')) / 1e6
143​
144/** Input, cached input, then output. A zero amount publishes no meter. */
145function unitMeters(cells: Array<string>): Array<MistralUnitMeter> | null {
146 const priced: Array<MistralUnitMeter & { unit: MistralUnit }> = []
147 for (const [index, column] of [1, 2, 3].entries()) {
148 const parsed = unitCell(cells[column] ?? '')
149 if (parsed === null) return null
150 if (!parsed || parsed.rate === 0) continue
151 const param = UNIT_PARAMS[parsed.unit][index]
152 if (!param) return null
153 priced.push({ unit: parsed.unit, param, rate: parsed.rate })
154 }
155 if (priced.length === 0) return null
156 const unit = priced[0]?.unit
157 if (!unit || priced.some((meter) => meter.unit !== unit)) return null
158 return priced.map((meter, index) => ({
159 param: meter.param,
160 rate: meter.rate,
161 ...(index > 0 ? { default: 0 } : {}),
162 }))
164​
165/**
166 * Docs slug → token or unit rates. Token sections skip a row that is not a
167 * plain per-million amount. Other sections accept one unit only.
168 */
169export function parseMistralPricing(
170 html: string,
171): Map<string, MistralListedPrice> {
172 const out = new Map<string, MistralListedPrice>()
173 for (const section of html.split(/<h2\b[^>]*>/i).slice(1)) {
174 const tokens = /Prices\s*\/\s*M Tokens/i.test(section)
175 const table = section.match(/<table\b[\s\S]*?<\/table>/i)?.[0] ?? ''
176 for (const row of table.matchAll(/<tr\b[\s\S]*?<\/tr>/gi)) {
177 const slug = row[0].match(/href="\/models\/([^"]+)"/)?.[1]
178 if (!slug || out.has(slug)) continue
179 const cells = [...row[0].matchAll(/<td\b[^>]*>([\s\S]*?)<\/td>/gi)].map(
180 ([, cell = '']) => currentCell(cell),
181 )
182 const text = cells
183 if (text.some((cell) => /^free$/i.test(cell))) continue
184 if (tokens) {
185 const input = perMillion(text[1] ?? '')
186 const cached = perMillion(text[2] ?? '')
187 const output = perMillion(text[3] ?? '')
188 if (input === null || cached === null || output === null) continue
189 if (input === undefined) continue
190 const rates: Record<string, number> = { input_tokens: input }
191 if (cached !== undefined) rates.cache_read_tokens = cached
192 if (output !== undefined) rates.output_tokens = output
193 out.set(slug, { kind: 'tokens', rates })
194 continue
195 }
196 const meters = unitMeters(text)
197 if (!meters) continue
198 out.set(slug, { kind: 'unit', meters })
199 }
200 }
201 return out
203​
204/** The card's price, to compose into a larger USD one. */
205export function usdExpr(card: RateCard): Expr {
206 const { currency, expr } = cardPrice(card)
207 if (currency !== 'USD') {
208 // Composing would drop the wrapper and read the amount as dollars.
209 throw new Error(`mistral pricing: cannot extend a ${currency} card`)
210 }
211 return expr
213​
214/** The card `mistralModelPricing` stores. `null` when the row prices nothing. */
215export function mistralRateCard(
216 row: MistralListedPrice,
217 source: RateCard['source'],
218): RateCard | null {
219 if (row.kind === 'tokens') return compileTokenCard(row.rates, [], source)
220 const [first, ...rest] = row.meters
221 if (!first || first.rate <= 0) return null
222 const card = compileUnitCard(
223 {
224 quantity: {
225 param: first.param,
226 bound: 'usage',
227 ...(first.default !== undefined ? { default: first.default } : {}),
228 },
229 rates: first.rate,
230 },
231 source,
232 )
233 if (!card || rest.length === 0) return card
234 return {
235 ...card,
236 inputs: {
237 ...card.inputs,
238 ...Object.fromEntries(
239 rest.map((meter) => [
240 meter.param,
241 {
242 param: meter.param,
243 bound: 'usage' as const,
244 kind: 'number' as const,
245 ...(meter.default !== undefined ? { default: meter.default } : {}),
246 },
247 ]),
248 ),
249 },
250 price: {
251 '+': [
252 usdExpr(card),
253 ...rest.map((meter) => ({ '*': [{ var: meter.param }, meter.rate] })),
254 ],
255 },
256 }
258​
259/**
260 * API ids a model page says the slug serves. The payload carries
261 * `"names":["mistral-large-2512","mistral-large-latest"]`. When several
262 * arrays match, the one sharing the most slug tokens wins; a tie that
263 * shares nothing is no mapping.
264 */
265export function parseMistralApiIds(html: string, slug: string): Array<string> {
266 // The page embeds the array as JSON (`"names":["id"]`) and, in the RSC
267 // payload, with escaped quotes (`names\":["id"]`).
268 const blocks = [
269 ...html.matchAll(/"names":\[([^\]]*)\]/g),
270 ...html.matchAll(/names\\":\[([^\]]*)\]/g),
271 ].flatMap((match) => {
272 const body = match[1] ?? ''
273 const ids = [
274 ...body.matchAll(/"([^"\\]+)"/g),
275 ...body.matchAll(/\\"([^"\\]+)\\"/g),
276 ].map(([, id = '']) => id)
277 return ids.length > 0 &&
278 ids.every((id) => /^[a-z0-9][a-z0-9._/-]*$/.test(id))
279 ? [ids]
280 : []
281 })
282 if (blocks.length === 0) return []
283 const tokens = slug.split('-').filter((token) => token.length > 1)
284 const score = (ids: Array<string>) =>
285 ids.reduce(
286 (total, id) =>
287 total + tokens.filter((token) => id.includes(token)).length,
288 0,
289 )
290 const ranked = [...blocks].sort((a, b) => score(b) - score(a))
291 const best = ranked[0] ?? []
292 const bestScore = score(best)
293 if (bestScore === 0 && blocks.length > 1) return []
294 return best
296​
297export interface MistralModalities {
298 input: Array<string>
299 output: Array<string>
301​
302/** Tooltip word → medium, in stored order. */
303const MISTRAL_MEDIA: Record<string, string> = {
304 text: 'text',
305 image: 'image',
306 audio: 'audio',
307 video: 'video',
308 document: 'file',
310​
311type Json = string | number | boolean | null | Array<Json> | JsonObject
312interface JsonObject {
313 [key: string]: Json
315​
316/** Props of an RSC element `["$", tag, key, props]`, else null. */
317function rscProps(node: Json): JsonObject | null {
318 if (!Array.isArray(node) || node[0] !== '$') return null
319 const props = node[3]
320 return typeof props === 'object' && props !== null && !Array.isArray(props)
321 ? props
322 : null
324​
325/** The page's RSC rows by id. Rows that are not JSON (text, imports) are skipped. */
326function rscRows(html: string): RscRows {
327 const stream = [
328 ...html.matchAll(/self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)/g),
329 ]
330 .map((match) => JSON.parse(match[1] ?? '""') as string)
331 .join('')
332 const rows = new Map<string, Json>()
333 for (const line of stream.split('\n')) {
334 const row = line.match(/^([0-9a-f]+):(.*)$/)
335 if (!row?.[1]) continue
336 try {
337 rows.set(row[1], JSON.parse(row[2] ?? '') as Json)
338 } catch {
339 // Not a JSON row.
340 }
341 }
342 return rows
344​
345/** Every node that directly follows a "Modalities" heading element. */
346function modalityBlocks(node: Json, out: Array<Json> = []): Array<Json> {
347 if (Array.isArray(node)) {
348 node.forEach((item, index) => {
349 const children = rscProps(item)?.children
350 const label = Array.isArray(children) ? children.at(-1) : children
351 const next = node[index + 1]
352 if (label === 'Modalities' && next !== undefined) out.push(next)
353 modalityBlocks(item, out)
354 })
355 } else if (typeof node === 'object' && node !== null) {
356 for (const value of Object.values(node)) modalityBlocks(value, out)
357 }
358 return out
360​
361type RscRows = Map<string, Json>
362​
363/** A `$L<id>` reference to a row of the page, followed; anything else as is. */
364function deref(rows: RscRows, node: Json): Json {
365 const id = typeof node === 'string' ? node.match(/^\$L(.+)$/)?.[1] : null
366 return id ? (rows.get(id) ?? node) : node
368​
369const isSvg = (node: Json): boolean =>
370 Array.isArray(node) && node[0] === '$' && node[1] === 'svg'
371​
372/**
373 * The label of every leaf of a Modalities block, references followed. The
374 * block is `div`s around tooltips, plus a `div` of arrow icons. A tooltip
375 * is a component with two children, an `asChild` trigger then the label
376 * component. Every other leaf (a reference with no row, another component,
377 * a tooltip of another shape, text, a lone icon, a node under a prop other
378 * than `children`) reads as `null`, which no caller can map: a tooltip
379 * this walk cannot reach must not be dropped while the rest are kept.
380 */
381function tooltipLabels(
382 rows: RscRows,
383 ref: Json,
384 out: Array<string | null> = [],
385): Array<string | null> {
386 const node = deref(rows, ref)
387 if (node === null) return out
388 const props = rscProps(node)
389 if (!Array.isArray(node) || (!props && node[0] === '$')) {
390 out.push(null)
391 return out
392 }
393 if (!props) {
394 for (const item of node) tooltipLabels(rows, item, out)
395 return out
396 }
397 const tag = node[1]
398 const { children } = props
399 if (typeof tag !== 'string' || tag.startsWith('$')) {
400 const parts = Array.isArray(children)
401 ? children.map((child) => deref(rows, child))
402 : []
403 const label =
404 parts.length === 2 && rscProps(parts[0] ?? null)?.asChild === true
405 ? rscProps(parts[1] ?? null)?.children
406 : null
407 out.push(typeof label === 'string' ? label : null)
408 return out
409 }
410 const list =
411 children === undefined
412 ? []
413 : Array.isArray(children) && children[0] !== '$'
414 ? children
415 : [children]
416 // The arrows between the input and output tooltips.
417 if (tag !== 'svg' && list.length > 0 && list.every(isSvg)) return out
418 const nested = Object.entries(props).some(
419 ([name, value]) =>
420 name !== 'children' && typeof value === 'object' && value !== null,
421 )
422 if (tag === 'svg' || nested) {
423 out.push(null)
424 return out
425 }
426 for (const item of list) tooltipLabels(rows, item, out)
427 return out
429​
430function blockModalities(rows: RscRows, block: Json): MistralModalities | null {
431 const found = { input: new Set<string>(), output: new Set<string>() }
432 for (const label of tooltipLabels(rows, block)) {
433 const match = label?.match(/^(.+) (input|output)$/i)
434 if (!match) return null
435 const word = (match[1] ?? '').toLowerCase()
436 const side = (match[2] ?? '').toLowerCase() === 'input' ? 'input' : 'output'
437 // A reasoning model's marker, not a medium.
438 if (word === 'reasoning' && side === 'output') continue
439 const medium = MISTRAL_MEDIA[word]
440 if (!medium) return null
441 found[side].add(medium)
442 }
443 if (found.input.size === 0 || found.output.size === 0) return null
444 const ordered = (have: Set<string>) =>
445 Object.values(MISTRAL_MEDIA).filter((medium) => have.has(medium))
446 return { input: ordered(found.input), output: ordered(found.output) }
448​
449/**
450 * Modalities a model page states: the tooltips ("Text input", "Image
451 * input", "Text output") of the block beside its "Modalities" heading, read
452 * from the RSC payload. Null unless every tooltip in the block is a known
453 * medium on a known side, both sides are stated, and every such block on
454 * the page (it renders one per layout) says the same. A partial list would
455 * read as the whole answer.
456 */
457export function parseMistralPageModalities(
458 html: string,
459): MistralModalities | null {
460 const rows = rscRows(html)
461 const blocks = [...rows.values()]
462 .flatMap((row) => modalityBlocks(row))
463 .map((block) => blockModalities(rows, block))
464 const [first] = blocks
465 if (!first) return null
466 return blocks.every(
467 (block) => JSON.stringify(block) === JSON.stringify(first),
468 )
469 ? first
470 : null
472​
473/** `128k` → 131072, `1M` → 1048576. Any other spelling is unreadable. */
474function suffixTokens(value: string): number | null {
475 const match = /^(\d+(?:\.\d+)?)(k|M)$/.exec(value)
476 if (!match?.[1] || !match[2]) return null
477 const tokens = Number(match[1]) * (match[2] === 'M' ? 1024 * 1024 : 1024)
478 return Number.isInteger(tokens) ? tokens : null
480​
481function statLabel(node: Json): string | null {
482 const props = rscProps(node)
483 const className = props?.className
484 if (typeof className !== 'string' || !className.includes('uppercase')) {
485 return null
486 }
487 const leaves: Array<string> = []
488 const walk = (value: Json) => {
489 if (typeof value === 'string') leaves.push(value)
490 else if (Array.isArray(value)) value.forEach(walk)
491 else if (typeof value === 'object' && value !== null) {
492 Object.values(value).forEach(walk)
493 }
494 }
495 walk(props?.children ?? null)
496 return leaves.includes('Max output') ? 'Max output' : null
498​
499function statValue(node: Json): string | null {
500 const props = rscProps(node)
501 const className = props?.className
502 if (
503 typeof className !== 'string' ||
504 !className.includes('text-lg font-bold font-mono text-primary-soft')
505 ) {
506 return null
507 }
508 return typeof props?.children === 'string' ? props.children : null
510​
511/**
512 * Tokens from the "Max output" stat. Null when the page has no such stat
513 * or two layouts disagree. The context stat uses the same value style and
514 * is not a max-output cap.
515 */
516export function parseMistralPageMaxOutput(html: string): number | null {
517 const values = new Set<number>()
518 // A closure write does not widen `let flag = false` (stays the literal
519 // `false`), so the unreadable mark lives on an object.
520 const mark = { unreadable: false }
521 const visit = (node: Json) => {
522 if (Array.isArray(node)) {
523 for (let index = 0; index < node.length - 1; index++) {
524 const current = node[index]
525 const next = node[index + 1]
526 if (current === undefined || next === undefined) continue
527 if (statLabel(current) !== 'Max output') continue
528 const raw = statValue(next)
529 const tokens = raw === null ? null : suffixTokens(raw)
530 if (tokens === null) mark.unreadable = true
531 else values.add(tokens)
532 }
533 node.forEach(visit)
534 return
535 }
536 if (typeof node === 'object' && node !== null) {
537 Object.values(node).forEach(visit)
538 }
539 }
540 for (const row of rscRows(html).values()) visit(row)
541 if (mark.unreadable || values.size !== 1) return null
542 return [...values][0] ?? null
544​
545interface WidgetMeter {
546 price?: number
547 originalPrice?: number
548 denominator?: string
549 label?: string
551​
552function isJsonRecord(value: Json): value is JsonObject {
553 return typeof value === 'object' && value !== null && !Array.isArray(value)
555​
556function pricingWidgets(html: string): Array<JsonObject> {
557 const found: Array<JsonObject> = []
558 const visit = (node: Json) => {
559 if (isJsonRecord(node)) {
560 const custom =
561 node.type === 'custom' &&
562 typeof node.free === 'boolean' &&
563 Array.isArray(node.input) &&
564 Array.isArray(node.output)
565 const flat =
566 node.type === 'flat' &&
567 typeof node.free === 'boolean' &&
568 typeof node.denominator === 'string'
569 if (custom || flat) found.push(node)
570 }
571 if (Array.isArray(node)) node.forEach(visit)
572 else if (isJsonRecord(node)) Object.values(node).forEach(visit)
573 }
574 for (const row of rscRows(html).values()) visit(row)
575 return found
577​
578function meterAmount(meter: WidgetMeter): number {
579 const amount = meter.price
580 if (typeof amount !== 'number' || !Number.isFinite(amount)) {
581 throw new Error('mistral model page pricing: unreadable amount')
582 }
583 return amount
585​
586function priceFamily(
587 denominator: string,
588): 'tokens' | 'audio_minutes' | 'pages' | 'characters' | null {
589 switch (denominator.trim().toLowerCase()) {
590 case '/m tokens':
591 case '/mtokens':
592 return 'tokens'
593 case '/min':
594 case '/minute':
595 case '/minutes':
596 return 'audio_minutes'
597 case '/1000 pages':
598 case '/1000 page':
599 case '/1000 annotated pages':
600 case '/1000 annotated page':
601 return 'pages'
602 case '/m chars':
603 case '/m char':
604 case '/m characters':
605 return 'characters'
606 default:
607 return null
608 }
610​
611function tokenLever(
612 side: 'input' | 'output',
613 label: string | undefined,
614): string {
615 const name = (label ?? '').trim().toLowerCase()
616 if (side === 'output') {
617 if (name === '' || name === 'output') return 'output_tokens'
618 } else if (name === 'cached input' || name === 'cached') {
619 return 'cache_read_tokens'
620 } else if (name === '' || name === 'input') return 'input_tokens'
621 throw new Error(
622 `mistral model page pricing: unknown ${side} label ${label ?? ''}`,
623 )
625​
626function unitParam(
627 unit: MistralUnit,
628 side: 'input' | 'output',
629 label: string | undefined,
630): string {
631 const cached = (label ?? '').toLowerCase().includes('cached')
632 const names = UNIT_PARAMS[unit]
633 // Each unit tuple is [input, cached, output], so the index is present.
634 return side === 'output' ? names[2] : cached ? names[1] : names[0]
636​
637function widgetMeters(widget: JsonObject): Array<{
638 side: 'input' | 'output'
639 label?: string
640 denominator: string
641 amount: number
642}> {
643 if (widget.type === 'flat') {
644 if (widget.free === true) {
645 const amount =
646 typeof widget.price === 'number' && Number.isFinite(widget.price)
647 ? widget.price
648 : 0
649 if (amount > 0) {
650 throw new Error(
651 'mistral model page pricing: free widget has a positive price',
652 )
653 }
654 return []
655 }
656 const denominator = widget.denominator
657 if (typeof denominator !== 'string') {
658 throw new Error('mistral model page pricing: meter has no denominator')
659 }
660 const amount = meterAmount(widget)
661 return amount === 0 ? [] : [{ side: 'input', denominator, amount }]
662 }
663 const meters: Array<{
664 side: 'input' | 'output'
665 label?: string
666 denominator: string
667 amount: number
668 }> = []
669 for (const side of ['input', 'output'] as const) {
670 const list = widget[side]
671 if (!Array.isArray(list)) {
672 throw new Error('mistral model page pricing: meters are not a list')
673 }
674 for (const item of list) {
675 if (!isJsonRecord(item) || typeof item.denominator !== 'string') {
676 throw new Error('mistral model page pricing: meter has no denominator')
677 }
678 const amount = meterAmount(item)
679 if (amount < 0) {
680 throw new Error('mistral model page pricing: negative amount')
681 }
682 if (amount === 0) continue
683 meters.push({
684 side,
685 ...(typeof item.label === 'string' ? { label: item.label } : {}),
686 denominator: item.denominator,
687 amount,
688 })
689 }
690 }
691 if (widget.free === true) {
692 if (meters.length > 0) {
693 throw new Error(
694 'mistral model page pricing: free widget has a positive price',
695 )
696 }
697 return []
698 }
699 return meters
701​
702function listedFromMeters(
703 meters: ReturnType<typeof widgetMeters>,
704): MistralListedPrice | null {
705 if (meters.length === 0) return null
706 const tokenRates: Record<string, number> = {}
707 const units: Array<{ unit: MistralUnit; param: string; rate: number }> = []
708 for (const meter of meters) {
709 const family = priceFamily(meter.denominator)
710 if (!family) {
711 throw new Error(
712 `mistral model page pricing: unknown denominator ${meter.denominator}`,
713 )
714 }
715 if (family === 'tokens') {
716 const lever = tokenLever(meter.side, meter.label)
717 if (tokenRates[lever] !== undefined) {
718 throw new Error(`mistral model page pricing: repeated ${lever}`)
719 }
720 tokenRates[lever] = meter.amount / 1e6
721 continue
722 }
723 // The native OCR widget publishes annotated pages as a distinct billed
724 // quantity, not an ordinary-page rate or a surcharge on all pages.
725 const annotated = /^\/1000 annotated pages?$/i.test(
726 meter.denominator.trim(),
727 )
728 const param = annotated
729 ? meter.side === 'input'
730 ? 'annotated_pages'
731 : 'output_annotated_pages'
732 : unitParam(family, meter.side, meter.label)
733 if (units.some((unit) => unit.param === param)) {
734 throw new Error(`mistral model page pricing: repeated ${param}`)
735 }
736 const rate =
737 family === 'pages'
738 ? meter.amount / 1000
739 : family === 'characters'
740 ? meter.amount / 1e6
741 : meter.amount
742 units.push({ unit: family, param, rate })
743 }
744 if (Object.keys(tokenRates).length > 0 && units.length > 0) {
745 if (units.some((unit) => unit.unit !== 'audio_minutes')) {
746 throw new Error('mistral model page pricing: mixed units')
747 }
748 for (const unit of units) {
749 if (tokenRates[unit.param] !== undefined) {
750 throw new Error(`mistral model page pricing: repeated ${unit.param}`)
751 }
752 tokenRates[unit.param] = unit.rate
753 }
754 return { kind: 'tokens', rates: tokenRates }
755 }
756 if (Object.keys(tokenRates).length > 0) {
757 return { kind: 'tokens', rates: tokenRates }
758 }
759 const unit = units[0]?.unit
760 if (!unit || units.some((meter) => meter.unit !== unit)) {
761 throw new Error('mistral model page pricing: mixed units')
762 }
763 return {
764 kind: 'unit',
765 meters: units.map((meter, index) => ({
766 param: meter.param,
767 rate: meter.rate,
768 ...(index > 0 ? { default: 0 } : {}),
769 })),
770 }
772​
773/**
774 * The model page's pricing widget. `price` is the current billed amount;
775 * `originalPrice` is historical and never fills a missing price. `free` or
776 * an all-zero widget is no card. Unreadable or conflicting widgets throw.
777 */
778export function parseMistralPagePrice(html: string): MistralListedPrice | null {
779 const widgets = [
780 ...new Map(
781 pricingWidgets(html).map((widget) => [JSON.stringify(widget), widget]),
782 ).values(),
783 ]
784 if (widgets.length === 0) return null
785 const priced = widgets.flatMap((widget) => {
786 const value = listedFromMeters(widgetMeters(widget))
787 return value ? [value] : []
788 })
789 if (priced.length === 0) return null
790 const first = JSON.stringify(priced[0])
791 if (priced.some((row) => JSON.stringify(row) !== first)) {
792 throw new Error('mistral model page pricing: widgets disagree')
793 }
794 return priced[0] ?? null
796​
797export interface MistralModelPage {
798 slug: string
799 ids: Array<string>
800 hash: string
801 serverTools?: Array<string>
802 modalities?: MistralModalities | null
803 maxOutput?: number | null
804 pagePrice?: MistralListedPrice | null
805 extractedAt?: string
807​
808/**
809 * API id → rates. A priced slug with no ids throws: caching a partial map
810 * would drop those models' stored cards for the cache TTL.
811 */
812export function indexMistralApiIds(
813 bySlug: Map<string, MistralListedPrice>,
814 pages: Array<MistralModelPage>,
815): Map<string, MistralListedPrice> {
816 const bySlugPage = new Map(pages.map((page) => [page.slug, page]))
817 const missing = [...bySlug.keys()].filter(
818 (slug) => (bySlugPage.get(slug)?.ids.length ?? 0) === 0,
819 )
820 if (missing.length > 0) {
821 throw new Error(`mistral model pages: no API ids for ${missing.join(', ')}`)
822 }
823 const byId = new Map<string, MistralListedPrice>()
824 const conflicts = new Set<string>()
825 for (const page of pages) {
826 const rates = bySlug.get(page.slug)
827 if (!rates) continue
828 const serialized = JSON.stringify(rates)
829 for (const id of page.ids) {
830 const prior = byId.get(id)
831 if (!prior) {
832 byId.set(id, rates)
833 continue
834 }
835 if (JSON.stringify(prior) !== serialized) conflicts.add(id)
836 }
837 }
838 for (const id of conflicts) byId.delete(id)
839 return byId
841​
842type PricedFacts = Pick<
843 ModelInfo,
844 'pricing' | 'factSources' | 'serverTools' | 'modalities'
846​
847interface MistralStatedModalities {
848 modalities: MistralModalities
849 url: string
850 hash: string
852​
853/**
854 * API id → modalities its model page states. An id two pages state
855 * differently gets none, like a price.
856 *
857 * Pages the pricing table does not link are fetched only when a listed id
858 * matches one index slug: the slug itself, a trailing `-MMDD` unfolded to
859 * `-MM-DD`, or the id with a `labs-` prefix removed. Zero or several
860 * matches fetch nothing.
861 */
862export function indexMistralModalities(
863 pages: Array<MistralModelPage>,
864): Map<string, MistralStatedModalities> {
865 const out = new Map<string, MistralStatedModalities>()
866 const conflicts = new Set<string>()
867 for (const page of pages) {
868 if (!page.modalities) continue
869 const stated = {
870 modalities: page.modalities,
871 url: MISTRAL_MODEL_PAGE(page.slug),
872 hash: page.hash,
873 }
874 for (const id of page.ids) {
875 const prior = out.get(id)
876 if (!prior) out.set(id, stated)
877 else if (
878 JSON.stringify(prior.modalities) !== JSON.stringify(page.modalities)
879 ) {
880 conflicts.add(id)
881 }
882 }
883 }
884 for (const id of conflicts) out.delete(id)
885 return out
887​
888interface MistralHostedTools {
889 tools: Array<string>
890 url: string
891 hash: string
893​
894/** API id → tool ids named on a model page. Pages that name none are absent. */
895export function indexMistralServerTools(
896 pages: Array<MistralModelPage>,
897): Map<string, MistralHostedTools> {
898 const out = new Map<string, MistralHostedTools>()
899 for (const page of pages) {
900 const named = page.serverTools ?? []
901 if (named.length === 0) continue
902 const url = MISTRAL_MODEL_PAGE(page.slug)
903 for (const id of page.ids) {
904 const prior = out.get(id)
905 const tools = [...new Set([...(prior?.tools ?? []), ...named])].sort()
906 out.set(id, { tools, url, hash: page.hash })
907 }
908 }
909 return out
911​
912/**
913 * Deprecated id → successor, when the changelog says the successor is the
914 * same price. OCR and Voxtral stay out of this map (issue #116).
915 */
916export function parseMistralSamePrice(html: string): Map<string, string> {
917 const text = html
918 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
919 .replace(/<[^>]+>/g, ' ')
920 .replace(/\s+/g, ' ')
921 const out = new Map<string, string>()
922 const pattern =
923 /\(\s*([a-z0-9-]+)\s*\)\s+is deprecated[\s\S]{0,300}?Use[\s\S]{0,200}?\(\s*([a-z0-9-]+)\s*\)\s+instead, at the same price/gi
924 for (const match of text.matchAll(pattern)) {
925 const from = match[1]
926 const to = match[2]
927 if (!from || !to || from === to) continue
928 if (/ocr|voxtral|embed/.test(from) || /ocr|voxtral|embed/.test(to)) {
929 continue
930 }
931 out.set(from, to)
932 }
933 return out
935​
936export const MISTRAL_MODELS_INDEX = 'https://docs.mistral.ai/models'
937​
938const INDEX_SKIP = new Set(['overview', 'model-cards', 'model-selection-guide'])
939​
940/** Docs slugs linked from the models index. An empty parse throws. */
941export function parseMistralModelIndex(html: string): Array<string> {
942 const slugs = new Set<string>()
943 for (const match of html.matchAll(/\/models\/([a-z0-9-]+)/g)) {
944 const slug = match[1]
945 if (!slug || INDEX_SKIP.has(slug) || slug.startsWith('page-')) continue
946 slugs.add(slug)
947 }
948 return [...slugs]
950​
951/**
952 * The one index slug a listed id is. Null when none or more than one of
953 * the exact slug, the unfolded date, and the `labs-`-stripped id match.
954 */
955export function mistralIndexSlugFor(
956 id: string,
957 slugs: ReadonlySet<string>,
958): string | null {
959 const unfolded = id.replace(/-(\d{2})(\d{2})$/, '-$1-$2')
960 const stripped = id.startsWith('labs-') ? id.slice('labs-'.length) : id
961 const hits = [...new Set([id, unfolded, stripped])].filter((name) =>
962 slugs.has(name),
963 )
964 return hits.length === 1 ? (hits[0] ?? null) : null
966​
967interface PageSourced<T> {
968 value: T
969 url: string
970 hash: string
972​
973function indexPageField<T>(
974 pages: Array<MistralModelPage>,
975 read: (page: MistralModelPage) => T | null | undefined,
976): Map<string, PageSourced<T>> {
977 const out = new Map<string, PageSourced<T>>()
978 const conflicts = new Set<string>()
979 for (const page of pages) {
980 const value = read(page)
981 if (value == null) continue
982 const stated = {
983 value,
984 url: MISTRAL_MODEL_PAGE(page.slug),
985 hash: page.hash,
986 }
987 const serialized = JSON.stringify(value)
988 for (const id of page.ids) {
989 const prior = out.get(id)
990 if (!prior) out.set(id, stated)
991 else if (JSON.stringify(prior.value) !== serialized) conflicts.add(id)
992 }
993 }
994 for (const id of conflicts) out.delete(id)
995 return out
997​
998/** Card lookup by API model id. `seen` is every id a fetched page names. */
999export interface MistralPricingLookup {
1000 (rawId: string): PricedFacts
1001 seen: ReadonlySet<string>
1003​
1004/** Card lookup by API model id. */
1005export async function mistralModelPricing(
1006 kv?: KVNamespace,
1007 listedIds: ReadonlyArray<string> = [],
1008): Promise<MistralPricingLookup> {
1009 const table = await cachedDocs(kv, MISTRAL_PRICING_URL, async () => {
1010 const [html, changelog] = await Promise.all([
1011 fetchText(MISTRAL_PRICING_URL),
1012 fetchText(MISTRAL_CHANGELOG_URL),
1013 ])
1014 const bySlug = parseMistralPricing(html)
1015 assertParsed(bySlug, 'mistral pricing page')
1016 return {
1017 bySlug: Object.fromEntries(bySlug),
1018 samePrice: Object.fromEntries(parseMistralSamePrice(changelog)),
1019 hash: await sha256Text(html),
1020 extractedAt: new Date().toISOString(),
1022 })
1023 const bySlug = new Map(Object.entries(table.bySlug))
1024 const loadPage = async (slug: string): Promise<MistralModelPage> => {
1025 const url = MISTRAL_MODEL_PAGE(slug)
1026 const page = await cachedDocs(kv, url, async () => {
1027 const body = await fetchText(url)
1028 const ids = parseMistralApiIds(body, slug)
1029 if (ids.length === 0) {
1030 throw new Error(`mistral model page ${slug}: parsed 0 API ids`)
1032 return {
1033 ids,
1034 hash: await sha256Text(body),
1035 serverTools: parseMistralPageTools(body),
1036 modalities: parseMistralPageModalities(body),
1037 maxOutput: parseMistralPageMaxOutput(body),
1038 pagePrice: parseMistralPagePrice(body),
1039 extractedAt: new Date().toISOString(),
1041 })
1042 return { slug, ...page }
1044 const tablePages = await mapConcurrent([...bySlug.keys()], 6, loadPage)
1045 const covered = new Set(tablePages.flatMap((page) => page.ids))
1046 const missing = listedIds.filter((id) => !covered.has(id))
1047 let extraSlugs: Array<string> = []
1048 if (missing.length > 0) {
1049 const slugs = await cachedDocs(kv, MISTRAL_MODELS_INDEX, async () => {
1050 const html = await fetchText(MISTRAL_MODELS_INDEX)
1051 const parsed = parseMistralModelIndex(html)
1052 if (parsed.length === 0) {
1053 throw new Error('mistral models index: parsed 0 slugs')
1055 return parsed
1056 })
1057 const index = new Set(slugs)
1058 extraSlugs = [
1059 ...new Set(
1060 missing.flatMap((id) => {
1061 const slug = mistralIndexSlugFor(id, index)
1062 return slug && !bySlug.has(slug) ? [slug] : []
1063 }),
1064 ),
1067 const extraPages = await mapConcurrent(extraSlugs, 6, loadPage)
1068 const pages = [...tablePages, ...extraPages]
1069 const byId = indexMistralApiIds(bySlug, pages)
1070 for (const [from, to] of Object.entries(table.samePrice)) {
1071 const rates = byId.get(to)
1072 if (!rates || byId.has(from)) continue
1073 byId.set(from, rates)
1075 assertParsed(byId, 'mistral model pages')
1076 const tools = indexMistralServerTools(pages)
1077 // Every page read and none states modalities is a reshaped site, not
1078 // a catalog without media. Throwing keeps the stored column.
1079 if (!pages.some((page) => page.modalities)) {
1080 throw new Error(
1081 `mistral model pages: 0 of ${String(pages.length)} state modalities`,
1084 const modalities = indexMistralModalities(pages)
1085 const maxOutput = indexPageField(pages, (page) => page.maxOutput)
1086 const pageRates = indexPageField(pages, (page) => page.pagePrice)
1087 const seen = new Set(pages.flatMap((page) => page.ids))
1088 const lookup = (rawId: string): PricedFacts => {
1089 const tableRow = byId.get(rawId)
1090 const pageRow = pageRates.get(rawId)
1091 const row = tableRow ?? pageRow?.value
1092 const pricing = row
1093 ? mistralRateCard(
1094 row,
1095 tableRow
1096 ? {
1097 url: MISTRAL_PRICING_URL,
1098 hash: table.hash,
1099 extractedAt: table.extractedAt,
1101 : {
1102 url: pageRow?.url ?? MISTRAL_PRICING_URL,
1103 hash: pageRow?.hash ?? table.hash,
1104 extractedAt:
1105 pages.find((page) => page.ids.includes(rawId))?.extractedAt ??
1106 table.extractedAt,
1107 },
1109 : null
1110 const hosted = tools.get(rawId)
1111 const pricingFacts = pricing
1112 ? tagDocsFacts(
1113 { pricing },
1114 tableRow
1115 ? MISTRAL_PRICING_URL
1116 : (pageRow?.url ?? MISTRAL_PRICING_URL),
1117 tableRow ? table.hash : pageRow?.hash,
1119 : {}
1120 const toolFacts = hosted
1121 ? tagDocsFacts({ serverTools: hosted.tools }, hosted.url, hosted.hash)
1122 : {}
1123 const stated = modalities.get(rawId)
1124 const modalityFacts = stated
1125 ? tagDocsFacts({ modalities: stated.modalities }, stated.url, stated.hash)
1126 : {}
1127 const cap = maxOutput.get(rawId)
1128 const maxFacts = cap
1129 ? tagDocsFacts({ maxOutput: cap.value }, cap.url, cap.hash)
1130 : {}
1131 const factSources = {
1132 ...pricingFacts,
1133 ...toolFacts,
1134 ...modalityFacts,
1135 ...maxFacts,
1137 if (!pricing && !hosted && !stated && !cap) return {}
1138 return {
1139 ...(pricing ? { pricing } : {}),
1140 ...(hosted ? { serverTools: hosted.tools } : {}),
1141 ...(stated ? { modalities: stated.modalities } : {}),
1142 ...(cap ? { maxOutput: cap.value } : {}),
1143 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
1146 lookup.seen = seen
1147 return lookup
1149​
1150const ALIAS_FACTS = [
1151 'pricing',
1152 'modalities',
1153 'maxOutput',
1154 'reasoning',
1155 'serverTools',
1156] as const
1157​
1158/**
1159 * Copy a fact onto mutual listing aliases when every member that has it
1160 * agrees. A conflict copies nothing. The copy keeps the donor's docs URL.
1161 */
1162export function copyMistralAliasFacts(
1163 models: Array<ModelInfo>,
1164 aliases: ReadonlyMap<string, ReadonlyArray<string>>,
1165): void {
1166 const byId = new Map(models.map((model) => [model.rawId, model]))
1167 const parent = new Map<string, string>()
1168 const find = (id: string): string => {
1169 const root = parent.get(id) ?? id
1170 if (root === id) return id
1171 const found = find(root)
1172 parent.set(id, found)
1173 return found
1175 const union = (left: string, right: string) => {
1176 const a = find(left)
1177 const b = find(right)
1178 if (a !== b) parent.set(a, b)
1180 const grouped = new Set<string>()
1181 for (const [id, names] of aliases) {
1182 if (!byId.has(id)) continue
1183 for (const other of names) {
1184 if (other === id || !byId.has(other)) continue
1185 if (!aliases.get(other)?.includes(id)) continue
1186 union(id, other)
1187 grouped.add(id)
1188 grouped.add(other)
1191 const groups = new Map<string, Array<string>>()
1192 for (const id of grouped) {
1193 const root = find(id)
1194 const group = groups.get(root) ?? []
1195 group.push(id)
1196 groups.set(root, group)
1198 for (const group of groups.values()) {
1199 if (group.length < 2) continue
1200 for (const fact of ALIAS_FACTS) {
1201 const donors = group.flatMap((id) => {
1202 const model = byId.get(id)
1203 return model && model[fact] != null ? [model] : []
1204 })
1205 if (donors.length === 0) continue
1206 const first = donors[0]
1207 if (!first) continue
1208 const serialized = JSON.stringify(first[fact])
1209 if (donors.some((donor) => JSON.stringify(donor[fact]) !== serialized)) {
1210 continue
1212 for (const id of group) {
1213 const target = byId.get(id)
1214 if (!target || target[fact] != null) continue
1215 Object.assign(target, { [fact]: first[fact] })
1216 const source = first.factSources?.[fact]
1217 if (!source) continue
1218 target.factSources = { ...(target.factSources ?? {}), [fact]: source }