Open History to see the last commit
1/** Xiaomi MiMo: live native documentation, never another provider's catalog. */
2import { compileTokenCard } from '@modelschemas/rate-card'
3import type { RateCard } from '@modelschemas/rate-card'
4import { bearerConnect } from '../connect.ts'
5import {
6 cachedDocs,
7 docsReport,
8 docsRun,
9 tokenCount,
10 tryDocs,
11 unavailable,
12} from '../model-facts.ts'
13import { fetchText, sha256Text } from '../types.ts'
14import type { ModelInfo, ProviderConfig, FactSource } from '../types.ts'
15import {
16 htmlTables,
17 nativeSchemas,
18 plain,
19 XIAOMI_MODELS,
20 XIAOMI_PRICING,
21 XIAOMI_THINKING,
22 XIAOMI_SCHEMA_URLS,
23 xiaomiSpec,
24} from '../xiaomi-docs.ts'
25
26const IDS = /`(mimo-[a-z0-9.-]+)`/g
27function fail(message: string): never {
28 throw new Error(`xiaomi: ${message}`)
29}
30const ids = (text: string) =>
31 [...text.matchAll(IDS)].map((match) => match[1] ?? '')
32
33export function parseXiaomiModels(text: string): Array<ModelInfo> {
34 const models: Array<ModelInfo> = []
35 const seen = new Set<string>()
36 const catalog = text.split('### Quick Selection Guide')[0] ?? text
37 for (const rows of htmlTables(catalog)) {
38 const header = rows[0]
39 if (!header || !/Model ID/i.test(plain(header[0] ?? ''))) continue
40 for (const row of rows.slice(1)) {
41 if (row.length !== 4) fail('model table has an unexpected column count')
42 const names = ids(row[0] ?? '')
43 if (!names.length) fail('model row has no native model IDs')
44 const support = plain(row[1] ?? '')
45 const limits = plain(row[2] ?? '')
46 const context = /Context Window:\s*([\d,.]+\s*[kKmM]?)/.exec(limits)?.[1]
47 const output = /Maximum Output:\s*([\d,.]+\s*[kKmM]?)/.exec(limits)?.[1]
48 if (!context || !output) fail('model row has unreadable token limits')
49 const contextWindow = tokenCount(context)
50 const maxOutput = tokenCount(output)
51 if (
52 contextWindow === null ||
53 contextWindow <= 0 ||
54 maxOutput === null ||
55 maxOutput <= 0
56 )
57 fail('model row has invalid token limits')
58 const capabilities: Array<string> = []
59 const labels = new Map([
60 ['Deep Thinking', 'reasoning'],
61 ['Streaming Output', 'streaming'],
62 ['Function Call', 'tools'],
63 ['Structured Output', 'structured_outputs'],
64 ])
65 for (const [label, flag] of labels)
66 if (support.includes(label)) capabilities.push(flag)
67 const activity = support.includes('Text Generation')
68 ? 'chat'
69 : support.includes('Speech Recognition') ||
70 support.includes('Speech Synthesis')
71 ? 'audio'
72 : null
73 if (!activity) fail('unknown model generation capability')
74 for (const rawId of names) {
75 if (seen.has(rawId)) fail(`duplicate model ${rawId}`)
76 seen.add(rawId)
77 models.push({
78 rawId,
79 displayName: null,
80 activity,
81 contextWindow,
82 maxOutput,
83 capabilities: capabilities.length ? capabilities : null,
84 modalities: support.includes('Speech Recognition')
85 ? { input: ['audio'], output: ['text'] }
86 : support.includes('Speech Synthesis')
87 ? { input: ['text'], output: ['audio'] }
88 : null,
89 pricing: null,
90 reasoning: null,
91 })
92 }
93 }
94 }
95 if (!models.length) fail('model catalog listed no model IDs')
96 return models
97}
98
99export function parseXiaomiPricing(
100 text: string,
101 source: RateCard['source'],
102): Map<string, RateCard> {
103 const overseas = text
104 .split('### Overseas Pricing of the Model')[1]
105 ?.split('### Pricing for Web Search Plugins')[0]
106 if (!overseas) fail('pricing has no overseas USD section')
107 const cards = new Map<string, RateCard>()
108 for (const rows of htmlTables(overseas)) {
109 const header = rows[0]?.map(plain) ?? []
110 if (header.length === 5 && header[0]?.includes('Inference Type')) {
111 if (
112 !header[1]?.includes('Model Name') ||
113 !header[2]?.includes('Input (Cache Hit)') ||
114 !header[3]?.includes('Input (Cache Miss)') ||
115 !header[4]?.includes('Output')
116 )
117 fail('USD token pricing headers changed')
118 for (const row of rows.slice(1)) {
119 if (row.length !== 5)
120 fail('USD token pricing row has unexpected columns')
121 const names = ids(row[1] ?? '')
122 if (!names.length) fail('USD pricing row has no model ID')
123 const rates = row.slice(2).map((cell) => {
124 const match = /^\$([\d.]+)$/.exec(plain(cell))
125 if (!match) fail('USD token price is unreadable')
126 const rate = Number(match[1])
127 if (!Number.isFinite(rate) || rate < 0)
128 fail('USD token price is invalid')
129 return rate / 1_000_000
130 })
131 const batch = plain(row[0] ?? '')
132 if (!['**Real-time API**', '**Batch API**'].includes(batch))
133 fail('unknown inference pricing type')
134 if (batch !== '**Real-time API**') continue
135 const [cache, input, output] = rates
136 if (cache === undefined || input === undefined || output === undefined)
137 fail('missing USD token rate')
138 for (const rawId of names) {
139 if (cards.has(rawId)) fail(`duplicate real-time price ${rawId}`)
140 const card = compileTokenCard(
141 {
142 input_tokens: input,
143 output_tokens: output,
144 cache_read_tokens: cache,
145 },
146 [],
147 source,
148 )
149 if (!card) fail(`USD price could not compile for ${rawId}`)
150 cards.set(rawId, card)
151 }
152 }
153 } else if (
154 header.length === 2 &&
155 header[1]?.includes('Input audio duration')
156 ) {
157 if (!header[0]?.includes('Model Name'))
158 fail('USD audio pricing headers changed')
159 for (const row of rows.slice(1)) {
160 const names = ids(row[0] ?? '')
161 const price = /^\$([\d.]+)\s*\/h$/.exec(plain(row[1] ?? ''))
162 if (!names.length || !price) fail('USD audio price is unreadable')
163 const rate = Number(price[1]) / 3600
164 if (!Number.isFinite(rate) || rate < 0)
165 fail('USD audio price is invalid')
166 const card = compileTokenCard({ audio_seconds: rate }, [], source)
167 if (!card) fail('USD audio price could not compile')
168 for (const rawId of names) cards.set(rawId, card)
169 }
170 } else fail('unrecognized overseas pricing table')
171 }
172 if (!cards.size) fail('USD pricing parsed no rates')
173 return cards
174}
175
176export function thinkingModels(text: string): Set<string> {
177 const section = text
178 .split('## Supported Models')[1]
179 ?.split('## Request Parameters')[0]
180 if (
181 !section ||
182 !/`thinking\.type`/.test(text) ||
183 !/`enabled`/.test(text) ||
184 !/`disabled`/.test(text)
185 )
186 fail('thinking controls are unreadable')
187 const supported = new Set(ids(section))
188 if (!supported.size) fail('thinking docs name no supported models')
189 return supported
190}
191
192/** Exact model-scoped modality statement in Xiaomi's own chat schema tree. */
193export function multimodalModels(text: string): Set<string> {
194 const supported = new Set<string>()
195 const visit = (value: unknown): void => {
196 if (Array.isArray(value)) {
197 value.forEach(visit)
198 return
199 }
200 if (typeof value !== 'object' || value === null) return
201 const obj = value as Record<string, unknown>
202 if (typeof obj.description === 'string') {
203 const named =
204 /Currently, the (.+?) models support image, audio or video input\./.exec(
205 obj.description,
206 )?.[1]
207 if (named)
208 for (const match of named.matchAll(/mimo-[a-z0-9.-]+/g))
209 supported.add(match[0])
210 }
211 Object.values(obj).forEach(visit)
212 }
213 nativeSchemas(text).forEach(visit)
214 if (!supported.size) fail('chat docs have no model-scoped modality statement')
215 return supported
216}
217
218async function load(
219 url: string,
220 kv?: KVNamespace,
221 cached: typeof cachedDocs = cachedDocs,
222) {
223 return cached(kv, url, async () => {
224 const text = await fetchText(url)
225 return {
226 text,
227 hash: await sha256Text(text),
228 extractedAt: new Date().toISOString(),
229 }
230 })
231}
232
233export const provider: ProviderConfig = {
234 id: 'xiaomi',
235 displayName: 'Xiaomi',
236 specSourceUrl: XIAOMI_SCHEMA_URLS[0],
237 modelsEndpoint: XIAOMI_MODELS,
238 defaultDerivation: 'generated',
239 connect: bearerConnect('https://api.xiaomimimo.com'),
240 async listModels(_env, kv) {
241 const chatUrl = XIAOMI_SCHEMA_URLS[0]
242 if (!chatUrl) fail('missing chat schema source URL')
243 // The catalog is the listing. A docs page that 404s keeps the facts it
244 // supplies and the poll continues (`tryDocs`).
245 const docs = docsRun()
246 const [catalog, pricing, thinking, chat] = await Promise.all([
247 load(XIAOMI_MODELS, kv),
248 tryDocs(docs, XIAOMI_PRICING, async (cached) => {
249 const doc = await load(XIAOMI_PRICING, kv, cached)
250 return {
251 doc,
252 cards: parseXiaomiPricing(doc.text, {
253 url: XIAOMI_PRICING,
254 hash: doc.hash,
255 extractedAt: doc.extractedAt,
256 }),
257 free: new Set(
258 ids(
259 doc.text
260 .split('### Overseas Pricing of the Model')[1]
261 ?.split('### Pricing for Web Search Plugins')[0]
262 ?.split('Free for a limited time:')[1] ?? '',
263 ),
264 ),
265 }
266 }),
267 tryDocs(docs, XIAOMI_THINKING, async (cached) => {
268 const doc = await load(XIAOMI_THINKING, kv, cached)
269 return { doc, supported: thinkingModels(doc.text) }
270 }),
271 tryDocs(docs, chatUrl, async (cached) => {
272 const doc = await load(chatUrl, kv, cached)
273 return { doc, multimodal: multimodalModels(doc.text) }
274 }),
275 ])
276 const source: FactSource = {
277 derivation: 'docs-derived',
278 sourceUrl: XIAOMI_MODELS,
279 sourceHash: catalog.hash,
280 }
281 return {
282 models: parseXiaomiModels(catalog.text).map((model): ModelInfo => {
283 const fromChat = chat?.multimodal.has(model.rawId) ?? false
284 const modalities = fromChat
285 ? { input: ['text', 'image', 'audio', 'video'], output: ['text'] }
286 : model.modalities
287 const card = pricing?.cards.get(model.rawId)
288 const thinks = thinking?.supported.has(model.rawId) ?? false
289 const absent = {
290 ...(pricing
291 ? pricing.free.has(model.rawId)
292 ? { pricing: 'cleared' as const }
293 : {}
294 : unavailable('pricing').absent),
295 ...(thinking ? {} : unavailable('reasoning').absent),
296 ...(chat ? {} : unavailable('modalities').absent),
297 }
298 return {
299 ...model,
300 pricing: card ?? null,
301 modalities,
302 ...(Object.keys(absent).length > 0 ? { absent } : {}),
303 reasoning: thinks
304 ? { mode: 'toggle' as const, mandatory: false }
305 : null,
306 factSources: {
307 contextWindow: source,
308 maxOutput: source,
309 ...(card && pricing
310 ? {
311 pricing: {
312 derivation: 'docs-derived' as const,
313 sourceUrl: XIAOMI_PRICING,
314 sourceHash: pricing.doc.hash,
315 path: 'Overseas Pricing of the Model',
316 },
317 }
318 : {}),
319 // Chat docs name the multimodal rows. Speech modalities are on
320 // the catalog. A failed chat page states neither.
321 ...(chat && modalities
322 ? {
323 modalities: fromChat
324 ? {
325 derivation: 'docs-derived' as const,
326 sourceUrl: chatUrl,
327 sourceHash: chat.doc.hash,
328 }
329 : source,
330 }
331 : {}),
332 ...(Array.isArray(model.capabilities)
333 ? {
334 capabilities: Object.fromEntries(
335 (model.capabilities as Array<string>).map((flag) => [
336 flag,
337 source,
338 ]),
339 ),
340 }
341 : {}),
342 ...(thinks && thinking
343 ? {
344 reasoning: {
345 derivation: 'docs-derived' as const,
346 sourceUrl: XIAOMI_THINKING,
347 sourceHash: thinking.doc.hash,
348 },
349 }
350 : {}),
351 },
352 }
353 }),
354 docsFailures: docsReport(docs),
355 }
356 },
357 async fetchSpec(_env) {
358 const docs = await Promise.all(
359 XIAOMI_SCHEMA_URLS.map(async (url) => ({ url, ...(await load(url)) })),
360 )
361 return {
362 specs: [xiaomiSpec(docs)],
363 sources: docs.map(({ url, hash }) => ({ url, hash })),
364 outputStrategy: 'post-200',
365 }
366 },
367 classify: (path) =>
368 [
369 '/v1/chat/completions',
370 '/v1/responses',
371 '/anthropic/v1/messages',
372 ].includes(path)
373 ? 'chat'
374 : null,
375 generationEndpointId: ({ activity }) =>
376 activity === 'chat' ? 'v1/chat/completions' : null,
377}