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

xiaomi.ts

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