Open History to see the last commit
1/** Model Studio's own model scopes; code samples never seed the catalog. */
2import { isCapabilityMap } from '#/lib/capabilities.ts'
3
4import {
5 DASHSCOPE_DOCS_INIT,
6 dashscopeDocText,
7} from './dashscope-model-limits.ts'
8import { cachedDocs } from './model-facts.ts'
9import { fetchText, sha256Text } from './types.ts'
10import type { ModelInfo } from './types.ts'
11
12export const DASHSCOPE_THINKING_URL =
13 'https://www.alibabacloud.com/help/en/model-studio/deep-thinking.md'
14interface ThinkingDoc {
15 models: Record<
16 string,
17 { hybrid: boolean; budget?: boolean; mandatory?: boolean | null }
18 >
19 /** Null when the page states no `preserve_thinking` model list. */
20 replay: Array<string> | null
21 /** False when the page states no `thinking_budget` applicability. */
22 budgetScope: boolean
23 hash: string
24}
25function ids(text: string): Array<string> {
26 return [
27 ...new Set(text.match(/\b[a-zA-Z][\w.]*(?:\/[\w.]+)?-[\w.-]+\b/g) ?? []),
28 ]
29}
30export function parseDashscopeThinking(
31 markdown: string,
32): Omit<ThinkingDoc, 'hash'> {
33 const scope = markdown.match(
34 /^## Supported Models[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m,
35 )?.[1]
36 if (
37 !scope ||
38 !/thinking.mode only|only thinking mode|thinking-only mode|hybrid thinking mode/i.test(
39 scope,
40 )
41 )
42 throw new Error('dashscope thinking: missing native modes')
43 const prose = markdown.replace(/```[\s\S]*?```/g, '')
44 const budgetLine = prose
45 .split('\n')
46 .find((line) => /`thinking_budget`[^\n]*Applicable to /.test(line))
47 if (
48 budgetLine &&
49 /\b(?:not|never|cannot|unsupported|except)\b|\b(?:can't|don't|doesn't|isn't)\b/i.test(
50 budgetLine,
51 )
52 )
53 throw new Error('dashscope thinking: negated native budget declaration')
54 // Until 2026-10-27 a tip named the `thinking_budget` families; the page
55 // now points at the Chat Completions reference instead. No tip states no
56 // budget scope: thinking-only models then get no reasoning mode.
57 const budgetScope = budgetLine?.match(
58 /Applicable to ([^\n]+?) series models\./,
59 )?.[1]
60 if (budgetLine && !budgetScope)
61 throw new Error('dashscope thinking: missing native thinking-budget scope')
62 const budgetFamilies = (budgetScope ?? '')
63 .split(/,|\band\b/)
64 .map((value) => value.trim().toLowerCase())
65 .filter(Boolean)
66 if (
67 (budgetScope && !budgetFamilies.length) ||
68 budgetFamilies.some((value) => !/^[a-z0-9.-]+$/.test(value))
69 )
70 throw new Error('dashscope thinking: malformed native budget families')
71 const models: ThinkingDoc['models'] = {}
72 for (const raw of scope.split('\n')) {
73 const line = raw.replace(/<[^>]+>/g, '').trim()
74 const colon = line.lastIndexOf(':')
75 if (colon < 0) continue
76 const names = ids(
77 (line.slice(colon + 1).split(/\. (?=[A-Z])/)[0] ?? '').replace(
78 /\[[^\]]*\]\([^)]*\)/g,
79 '',
80 ),
81 )
82 if (
83 names.length &&
84 /thinking.mode only|only thinking mode|thinking-only mode/i.test(line) &&
85 /\b(?:not|never|no|unsupported)\b|\b(?:can't|don't|doesn't|isn't)\b/i.test(
86 line,
87 )
88 )
89 throw new Error(
90 'dashscope thinking: negated native model mode declaration',
91 )
92 for (const id of names) {
93 // The supported-model section includes thinking models whose control
94 // details are absent. Their capability is still independently stated.
95 const hybrid = /hybrid thinking mode/i.test(line)
96 const previous = models[id]
97 if (previous && previous.hybrid !== hybrid)
98 throw new Error(`dashscope thinking: conflicting mode for ${id}`)
99 const only =
100 /thinking.mode only|only thinking mode|thinking-only mode|only thinking mode supported/i.test(
101 line,
102 )
103 const budget = budgetFamilies.some(
104 (family) =>
105 id.toLowerCase() === family ||
106 id.toLowerCase().startsWith(family + '-') ||
107 id.toLowerCase().startsWith(family + '.') ||
108 id.toLowerCase().startsWith(family + '/'),
109 )
110 models[id] = {
111 hybrid,
112 ...(budget ? { budget: true, mandatory: only ? true : null } : {}),
113 }
114 }
115 }
116 if (!Object.keys(models).length)
117 throw new Error('dashscope thinking: parsed zero native model IDs')
118 // The same date dropped the `preserve_thinking` model list; without it
119 // the page states no replay scope.
120 const replayBlock = markdown.match(
121 /`preserve_thinking`This Parameter only supports ([^\n]+)/,
122 )?.[1]
123 if (
124 replayBlock &&
125 !/client needs to provide historical assistant messages/i.test(markdown)
126 )
127 throw new Error('dashscope thinking: unreadable native replay scope')
128 const replay = replayBlock ? ids(replayBlock) : null
129 if (replay && !replay.length)
130 throw new Error('dashscope thinking: empty replay scope')
131 return { models, replay, budgetScope: budgetScope !== undefined }
132}
133export async function dashscopeThinking(
134 kv?: KVNamespace,
135 cached: typeof cachedDocs = cachedDocs,
136) {
137 return cached(kv, `${DASHSCOPE_THINKING_URL}#model-thinking`, async () => {
138 const markdown = dashscopeDocText(
139 await fetchText(DASHSCOPE_THINKING_URL, DASHSCOPE_DOCS_INIT),
140 'dashscope thinking',
141 )
142 return {
143 ...parseDashscopeThinking(markdown),
144 hash: await sha256Text(markdown),
145 }
146 })
147}
148export function applyDashscopeThinking(
149 model: ModelInfo,
150 doc: ThinkingDoc,
151): ModelInfo {
152 if (model.activity !== 'chat') return model
153 const stated = doc.models[model.rawId]
154 const replay = doc.replay?.includes(model.rawId) ?? false
155 // A scope the page no longer states keeps the stored value: the budget
156 // mode of a thinking-only row, and every chat row's request map (the
157 // replay flag lives in it).
158 const kept: ModelInfo['absent'] = {
159 ...(doc.replay === null ? { requestMap: 'unavailable' as const } : {}),
160 ...(stated && !stated.hybrid && !stated.budget && !doc.budgetScope
161 ? { reasoning: 'unavailable' as const }
162 : {}),
163 }
164 const absent = Object.keys(kept).length
165 ? { absent: { ...model.absent, ...kept } }
166 : {}
167 if (!stated && !replay) return { ...model, ...absent }
168 if (replay && model.requestMap?.replayReasoningContent === false)
169 throw new Error(
170 'dashscope: native replay contradicts existing explicit rejection',
171 )
172 const nativeReasoning = !!stated
173 if (
174 nativeReasoning &&
175 (model.unsupportedCapabilities?.includes('reasoning') ||
176 (isCapabilityMap(model.capabilities) &&
177 model.capabilities.reasoning === false))
178 ) {
179 throw new Error(
180 'dashscope: native reasoning contradicts existing explicit rejection',
181 )
182 }
183 const capabilities = isCapabilityMap(model.capabilities)
184 ? { ...model.capabilities, reasoning: true }
185 : [
186 ...new Set([
187 ...(Array.isArray(model.capabilities)
188 ? (model.capabilities as Array<string>)
189 : []),
190 'reasoning',
191 ]),
192 ]
193 const source = (path: string) => ({
194 derivation: 'docs-derived' as const,
195 sourceUrl: DASHSCOPE_THINKING_URL,
196 sourceHash: doc.hash,
197 path,
198 })
199 return {
200 ...model,
201 ...absent,
202 ...(stated
203 ? {
204 capabilities,
205 ...(stated.hybrid
206 ? { reasoning: { mode: 'toggle' as const, mandatory: false } }
207 : stated.budget
208 ? {
209 reasoning: {
210 mode: 'budget' as const,
211 mandatory: stated.mandatory ?? null,
212 },
213 }
214 : {}),
215 }
216 : {}),
217 ...(replay && model.requestMap
218 ? { requestMap: { ...model.requestMap, replayReasoningContent: true } }
219 : {}),
220 factSources: {
221 ...model.factSources,
222 ...(stated
223 ? {
224 capabilities: {
225 ...model.factSources?.capabilities,
226 reasoning: source('Supported models'),
227 },
228 ...(stated.hybrid
229 ? { reasoning: source('Supported models.Hybrid thinking mode') }
230 : stated.budget
231 ? {
232 reasoning: source(
233 'Supported models.Thinking-only mode; Limit Thinking Length.thinking_budget applicability',
234 ),
235 }
236 : {}),
237 }
238 : {}),
239 ...(replay && model.requestMap
240 ? {
241 requestMapFields: {
242 ...model.factSources?.requestMapFields,
243 replayReasoningContent: source(
244 'Pass Thinking Process.preserve_thinking',
245 ),
246 },
247 }
248 : {}),
249 },
250 }
251}