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

cerebras-pricing.ts

215 lines7.2 KB

1/**
2 * Cerebras model pages linked from the catalog (issue #109). Each page's
3 * `<ModelInfo>` states the API id, paid prices per million tokens, the
4 * paid output cap, input and output formats, and feature names. The
5 * marketing pricing page is a client render and is not parsed.
6 */
7import { compileTokenCard } from '@modelschemas/rate-card'
8​
9import { tagDocsFacts } from './fact-sources.ts'
10import {
11 assertParsed,
12 cachedDocs,
13 mapConcurrent,
14 tokenCount,
15} from './model-facts.ts'
16import { fetchText, sha256Text } from './types.ts'
17import type { ModelInfo } from './types.ts'
18​
19export const CEREBRAS_CATALOG_URL =
20 'https://inference-docs.cerebras.ai/models/overview.md'
21​
22const PAGE = (slug: string) =>
23 `https://inference-docs.cerebras.ai/models/${slug}.md`
24​
25export interface CerebrasModelFacts {
26 inputPerMillion: number | null
27 outputPerMillion: number | null
28 modalities: { input: Array<string>; output: Array<string> } | null
29 capabilities: Array<string>
30 /** Paid window. A parenthetical integer beats `128k` → 128,000. */
31 contextWindow: number | null
32 /** Paid-tier cap. A parenthetical integer beats `40k` → 40,000. */
33 maxOutput: number | null
35​
36const FEATURES: Record<string, Array<string>> = {
37 Reasoning: ['reasoning'],
38 'Tool Calling': ['tools'],
39 'Structured Outputs': ['structured_outputs', 'response_format'],
41​
42function dollars(cell: string): number | null {
43 const match = cell.match(/\$(\d+(?:\.\d+)?)/)
44 return match?.[1] ? Number(match[1]) : null
46​
47/**
48 * `128K tokens (131,072) for paid` is 131072. The first `Nk (exact) for paid`
49 * wins, so a free-tier parenthetical earlier in the sentence is ignored.
50 */
51function paidParenthetical(sentence: string | undefined): number | null {
52 const exact = sentence?.match(
53 /(\d+(?:\.\d+)?)\s*k\s+tokens?\s*\(([\d,]+)\)\s+for paid\b/i,
54 )?.[2]
55 if (!exact) return null
56 const count = Number(exact.replace(/,/g, ''))
57 if (!Number.isFinite(count)) {
58 throw new Error(`cerebras model page: unreadable paid token count`)
59 }
60 return count
62​
63/**
64 * Paid context window. The prose parenthetical beats `<ModelInfo>` (`128k`
65 * → 128,000). An unreadable paid tier throws.
66 */
67function paidContextWindow(markdown: string, block: string): number | null {
68 const sentence = markdown.match(/context window:\s*([^\n]+)/i)?.[1]
69 const exact = paidParenthetical(sentence)
70 if (exact != null) return exact
71 const contextPaid = block.match(/contextLength=\{\{([\s\S]*?)\}\}/)?.[1]
72 const paid = contextPaid?.match(/paidTiers:\s*"([^"]*)"/)?.[1]
73 if (paid === undefined) return null
74 if (paid.trim() === '' || /^n\/a$/i.test(paid.trim())) return null
75 const count = tokenCount(paid)
76 if (count == null) {
77 throw new Error(
78 `cerebras model page: unreadable paid context window "${paid}"`,
79 )
80 }
81 return count
83​
84/**
85 * Paid max output. `40K tokens (40,960) for paid` is 40960. Otherwise the
86 * `<ModelInfo>` paid tier (`40k` → 40,000). An unreadable tier throws.
87 */
88function paidMaxOutput(markdown: string, block: string): number | null {
89 const sentence = markdown.match(/max(?:imum)? output:\s*([^\n]+)/i)?.[1]
90 const exact = paidParenthetical(sentence)
91 if (exact != null) return exact
92 const paid = block.match(/maxOutput=\{\{([\s\S]*?)\}\}/)?.[1]
93 if (!paid) return null
94 const tiers = paid.match(/paidTiers:\s*"([^"]*)"/)?.[1]
95 if (tiers === undefined) return null
96 if (tiers.trim() === '' || /^n\/a$/i.test(tiers.trim())) return null
97 const count = tokenCount(tiers)
98 if (count == null) {
99 throw new Error(
100 `cerebras model page: unreadable paid max output "${tiers}"`,
101 )
102 }
103 return count
105​
106function quotedList(block: string, key: string): Array<string> {
107 const match = block.match(
108 new RegExp(`${key}(?:=|:)?\\s*\\{?\\s*\\[([^\\]]*)\\]`),
109 )
110 if (!match?.[1]) return []
111 return [...match[1].matchAll(/"([^"]+)"/g)].map((item) => item[1] ?? '')
113​
114/** Catalog table: link slug plus the backticked API id. */
115export function cerebrasCatalogRows(
116 markdown: string,
117): Array<{ slug: string; id: string }> {
118 const out: Array<{ slug: string; id: string }> = []
119 const re = /\[[^\]]+\]\(\/models\/([a-z0-9.-]+)\)\s*\|\s*`([^`]+)`/g
120 for (const match of markdown.matchAll(re)) {
121 if (match[1] && match[2]) out.push({ slug: match[1], id: match[2] })
122 }
123 return out
125​
126export function parseCerebrasModelPage(
127 markdown: string,
128): CerebrasModelFacts | null {
129 const block = markdown.match(/<ModelInfo[\s\S]*?\/>/)?.[0]
130 if (!block) return null
131 const input = dollars(block.match(/inputPrice:\s*"([^"]+)"/)?.[1] ?? '')
132 const output = dollars(block.match(/outputPrice:\s*"([^"]+)"/)?.[1] ?? '')
133 const inputFormats = quotedList(block, 'inputFormats')
134 const outputFormats = quotedList(block, 'outputFormats')
135 const features = quotedList(block, 'features')
136 const capabilities = features.flatMap((feature) => FEATURES[feature] ?? [])
137 return {
138 inputPerMillion: input,
139 outputPerMillion: output,
140 modalities:
141 inputFormats.length > 0 || outputFormats.length > 0
142 ? { input: inputFormats, output: outputFormats }
143 : null,
144 capabilities,
145 contextWindow: paidContextWindow(markdown, block),
146 maxOutput: paidMaxOutput(markdown, block),
147 }
149​
150type Attached = Pick<
151 ModelInfo,
152 | 'pricing'
153 | 'modalities'
154 | 'capabilities'
155 | 'contextWindow'
156 | 'maxOutput'
157 | 'factSources'
159​
160export async function cerebrasModelFacts(
161 kv?: KVNamespace,
162): Promise<(rawId: string) => Attached> {
163 const doc = await cachedDocs(kv, CEREBRAS_CATALOG_URL, async () => {
164 const catalog = await fetchText(CEREBRAS_CATALOG_URL)
165 const rows = cerebrasCatalogRows(catalog)
166 assertParsed(new Map(rows.map((row) => [row.id, row])), 'cerebras catalog')
167 const pages = await mapConcurrent(rows, 4, async (row) => {
168 const url = PAGE(row.slug)
169 const markdown = await fetchText(url)
170 return {
171 id: row.id,
172 url,
173 markdown,
174 facts: parseCerebrasModelPage(markdown),
175 }
176 })
177 const priced = pages.filter((page) => page.facts?.inputPerMillion)
178 assertParsed(
179 new Map(priced.map((page) => [page.id, page])),
180 'cerebras model pages',
181 )
182 const hash = await sha256Text(pages.map((page) => page.markdown).join('\n'))
183 return {
184 byId: Object.fromEntries(
185 pages.flatMap((page) =>
186 page.facts ? [[page.id, { ...page.facts, url: page.url }]] : [],
187 ),
188 ),
189 hash,
190 extractedAt: new Date().toISOString(),
191 }
192 })
193 return (rawId) => {
194 const row = doc.byId[rawId]
195 if (!row) return {}
196 const rates: Record<string, number> = {}
197 if (row.inputPerMillion) rates.input_tokens = row.inputPerMillion / 1e6
198 if (row.outputPerMillion) rates.output_tokens = row.outputPerMillion / 1e6
199 const pricing = compileTokenCard(rates, [], {
200 url: row.url,
201 hash: doc.hash,
202 extractedAt: doc.extractedAt,
203 })
204 const facts = {
205 ...(pricing ? { pricing } : {}),
206 ...(row.modalities ? { modalities: row.modalities } : {}),
207 ...(row.capabilities.length > 0
208 ? { capabilities: row.capabilities }
209 : {}),
210 ...(row.contextWindow ? { contextWindow: row.contextWindow } : {}),
211 ...(row.maxOutput != null ? { maxOutput: row.maxOutput } : {}),
212 }
213 return { ...facts, factSources: tagDocsFacts(facts, row.url, doc.hash) }
214 }