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

groq-pricing.ts

166 lines5.9 KB

1/**
2 * Groq prices from GroqCloud's supported-models page (issue #73). The
3 * markdown mirror is one table per lifecycle (production, preview) whose
4 * price cell is `$0.15 input$0.60 output`, `$0.111 per hour`, or
5 * `$40.00 per 1M characters`. "Contact Sales" publishes no number, so that
6 * row gets no card. The models table has no cached-input column: the
7 * prompt-caching doc lists the models that cache, and each of their model
8 * pages states its own `Cached Input` price (issue #411), read as
9 * `cache_read_tokens`. A listed caching model whose page states none
10 * throws. A price cell in any other shape refuses that model rather than
11 * quoting part of it. A page that prices nothing throws.
12 */
13import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
14import type { UnitCardSpec } from '@modelschemas/rate-card'
15​
16import { tagDocsFacts } from './fact-sources.ts'
17import {
18 assertParsed,
19 cachedDocs,
20 markdownSection,
21 markdownTableRows,
22} from './model-facts.ts'
23import { fetchText, sha256Text } from './types.ts'
24import type { ModelInfo } from './types.ts'
25​
26export const GROQ_PRICING_URL = 'https://console.groq.com/docs/models.md'
27export const GROQ_CACHING_URL =
28 'https://console.groq.com/docs/prompt-caching.md'
29export const groqModelPageUrl = (id: string): string =>
30 `https://console.groq.com/docs/model/${id}.md`
31​
32export type GroqPrice =
33 | { kind: 'tokens'; rates: Record<string, number> }
34 | { kind: 'unit'; unit: UnitCardSpec }
35​
36/** API id glued on after the docs link. `Enterprise` is a badge, not the id. */
37export function groqModelId(cell: string): string | null {
38 // The cell leads with an image link; the model id follows the docs link.
39 const matches = [
40 ...cell.matchAll(/\]\([^)]+\)([A-Za-z0-9][A-Za-z0-9./_-]*)/g),
41 ]
42 const id = matches.at(-1)?.[1]?.replace(/^Enterprise(?=[a-z0-9])/, '')
43 return id && id.length > 0 ? id : null
45​
46/**
47 * One price cell. `null` skips a row with no public price. A cell that
48 * quotes `$` in a shape this does not know refuses the model (`'refuse'`).
49 */
50export function parseGroqPrice(cell: string): GroqPrice | null | 'refuse' {
51 const text = cell.replace(/\\/g, '').replace(/\s+/g, '')
52 if (text === '' || text === '-' || /^contactsales$/i.test(text)) {
53 return null
54 }
55 const tokens = text.match(/^\$(\d+(?:\.\d+)?)input\$(\d+(?:\.\d+)?)output$/)
56 if (tokens?.[1] && tokens[2]) {
57 return {
58 kind: 'tokens',
59 rates: {
60 input_tokens: Number(tokens[1]) / 1e6,
61 output_tokens: Number(tokens[2]) / 1e6,
62 },
63 }
64 }
65 const hour = text.match(/^\$(\d+(?:\.\d+)?)perhour$/)
66 if (hour?.[1]) {
67 return {
68 kind: 'unit',
69 unit: {
70 quantity: { param: 'audio_seconds', bound: 'usage' },
71 rates: Number(hour[1]) / 3600,
72 },
73 }
74 }
75 const characters = text.match(/^\$(\d+(?:\.\d+)?)per1Mcharacters$/)
76 if (characters?.[1]) {
77 return {
78 kind: 'unit',
79 unit: {
80 quantity: { param: 'characters', bound: 'usage' },
81 rates: Number(characters[1]) / 1e6,
82 },
83 }
84 }
85 return text.includes('$') ? 'refuse' : null
87​
88/** Model id → the price the models page states. Refused rows are absent. */
89export function parseGroqPricing(markdown: string): Map<string, GroqPrice> {
90 const out = new Map<string, GroqPrice>()
91 for (const cells of markdownTableRows(markdown)) {
92 const id = groqModelId(cells[0] ?? '')
93 const price = parseGroqPrice(cells[2] ?? '')
94 if (!id || price === null || price === 'refuse' || out.has(id)) continue
95 out.set(id, price)
96 }
97 return out
99​
100/** Model ids in the prompt-caching doc's Supported Models table; throws on none. */
101export function parseGroqCachingModels(markdown: string): Array<string> {
102 const ids = markdownTableRows(markdownSection(markdown, '[Supported Models]'))
103 .map((cells) => cells[0] ?? '')
104 .filter((id) => id !== 'Model ID' && /^[a-z0-9][a-z0-9./_-]*$/i.test(id))
105 if (ids.length === 0) {
106 throw new Error('groq prompt-caching doc: no Supported Models rows')
107 }
108 return ids
110​
111/** USD per token from a model page's `Cached Input` price; throws on none. */
112export function parseGroqCachedInput(markdown: string, id: string): number {
113 const match = markdown.match(/^Cached Input\s*\n\s*\$(\d+(?:\.\d+)?)\s*$/m)
114 if (!match?.[1]) {
115 throw new Error(`groq model page ${id}: no Cached Input price`)
116 }
117 return Number(match[1]) / 1e6
119​
120type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
121​
122/** Card lookup by listed model id. */
123export async function groqModelPricing(
124 kv: KVNamespace | undefined,
125 cached: typeof cachedDocs = cachedDocs,
126): Promise<(rawId: string) => PricedFacts> {
127 const doc = await cached(kv, GROQ_PRICING_URL, async () => {
128 const markdown = await fetchText(GROQ_PRICING_URL)
129 const parsed = parseGroqPricing(markdown)
130 assertParsed(parsed, 'groq models page')
131 const caching = await fetchText(GROQ_CACHING_URL)
132 const pages = await Promise.all(
133 parseGroqCachingModels(caching).map(async (id) => {
134 const price = parsed.get(id)
135 // A caching model the models page does not token-price has no card.
136 if (price?.kind !== 'tokens') return ''
137 const page = await fetchText(groqModelPageUrl(id))
138 price.rates.cache_read_tokens = parseGroqCachedInput(page, id)
139 return page
140 }),
141 )
142 return {
143 rates: Object.fromEntries(parsed),
144 hash: await sha256Text([markdown, caching, ...pages].join('\n')),
145 extractedAt: new Date().toISOString(),
146 }
147 })
148 return (rawId) => {
149 const row = doc.rates[rawId]
150 if (!row) return {}
151 const source = {
152 url: GROQ_PRICING_URL,
153 hash: doc.hash,
154 extractedAt: doc.extractedAt,
155 }
156 const pricing =
157 row.kind === 'unit'
158 ? compileUnitCard(row.unit, source)
159 : compileTokenCard(row.rates, [], source)
160 if (!pricing) return {}
161 return {
162 pricing,
163 factSources: tagDocsFacts({ pricing }, GROQ_PRICING_URL, doc.hash),
164 }
165 }