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

deepgram-pricing.ts

299 lines8.9 KB

1/**
2 * Deepgram Pay As You Go prices from https://deepgram.com/pricing (issues
3 * #121, #528). The page's JSON-LD `OfferCatalog` names each product, its
4 * plan (`category`), USD price, and unit (`priceSpecification.unitText`).
5 * Growth is a prepaid discount, not the list price. Add-ons, Voice Agent
6 * tiers, and Audio Intelligence are not model rates. Nova-2, Enhanced, and
7 * Base are absent from the current offers, so those rows stay null.
8 * Whisper Large is priced for pre-recorded only while the model also streams,
9 * so that id stays null rather than quoting one mode for both. Only the
10 * products `deepgramCard` reads are kept.
11 */
12import { compileUnitCard } from '@modelschemas/rate-card'
13import type { RateCard } from '@modelschemas/rate-card'
14​
15import { tagDocsFacts } from './fact-sources.ts'
16import { assertParsed, cachedDocs } from './model-facts.ts'
17import { fetchText, sha256Text } from './types.ts'
18import type { ModelInfo } from './types.ts'
19​
20export const DEEPGRAM_PRICING_URL = 'https://deepgram.com/pricing'
21​
22const PAYG = 'Pay as you go'
23​
24const REQUIRED = [
25 'Speech-to-text: Flux STT English (Streaming)',
26 'Speech-to-text: Flux STT Multilingual (Streaming)',
27 'Speech-to-text: Nova-3 Monolingual (Streaming)',
28 'Speech-to-text: Nova-3 Multilingual (Streaming)',
29 'Speech-to-text: Nova-3 Monolingual (Pre-recorded)',
30 'Speech-to-text: Nova-3 Multilingual (Pre-recorded)',
31 'Text-to-speech: Flux TTS',
32 'Text-to-speech: Aura-2',
33 'Text-to-speech: Aura-1',
34] as const
35​
36const LD_JSON =
37 /<script[^>]*type="application\/ld\+json"[^>]*>([\s\S]*?)<\/script>/g
38​
39/** The `unitText` a required product's rate must carry. */
40function unitFor(product: string): 'minute' | '1,000 characters' | null {
41 if (!(REQUIRED as ReadonlyArray<string>).includes(product)) return null
42 return product.startsWith('Speech-to-text: ') ? 'minute' : '1,000 characters'
44​
45function record(value: unknown): Record<string, unknown> | null {
46 return typeof value === 'object' && value !== null && !Array.isArray(value)
47 ? (value as Record<string, unknown>)
48 : null
50​
51function collectOffers(
52 node: unknown,
53 out: Array<Record<string, unknown>>,
54): void {
55 if (Array.isArray(node)) {
56 for (const item of node) collectOffers(item, out)
57 return
58 }
59 const obj = record(node)
60 if (!obj) return
61 if (obj['@type'] === 'Offer') out.push(obj)
62 for (const value of Object.values(obj)) collectOffers(value, out)
64​
65/**
66 * Pay As You Go product → USD per minute or per 1k characters. Empty when a
67 * required rate is missing or conflicting; throws on malformed JSON-LD.
68 */
69export function parseDeepgramPricing(html: string): Map<string, number> {
70 const offers: Array<Record<string, unknown>> = []
71 for (const match of html.matchAll(LD_JSON)) {
72 collectOffers(JSON.parse(match[1] ?? '') as unknown, offers)
73 }
74 const out = new Map<string, number>()
75 const suffix = ` — ${PAYG}`
76 for (const offer of offers) {
77 const name = offer.name
78 if (offer.category !== PAYG || typeof name !== 'string') continue
79 if (!name.endsWith(suffix)) continue
80 const product = name.slice(0, -suffix.length)
81 const spec = record(offer.priceSpecification)
82 const amount = spec?.price
83 if (
84 spec?.priceCurrency !== 'USD' ||
85 typeof amount !== 'number' ||
86 !Number.isFinite(amount) ||
87 amount <= 0 ||
88 amount !== offer.price
89 ) {
90 continue
91 }
92 const unit = unitFor(product)
93 if (!unit || spec.unitText !== unit) continue
94 const prior = out.get(product)
95 if (prior !== undefined && prior !== amount) return new Map()
96 out.set(product, amount)
97 }
98 if (REQUIRED.some((product) => !out.has(product))) return new Map()
99 return out
101​
102function perMinute(rates: Map<string, number>, product: string): number | null {
103 const amount = rates.get(product)
104 return amount === undefined ? null : amount / 60
106​
107function perCharacter(
108 rates: Map<string, number>,
109 product: string,
110): number | null {
111 const amount = rates.get(product)
112 return amount === undefined ? null : amount / 1000
114​
115/**
116 * One shared card for a model family. Nova-3 general bills monolingual and
117 * multilingual, and streaming and pre-recorded, at different published rates.
118 * The caller supplies those usage levers; they are not request fields.
119 */
120export function deepgramCard(
121 rawId: string,
122 rates: Map<string, number>,
123 source: RateCard['source'],
124): RateCard | null {
125 const listen = (
126 streaming: number | null,
127 preRecorded: number | null,
128 ): RateCard | null => {
129 if (streaming === null || preRecorded === null) return null
130 return compileUnitCard(
131 {
132 quantity: { param: 'audio_seconds', bound: 'usage' },
133 keys: [
134 {
135 param: 'listen_mode',
136 values: ['streaming', 'pre_recorded'],
137 bound: 'usage',
138 },
139 ],
140 rates: { streaming, pre_recorded: preRecorded },
141 },
142 source,
143 )
144 }
145​
146 if (rawId === 'flux-general-en') {
147 const streaming = perMinute(
148 rates,
149 'Speech-to-text: Flux STT English (Streaming)',
150 )
151 if (streaming === null) return null
152 return compileUnitCard(
153 {
154 quantity: { param: 'audio_seconds', bound: 'usage' },
155 rates: streaming,
156 },
157 source,
158 )
159 }
160 if (rawId === 'flux-general-multi') {
161 const streaming = perMinute(
162 rates,
163 'Speech-to-text: Flux STT Multilingual (Streaming)',
164 )
165 if (streaming === null) return null
166 return compileUnitCard(
167 {
168 quantity: { param: 'audio_seconds', bound: 'usage' },
169 rates: streaming,
170 },
171 source,
172 )
173 }
174 if (rawId.startsWith('flux-')) {
175 const characters = perCharacter(rates, 'Text-to-speech: Flux TTS')
176 if (characters === null) return null
177 return compileUnitCard(
178 {
179 quantity: { param: 'characters', bound: 'usage' },
180 rates: characters,
181 },
182 source,
183 )
184 }
185 if (rawId.startsWith('aura-2-')) {
186 const characters = perCharacter(rates, 'Text-to-speech: Aura-2')
187 if (characters === null) return null
188 return compileUnitCard(
189 {
190 quantity: { param: 'characters', bound: 'usage' },
191 rates: characters,
192 },
193 source,
194 )
195 }
196 if (rawId.startsWith('aura-')) {
197 const characters = perCharacter(rates, 'Text-to-speech: Aura-1')
198 if (characters === null) return null
199 return compileUnitCard(
200 {
201 quantity: { param: 'characters', bound: 'usage' },
202 rates: characters,
203 },
204 source,
205 )
206 }
207 if (rawId === 'nova-3' || rawId === 'nova-3-general') {
208 const streamingMono = perMinute(
209 rates,
210 'Speech-to-text: Nova-3 Monolingual (Streaming)',
211 )
212 const streamingMulti = perMinute(
213 rates,
214 'Speech-to-text: Nova-3 Multilingual (Streaming)',
215 )
216 const batchMono = perMinute(
217 rates,
218 'Speech-to-text: Nova-3 Monolingual (Pre-recorded)',
219 )
220 const batchMulti = perMinute(
221 rates,
222 'Speech-to-text: Nova-3 Multilingual (Pre-recorded)',
223 )
224 if (
225 streamingMono === null ||
226 streamingMulti === null ||
227 batchMono === null ||
228 batchMulti === null
229 ) {
230 return null
231 }
232 return compileUnitCard(
233 {
234 quantity: { param: 'audio_seconds', bound: 'usage' },
235 keys: [
236 {
237 param: 'listen_mode',
238 values: ['streaming', 'pre_recorded'],
239 bound: 'usage',
240 },
241 {
242 param: 'language_scope',
243 values: ['monolingual', 'multilingual'],
244 bound: 'usage',
245 },
246 ],
247 rates: {
248 streaming: {
249 monolingual: streamingMono,
250 multilingual: streamingMulti,
251 },
252 pre_recorded: {
253 monolingual: batchMono,
254 multilingual: batchMulti,
255 },
256 },
257 },
258 source,
259 )
260 }
261 if (rawId.startsWith('nova-3-')) {
262 return listen(
263 perMinute(rates, 'Speech-to-text: Nova-3 Monolingual (Streaming)'),
264 perMinute(rates, 'Speech-to-text: Nova-3 Monolingual (Pre-recorded)'),
265 )
266 }
267 return null
269​
270type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
271​
272export async function deepgramModelPricing(
273 kv?: KVNamespace,
274): Promise<(rawId: string) => PricedFacts> {
275 const doc = await cachedDocs(kv, DEEPGRAM_PRICING_URL, async () => {
276 const html = await fetchText(DEEPGRAM_PRICING_URL)
277 const parsed = parseDeepgramPricing(html)
278 assertParsed(parsed, 'deepgram pricing page')
279 return {
280 rates: Object.fromEntries(parsed),
281 hash: await sha256Text(html),
282 extractedAt: new Date().toISOString(),
283 }
284 })
285 const rates = new Map(Object.entries(doc.rates))
286 const source = {
287 url: DEEPGRAM_PRICING_URL,
288 hash: doc.hash,
289 extractedAt: doc.extractedAt,
290 }
291 return (rawId) => {
292 const pricing = deepgramCard(rawId, rates, source)
293 if (!pricing) return {}
294 return {
295 pricing,
296 factSources: tagDocsFacts({ pricing }, DEEPGRAM_PRICING_URL, doc.hash),
297 }
298 }