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

dashscope-compat.ts

213 lines6.7 KB

1/**
2 * OpenAI-compatible chat parameters from Model Studio's own markdown.
3 * The page is one HTML table inside the doc; its cells may carry MDX
4 * attributes (`<td style={{ ... }}>`). A zero-row parse throws.
5 * A parameter whose description limits it to some models is not stamped
6 * on every chat row.
7 */
8import { assertDashscopeMarkdown } from './dashscope-model-limits.ts'
9import type { ChatRequestMap } from './request-map.ts'
10import { sha256Text } from './types.ts'
11​
12export const DASHSCOPE_COMPAT_URL =
13 'https://www.alibabacloud.com/help/en/model-studio/compatibility-of-openai-with-dashscope.md'
14​
15/** Request parameters with no model restriction, and the flag they name. */
16const PARAM_TO_FLAG: Record<string, string> = {
17 temperature: 'temperature',
18 top_p: 'top_p',
19 max_tokens: 'max_tokens',
20 seed: 'seed',
21 stop: 'stop',
23​
24/**
25 * A limit to some models. Bare "only" is not one: top_p says "keeps only
26 * the smallest set of tokens", and tools says type is currently only
27 * "function".
28 */
29const RESTRICTED =
30 /supported only on|currently supported models|currently supported only/i
31​
32export interface DashscopeCompatFacts {
33 requestMap: ChatRequestMap
34 flags: Array<string>
35 sourceHash: string
36 scope: DashscopeCompatScope
38​
39/**
40 * Which listing ids the compat page names. `qwenLlm` is the generic Qwen
41 * line. `qwenKinds` are the Qwen-VL style names. `families` are the other
42 * names (DeepSeek, Kimi, GLM, MiniMax). `deny` is a family the page says
43 * does not speak this protocol (Qwen-Audio).
44 */
45export interface DashscopeCompatScope {
46 qwenLlm: boolean
47 qwenKinds: Array<string>
48 families: Array<string>
49 deny: Array<string>
51​
52/** Supported-models sentences from the compat page, checked 2026-10-08. */
53export const DASHSCOPE_COMPAT_SCOPE = `Supported models: Qwen large language models (commercial and open-source editions), Qwen-VL, Qwen-Coder, Qwen-Omni, Qwen-Math, DeepSeek, Kimi, GLM, MiniMax.
54Qwen-Audio does not support the OpenAI compatible protocol.`
55​
56/** The Supported models line, plus a family the page says is not compatible. */
57export function parseDashscopeCompatScope(
58 markdown: string,
59): DashscopeCompatScope {
60 const line = markdown.match(/Supported models:\s*([^\n]+)/i)?.[1] ?? ''
61 const items = line
62 .replace(/\.\s*$/, '')
63 .split(',')
64 .map((item) => item.trim())
65 .filter((item) => item !== '')
66 const scope: DashscopeCompatScope = {
67 qwenLlm: false,
68 qwenKinds: [],
69 families: [],
70 deny: [],
71 }
72 if (/qwen-audio does not support/i.test(markdown)) scope.deny.push('audio')
73 for (const item of items) {
74 if (/qwen large language models/i.test(item)) {
75 scope.qwenLlm = true
76 continue
77 }
78 const words = item
79 .toLowerCase()
80 .split(/[^a-z0-9]+/)
81 .filter((word) => word !== '')
82 if (words[0] === 'qwen' && words[1]) {
83 scope.qwenKinds.push(words[1])
84 continue
85 }
86 if (words[0]) scope.families.push(words[0])
87 }
88 return scope
90​
91/** True when this listing id is one of the compat page's supported models. */
92export function dashscopeCompatCovers(
93 rawId: string,
94 scope: DashscopeCompatScope,
95): boolean {
96 const id = rawId.toLowerCase()
97 const parts = id.split(/[^a-z0-9]+/).filter((part) => part !== '')
98 if (parts[0] === 'qwen' && scope.deny.some((kind) => parts.includes(kind))) {
99 return false
100 }
101 if (scope.qwenLlm && id.startsWith('qwen')) return true
102 if (
103 parts[0] === 'qwen' &&
104 scope.qwenKinds.some((kind) => parts.includes(kind))
105 ) {
106 return true
107 }
108 return scope.families.some((family) => id.startsWith(family))
110​
111interface CompatParam {
112 name: string
113 description: string
115​
116function cellText(html: string): string {
117 return html
118 .replace(/<[^>]+>/g, ' ')
119 .replace(/\\_/g, '_')
120 .replace(/\\\//g, '/')
121 .replace(/\s+/g, ' ')
122 .trim()
124​
125function requestSection(markdown: string): string {
126 const start = markdown.search(/request parameters/i)
127 const end = markdown.search(/response parameters/i)
128 if (start < 0 || end < start) {
129 throw new Error(`${DASHSCOPE_COMPAT_URL}: no request-parameter section`)
130 }
131 return markdown.slice(start, end)
133​
134function parameters(section: string): Array<CompatParam> {
135 const params: Array<CompatParam> = []
136 for (const row of section.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/g)) {
137 const rowHtml = row[1]
138 if (!rowHtml) continue
139 const cells = [...rowHtml.matchAll(/<td\b[^>]*>([\s\S]*?)<\/td>/g)].flatMap(
140 (cell) => {
141 const html = cell[1]
142 return html == null ? [] : [cellText(html)]
143 },
144 )
145 const raw = cells[0]
146 if (!raw || cells.length < 4) continue
147 const name = raw.replace(/\s*\(optional\)\s*$/i, '').trim()
148 if (!name || name.toLowerCase() === 'parameter') continue
149 params.push({ name, description: cells[3] ?? '' })
150 }
151 if (params.length === 0) {
152 throw new Error(`${DASHSCOPE_COMPAT_URL}: parsed 0 request parameters`)
153 }
154 return params
156​
157function maxTokensField(names: Set<string>): ChatRequestMap['maxTokensField'] {
158 const max = names.has('max_tokens')
159 const completion = names.has('max_completion_tokens')
160 if (max && !completion) return 'max_tokens'
161 if (completion && !max) return 'max_completion_tokens'
162 if (!max && !completion) {
163 throw new Error(
164 `${DASHSCOPE_COMPAT_URL}: request table names no max-token field`,
165 )
166 }
167 return null
169​
170/** `Valid roles: system, user, assistant` → developer is not one of them. */
171function developerRole(messages: string | undefined): boolean | null {
172 const listed = messages?.match(/valid roles:\s*([^.]+)/i)?.[1]
173 if (!listed) return null
174 const roles = listed
175 .split(/,| and /)
176 .map((role) => role.trim().toLowerCase())
177 .filter((role) => role !== '')
178 if (roles.length === 0) return null
179 return roles.includes('developer')
181​
182export async function parseDashscopeCompat(
183 markdown: string,
184): Promise<DashscopeCompatFacts> {
185 assertDashscopeMarkdown(markdown, DASHSCOPE_COMPAT_URL)
186 const params = parameters(requestSection(markdown))
187 const names = new Set(params.map((param) => param.name))
188 const messages = params.find((param) => param.name === 'messages')
189 const flags = params
190 .filter(
191 (param) =>
192 PARAM_TO_FLAG[param.name] !== undefined &&
193 !RESTRICTED.test(param.description),
194 )
195 .map((param) => PARAM_TO_FLAG[param.name] ?? param.name)
196 return {
197 requestMap: {
198 thinking: null,
199 maxTokensField: maxTokensField(names),
200 developerRole: developerRole(messages?.description),
201 replayReasoningContent: null,
202 store: null,
203 strictTools: null,
204 sessionAffinity: null,
205 cacheControl: null,
206 toolStream: null,
207 reasoningEffort: null,
208 },
209 flags,
210 scope: parseDashscopeCompatScope(markdown),
211 sourceHash: await sha256Text(markdown),
212 }