Open History to see the last commit
1/**
2 * Reasoning controls and the chat request map, read on every poll.
3 *
4 * The reasoning page
5 * (https://inference-docs.cerebras.ai/capabilities/reasoning.md) lists each
6 * model under "Model behavior". That section's value table is the effort
7 * list. A behavior of "Disables reasoning" is the off value; "Not supported"
8 * is rejected; "always enables reasoning" or a rejected `none` is
9 * `mandatory`. A section that says the API ignores `reasoning_effort` is
10 * not a control. `mandatory` stays unset unless that section states it.
11 *
12 * The chat spec
13 * (https://inference-docs.cerebras.ai/api-reference/openapi.yaml) names
14 * `max_completion_tokens` (`max_tokens` is its alias) and says developer
15 * messages are supported only by the ids in that sentence.
16 */
17import { assertParsed, cachedDocs } from './model-facts.ts'
18import { reasoningFactsFor } from './reasoning-config.ts'
19import type { ChatRequestMap, EffortLevelMap } from './request-map.ts'
20import { fetchText, sha256Text } from './types.ts'
21import type { ModelInfo, ModelReasoning } from './types.ts'
22
23export const CEREBRAS_REASONING_URL =
24 'https://inference-docs.cerebras.ai/capabilities/reasoning.md'
25export const CEREBRAS_CHAT_SPEC_URL =
26 'https://inference-docs.cerebras.ai/api-reference/openapi.yaml'
27
28export interface CerebrasReasoningDoc {
29 configured: Map<string, ModelReasoning>
30 /** Accepts `reasoning_effort` and ignores it. No reasoning object. */
31 ignored: Array<string>
32}
33
34export interface CerebrasChatSpec {
35 maxTokensField: 'max_completion_tokens' | 'max_tokens'
36 /** Ids the spec says may send `role: "developer"`. */
37 developerIds: Array<string>
38}
39
40interface SummaryRow {
41 name: string
42 /** Null when the summary says the effort is not configurable. */
43 defaultEffort: string | null
44}
45
46function tableCells(line: string): Array<string> | null {
47 const trimmed = line.trim()
48 if (!trimmed.startsWith('|') || !trimmed.endsWith('|')) return null
49 return trimmed
50 .slice(1, -1)
51 .split('|')
52 .map((cell) => cell.trim())
53}
54
55function isSeparator(cells: Array<string>): boolean {
56 return cells.every((cell) => /^:?-+:?$/.test(cell))
57}
58
59function markdownTables(markdown: string): Array<Array<Array<string>>> {
60 const tables: Array<Array<Array<string>>> = []
61 let current: Array<Array<string>> | null = null
62 for (const line of markdown.split('\n')) {
63 const cells = tableCells(line)
64 if (!cells) {
65 if (current) tables.push(current)
66 current = null
67 continue
68 }
69 if (isSeparator(cells)) continue
70 current ??= []
71 current.push(cells)
72 }
73 if (current) tables.push(current)
74 return tables
75}
76
77function summaryName(cell: string): string {
78 const name = cell.match(/^\[([^\]]+)\]\(#[^)]+\)$/)?.[1]
79 if (!name) {
80 throw new Error(`cerebras reasoning: model cell has no anchor: ${cell}`)
81 }
82 return name
83}
84
85function summaryDefault(cell: string): string | null {
86 if (/^not configurable$/i.test(cell)) return null
87 const token = cell.match(
88 /^`([a-z][a-z0-9]*)`(?:\s*\((?:disabled|default)\))?$/,
89 )?.[1]
90 if (!token) {
91 throw new Error(`cerebras reasoning: unread default effort: ${cell}`)
92 }
93 return token
94}
95
96/** The supported-models table. Its default has to match the model section. */
97function supportedModels(markdown: string): Array<SummaryRow> {
98 const tables = markdownTables(markdown).filter((table) => {
99 const header = table[0]
100 return (
101 header?.length === 3 &&
102 header[0]?.toLowerCase() === 'model' &&
103 header[1]?.toLowerCase() === 'default effort' &&
104 header[2]?.toLowerCase() === 'availability'
105 )
106 })
107 if (tables.length === 0) {
108 throw new Error('cerebras reasoning: no supported-models table')
109 }
110 if (tables.length > 1) {
111 throw new Error('cerebras reasoning: more than one supported-models table')
112 }
113 const rows = tables[0]?.slice(1) ?? []
114 if (rows.length === 0) {
115 throw new Error('cerebras reasoning: supported-models table is empty')
116 }
117 return rows.map((cells) => {
118 if (cells.length !== 3) {
119 throw new Error(
120 `cerebras reasoning: short summary row: ${cells.join(' | ')}`,
121 )
122 }
123 return {
124 name: summaryName(cells[0] ?? ''),
125 defaultEffort: summaryDefault(cells[1] ?? ''),
126 }
127 })
128}
129
130function modelSections(
131 markdown: string,
132): Array<{ heading: string; body: string }> {
133 const lines = markdown.split('\n')
134 const start = lines.findIndex((line) => line.trim() === '## Model behavior')
135 if (start < 0) {
136 throw new Error('cerebras reasoning: no model behavior section')
137 }
138 let end = lines.length
139 for (let index = start + 1; index < lines.length; index++) {
140 if (/^## [^#]/.test(lines[index] ?? '')) {
141 end = index
142 break
143 }
144 }
145 const parts = lines
146 .slice(start + 1, end)
147 .join('\n')
148 .split(/^### /m)
149 if (/^\|/m.test(parts[0] ?? '')) {
150 throw new Error('cerebras reasoning: unread table before the first model')
151 }
152 const sections = parts.slice(1).map((part) => {
153 const breakAt = part.indexOf('\n')
154 const heading = (breakAt < 0 ? part : part.slice(0, breakAt)).trim()
155 if (heading === '') {
156 throw new Error('cerebras reasoning: empty model heading')
157 }
158 return { heading, body: breakAt < 0 ? '' : part.slice(breakAt + 1) }
159 })
160 if (sections.length === 0) {
161 throw new Error('cerebras reasoning: no model sections')
162 }
163 return sections
164}
165
166/** The first backtick is the model id. A later `reasoning_effort` is not. */
167function sectionModelId(heading: string, body: string): string {
168 const id = body.match(/`([^`]+)`/)?.[1]
169 if (!id || !/^[a-z0-9][a-z0-9.-]*$/.test(id)) {
170 throw new Error(`cerebras reasoning: ${heading} names no model id`)
171 }
172 return id
173}
174
175function valueRows(
176 id: string,
177 body: string,
178): Array<{ value: string; behavior: string }> {
179 const rows: Array<{ value: string; behavior: string }> = []
180 let open = false
181 let tables = 0
182 for (const line of body.split('\n')) {
183 const cells = tableCells(line)
184 if (!cells) {
185 open = false
186 continue
187 }
188 if (isSeparator(cells)) continue
189 const header =
190 cells.length === 2 &&
191 cells[0]?.toLowerCase() === 'value' &&
192 cells[1]?.toLowerCase() === 'behavior'
193 if (header) {
194 tables += 1
195 if (tables > 1) {
196 throw new Error(
197 `cerebras reasoning: ${id} has more than one effort table`,
198 )
199 }
200 open = true
201 continue
202 }
203 if (!open || cells.length !== 2) {
204 throw new Error(`cerebras reasoning: ${id} has an unread table`)
205 }
206 rows.push({ value: cells[0] ?? '', behavior: cells[1] ?? '' })
207 }
208 if (tables === 0) {
209 throw new Error(`cerebras reasoning: ${id} has no effort table`)
210 }
211 if (rows.length === 0) {
212 throw new Error(`cerebras reasoning: ${id} effort table is empty`)
213 }
214 return rows
215}
216
217function ignoresEffort(body: string): boolean {
218 return (
219 /accepts `reasoning_effort`[\s\S]{0,160}?ignores its value/i.test(body) ||
220 /accepted but ignored/i.test(body)
221 )
222}
223
224function readIgnored(
225 id: string,
226 rows: Array<{ value: string; behavior: string }>,
227): void {
228 for (const row of rows) {
229 if (row.value.startsWith('`')) {
230 throw new Error(
231 `cerebras reasoning: ${id} ignores reasoning_effort but lists ${row.value}`,
232 )
233 }
234 if (!/^(?:omitted|any accepted value)\b/i.test(row.value)) {
235 throw new Error(
236 `cerebras reasoning: ${id} unread ignored value: ${row.value}`,
237 )
238 }
239 if (!/keeps reasoning enabled/i.test(row.behavior)) {
240 throw new Error(
241 `cerebras reasoning: ${id} unread ignored behavior: ${row.behavior}`,
242 )
243 }
244 }
245}
246
247function behaviorKind(
248 id: string,
249 cell: string,
250): 'disable' | 'accept' | 'reject' {
251 if (/^disables reasoning\.?$/i.test(cell)) return 'disable'
252 if (/^not supported\.?$/i.test(cell)) return 'reject'
253 if (/^selects\b/i.test(cell) || /^enables reasoning\b/i.test(cell)) {
254 return 'accept'
255 }
256 throw new Error(`cerebras reasoning: ${id} unread behavior: ${cell}`)
257}
258
259function effortTokens(
260 id: string,
261 cell: string,
262): { tokens: Array<string>; defaultToken: string | null } {
263 const parts = cell
264 .split(',')
265 .map((part) => part.trim())
266 .filter((part) => part !== '')
267 if (parts.length === 0) {
268 throw new Error(`cerebras reasoning: ${id} unread effort cell: ${cell}`)
269 }
270 const tokens: Array<string> = []
271 let defaultToken: string | null = null
272 for (const part of parts) {
273 const match = part.match(/^`([a-z][a-z0-9]*)`(?:\s*\((default)\))?$/)
274 const token = match?.[1]
275 if (!token || tokens.includes(token)) {
276 throw new Error(`cerebras reasoning: ${id} unread effort cell: ${cell}`)
277 }
278 tokens.push(token)
279 if (match[2]) {
280 if (defaultToken) {
281 throw new Error(`cerebras reasoning: ${id} marks two defaults`)
282 }
283 defaultToken = token
284 }
285 }
286 return { tokens, defaultToken }
287}
288
289function reasoningFrom(
290 id: string,
291 body: string,
292 rows: Array<{ value: string; behavior: string }>,
293 summaryDefaultEffort: string,
294): ModelReasoning {
295 const efforts: Array<string> = []
296 const rejected: Array<string> = []
297 let defaultToken: string | null = null
298 let disables = false
299 for (const row of rows) {
300 const kind = behaviorKind(id, row.behavior)
301 const parsed = effortTokens(id, row.value)
302 if (parsed.defaultToken) {
303 if (kind === 'reject') {
304 throw new Error(
305 `cerebras reasoning: ${id} default ${parsed.defaultToken} is not supported`,
306 )
307 }
308 if (defaultToken) {
309 throw new Error(`cerebras reasoning: ${id} marks two defaults`)
310 }
311 defaultToken = parsed.defaultToken
312 }
313 for (const token of parsed.tokens) {
314 if (efforts.includes(token) || rejected.includes(token)) {
315 throw new Error(`cerebras reasoning: ${id} lists ${token} twice`)
316 }
317 if (kind === 'reject') rejected.push(token)
318 else efforts.push(token)
319 }
320 if (kind === 'disable') disables = true
321 }
322 if (efforts.length === 0) {
323 throw new Error(`cerebras reasoning: ${id} lists no effort values`)
324 }
325 if (!defaultToken || !efforts.includes(defaultToken)) {
326 throw new Error(`cerebras reasoning: ${id} marks no accepted default`)
327 }
328 if (defaultToken !== summaryDefaultEffort) {
329 throw new Error(
330 `cerebras reasoning: ${id} default is ${defaultToken} but the summary says ${summaryDefaultEffort}`,
331 )
332 }
333 const always = /always enables reasoning/i.test(body)
334 if (disables && always) {
335 throw new Error(
336 `cerebras reasoning: ${id} always enables reasoning but a value disables it`,
337 )
338 }
339 const proseOff = /set `reasoning_effort` to `none`/i.test(body)
340 // `none` that disables, or a stated always-on / rejected `none`. Nothing
341 // else sets mandatory: a bare effort list states no off switch.
342 const mandatory = disables
343 ? false
344 : always || rejected.includes('none')
345 ? true
346 : null
347 if (mandatory === null) {
348 throw new Error(
349 `cerebras reasoning: ${id} does not state whether reasoning can be disabled`,
350 )
351 }
352 if (proseOff && (mandatory || !efforts.includes('none'))) {
353 throw new Error(
354 `cerebras reasoning: ${id} says to send none but the table disagrees`,
355 )
356 }
357 if (mandatory && efforts.includes('none')) {
358 throw new Error(
359 `cerebras reasoning: ${id} cannot be disabled but lists none`,
360 )
361 }
362 if (!mandatory && !efforts.includes('none')) {
363 throw new Error(
364 `cerebras reasoning: ${id} can be disabled but lists no none`,
365 )
366 }
367 return { mode: 'effort', mandatory, efforts }
368}
369
370/**
371 * Per-model sections under "Model behavior". The summary table only checks
372 * that every listed model has a section and that its default matches.
373 */
374export function parseCerebrasReasoning(markdown: string): CerebrasReasoningDoc {
375 const text = markdown.replace(/```[\s\S]*?```/g, '')
376 const summary = supportedModels(text)
377 const sections = modelSections(text)
378 if (sections.length !== summary.length) {
379 throw new Error(
380 `cerebras reasoning: ${sections.length} model sections for ${summary.length} summary rows`,
381 )
382 }
383 const configured = new Map<string, ModelReasoning>()
384 const ignored: Array<string> = []
385 for (let index = 0; index < sections.length; index++) {
386 const section = sections[index]
387 const row = summary[index]
388 if (!section || !row || section.heading !== row.name) {
389 throw new Error(
390 `cerebras reasoning: section ${section?.heading ?? '(missing)'} is not summary row ${row?.name ?? '(missing)'}`,
391 )
392 }
393 const id = sectionModelId(section.heading, section.body)
394 if (configured.has(id) || ignored.includes(id)) {
395 throw new Error(`cerebras reasoning: duplicate id ${id}`)
396 }
397 const values = valueRows(id, section.body)
398 if (ignoresEffort(section.body)) {
399 readIgnored(id, values)
400 if (row.defaultEffort !== null) {
401 throw new Error(
402 `cerebras reasoning: ${id} ignores reasoning_effort but the summary default is ${row.defaultEffort}`,
403 )
404 }
405 ignored.push(id)
406 continue
407 }
408 if (row.defaultEffort === null) {
409 throw new Error(
410 `cerebras reasoning: ${id} summary says not configurable but the section lists efforts`,
411 )
412 }
413 configured.set(
414 id,
415 reasoningFrom(id, section.body, values, row.defaultEffort),
416 )
417 }
418 return { configured, ignored }
419}
420
421function property(yaml: string, name: string): boolean {
422 return new RegExp(`^[ \\t]+${name}:[ \\t]*$`, 'm').test(yaml)
423}
424
425/**
426 * Output-cap field and the models allowed to send `developer`. Throws when
427 * the spec no longer says which field is the alias, or which models take
428 * the developer role.
429 */
430export function parseCerebrasChatSpec(yaml: string): CerebrasChatSpec {
431 const completion = property(yaml, 'max_completion_tokens')
432 const alias = property(yaml, 'max_tokens')
433 if (!completion && !alias) {
434 throw new Error('cerebras spec: no max token field')
435 }
436 if (alias) {
437 const aliasOf =
438 /max_tokens:[\s\S]{0,400}?An alias for `max_completion_tokens`/.test(yaml)
439 if (!aliasOf) {
440 throw new Error(
441 'cerebras spec: max_tokens is not an alias of max_completion_tokens',
442 )
443 }
444 }
445 if (!completion) {
446 return { maxTokensField: 'max_tokens', developerIds: developerIds(yaml) }
447 }
448 return {
449 maxTokensField: 'max_completion_tokens',
450 developerIds: developerIds(yaml),
451 }
452}
453
454function developerIds(yaml: string): Array<string> {
455 const sentence = yaml.match(
456 /Developer messages are supported only by ([^.]+)\./,
457 )?.[1]
458 if (!sentence) {
459 throw new Error('cerebras spec: developer-role sentence missing')
460 }
461 const ids = [...sentence.matchAll(/`([^`]+)`/g)].map(
462 (match) => match[1] ?? '',
463 )
464 if (ids.length === 0 || ids.some((id) => id === '')) {
465 throw new Error('cerebras spec: developer-role sentence names no model')
466 }
467 return ids
468}
469
470function levelsFor(efforts: Array<string>, off: string | null): EffortLevelMap {
471 return {
472 off,
473 minimal: efforts.includes('minimal') ? 'minimal' : null,
474 low: efforts.includes('low') ? 'low' : null,
475 medium: efforts.includes('medium') ? 'medium' : null,
476 high: efforts.includes('high') ? 'high' : null,
477 xhigh: efforts.includes('xhigh') ? 'xhigh' : null,
478 max: efforts.includes('max') ? 'max' : null,
479 }
480}
481
482/** `on` is effort high. A model that does not accept `high` has no such body. */
483export function cerebrasThinking(
484 efforts: Array<string>,
485): ChatRequestMap['thinking'] {
486 if (!efforts.includes('high')) return null
487 const off = efforts.includes('none') ? 'none' : null
488 return {
489 on: { reasoning_effort: 'high' },
490 off: off === null ? null : { reasoning_effort: off },
491 levels: levelsFor(efforts, off),
492 }
493}
494
495export function cerebrasRequestMap(
496 rawId: string,
497 spec: CerebrasChatSpec,
498 reasoning: ModelReasoning | undefined,
499 ignored: boolean,
500): ChatRequestMap {
501 const efforts =
502 reasoning?.mode === 'effort' ? (reasoning.efforts ?? []) : null
503 return {
504 thinking: efforts ? cerebrasThinking(efforts) : null,
505 maxTokensField: spec.maxTokensField,
506 developerRole: spec.developerIds.includes(rawId),
507 replayReasoningContent: null,
508 store: null,
509 strictTools: null,
510 sessionAffinity: null,
511 cacheControl: null,
512 toolStream: null,
513 reasoningEffort: efforts !== null || ignored ? true : null,
514 }
515}
516
517interface CachedReasoning {
518 byId: Record<string, ModelReasoning>
519 ignored: Array<string>
520 hash: string
521}
522
523interface CachedSpec {
524 spec: CerebrasChatSpec
525 hash: string
526}
527
528/** Reasoning object plus the request map for one listed id. */
529export async function cerebrasChatFacts(
530 kv?: KVNamespace,
531): Promise<(rawId: string, capability: boolean) => Partial<ModelInfo>> {
532 const [reasoning, spec] = await Promise.all([
533 cachedDocs(kv, CEREBRAS_REASONING_URL, async () => {
534 const markdown = await fetchText(CEREBRAS_REASONING_URL)
535 const parsed = parseCerebrasReasoning(markdown)
536 assertParsed(parsed.configured, 'cerebras reasoning')
537 const cached: CachedReasoning = {
538 byId: Object.fromEntries(parsed.configured),
539 ignored: parsed.ignored,
540 hash: await sha256Text(markdown),
541 }
542 return cached
543 }),
544 cachedDocs(kv, CEREBRAS_CHAT_SPEC_URL, async () => {
545 const yaml = await fetchText(CEREBRAS_CHAT_SPEC_URL)
546 const cached: CachedSpec = {
547 spec: parseCerebrasChatSpec(yaml),
548 hash: await sha256Text(yaml),
549 }
550 return cached
551 }),
552 ])
553 return (rawId, capability) => {
554 const row = reasoning.byId[rawId]
555 return {
556 ...reasoningFactsFor(
557 rawId,
558 reasoning.byId,
559 { url: CEREBRAS_REASONING_URL, hash: reasoning.hash },
560 capability,
561 ),
562 requestMap: cerebrasRequestMap(
563 rawId,
564 spec.spec,
565 row,
566 reasoning.ignored.includes(rawId),
567 ),
568 }
569 }
570}