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

dashscope-model-limits.ts

172 lines5.5 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.
17 */
18export const DASHSCOPE_DOCS_INIT: RequestInit = {
19 headers: {
20 Accept: 'text/markdown,text/plain,*/*',
21 'User-Agent':
22 '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',
23 },
25​
26export interface DashscopeModelLimits {
27 contextWindow: number | null
28 maxOutput: number | null
30​
31export interface DashscopeLimitsDoc {
32 sourceHash: string
33 models: Record<string, DashscopeModelLimits>
35​
36const CONTEXT = /^context window$/i
37const MAX_OUTPUT = /^max(?:imum)? output (?:length|tokens)$/i
38const NOT_RESPONSE = /thinking|chain-of-thought|chain of thought/i
39​
40/** Dated snapshots are sections of the stable id's page. */
41export function dashscopeModelPageUrl(rawId: string): string {
42 const stable = rawId.replace(/-\d{4}-\d{2}-\d{2}$/, '')
43 return `${PAGE_ORIGIN}/${stable.replace(/\./g, '-')}.md`
45​
46function cellText(html: string): string {
47 return html
48 .replace(/<[^>]+>/g, ' ')
49 .replace(/\s+/g, ' ')
50 .trim()
52​
53function headingText(line: string): string | null {
54 const match = /^(#{1,6})\s+(.*)$/.exec(line)
55 if (!match?.[2]) return null
56 return match[2].replace(/<[^>]+>/g, '').trim()
58​
59function isModelId(text: string): boolean {
60 return /^[a-z0-9][a-z0-9._-]*$/i.test(text) && /[-.]/.test(text)
62​
63function sectionAfter(lines: Array<string>, start: number): string {
64 const body: Array<string> = []
65 for (let i = start; i < lines.length; i++) {
66 if (/^#{1,6}\s/.test(lines[i] ?? '')) break
67 body.push(lines[i] ?? '')
68 }
69 return body.join('\n')
71​
72function htmlRows(section: string): Array<Array<string>> {
73 const table = section.match(/<table[\s\S]*?<\/table>/i)?.[0]
74 if (!table) return []
75 const rows: Array<Array<string>> = []
76 for (const row of table.matchAll(/<tr>([\s\S]*?)<\/tr>/gi)) {
77 const rowHtml = row[1]
78 if (!rowHtml) continue
79 const cells = [
80 ...rowHtml.matchAll(/<t[dh][^>]*>([\s\S]*?)<\/t[dh]>/gi),
81 ].flatMap((cell) => {
82 const html = cell[1]
83 return html == null ? [] : [cellText(html)]
84 })
85 if (cells.length > 0) rows.push(cells)
86 }
87 return rows
89​
90function tableRows(section: string): Array<Array<string>> {
91 const htmlAt = section.indexOf('<table')
92 const markdownAt = section.search(/^\|/m)
93 if (htmlAt >= 0 && (markdownAt < 0 || htmlAt < markdownAt)) {
94 return htmlRows(section)
95 }
96 return markdownTableRows(section)
98​
99function wholeNumber(text: string): number | null {
100 if (!/^[\d,]+$/.test(text)) return null
101 const value = Number(text.replace(/,/g, ''))
102 if (!Number.isInteger(value) || value < 0) return null
103 return value
105​
106function limitsFrom(rows: Array<Array<string>>): DashscopeModelLimits | null {
107 if (rows.length === 0) return null
108 let contextWindow: number | null = null
109 let maxOutput: number | null = null
110 for (const row of rows) {
111 for (let i = 0; i + 1 < row.length; i += 2) {
112 const label = row[i] ?? ''
113 if (label === '' || NOT_RESPONSE.test(label)) continue
114 const value = wholeNumber(row[i + 1] ?? '')
115 if (value === null) continue
116 if (CONTEXT.test(label)) contextWindow = value
117 else if (MAX_OUTPUT.test(label)) maxOutput = value
118 }
119 }
120 return { contextWindow, maxOutput }
122​
123export function parseDashscopeModelLimits(
124 markdown: string,
125): Record<string, DashscopeModelLimits> {
126 const lines = markdown.split('\n')
127 let current: string | null = null
128 const models: Record<string, DashscopeModelLimits> = {}
129 for (let i = 0; i < lines.length; i++) {
130 const title = headingText(lines[i] ?? '')
131 if (!title) continue
132 if (isModelId(title)) current = title
133 if (!/^context limits$/i.test(title) || !current) continue
134 const limits = limitsFrom(tableRows(sectionAfter(lines, i + 1)))
135 if (limits) models[current] = limits
136 }
137 const parsed = Object.values(models)
138 if (
139 parsed.length === 0 ||
140 parsed.every((row) => row.contextWindow == null && row.maxOutput == null)
141 ) {
142 throw new Error('dashscope model page: parsed 0 context-limit rows')
143 }
144 return models
146​
147/**
148 * Throws when a Model Studio `.md` URL answered with an HTML page. The
149 * error carries the page title and the first 200 characters, so the next
150 * failure shows what Alibaba served (challenge, region notice).
151 */
152export function assertDashscopeMarkdown(body: string, label: string): void {
153 const text = body.trimStart()
154 if (!text.startsWith('<')) return
155 const title = text.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1]?.trim()
156 const head = text.slice(0, 200).replace(/\s+/g, ' ')
157 throw new Error(
158 `${label}: response is HTML, not markdown` +
159 (title ? ` (title: ${title})` : '') +
160 `: ${head}`,
161 )
163​
164export async function loadDashscopeModelLimits(
165 markdown: string,
166): Promise<DashscopeLimitsDoc> {
167 assertDashscopeMarkdown(markdown, 'dashscope model page')
168 return {
169 sourceHash: await sha256Text(markdown),
170 models: parseDashscopeModelLimits(markdown),
171 }