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

cerebras-reasoning.ts

274 lines8.8 KB

1/**
2 * Reasoning controls and the chat request map, read on every poll.
3 *
4 * The reasoning table
5 * (https://inference-docs.cerebras.ai/capabilities/reasoning.md) names each
6 * model's `reasoning_effort` values and whether reasoning can be disabled.
7 * A value list is effort mode. "Accepted but ignored" is not a control.
8 *
9 * The chat spec
10 * (https://inference-docs.cerebras.ai/api-reference/openapi.yaml) names
11 * `max_completion_tokens` (`max_tokens` is its alias) and says developer
12 * messages are supported only by the ids in that sentence.
13 */
14import { assertParsed, cachedDocs, markdownTableRows } from './model-facts.ts'
15import { reasoningFactsFor } from './reasoning-config.ts'
16import type { ChatRequestMap, EffortLevelMap } from './request-map.ts'
17import { fetchText, sha256Text } from './types.ts'
18import type { ModelInfo, ModelReasoning } from './types.ts'
19​
20export const CEREBRAS_REASONING_URL =
21 'https://inference-docs.cerebras.ai/capabilities/reasoning.md'
22export const CEREBRAS_CHAT_SPEC_URL =
23 'https://inference-docs.cerebras.ai/api-reference/openapi.yaml'
24​
25export interface CerebrasReasoningDoc {
26 configured: Map<string, ModelReasoning>
27 /** Accepts `reasoning_effort` and ignores it. No reasoning object. */
28 ignored: Array<string>
30​
31export interface CerebrasChatSpec {
32 maxTokensField: 'max_completion_tokens' | 'max_tokens'
33 /** Ids the spec says may send `role: "developer"`. */
34 developerIds: Array<string>
36​
37function column(
38 header: Array<string>,
39 cells: Array<string>,
40 name: string,
41): string {
42 const index = header.findIndex((cell) =>
43 cell.toLowerCase().includes(name.toLowerCase()),
44 )
45 return index < 0 ? '' : (cells[index] ?? '')
47​
48function modelId(cell: string): string {
49 const id = cell.match(/`([a-z0-9][a-z0-9.-]*)`/)?.[1]
50 if (!id) throw new Error(`cerebras reasoning: model cell has no id: ${cell}`)
51 return id
53​
54/** `true` when the cell says reasoning cannot be disabled. */
55function mandatoryFrom(cell: string): boolean {
56 const notSupported = /not supported/i.test(cell)
57 const canDisable = /set `reasoning_effort` to `none`/i.test(cell)
58 if (notSupported === canDisable) {
59 throw new Error(`cerebras reasoning: unread disable cell: ${cell}`)
60 }
61 return notSupported
63​
64function effortValues(cell: string): Array<string> | 'ignored' {
65 if (/accepted but ignored/i.test(cell)) {
66 if (/`[^`]+`/.test(cell)) {
67 throw new Error(
68 `cerebras reasoning: ignored effort cell also lists values: ${cell}`,
69 )
70 }
71 return 'ignored'
72 }
73 const values = [...cell.matchAll(/`([^`]+)`/g)].map((match) => match[1] ?? '')
74 if (values.length === 0 || values.some((value) => value === '')) {
75 throw new Error(`cerebras reasoning: unread effort cell: ${cell}`)
76 }
77 return values
79​
80/** The first reasoning table. Any other disable or effort wording throws. */
81export function parseCerebrasReasoning(markdown: string): CerebrasReasoningDoc {
82 const configured = new Map<string, ModelReasoning>()
83 const ignored: Array<string> = []
84 let header: Array<string> | null = null
85 for (const cells of markdownTableRows(markdown)) {
86 if (
87 cells[0] === 'Model' &&
88 cells.some((cell) => cell.includes('reasoning_effort'))
89 ) {
90 if (!cells.some((cell) => /disable reasoning/i.test(cell))) {
91 throw new Error(
92 'cerebras reasoning: table has no Disable reasoning column',
93 )
94 }
95 header = cells
96 continue
97 }
98 if (!header || cells.length !== header.length) continue
99 const id = modelId(column(header, cells, 'Model'))
100 if (configured.has(id) || ignored.includes(id)) {
101 throw new Error(`cerebras reasoning: duplicate id ${id}`)
102 }
103 const efforts = effortValues(column(header, cells, 'reasoning_effort'))
104 if (efforts === 'ignored') {
105 ignored.push(id)
106 continue
107 }
108 const mandatory = mandatoryFrom(column(header, cells, 'Disable reasoning'))
109 if (mandatory && efforts.includes('none')) {
110 throw new Error(
111 `cerebras reasoning: ${id} cannot be disabled but lists none`,
112 )
113 }
114 if (!mandatory && !efforts.includes('none')) {
115 throw new Error(
116 `cerebras reasoning: ${id} can be disabled but lists no none`,
117 )
118 }
119 configured.set(id, { mode: 'effort', mandatory, efforts })
120 }
121 if (!header) throw new Error('cerebras reasoning: no reasoning_effort table')
122 return { configured, ignored }
124​
125function property(yaml: string, name: string): boolean {
126 return new RegExp(`^[ \\t]+${name}:[ \\t]*$`, 'm').test(yaml)
128​
129/**
130 * Output-cap field and the models allowed to send `developer`. Throws when
131 * the spec no longer says which field is the alias, or which models take
132 * the developer role.
133 */
134export function parseCerebrasChatSpec(yaml: string): CerebrasChatSpec {
135 const completion = property(yaml, 'max_completion_tokens')
136 const alias = property(yaml, 'max_tokens')
137 if (!completion && !alias) {
138 throw new Error('cerebras spec: no max token field')
139 }
140 if (alias) {
141 const aliasOf =
142 /max_tokens:[\s\S]{0,400}?An alias for `max_completion_tokens`/.test(yaml)
143 if (!aliasOf) {
144 throw new Error(
145 'cerebras spec: max_tokens is not an alias of max_completion_tokens',
146 )
147 }
148 }
149 if (!completion) {
150 return { maxTokensField: 'max_tokens', developerIds: developerIds(yaml) }
151 }
152 return {
153 maxTokensField: 'max_completion_tokens',
154 developerIds: developerIds(yaml),
155 }
157​
158function developerIds(yaml: string): Array<string> {
159 const sentence = yaml.match(
160 /Developer messages are supported only by ([^.]+)\./,
161 )?.[1]
162 if (!sentence) {
163 throw new Error('cerebras spec: developer-role sentence missing')
164 }
165 const ids = [...sentence.matchAll(/`([^`]+)`/g)].map(
166 (match) => match[1] ?? '',
167 )
168 if (ids.length === 0 || ids.some((id) => id === '')) {
169 throw new Error('cerebras spec: developer-role sentence names no model')
170 }
171 return ids
173​
174function levelsFor(efforts: Array<string>, off: string | null): EffortLevelMap {
175 return {
176 off,
177 minimal: efforts.includes('minimal') ? 'minimal' : null,
178 low: efforts.includes('low') ? 'low' : null,
179 medium: efforts.includes('medium') ? 'medium' : null,
180 high: efforts.includes('high') ? 'high' : null,
181 xhigh: efforts.includes('xhigh') ? 'xhigh' : null,
182 max: efforts.includes('max') ? 'max' : null,
183 }
185​
186/** `on` is effort high. A model that does not accept `high` has no such body. */
187export function cerebrasThinking(
188 efforts: Array<string>,
189): ChatRequestMap['thinking'] {
190 if (!efforts.includes('high')) return null
191 const off = efforts.includes('none') ? 'none' : null
192 return {
193 on: { reasoning_effort: 'high' },
194 off: off === null ? null : { reasoning_effort: off },
195 levels: levelsFor(efforts, off),
196 }
198​
199export function cerebrasRequestMap(
200 rawId: string,
201 spec: CerebrasChatSpec,
202 reasoning: ModelReasoning | undefined,
203 ignored: boolean,
204): ChatRequestMap {
205 const efforts =
206 reasoning?.mode === 'effort' ? (reasoning.efforts ?? []) : null
207 return {
208 thinking: efforts ? cerebrasThinking(efforts) : null,
209 maxTokensField: spec.maxTokensField,
210 developerRole: spec.developerIds.includes(rawId),
211 replayReasoningContent: null,
212 store: null,
213 strictTools: null,
214 sessionAffinity: null,
215 cacheControl: null,
216 toolStream: null,
217 reasoningEffort: efforts !== null || ignored ? true : null,
218 }
220​
221interface CachedReasoning {
222 byId: Record<string, ModelReasoning>
223 ignored: Array<string>
224 hash: string
226​
227interface CachedSpec {
228 spec: CerebrasChatSpec
229 hash: string
231​
232/** Reasoning object plus the request map for one listed id. */
233export async function cerebrasChatFacts(
234 kv?: KVNamespace,
235): Promise<(rawId: string, capability: boolean) => Partial<ModelInfo>> {
236 const [reasoning, spec] = await Promise.all([
237 cachedDocs(kv, CEREBRAS_REASONING_URL, async () => {
238 const markdown = await fetchText(CEREBRAS_REASONING_URL)
239 const parsed = parseCerebrasReasoning(markdown)
240 assertParsed(parsed.configured, 'cerebras reasoning')
241 const cached: CachedReasoning = {
242 byId: Object.fromEntries(parsed.configured),
243 ignored: parsed.ignored,
244 hash: await sha256Text(markdown),
245 }
246 return cached
247 }),
248 cachedDocs(kv, CEREBRAS_CHAT_SPEC_URL, async () => {
249 const yaml = await fetchText(CEREBRAS_CHAT_SPEC_URL)
250 const cached: CachedSpec = {
251 spec: parseCerebrasChatSpec(yaml),
252 hash: await sha256Text(yaml),
253 }
254 return cached
255 }),
256 ])
257 return (rawId, capability) => {
258 const row = reasoning.byId[rawId]
259 return {
260 ...reasoningFactsFor(
261 rawId,
262 reasoning.byId,
263 { url: CEREBRAS_REASONING_URL, hash: reasoning.hash },
264 capability,
265 ),
266 requestMap: cerebrasRequestMap(
267 rawId,
268 spec.spec,
269 row,
270 reasoning.ignored.includes(rawId),
271 ),
272 }
273 }