Open History to see the last commit
1/**
2 * DeepSeek prices from the models page (issue #109). Each model publishes
3 * off-peak and peak rates. The card holds both behind a required
4 * `pricing_period` lever (issue #449, same compiler as BytePlus #411).
5 * A page that does not give both sets for every model throws.
6 */
7import { compilePeriodCard } from './byteplus-pricing.ts'
8import type { cachedDocs } from './model-facts.ts'
9import { assertParsed } from './model-facts.ts'
10import { fetchText, sha256Text } from './types.ts'
11import type { ModelInfo } from './types.ts'
12
13/** The trailing slash is load-bearing: without it the docs host serves its home page (issue #369). */
14export const DEEPSEEK_PRICING_URL =
15 'https://api-docs.deepseek.com/quick_start/pricing/'
16
17export interface DeepseekRates {
18 input: number
19 cacheRead: number
20 output: number
21}
22
23/** Both published periods, USD per million tokens. Neither is a default. */
24export interface DeepseekPeriodRates {
25 off_peak: DeepseekRates
26 peak: DeepseekRates
27}
28
29function money(line: string): number | null {
30 const match = line.match(/^\$(\d+(?:\.\d+)?)$/)
31 return match?.[1] ? Number(match[1]) : null
32}
33
34/** Both periods, USD per million tokens, keyed by API id. */
35export function parseDeepseekPricing(
36 html: string,
37): Map<string, DeepseekPeriodRates> {
38 const text = html
39 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
40 .replace(/<[^>]+>/g, '\n')
41 .replace(/&/g, '&')
42 const lines = text
43 .split('\n')
44 .map((line) => line.trim())
45 .filter((line) => line.length > 0)
46 const modelAt = lines.indexOf('MODEL')
47 const pricingAt = lines.indexOf('PRICING')
48 if (modelAt < 0 || pricingAt < modelAt) return new Map()
49 const ids: Array<string> = []
50 for (const line of lines.slice(modelAt + 1, pricingAt)) {
51 if (/^deepseek-[a-z0-9.-]+$/.test(line)) ids.push(line)
52 else if (line.startsWith('BASE URL')) break
53 }
54 const prices: Array<number> = []
55 for (const line of lines.slice(pricingAt + 1)) {
56 const value = money(line)
57 if (value !== null) prices.push(value)
58 else if (prices.length > 0 && line.startsWith('Concurrency')) break
59 }
60 if (ids.length === 0) return new Map()
61 if (prices.length !== ids.length * 6) {
62 throw new Error(
63 `deepseek pricing page: expected ${ids.length * 6} prices (off-peak and peak for cache read, input, and output), got ${prices.length}`,
64 )
65 }
66 const out = new Map<string, DeepseekPeriodRates>()
67 for (const [index, id] of ids.entries()) {
68 const at = (row: number) => prices[row * ids.length + index]
69 const period = (start: number): DeepseekRates => {
70 const cacheRead = at(start)
71 const input = at(start + 2)
72 const output = at(start + 4)
73 if (
74 cacheRead === undefined ||
75 input === undefined ||
76 output === undefined
77 ) {
78 throw new Error(
79 `deepseek pricing page: ${id} is missing an off-peak or peak rate`,
80 )
81 }
82 return { input, cacheRead, output }
83 }
84 // Rows alternate off-peak then peak: cache, input, output.
85 out.set(id, { off_peak: period(0), peak: period(1) })
86 }
87 return out
88}
89
90function perToken(row: DeepseekRates): Record<string, number> {
91 return {
92 input_tokens: row.input / 1e6,
93 output_tokens: row.output / 1e6,
94 cache_read_tokens: row.cacheRead / 1e6,
95 }
96}
97
98type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
99
100/**
101 * Name the body's size and title so a zero-row parse says what came back
102 * (issue #367; the title is how #369 found the home page served instead).
103 */
104function describeBody(html: string): string {
105 const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1]?.trim()
106 return `${html.length} chars, title ${JSON.stringify(title ?? null)}`
107}
108
109export async function deepseekModelPricing(
110 kv: KVNamespace | undefined,
111 cached: typeof cachedDocs,
112): Promise<(rawId: string) => PricedFacts> {
113 const doc = await cached(kv, DEEPSEEK_PRICING_URL, async () => {
114 const html = await fetchText(DEEPSEEK_PRICING_URL)
115 const parsed = parseDeepseekPricing(html)
116 if (parsed.size === 0) {
117 throw new Error(
118 `deepseek pricing page (${describeBody(html)}): parsed 0 model rows`,
119 )
120 }
121 assertParsed(parsed, 'deepseek pricing page')
122 return {
123 rates: Object.fromEntries(parsed),
124 hash: await sha256Text(html),
125 extractedAt: new Date().toISOString(),
126 }
127 })
128 return (rawId) => {
129 const row = doc.rates[rawId]
130 if (!row) return {}
131 const pricing = compilePeriodCard(
132 {
133 periods: {
134 off_peak: perToken(row.off_peak),
135 peak: perToken(row.peak),
136 },
137 },
138 {
139 url: DEEPSEEK_PRICING_URL,
140 hash: doc.hash,
141 extractedAt: doc.extractedAt,
142 },
143 )
144 return { pricing }
145 }
146}