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

dashscope-model-limits.ts

248 lines8.0 KB

1/**
2 * Context window and max output from a Model Studio model-info markdown
3 * page. The listing leaves both null on a few chat rows; the page's
4 * Context limits table publishes them. A page that parses nothing throws.
5 * Thinking-mode and chain-of-thought lengths are not the max output.
6 * Maximum input tokens are not the context window.
7 */
8import { markdownTableRows } from './model-facts.ts'
9import { sha256Text } from './types.ts'
10​
11const PAGE_ORIGIN = 'https://www.alibabacloud.com/help/en/model-studio'
12​
13/**
14 * alibabacloud.com answered the Worker's bare fetch with an HTML page from
15 * 2026-10-07 (issue #256); workerd sends no User-Agent or Accept. These
16 * match a browser's fetch of the `.md` URL. Since 2026-10-27 the portal
17 * serves the rendered page to every client (issue #520); `dashscopeDocText`
18 * reads either answer.
19 */
20export const DASHSCOPE_DOCS_INIT: RequestInit = {
21 headers: {
22 Accept: 'text/markdown,text/plain,*/*',
23 'User-Agent':
24 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
25 },
27​
28export interface DashscopeModelLimits {
29 contextWindow: number | null
30 maxOutput: number | null
32​
33export interface DashscopeLimitsDoc {
34 sourceHash: string
35 models: Record<string, DashscopeModelLimits>
37​
38const CONTEXT = /^context window$/i
39const MAX_OUTPUT = /^max(?:imum)? output (?:length|tokens)$/i
40const NOT_RESPONSE = /thinking|chain-of-thought|chain of thought/i
41​
42/** Dated snapshots are sections of the stable id's page. */
43export function dashscopeModelPageUrl(rawId: string): string {
44 const stable = rawId.replace(/-\d{4}-\d{2}-\d{2}$/, '')
45 return `${PAGE_ORIGIN}/${stable.replace(/\./g, '-')}.md`
47​
48function cellText(html: string): string {
49 return html
50 .replace(/<[^>]+>/g, ' ')
51 .replace(/\s+/g, ' ')
52 .trim()
54​
55function headingText(line: string): string | null {
56 const match = /^(#{1,6})\s+(.*)$/.exec(line)
57 if (!match?.[2]) return null
58 return match[2].replace(/<[^>]+>/g, '').trim()
60​
61function isModelId(text: string): boolean {
62 return /^[a-z0-9][a-z0-9._-]*$/i.test(text) && /[-.]/.test(text)
64​
65function sectionAfter(lines: Array<string>, start: number): string {
66 const body: Array<string> = []
67 for (let i = start; i < lines.length; i++) {
68 if (/^#{1,6}\s/.test(lines[i] ?? '')) break
69 body.push(lines[i] ?? '')
70 }
71 return body.join('\n')
73​
74function htmlRows(section: string): Array<Array<string>> {
75 const table = section.match(/<table[\s\S]*?<\/table>/i)?.[0]
76 if (!table) return []
77 const rows: Array<Array<string>> = []
78 for (const row of table.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)) {
79 const rowHtml = row[1]
80 if (!rowHtml) continue
81 const cells = [
82 ...rowHtml.matchAll(/<t[dh][^>]*>([\s\S]*?)<\/t[dh]>/gi),
83 ].flatMap((cell) => {
84 const html = cell[1]
85 return html == null ? [] : [cellText(html)]
86 })
87 if (cells.length > 0) rows.push(cells)
88 }
89 return rows
91​
92function tableRows(section: string): Array<Array<string>> {
93 const htmlAt = section.indexOf('<table')
94 const markdownAt = section.search(/^\|/m)
95 if (htmlAt >= 0 && (markdownAt < 0 || htmlAt < markdownAt)) {
96 return htmlRows(section)
97 }
98 return markdownTableRows(section)
100​
101function wholeNumber(text: string): number | null {
102 if (!/^[\d,]+$/.test(text)) return null
103 const value = Number(text.replace(/,/g, ''))
104 if (!Number.isInteger(value) || value < 0) return null
105 return value
107​
108function limitsFrom(rows: Array<Array<string>>): DashscopeModelLimits | null {
109 if (rows.length === 0) return null
110 let contextWindow: number | null = null
111 let maxOutput: number | null = null
112 for (const row of rows) {
113 for (let i = 0; i + 1 < row.length; i += 2) {
114 const label = row[i] ?? ''
115 if (label === '' || NOT_RESPONSE.test(label)) continue
116 const value = wholeNumber(row[i + 1] ?? '')
117 if (value === null) continue
118 if (CONTEXT.test(label)) contextWindow = value
119 else if (MAX_OUTPUT.test(label)) maxOutput = value
120 }
121 }
122 return { contextWindow, maxOutput }
124​
125export function parseDashscopeModelLimits(
126 markdown: string,
127): Record<string, DashscopeModelLimits> {
128 const lines = markdown.split('\n')
129 let current: string | null = null
130 const models: Record<string, DashscopeModelLimits> = {}
131 for (let i = 0; i < lines.length; i++) {
132 const title = headingText(lines[i] ?? '')
133 if (!title) continue
134 if (isModelId(title)) current = title
135 if (!/^context limits$/i.test(title) || !current) continue
136 const limits = limitsFrom(tableRows(sectionAfter(lines, i + 1)))
137 if (limits) models[current] = limits
138 }
139 const parsed = Object.values(models)
140 if (
141 parsed.every((row) => row.contextWindow == null && row.maxOutput == null)
142 ) {
143 throw new Error('dashscope model page: parsed 0 context-limit rows')
144 }
145 return models
147​
148function decodeEntities(text: string): string {
149 return text
150 .replace(/&nbsp;/g, ' ')
151 .replace(/&quot;/g, '"')
152 .replace(/&#39;|&#x27;|&apos;/g, "'")
153 .replace(/&lt;/g, '<')
154 .replace(/&gt;/g, '>')
155 .replace(/&#(\d+);/g, (_, code: string) =>
156 String.fromCodePoint(Number(code)),
157 )
158 .replace(/&amp;/g, '&')
160​
161function inlineText(html: string): string {
162 return decodeEntities(html.replace(/<[^>]+>/g, ' '))
163 .replace(/\s+/g, ' ')
164 .trim()
166​
167/**
168 * The rendered help page's article, back in the shape the `.md` URL used
169 * to serve: headings become `#` lines, `<code>` backticks, `<pre>` fences,
170 * block elements line breaks. Tables stay HTML; the parsers read those as
171 * the markdown carried them.
172 */
173function articleText(article: string): string {
174 const tables: Array<string> = []
175 const text = article
176 .replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, '')
177 .replace(
178 /<table\b[\s\S]*?<\/table>/gi,
179 (table) => `\n\uE000${String(tables.push(table) - 1)}\uE000\n`,
180 )
181 .replace(
182 /<pre\b[^>]*>([\s\S]*?)<\/pre>/gi,
183 (_, code: string) =>
184 `\n\`\`\`\n${decodeEntities(code.replace(/<[^>]+>/g, ''))}\n\`\`\`\n`,
185 )
186 .replace(
187 /<h([1-6])\b[^>]*>([\s\S]*?)<\/h\1>/gi,
188 (_, level: string, inner: string) =>
189 `\n${'#'.repeat(Number(level))} ${inlineText(inner)}\n`,
190 )
191 .replace(
192 /<code\b[^>]*>([\s\S]*?)<\/code>/gi,
193 (_, inner: string) => `\`${inner.replace(/<[^>]+>/g, '')}\``,
194 )
195 .replace(
196 /<\/?(?:p|li|ul|ol|div|section|blockquote|br|dd|dt)\b[^>]*>/gi,
197 '\n',
198 )
199 .replace(/<[^>]+>/g, '')
200 return `${decodeEntities(text)
201 .replace(
202 /\uE000(\d+)\uE000/g,
203 (_, index: string) => tables[Number(index)] ?? '',
204 )
205 .replace(/[ \t]+\n/g, '\n')
206 .replace(/\n{3,}/g, '\n\n')
207 .trim()}\n`
209​
210/**
211 * The text the Model Studio parsers read: the body itself when it is
212 * markdown, or the article of a rendered help page (issue #520) turned
213 * back into that shape, under the page's h1 (`<product>:<title>`, outside
214 * the article) as the markdown's `#` title. Throws on an HTML page with no
215 * article (a challenge or an error page), naming its title and first 200
216 * characters so the next failure shows what Alibaba served.
217 */
218export function dashscopeDocText(body: string, label: string): string {
219 const text = body.trimStart()
220 if (!text.startsWith('<')) return body
221 const article = text.match(
222 /<article\b[^>]*\bmarkdown-body\b[^>]*>([\s\S]*?)<\/article>/i,
223 )?.[1]
224 if (article) {
225 const h1 = text.match(/<h1\b[^>]*>([\s\S]*?)<\/h1>/i)?.[1]
226 const heading = h1
227 ? `# ${inlineText(h1).replace(/^Alibaba Cloud Model Studio:/, '')}\n\n`
228 : ''
229 return heading + articleText(article)
230 }
231 const title = text.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1]?.trim()
232 const head = text.slice(0, 200).replace(/\s+/g, ' ')
233 throw new Error(
234 `${label}: response is HTML, not markdown` +
235 (title ? ` (title: ${title})` : '') +
236 `: ${head}`,
237 )
239​
240export async function loadDashscopeModelLimits(
241 body: string,
242): Promise<DashscopeLimitsDoc> {
243 const markdown = dashscopeDocText(body, 'dashscope model page')
244 return {
245 sourceHash: await sha256Text(markdown),
246 models: parseDashscopeModelLimits(markdown),
247 }