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

dashscope-model-limits.ts

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