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

reasoning-config.ts

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