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

minimax-docs.ts

576 lines21.3 KB

1/**
2 * MiniMax chat facts from platform.minimax.io. The Anthropic SDK page has
3 * the context-window, thinking, and content-type tables. The chat spec
4 * states the output cap. The pay-as-you-go page has the token prices, USD
5 * per 1M tokens. A parse that finds no rows throws.
6 *
7 * The China platform (platform.minimaxi.com) publishes the same pages in
8 * Chinese: `MINIMAX_CN` holds its URLs and wording. Its prices are yuan
9 * per 1M tokens, stored as CNY cards.
10 */
11import { compileTokenCard } from '@modelschemas/rate-card'
12import type { TokenRateTier } from '@modelschemas/rate-card'
13​
14import { tagDocsFacts } from './fact-sources.ts'
15import {
16 assertParsed,
17 cachedDocs,
18 markdownSection,
19 markdownTableRows,
20 tokenCount,
21} from './model-facts.ts'
22import type { ModelFacts } from './model-facts.ts'
23import { sha256Text } from './types.ts'
24import type { ModelReasoning } from './types.ts'
25​
26const DOCS = 'https://platform.minimax.io/docs'
27export const MINIMAX_SDK_URL = `${DOCS}/api-reference/text-anthropic-api.md`
28export const MINIMAX_PRICING_URL = `${DOCS}/guides/pricing-paygo.md`
29export const MINIMAX_CHAT_SPEC_URL = `${DOCS}/api-reference/text/api/openapi-chat-openai.json`
30export const MINIMAX_MESSAGES_SPEC_URL = `${DOCS}/api-reference/text/api/openapi-chat-anthropic.json`
31​
32const ID_PREFIX = 'MiniMax-'
33​
34/** One platform's page URLs and the wording its tables and spec use. */
35export interface MinimaxPlatform {
36 /** Names the platform in a zero-row parse error. */
37 label: string
38 /** Hosts allowed to answer a page fetch, redirects included. */
39 hosts: Array<string>
40 sdkUrl: string
41 chatSpecUrl: string
42 pricingUrl: string
43 /** ISO-4217 code of the pricing page's amounts; absent for USD. */
44 currency?: string
45 /** `## <heading>` of the token-price tables. */
46 priceSection: string
47 /** Title of the standard-tier `<Tab>`; every other tab is dropped. */
48 standardTab: string
49 /**
50 * Title of the only `<Accordion>` whose rows are standard prices. One
51 * with any other title is ignored when it holds no price row, and
52 * refuses the section when it does.
53 */
54 legacyAccordion: string
55 /** First header cell of a price table. */
56 modelHeader: string
57 /** Price-table header cell → the usage lever it prices. */
58 priceLevers: Record<string, string>
59 /** A billed price cell, whole: group 1 is the amount per 1M tokens. */
60 price: RegExp
61 /** The badge that makes a struck price the standing one. */
62 permanent: RegExp
63 /** A model cell's tier bound: group 1 is `≤` or `>`, group 2 the count. */
64 inputBound: RegExp
65 /** Header of the context-window column. */
66 contextWindow: string
67 /** `Messages Field Support` status: every model. */
68 allModels: RegExp
69 /**
70 * Status naming the only models that take the type: group 1 is the
71 * `M3.1-Flash-Preview / M3` list and nothing else may follow it.
72 */
73 onlyModels: RegExp
74 /** `Thinking Control` cells, each anchored to the end of the cell. */
75 thinkingOn: RegExp
76 cannotDisable: RegExp
77 thinkingOff: RegExp
78 /** Group 1 is the effort list in the `output_config.effort` row. */
79 efforts: RegExp
80 /** Splits the `max_completion_tokens` description into clauses. */
81 clause: RegExp
82 /** Group 1 is a clause's maximum, a plain token count. */
83 maximum: RegExp
84 otherModels: RegExp
86​
87export const MINIMAX: MinimaxPlatform = {
88 label: 'minimax',
89 hosts: ['platform.minimax.io'],
90 sdkUrl: MINIMAX_SDK_URL,
91 chatSpecUrl: MINIMAX_CHAT_SPEC_URL,
92 pricingUrl: MINIMAX_PRICING_URL,
93 priceSection: 'LLM',
94 standardTab: 'Standard',
95 legacyAccordion: 'Legacy Models',
96 modelHeader: 'Model',
97 priceLevers: {
98 Input: 'input_tokens',
99 Output: 'output_tokens',
100 'Prompt caching Read': 'cache_read_tokens',
101 'Prompt caching Write': 'cache_write_tokens',
102 },
103 price: /^\\?\$([\d.]+) \/ M tokens$/,
104 permanent: /<span[^>]*>\s*Permanent\b/,
105 inputBound: /([≤>])\s*([\d.]+[kKmM]?) input tokens/,
106 contextWindow: 'Context Window',
107 allModels: /^fully supported$/i,
108 onlyModels: /^(M\d[\w.-]*(?:\s*\/\s*M\d[\w.-]*)*) only$/i,
109 thinkingOn: /^thinking on$/i,
110 cannotDisable: /(?:^|[—;,] )thinking (?:cannot be disabled|remains on)$/i,
111 thinkingOff: /^thinking stays off$/i,
112 efforts: /Accepts ([^;.]+)/,
113 clause: /;|\.\s/,
114 maximum: /the maximum is ([\d,]+)/i,
115 otherModels: /other models/i,
117​
118const DOCS_CN = 'https://platform.minimaxi.com/docs'
119export const MINIMAX_CN_MESSAGES_SPEC_URL = `${DOCS_CN}/api-reference/text/api/openapi-chat-anthropic.json`
120​
121export const MINIMAX_CN: MinimaxPlatform = {
122 label: 'minimax-cn',
123 // platform.minimaxi.com answers 302 to the same path on platform.minimax.cn.
124 hosts: ['platform.minimaxi.com', 'platform.minimax.cn'],
125 sdkUrl: `${DOCS_CN}/api-reference/text-anthropic-api.md`,
126 chatSpecUrl: `${DOCS_CN}/api-reference/text/api/openapi-chat-openai.json`,
127 pricingUrl: `${DOCS_CN}/guides/pricing-paygo.md`,
128 currency: 'CNY',
129 priceSection: '语言模型',
130 standardTab: '标准',
131 legacyAccordion: '历史模型',
132 modelHeader: '**模型**',
133 // The header carries the unit, so a reworded unit prices nothing.
134 priceLevers: {
135 '**输入价格**<br /> 元/百万 tokens': 'input_tokens',
136 '**输出价格**<br /> 元/百万 tokens': 'output_tokens',
137 '**缓存读取**<br /> 元/百万 tokens': 'cache_read_tokens',
138 '**缓存写入**<br /> 元/百万 tokens': 'cache_write_tokens',
139 },
140 price: /^(\d+(?:\.\d+)?)$/,
141 permanent: /<span[^>]*>\s*永久/,
142 inputBound: /([≤>])\s*([\d.]+[kKmM]?) 输入 tokens/,
143 contextWindow: '上下文窗口',
144 allModels: /^完全支持$/,
145 onlyModels: /^仅\s*(M\d[\w.-]*(?:\s*\/\s*M\d[\w.-]*)*)$/,
146 thinkingOn: /^开启 thinking$/,
147 cannotDisable: /(?:^|,)thinking (?:无法关闭|仍保持开启)$/,
148 thinkingOff: /^保持 thinking 关闭$/,
149 efforts: /可取([^;。]+)/,
150 clause: /;|。/,
151 // `推荐值上限为` is a cap on the recommended value, not on output.
152 maximum: /(?<!推荐值)上限为\s*([\d,]+)/,
153 otherModels: /其他模型/,
155​
156/** `MiniMax-M3` must not match inside `MiniMax-M3.1-Flash-Preview`. */
157function names(text: string, id: string): boolean {
158 const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
159 return new RegExp(`(?<![\\w.-])${escaped}(?![\\w-]|\\.\\w)`).test(text)
161​
162/** The `Model Name | Context Window` table. */
163export function parseMinimaxContextWindows(
164 markdown: string,
165 platform: MinimaxPlatform = MINIMAX,
166): Map<string, number> {
167 const out = new Map<string, number>()
168 let column = -1
169 for (const cells of markdownTableRows(markdown)) {
170 const header = cells.indexOf(platform.contextWindow)
171 if (header >= 0) {
172 column = header
173 continue
174 }
175 const id = (cells[0] ?? '').replace(/<[^>]+>/g, '').trim()
176 const window = cells[column] ?? ''
177 if (!id.startsWith(ID_PREFIX) || !/^[\d,]+$/.test(window)) continue
178 const tokens = tokenCount(window)
179 if (tokens !== null) out.set(id, tokens)
180 }
181 return out
183​
184const INPUT_TYPES = new Set(['text', 'image', 'video', 'audio'])
185​
186/**
187 * The `Messages Field Support` table. A `type="image"` row is every model
188 * when its status is `Fully supported`, and otherwise only the models the
189 * status names (`M3.1-Flash-Preview / M3 only`). Empty when a status reads
190 * as neither or names a model the page does not list, so a reworded row
191 * (`M2.x not supported`) cannot move a type between models.
192 */
193export function parseMinimaxInputModalities(
194 markdown: string,
195 ids: Array<string>,
196 platform: MinimaxPlatform = MINIMAX,
197): Map<string, Array<string>> {
198 const out = new Map<string, Array<string>>()
199 for (const cells of markdownTableRows(markdown)) {
200 const type = cells[0]?.match(/^`type="(\w+)"`$/)?.[1]
201 const status = cells[1] ?? ''
202 if (!type || !INPUT_TYPES.has(type)) continue
203 const everyModel = platform.allModels.test(status)
204 const only = status.match(platform.onlyModels)?.[1]
205 if (!everyModel && only === undefined) return new Map()
206 const named = everyModel
207 ? ids
208 : [...(only ?? '').matchAll(/\bM\d[\w.-]*/g)].map(
209 (match) => `${ID_PREFIX}${match[0]}`,
210 )
211 if (named.some((id) => !ids.includes(id))) return new Map()
212 for (const id of named) {
213 out.set(id, [...(out.get(id) ?? []), type])
214 }
215 }
216 return out
218​
219/**
220 * The `Thinking Control` table: every model takes `thinking.type: adaptive`,
221 * and the `disabled` column says whether thinking can be turned off. A
222 * `M2.x` row covers the listed `MiniMax-M2…` ids that have no row of their
223 * own. Effort names come from the `output_config.effort` parameter row,
224 * for the models that row names.
225 */
226export function parseMinimaxReasoning(
227 markdown: string,
228 ids: Array<string>,
229 platform: MinimaxPlatform = MINIMAX,
230): Map<string, ModelReasoning> {
231 const out = new Map<string, ModelReasoning>()
232 const families: Array<[string, ModelReasoning]> = []
233 const rows = markdownTableRows(markdown)
234 let adaptive = -1
235 let disabled = -1
236 for (const cells of rows) {
237 if (cells.includes('`{"type": "disabled"}`')) {
238 adaptive = cells.indexOf('`{"type": "adaptive"}`')
239 disabled = cells.indexOf('`{"type": "disabled"}`')
240 continue
241 }
242 if (adaptive < 0 || !platform.thinkingOn.test(cells[adaptive] ?? ''))
243 continue
244 const off = cells[disabled] ?? ''
245 const mandatory = platform.cannotDisable.test(off)
246 if (!mandatory && !platform.thinkingOff.test(off)) continue
247 const reasoning: ModelReasoning = { mode: 'adaptive', mandatory }
248 const model = cells[0] ?? ''
249 const id = model.match(/^`([^`]+)`$/)?.[1]
250 const family = model.match(/^(M\d+)\.x$/)?.[1]
251 if (id && ids.includes(id)) out.set(id, reasoning)
252 else if (family) families.push([`${ID_PREFIX}${family}`, reasoning])
253 }
254 for (const [prefix, reasoning] of families) {
255 for (const id of ids) {
256 const rest = id.startsWith(prefix) ? id.slice(prefix.length) : null
257 if (rest === null || out.has(id)) continue
258 if (rest === '' || /^[.-]/.test(rest)) out.set(id, reasoning)
259 }
260 }
261 const effort = rows.find((cells) => cells[0] === '`output_config.effort`')
262 const description = effort?.[2] ?? ''
263 const efforts = [
264 ...(description.match(platform.efforts)?.[1] ?? '').matchAll(/`([a-z]+)`/g),
265 ].flatMap((match) => (match[1] ? [match[1]] : []))
266 if (efforts.length > 0) {
267 for (const [id, reasoning] of out) {
268 if (names(description, id)) out.set(id, { ...reasoning, efforts })
269 }
270 }
271 return out
273​
274/**
275 * The spec's `max_completion_tokens` description: `For A and B … the
276 * maximum is N; for other models … the maximum is M`. The `other models`
277 * number goes only to ids the description never names. Empty unless every
278 * id it does name got a maximum from its own clause, so a reworded clause
279 * cannot hand a named model the catch-all. Also empty when one clause
280 * holds two maximums or names ids beside `other models` (the clauses ran
281 * together), or when a maximum carries a unit (`512K`) or a decimal.
282 */
283export function parseMinimaxMaxOutput(
284 description: string,
285 ids: Array<string>,
286 platform: MinimaxPlatform = MINIMAX,
287): Map<string, number> {
288 const out = new Map<string, number>()
289 let others: number | null = null
290 for (const clause of description.split(platform.clause)) {
291 const maximums = [...clause.matchAll(new RegExp(platform.maximum, 'g'))]
292 const [found] = maximums
293 if (!found) continue
294 const after = clause.slice(found.index + found[0].length)
295 if (maximums.length > 1 || /^(?:\.\d|\s*[kKmM万千亿])/.test(after)) {
296 return new Map()
297 }
298 const tokens = tokenCount(found[1])
299 if (tokens === null) continue
300 const named = ids.filter((id) => names(clause, id))
301 if (named.length > 0 && platform.otherModels.test(clause)) return new Map()
302 for (const id of named) out.set(id, tokens)
303 if (named.length === 0 && platform.otherModels.test(clause)) others = tokens
304 }
305 const named = ids.filter((id) => names(description, id))
306 if (named.length === 0 || named.some((id) => !out.has(id))) return new Map()
307 if (others !== null) {
308 for (const id of ids) if (!out.has(id)) out.set(id, others)
309 }
310 return out
312​
313function maxCompletionTokensDescription(spec: unknown): string {
314 let found = ''
315 const walk = (node: unknown) => {
316 if (found || typeof node !== 'object' || node === null) return
317 const cap = (node as Record<string, unknown>).max_completion_tokens
318 const description =
319 typeof cap === 'object' && cap !== null
320 ? (cap as Record<string, unknown>).description
321 : undefined
322 if (typeof description === 'string') found = description
323 else for (const value of Object.values(node)) walk(value)
324 }
325 walk(spec)
326 return found
328​
329/**
330 * `~~\$0.60~~ \$0.30 / M tokens` → 0.30: the struck list price is not
331 * billed. The caller takes a struck row only under a `Permanent` badge.
332 */
333function perMillion(cell: string, price: RegExp): number | null {
334 const billed = cell.replace(/~~[^~]*~~/g, '').trim()
335 const amount = billed.match(price)?.[1]
336 return amount ? Number(amount) : null
338​
339/** A price row's first cell: the bold id, then any bound or badge. */
340const MODEL_CELL = /^\*\*([A-Za-z0-9][\w.-]*)\*\*(.*)$/
341​
342export interface MinimaxRates {
343 base: Record<string, number>
344 tiers: Array<TokenRateTier>
346​
347/**
348 * The `## LLM` tables, standard tier only: the `Priority` tab is dropped.
349 * A `> 512k input tokens` row is a tier over the same model's base row.
350 * Rates are per token, in the platform's currency.
351 *
352 * What it cannot attribute it refuses. Nothing is priced when a `<Tab`
353 * other than the standard one survives, or the section holds a heading
354 * of its own. A model gets no price when a row of its has text beside the
355 * id that is not a bound or the permanent badge, a price cell that does
356 * not read, a second base row, or a repeated tier threshold.
357 */
358export function parseMinimaxPricing(
359 markdown: string,
360 platform: MinimaxPlatform = MINIMAX,
361): Map<string, MinimaxRates> {
362 const tabbed = markdownSection(markdown, platform.priceSection)
363 .replace(
364 new RegExp(
365 `<Tab title="(?!${platform.standardTab}")[^"]*">[\\s\\S]*?</Tab>`,
366 'g',
367 ),
368 '',
369 )
370 .split('\n')
371 .map((line) => line.trim())
372 .join('\n')
373 const out = new Map<string, MinimaxRates>()
374 // A tab the strip did not recognise, or a sub-heading, may hold another
375 // tier's table under the same headers.
376 const standard = `<Tab title="${platform.standardTab}">`
377 if (
378 /<Tab(?!s>)/.test(tabbed.replaceAll(standard, '')) ||
379 /^#{1,6} /m.test(tabbed.slice(tabbed.indexOf('\n')))
380 ) {
381 return out
382 }
383 // So may an accordion that is not the legacy models. One with no price
384 // row (a FAQ) is dropped; one with a price row cannot be attributed.
385 const priceRow = (cells: Array<string>) =>
386 cells[0] === platform.modelHeader || MODEL_CELL.test(cells[0] ?? '')
387 const foreign: Array<string> = []
388 const section = tabbed.replace(
389 /<Accordion\b([^>]*)>([\s\S]*?)<\/Accordion>/g,
390 (whole, attributes: string, body: string) => {
391 const title = /\btitle="([^"]*)"/.exec(attributes)?.[1]
392 if (title === platform.legacyAccordion) return whole
393 if (markdownTableRows(body).some(priceRow)) foreign.push(whole)
394 return ''
395 },
396 )
397 if (foreign.length > 0) return out
398 const refused = new Set<string>()
399 const based = new Set<string>()
400 /** A base row's `≤ N` bound; the first tier must start at the same N. */
401 const baseBound = new Map<string, number | null>()
402 let header: Array<string> = []
403 for (const cells of markdownTableRows(section)) {
404 if (cells[0] === platform.modelHeader) {
405 header = cells
406 continue
407 }
408 const model = cells[0]?.match(MODEL_CELL)
409 const id = model?.[1]
410 if (!id) continue
411 // A struck price without a `Permanent` badge may be a promotion that
412 // ends: the model gets no card.
413 const struck = cells.some((cell) => cell.includes('~~'))
414 if (struck && !platform.permanent.test(model[2] ?? '')) {
415 refused.add(id)
416 continue
417 }
418 const rates: Record<string, number> = {}
419 // Every column beside the model is a price this must read: an unknown
420 // header or a cell that does not parse refuses the model, so a lever
421 // is never dropped from a card that still prices the rest.
422 let unread = cells.length !== header.length
423 header.slice(1).forEach((name, index) => {
424 const lever = platform.priceLevers[name]
425 const amount = lever
426 ? perMillion(cells[index + 1] ?? '', platform.price)
427 : null
428 if (lever && amount !== null) rates[lever] = amount / 1e6
429 else unread = true
430 })
431 const bound = model[2]?.match(platform.inputBound)
432 const above = bound?.[1] === '>' ? tokenCount(bound[2]) : null
433 // Beside the id: a bound, the permanent badge, a footnote mark. Any
434 // other text qualifies the price in a way this does not read.
435 const qualifier = (model[2] ?? '')
436 .replace(/<span[^>]*>[^<]*<\/span>/g, (span) =>
437 platform.permanent.test(span) ? '' : span,
438 )
439 .replace(bound?.[0] ?? '', '')
440 .replace(/<br \/>|\\\*/g, '')
441 .trim()
442 const entry = out.get(id) ?? { base: {}, tiers: [] }
443 const repeated =
444 above === null
445 ? based.has(id)
446 : entry.tiers.some((tier) => tier.minPromptTokens === above)
447 if (
448 unread ||
449 rates.input_tokens === undefined ||
450 rates.output_tokens === undefined ||
451 qualifier !== '' ||
452 (bound && bound[1] === '>' && above === null) ||
453 repeated
454 ) {
455 refused.add(id)
456 continue
457 }
458 if (above !== null) entry.tiers.push({ minPromptTokens: above, rates })
459 else {
460 entry.base = rates
461 based.add(id)
462 if (bound) baseBound.set(id, tokenCount(bound[2]))
463 }
464 out.set(id, entry)
465 }
466 for (const [id, entry] of out) {
467 // `≤ 256k` beside `> 512k` leaves 256k–512k unpriced, and a bounded
468 // base with no tier leaves everything above it: neither is a card.
469 const tiers = entry.tiers.map((tier) => tier.minPromptTokens)
470 const first = tiers.length > 0 ? Math.min(...tiers) : undefined
471 if (baseBound.has(id) ? baseBound.get(id) !== first : first !== undefined) {
472 refused.add(id)
473 }
474 }
475 for (const id of refused) out.delete(id)
476 return out
478​
479const FETCH_TIMEOUT_MS = 30_000
480​
481/**
482 * One docs page. Throws when a redirect lands on a host that is not the
483 * platform's own: the two platforms publish the same paths, so a redirect
484 * across them would hand one platform the other's document.
485 */
486export async function fetchMinimaxPage(
487 url: string,
488 platform: MinimaxPlatform,
489): Promise<string> {
490 const response = await fetch(url, {
491 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
492 })
493 if (!response.ok) {
494 throw new Error(
495 `fetch failed: ${url} → ${String(response.status)} ${response.statusText}`,
496 )
497 }
498 const host = new URL(response.url || url).host
499 if (!platform.hosts.includes(host)) {
500 throw new Error(`${platform.label}: ${url} was answered by ${host}`)
501 }
502 return response.text()
504​
505/** Facts for one chat id; `{}` when the docs do not name it. */
506export async function minimaxModelFacts(
507 kv?: KVNamespace,
508 platform: MinimaxPlatform = MINIMAX,
509): Promise<(rawId: string) => Partial<ModelFacts>> {
510 const { label, sdkUrl, chatSpecUrl, pricingUrl } = platform
511 const fetchPage = (url: string) => fetchMinimaxPage(url, platform)
512 const doc = await cachedDocs(kv, sdkUrl, async () => {
513 const [sdk, pricingPage, specText] = await Promise.all([
514 fetchPage(sdkUrl),
515 fetchPage(pricingUrl),
516 fetchPage(chatSpecUrl),
517 ])
518 const windows = parseMinimaxContextWindows(sdk, platform)
519 assertParsed(windows, `${label} context windows`)
520 const ids = [...windows.keys()]
521 const inputs = parseMinimaxInputModalities(sdk, ids, platform)
522 assertParsed(inputs, `${label} input modalities`)
523 const reasoning = parseMinimaxReasoning(sdk, ids, platform)
524 assertParsed(reasoning, `${label} thinking table`)
525 const caps = parseMinimaxMaxOutput(
526 maxCompletionTokensDescription(JSON.parse(specText) as unknown),
527 ids,
528 platform,
529 )
530 assertParsed(caps, `${label} max output`)
531 const prices = parseMinimaxPricing(pricingPage, platform)
532 assertParsed(prices, `${label} pricing page`)
533​
534 const [sdkHash, pricingHash, specHash] = await Promise.all([
535 sha256Text(sdk),
536 sha256Text(pricingPage),
537 sha256Text(specText),
538 ])
539 const extractedAt = new Date().toISOString()
540 const facts: Record<string, Partial<ModelFacts>> = {}
541 for (const id of ids) {
542 const input = inputs.get(id)
543 const fromSdk = {
544 contextWindow: windows.get(id) ?? null,
545 modalities: input ? { input, output: ['text'] } : null,
546 reasoning: reasoning.get(id) ?? null,
547 }
548 // A maximum equal to the model's whole context window is the context
549 // bound, not an output cap: nothing is stored for it.
550 const cap = caps.get(id)
551 const maxOutput =
552 cap === undefined || cap === fromSdk.contextWindow ? null : cap
553 const rates = prices.get(id)
554 const pricing = rates
555 ? compileTokenCard(
556 rates.base,
557 rates.tiers,
558 { url: pricingUrl, hash: pricingHash, extractedAt },
559 { currency: platform.currency },
560 )
561 : null
562 facts[id] = {
563 ...fromSdk,
564 maxOutput,
565 pricing,
566 factSources: {
567 ...tagDocsFacts(fromSdk, sdkUrl, sdkHash),
568 ...tagDocsFacts({ maxOutput }, chatSpecUrl, specHash),
569 ...tagDocsFacts({ pricing }, pricingUrl, pricingHash),
570 },
571 }
572 }
573 return { facts }
574 })
575 return (rawId) => doc.facts[rawId] ?? {}