Open History to see the last commit
1/** Public Beijing catalog and RMB quotes, without international substitution. */
2import { compileTokenCard } from '@modelschemas/rate-card'
3import type { FactSource, ModelInfo } from './types.ts'
4
5export const DASHSCOPE_CN_PRICES =
6 'https://help.aliyun.com/zh/model-studio/model-pricing.md'
7export const DASHSCOPE_CN_MODELS =
8 'https://help.aliyun.com/zh/model-studio/models.md'
9export interface CnDoc {
10 text: string
11 url: string
12 hash: string
13}
14function fail(message: string): never {
15 throw new Error(`dashscope-cn: ${message}`)
16}
17export function cnText(value: string): string {
18 return value
19 .replace(/\\</g, '<')
20 .replace(/<[^>]+>/g, ' ')
21 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
22 .replace(/</g, '<')
23 .replace(/>/g, '>')
24 .replace(/&/g, '&')
25 .replace(/ /g, ' ')
26 .replace(/\\</g, '<')
27 .replace(/\\([_*-])/g, '$1')
28 .replace(/[*`]/g, '')
29 .replace(/\s+/g, ' ')
30 .trim()
31}
32/** Expand actual MDX rowSpan/colSpan values, including self-closing empty cells. */
33export function cnTable(table: string): string[][] {
34 const grid: string[][] = []
35 const pending = new Map<number, { text: string; remaining: number }>()
36 for (const row of table.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)) {
37 const values: string[] = []
38 let column = 0
39 const fill = () => {
40 while (pending.has(column)) {
41 const span = pending.get(column)!
42 values[column++] = span.text
43 if (--span.remaining === 0) pending.delete(column - 1)
44 }
45 }
46 for (const cell of row[1]!.matchAll(
47 /<t[dh]\b([^>]*?)(?:\/>|>([\s\S]*?)<\/t[dh]>)/gi,
48 )) {
49 fill()
50 const span = (name: string) => {
51 const attrs = cell[1] ?? ''
52 const found = new RegExp(
53 `${name}\\s*=\\s*(?:\\{(\\d+)\\}|"(\\d+)")`,
54 'i',
55 ).exec(attrs)
56 if (new RegExp(name, 'i').test(attrs) && !found)
57 fail('unreadable table span')
58 const value = Number(found?.[1] ?? found?.[2] ?? 1)
59 if (!Number.isSafeInteger(value) || value < 1)
60 fail('invalid table span')
61 return value
62 }
63 const across = span('colspan'),
64 down = span('rowspan')
65 for (let index = 0; index < across; index++) {
66 if (pending.has(column)) fail('overlapping table span')
67 values[column] = cell[2] ?? ''
68 if (down > 1)
69 pending.set(column, { text: cell[2] ?? '', remaining: down - 1 })
70 column++
71 }
72 }
73 fill()
74 if (values.length) grid.push(values)
75 }
76 if (pending.size) fail('table span extends beyond rows')
77 return grid
78}
79function cellIds(cell: string): string[] {
80 const body = cell.split(/\n\s*>/)[0] ?? ''
81 const text = cnText(body.replace(/<\/(?:p|div)>|<br\s*\/?\s*>/gi, '\n'))
82 const ids = [
83 ...new Set(
84 text.split(/\s+/).filter((id) => /^[a-z][a-z0-9_./-]+$/i.test(id)),
85 ),
86 ]
87 if (
88 !ids.length &&
89 /^参见\s*模型列表$/.test(text) &&
90 /(?:\[模型列表\]\([^)]*\)|<a\b[^>]*href=)/.test(body)
91 )
92 return []
93 if (!ids.length) fail(`unreadable model ID cell: ${text}`)
94 return ids
95}
96function activity(heading: string): ModelInfo['activity'] {
97 if (/文本生成/.test(heading)) return 'chat'
98 if (/向量|文本嵌入|多模态嵌入/.test(heading)) return 'embeddings'
99 if (/重排序|排序模型/.test(heading)) return null // The repository has no rerank activity.;
100 if (/图像|图片/.test(heading)) return 'image'
101 if (/视频/.test(heading)) return 'video'
102 if (/音频|语音|音乐/.test(heading)) return 'audio'
103 return null
104}
105function ownSource(doc: CnDoc, path: string): FactSource {
106 return {
107 derivation: 'docs-derived',
108 sourceUrl: doc.url,
109 sourceHash: doc.hash,
110 path,
111 }
112}
113function amount(cell: string): number {
114 const text = cnText(cell)
115 const match = /^(\d+(?:\.\d+)?)元$/.exec(text)
116 if (!match) fail(`unreadable RMB token quote: ${text}`)
117 const value = Number(match[1]) / 1e6
118 if (!Number.isFinite(value) || value < 0) fail('invalid RMB token quote')
119 return value
120}
121function floor(cell: string): number {
122 const text = cnText(cell).replace(/\s+/g, '')
123 if (text === '无阶梯计价' || text === '不区分阶梯') return 0
124 const match =
125 /^(\d+(?:\.\d+)?)([KM]?)<Token[≤<](?:=?)(\d+(?:\.\d+)?)([KM]?)$/i.exec(text)
126 if (!match) fail(`unreadable token range: ${text}`)
127 const scale = (unit: string) =>
128 unit.toUpperCase() === 'M' ? 1e6 : unit.toUpperCase() === 'K' ? 1e3 : 1
129 const min = Number(match[1]) * scale(match[2]!),
130 max = Number(match[3]) * scale(match[4]!)
131 if (!Number.isFinite(min) || max <= min) fail('invalid token range')
132 return min
133}
134interface Quoted {
135 models: string[]
136 mode: string
137 floor: number
138 rates: Record<string, number>
139}
140/** Balance nested model-family Tabs inside each explicitly Beijing panel. */
141export function cnBeijingTabs(
142 text: string,
143): Array<{ body: string; start: number }> {
144 const panels: Array<{ body: string; start: number }> = []
145 const stack: Array<{ start: number; bodyAt: number; beijing: boolean }> = []
146 for (const tag of text.matchAll(/<\/?Tab\b[^>]*>/g)) {
147 if (tag[0].startsWith('</')) {
148 const open = stack.pop()
149 if (!open) fail('unbalanced region Tab')
150 if (open.beijing)
151 panels.push({
152 body: text.slice(open.bodyAt, tag.index),
153 start: open.start,
154 })
155 } else
156 stack.push({
157 start: tag.index,
158 bodyAt: tag.index + tag[0].length,
159 beijing: /\btitle="华北2(北京)"/.test(tag[0]),
160 })
161 }
162 if (stack.length) fail('unclosed region Tab')
163 return panels
164}
165export function cnPriceModels(doc: CnDoc): ModelInfo[] {
166 const result = new Map<string, ModelInfo>()
167 const quoted = new Map<string, Quoted[]>()
168 let tabs = 0
169 for (const tab of cnBeijingTabs(doc.text)) {
170 tabs++
171 const prior = doc.text.slice(0, tab.start)
172 const major = [...prior.matchAll(/^## (.*)$/gm)].at(-1)?.[1] ?? ''
173 for (const table of tab.body.matchAll(/<table\b[^>]*>[\s\S]*?<\/table>/g)) {
174 const rows = cnTable(table[0])
175 const head = (rows.shift() ?? []).map(cnText)
176 const idAt = head.findIndex((column) => /模型\s*ID/.test(column))
177 if (idAt < 0) continue // Native cache/promotion tables are not model listings.
178 for (const column of head) {
179 if (
180 /^(?:输入|输出)单价.*Token/.test(column) &&
181 !/^(?:输入|输出)单价\s*(每百万\s*Token)/.test(column)
182 )
183 fail(`unknown token price unit ${column}`)
184 }
185 const inputAt = head.findIndex((column) =>
186 /^输入单价\s*(每百万\s*Token)/.test(column),
187 )
188 const multipleTokenMeters =
189 head.filter((column) => /^输入单价\s*(每百万\s*Token)/.test(column))
190 .length > 1 ||
191 head.filter((column) => /^输出单价\s*(每百万\s*Token)/.test(column))
192 .length > 1
193 while (rows[0] && cnText(rows[0][idAt] ?? '') === head[idAt]) rows.shift()
194 const outputAt = head.findIndex((column) =>
195 /^输出单价\s*(每百万\s*Token)/.test(column),
196 )
197 const rangeAt = head.findIndex((column) =>
198 /输入Token(?:数|范围|数量)/.test(column),
199 )
200 const modeAt = head.indexOf('模式')
201 for (const row of rows) {
202 if (row.length !== head.length)
203 fail(`unequal model table columns ${head.join('|')}`)
204 const ids = cellIds(row[idAt]!)
205 for (const rawId of ids) {
206 if (!result.has(rawId))
207 result.set(rawId, {
208 rawId,
209 displayName: null,
210 activity: activity(major),
211 pricing: null,
212 contextWindow: null,
213 maxOutput: null,
214 capabilities: null,
215 serverTools: null,
216 modalities: null,
217 reasoning: null,
218 requestMap: null,
219 schemaEndpointId: null,
220 absent: { pricing: 'cleared' },
221 providerMetadata: {
222 listingScope: 'public Beijing documentation',
223 nativePricingColumns: head,
224 },
225 })
226 }
227 // Dimensional audio/image/video/size pricing is sourced but requires its
228 // own usage model; it is not a single text token quote. Remain null.
229 if (inputAt < 0 || multipleTokenMeters) continue
230 if (/^已下线(?:[ >]|$)/.test(cnText(row[inputAt]!))) {
231 for (const id of ids) result.get(id)!.deprecated = true
232 continue
233 }
234 if (/^目前仅供免费体验[。.]?|^限时免费$/.test(cnText(row[inputAt]!)))
235 continue
236 if (
237 /忙时.+闲时|^(?:文本|图片|视频|音频)输入:/.test(
238 cnText(row[inputAt]!),
239 )
240 )
241 continue
242 const rates: Record<string, number> = {
243 input_tokens: amount(row[inputAt]!),
244 }
245 if (outputAt >= 0) rates.output_tokens = amount(row[outputAt]!)
246 const quote: Quoted = {
247 models: ids,
248 mode: modeAt >= 0 ? cnText(row[modeAt]!) : '',
249 floor: rangeAt >= 0 ? floor(row[rangeAt]!) : 0,
250 rates,
251 }
252 for (const id of ids) quoted.set(id, [...(quoted.get(id) ?? []), quote])
253 }
254 }
255 }
256 if (!tabs || !result.size) fail('no Beijing model listing tables')
257 for (const [id, rows] of quoted) {
258 const modes = new Set(rows.map((row) => row.mode))
259 // Distinct thinking-mode prices cannot be selected silently.
260 if (modes.size > 1) continue
261 const tiers = new Map<number, Record<string, number>>()
262 for (const row of rows) {
263 const old = tiers.get(row.floor)
264 if (old && JSON.stringify(old) !== JSON.stringify(row.rates))
265 fail(`conflicting Beijing price ${id}`)
266 tiers.set(row.floor, row.rates)
267 }
268 const base = tiers.get(0)
269 if (
270 base &&
271 [...tiers.values()].some((rates) =>
272 Object.keys(base).some((lever) => rates[lever] === undefined),
273 )
274 )
275 fail(`incomplete price tier ${id}`)
276 if (!base) fail(`missing base price tier ${id}`)
277 const pricing = compileTokenCard(
278 base,
279 [...tiers]
280 .filter(([min]) => min > 0)
281 .sort(([a], [b]) => a - b)
282 .map(([minPromptTokens, rates]) => ({ minPromptTokens, rates })),
283 { url: doc.url, hash: doc.hash, extractedAt: new Date().toISOString() },
284 { currency: 'CNY' },
285 )
286 if (!pricing) fail(`unrepresentable token quote ${id}`)
287 const model = result.get(id)!
288 model.pricing = pricing
289 model.factSources = {
290 pricing: ownSource(doc, '华北2(北京) model pricing table'),
291 }
292 }
293 return [...result.values()]
294}
295
296/** Exact ids and expressly included snapshots in the provider's Chinese table. */
297export function applyCnTextFacts(models: ModelInfo[], doc: CnDoc): ModelInfo[] {
298 const facts = new Map<
299 string,
300 {
301 contextWindow: number
302 capabilities: string[]
303 unsupportedCapabilities: string[]
304 snapshots: boolean
305 }
306 >()
307 for (const table of doc.text.matchAll(/<table\b[^>]*>[\s\S]*?<\/table>/g)) {
308 const rows = cnTable(table[0]),
309 head = (rows.shift() ?? []).map(cnText)
310 if (head[0] !== '模型ID' || !head.includes('上下文')) continue
311 const contextAt = head.indexOf('上下文')
312 const mapped: Record<string, string> = {
313 思考模式: 'reasoning',
314 'Function Calling': 'tools',
315 结构化输出: 'structured_outputs',
316 }
317 for (const row of rows) {
318 if (row.length !== head.length) fail('unequal native capability table')
319 const ids = [...row[0]!.matchAll(/<code>([^<]+)<\/code>/g)].map(
320 (match) => match[1]!,
321 )
322 if (!ids.length) ids.push(...cellIds(row[0]!))
323 const contextValue = cnText(row[contextAt]!),
324 match = /^(\d+(?:\.\d+)?)([KM])$/i.exec(contextValue)
325 if (!match) fail(`unreadable native context limit ${contextValue}`)
326 const contextWindow =
327 Number(match[1]) * (match[2]!.toUpperCase() === 'M' ? 1e6 : 1e3)
328 if (!Number.isSafeInteger(contextWindow) || contextWindow <= 0)
329 fail('invalid native context limit')
330 const capabilities: string[] = [],
331 unsupportedCapabilities: string[] = []
332 for (let index = 0; index < head.length; index++) {
333 const flag = mapped[head[index]!]
334 if (!flag) continue
335 const value = cnText(row[index]!)
336 if (value !== '支持' && value !== '不支持')
337 fail('unknown capability support value')
338 if (value === '支持') capabilities.push(flag)
339 else unsupportedCapabilities.push(flag)
340 }
341 for (const id of ids) {
342 const fact = {
343 contextWindow,
344 capabilities,
345 unsupportedCapabilities,
346 snapshots: /及其快照版本/.test(cnText(row[0]!)),
347 }
348 if (
349 facts.has(id) &&
350 JSON.stringify(facts.get(id)) !== JSON.stringify(fact)
351 )
352 fail('conflicting native capability rows')
353 facts.set(id, fact)
354 }
355 }
356 }
357 if (!facts.size) fail('native text catalog has no capability tables')
358 return models.map((model) => {
359 const candidates = [...facts].filter(
360 ([id, fact]) =>
361 id === model.rawId ||
362 (fact.snapshots &&
363 model.rawId.startsWith(`${id}-`) &&
364 /^\d{4}-\d{2}-\d{2}$/.test(model.rawId.slice(id.length + 1))),
365 )
366 if (candidates.length > 1) fail('ambiguous native snapshot scope')
367 const fact = candidates[0]?.[1]
368 if (!fact) return model
369 return {
370 ...model,
371 contextWindow: fact.contextWindow,
372 capabilities: fact.capabilities,
373 unsupportedCapabilities: fact.unsupportedCapabilities,
374 factSources: {
375 ...model.factSources,
376 contextWindow: ownSource(doc, '上下文'),
377 capabilities: Object.fromEntries(
378 [...fact.capabilities, ...fact.unsupportedCapabilities].map(
379 (flag) => [flag, ownSource(doc, `model capability table.${flag}`)],
380 ),
381 ),
382 },
383 }
384 })
385}
386
387/** Own card headings define exact ids; Beijing capability tables alone win. */
388export function applyCnCardFacts(models: ModelInfo[], doc: CnDoc): ModelInfo[] {
389 const byId = new Map<
390 string,
391 Partial<Omit<ModelInfo, 'capabilities'>> & { capabilities?: string[] }
392 >()
393 const completed = new Map<string, Set<string>>()
394 let current: string | null = null
395 const starts = [...doc.text.matchAll(/^#{1,6}\s+([^\n]+)$/gm)]
396 for (let index = 0; index < starts.length; index++) {
397 const heading = cnText(starts[index]![1]!)
398 if (/^[a-z][a-z0-9._-]*-[a-z0-9._-]+$/.test(heading)) current = heading
399 if (!current) continue
400 const section = doc.text.slice(
401 starts[index]!.index + starts[index]![0].length,
402 starts[index + 1]?.index ?? doc.text.length,
403 )
404 const facts = byId.get(current) ?? {}
405 const seen = completed.get(current) ?? new Set<string>()
406 if (heading === '上下文限制') {
407 for (const table of section.matchAll(
408 /<table\b[^>]*>[\s\S]*?<\/table>/g,
409 )) {
410 for (const row of cnTable(table[0]).slice(1))
411 for (let column = 0; column + 1 < row.length; column += 2) {
412 const label = cnText(row[column]!),
413 text = cnText(row[column + 1]!)
414 if (label !== '上下文长度' && label !== '最大输出长度') continue
415 if (
416 !/^\d+$/.test(text) ||
417 !Number.isSafeInteger(Number(text)) ||
418 Number(text) <= 0
419 )
420 fail('unreadable card token limit')
421 const key = label === '上下文长度' ? 'contextWindow' : 'maxOutput'
422 if (facts[key] != null && facts[key] !== Number(text))
423 fail('conflicting card token limit')
424 facts[key] = Number(text)
425 seen.add(key)
426 }
427 }
428 }
429 if (heading === '模型能力') {
430 const modes: Record<string, string> = {
431 Text: 'text',
432 Image: 'image',
433 Audio: 'audio',
434 Video: 'video',
435 }
436 let input: string[] | null = null,
437 output: string[] | null = null
438 const flags = new Set<string>(),
439 unsupported = new Set<string>()
440 const checked = new Set<string>()
441 const panels = cnBeijingTabs(section)
442 if (!panels.length) fail('card has no Beijing capability panel')
443 for (const panel of panels)
444 for (const table of panel.body.matchAll(
445 /<table\b[^>]*>[\s\S]*?<\/table>/g,
446 )) {
447 for (const row of cnTable(table[0]).slice(1))
448 for (let column = 0; column + 1 < row.length; column += 2) {
449 const label = cnText(row[column]!),
450 value = cnText(row[column + 1]!)
451 if (label === '输入模态' || label === '输出模态') {
452 const kinds = value
453 .split(/[,,/\s]+/)
454 .map(
455 (kind) =>
456 modes[kind] ?? fail(`unknown card modality ${kind}`),
457 )
458 const old = label === '输入模态' ? input : output
459 if (old && JSON.stringify(old) !== JSON.stringify(kinds))
460 fail('conflicting card modality')
461 if (label === '输入模态') input = kinds
462 else output = kinds
463 }
464 const flag =
465 label === 'Function Calling'
466 ? 'tools'
467 : label === '结构化输出'
468 ? 'structured_outputs'
469 : null
470 if (flag) {
471 if (value !== '支持' && value !== '不支持')
472 fail('unknown card capability status')
473 if (
474 (flags.has(flag) && value === '不支持') ||
475 (unsupported.has(flag) && value === '支持')
476 )
477 fail('conflicting card capability status')
478 checked.add(flag)
479 if (value === '支持') flags.add(flag)
480 else unsupported.add(flag)
481 }
482 }
483 }
484 if (
485 !input ||
486 !output ||
487 !checked.has('tools') ||
488 !checked.has('structured_outputs')
489 )
490 fail('incomplete Beijing card capability table')
491 facts.modalities = { input, output }
492 facts.capabilities = [...flags]
493 facts.unsupportedCapabilities = [...unsupported]
494 seen.add('capabilities')
495 }
496 byId.set(current, facts)
497 completed.set(current, seen)
498 }
499 if (!byId.size) fail('own card names no model ids')
500 for (const [id, seen] of completed)
501 if (
502 !['contextWindow', 'maxOutput', 'capabilities'].every((key) =>
503 seen.has(key),
504 )
505 )
506 fail(`incomplete native card ${id}`)
507 return models.map((model) => {
508 const fact = byId.get(model.rawId)
509 if (!fact) return model
510 const capabilities = [
511 ...new Set([
512 ...(Array.isArray(model.capabilities)
513 ? (model.capabilities as string[]).filter(
514 (flag) =>
515 !Array.isArray(fact.capabilities) ||
516 (flag !== 'tools' && flag !== 'structured_outputs'),
517 )
518 : []),
519 ...(Array.isArray(fact.capabilities) ? fact.capabilities : []),
520 ]),
521 ]
522 const sources = { ...model.factSources }
523 if (fact.contextWindow != null)
524 sources.contextWindow = ownSource(doc, '上下文限制.上下文长度')
525 if (fact.maxOutput != null)
526 sources.maxOutput = ownSource(doc, '上下文限制.最大输出长度')
527 if (fact.modalities != null)
528 sources.modalities = ownSource(
529 doc,
530 '华北2(北京).模型能力.输入/输出模态',
531 )
532 if (Array.isArray(fact.capabilities))
533 sources.capabilities = {
534 ...Object.fromEntries(
535 Object.entries(model.factSources?.capabilities ?? {}).filter(
536 ([flag]) => flag !== 'tools' && flag !== 'structured_outputs',
537 ),
538 ),
539 ...Object.fromEntries(
540 [...fact.capabilities, ...(fact.unsupportedCapabilities ?? [])].map(
541 (flag) => [flag, ownSource(doc, `华北2(北京).模型能力.${flag}`)],
542 ),
543 ),
544 }
545 const unsupportedCapabilities = [
546 ...new Set([
547 ...(model.unsupportedCapabilities ?? []).filter(
548 (flag) => !['tools', 'structured_outputs'].includes(flag),
549 ),
550 ...(fact.unsupportedCapabilities ?? []),
551 ]),
552 ]
553 return {
554 ...model,
555 ...fact,
556 capabilities,
557 unsupportedCapabilities,
558 factSources: sources,
559 }
560 })
561}
562
563/** Native CN console links publish their exact encoded model ids. */
564export function applyCnCatalog(models: ModelInfo[], doc: CnDoc): ModelInfo[] {
565 const out = new Map(models.map((model) => [model.rawId, model]))
566 let count = 0
567 for (const anchor of doc.text.matchAll(
568 /<a\b[^>]*href="(https:\/\/bailian\.console\.aliyun\.com\/cn-beijing\/model\/market\/detail\/[^"?#]+)"[^>]*>([\s\S]*?)<\/a>/g,
569 )) {
570 const encoded = new URL(anchor[1]!).pathname.split('/detail/')[1]
571 if (!encoded) fail('empty native console id')
572 const rawId = decodeURIComponent(encoded)
573 if (!/^[a-z][a-z0-9_./-]+$/i.test(rawId))
574 fail('malformed native console id')
575 count++
576 if (out.has(rawId)) {
577 out.get(rawId)!.displayName = cnText(anchor[2]!) || null
578 continue
579 }
580 const prior = doc.text.slice(0, anchor.index)
581 const major = [...prior.matchAll(/^## (.*)$/gm)].at(-1)?.[1] ?? ''
582 const ambiguous = /图像与视频|向量与重排序/.test(major)
583 out.set(rawId, {
584 rawId,
585 displayName: cnText(anchor[2]!) || null,
586 activity: ambiguous ? null : activity(major),
587 pricing: null,
588 absent: { pricing: 'cleared' },
589 contextWindow: null,
590 maxOutput: null,
591 modalities: null,
592 capabilities: null,
593 serverTools: null,
594 reasoning: null,
595 requestMap: null,
596 schemaEndpointId: null,
597 providerMetadata: {
598 listingScope: 'public Beijing console links',
599 catalogSource: doc.url,
600 },
601 })
602 }
603 if (!count) fail('native selection docs have no Beijing console models')
604 return [...out.values()]
605}