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

ant-ling-docs.ts

439 lines16.5 KB

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