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

deepseek-pricing.ts

121 lines3.9 KB

1/**
2 * DeepSeek prices from the models page (issue #109). Each model publishes
3 * off-peak and peak rates. There is no request lever for the clock, so the
4 * card is the off-peak rate (the rate outside the named peak windows).
5 * Peak is not stored. A page that does not match this table throws.
6 */
7import { compileTokenCard } from '@modelschemas/rate-card'
8​
9import type { cachedDocs } from './model-facts.ts'
10import { assertParsed } from './model-facts.ts'
11import { fetchText, sha256Text } from './types.ts'
12import type { ModelInfo } from './types.ts'
13​
14/** The trailing slash is load-bearing: without it the docs host serves its home page (issue #369). */
15export const DEEPSEEK_PRICING_URL =
16 'https://api-docs.deepseek.com/quick_start/pricing/'
17​
18export interface DeepseekRates {
19 input: number
20 cacheRead: number
21 output: number
23​
24function money(line: string): number | null {
25 const match = line.match(/^\$(\d+(?:\.\d+)?)$/)
26 return match?.[1] ? Number(match[1]) : null
28​
29/** Off-peak USD per million tokens, keyed by API id. */
30export function parseDeepseekPricing(html: string): Map<string, DeepseekRates> {
31 const text = html
32 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
33 .replace(/<[^>]+>/g, '\n')
34 .replace(/&amp;/g, '&')
35 const lines = text
36 .split('\n')
37 .map((line) => line.trim())
38 .filter((line) => line.length > 0)
39 const modelAt = lines.indexOf('MODEL')
40 const pricingAt = lines.indexOf('PRICING')
41 if (modelAt < 0 || pricingAt < modelAt) return new Map()
42 const ids: Array<string> = []
43 for (const line of lines.slice(modelAt + 1, pricingAt)) {
44 if (/^deepseek-[a-z0-9.-]+$/.test(line)) ids.push(line)
45 else if (line.startsWith('BASE URL')) break
46 }
47 const prices: Array<number> = []
48 for (const line of lines.slice(pricingAt + 1)) {
49 const value = money(line)
50 if (value !== null) prices.push(value)
51 else if (prices.length > 0 && line.startsWith('Concurrency')) break
52 }
53 if (ids.length === 0 || prices.length !== ids.length * 6) return new Map()
54 const out = new Map<string, DeepseekRates>()
55 ids.forEach((id, index) => {
56 const at = (row: number) => prices[row * ids.length + index]
57 const cacheRead = at(0)
58 const input = at(2)
59 const output = at(4)
60 if (
61 cacheRead === undefined ||
62 input === undefined ||
63 output === undefined
64 ) {
65 return
66 }
67 out.set(id, { input, cacheRead, output })
68 })
69 return out
71​
72type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
73​
74/**
75 * Name the body's size and title so a zero-row parse says what came back
76 * (issue #367; the title is how #369 found the home page served instead).
77 */
78function describeBody(html: string): string {
79 const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1]?.trim()
80 return `${html.length} chars, title ${JSON.stringify(title ?? null)}`
82​
83export async function deepseekModelPricing(
84 kv: KVNamespace | undefined,
85 cached: typeof cachedDocs,
86): Promise<(rawId: string) => PricedFacts> {
87 const doc = await cached(kv, DEEPSEEK_PRICING_URL, async () => {
88 const html = await fetchText(DEEPSEEK_PRICING_URL)
89 const parsed = parseDeepseekPricing(html)
90 if (parsed.size === 0) {
91 throw new Error(
92 `deepseek pricing page (${describeBody(html)}): parsed 0 model rows`,
93 )
94 }
95 assertParsed(parsed, 'deepseek pricing page')
96 return {
97 rates: Object.fromEntries(parsed),
98 hash: await sha256Text(html),
99 extractedAt: new Date().toISOString(),
100 }
101 })
102 return (rawId) => {
103 const row = doc.rates[rawId]
104 if (!row) return {}
105 const pricing = compileTokenCard(
106 {
107 input_tokens: row.input / 1e6,
108 output_tokens: row.output / 1e6,
109 cache_read_tokens: row.cacheRead / 1e6,
110 },
111 [],
112 {
113 url: DEEPSEEK_PRICING_URL,
114 hash: doc.hash,
115 extractedAt: doc.extractedAt,
116 },
117 )
118 if (!pricing) return {}
119 return { pricing }
120 }