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

kimi-code-docs.ts

176 lines5.7 KB

1/** Kimi Code's own transposed model table, not an API compatibility catalog. */
2import type { FactSource, ModelInfo, ModelReasoning } from './types.ts'
3​
4export const KIMI_CODE_MODELS_URL =
5 'https://www.kimi.com/code/docs/en/kimi-code/models.html'
6​
7function fail(message: string): never {
8 throw new Error(`kimi-code: ${message}`)
9}
10function text(html: string): string {
11 return html
12 .replace(/<[^>]*>/g, ' ')
13 .replace(/&nbsp;/g, ' ')
14 .replace(/&amp;/g, '&')
15 .replace(/&#39;|&apos;/g, "'")
16 .replace(/&quot;/g, '"')
17 .replace(/\s+/g, ' ')
18 .trim()
20function codes(html: string): Array<string> {
21 return [...html.matchAll(/<code\b[^>]*>([\s\S]*?)<\/code>/g)].map((match) =>
22 text(match[1] ?? ''),
23 )
25​
26interface ModelColumn {
27 rawId: string
28 cells: Map<string, string>
30​
31function modelColumns(html: string): Array<ModelColumn> {
32 const matches: Array<Array<Array<string>>> = []
33 for (const table of html.matchAll(/<table\b[^>]*>([\s\S]*?)<\/table>/g)) {
34 const rows = [
35 ...(table[1] ?? '').matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/g),
36 ].map((row) =>
37 [...(row[1] ?? '').matchAll(/<t[dh]\b([^>]*)>([\s\S]*?)<\/t[dh]>/g)].map(
38 (cell) => {
39 if (/\b(?:rowspan|colspan)=/.test(cell[1] ?? ''))
40 fail('unexpected spans in model table')
41 return cell[2] ?? ''
42 },
43 ),
44 )
45 if (text(rows[0]?.[0] ?? '') === 'Model ID') matches.push(rows)
46 }
47 if (matches.length !== 1)
48 fail('model source must contain exactly one Model ID table')
49 const rows = matches[0] ?? fail('missing model table')
50 const header = rows[0] ?? fail('missing model header')
51 if (header.length < 2) fail('model header names no IDs')
52 const columns = header.slice(1).map((cell) => {
53 const nativeIds = codes(cell)
54 const rawId = nativeIds[0]
55 if (
56 nativeIds.length !== 1 ||
57 !rawId ||
58 !/^[a-z0-9][a-z0-9.-]*$/.test(rawId)
59 )
60 fail('invalid native model ID')
61 return { rawId, cells: new Map<string, string>() }
62 })
63 if (new Set(columns.map((column) => column.rawId)).size !== columns.length)
64 fail('duplicate native model ID')
65 for (const row of rows.slice(1)) {
66 if (row.length !== header.length)
67 fail('model source has unequal table widths')
68 const label = text(row[0] ?? '')
69 if (!label) fail('unlabeled model fact row')
70 columns.forEach((column, index) => {
71 if (column.cells.has(label)) fail(`duplicate model fact ${label}`)
72 column.cells.set(label, row[index + 1] ?? '')
73 })
74 }
75 return columns
77​
78function contextWindow(raw: string | undefined): number | null {
79 if (raw === undefined || /^[-—]$/.test(text(raw))) return null
80 const values = codes(raw)
81 if (values.length !== 1 || !/^\d+$/.test(values[0] ?? ''))
82 fail('unreadable native context window')
83 const amount = Number(values[0])
84 if (!Number.isSafeInteger(amount) || amount <= 0)
85 fail('invalid native context window')
86 return amount
88​
89function reasoning(raw: string | undefined): ModelReasoning | null {
90 if (raw === undefined || /^[-—]$/.test(text(raw))) return null
91 const values = codes(raw.split(/\(default\b/)[0] ?? raw)
92 const first = values[0]
93 if (first === 'Thinking:ON') return null // An enabled flag does not name a control or state mandatory.
94 if (!first?.startsWith('reasoning_effort:'))
95 fail('unrecognized native reasoning control')
96 const efforts = [first.slice('reasoning_effort:'.length), ...values.slice(1)]
97 if (
98 !efforts.length ||
99 efforts.some((effort) => !/^[a-z][a-z0-9_-]*$/.test(effort)) ||
100 new Set(efforts).size !== efforts.length
101 )
102 fail('invalid native effort list')
103 return { mode: 'effort', mandatory: null, efforts }
105​
106function media(raw: string | undefined): Array<string> | null {
107 if (raw === undefined || /^[-—]$/.test(text(raw))) return null
108 const input = text(raw)
109 .replace(/\bonly\b/g, '')
110 .split(',')
111 .map((value) => value.trim().toLowerCase())
112 if (
113 !input.length ||
114 input.some((value) => !['text', 'image', 'video', 'audio'].includes(value))
115 )
116 fail('unreadable native input modalities')
117 return input
119​
120export function parseKimiCodeModels(
121 html: string,
122 source: FactSource,
123): Array<ModelInfo> {
124 return modelColumns(html).map(({ rawId, cells }) => {
125 const window = contextWindow(cells.get('Context window'))
126 const control = reasoning(cells.get('Reasoning'))
127 const input = media(cells.get('Multimodal input'))
128 const thinks =
129 control !== null ||
130 codes(cells.get('Reasoning') ?? '').includes('Thinking:ON')
131 return {
132 rawId,
133 displayName: null,
134 activity: 'chat',
135 contextWindow: window,
136 maxOutput: null,
137 pricing: null,
138 // Only the published media inputs are known; output is not stated by this table.
139 modalities: input ? { input, output: null } : null,
140 capabilities: thinks ? ['reasoning'] : null,
141 reasoning: control,
142 requestMap: null,
143 providerMetadata: Object.fromEntries(
144 [...cells].map(([label, raw]) => [label, text(raw)]),
145 ),
146 factSources: {
147 ...(window !== null
148 ? {
149 contextWindow: {
150 ...source,
151 path: `Model ID=${rawId}; Context window`,
152 },
153 }
154 : {}),
155 ...(input
156 ? {
157 modalities: {
158 ...source,
159 path: `Model ID=${rawId}; Multimodal input`,
160 },
161 }
162 : {}),
163 ...(control
164 ? { reasoning: { ...source, path: `Model ID=${rawId}; Reasoning` } }
165 : {}),
166 ...(thinks
167 ? {
168 capabilities: {
169 reasoning: { ...source, path: `Model ID=${rawId}; Reasoning` },
170 },
171 }
172 : {}),
173 },
174 }
175 })