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

dashscope-compat.ts

212 lines6.6 KB

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