Open History to see the last commit
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 *
7 * As of 2026-10-20 a page's `.md` export renders `<ModelInfo>` as bare
8 * labels with no values (issue #381), so the HTML page is read: its RSC
9 * payload (`self.__next_f.push`) embeds the compiled MDX,
10 * `_jsx(ModelInfo,{…})` with the same props as template literals. It
11 * carries the body twice, and on some pages the second copy has no
12 * `pricing`, `contextLength`, or `maxOutput`, so the copy with `pricing`
13 * is read. The `<ModelInfo …/>` JSX (the MDX source) is still accepted.
14 */
15import { compileTokenCard } from '@modelschemas/rate-card'
16
17import { closing } from './compiled-mdx.ts'
18import { tagDocsFacts } from './fact-sources.ts'
19import {
20 assertParsed,
21 cachedDocs,
22 mapConcurrent,
23 tokenCount,
24} from './model-facts.ts'
25import { fetchText, sha256Text } from './types.ts'
26import type { ModelInfo } from './types.ts'
27
28export const CEREBRAS_CATALOG_URL =
29 'https://inference-docs.cerebras.ai/models/overview.md'
30
31const PAGE = (slug: string) =>
32 `https://inference-docs.cerebras.ai/models/${slug}`
33
34export interface CerebrasModelFacts {
35 inputPerMillion: number | null
36 outputPerMillion: number | null
37 modalities: { input: Array<string>; output: Array<string> } | null
38 capabilities: Array<string>
39 /** Paid window. A parenthetical integer beats `128k` → 128,000. */
40 contextWindow: number | null
41 /** Paid-tier cap. A parenthetical integer beats `40k` → 40,000. */
42 maxOutput: number | null
43}
44
45const FEATURES: Record<string, Array<string>> = {
46 Reasoning: ['reasoning'],
47 'Tool Calling': ['tools'],
48 'Structured Outputs': ['structured_outputs', 'response_format'],
49}
50
51/** A `"…"` (MDX source) or `` `…` `` (compiled MDX) string; quotes are not paired. */
52const STRING = '["`]([^"`]*)["`]'
53
54/**
55 * The prose sentence after `label`. It ends at its full stop, a newline
56 * (`\\n` once JSON-escaped in the payload), or the end of its template
57 * literal, so the context sentence never reaches the max output one.
58 */
59function proseSentence(page: string, label: RegExp): string | undefined {
60 const rest = page.match(
61 new RegExp(`${label.source}\\s*([^\\n\`]+)`, 'i'),
62 )?.[1]
63 return rest?.split(/\.\s|\\n/)[0]
64}
65
66function dollars(cell: string): number | null {
67 const match = cell.match(/\$(\d+(?:\.\d+)?)/)
68 return match?.[1] ? Number(match[1]) : null
69}
70
71/**
72 * `128K tokens (131,072) for paid` is 131072. The first `Nk (exact) for paid`
73 * wins, so a free-tier parenthetical earlier in the sentence is ignored.
74 */
75function paidParenthetical(sentence: string | undefined): number | null {
76 const exact = sentence?.match(
77 /(\d+(?:\.\d+)?)\s*k\s+tokens?\s*\(([\d,]+)\)\s+for paid\b/i,
78 )?.[2]
79 if (!exact) return null
80 const count = Number(exact.replace(/,/g, ''))
81 if (!Number.isFinite(count)) {
82 throw new Error(`cerebras model page: unreadable paid token count`)
83 }
84 return count
85}
86
87/**
88 * Paid context window. The prose parenthetical beats `<ModelInfo>` (`128k`
89 * → 128,000). An unreadable paid tier throws.
90 */
91function paidContextWindow(page: string, block: string): number | null {
92 const sentence = proseSentence(page, /context window:/)
93 const exact = paidParenthetical(sentence)
94 if (exact != null) return exact
95 const contextPaid = block.match(/contextLength(?:=\{\{|:\{)([^}]*)\}/)?.[1]
96 const paid = contextPaid?.match(new RegExp(`paidTiers:\\s*${STRING}`))?.[1]
97 if (paid === undefined) return null
98 if (paid.trim() === '' || /^n\/a$/i.test(paid.trim())) return null
99 const count = tokenCount(paid)
100 if (count == null) {
101 throw new Error(
102 `cerebras model page: unreadable paid context window "${paid}"`,
103 )
104 }
105 return count
106}
107
108/**
109 * Paid max output. `40K tokens (40,960) for paid` is 40960. Otherwise the
110 * `<ModelInfo>` paid tier (`40k` → 40,000). An unreadable tier throws.
111 */
112function paidMaxOutput(page: string, block: string): number | null {
113 const sentence = proseSentence(page, /max(?:imum)? output:/)
114 const exact = paidParenthetical(sentence)
115 if (exact != null) return exact
116 const paid = block.match(/maxOutput(?:=\{\{|:\{)([^}]*)\}/)?.[1]
117 if (!paid) return null
118 const tiers = paid.match(new RegExp(`paidTiers:\\s*${STRING}`))?.[1]
119 if (tiers === undefined) return null
120 if (tiers.trim() === '' || /^n\/a$/i.test(tiers.trim())) return null
121 const count = tokenCount(tiers)
122 if (count == null) {
123 throw new Error(
124 `cerebras model page: unreadable paid max output "${tiers}"`,
125 )
126 }
127 return count
128}
129
130function quotedList(block: string, key: string): Array<string> {
131 const match = block.match(
132 new RegExp(`${key}(?:=|:)?\\s*\\{?\\s*\\[([^\\]]*)\\]`),
133 )
134 if (!match?.[1]) return []
135 return [...match[1].matchAll(/["`]([^"`]+)["`]/g)].map(
136 (item) => item[1] ?? '',
137 )
138}
139
140/**
141 * The `<ModelInfo …/>` JSX, else the `{…}` props of each compiled
142 * `_jsx(s)(ModelInfo,{…})`: the copies with `pricing`, or all of them when
143 * none has it.
144 */
145function modelInfoBlocks(page: string): Array<string> {
146 const jsx = page.match(/<ModelInfo[\s\S]*?\/>/)?.[0]
147 if (jsx) return [jsx]
148 const blocks = [...page.matchAll(/_jsxs?\(ModelInfo,\{/g)].map((call) => {
149 const open = call.index + call[0].length - 1
150 return page.slice(open, closing(page, open, 'cerebras model page') + 1)
151 })
152 const priced = blocks.filter((block) => /\bpricing:\{/.test(block))
153 return priced.length > 0 ? priced : blocks
154}
155
156/**
157 * Catalog table: link slug plus the backticked API id. Links may end in
158 * `.md` (issue #437); the slug drops it so the HTML page is read. As of
159 * 2026-10-23 links carry the docs origin (issue #486).
160 */
161export function cerebrasCatalogRows(
162 markdown: string,
163): Array<{ slug: string; id: string }> {
164 const out: Array<{ slug: string; id: string }> = []
165 const re =
166 /\[[^\]]+\]\((?:https:\/\/inference-docs\.cerebras\.ai)?\/models\/([a-z0-9.-]+?)(?:\.md)?\)\s*\|\s*`([^`]+)`/g
167 for (const match of markdown.matchAll(re)) {
168 if (match[1] && match[2]) out.push({ slug: match[1], id: match[2] })
169 }
170 return out
171}
172
173/**
174 * Facts from the page's `<ModelInfo>`; null when it has none. Throws when
175 * two compiled copies with `pricing` state different facts.
176 */
177export function parseCerebrasModelPage(
178 page: string,
179): CerebrasModelFacts | null {
180 const [first, ...rest] = modelInfoBlocks(page).map((block) =>
181 blockFacts(page, block),
182 )
183 if (!first) return null
184 const stated = JSON.stringify(first)
185 if (rest.some((facts) => JSON.stringify(facts) !== stated)) {
186 throw new Error('cerebras model page: ModelInfo copies disagree')
187 }
188 return first
189}
190
191function blockFacts(page: string, block: string): CerebrasModelFacts {
192 const input = dollars(
193 block.match(new RegExp(`inputPrice:\\s*${STRING}`))?.[1] ?? '',
194 )
195 const output = dollars(
196 block.match(new RegExp(`outputPrice:\\s*${STRING}`))?.[1] ?? '',
197 )
198 const inputFormats = quotedList(block, 'inputFormats')
199 const outputFormats = quotedList(block, 'outputFormats')
200 const features = quotedList(block, 'features')
201 const capabilities = features.flatMap((feature) => FEATURES[feature] ?? [])
202 return {
203 inputPerMillion: input,
204 outputPerMillion: output,
205 modalities:
206 inputFormats.length > 0 || outputFormats.length > 0
207 ? { input: inputFormats, output: outputFormats }
208 : null,
209 capabilities,
210 contextWindow: paidContextWindow(page, block),
211 maxOutput: paidMaxOutput(page, block),
212 }
213}
214
215type Attached = Pick<
216 ModelInfo,
217 | 'pricing'
218 | 'modalities'
219 | 'capabilities'
220 | 'contextWindow'
221 | 'maxOutput'
222 | 'factSources'
223>
224
225export async function cerebrasModelFacts(
226 kv?: KVNamespace,
227): Promise<(rawId: string) => Attached> {
228 const doc = await cachedDocs(kv, CEREBRAS_CATALOG_URL, async () => {
229 const catalog = await fetchText(CEREBRAS_CATALOG_URL)
230 const rows = cerebrasCatalogRows(catalog)
231 assertParsed(new Map(rows.map((row) => [row.id, row])), 'cerebras catalog')
232 const pages = await mapConcurrent(rows, 4, async (row) => {
233 const url = PAGE(row.slug)
234 const html = await fetchText(url)
235 return { id: row.id, url, html, facts: parseCerebrasModelPage(html) }
236 })
237 const priced = pages.filter((page) => page.facts?.inputPerMillion)
238 assertParsed(
239 new Map(priced.map((page) => [page.id, page])),
240 'cerebras model pages',
241 )
242 const hash = await sha256Text(pages.map((page) => page.html).join('\n'))
243 return {
244 byId: Object.fromEntries(
245 pages.flatMap((page) =>
246 page.facts ? [[page.id, { ...page.facts, url: page.url }]] : [],
247 ),
248 ),
249 hash,
250 extractedAt: new Date().toISOString(),
251 }
252 })
253 return (rawId) => {
254 const row = doc.byId[rawId]
255 if (!row) return {}
256 const rates: Record<string, number> = {}
257 if (row.inputPerMillion) rates.input_tokens = row.inputPerMillion / 1e6
258 if (row.outputPerMillion) rates.output_tokens = row.outputPerMillion / 1e6
259 const pricing = compileTokenCard(rates, [], {
260 url: row.url,
261 hash: doc.hash,
262 extractedAt: doc.extractedAt,
263 })
264 const facts = {
265 ...(pricing ? { pricing } : {}),
266 ...(row.modalities ? { modalities: row.modalities } : {}),
267 ...(row.capabilities.length > 0
268 ? { capabilities: row.capabilities }
269 : {}),
270 ...(row.contextWindow ? { contextWindow: row.contextWindow } : {}),
271 ...(row.maxOutput != null ? { maxOutput: row.maxOutput } : {}),
272 }
273 return { ...facts, factSources: tagDocsFacts(facts, row.url, doc.hash) }
274 }
275}