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

dashscope.ts

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