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

ant-ling.ts

362 lines11.9 KB

1/** Dynamic direct Ant Ling facts; never reseller prices or borrowed schemas. */
2import { cachedDocs } from '../model-facts.ts'
3import { tagDocsFacts } from '../fact-sources.ts'
4import { bearerConnect } from '../connect.ts'
5import { sha256Text } from '../types.ts'
6import { SHARED_EFFORT_LEVELS } from '../request-map.ts'
7import type { ChatRequestMap, EffortLevelMap } from '../request-map.ts'
8import type {
9 ModelInfo,
10 ProviderConfig,
11 ProviderEnvironment,
12} from '../types.ts'
13import {
14 ANT_OPENAI,
15 ANT_OVERVIEW,
16 ANT_PRICE,
17 ANT_LING,
18 ANT_EFFORT,
19 text,
20 article,
21 controls,
22 blocks,
23 overviewContextIds,
24 antModelRows,
25 nativeModelIds,
26 nativePrices,
27 priceCards,
28 nativeContexts,
29 nativeFields,
30 nativeRequest,
31 antSpec,
32} from '../ant-ling-docs.ts'
33​
34function validateNativeArticle(html: string): void {
35 if (
36 /window\.netd\s*=|id=["']netd-iframe["']|waf\.alipay\.com\/api\/v1\/sec-human-appeal/.test(
37 html,
38 )
39 )
40 throw new Error('native documentation blocked by Alipay WAF/captcha')
41 article(html)
43​
44const INPUT_WORDS: Record<string, string> = {
45 text: 'text',
46 images: 'image',
47 videos: 'video',
48 audio: 'audio',
50​
51function record(value: unknown): value is Record<string, unknown> {
52 return !!value && typeof value === 'object' && !Array.isArray(value)
54​
55async function browserHtml(
56 url: string,
57 env: ProviderEnvironment,
58): Promise<string> {
59 if (!env.BROWSER || typeof env.BROWSER.quickAction !== 'function')
60 throw new Error('Cloudflare Browser Rendering BROWSER binding is required')
61 const response = await env.BROWSER.quickAction('content', {
62 url,
63 gotoOptions: { timeout: 30_000, waitUntil: 'domcontentloaded' },
64 actionTimeout: 30_000,
65 })
66 if (!response.ok)
67 throw new Error(
68 `Cloudflare Browser Rendering request failed: HTTP ${response.status}`,
69 )
70 const body: unknown = await response.json()
71 if (
72 !record(body) ||
73 body.success !== true ||
74 typeof body.result !== 'string' ||
75 !record(body.meta)
76 )
77 throw new Error('unreadable Cloudflare Browser Rendering content response')
78 const meta = body.meta
79 if (
80 typeof meta.status !== 'number' ||
81 !Number.isInteger(meta.status) ||
82 meta.status < 200 ||
83 meta.status >= 300
84 )
85 throw new Error(
86 `Cloudflare Browser Rendering native page failed: status ${String(meta.status)}`,
87 )
88 if (
89 typeof meta.finalUrl !== 'string' ||
90 new URL(meta.finalUrl).href !== new URL(url).href
91 )
92 throw new Error('Cloudflare Browser Rendering native page URL mismatch')
93 return body.result
95​
96async function load(url: string, env: ProviderEnvironment, kv?: KVNamespace) {
97 try {
98 if (!env.BROWSER || typeof env.BROWSER.quickAction !== 'function')
99 throw new Error(
100 'Cloudflare Browser Rendering BROWSER binding is required',
101 )
102 const doc = await cachedDocs(
103 kv,
104 `ant-ling:${url}#cloudflare-browser-content-v1`,
105 async () => {
106 const html = await browserHtml(url, env)
107 validateNativeArticle(html)
108 return { html, hash: await sha256Text(html) }
109 },
110 )
111 validateNativeArticle(doc.html)
112 return doc
113 } catch (error) {
114 throw new Error(
115 `ant-ling: native source ${url}: ${error instanceof Error ? error.message : String(error)}`,
116 { cause: error },
117 )
118 }
120export const provider: ProviderConfig = {
121 id: 'ant-ling',
122 displayName: 'Ant Ling',
123 specSourceUrl: ANT_OPENAI,
124 modelsEndpoint: ANT_PRICE,
125 defaultDerivation: 'docs-derived',
126 bindSyncedRoutesOnly: true,
127 perModelSchemaFlags: ['reasoning'],
128 connect: bearerConnect('https://api.ant-ling.com'),
129 async listModels(env, kv) {
130 // Sequential cache misses keep browser requests within session capacity.
131 const sources = []
132 for (const url of [
133 ANT_OPENAI,
134 ANT_OVERVIEW,
135 ANT_PRICE,
136 ANT_LING,
137 ANT_EFFORT,
138 ])
139 sources.push(await load(url, env, kv))
140 const [api, overview, pricing, ling, effort] = sources
141 if (!api || !overview || !pricing || !ling || !effort)
142 throw new Error('ant-ling: missing loaded source')
143 const overviewIds = overviewContextIds(overview.html)
144 const contexts = nativeContexts(overview.html, ling.html)
145 const quotes = nativePrices(pricing.html)
146 const cards = priceCards(quotes, {
147 url: ANT_PRICE,
148 hash: pricing.hash,
149 extractedAt: new Date().toISOString(),
150 })
151 const control = controls(api.html)
152 const fields = nativeFields(api.html)
153 const schema = nativeRequest(api.html)
154 const properties = schema.properties as Record<string, unknown>
155 const role = fields.get('messages.role')
156 if (!role) throw new Error('ant-ling: missing native role declaration')
157 const apiIds = new Set(nativeModelIds(api.html))
158 const nativePaths = Object.keys(antSpec(api.html).paths)
159 if (nativePaths.length !== 1 || !nativePaths[0])
160 throw new Error('ant-ling: unreadable native API route')
161 const nativeEndpointId = nativePaths[0].replace(/^\//, '')
162 const apiOverview = text(article(overview.html))
163 // "When using <id>, the request accepts text, images, and videos." — one
164 // statement per model that takes more than text.
165 const accepts = new Map(
166 [
167 ...text(fields.get('model') ?? '').matchAll(
168 /When using ([\w.-]+)\s*, the request accepts ([^.]+)\./g,
169 ),
170 ].map(([, id = '', list = '']) => [
171 id,
172 list.split(/,\s*(?:and\s+)?|\s+and\s+/).map((word) => {
173 const modality = INPUT_WORDS[word]
174 if (!modality)
175 throw new Error(
176 `ant-ling: unreadable native input modality ${word}`,
177 )
178 return modality
179 }),
180 ]),
181 )
182 if (
183 !accepts.size ||
184 accepts.size !==
185 text(fields.get('model') ?? '').split('When using ').length - 1 ||
186 [...accepts.keys()].some((id) => !apiIds.has(id))
187 )
188 throw new Error('ant-ling: missing native multimodal applicability')
189 const levels = Object.fromEntries(
190 SHARED_EFFORT_LEVELS.map((level) => [
191 level,
192 control.efforts.includes(level) ? level : null,
193 ]),
194 ) as EffortLevelMap
195 const toggleOn = control.toggles.find((v) => v === 'enabled')
196 const toggleOff = control.toggles.find((v) => v === 'disabled')
197 if (
198 !toggleOn ||
199 !toggleOff ||
200 (control.effortIds.length > 0 &&
201 (!control.efforts.length ||
202 !control.effortDefault ||
203 !control.efforts.includes(control.effortDefault)))
204 )
205 throw new Error('ant-ling: unreadable native control values')
206 const effortText = text(article(effort.html))
207 if (!control.effortIds.every((id) => effortText.includes(id)))
208 throw new Error('ant-ling: effort source model disagreement')
209 const map: ChatRequestMap = {
210 thinking: null,
211 maxTokensField: 'max_tokens' in properties ? 'max_tokens' : null,
212 developerRole: text(role).includes('developer') ? null : false,
213 replayReasoningContent: null,
214 store: null,
215 strictTools: null,
216 sessionAffinity: null,
217 cacheControl: null,
218 toolStream: null,
219 reasoningEffort: null,
220 }
221 return {
222 models: antModelRows(api.html, pricing.html, contexts).map(
223 (model): ModelInfo => {
224 const hasEffort = control.effortIds.includes(model.rawId)
225 const hasToggle = control.toggleIds.includes(model.rawId)
226 const reasoning = hasEffort
227 ? {
228 mode: 'effort' as const,
229 mandatory: null,
230 efforts: control.efforts,
231 }
232 : hasToggle
233 ? { mode: 'toggle' as const, mandatory: false }
234 : null
235 const thinking = hasEffort
236 ? {
237 on:
238 control.effortField === 'reasoning'
239 ? { reasoning: { effort: control.effortDefault } }
240 : { reasoning_effort: control.effortDefault },
241 off: null,
242 levels,
243 }
244 : hasToggle
245 ? {
246 on: { thinking: { type: toggleOn } },
247 off: { thinking: { type: toggleOff } },
248 levels: null,
249 }
250 : null
251 const declaredText =
252 apiIds.has(model.rawId) && apiOverview.includes('Text Conversation')
253 // Text-only rows are sourced from the native text-conversation scope;
254 // a newer price-only ID has no API-scoped modality statement yet.
255 const modalities = declaredText
256 ? {
257 input: accepts.get(model.rawId) ?? ['text'],
258 output: ['text'],
259 }
260 : null
261 const lingDetail = text(
262 blocks(article(ling.html)).get(model.rawId) ?? '',
263 )
264 const capabilities = declaredText
265 ? ['tools', ...(reasoning ? ['reasoning'] : [])]
266 : /tool calling/.test(lingDetail)
267 ? [
268 'tools',
269 ...(/hybrid reasoning/.test(lingDetail) ? ['reasoning'] : []),
270 ]
271 : null
272 const requestMap = apiIds.has(model.rawId)
273 ? { ...map, thinking }
274 : null
275 const facts = {
276 ...model,
277 modalities,
278 capabilities,
279 pricing: cards.get(model.rawId) ?? null,
280 absent: cards.has(model.rawId)
281 ? undefined
282 : { pricing: 'cleared' as const },
283 schemaEndpointId: apiIds.has(model.rawId) ? nativeEndpointId : null,
284 reasoning,
285 requestMap,
286 }
287 const contextUrl = overviewIds.has(model.rawId)
288 ? ANT_OVERVIEW
289 : ANT_LING
290 const contextHash =
291 contextUrl === ANT_OVERVIEW ? overview.hash : ling.hash
292 return {
293 ...facts,
294 providerMetadata: {
295 ...(quotes.has(model.rawId)
296 ? {
297 directQuote: quotes.get(model.rawId)?.free
298 ? 'currently-free'
299 : 'paid',
300 }
301 : {}),
302 ...(control.effortIds.includes(model.rawId)
303 ? { nativeReasoningModelSource: ANT_EFFORT }
304 : {}),
305 },
306 factSources: {
307 ...(apiIds.has(model.rawId)
308 ? {
309 schemaEndpointId: {
310 derivation: 'docs-derived' as const,
311 sourceUrl: ANT_OPENAI,
312 sourceHash: api.hash,
313 path: 'Request Address + model.Options',
314 },
315 }
316 : {}),
317 ...tagDocsFacts(
318 { contextWindow: model.contextWindow },
319 contextUrl,
320 contextHash,
321 ),
322 ...tagDocsFacts({ modalities, reasoning }, ANT_OPENAI, api.hash),
323 ...(capabilities
324 ? tagDocsFacts(
325 { capabilities },
326 declaredText ? ANT_OPENAI : ANT_LING,
327 declaredText ? api.hash : ling.hash,
328 )
329 : {}),
330 ...(requestMap
331 ? {
332 requestMap: {
333 derivation: 'docs-derived' as const,
334 sourceUrl: ANT_OPENAI,
335 sourceHash: api.hash,
336 path: 'Request Body',
337 },
338 }
339 : {}),
340 ...(facts.pricing
341 ? tagDocsFacts(
342 { pricing: facts.pricing },
343 ANT_PRICE,
344 pricing.hash,
345 )
346 : {}),
347 },
348 }
349 },
350 ),
351 }
352 },
353 async fetchSpec(env) {
354 const api = await load(ANT_OPENAI, env)
355 return {
356 specs: [antSpec(api.html)],
357 sources: [{ url: ANT_OPENAI, hash: api.hash }],
358 outputStrategy: 'post-200',
359 }
360 },
361 classify: (path) => (path === '/v1/chat/completions' ? 'chat' : null),