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

xiaomi.ts

379 lines12.9 KB

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}`)
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
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
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
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
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 })
232​
233export const provider: ProviderConfig = {
234 id: 'xiaomi',
235 // Hosts' `maker/model` ids (Novita `xiaomimimo/mimo-v2.6-pro`).
236 modelNamespaces: ['xiaomimimo'],
237 displayName: 'Xiaomi',
238 specSourceUrl: XIAOMI_SCHEMA_URLS[0],
239 modelsEndpoint: XIAOMI_MODELS,
240 defaultDerivation: 'generated',
241 connect: bearerConnect('https://api.xiaomimimo.com'),
242 async listModels(_env, kv) {
243 const chatUrl = XIAOMI_SCHEMA_URLS[0]
244 if (!chatUrl) fail('missing chat schema source URL')
245 // The catalog is the listing. A docs page that 404s keeps the facts it
246 // supplies and the poll continues (`tryDocs`).
247 const docs = docsRun()
248 const [catalog, pricing, thinking, chat] = await Promise.all([
249 load(XIAOMI_MODELS, kv),
250 tryDocs(docs, XIAOMI_PRICING, async (cached) => {
251 const doc = await load(XIAOMI_PRICING, kv, cached)
252 return {
253 doc,
254 cards: parseXiaomiPricing(doc.text, {
255 url: XIAOMI_PRICING,
256 hash: doc.hash,
257 extractedAt: doc.extractedAt,
258 }),
259 free: new Set(
260 ids(
261 doc.text
262 .split('### Overseas Pricing of the Model')[1]
263 ?.split('### Pricing for Web Search Plugins')[0]
264 ?.split('Free for a limited time:')[1] ?? '',
265 ),
266 ),
267 }
268 }),
269 tryDocs(docs, XIAOMI_THINKING, async (cached) => {
270 const doc = await load(XIAOMI_THINKING, kv, cached)
271 return { doc, supported: thinkingModels(doc.text) }
272 }),
273 tryDocs(docs, chatUrl, async (cached) => {
274 const doc = await load(chatUrl, kv, cached)
275 return { doc, multimodal: multimodalModels(doc.text) }
276 }),
277 ])
278 const source: FactSource = {
279 derivation: 'docs-derived',
280 sourceUrl: XIAOMI_MODELS,
281 sourceHash: catalog.hash,
282 }
283 return {
284 models: parseXiaomiModels(catalog.text).map((model): ModelInfo => {
285 const fromChat = chat?.multimodal.has(model.rawId) ?? false
286 const modalities = fromChat
287 ? { input: ['text', 'image', 'audio', 'video'], output: ['text'] }
288 : model.modalities
289 const card = pricing?.cards.get(model.rawId)
290 const thinks = thinking?.supported.has(model.rawId) ?? false
291 const absent = {
292 ...(pricing
293 ? pricing.free.has(model.rawId)
294 ? { pricing: 'cleared' as const }
295 : {}
296 : unavailable('pricing').absent),
297 ...(thinking ? {} : unavailable('reasoning').absent),
298 ...(chat ? {} : unavailable('modalities').absent),
299 }
300 return {
301 ...model,
302 pricing: card ?? null,
303 modalities,
304 ...(Object.keys(absent).length > 0 ? { absent } : {}),
305 reasoning: thinks
306 ? { mode: 'toggle' as const, mandatory: false }
307 : null,
308 factSources: {
309 contextWindow: source,
310 maxOutput: source,
311 ...(card && pricing
312 ? {
313 pricing: {
314 derivation: 'docs-derived' as const,
315 sourceUrl: XIAOMI_PRICING,
316 sourceHash: pricing.doc.hash,
317 path: 'Overseas Pricing of the Model',
318 },
319 }
320 : {}),
321 // Chat docs name the multimodal rows. Speech modalities are on
322 // the catalog. A failed chat page states neither.
323 ...(chat && modalities
324 ? {
325 modalities: fromChat
326 ? {
327 derivation: 'docs-derived' as const,
328 sourceUrl: chatUrl,
329 sourceHash: chat.doc.hash,
330 }
331 : source,
332 }
333 : {}),
334 ...(Array.isArray(model.capabilities)
335 ? {
336 capabilities: Object.fromEntries(
337 (model.capabilities as Array<string>).map((flag) => [
338 flag,
339 source,
340 ]),
341 ),
342 }
343 : {}),
344 ...(thinks && thinking
345 ? {
346 reasoning: {
347 derivation: 'docs-derived' as const,
348 sourceUrl: XIAOMI_THINKING,
349 sourceHash: thinking.doc.hash,
350 },
351 }
352 : {}),
353 },
354 }
355 }),
356 docsFailures: docsReport(docs),
357 }
358 },
359 async fetchSpec(_env) {
360 const docs = await Promise.all(
361 XIAOMI_SCHEMA_URLS.map(async (url) => ({ url, ...(await load(url)) })),
362 )
363 return {
364 specs: [xiaomiSpec(docs)],
365 sources: docs.map(({ url, hash }) => ({ url, hash })),
366 outputStrategy: 'post-200',
367 }
368 },
369 classify: (path) =>
370 [
371 '/v1/chat/completions',
372 '/v1/responses',
373 '/anthropic/v1/messages',
374 ].includes(path)
375 ? 'chat'
376 : null,
377 generationEndpointId: ({ activity }) =>
378 activity === 'chat' ? 'v1/chat/completions' : null,