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

ant-ling.ts

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