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

dashscope.ts

548 lines16.8 KB

1/**
2 * Alibaba Cloud Model Studio (DashScope) — OpenAI-compatible mode.
3 * No published OpenAPI; schemas are generated from OpenAI's spec.
4 * Intl host; China is dashscope.aliyuncs.com.
5 *
6 * The compatible-mode models list is id-only. Activity, modalities, and
7 * prices come from GET /api/v1/models (issue #109).
8 */
9import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
10import type { RateCard, TokenRateTier } from '@modelschemas/rate-card'
11​
12import {
13 DASHSCOPE_COMPAT_SCOPE,
14 DASHSCOPE_COMPAT_URL,
15 dashscopeCompatCovers,
16 parseDashscopeCompat,
17 parseDashscopeCompatScope,
18} from '../dashscope-compat.ts'
19import type { DashscopeCompatFacts } from '../dashscope-compat.ts'
20import {
21 dashscopeModelPageUrl,
22 loadDashscopeModelLimits,
23} from '../dashscope-model-limits.ts'
24import type { DashscopeLimitsDoc } from '../dashscope-model-limits.ts'
25import {
26 dashscopeThinking,
27 applyDashscopeThinking,
28} from '../dashscope-thinking.ts'
29import { docsReport, docsRun, tryDocs } from '../model-facts.ts'
30import {
31 compatGenerationEndpointId,
32 dashscopeModelActivity,
33} from '../model-meta.ts'
34import {
35 classifyOpenAiCompat,
36 fetchOpenAiCompatibleSpec,
37} from '../openai-compat.ts'
38import type { OpenAiCompatPath } from '../openai-compat.ts'
39import { fetchJson, fetchText, sha256Text, skippedResult } from '../types.ts'
40import type {
41 FactSource,
42 ListModelsResult,
43 ModelFactSources,
44 ModelInfo,
45 ProviderConfig,
46 ProviderSecrets,
47 SpecFetchResult,
48} from '../types.ts'
49​
50const SPEC_SOURCE_URL =
51 'https://www.alibabacloud.com/help/en/model-studio/compatibility-of-openai-with-dashscope'
52const MODELS_URL = 'https://dashscope-intl.aliyuncs.com/api/v1/models'
53const SERVER_URL = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
54​
55/**
56 * alibabacloud.com answered the Worker's bare fetch with an HTML page from
57 * 2026-10-07 (issue #256); workerd sends no User-Agent or Accept. These
58 * match a browser's fetch of the `.md` URL.
59 */
60const DOCS_INIT: RequestInit = {
61 headers: {
62 Accept: 'text/markdown,text/plain,*/*',
63 'User-Agent':
64 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
65 },
67​
68const INCLUDE: ReadonlyArray<OpenAiCompatPath> = [
69 '/chat/completions',
70 '/embeddings',
71 '/images/generations',
72 '/audio/speech',
73 '/audio/transcriptions',
75​
76async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
77 const { spec, url, hash } = await fetchOpenAiCompatibleSpec({
78 title: 'Alibaba Cloud Model Studio',
79 serverUrl: SERVER_URL,
80 include: INCLUDE,
81 })
82 return {
83 specs: [spec],
84 sources: [{ url, hash }],
85 outputStrategy: 'post-200',
86 }
88​
89const TOKEN_LEVERS: Record<string, string> = {
90 input_token: 'input_tokens',
91 output_token: 'output_tokens',
92 omni_input_token: 'input_tokens',
93 omni_output_token: 'output_tokens',
94 input_token_cache: 'cache_read_tokens',
95 omni_input_token_cache: 'cache_read_tokens',
96 input_token_cache_read: 'cache_read_tokens',
97 input_token_cache_creation_5m: 'cache_write_tokens',
98 input_token_cache_creation_1h: 'cache_write_1h_tokens',
100​
101/**
102 * Thinking-only rows publish `thinking_*` and no plain token type. A row
103 * that publishes both keeps the plain type: that is the non-thinking price,
104 * and the thinking price is a different mode.
105 */
106const THINKING_ALIAS: Record<string, string> = {
107 thinking_input_token: 'input_token',
108 thinking_output_token: 'output_token',
109 thinking_input_token_cache: 'input_token_cache',
110 thinking_input_token_cache_creation_5m: 'input_token_cache_creation_5m',
111 thinking_input_token_cache_read: 'input_token_cache_read',
113​
114const FEATURES: Record<string, Array<string>> = {
115 'function-calling': ['tools'],
116 'structured-outputs': ['structured_outputs', 'response_format'],
118​
119interface DashscopePrice {
120 type?: string
121 price?: string
122 price_unit?: string
123 time_band?: string | null
125​
126interface DashscopeRange {
127 range_name?: string
128 prices?: Array<DashscopePrice>
130​
131export interface DashscopeListedModel {
132 model?: string
133 name?: string
134 capabilities?: Array<string>
135 features?: Array<string>
136 prices?: Array<DashscopeRange>
137 published_time?: string | null
138 inference_metadata?: {
139 request_modality?: Array<string>
140 response_modality?: Array<string>
141 }
142 model_info?: {
143 context_window?: number | null
144 max_output_tokens?: number | null
145 /** Published response cap when `max_output_tokens` is null. */
146 reasoning_max_output_tokens?: number | null
147 }
149​
150function modalityList(values: Array<string> | undefined): Array<string> {
151 return (values ?? []).map((value) => value.toLowerCase())
153​
154/**
155 * Lower bound of a prompt tier. `Default` and an upper bound only
156 * (`Input<=32k`) are the base. `32k<Input<=128k` starts above 32k.
157 * `256k<Input<=1m` starts above 256k. An unrecognized name is null,
158 * and the card is dropped.
159 */
160export function promptFloor(range: string): number | null {
161 const text = range.trim()
162 if (text === '' || /^default$/i.test(text)) return 0
163 const head = text.split(/[<≤]/, 1)[0] ?? ''
164 const bound = head.match(/(\d+(?:\.\d+)?)\s*([km])?\s*$/i)
165 if (bound?.[1]) {
166 const amount = Number(bound[1])
167 const unit = bound[2]?.toLowerCase()
168 if (!Number.isFinite(amount)) return null
169 return amount * (unit === 'm' ? 1_000_000 : unit === 'k' ? 1_000 : 1)
170 }
171 if (/[<≤=]/.test(text)) return 0
172 return null
174​
175function positive(price: string | undefined): number | null {
176 if (!price || !/^\d+(?:\.\d+)?$/.test(price)) return null
177 const value = Number(price)
178 return value > 0 ? value : null
180​
181function standardBand(items: Array<DashscopePrice>): Array<DashscopePrice> {
182 const bands = new Set(items.map((item) => item.time_band ?? null))
183 if (bands.size <= 1) return items
184 return items.filter(
185 (item) => item.time_band == null || item.time_band === 'standard',
186 )
188​
189function canonicalType(type: string, present: Set<string>): string | undefined {
190 if (TOKEN_LEVERS[type]) return type
191 const alias = THINKING_ALIAS[type]
192 if (!alias || present.has(alias)) return undefined
193 return alias
195​
196/**
197 * Token ranges become a token card. A per-image quote becomes a unit card.
198 * An unparsed range, a mixed unit, or an all-zero quote stays null.
199 * Explicit cache read is omitted when implicit cache is also quoted.
200 * Text, vision, and audio prices that are not one input rate stay null.
201 */
202export async function dashscopeListedCard(
203 ranges: Array<DashscopeRange> | undefined,
204): Promise<RateCard | null> {
205 if (!ranges || ranges.length === 0) return null
206 const parsed: Array<{ floor: number; prices: Array<DashscopePrice> }> = []
207 for (const range of ranges) {
208 const floor = promptFloor(range.range_name ?? 'Default')
209 if (floor === null) return null
210 parsed.push({ floor, prices: standardBand(range.prices ?? []) })
211 }
212 const units = new Set(
213 parsed.flatMap((range) =>
214 range.prices.map((price) => price.price_unit ?? ''),
215 ),
216 )
217 const source = {
218 url: MODELS_URL,
219 hash: await sha256Text(JSON.stringify(ranges)),
220 extractedAt: new Date().toISOString(),
221 }
222 if ([...units].every((unit) => /per image/i.test(unit))) {
223 const image = positive(parsed[0]?.prices[0]?.price)
224 if (parsed.length !== 1 || image === null) return null
225 if (parsed[0]?.prices[0]?.type !== 'image_number') return null
226 return compileUnitCard(
227 {
228 quantity: { param: 'images', bound: 'usage' },
229 rates: image,
230 },
231 source,
232 )
233 }
234 if ([...units].some((unit) => !/per (1m|million) tokens/i.test(unit))) {
235 return null
236 }
237​
238 const rateMap = (
239 prices: Array<DashscopePrice>,
240 ): Record<string, number> | null => {
241 const present = new Set(
242 prices.flatMap((price) => (price.type ? [price.type] : [])),
243 )
244 const hasImplicit = prices.some((price) => {
245 const type = price.type ? canonicalType(price.type, present) : undefined
246 return type === 'input_token_cache' || type === 'omni_input_token_cache'
247 })
248 const rates: Record<string, number> = {}
249 for (const price of prices) {
250 const type = price.type ? canonicalType(price.type, present) : undefined
251 if (!type || (hasImplicit && type === 'input_token_cache_read')) continue
252 const lever = TOKEN_LEVERS[type]
253 const amount = positive(price.price)
254 if (!lever || amount === null) continue
255 if (lever in rates && rates[lever] !== amount / 1e6) return null
256 rates[lever] = amount / 1e6
257 }
258 return rates
259 }
260​
261 const base = parsed.find((range) => range.floor === 0)
262 if (!base) return null
263 const baseRates = rateMap(base.prices)
264 if (!baseRates) return null
265 const tiers: Array<TokenRateTier> = []
266 for (const range of parsed) {
267 if (range.floor === 0) continue
268 const rates = rateMap(range.prices)
269 if (!rates) return null
270 tiers.push({ minPromptTokens: range.floor, rates })
271 }
272 return compileTokenCard(baseRates, tiers, source)
274​
275function releasedAt(value: string | null | undefined): number | null {
276 if (!value) return null
277 const ms = Date.parse(value.replace(' ', 'T') + 'Z')
278 return Number.isNaN(ms) ? null : Math.floor(ms / 1000)
280​
281function listingSource(path: string): FactSource {
282 return { derivation: 'listing', sourceUrl: MODELS_URL, path }
284​
285function unique(flags: Array<string>): Array<string> {
286 return [...new Set(flags)]
288​
289export async function dashscopeListedModel(
290 row: DashscopeListedModel,
291): Promise<ModelInfo | null> {
292 if (!row.model) return null
293 const activity = dashscopeModelActivity(row)
294 const capabilities = (row.features ?? []).flatMap(
295 (feature) => FEATURES[feature] ?? [],
296 )
297 const input = modalityList(row.inference_metadata?.request_modality)
298 const output = modalityList(row.inference_metadata?.response_modality)
299 const info = row.model_info
300 const maxFromOutput = info?.max_output_tokens ?? null
301 const maxOutput = maxFromOutput ?? info?.reasoning_max_output_tokens ?? null
302 const contextWindow = info?.context_window ?? null
303 const chatFeatures = activity === 'chat' && Array.isArray(row.features)
304 const model: ModelInfo = {
305 rawId: row.model,
306 displayName: row.name ?? null,
307 activity,
308 contextWindow,
309 maxOutput,
310 releasedAt: releasedAt(row.published_time),
311 ...(input.length > 0 || output.length > 0
312 ? { modalities: { input, output } }
313 : {}),
314 ...(chatFeatures || capabilities.length > 0
315 ? { capabilities, ...(chatFeatures ? { exactCapabilities: true } : {}) }
316 : {}),
317 }
318 const card = await dashscopeListedCard(row.prices)
319 if (card) model.pricing = card
320 const sources: ModelFactSources = {}
321 if (contextWindow != null) {
322 sources.contextWindow = listingSource('model_info.context_window')
323 }
324 if (maxOutput != null) {
325 sources.maxOutput = listingSource(
326 maxFromOutput != null
327 ? 'model_info.max_output_tokens'
328 : 'model_info.reasoning_max_output_tokens',
329 )
330 }
331 if (model.modalities != null) {
332 sources.modalities = listingSource('inference_metadata')
333 }
334 if (card) sources.pricing = listingSource('prices')
335 if (capabilities.length > 0) {
336 sources.capabilities = Object.fromEntries(
337 capabilities.map((flag) => [flag, listingSource(`features.${flag}`)]),
338 )
339 }
340 if (
341 sources.contextWindow ||
342 sources.maxOutput ||
343 sources.modalities ||
344 sources.pricing ||
345 sources.capabilities
346 ) {
347 model.factSources = sources
348 }
349 return model
351​
352function withCompat(
353 model: ModelInfo,
354 compat: DashscopeCompatFacts | null,
355): ModelInfo {
356 if (model.activity !== 'chat') return model
357 if (compat && !dashscopeCompatCovers(model.rawId, compat.scope)) return model
358 if (!compat) {
359 return {
360 ...model,
361 absent: { ...model.absent, requestMap: 'unavailable' },
362 }
363 }
364 const prior = Array.isArray(model.capabilities) ? model.capabilities : []
365 const flags = unique([
366 ...prior.filter((flag): flag is string => typeof flag === 'string'),
367 ...compat.flags,
368 ])
369 const compatSource = (flag: string): FactSource => ({
370 derivation: 'docs-extracted',
371 sourceUrl: DASHSCOPE_COMPAT_URL,
372 sourceHash: compat.sourceHash,
373 path: `parameters.${flag}`,
374 })
375 const sources: ModelFactSources = { ...model.factSources }
376 sources.capabilities = {
377 ...sources.capabilities,
378 ...Object.fromEntries(
379 compat.flags.map((flag) => [flag, compatSource(flag)]),
380 ),
381 }
382 return {
383 ...model,
384 requestMap: compat.requestMap,
385 capabilities: flags,
386 // This shared request table does not enumerate model-specific reasoning
387 // capabilities. Omitted flags remain unknown, not a sourced rejection.
388 exactCapabilities: false,
389 factSources: sources,
390 }
392​
393function needsModelPage(model: ModelInfo): boolean {
394 return (
395 model.activity === 'chat' &&
396 (model.contextWindow == null || model.maxOutput == null)
397 )
399​
400function applyModelLimits(
401 model: ModelInfo,
402 url: string,
403 doc: DashscopeLimitsDoc | null,
404): ModelInfo {
405 if (!needsModelPage(model)) return model
406 const limits = doc?.models[model.rawId]
407 const next: ModelInfo = { ...model }
408 const sources: ModelFactSources = { ...model.factSources }
409 const absent = { ...model.absent }
410 const source = (path: string): FactSource => ({
411 derivation: 'docs-extracted',
412 sourceUrl: url,
413 ...(doc ? { sourceHash: doc.sourceHash } : {}),
414 path,
415 })
416 if (model.contextWindow == null) {
417 const value = limits?.contextWindow
418 if (value != null) {
419 next.contextWindow = value
420 sources.contextWindow = source('Context limits.Context Window')
421 } else if (!doc) {
422 absent.contextWindow = 'unavailable'
423 }
424 }
425 if (model.maxOutput == null) {
426 const value = limits?.maxOutput
427 if (value != null) {
428 next.maxOutput = value
429 sources.maxOutput = source('Context limits.Max Output')
430 } else if (!doc) {
431 absent.maxOutput = 'unavailable'
432 }
433 }
434 if (
435 sources.contextWindow ||
436 sources.maxOutput ||
437 sources.modalities ||
438 sources.pricing ||
439 sources.capabilities
440 ) {
441 next.factSources = sources
442 }
443 if (Object.keys(absent).length > 0) next.absent = absent
444 return next
446​
447async function listModels(
448 env: ProviderSecrets,
449 kv?: KVNamespace,
450): Promise<ListModelsResult> {
451 const key = env.DASHSCOPE_API_KEY
452 if (!key) {
453 return { models: [], ...skippedResult('dashscope', 'DASHSCOPE_API_KEY') }
454 }
455 const run = docsRun()
456 const listed: Array<ModelInfo> = []
457 let page = 1
458 let total = Infinity
459 while (listed.length < total && page < 20) {
460 const body = (await fetchJson(
461 `${MODELS_URL}?page_no=${String(page)}&page_size=100&language=en-US`,
462 { headers: { Authorization: `Bearer ${key}` } },
463 )) as { output?: { total?: number; models?: Array<DashscopeListedModel> } }
464 const batch = body.output?.models ?? []
465 if (typeof body.output?.total === 'number') total = body.output.total
466 if (batch.length === 0) break
467 for (const row of batch) {
468 const model = await dashscopeListedModel(row)
469 if (model) listed.push(model)
470 }
471 page += 1
472 }
473 const thinking = listed.some((model) => model.activity === 'chat')
474 ? await dashscopeThinking(kv)
475 : null
476 const compat = await tryDocs(run, DASHSCOPE_COMPAT_URL, (cached) =>
477 cached(kv, DASHSCOPE_COMPAT_URL, async () =>
478 parseDashscopeCompat(await fetchText(DASHSCOPE_COMPAT_URL, DOCS_INIT)),
479 ),
480 )
481 const limitUrls = [
482 ...new Set(
483 listed
484 .filter(needsModelPage)
485 .map((model) => dashscopeModelPageUrl(model.rawId)),
486 ),
487 ]
488 const limitDocs = new Map<string, DashscopeLimitsDoc | null>()
489 for (const url of limitUrls) {
490 limitDocs.set(
491 url,
492 await tryDocs(run, url, (cached) =>
493 cached(kv, url, async () =>
494 loadDashscopeModelLimits(await fetchText(url, DOCS_INIT)),
495 ),
496 ),
497 )
498 }
499 return {
500 models: listed.map((model) => {
501 const configured = withCompat(
502 needsModelPage(model)
503 ? applyModelLimits(
504 model,
505 dashscopeModelPageUrl(model.rawId),
506 limitDocs.get(dashscopeModelPageUrl(model.rawId)) ?? null,
507 )
508 : model,
509 compat,
510 )
511 return thinking
512 ? applyDashscopeThinking(configured, thinking)
513 : configured
514 }),
515 docsFailures: docsReport(run),
516 }
518​
519export const provider: ProviderConfig = {
520 id: 'dashscope',
521 displayName: 'Alibaba Cloud Model Studio',
522 authEnvVar: 'DASHSCOPE_API_KEY',
523 specSourceUrl: SPEC_SOURCE_URL,
524 modelsEndpoint: MODELS_URL,
525 defaultDerivation: 'generated',
526 fetchSpec,
527 listModels,
528 classify: classifyOpenAiCompat,
529 generationEndpointId: ({ rawId, activity }) => {
530 if (activity === 'video') return null
531 if (
532 activity === 'chat' &&
533 !dashscopeCompatCovers(
534 rawId,
535 parseDashscopeCompatScope(DASHSCOPE_COMPAT_SCOPE),
536 )
537 ) {
538 return null
539 }
540 return compatGenerationEndpointId(
541 activity,
542 '',
543 activity === 'audio' && /asr|transcri/i.test(rawId)
544 ? 'transcriptions'
545 : 'speech',
546 )
547 },