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

ant-ling-docs.ts

345 lines12.6 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/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_RING = `${ANT_ROOT}models/ring/`
12export const ANT_EFFORT = `${ANT_ROOT}tutorials/effort/`
13function fail(message: string): never {
14 throw new Error(`ant-ling: ${message}`)
16export function text(html: string): string {
17 return html
18 .replace(/<[^>]*>/g, ' ')
19 .replace(/&amp;/g, '&')
20 .replace(/&quot;/g, '"')
21 .replace(/&#39;|&#x27;/g, "'")
22 .replace(/&lt;/g, '<')
23 .replace(/&gt;/g, '>')
24 .replace(/\s+/g, ' ')
25 .trim()
27export function article(html: string): string {
28 const body = html.match(/<article\b[^>]*>([\s\S]*?)<\/article>/)?.[1]
29 if (!body) fail('missing native article')
30 return body
32export function rows(html: string): Array<Array<string>> {
33 return [...html.matchAll(/<tr\b[\s\S]*?<\/tr>/g)].map((row) =>
34 [...row[0].matchAll(/<t[dh]\b[^>]*>([\s\S]*?)<\/t[dh]>/g)].map(
35 (cell) => cell[1] ?? '',
36 ),
37 )
39function section(html: string, id: string): string {
40 const s = html.match(
41 new RegExp(
42 `<h[234]\\b[^>]*id="${id}"[^>]*>[\\s\\S]*?<\\/h[234]>([\\s\\S]*?)(?=<h2\\b|$)`,
43 ),
44 )?.[1]
45 if (s === undefined) fail(`missing ${id} section`)
46 return s
48export function blocks(html: string): Map<string, string> {
49 const head = [...html.matchAll(/<h[34]\b[^>]*>[\s\S]*?<\/h[34]>/g)]
50 return new Map(
51 head.map((m, i) => [
52 text(m[0]),
53 html.slice(m.index + m[0].length, head[i + 1]?.index ?? html.length),
54 ]),
55 )
57function options(block: string): Array<string> {
58 const after = block.split(/<strong>Options<\/strong>:/)[1]
59 if (after === undefined) return []
60 return [
61 ...(after.split('</ul>')[0]?.matchAll(/<code\b[^>]*>([^<]+)<\/code>/g) ??
62 []),
63 ].map((m) => text(m[1] ?? ''))
65export function nativeFields(html: string): Map<string, string> {
66 return blocks(section(article(html), 'request-body'))
68export function nativeModelIds(html: string): Array<string> {
69 const model = nativeFields(html).get('model')
70 if (!model) fail('missing model parameter')
71 const ids = options(model)
72 if (!ids.length || new Set(ids).size !== ids.length)
73 fail('unreadable native model options')
74 return ids
76export interface NativePrice {
77 rates: Record<string, number>
78 free: boolean
80export function nativePrices(html: string): Map<string, NativePrice> {
81 const body = section(article(html), 'model-pricing')
82 if (!text(body).includes('All prices below are in CNY'))
83 fail('direct pricing currency not CNY')
84 const table = body.match(/<table\b[\s\S]*?<\/table>/)?.[0]
85 if (!table) fail('missing direct price table')
86 const all = rows(table)
87 if (
88 all[0]?.map(text).join('|') !==
89 'Model|Use Case|Input (per 1M tokens)|Output (per 1M tokens)|Cache Read (per 1M tokens)'
90 )
91 fail('direct pricing headers changed')
92 const out = new Map<string, NativePrice>()
93 for (const row of all.slice(1)) {
94 if (row.length !== 5) fail('direct price row missing cells')
95 const id = text(row[0] ?? '')
96 if (!id || out.has(id)) fail('missing or duplicate direct model ID')
97 const amounts = row.slice(2).map((cell) => {
98 const current = text(cell.replace(/<del\b[\s\S]*?<\/del>/g, ''))
99 const price = /^¥(\d+(?:\.\d+)?)$/.exec(current)
100 if (!price) fail('unreadable current CNY price')
101 return Number(price[1]) / 1e6
102 })
103 const input = amounts[0],
104 output = amounts[1],
105 cache = amounts[2]
106 if (input === undefined || output === undefined || cache === undefined)
107 fail('missing direct price')
108 out.set(id, {
109 rates: {
110 input_tokens: input,
111 output_tokens: output,
112 cache_read_tokens: cache,
113 },
114 free: amounts.every((a) => a === 0),
115 })
116 }
117 if (!out.size) fail('direct price table empty')
118 return out
120export function priceCards(
121 prices: Map<string, NativePrice>,
122 source: RateCard['source'],
123): Map<string, RateCard> {
124 const out = new Map<string, RateCard>()
125 for (const [id, quote] of prices) {
126 // A constant zero is justified only when every current native quote is zero.
127 const card = quote.free
128 ? {
129 inputs: {},
130 tables: { rate: { base: quote.rates } },
131 price: {
132 currency: ['CNY', quote.rates.input_tokens],
133 } as RateCard['price'],
134 examples: [],
135 source,
136 }
137 : compileTokenCard(quote.rates, [], source, { currency: 'CNY' })
138 if (!card) fail('uncompilable direct price')
139 out.set(id, card)
140 }
141 return out
143export function nativeContexts(
144 overview: string,
145 ling: string,
146): Map<string, number> {
147 const out = new Map<string, number>()
148 const body = section(article(overview), 'model-quick-overview')
149 const table = body.match(/<table\b[\s\S]*?<\/table>/)?.[0]
150 if (!table) fail('missing hosted context overview')
151 const all = rows(table)
152 if (all[0]?.map(text).join('|') !== 'Model Name|Context Window|Description')
153 fail('context overview headers changed')
154 const tokens = (value: string) => {
155 const m = /^(\d+(?:\.\d+)?)(K|M)$/.exec(value)
156 if (!m) fail('unreadable context')
157 const limit = Number(m[1]) * (m[2] === 'K' ? 1e3 : 1e6)
158 if (!Number.isSafeInteger(limit) || limit <= 0)
159 fail('invalid context limit')
160 return limit
161 }
162 for (const row of all.slice(1)) {
163 if (row.length !== 3) fail('context row missing cells')
164 out.set(text(row[0] ?? ''), tokens(text(row[1] ?? '')))
165 }
166 const selection = section(article(ling), 'model-selection-guide').match(
167 /<table\b[\s\S]*?<\/table>/,
168 )?.[0]
169 if (!selection) fail('missing Ling model selection')
170 for (const row of rows(selection).slice(1)) {
171 const id = text(row[0] ?? '')
172 const context = text(row[2] ?? '')
173 if (context !== '—' && !out.has(id)) out.set(id, tokens(context))
174 }
175 return out
177export function overviewContextIds(html: string): Set<string> {
178 return new Set(
179 rows(section(article(html), 'model-quick-overview'))
180 .slice(1)
181 .map((row) => text(row[0] ?? '')),
182 )
184type Schema = Record<string, unknown>
185export function nativeRequest(html: string): Schema {
186 const fields = nativeFields(html)
187 const overview = fields.get('Overview')
188 const table = overview?.match(/<table\b[\s\S]*?<\/table>/)?.[0]
189 if (!table) fail('missing request overview')
190 const all = rows(table).map((row) => row.map(text))
191 if (all[0]?.join('|') !== 'Parameter|Type|Required|Default|Description')
192 fail('request parameter table headers changed')
193 const schema: Schema = { type: 'object', properties: {}, required: [] }
194 const nodes = new Map<string, Schema>([['', schema]])
195 const type = (name: string): Schema => {
196 if (['string', 'boolean', 'object'].includes(name)) return { type: name }
197 if (name === 'double') return { type: 'number' }
198 if (name === 'object[]') return { type: 'array', items: { type: 'object' } }
199 if (name === 'list')
200 return { type: 'array', items: { 'x-source-type': null } }
201 fail(`unknown native field type ${name}`)
202 }
203 for (const row of all.slice(1)) {
204 if (row.length !== 5 || !['Yes', 'No'].includes(row[2] ?? ''))
205 fail('request parameter row missing cells')
206 const name = row[0] ?? ''
207 const node = type(row[1] ?? '')
208 node.description = row[4]
209 const range = row[4]?.match(
210 /([[(])\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*([\])])/,
211 )
212 if (range) {
213 node[range[1] === '(' ? 'exclusiveMinimum' : 'minimum'] = Number(range[2])
214 node[range[4] === ')' ? 'exclusiveMaximum' : 'maximum'] = Number(range[3])
215 }
216 const def = row[3]
217 if (def !== undefined && def !== '—') {
218 if (!def) fail('missing parameter default cell')
219 if (def === 'true' || def === 'false') node.default = def === 'true'
220 else if (Number.isFinite(Number(def))) node.default = Number(def)
221 else fail('unknown parameter default')
222 }
223 const detail = fields.get(name)
224 if (!detail) fail(`missing native detail for ${name}`)
225 const values = options(detail)
226 if (values.length) {
227 // Native model options lag the direct pricing catalog. Preserve the list
228 // as evidence without inventing a closed allowlist for newer native IDs.
229 node[name === 'model' ? 'x-source-options' : 'enum'] = values
230 }
231 ;(schema.properties as Record<string, Schema>)[name] = node
232 nodes.set(name, node)
233 if (row[2] === 'Yes') (schema.required as Array<string>).push(name)
234 }
235 for (const [name, detail] of fields) {
236 if (!name.includes('.')) continue
237 const pieces = name.split('.')
238 const leaf = pieces.pop()
239 const parentKey = pieces.join('.')
240 let parent = nodes.get(parentKey)
241 if (!parent || !leaf) fail(`unresolved native nested field ${name}`)
242 if (parent.type === 'array') parent = parent.items as Schema
243 if (parent.type !== 'object') fail('nested field has non-object parent')
244 const declared = detail.match(
245 /<strong>Type<\/strong>: ([\s\S]*?)<\/li>/,
246 )?.[1]
247 if (!declared) fail('missing native nested type')
248 const node = type(text(declared))
249 // The same native page states that its VL model accepts image/video blocks,
250 // contradicting the formal string-only content declaration. Preserve both
251 // statements as source evidence; no block shape is published in this table.
252 if (
253 name === 'messages.content' &&
254 /the request accepts text, images, and videos/.test(
255 text(fields.get('model') ?? ''),
256 )
257 ) {
258 delete node.type
259 node['x-source-type'] = null
260 node['x-source-declared-type'] = text(declared)
261 node['x-source-conflicting-statement'] = text(fields.get('model') ?? '')
262 }
263 const values = options(detail)
264 if (values.length) node.enum = values
265 const def = detail.match(/default <code\b[^>]*>([^<]+)<\/code>/)?.[1]
266 if (def !== undefined)
267 node.default = def === 'true' ? true : def === 'false' ? false : def
268 ;((parent.properties ??= {}) as Record<string, Schema>)[leaf] = node
269 if (/<strong>Required<\/strong>/.test(detail))
270 ((parent.required ??= []) as Array<string>).push(leaf)
271 nodes.set(name, node)
272 }
273 return schema
275export function applicability(html: string, field: string): string {
276 const block = nativeFields(html).get(field)
277 if (!block) fail(`missing ${field} applicability`)
278 const t = text(block)
279 const id = t.match(/Only (?:takes effect|effective) for ([\w.-]+)/i)?.[1]
280 if (!id) fail(`unreadable ${field} applicability`)
281 return id.replace(/\.$/, '')
283export function controls(html: string) {
284 const fields = nativeFields(html)
285 const effort = fields.get('reasoning.effort')
286 const toggle = fields.get('thinking.type')
287 if (!effort || !toggle) fail('missing native reasoning controls')
288 return {
289 effortId: applicability(html, 'reasoning'),
290 toggleId: applicability(html, 'thinking'),
291 efforts: options(effort),
292 effortDefault:
293 effort.match(/default <code\b[^>]*>([^<]+)<\/code>/)?.[1] ?? null,
294 toggles: options(toggle),
295 }
297export function antModelRows(
298 api: string,
299 pricing: string,
300 contexts: Map<string, number>,
301): Array<ModelInfo> {
302 const apiIds = new Set(nativeModelIds(api))
303 const ids = [...new Set([...apiIds, ...nativePrices(pricing).keys()])]
304 return ids.map((rawId) => ({
305 rawId,
306 displayName: null,
307 activity: apiIds.has(rawId) ? 'chat' : null,
308 contextWindow: contexts.get(rawId) ?? null,
309 maxOutput: null,
310 modalities: null,
311 pricing: null,
312 reasoning: null,
313 requestMap: null,
314 }))
316export function antSpec(api: string) {
317 const all = rows(section(article(api), 'request-address')).map((row) =>
318 row.map(text),
319 )
320 const route = all[1]
321 if (all[0]?.join('|') !== 'Method|URL' || route?.[0] !== 'POST' || !route[1])
322 fail('missing native request address')
323 const url = new URL(route[1])
324 if (url.origin !== 'https://api.ant-ling.com') fail('native API host changed')
325 return {
326 openapi: '3.1.0',
327 info: { title: 'Ant Ling native API', version: 'source-derived' },
328 paths: {
329 [url.pathname]: {
330 post: {
331 requestBody: {
332 required: true,
333 content: { 'application/json': { schema: nativeRequest(api) } },
334 },
335 responses: {
336 '200': {
337 description:
338 'The source publishes response examples but no response field schema.',
339 },
340 },
341 },
342 },
343 },
344 }