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

reasoning-config.ts

571 lines18.0 KB

1/**
2 * Reasoning objects for chat rows whose capabilities already say `reasoning`
3 * (issue #110). Mode and effort names come only from a native listing or
4 * docs page. A model the source does not configure stays null; `path:
5 * 'silent'` records that the page was read and did not state a mode.
6 */
7import { ingestFailedEvent, noteIngest } from '../ingest/ingest-signals.ts'
8import { emptySources } from './fact-sources.ts'
9import { assertParsed, cachedDocs, markdownTableRows } from './model-facts.ts'
10import { fetchText, reasoningViolation, sha256Text } from './types.ts'
11import type { ModelFactSources, ModelInfo, ModelReasoning } from './types.ts'
12​
13export const MISTRAL_REASONING_URL =
14 'https://docs.mistral.ai/studio/conversations/reasoning.md'
15export const GROQ_REASONING_URL = 'https://console.groq.com/docs/reasoning.md'
16export const COHERE_REASONING_URL = 'https://docs.cohere.com/docs/reasoning.md'
17export const BYTEPLUS_REASONING_URL =
18 'https://docs.byteplus.com/en/docs/ModelArk/1449737'
19​
20/** The thinking page names no mode for this id. */
21export const REASONING_SOURCE_SILENT = 'silent'
22​
23/**
24 * The write gate for `reasoning`. A listed object that breaks the shape is
25 * not stored: the row keeps the value and source it had (null on a new row),
26 * the poll goes on, and an `ingest_failed` event names the model and reason.
27 */
28export function keepValidReasoning(
29 providerId: string,
30 info: ModelInfo,
31 prior?: { reasoning: unknown; factSources: unknown },
32): ModelInfo {
33 if (info.reasoning == null) return info
34 const reason = reasoningViolation(info.reasoning)
35 if (reason === null) return info
36 noteIngest(
37 ingestFailedEvent(
38 'models-poll',
39 providerId,
40 `${info.rawId}: reasoning not stored: ${reason}`,
41 ),
42 )
43 const { reasoning: _refused, ...sources } = info.factSources ?? {}
44 const priorSource = (prior?.factSources as ModelFactSources | null)?.reasoning
45 const factSources = priorSource
46 ? { ...sources, reasoning: priorSource }
47 : sources
48 return {
49 ...info,
50 reasoning: (prior?.reasoning ?? null) as ModelReasoning | null,
51 factSources: emptySources(factSources) ? undefined : factSources,
52 }
54​
55export function listsReasoning(capabilities: unknown): boolean {
56 return Array.isArray(capabilities) && capabilities.includes('reasoning')
58​
59function docsReasoningSource(
60 sourceUrl: string,
61 sourceHash: string,
62 path: string,
63): ModelFactSources {
64 return {
65 reasoning: {
66 derivation: 'docs-derived',
67 sourceUrl,
68 sourceHash,
69 path,
70 },
71 }
73​
74/**
75 * Attach a parsed reasoning object, or a silent note when the row already
76 * has the reasoning capability and this source does not configure it.
77 */
78export function reasoningFactsFor(
79 rawId: string,
80 byId: Record<string, ModelReasoning>,
81 source: { url: string; hash: string },
82 capability: boolean,
83): Partial<ModelInfo> {
84 const reasoning = byId[rawId]
85 if (reasoning) {
86 return {
87 reasoning,
88 factSources: docsReasoningSource(source.url, source.hash, 'reasoning'),
89 }
90 }
91 if (!capability) return {}
92 return {
93 factSources: docsReasoningSource(
94 source.url,
95 source.hash,
96 REASONING_SOURCE_SILENT,
97 ),
98 }
100​
101/** Merge docs patches without letting one factSources bag replace another. */
102export function overlayModelFacts(
103 model: ModelInfo,
104 ...patches: Array<Partial<ModelInfo>>
105): ModelInfo {
106 let next: ModelInfo = { ...model }
107 const factSources: ModelFactSources = { ...(model.factSources ?? {}) }
108 for (const patch of patches) {
109 const { factSources: more, ...rest } = patch
110 next = { ...next, ...rest }
111 if (more) Object.assign(factSources, more)
112 }
113 if (emptySources(factSources)) {
114 const { factSources: _drop, ...bare } = next
115 return bare
116 }
117 return { ...next, factSources }
119​
120/**
121 * OpenRouter `GET /api/v1/models` reasoning object. `supported_efforts`
122 * names the effort mode. `null` accepts gateway effort names supplied from
123 * normative host docs; mandatory rows reject the documented disable value.
124 * Without gateway docs, null keeps its effort names unknown. `supports_max_tokens` is a budget
125 * only when the listing does not speak about efforts. No reasoning object,
126 * or a mandatory flag that is not a boolean, stays null.
127 */
128export function openRouterReasoning(
129 row: {
130 reasoning?: {
131 supported_efforts?: Array<string | null> | null
132 mandatory?: unknown
133 supports_max_tokens?: unknown
134 } | null
135 },
136 gatewayEfforts?: ReadonlyArray<string>,
137 gatewayToggle?: boolean,
138): ModelReasoning | null {
139 const reasoning = row.reasoning
140 if (!reasoning || typeof reasoning !== 'object') return null
141 for (const key of ['mandatory', 'supports_max_tokens'] as const) {
142 const value = reasoning[key]
143 if (value != null && typeof value !== 'boolean')
144 throw new Error(`openrouter: malformed native ${key}`)
145 }
146 const declared = reasoning.supported_efforts
147 if (
148 declared != null &&
149 (!Array.isArray(declared) ||
150 declared.some(
151 (value) =>
152 value != null && (typeof value !== 'string' || !value.length),
153 ))
154 )
155 throw new Error('openrouter: malformed native supported_efforts')
156 if (typeof reasoning.mandatory !== 'boolean') return null
157 const mandatory = reasoning.mandatory
158 if (Array.isArray(reasoning.supported_efforts)) {
159 const efforts = reasoning.supported_efforts.filter(
160 (effort): effort is string =>
161 typeof effort === 'string' && effort.length > 0,
162 )
163 if (efforts.length === 0) return null
164 return { mode: 'effort', mandatory, efforts }
165 }
166 if (reasoning.supported_efforts === null) {
167 return {
168 mode: 'effort',
169 mandatory,
170 ...(gatewayEfforts
171 ? {
172 efforts: gatewayEfforts.filter(
173 (value) => !mandatory || value !== 'none',
174 ),
175 }
176 : {}),
177 }
178 }
179 if (reasoning.supports_max_tokens === true) {
180 return { mode: 'budget', mandatory }
181 }
182 if (gatewayToggle === true && mandatory === false)
183 return { mode: 'toggle', mandatory: false }
184 return null
186​
187/**
188 * Mistral's reasoning guide. Bullets that name `reasoning_effort` are effort
189 * mode. Effort names are the `reasoning_effort = "…"` values, unless the
190 * same bullet publishes its own list. Native "always on, no parameter"
191 * prose names no mode and contributes nothing.
192 */
193export function parseMistralReasoning(
194 markdown: string,
195): Map<string, ModelReasoning> {
196 const out = new Map<string, ModelReasoning>()
197 const prose = markdown.replace(/```[\s\S]*?```/g, '')
198 const preludeEnd = prose.search(/handling thinking chunks/i)
199 const prelude = preludeEnd < 0 ? prose : prose.slice(0, preludeEnd)
200 const bullet =
201 /`([a-z0-9][a-z0-9.-]*)`:\s*Supports adjustable reasoning via the `reasoning_effort`/g
202 // `reasoning_effort = "none"` omits the thinking chunk for Mistral models.
203 // Example assignments are still not an allowlist. A model's own value list
204 // below replaces this.
205 const noneOmits =
206 /reasoning_effort\s*=\s*"none"[\s\S]{0,240}thinking chunk (?:is )?omitted/i.test(
207 prelude,
208 )
209 for (const match of prelude.matchAll(bullet)) {
210 const id = match[1]
211 if (!id) continue
212 out.set(id, { mode: 'effort', mandatory: noneOmits ? false : null })
213 }
214 // The scoped model list is followed by normative parameter values. These
215 // are not code examples; an explicit model-specific list overrides them.
216 const valueSection = prelude.split(
217 'The `reasoning_effort` parameter controls',
218 )[1]
219 const levels = [
220 ...(valueSection?.matchAll(/^- `reasoning_effort\s*=\s*"([a-z]+)"`:/gm) ??
221 []),
222 ].flatMap((match) => (match[1] ? [match[1]] : []))
223 if (levels.length) {
224 for (const id of out.keys())
225 out.set(id, {
226 mode: 'effort',
227 mandatory: noneOmits && levels.includes('none') ? false : null,
228 efforts: levels,
229 })
230 }
231 const ownList =
232 /`([a-z0-9][a-z0-9.-]*)`:[^\n]{0,240}?Supported values are ([^\n.]+)/g
233 for (const match of prelude.matchAll(ownList)) {
234 const id = match[1]
235 if (!id || !out.has(id)) continue
236 const efforts = [...(match[2] ?? '').matchAll(/`([a-z]+)`/g)].flatMap(
237 (found) => (found[1] ? [found[1]] : []),
238 )
239 if (efforts.length === 0) continue
240 const ownNote = prelude
241 .split(/\n\s*\n/)
242 .find(
243 (para) =>
244 para.split('\n').some((line) => line.startsWith('`' + id + '` ')) &&
245 /always|cannot/i.test(para),
246 )
247 const alwaysThinking =
248 !!ownNote &&
249 /(?:reasoning|thinking)\s+(?:is\s+)?(?:always on|cannot be disabled|cannot be turned off)|is always returned[^.\n]*\(thinking\s*\+\s*text\)/i.test(
250 ownNote,
251 )
252 out.set(id, {
253 mode: 'effort',
254 mandatory: alwaysThinking
255 ? true
256 : noneOmits && efforts.includes('none')
257 ? false
258 : null,
259 efforts,
260 })
261 }
262 return out
264​
265interface NamedModel {
266 id: string
267 label: string
269​
270function headingBlocks(
271 markdown: string,
272): Array<{ title: string; body: string }> {
273 return markdown.split(/\n(?=#{2,3} )/).flatMap((part) => {
274 const match = part.match(/^#{2,3} (.+)$/m)
275 const title = (match?.[1] ?? '')
276 .replace(/^\s*\[([^\]]+)\]\([^)]*\)\s*/, '$1')
277 .replace(/\s*\([^)]*\)\s*$/, '')
278 .trim()
279 if (!match || title.length === 0) return []
280 return [{ title, body: part.slice(part.indexOf('\n') + 1) }]
281 })
283​
284function linkLabel(cell: string): string {
285 return cell
286 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
287 .replace(/\\/g, '')
288 .trim()
290​
291/** Groq reasoning page: per-model `reasoning_effort` tables. Ids the page lists as reasoning models but never gives options stay absent. */
292export function parseGroqReasoning(
293 markdown: string,
294): Map<string, ModelReasoning> {
295 const models: Array<NamedModel> = []
296 const effortsById = new Map<string, Array<string>>()
297 const conflicts = new Set<string>()
298 for (const block of headingBlocks(markdown)) {
299 if (block.title === 'Supported Models') {
300 for (const row of markdownTableRows(block.body)) {
301 const id = (row[0] ?? '').trim()
302 if (!/^[A-Za-z0-9][A-Za-z0-9./_-]*$/.test(id) || id === 'Model ID') {
303 continue
304 }
305 models.push({ id, label: linkLabel(row[1] ?? '') })
306 }
307 continue
308 }
309 if (!block.title.startsWith('Options for Reasoning Effort')) continue
310 const efforts: Array<string> = []
311 for (const row of markdownTableRows(block.body)) {
312 const name = (row[0] ?? '').replace(/[`\\]/g, '').trim()
313 if (/^[a-z]+$/.test(name) && !efforts.includes(name)) efforts.push(name)
314 }
315 if (efforts.length === 0) continue
316 const norm = (value: string) =>
317 value.toLowerCase().replace(/[^a-z0-9]/g, '')
318 const sectionNorm = norm(block.body)
319 const linked = [...block.body.matchAll(/\[([^\]]+)\]/g)].map((match) =>
320 norm(match[1] ?? ''),
321 )
322 for (const model of models) {
323 const labelNorm = norm(model.label)
324 const named =
325 block.body.includes(model.id) ||
326 (labelNorm.length > 0 && sectionNorm.includes(labelNorm)) ||
327 linked.some((name) => name.length >= 6 && labelNorm.includes(name))
328 if (!named) continue
329 const prior = effortsById.get(model.id)
330 if (prior && prior.join('\0') !== efforts.join('\0')) {
331 conflicts.add(model.id)
332 continue
333 }
334 effortsById.set(model.id, efforts)
335 }
336 }
337 const out = new Map<string, ModelReasoning>()
338 for (const [id, efforts] of effortsById) {
339 if (conflicts.has(id)) continue
340 out.set(id, {
341 mode: 'effort',
342 mandatory: !efforts.includes('none'),
343 efforts,
344 })
345 }
346 return out
348​
349/**
350 * Cohere's reasoning guide. `thinking.token_budget` is budget mode, and
351 * thinking can be turned off, so it is not mandatory. No effort names are
352 * published. A page that does not state `token_budget` configures nothing.
353 *
354 * The guide names one model in its examples but says "Cohere's reasoning
355 * models are hybrid", enabled or disabled. While it says so, the same
356 * configuration is kept under `COHERE_ANY_REASONING` for the other models
357 * the listing flags `reasoning` (Command A+, North Mini Code).
358 */
359export const COHERE_ANY_REASONING = '*'
360​
361export function parseCohereReasoning(
362 markdown: string,
363): Map<string, ModelReasoning> {
364 const out = new Map<string, ModelReasoning>()
365 if (!/token_budget/.test(markdown)) return out
366 if (!/"type":\s*"disabled"|turns off thinking/i.test(markdown)) return out
367 const ids = new Set<string>()
368 for (const match of markdown.matchAll(
369 /`([a-z0-9][a-z0-9._-]*-\d{2}-\d{4})`/g,
370 )) {
371 if (match[1]) ids.add(match[1])
372 }
373 for (const match of markdown.matchAll(/model="([^"]+)"/g)) {
374 if (match[1]) ids.add(match[1])
375 }
376 if (
377 /Cohere's reasoning models are \*hybrid\*, meaning reasoning can be enabled \([^)]*\) or disabled/.test(
378 markdown,
379 )
380 ) {
381 ids.add(COHERE_ANY_REASONING)
382 }
383 for (const id of ids) {
384 out.set(id, { mode: 'budget', mandatory: false })
385 }
386 return out
388​
389/** Pull the chain-of-thought section out of the docs HTML or a markdown fixture. */
390export function byteplusReasoningSection(body: string): string {
391 const text = body
392 .replace(/\\u003C/gi, '<')
393 .replace(/\\u003E/gi, '>')
394 .replace(/\\u0026/gi, '&')
395 .replace(/\\u002F/gi, '/')
396 .replace(/\\n/g, '\n')
397 .replace(/\\-/g, '-')
398 .replace(/<br\s*\/?>/gi, ' ')
399 .replace(/<[^>]+>/g, '')
400 const headed = text.search(/(?:^|\n)## Adjust chain-of-thought length/i)
401 const start =
402 headed >= 0 ? headed : text.search(/adjust chain-of-thought length/i)
403 if (start < 0) return ''
404 const rest = text.slice(start)
405 const end = rest.search(/\n## (?!Adjust)/)
406 return end < 0 ? rest : rest.slice(0, end)
408​
409/**
410 * Doc-center delta: each visible string is an `"insert":"..."` fragment.
411 * Effort names are the published value list. Model ids are the dated ids
412 * after that list. Markdown fixtures fall through to the table parser.
413 */
414function parseByteplusInserts(section: string): Map<string, ModelReasoning> {
415 const out = new Map<string, ModelReasoning>()
416 const inserts = [
417 ...section.matchAll(/\\"insert\\":\\"([^\\"]*)\\"/g),
418 ].flatMap((match) => {
419 const text = (match[1] ?? '').replace(/\\n/g, '').trim()
420 return text.length > 0 ? [text] : []
421 })
422 const efforts: Array<string> = []
423 const ids: Array<string> = []
424 let phase: 'seek' | 'values' | 'models' = 'seek'
425 for (const insert of inserts) {
426 if (phase === 'seek') {
427 if (insert === 'reasoning_effort' || insert === 'reasoning.effort') {
428 phase = 'values'
429 }
430 continue
431 }
432 if (phase === 'values') {
433 if (/the table below|^supported models$/i.test(insert)) {
434 phase = 'models'
435 continue
436 }
437 if (
438 /^(none|minimal|low|medium|high|xhigh|max)$/.test(insert) &&
439 !efforts.includes(insert)
440 ) {
441 efforts.push(insert)
442 }
443 continue
444 }
445 if (
446 /^[a-z0-9]+(?:-[a-z0-9]+)*-\d{4,}$/.test(insert) &&
447 !ids.includes(insert)
448 ) {
449 ids.push(insert)
450 }
451 }
452 if (efforts.length === 0 || ids.length === 0) return out
453 const reasoning: ModelReasoning = {
454 mode: 'effort',
455 mandatory: !efforts.includes('none'),
456 efforts,
457 }
458 for (const id of ids) out.set(id, reasoning)
459 return out
461​
462export function parseByteplusReasoning(
463 body: string,
464): Map<string, ModelReasoning> {
465 const section = byteplusReasoningSection(body)
466 const out = new Map<string, ModelReasoning>()
467 if (!section) return out
468 const inserted = parseByteplusInserts(section)
469 if (inserted.size > 0) return inserted
470 const [values = ''] = section.split(/\| ?Supported models/i)
471 const efforts: Array<string> = []
472 for (const line of values.split('\n')) {
473 const name = line.match(/^\*\s*`([a-z]+)`/)?.[1]
474 if (name && !efforts.includes(name)) efforts.push(name)
475 }
476 if (efforts.length === 0) return out
477 const reasoning: ModelReasoning = {
478 mode: 'effort',
479 mandatory: !efforts.includes('none'),
480 efforts,
481 }
482 let inTable = false
483 for (const row of markdownTableRows(section)) {
484 const head = (row[0] ?? '').replace(/\\/g, '').trim()
485 if (/^supported models$/i.test(head)) {
486 inTable = true
487 continue
488 }
489 if (!inTable) continue
490 if (/^(api|example)$/i.test(head)) break
491 for (const match of head.matchAll(/`([a-z0-9]+(?:-[a-z0-9]+)*-\d{4,})`/g)) {
492 const id = match[1]
493 if (id) out.set(id, reasoning)
494 }
495 }
496 return out
498​
499async function loadReasoningMap(
500 kv: KVNamespace | undefined,
501 url: string,
502 source: string,
503 parse: (body: string) => Map<string, ModelReasoning>,
504): Promise<{
505 byId: Record<string, ModelReasoning>
506 hash: string
507 url: string
508}> {
509 return cachedDocs(kv, url, async () => {
510 const body = await fetchText(url)
511 const parsed = parse(body)
512 assertParsed(parsed, source)
513 return { byId: Object.fromEntries(parsed), hash: await sha256Text(body) }
514 }).then((doc) => ({ ...doc, url }))
516​
517function lookup(doc: {
518 byId: Record<string, ModelReasoning>
519 hash: string
520 url: string
521}): (rawId: string, capability: boolean) => Partial<ModelInfo> {
522 return (rawId, capability) =>
523 reasoningFactsFor(rawId, doc.byId, doc, capability)
525​
526export async function mistralModelReasoning(kv?: KVNamespace) {
527 const doc = await loadReasoningMap(
528 kv,
529 MISTRAL_REASONING_URL,
530 'mistral reasoning page',
531 parseMistralReasoning,
532 )
533 return lookup(doc)
535​
536export async function groqModelReasoning(kv?: KVNamespace) {
537 const doc = await loadReasoningMap(
538 kv,
539 GROQ_REASONING_URL,
540 'groq reasoning page',
541 parseGroqReasoning,
542 )
543 return lookup(doc)
545​
546export async function cohereModelReasoning(kv?: KVNamespace) {
547 const doc = await loadReasoningMap(
548 kv,
549 COHERE_REASONING_URL,
550 'cohere reasoning page',
551 parseCohereReasoning,
552 )
553 const any = COHERE_ANY_REASONING in doc.byId
554 return (rawId: string, capability: boolean): Partial<ModelInfo> =>
555 reasoningFactsFor(
556 capability && any && !(rawId in doc.byId) ? COHERE_ANY_REASONING : rawId,
557 doc.byId,
558 doc,
559 capability,
560 )
562​
563export async function byteplusModelReasoning(kv?: KVNamespace) {
564 const doc = await loadReasoningMap(
565 kv,
566 BYTEPLUS_REASONING_URL,
567 'byteplus reasoning page',
568 parseByteplusReasoning,
569 )
570 return lookup(doc)