Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import nativeDocs from '../fixtures/native-reasoning-docs.json'
3import { DASHSCOPE_THINKING_URL } from '../dashscope-thinking.ts'
4
5import {
6 DASHSCOPE_COMPAT_SCOPE,
7 DASHSCOPE_COMPAT_URL,
8} from '../dashscope-compat.ts'
9import { dashscopeModelPageUrl } from '../dashscope-model-limits.ts'
10import { OPENAI_OPENAPI_URL } from '../openai-compat.ts'
11import {
12 dashscopeListedCard,
13 dashscopeListedModel,
14 promptFloor,
15 provider,
16} from './dashscope.ts'
17
18const OPENAI_FIXTURE = JSON.stringify({
19 openapi: '3.1.0',
20 info: { title: 'OpenAI API', version: '2.3.0' },
21 servers: [{ url: 'https://api.openai.com/v1' }],
22 paths: {
23 '/chat/completions': { post: { operationId: 'createChatCompletion' } },
24 '/embeddings': { post: { operationId: 'createEmbedding' } },
25 '/images/generations': { post: { operationId: 'createImage' } },
26 '/audio/speech': { post: { operationId: 'createSpeech' } },
27 '/audio/transcriptions': { post: { operationId: 'createTranscription' } },
28 '/files': { get: { operationId: 'listFiles' } },
29 },
30})
31
32function withStubbedFetch<T>(
33 handler: (url: string, init?: RequestInit) => Response,
34 run: () => Promise<T>,
35): Promise<{ result: T; calls: Array<{ url: string; auth: string | null }> }> {
36 const original = globalThis.fetch
37 const calls: Array<{ url: string; auth: string | null }> = []
38 globalThis.fetch = ((url: string, init?: RequestInit) => {
39 calls.push({
40 url: String(url),
41 auth: new Headers(init?.headers).get('authorization'),
42 })
43 return Promise.resolve(handler(String(url), init))
44 }) as typeof fetch
45 return run()
46 .then((result) => ({ result, calls }))
47 .finally(() => {
48 globalThis.fetch = original
49 })
50}
51
52describe('dashscope adapter', () => {
53 it('exports seed metadata for the OpenAI-compatible intl host', () => {
54 expect(provider.id).toBe('dashscope')
55 expect(provider.displayName).toBe('Alibaba Cloud Model Studio')
56 expect(provider.authEnvVar).toBe('DASHSCOPE_API_KEY')
57 expect(provider.defaultDerivation).toBe('generated')
58 expect(provider.specSourceUrl).toMatch(/^https:\/\//)
59 expect(provider.modelsEndpoint).toBe(
60 'https://dashscope-intl.aliyuncs.com/api/v1/models',
61 )
62 })
63
64 it('classifies generation paths and drops platform ones', () => {
65 expect(provider.classify('/chat/completions', {})).toBe('chat')
66 expect(provider.classify('/v1/chat/completions', {})).toBe('chat')
67 expect(provider.classify('/embeddings', {})).toBe('embeddings')
68 expect(provider.classify('/images/generations', {})).toBe('image')
69 expect(provider.classify('/audio/speech', {})).toBe('audio')
70 expect(provider.classify('/audio/transcriptions', {})).toBe('audio')
71 expect(provider.classify('/files', {})).toBeNull()
72 expect(provider.classify('/v1/models', {})).toBeNull()
73 expect(provider.classify('/fine_tuning/jobs', {})).toBeNull()
74 expect(provider.classify('/batches', {})).toBeNull()
75 })
76
77 it('skips listModels when the key is absent', async () => {
78 const { models, skipped } = await provider.listModels({})
79 expect(models).toEqual([])
80 expect(skipped).toBe('dashscope: DASHSCOPE_API_KEY not set — skipped')
81 })
82
83 it('fetches a filtered OpenAI spec without calling DashScope', async () => {
84 const { result, calls } = await withStubbedFetch(
85 (url) => {
86 if (url === OPENAI_OPENAPI_URL) return new Response(OPENAI_FIXTURE)
87 return new Response('not found', { status: 404 })
88 },
89 () => provider.fetchSpec({}),
90 )
91
92 expect(calls.map((c) => c.url)).toEqual([OPENAI_OPENAPI_URL])
93 expect(result.outputStrategy).toBe('post-200')
94 expect(result.sources[0]?.url).toBe(OPENAI_OPENAPI_URL)
95 expect(result.sources[0]?.hash).toMatch(/^[0-9a-f]{64}$/)
96 expect(result.specs[0]?.info?.title).toBe('Alibaba Cloud Model Studio')
97 expect(result.specs[0]?.servers).toEqual([
98 { url: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1' },
99 ])
100 expect(Object.keys(result.specs[0]?.paths ?? {}).sort()).toEqual([
101 '/audio/speech',
102 '/audio/transcriptions',
103 '/chat/completions',
104 '/embeddings',
105 '/images/generations',
106 ])
107 expect(result.specs[0]?.paths?.['/files']).toBeUndefined()
108 })
109
110 it('lists models with a bearer key against the intl host', async () => {
111 const { result, calls } = await withStubbedFetch(
112 () =>
113 new Response(
114 JSON.stringify({
115 output: {
116 total: 1,
117 models: [{ model: 'qwen-plus', name: 'Qwen Plus' }],
118 },
119 }),
120 ),
121 () => provider.listModels({ DASHSCOPE_API_KEY: 'test-key' }),
122 )
123 expect(calls).toEqual([
124 {
125 url: 'https://dashscope-intl.aliyuncs.com/api/v1/models?page_no=1&page_size=100&language=en-US',
126 auth: 'Bearer test-key',
127 },
128 { url: DASHSCOPE_COMPAT_URL, auth: null },
129 ])
130 expect(result.skipped).toBeUndefined()
131 expect(result.models).toEqual([
132 {
133 rawId: 'qwen-plus',
134 displayName: 'Qwen Plus',
135 activity: null,
136 contextWindow: null,
137 maxOutput: null,
138 releasedAt: null,
139 },
140 ])
141 expect(result.docsFailures?.failed).toBe(1)
142 })
143})
144
145const TOKEN = 'Per 1M tokens'
146
147function rateCell(
148 card: Awaited<ReturnType<typeof dashscopeListedCard>>,
149 key: string,
150): Record<string, number> {
151 if (!card) throw new Error('expected a card')
152 const rate = card.tables.rate
153 if (!rate) throw new Error('expected a rate table')
154 const cell = rate[key]
155 if (!cell || typeof cell !== 'object') {
156 throw new Error(`expected rate.${key}`)
157 }
158 return Object.fromEntries(
159 Object.entries(cell).filter(
160 (entry): entry is [string, number] => typeof entry[1] === 'number',
161 ),
162 )
163}
164
165describe('dashscope listing cards', () => {
166 it('reads an upper bound as the base tier and the next floor above it', () => {
167 expect(promptFloor('Input<=32k')).toBe(0)
168 expect(promptFloor('32k<Input<=128k')).toBe(32_000)
169 expect(promptFloor('256k<Input<=1m')).toBe(256_000)
170 expect(promptFloor('not-a-tier')).toBeNull()
171 })
172
173 it('prices the non-thinking standard tier and its prompt floors', async () => {
174 const card = await dashscopeListedCard([
175 {
176 range_name: 'Input<=32k',
177 prices: [
178 { type: 'input_token', price: '1.2', price_unit: TOKEN },
179 { type: 'output_token', price: '6', price_unit: TOKEN },
180 { type: 'thinking_output_token', price: '12', price_unit: TOKEN },
181 { type: 'input_token_cache', price: '0.24', price_unit: TOKEN },
182 { type: 'input_token_batch', price: '0.6', price_unit: TOKEN },
183 ],
184 },
185 {
186 range_name: '32k<Input<=128k',
187 prices: [
188 { type: 'input_token', price: '2.4', price_unit: TOKEN },
189 { type: 'output_token', price: '12', price_unit: TOKEN },
190 { type: 'input_token_cache', price: '0.48', price_unit: TOKEN },
191 ],
192 },
193 ])
194 const base = rateCell(card, 'base')
195 expect(base.input_tokens).toBeCloseTo(1.2 / 1e6)
196 expect(base.output_tokens).toBeCloseTo(6 / 1e6, 10)
197 expect(base.cache_read_tokens).toBeCloseTo(0.24 / 1e6, 10)
198 expect(base.output_tokens).not.toBeCloseTo(12 / 1e6, 10)
199 const tier = rateCell(card, '32000')
200 expect(tier.input_tokens).toBeCloseTo(2.4 / 1e6)
201 })
202
203 it('bills thinking rates when the row publishes no plain token price', async () => {
204 const card = await dashscopeListedCard([
205 {
206 range_name: 'Default',
207 prices: [
208 { type: 'thinking_input_token', price: '0.23', price_unit: TOKEN },
209 { type: 'thinking_output_token', price: '2.3', price_unit: TOKEN },
210 ],
211 },
212 ])
213 const base = rateCell(card, 'base')
214 expect(base.input_tokens).toBeCloseTo(0.23 / 1e6)
215 expect(base.output_tokens).toBeCloseTo(2.3 / 1e6)
216 })
217
218 it('uses explicit cache read when implicit cache is absent', async () => {
219 const card = await dashscopeListedCard([
220 {
221 range_name: 'Input<=256k',
222 prices: [
223 { type: 'input_token', price: '0.5', price_unit: TOKEN },
224 { type: 'output_token', price: '3', price_unit: TOKEN },
225 {
226 type: 'input_token_cache_read',
227 price: '0.05',
228 price_unit: TOKEN,
229 },
230 ],
231 },
232 ])
233 const base = rateCell(card, 'base')
234 expect(base.cache_read_tokens).toBeCloseTo(0.05 / 1e6)
235 })
236
237 it('drops peak/off-peak quotes and modality-split quotes', async () => {
238 const peak = await dashscopeListedCard([
239 {
240 range_name: 'Default',
241 prices: [
242 {
243 type: 'input_token',
244 price: '0.15',
245 price_unit: TOKEN,
246 time_band: 'offpeak',
247 },
248 {
249 type: 'input_token',
250 price: '0.3',
251 price_unit: TOKEN,
252 time_band: 'peak',
253 },
254 {
255 type: 'output_token',
256 price: '0.6',
257 price_unit: TOKEN,
258 time_band: 'offpeak',
259 },
260 {
261 type: 'output_token',
262 price: '1.2',
263 price_unit: TOKEN,
264 time_band: 'peak',
265 },
266 ],
267 },
268 ])
269 const split = await dashscopeListedCard([
270 {
271 range_name: 'Default',
272 prices: [
273 { type: 'text_input_token', price: '0.43', price_unit: TOKEN },
274 { type: 'audio_input_token', price: '3.81', price_unit: TOKEN },
275 {
276 type: 'purein_text_output_token',
277 price: '1.66',
278 price_unit: TOKEN,
279 },
280 ],
281 },
282 ])
283 expect(peak).toBeNull()
284 expect(split).toBeNull()
285 })
286
287 it('uses reasoning max output when max output is null', async () => {
288 const model = await dashscopeListedModel({
289 model: 'qwen3-235b-a22b-thinking-2507',
290 capabilities: ['TG'],
291 features: [],
292 inference_metadata: {
293 request_modality: ['Text'],
294 response_modality: ['Text'],
295 },
296 model_info: {
297 context_window: 131072,
298 max_output_tokens: null,
299 reasoning_max_output_tokens: 32768,
300 },
301 })
302 expect(model?.maxOutput).toBe(32768)
303 expect(model?.factSources?.maxOutput?.path).toBe(
304 'model_info.reasoning_max_output_tokens',
305 )
306 })
307})
308
309const COMPAT_PAGE = `
310${DASHSCOPE_COMPAT_SCOPE}
311## Request parameters
312<table><tbody>
313<tr><td><p>messages</p></td><td><p>array</p></td><td><p>-</p></td><td><p>Valid roles: system, user, assistant.</p></td></tr>
314<tr><td><p>temperature</p></td><td><p>float</p></td><td><p>-</p></td><td><p>Controls randomness.</p></td></tr>
315<tr><td><p>max_tokens</p></td><td><p>integer</p></td><td><p>-</p></td><td><p>The maximum number of tokens the model can generate.</p></td></tr>
316</tbody></table>
317## Response parameters
318`
319
320const OMNI_PAGE = `# qwen3-omni-flash
321
322## Context Limits
323
324<table><tbody><tr><td><p>Context Window</p></td><td><p>65536</p></td><td><p>Max Output Length</p></td><td><p>16384</p></td></tr></tbody></table>
325
326### qwen3-omni-flash-2025-09-15
327
328#### Context Limits
329
330<table><tbody><tr><td><p>Context Window</p></td><td><p>65536</p></td><td><p>Max Output Length</p></td><td><p>16384</p></td></tr></tbody></table>
331`
332
333describe('dashscope listModels docs', () => {
334 it('stamps the compat request map on chat rows', async () => {
335 const { result, calls } = await withStubbedFetch(
336 (url) => {
337 if (url === DASHSCOPE_THINKING_URL)
338 return new Response(nativeDocs[DASHSCOPE_THINKING_URL])
339 if (url === DASHSCOPE_COMPAT_URL) return new Response(COMPAT_PAGE)
340 return new Response(
341 JSON.stringify({
342 output: {
343 total: 1,
344 models: [
345 {
346 model: 'qwen-plus',
347 name: 'Qwen Plus',
348 capabilities: ['TG'],
349 features: ['function-calling'],
350 inference_metadata: {
351 request_modality: ['Text'],
352 response_modality: ['Text'],
353 },
354 model_info: {
355 context_window: 1000000,
356 max_output_tokens: 32768,
357 },
358 },
359 ],
360 },
361 }),
362 )
363 },
364 () => provider.listModels({ DASHSCOPE_API_KEY: 'test-key' }),
365 )
366 expect(calls.map((call) => call.url)).toEqual([
367 'https://dashscope-intl.aliyuncs.com/api/v1/models?page_no=1&page_size=100&language=en-US',
368 DASHSCOPE_THINKING_URL,
369 DASHSCOPE_COMPAT_URL,
370 ])
371 const model = result.models[0]
372 expect(model?.requestMap?.maxTokensField).toBe('max_tokens')
373 expect(model?.requestMap?.developerRole).toBe(false)
374 expect(model?.exactCapabilities).toBe(false)
375 expect(model?.capabilities).toEqual([
376 'tools',
377 'temperature',
378 'max_tokens',
379 'reasoning',
380 ])
381 expect(model?.factSources?.capabilities?.temperature?.sourceUrl).toBe(
382 DASHSCOPE_COMPAT_URL,
383 )
384 expect(result.docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
385 })
386
387 it('fills a null context window from the model page', async () => {
388 const page = dashscopeModelPageUrl('qwen3-omni-flash-2025-09-15')
389 const { result, calls } = await withStubbedFetch(
390 (url) => {
391 if (url === DASHSCOPE_THINKING_URL)
392 return new Response(nativeDocs[DASHSCOPE_THINKING_URL])
393 if (url === DASHSCOPE_COMPAT_URL) return new Response(COMPAT_PAGE)
394 if (url === page) return new Response(OMNI_PAGE)
395 return new Response(
396 JSON.stringify({
397 output: {
398 total: 1,
399 models: [
400 {
401 model: 'qwen3-omni-flash-2025-09-15',
402 capabilities: ['Multimodal-Omni'],
403 features: [],
404 inference_metadata: {
405 request_modality: ['Text'],
406 response_modality: ['Text'],
407 },
408 model_info: {
409 context_window: null,
410 max_output_tokens: null,
411 },
412 },
413 ],
414 },
415 }),
416 )
417 },
418 () => provider.listModels({ DASHSCOPE_API_KEY: 'test-key' }),
419 )
420 expect(calls.map((call) => call.url)).toContain(page)
421 expect(page).toBe(
422 'https://www.alibabacloud.com/help/en/model-studio/qwen3-omni-flash.md',
423 )
424 const model = result.models[0]
425 expect(model?.contextWindow).toBe(65536)
426 expect(model?.maxOutput).toBe(16384)
427 expect(model?.factSources?.contextWindow?.sourceUrl).toBe(page)
428 expect(model?.requestMap?.maxTokensField).toBe('max_tokens')
429 })
430
431 it('leaves a non-compat chat id off the OpenAI request map', async () => {
432 const { result } = await withStubbedFetch(
433 (url) => {
434 if (url === DASHSCOPE_THINKING_URL)
435 return new Response(nativeDocs[DASHSCOPE_THINKING_URL])
436 if (url === DASHSCOPE_COMPAT_URL) return new Response(COMPAT_PAGE)
437 return new Response(
438 JSON.stringify({
439 output: {
440 total: 1,
441 models: [
442 {
443 model: 'decision-model-preview',
444 capabilities: ['TG'],
445 features: [],
446 inference_metadata: {
447 request_modality: ['Text'],
448 response_modality: ['Text'],
449 },
450 model_info: {
451 context_window: 65536,
452 max_output_tokens: 0,
453 },
454 },
455 ],
456 },
457 }),
458 )
459 },
460 () => provider.listModels({ DASHSCOPE_API_KEY: 'test-key' }),
461 )
462 const model = result.models[0]
463 expect(model?.contextWindow).toBe(65536)
464 expect(model?.maxOutput).toBe(0)
465 expect(model?.requestMap).toBeUndefined()
466 expect(model?.capabilities ?? []).not.toEqual(
467 expect.arrayContaining(['temperature', 'max_tokens', 'top_p']),
468 )
469 expect(model?.factSources?.capabilities?.temperature).toBeUndefined()
470 expect(
471 provider.generationEndpointId?.({
472 rawId: 'decision-model-preview',
473 activity: 'chat',
474 }),
475 ).toBeNull()
476 expect(
477 provider.generationEndpointId?.({
478 rawId: 'qwen-plus',
479 activity: 'chat',
480 }),
481 ).toBe('chat/completions')
482 })
483})