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

dashscope-thinking.ts

230 lines7.3 KB

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 assertDashscopeMarkdown,
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 replay: Array<string>
20 hash: string
22function ids(text: string): Array<string> {
23 return [
24 ...new Set(text.match(/\b[a-zA-Z][\w.]*(?:\/[\w.]+)?-[\w.-]+\b/g) ?? []),
25 ]
27export function parseDashscopeThinking(
28 markdown: string,
29): Omit<ThinkingDoc, 'hash'> {
30 const scope = markdown.match(
31 /^## Supported Models[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m,
32 )?.[1]
33 if (
34 !scope ||
35 !/thinking.mode only|only thinking mode|thinking-only mode|hybrid thinking mode/i.test(
36 scope,
37 )
38 )
39 throw new Error('dashscope thinking: missing native modes')
40 const prose = markdown.replace(/```[\s\S]*?```/g, '')
41 const budgetLine = prose
42 .split('\n')
43 .find((line) => /`thinking_budget`[^\n]*Applicable to /.test(line))
44 if (
45 budgetLine &&
46 /\b(?:not|never|cannot|unsupported|except)\b|\b(?:can't|don't|doesn't|isn't)\b/i.test(
47 budgetLine,
48 )
49 )
50 throw new Error('dashscope thinking: negated native budget declaration')
51 const budgetScope = budgetLine?.match(
52 /Applicable to ([^\n]+?) series models\./,
53 )?.[1]
54 if (!budgetScope)
55 throw new Error('dashscope thinking: missing native thinking-budget scope')
56 const budgetFamilies = budgetScope
57 .split(/,|\band\b/)
58 .map((value) => value.trim().toLowerCase())
59 .filter(Boolean)
60 if (
61 !budgetFamilies.length ||
62 budgetFamilies.some((value) => !/^[a-z0-9.-]+$/.test(value))
63 )
64 throw new Error('dashscope thinking: malformed native budget families')
65 const models: ThinkingDoc['models'] = {}
66 for (const raw of scope.split('\n')) {
67 const line = raw.replace(/<[^>]+>/g, '').trim()
68 const colon = line.lastIndexOf(':')
69 if (colon < 0) continue
70 const names = ids(
71 (line.slice(colon + 1).split(/\. (?=[A-Z])/)[0] ?? '').replace(
72 /\[[^\]]*\]\([^)]*\)/g,
73 '',
74 ),
75 )
76 if (
77 names.length &&
78 /thinking.mode only|only thinking mode|thinking-only mode/i.test(line) &&
79 /\b(?:not|never|no|unsupported)\b|\b(?:can't|don't|doesn't|isn't)\b/i.test(
80 line,
81 )
82 )
83 throw new Error(
84 'dashscope thinking: negated native model mode declaration',
85 )
86 for (const id of names) {
87 // The supported-model section includes thinking models whose control
88 // details are absent. Their capability is still independently stated.
89 const hybrid = /hybrid thinking mode/i.test(line)
90 const previous = models[id]
91 if (previous && previous.hybrid !== hybrid)
92 throw new Error(`dashscope thinking: conflicting mode for ${id}`)
93 const only =
94 /thinking.mode only|only thinking mode|thinking-only mode|only thinking mode supported/i.test(
95 line,
96 )
97 const budget = budgetFamilies.some(
98 (family) =>
99 id.toLowerCase() === family ||
100 id.toLowerCase().startsWith(family + '-') ||
101 id.toLowerCase().startsWith(family + '.') ||
102 id.toLowerCase().startsWith(family + '/'),
103 )
104 models[id] = {
105 hybrid,
106 ...(budget ? { budget: true, mandatory: only ? true : null } : {}),
107 }
108 }
109 }
110 if (!Object.keys(models).length)
111 throw new Error('dashscope thinking: parsed zero native model IDs')
112 const replayBlock = markdown.match(
113 /`preserve_thinking`This Parameter only supports ([^\n]+)/,
114 )?.[1]
115 if (
116 !replayBlock ||
117 !/client needs to provide historical assistant messages/i.test(markdown)
118 )
119 throw new Error('dashscope thinking: unreadable native replay scope')
120 const replay = ids(replayBlock)
121 if (!replay.length) throw new Error('dashscope thinking: empty replay scope')
122 return { models, replay }
124export async function dashscopeThinking(
125 kv?: KVNamespace,
126 cached: typeof cachedDocs = cachedDocs,
127) {
128 return cached(kv, `${DASHSCOPE_THINKING_URL}#model-thinking`, async () => {
129 const markdown = await fetchText(
130 DASHSCOPE_THINKING_URL,
131 DASHSCOPE_DOCS_INIT,
132 )
133 assertDashscopeMarkdown(markdown, 'dashscope thinking')
134 return {
135 ...parseDashscopeThinking(markdown),
136 hash: await sha256Text(markdown),
137 }
138 })
140export function applyDashscopeThinking(
141 model: ModelInfo,
142 doc: ThinkingDoc,
143): ModelInfo {
144 if (model.activity !== 'chat') return model
145 const stated = doc.models[model.rawId]
146 const replay = doc.replay.includes(model.rawId)
147 if (!stated && !replay) return model
148 if (replay && model.requestMap?.replayReasoningContent === false)
149 throw new Error(
150 'dashscope: native replay contradicts existing explicit rejection',
151 )
152 const nativeReasoning = !!stated
153 if (
154 nativeReasoning &&
155 (model.unsupportedCapabilities?.includes('reasoning') ||
156 (isCapabilityMap(model.capabilities) &&
157 model.capabilities.reasoning === false))
158 ) {
159 throw new Error(
160 'dashscope: native reasoning contradicts existing explicit rejection',
161 )
162 }
163 const capabilities = isCapabilityMap(model.capabilities)
164 ? { ...model.capabilities, reasoning: true }
165 : [
166 ...new Set([
167 ...(Array.isArray(model.capabilities)
168 ? (model.capabilities as Array<string>)
169 : []),
170 'reasoning',
171 ]),
172 ]
173 const source = (path: string) => ({
174 derivation: 'docs-derived' as const,
175 sourceUrl: DASHSCOPE_THINKING_URL,
176 sourceHash: doc.hash,
177 path,
178 })
179 return {
180 ...model,
181 ...(stated
182 ? {
183 capabilities,
184 ...(stated.hybrid
185 ? { reasoning: { mode: 'toggle' as const, mandatory: false } }
186 : stated.budget
187 ? {
188 reasoning: {
189 mode: 'budget' as const,
190 mandatory: stated.mandatory ?? null,
191 },
192 }
193 : {}),
194 }
195 : {}),
196 ...(replay && model.requestMap
197 ? { requestMap: { ...model.requestMap, replayReasoningContent: true } }
198 : {}),
199 factSources: {
200 ...model.factSources,
201 ...(stated
202 ? {
203 capabilities: {
204 ...model.factSources?.capabilities,
205 reasoning: source('Supported models'),
206 },
207 ...(stated.hybrid
208 ? { reasoning: source('Supported models.Hybrid thinking mode') }
209 : stated.budget
210 ? {
211 reasoning: source(
212 'Supported models.Thinking-only mode; Limit Thinking Length.thinking_budget applicability',
213 ),
214 }
215 : {}),
216 }
217 : {}),
218 ...(replay && model.requestMap
219 ? {
220 requestMapFields: {
221 ...model.factSources?.requestMapFields,
222 replayReasoningContent: source(
223 'Pass Thinking Process.preserve_thinking',
224 ),
225 },
226 }
227 : {}),
228 },
229 }