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

mistral-pricing.ts

1,291 lines41.9 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/** The feature ids of a grid that follows a "Features" heading. */
474function featureGrids(
475 rows: RscRows,
476 node: Json,
477 out: Array<Array<string> | null> = [],
478): Array<Array<string> | null> {
479 if (Array.isArray(node)) {
480 node.forEach((item, index) => {
481 const heading = rscProps(rscProps(item)?.children ?? null)?.children
482 const grid = rscProps(node[index + 1] ?? null)?.children
483 if (heading === 'Features' && Array.isArray(grid)) {
484 // Each feature is a `div` keyed by its id. Any other child, or one
485 // marked disabled, makes the grid unreadable rather than shorter.
486 const ids = grid.map((ref) => {
487 const child = deref(rows, ref)
488 const key = Array.isArray(child) ? child[2] : null
489 const props = rscProps(child)
490 return typeof key === 'string' &&
491 props?.['aria-disabled'] === '$undefined'
492 ? key
493 : null
494 })
495 out.push(ids.every((id) => id !== null) ? ids : null)
496 }
497 featureGrids(rows, item, out)
498 })
499 } else if (typeof node === 'object' && node !== null) {
500 for (const value of Object.values(node)) featureGrids(rows, value, out)
501 }
502 return out
504​
505/**
506 * Feature ids a model page lists under its "Features" heading
507 * (`document-qna`, `function-calling`, …), read from the RSC payload. Null
508 * when the page has no such grid. A grid it cannot fully read, or grids
509 * that disagree, throw: a shorter list would drop `file` from the row.
510 */
511export function parseMistralPageFeatures(html: string): Array<string> | null {
512 const rows = rscRows(html)
513 const grids = [...rows.values()].flatMap((row) => featureGrids(rows, row))
514 if (grids.length === 0) return null
515 const [first] = grids
516 if (
517 !first ||
518 grids.some((grid) => JSON.stringify(grid) !== JSON.stringify(first))
519 ) {
520 throw new Error('mistral model page: Features grid in an unread shape')
521 }
522 return first
524​
525/**
526 * A page's modalities with `file` input when it lists `document-qna`: the
527 * Document QnA guide sends PDFs to such a model as `document_url` chat
528 * content (#407). Without stated modalities nothing is added.
529 */
530export function withDocumentInput(
531 modalities: MistralModalities | null,
532 features: Array<string> | null,
533): MistralModalities | null {
534 if (!modalities || !features?.includes('document-qna')) return modalities
535 if (modalities.input.includes('file')) return modalities
536 return { ...modalities, input: [...modalities.input, 'file'] }
538​
539/** `128k` → 131072, `1M` → 1048576. Any other spelling is unreadable. */
540function suffixTokens(value: string): number | null {
541 const match = /^(\d+(?:\.\d+)?)(k|M)$/.exec(value)
542 if (!match?.[1] || !match[2]) return null
543 const tokens = Number(match[1]) * (match[2] === 'M' ? 1024 * 1024 : 1024)
544 return Number.isInteger(tokens) ? tokens : null
546​
547function statLabel(node: Json): string | null {
548 const props = rscProps(node)
549 const className = props?.className
550 if (typeof className !== 'string' || !className.includes('uppercase')) {
551 return null
552 }
553 const leaves: Array<string> = []
554 const walk = (value: Json) => {
555 if (typeof value === 'string') leaves.push(value)
556 else if (Array.isArray(value)) value.forEach(walk)
557 else if (typeof value === 'object' && value !== null) {
558 Object.values(value).forEach(walk)
559 }
560 }
561 walk(props?.children ?? null)
562 return leaves.includes('Max output') ? 'Max output' : null
564​
565function statValue(node: Json): string | null {
566 const props = rscProps(node)
567 const className = props?.className
568 if (
569 typeof className !== 'string' ||
570 !className.includes('text-lg font-bold font-mono text-primary-soft')
571 ) {
572 return null
573 }
574 return typeof props?.children === 'string' ? props.children : null
576​
577/**
578 * Tokens from the "Max output" stat. Null when the page has no such stat
579 * or two layouts disagree. The context stat uses the same value style and
580 * is not a max-output cap.
581 */
582export function parseMistralPageMaxOutput(html: string): number | null {
583 const values = new Set<number>()
584 // A closure write does not widen `let flag = false` (stays the literal
585 // `false`), so the unreadable mark lives on an object.
586 const mark = { unreadable: false }
587 const visit = (node: Json) => {
588 if (Array.isArray(node)) {
589 for (let index = 0; index < node.length - 1; index++) {
590 const current = node[index]
591 const next = node[index + 1]
592 if (current === undefined || next === undefined) continue
593 if (statLabel(current) !== 'Max output') continue
594 const raw = statValue(next)
595 const tokens = raw === null ? null : suffixTokens(raw)
596 if (tokens === null) mark.unreadable = true
597 else values.add(tokens)
598 }
599 node.forEach(visit)
600 return
601 }
602 if (typeof node === 'object' && node !== null) {
603 Object.values(node).forEach(visit)
604 }
605 }
606 for (const row of rscRows(html).values()) visit(row)
607 if (mark.unreadable || values.size !== 1) return null
608 return [...values][0] ?? null
610​
611interface WidgetMeter {
612 price?: number
613 originalPrice?: number
614 denominator?: string
615 label?: string
617​
618function isJsonRecord(value: Json): value is JsonObject {
619 return typeof value === 'object' && value !== null && !Array.isArray(value)
621​
622function pricingWidgets(html: string): Array<JsonObject> {
623 const found: Array<JsonObject> = []
624 const visit = (node: Json) => {
625 if (isJsonRecord(node)) {
626 const custom =
627 node.type === 'custom' &&
628 typeof node.free === 'boolean' &&
629 Array.isArray(node.input) &&
630 Array.isArray(node.output)
631 const flat =
632 node.type === 'flat' &&
633 typeof node.free === 'boolean' &&
634 typeof node.denominator === 'string'
635 if (custom || flat) found.push(node)
636 }
637 if (Array.isArray(node)) node.forEach(visit)
638 else if (isJsonRecord(node)) Object.values(node).forEach(visit)
639 }
640 for (const row of rscRows(html).values()) visit(row)
641 return found
643​
644function meterAmount(meter: WidgetMeter): number {
645 const amount = meter.price
646 if (typeof amount !== 'number' || !Number.isFinite(amount)) {
647 throw new Error('mistral model page pricing: unreadable amount')
648 }
649 return amount
651​
652function priceFamily(
653 denominator: string,
654): 'tokens' | 'audio_minutes' | 'pages' | 'characters' | null {
655 switch (denominator.trim().toLowerCase()) {
656 case '/m tokens':
657 case '/mtokens':
658 return 'tokens'
659 case '/min':
660 case '/minute':
661 case '/minutes':
662 return 'audio_minutes'
663 case '/1000 pages':
664 case '/1000 page':
665 case '/1000 annotated pages':
666 case '/1000 annotated page':
667 return 'pages'
668 case '/m chars':
669 case '/m char':
670 case '/m characters':
671 return 'characters'
672 default:
673 return null
674 }
676​
677function tokenLever(
678 side: 'input' | 'output',
679 label: string | undefined,
680): string {
681 const name = (label ?? '').trim().toLowerCase()
682 if (side === 'output') {
683 if (name === '' || name === 'output') return 'output_tokens'
684 } else if (name === 'cached input' || name === 'cached') {
685 return 'cache_read_tokens'
686 } else if (name === '' || name === 'input') return 'input_tokens'
687 throw new Error(
688 `mistral model page pricing: unknown ${side} label ${label ?? ''}`,
689 )
691​
692function unitParam(
693 unit: MistralUnit,
694 side: 'input' | 'output',
695 label: string | undefined,
696): string {
697 const cached = (label ?? '').toLowerCase().includes('cached')
698 const names = UNIT_PARAMS[unit]
699 // Each unit tuple is [input, cached, output], so the index is present.
700 return side === 'output' ? names[2] : cached ? names[1] : names[0]
702​
703function widgetMeters(widget: JsonObject): Array<{
704 side: 'input' | 'output'
705 label?: string
706 denominator: string
707 amount: number
708}> {
709 if (widget.type === 'flat') {
710 if (widget.free === true) {
711 const amount =
712 typeof widget.price === 'number' && Number.isFinite(widget.price)
713 ? widget.price
714 : 0
715 if (amount > 0) {
716 throw new Error(
717 'mistral model page pricing: free widget has a positive price',
718 )
719 }
720 return []
721 }
722 const denominator = widget.denominator
723 if (typeof denominator !== 'string') {
724 throw new Error('mistral model page pricing: meter has no denominator')
725 }
726 const amount = meterAmount(widget)
727 return amount === 0 ? [] : [{ side: 'input', denominator, amount }]
728 }
729 const meters: Array<{
730 side: 'input' | 'output'
731 label?: string
732 denominator: string
733 amount: number
734 }> = []
735 for (const side of ['input', 'output'] as const) {
736 const list = widget[side]
737 if (!Array.isArray(list)) {
738 throw new Error('mistral model page pricing: meters are not a list')
739 }
740 for (const item of list) {
741 if (!isJsonRecord(item) || typeof item.denominator !== 'string') {
742 throw new Error('mistral model page pricing: meter has no denominator')
743 }
744 const amount = meterAmount(item)
745 if (amount < 0) {
746 throw new Error('mistral model page pricing: negative amount')
747 }
748 if (amount === 0) continue
749 meters.push({
750 side,
751 ...(typeof item.label === 'string' ? { label: item.label } : {}),
752 denominator: item.denominator,
753 amount,
754 })
755 }
756 }
757 if (widget.free === true) {
758 if (meters.length > 0) {
759 throw new Error(
760 'mistral model page pricing: free widget has a positive price',
761 )
762 }
763 return []
764 }
765 return meters
767​
768function listedFromMeters(
769 meters: ReturnType<typeof widgetMeters>,
770): MistralListedPrice | null {
771 if (meters.length === 0) return null
772 const tokenRates: Record<string, number> = {}
773 const units: Array<{ unit: MistralUnit; param: string; rate: number }> = []
774 for (const meter of meters) {
775 const family = priceFamily(meter.denominator)
776 if (!family) {
777 throw new Error(
778 `mistral model page pricing: unknown denominator ${meter.denominator}`,
779 )
780 }
781 if (family === 'tokens') {
782 const lever = tokenLever(meter.side, meter.label)
783 if (tokenRates[lever] !== undefined) {
784 throw new Error(`mistral model page pricing: repeated ${lever}`)
785 }
786 tokenRates[lever] = meter.amount / 1e6
787 continue
788 }
789 // The native OCR widget publishes annotated pages as a distinct billed
790 // quantity, not an ordinary-page rate or a surcharge on all pages.
791 const annotated = /^\/1000 annotated pages?$/i.test(
792 meter.denominator.trim(),
793 )
794 const param = annotated
795 ? meter.side === 'input'
796 ? 'annotated_pages'
797 : 'output_annotated_pages'
798 : unitParam(family, meter.side, meter.label)
799 if (units.some((unit) => unit.param === param)) {
800 throw new Error(`mistral model page pricing: repeated ${param}`)
801 }
802 const rate =
803 family === 'pages'
804 ? meter.amount / 1000
805 : family === 'characters'
806 ? meter.amount / 1e6
807 : meter.amount
808 units.push({ unit: family, param, rate })
809 }
810 if (Object.keys(tokenRates).length > 0 && units.length > 0) {
811 if (units.some((unit) => unit.unit !== 'audio_minutes')) {
812 throw new Error('mistral model page pricing: mixed units')
813 }
814 for (const unit of units) {
815 if (tokenRates[unit.param] !== undefined) {
816 throw new Error(`mistral model page pricing: repeated ${unit.param}`)
817 }
818 tokenRates[unit.param] = unit.rate
819 }
820 return { kind: 'tokens', rates: tokenRates }
821 }
822 if (Object.keys(tokenRates).length > 0) {
823 return { kind: 'tokens', rates: tokenRates }
824 }
825 const unit = units[0]?.unit
826 if (!unit || units.some((meter) => meter.unit !== unit)) {
827 throw new Error('mistral model page pricing: mixed units')
828 }
829 return {
830 kind: 'unit',
831 meters: units.map((meter, index) => ({
832 param: meter.param,
833 rate: meter.rate,
834 ...(index > 0 ? { default: 0 } : {}),
835 })),
836 }
838​
839/**
840 * The model page's pricing widget. `price` is the current billed amount;
841 * `originalPrice` is historical and never fills a missing price. `free` or
842 * an all-zero widget is no card. Unreadable or conflicting widgets throw.
843 */
844export function parseMistralPagePrice(html: string): MistralListedPrice | null {
845 const widgets = [
846 ...new Map(
847 pricingWidgets(html).map((widget) => [JSON.stringify(widget), widget]),
848 ).values(),
849 ]
850 if (widgets.length === 0) return null
851 const priced = widgets.flatMap((widget) => {
852 const value = listedFromMeters(widgetMeters(widget))
853 return value ? [value] : []
854 })
855 if (priced.length === 0) return null
856 const first = JSON.stringify(priced[0])
857 if (priced.some((row) => JSON.stringify(row) !== first)) {
858 throw new Error('mistral model page pricing: widgets disagree')
859 }
860 return priced[0] ?? null
862​
863export interface MistralModelPage {
864 slug: string
865 ids: Array<string>
866 hash: string
867 serverTools?: Array<string>
868 modalities?: MistralModalities | null
869 maxOutput?: number | null
870 pagePrice?: MistralListedPrice | null
871 extractedAt?: string
873​
874/**
875 * API id → rates. A priced slug with no ids throws: caching a partial map
876 * would drop those models' stored cards for the cache TTL.
877 */
878export function indexMistralApiIds(
879 bySlug: Map<string, MistralListedPrice>,
880 pages: Array<MistralModelPage>,
881): Map<string, MistralListedPrice> {
882 const bySlugPage = new Map(pages.map((page) => [page.slug, page]))
883 const missing = [...bySlug.keys()].filter(
884 (slug) => (bySlugPage.get(slug)?.ids.length ?? 0) === 0,
885 )
886 if (missing.length > 0) {
887 throw new Error(`mistral model pages: no API ids for ${missing.join(', ')}`)
888 }
889 const byId = new Map<string, MistralListedPrice>()
890 const conflicts = new Set<string>()
891 for (const page of pages) {
892 const rates = bySlug.get(page.slug)
893 if (!rates) continue
894 const serialized = JSON.stringify(rates)
895 for (const id of page.ids) {
896 const prior = byId.get(id)
897 if (!prior) {
898 byId.set(id, rates)
899 continue
900 }
901 if (JSON.stringify(prior) !== serialized) conflicts.add(id)
902 }
903 }
904 for (const id of conflicts) byId.delete(id)
905 return byId
907​
908type PricedFacts = Pick<
909 ModelInfo,
910 'pricing' | 'factSources' | 'serverTools' | 'modalities'
912​
913interface MistralStatedModalities {
914 modalities: MistralModalities
915 url: string
916 hash: string
918​
919/**
920 * API id → modalities its model page states. An id two pages state
921 * differently gets none, like a price.
922 *
923 * Pages the pricing table does not link are fetched only when a listed id
924 * matches one index slug: the slug itself, a trailing `-MMDD` unfolded to
925 * `-MM-DD`, or the id with a `labs-` prefix removed. Zero or several
926 * matches fetch nothing.
927 */
928export function indexMistralModalities(
929 pages: Array<MistralModelPage>,
930): Map<string, MistralStatedModalities> {
931 const out = new Map<string, MistralStatedModalities>()
932 const conflicts = new Set<string>()
933 for (const page of pages) {
934 if (!page.modalities) continue
935 const stated = {
936 modalities: page.modalities,
937 url: MISTRAL_MODEL_PAGE(page.slug),
938 hash: page.hash,
939 }
940 for (const id of page.ids) {
941 const prior = out.get(id)
942 if (!prior) out.set(id, stated)
943 else if (
944 JSON.stringify(prior.modalities) !== JSON.stringify(page.modalities)
945 ) {
946 conflicts.add(id)
947 }
948 }
949 }
950 for (const id of conflicts) out.delete(id)
951 return out
953​
954interface MistralHostedTools {
955 tools: Array<string>
956 url: string
957 hash: string
959​
960/** API id → tool ids named on a model page. Pages that name none are absent. */
961export function indexMistralServerTools(
962 pages: Array<MistralModelPage>,
963): Map<string, MistralHostedTools> {
964 const out = new Map<string, MistralHostedTools>()
965 for (const page of pages) {
966 const named = page.serverTools ?? []
967 if (named.length === 0) continue
968 const url = MISTRAL_MODEL_PAGE(page.slug)
969 for (const id of page.ids) {
970 const prior = out.get(id)
971 const tools = [...new Set([...(prior?.tools ?? []), ...named])].sort()
972 out.set(id, { tools, url, hash: page.hash })
973 }
974 }
975 return out
977​
978/**
979 * Deprecated id → successor, when the changelog says the successor is the
980 * same price. OCR and Voxtral stay out of this map (issue #116).
981 */
982export function parseMistralSamePrice(html: string): Map<string, string> {
983 const text = html
984 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
985 .replace(/<[^>]+>/g, ' ')
986 .replace(/\s+/g, ' ')
987 const out = new Map<string, string>()
988 const pattern =
989 /\(\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
990 for (const match of text.matchAll(pattern)) {
991 const from = match[1]
992 const to = match[2]
993 if (!from || !to || from === to) continue
994 if (/ocr|voxtral|embed/.test(from) || /ocr|voxtral|embed/.test(to)) {
995 continue
996 }
997 out.set(from, to)
998 }
999 return out
1001​
1002export const MISTRAL_MODELS_INDEX = 'https://docs.mistral.ai/models'
1003​
1004const INDEX_SKIP = new Set(['overview', 'model-cards', 'model-selection-guide'])
1005​
1006/** Docs slugs linked from the models index. An empty parse throws. */
1007export function parseMistralModelIndex(html: string): Array<string> {
1008 const slugs = new Set<string>()
1009 for (const match of html.matchAll(/\/models\/([a-z0-9-]+)/g)) {
1010 const slug = match[1]
1011 if (!slug || INDEX_SKIP.has(slug) || slug.startsWith('page-')) continue
1012 slugs.add(slug)
1014 return [...slugs]
1016​
1017/**
1018 * The one index slug a listed id is. Null when none or more than one of
1019 * the exact slug, the unfolded date, and the `labs-`-stripped id match.
1020 */
1021export function mistralIndexSlugFor(
1022 id: string,
1023 slugs: ReadonlySet<string>,
1024): string | null {
1025 const unfolded = id.replace(/-(\d{2})(\d{2})$/, '-$1-$2')
1026 const stripped = id.startsWith('labs-') ? id.slice('labs-'.length) : id
1027 const hits = [...new Set([id, unfolded, stripped])].filter((name) =>
1028 slugs.has(name),
1030 return hits.length === 1 ? (hits[0] ?? null) : null
1032​
1033interface PageSourced<T> {
1034 value: T
1035 url: string
1036 hash: string
1038​
1039function indexPageField<T>(
1040 pages: Array<MistralModelPage>,
1041 read: (page: MistralModelPage) => T | null | undefined,
1042): Map<string, PageSourced<T>> {
1043 const out = new Map<string, PageSourced<T>>()
1044 const conflicts = new Set<string>()
1045 for (const page of pages) {
1046 const value = read(page)
1047 if (value == null) continue
1048 const stated = {
1049 value,
1050 url: MISTRAL_MODEL_PAGE(page.slug),
1051 hash: page.hash,
1053 const serialized = JSON.stringify(value)
1054 for (const id of page.ids) {
1055 const prior = out.get(id)
1056 if (!prior) out.set(id, stated)
1057 else if (JSON.stringify(prior.value) !== serialized) conflicts.add(id)
1060 for (const id of conflicts) out.delete(id)
1061 return out
1063​
1064/** Card lookup by API model id. `seen` is every id a fetched page names. */
1065export interface MistralPricingLookup {
1066 (rawId: string): PricedFacts
1067 seen: ReadonlySet<string>
1069​
1070/** Card lookup by API model id. */
1071export async function mistralModelPricing(
1072 kv?: KVNamespace,
1073 listedIds: ReadonlyArray<string> = [],
1074): Promise<MistralPricingLookup> {
1075 const table = await cachedDocs(kv, MISTRAL_PRICING_URL, async () => {
1076 const [html, changelog] = await Promise.all([
1077 fetchText(MISTRAL_PRICING_URL),
1078 fetchText(MISTRAL_CHANGELOG_URL),
1079 ])
1080 const bySlug = parseMistralPricing(html)
1081 assertParsed(bySlug, 'mistral pricing page')
1082 return {
1083 bySlug: Object.fromEntries(bySlug),
1084 samePrice: Object.fromEntries(parseMistralSamePrice(changelog)),
1085 hash: await sha256Text(html),
1086 extractedAt: new Date().toISOString(),
1088 })
1089 const bySlug = new Map(Object.entries(table.bySlug))
1090 const loadPage = async (slug: string): Promise<MistralModelPage> => {
1091 const url = MISTRAL_MODEL_PAGE(slug)
1092 const page = await cachedDocs(kv, url, async () => {
1093 const body = await fetchText(url)
1094 const ids = parseMistralApiIds(body, slug)
1095 if (ids.length === 0) {
1096 throw new Error(`mistral model page ${slug}: parsed 0 API ids`)
1098 return {
1099 ids,
1100 hash: await sha256Text(body),
1101 serverTools: parseMistralPageTools(body),
1102 modalities: withDocumentInput(
1103 parseMistralPageModalities(body),
1104 parseMistralPageFeatures(body),
1105 ),
1106 maxOutput: parseMistralPageMaxOutput(body),
1107 pagePrice: parseMistralPagePrice(body),
1108 extractedAt: new Date().toISOString(),
1110 })
1111 return { slug, ...page }
1113 const tablePages = await mapConcurrent([...bySlug.keys()], 6, loadPage)
1114 const covered = new Set(tablePages.flatMap((page) => page.ids))
1115 const missing = listedIds.filter((id) => !covered.has(id))
1116 let extraSlugs: Array<string> = []
1117 if (missing.length > 0) {
1118 const slugs = await cachedDocs(kv, MISTRAL_MODELS_INDEX, async () => {
1119 const html = await fetchText(MISTRAL_MODELS_INDEX)
1120 const parsed = parseMistralModelIndex(html)
1121 if (parsed.length === 0) {
1122 throw new Error('mistral models index: parsed 0 slugs')
1124 return parsed
1125 })
1126 const index = new Set(slugs)
1127 extraSlugs = [
1128 ...new Set(
1129 missing.flatMap((id) => {
1130 const slug = mistralIndexSlugFor(id, index)
1131 return slug && !bySlug.has(slug) ? [slug] : []
1132 }),
1133 ),
1136 const extraPages = await mapConcurrent(extraSlugs, 6, loadPage)
1137 const pages = [...tablePages, ...extraPages]
1138 const byId = indexMistralApiIds(bySlug, pages)
1139 for (const [from, to] of Object.entries(table.samePrice)) {
1140 const rates = byId.get(to)
1141 if (!rates || byId.has(from)) continue
1142 byId.set(from, rates)
1144 assertParsed(byId, 'mistral model pages')
1145 const tools = indexMistralServerTools(pages)
1146 // Every page read and none states modalities is a reshaped site, not
1147 // a catalog without media. Throwing keeps the stored column.
1148 if (!pages.some((page) => page.modalities)) {
1149 throw new Error(
1150 `mistral model pages: 0 of ${String(pages.length)} state modalities`,
1153 const modalities = indexMistralModalities(pages)
1154 const maxOutput = indexPageField(pages, (page) => page.maxOutput)
1155 const pageRates = indexPageField(pages, (page) => page.pagePrice)
1156 const seen = new Set(pages.flatMap((page) => page.ids))
1157 const lookup = (rawId: string): PricedFacts => {
1158 const tableRow = byId.get(rawId)
1159 const pageRow = pageRates.get(rawId)
1160 const row = tableRow ?? pageRow?.value
1161 const pricing = row
1162 ? mistralRateCard(
1163 row,
1164 tableRow
1165 ? {
1166 url: MISTRAL_PRICING_URL,
1167 hash: table.hash,
1168 extractedAt: table.extractedAt,
1170 : {
1171 url: pageRow?.url ?? MISTRAL_PRICING_URL,
1172 hash: pageRow?.hash ?? table.hash,
1173 extractedAt:
1174 pages.find((page) => page.ids.includes(rawId))?.extractedAt ??
1175 table.extractedAt,
1176 },
1178 : null
1179 const hosted = tools.get(rawId)
1180 const pricingFacts = pricing
1181 ? tagDocsFacts(
1182 { pricing },
1183 tableRow
1184 ? MISTRAL_PRICING_URL
1185 : (pageRow?.url ?? MISTRAL_PRICING_URL),
1186 tableRow ? table.hash : pageRow?.hash,
1188 : {}
1189 const toolFacts = hosted
1190 ? tagDocsFacts({ serverTools: hosted.tools }, hosted.url, hosted.hash)
1191 : {}
1192 const stated = modalities.get(rawId)
1193 const modalityFacts = stated
1194 ? tagDocsFacts({ modalities: stated.modalities }, stated.url, stated.hash)
1195 : {}
1196 const cap = maxOutput.get(rawId)
1197 const maxFacts = cap
1198 ? tagDocsFacts({ maxOutput: cap.value }, cap.url, cap.hash)
1199 : {}
1200 const factSources = {
1201 ...pricingFacts,
1202 ...toolFacts,
1203 ...modalityFacts,
1204 ...maxFacts,
1206 if (!pricing && !hosted && !stated && !cap) return {}
1207 return {
1208 ...(pricing ? { pricing } : {}),
1209 ...(hosted ? { serverTools: hosted.tools } : {}),
1210 ...(stated ? { modalities: stated.modalities } : {}),
1211 ...(cap ? { maxOutput: cap.value } : {}),
1212 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
1215 lookup.seen = seen
1216 return lookup
1218​
1219const ALIAS_FACTS = [
1220 'pricing',
1221 'modalities',
1222 'maxOutput',
1223 'reasoning',
1224 'serverTools',
1225] as const
1226​
1227/**
1228 * Copy a fact onto mutual listing aliases when every member that has it
1229 * agrees. A conflict copies nothing. The copy keeps the donor's docs URL.
1230 */
1231export function copyMistralAliasFacts(
1232 models: Array<ModelInfo>,
1233 aliases: ReadonlyMap<string, ReadonlyArray<string>>,
1234): void {
1235 const byId = new Map(models.map((model) => [model.rawId, model]))
1236 const parent = new Map<string, string>()
1237 const find = (id: string): string => {
1238 const root = parent.get(id) ?? id
1239 if (root === id) return id
1240 const found = find(root)
1241 parent.set(id, found)
1242 return found
1244 const union = (left: string, right: string) => {
1245 const a = find(left)
1246 const b = find(right)
1247 if (a !== b) parent.set(a, b)
1249 const grouped = new Set<string>()
1250 for (const [id, names] of aliases) {
1251 if (!byId.has(id)) continue
1252 for (const other of names) {
1253 if (other === id || !byId.has(other)) continue
1254 if (!aliases.get(other)?.includes(id)) continue
1255 union(id, other)
1256 grouped.add(id)
1257 grouped.add(other)
1260 const groups = new Map<string, Array<string>>()
1261 for (const id of grouped) {
1262 const root = find(id)
1263 const group = groups.get(root) ?? []
1264 group.push(id)
1265 groups.set(root, group)
1267 for (const group of groups.values()) {
1268 if (group.length < 2) continue
1269 for (const fact of ALIAS_FACTS) {
1270 const donors = group.flatMap((id) => {
1271 const model = byId.get(id)
1272 return model && model[fact] != null ? [model] : []
1273 })
1274 if (donors.length === 0) continue
1275 const first = donors[0]
1276 if (!first) continue
1277 const serialized = JSON.stringify(first[fact])
1278 if (donors.some((donor) => JSON.stringify(donor[fact]) !== serialized)) {
1279 continue
1281 for (const id of group) {
1282 const target = byId.get(id)
1283 if (!target || target[fact] != null) continue
1284 Object.assign(target, { [fact]: first[fact] })
1285 const source = first.factSources?.[fact]
1286 if (!source) continue
1287 target.factSources = { ...(target.factSources ?? {}), [fact]: source }