Open History to see the last commit
1/** Ant Ling's direct API documentation. USD reseller tables are never ingested. */
2import { compileTokenCard } from '@modelschemas/rate-card'
3import type { RateCard } from '@modelschemas/rate-card'
4import type { ModelInfo } from './types.ts'
5
6export const ANT_ROOT = 'https://developer.ant-ling.com/en/docs/'
7export const ANT_OPENAI = `${ANT_ROOT}api-reference/chat/openai/`
8export const ANT_OVERVIEW = `${ANT_ROOT}api-reference/`
9export const ANT_PRICE = `${ANT_ROOT}models/price/`
10export const ANT_LING = `${ANT_ROOT}models/ling/`
11export const ANT_EFFORT = `${ANT_ROOT}tutorials/effort/`
12function fail(message: string): never {
13 throw new Error(`ant-ling: ${message}`)
14}
15export function text(html: string): string {
16 return html
17 .replace(/<[^>]*>/g, ' ')
18 .replace(/&/g, '&')
19 .replace(/"/g, '"')
20 .replace(/'|'/g, "'")
21 .replace(/</g, '<')
22 .replace(/>/g, '>')
23 .replace(/\s+/g, ' ')
24 .trim()
25}
26export function article(html: string): string {
27 const body = html.match(/<article\b[^>]*>([\s\S]*?)<\/article>/)?.[1]
28 if (!body) fail('missing native article')
29 return body
30}
31export function rows(html: string): Array<Array<string>> {
32 return [...html.matchAll(/<tr\b[\s\S]*?<\/tr>/g)].map((row) =>
33 [...row[0].matchAll(/<t[dh]\b[^>]*>([\s\S]*?)<\/t[dh]>/g)].map(
34 (cell) => cell[1] ?? '',
35 ),
36 )
37}
38function section(html: string, id: string): string {
39 const s = html.match(
40 new RegExp(
41 `<h[234]\\b[^>]*id="${id}"[^>]*>[\\s\\S]*?<\\/h[234]>([\\s\\S]*?)(?=<h2\\b|$)`,
42 ),
43 )?.[1]
44 if (s === undefined) fail(`missing ${id} section`)
45 return s
46}
47export function blocks(html: string): Map<string, string> {
48 const head = [...html.matchAll(/<h[34]\b[^>]*>[\s\S]*?<\/h[34]>/g)]
49 return new Map(
50 head.map((m, i) => [
51 text(m[0]),
52 html.slice(m.index + m[0].length, head[i + 1]?.index ?? html.length),
53 ]),
54 )
55}
56function options(block: string): Array<string> {
57 const after = block.split(/<strong>Options<\/strong>:/)[1]
58 if (after === undefined) return []
59 return [
60 ...(after.split('</ul>')[0]?.matchAll(/<code\b[^>]*>([^<]+)<\/code>/g) ??
61 []),
62 ].map((m) => text(m[1] ?? ''))
63}
64export function nativeFields(html: string): Map<string, string> {
65 return blocks(section(article(html), 'request-body'))
66}
67export function nativeModelIds(html: string): Array<string> {
68 const model = nativeFields(html).get('model')
69 if (!model) fail('missing model parameter')
70 const ids = options(model)
71 if (!ids.length || new Set(ids).size !== ids.length)
72 fail('unreadable native model options')
73 return ids
74}
75export interface NativePrice {
76 rates: Record<string, number>
77 free: boolean
78}
79export function nativePrices(html: string): Map<string, NativePrice> {
80 const body = section(article(html), 'model-pricing')
81 if (!text(body).includes('All prices below are in CNY'))
82 fail('direct pricing currency not CNY')
83 const table = body.match(/<table\b[\s\S]*?<\/table>/)?.[0]
84 if (!table) fail('missing direct price table')
85 const all = rows(table)
86 if (
87 all[0]?.map(text).join('|') !==
88 'Model|Use Case|Input (per 1M tokens)|Output (per 1M tokens)|Cache Read (per 1M tokens)'
89 )
90 fail('direct pricing headers changed')
91 const out = new Map<string, NativePrice>()
92 for (const row of all.slice(1)) {
93 if (row.length !== 5) fail('direct price row missing cells')
94 const id = text(row[0] ?? '')
95 if (!id || out.has(id)) fail('missing or duplicate direct model ID')
96 const amounts = row.slice(2).map((cell) => {
97 const current = text(cell.replace(/<del\b[\s\S]*?<\/del>/g, ''))
98 const price = /^¥(\d+(?:\.\d+)?)$/.exec(current)
99 if (!price) fail('unreadable current CNY price')
100 return Number(price[1]) / 1e6
101 })
102 const input = amounts[0],
103 output = amounts[1],
104 cache = amounts[2]
105 if (input === undefined || output === undefined || cache === undefined)
106 fail('missing direct price')
107 out.set(id, {
108 rates: {
109 input_tokens: input,
110 output_tokens: output,
111 cache_read_tokens: cache,
112 },
113 free: amounts.every((a) => a === 0),
114 })
115 }
116 if (!out.size) fail('direct price table empty')
117 return out
118}
119export function priceCards(
120 prices: Map<string, NativePrice>,
121 source: RateCard['source'],
122): Map<string, RateCard> {
123 const out = new Map<string, RateCard>()
124 for (const [id, quote] of prices) {
125 // A constant zero is justified only when every current native quote is zero.
126 const card = quote.free
127 ? {
128 inputs: {},
129 tables: { rate: { base: quote.rates } },
130 price: {
131 currency: ['CNY', quote.rates.input_tokens],
132 } as RateCard['price'],
133 examples: [],
134 source,
135 }
136 : compileTokenCard(quote.rates, [], source, { currency: 'CNY' })
137 if (!card) fail('uncompilable direct price')
138 out.set(id, card)
139 }
140 return out
141}
142export function nativeContexts(
143 overview: string,
144 ling: string,
145): Map<string, number> {
146 const out = new Map<string, number>()
147 const body = section(article(overview), 'model-quick-overview')
148 const table = body.match(/<table\b[\s\S]*?<\/table>/)?.[0]
149 if (!table) fail('missing hosted context overview')
150 const all = rows(table)
151 if (all[0]?.map(text).join('|') !== 'Model Name|Context Window|Description')
152 fail('context overview headers changed')
153 const tokens = (value: string) => {
154 const m = /^(\d+(?:\.\d+)?)(K|M)$/.exec(value)
155 if (!m) fail('unreadable context')
156 const limit = Number(m[1]) * (m[2] === 'K' ? 1e3 : 1e6)
157 if (!Number.isSafeInteger(limit) || limit <= 0)
158 fail('invalid context limit')
159 return limit
160 }
161 for (const row of all.slice(1)) {
162 if (row.length !== 3) fail('context row missing cells')
163 out.set(text(row[0] ?? ''), tokens(text(row[1] ?? '')))
164 }
165 const selection = section(article(ling), 'model-selection-guide').match(
166 /<table\b[\s\S]*?<\/table>/,
167 )?.[0]
168 if (!selection) fail('missing Ling model selection')
169 for (const row of rows(selection).slice(1)) {
170 const id = text(row[0] ?? '')
171 const context = text(row[2] ?? '')
172 if (context !== '—' && !out.has(id)) out.set(id, tokens(context))
173 }
174 return out
175}
176export function overviewContextIds(html: string): Set<string> {
177 return new Set(
178 rows(section(article(html), 'model-quick-overview'))
179 .slice(1)
180 .map((row) => text(row[0] ?? '')),
181 )
182}
183type Schema = Record<string, unknown>
184export function nativeRequest(html: string): Schema {
185 const fields = nativeFields(html)
186 const overview = fields.get('Overview')
187 const table = overview?.match(/<table\b[\s\S]*?<\/table>/)?.[0]
188 if (!table) fail('missing request overview')
189 const all = rows(table).map((row) => row.map(text))
190 if (all[0]?.join('|') !== 'Parameter|Type|Required|Default|Description')
191 fail('request parameter table headers changed')
192 const schema: Schema = { type: 'object', properties: {}, required: [] }
193 const nodes = new Map<string, Schema>([['', schema]])
194 const type = (name: string): Schema => {
195 if (['string', 'boolean', 'object'].includes(name)) return { type: name }
196 if (name === 'double') return { type: 'number' }
197 if (name === 'object[]') return { type: 'array', items: { type: 'object' } }
198 if (name === 'list')
199 return { type: 'array', items: { 'x-source-type': null } }
200 fail(`unknown native field type ${name}`)
201 }
202 for (const row of all.slice(1)) {
203 if (row.length !== 5 || !['Yes', 'No'].includes(row[2] ?? ''))
204 fail('request parameter row missing cells')
205 const name = row[0] ?? ''
206 const node = type(row[1] ?? '')
207 node.description = row[4]
208 const range = row[4]?.match(
209 /([[(])\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*([\])])/,
210 )
211 if (range) {
212 node[range[1] === '(' ? 'exclusiveMinimum' : 'minimum'] = Number(range[2])
213 node[range[4] === ')' ? 'exclusiveMaximum' : 'maximum'] = Number(range[3])
214 }
215 const detail = fields.get(name)
216 if (!detail) fail(`missing native detail for ${name}`)
217 const values = options(detail)
218 const def = row[3]
219 if (def !== undefined && def !== '—') {
220 if (!def) fail('missing parameter default cell')
221 if (def === 'true' || def === 'false') node.default = def === 'true'
222 else if (Number.isFinite(Number(def))) node.default = Number(def)
223 else if (node.type === 'string' && values.includes(def))
224 node.default = def
225 else fail('unknown parameter default')
226 }
227 if (values.length) {
228 // Native model options lag the direct pricing catalog. Preserve the list
229 // as evidence without inventing a closed allowlist for newer native IDs.
230 node[name === 'model' ? 'x-source-options' : 'enum'] = values
231 }
232 ;(schema.properties as Record<string, Schema>)[name] = node
233 nodes.set(name, node)
234 if (row[2] === 'Yes') (schema.required as Array<string>).push(name)
235 }
236 for (const [name, detail] of fields) {
237 if (!name.includes('.')) continue
238 const pieces = name.split('.')
239 const leaf = pieces.pop()
240 const parentKey = pieces.join('.')
241 let parent = nodes.get(parentKey)
242 if (!parent || !leaf) fail(`unresolved native nested field ${name}`)
243 if (parent.type === 'array') parent = parent.items as Schema
244 if (parent.type !== 'object') fail('nested field has non-object parent')
245 const declared = detail.match(
246 /<strong>Type<\/strong>: ([\s\S]*?)<\/li>/,
247 )?.[1]
248 if (!declared) fail('missing native nested type')
249 const node = type(text(declared))
250 // The same native page states that its VL model accepts image/video blocks,
251 // contradicting the formal string-only content declaration. Preserve both
252 // statements as source evidence; no block shape is published in this table.
253 if (
254 name === 'messages.content' &&
255 /the request accepts text, images, and videos/.test(
256 text(fields.get('model') ?? ''),
257 )
258 ) {
259 delete node.type
260 node['x-source-type'] = null
261 node['x-source-declared-type'] = text(declared)
262 node['x-source-conflicting-statement'] = text(fields.get('model') ?? '')
263 }
264 const values = options(detail)
265 if (values.length) node.enum = values
266 const def = detail.match(/default <code\b[^>]*>([^<]+)<\/code>/)?.[1]
267 if (def !== undefined)
268 node.default = def === 'true' ? true : def === 'false' ? false : def
269 ;((parent.properties ??= {}) as Record<string, Schema>)[leaf] = node
270 if (/<strong>Required<\/strong>/.test(detail))
271 ((parent.required ??= []) as Array<string>).push(leaf)
272 nodes.set(name, node)
273 }
274 return schema
275}
276function overviewRow(
277 fields: Map<string, string>,
278 field: string,
279): Array<string> | undefined {
280 return rows(fields.get('Overview') ?? '')
281 .map((row) => row.map(text))
282 .find((row) => row[0] === field)
283}
284/**
285 * What a field's description scopes it to: one named id ("Only takes effect
286 * for Ring-2.6-1T", or its Overview row's "(Ring-2.6-1T only)"), or every
287 * model option in each named version series when that is the description's
288 * last sentence ("Supported by 3.0 series models and 3.1 series models.").
289 * An Overview id that disagrees with the description throws.
290 */
291function scope(html: string, field: string) {
292 const fields = nativeFields(html)
293 const block = fields.get(field)
294 if (!block) fail(`missing ${field} applicability`)
295 const t = text(block)
296 const stated = t
297 .match(/Only (?:takes effect|effective) for ([\w.-]+)/i)?.[1]
298 ?.replace(/\.$/, '')
299 const series = t.match(
300 /(?:^|\.\s)Supported by (\d+(?:\.\d+)* series models(?:(?:,| and|, and) \d+(?:\.\d+)* series models)*)\.$/,
301 )?.[1]
302 const listed = overviewRow(fields, field)?.[4]?.match(
303 /\(([\w.-]+) only\)$/,
304 )?.[1]
305 if (
306 listed &&
307 (stated
308 ? stated !== listed
309 : /series models/i.test(t) ||
310 !t.split(/\s+/).some((word) => word.replace(/[.,;:]$/, '') === listed))
311 )
312 fail(`conflicting ${field} applicability`)
313 const id = stated ?? listed
314 if (id) return { named: [id], ids: [id] }
315 if (!series) fail(`unreadable ${field} applicability`)
316 const offered = nativeModelIds(html)
317 const named = [...series.matchAll(/\d+(?:\.\d+)* series models/g)].map(
318 (m) => m[0],
319 )
320 const ids = named.flatMap((name) => {
321 const version = name.split(' ')[0] ?? ''
322 const members = offered.filter((rawId) =>
323 rawId.split('-').includes(version),
324 )
325 if (!members.length) fail(`no native model in the ${version} series`)
326 return members
327 })
328 return { named, ids }
329}
330export function applicability(html: string, field: string): Array<string> {
331 return scope(html, field).ids
332}
333export function controls(html: string) {
334 const fields = nativeFields(html)
335 // The page has published the effort as `reasoning.effort` and, since
336 // 2026-10-16, as a top-level `reasoning_effort` string. Since 2026-10-19
337 // it publishes neither: Ring-2.6-1T, the one model it scoped, left the
338 // model options for deprecation. No effort field means no effort model.
339 const nested = fields.get('reasoning.effort')
340 const flat = fields.get('reasoning_effort')
341 if (nested && flat) fail('two native effort fields')
342 const effort = nested ?? flat
343 const toggle = fields.get('thinking.type')
344 if (!toggle) fail('missing native reasoning controls')
345 const effortField = nested ? 'reasoning' : 'reasoning_effort'
346 const effortIds = effort ? applicability(html, effortField) : []
347 const thinking = scope(html, 'thinking')
348 if (!thinking.named.every((name) => text(toggle).includes(name)))
349 fail('thinking.type names other models than thinking')
350 if (thinking.ids.some((id) => effortIds.includes(id)))
351 fail('a model has both native reasoning controls')
352 const effortDefault =
353 effort?.match(/default <code\b[^>]*>([^<]+)<\/code>/)?.[1] ?? null
354 if (flat) {
355 const listed = overviewRow(fields, effortField)?.[3]
356 if (!effortDefault || !listed || listed === '—')
357 fail('reasoning_effort default unstated')
358 if (listed !== effortDefault) fail('reasoning_effort defaults disagree')
359 }
360 return {
361 effortField,
362 effortIds,
363 toggleIds: thinking.ids,
364 efforts: effort ? options(effort) : [],
365 effortDefault,
366 toggles: options(toggle),
367 }
368}
369export function antModelRows(
370 api: string,
371 pricing: string,
372 contexts: Map<string, number>,
373): Array<ModelInfo> {
374 const apiIds = new Set(nativeModelIds(api))
375 const ids = [...new Set([...apiIds, ...nativePrices(pricing).keys()])]
376 return ids.map((rawId) => ({
377 rawId,
378 displayName: null,
379 activity: apiIds.has(rawId) ? 'chat' : null,
380 contextWindow: contexts.get(rawId) ?? null,
381 maxOutput: null,
382 modalities: null,
383 pricing: null,
384 reasoning: null,
385 requestMap: null,
386 }))
387}
388export function antSpec(api: string) {
389 const all = rows(section(article(api), 'request-address')).map((row) =>
390 row.map(text),
391 )
392 const route = all[1]
393 if (all[0]?.join('|') !== 'Method|URL' || route?.[0] !== 'POST' || !route[1])
394 fail('missing native request address')
395 const url = new URL(route[1])
396 if (url.origin !== 'https://api.ant-ling.com') fail('native API host changed')
397 return {
398 openapi: '3.1.0',
399 info: { title: 'Ant Ling native API', version: 'source-derived' },
400 paths: {
401 [url.pathname]: {
402 post: {
403 requestBody: {
404 required: true,
405 content: { 'application/json': { schema: nativeRequest(api) } },
406 },
407 responses: {
408 '200': {
409 description:
410 'The source publishes response examples but no response field schema.',
411 },
412 },
413 },
414 },
415 },
416 }
417}