Open History to see the last commit
1import type { ModelReasoning, ReasoningLevel } from '@tanstack/ai'
2
3/** The reasoning data of a model that reasons. */
4export type ReasoningShape = Exclude<ModelReasoning, false>
5
6// ponytail: a copy of REASONING_LEVELS, because the scripts run without a build of @tanstack/ai.
7const LEVELS: ReadonlyArray<ReasoningLevel> = [
8 'off',
9 'minimal',
10 'low',
11 'medium',
12 'high',
13 'xhigh',
14 'max',
15]
16
17/** The shape as source code, with its levels from least to most thinking. */
18export function formatReasoningShape(shape: ReasoningShape): string {
19 const levels = LEVELS.filter((level) => shape.levels[level] !== undefined)
20 .map((level) => `${level}: '${shape.levels[level]}'`)
21 .join(', ')
22 return `{ levels: { ${levels} }, budget: ${shape.budget} }`
23}
24
25/**
26 * A constant name for a shape: `BUDGET_` when it takes a token budget, else
27 * `EFFORT_`, then its levels. Three or more neighbouring levels sent as their
28 * own names become `LOW_TO_HIGH`. A level sent as another value shows that
29 * value, for example `NONE` for `off: 'none'`.
30 */
31export function reasoningShapeName(shape: ReasoningShape): string {
32 const runs: Array<Array<string>> = []
33 let open = false
34 for (const level of LEVELS) {
35 const value = shape.levels[level]
36 if (value === undefined) {
37 open = false
38 continue
39 }
40 const token = value.toUpperCase().replace(/[^A-Z0-9]+/g, '_')
41 const last = runs.at(-1)
42 if (value === level && open && last) last.push(token)
43 else runs.push([token])
44 open = value === level
45 }
46 const levels = runs
47 .map((run) =>
48 run.length > 2 ? `${run[0]}_TO_${run[run.length - 1]}` : run.join('_'),
49 )
50 .join('_')
51 return `${shape.budget ? 'BUDGET' : 'EFFORT'}_${levels}`
52}
53
54/**
55 * One constant per distinct shape, so each model points at a shape instead of
56 * repeating it. `names` gives the constant for a shape, keyed by
57 * `formatReasoningShape`.
58 */
59export function reasoningShapeTable(shapes: Iterable<ReasoningShape>): {
60 names: Map<string, string>
61 code: string
62} {
63 const names = new Map<string, string>()
64 for (const shape of shapes) {
65 names.set(formatReasoningShape(shape), reasoningShapeName(shape))
66 }
67 const taken = new Set(names.values())
68 if (taken.size !== names.size) {
69 throw new Error('Two reasoning shapes got the same constant name')
70 }
71 const code = Array.from(names)
72 .sort(([, a], [, b]) => a.localeCompare(b))
73 .map(([source, name]) => `const ${name} = ${source} as const`)
74 .join('\n')
75 return { names, code }
76}