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

dashscope-thinking.ts

222 lines7.1 KB

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