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

reasoning.ts

68 lines2.3 KB

1import { resolveReasoning } from '@tanstack/ai/adapter-internals'
2import type { ThinkingConfig, ThinkingLevel } from '@google/genai'
3import type { ModelReasoning, ReasoningRequest } from '@tanstack/ai'
4​
5/**
6 * pi's thinking budgets for the Gemini 2.5 models. `-1` asks Gemini for a
7 * dynamic budget.
8 */
9function budgetFor(model: string, level: string): number {
10 const high = model.includes('2.5-pro')
11 ? 32768
12 : model.includes('2.5-flash')
13 ? 24576
14 : undefined
15 if (high === undefined) return -1
16 const minimal = model.includes('2.5-flash-lite') ? 512 : 128
17 const budgets: Record<string, number> = {
18 minimal,
19 low: 2048,
20 medium: 8192,
21 high,
22 }
23 return budgets[level] ?? high
25​
26/**
27 * The `thinkingConfig` for `chat({ reasoning })`:
28 * - `off`: a zero thinking budget. A model that cannot stop thinking never
29 * gets here, because the clamp moves `off` to its lowest level.
30 * - a model with effort levels (Gemini 3): `thinkingLevel`.
31 * - a budget model (Gemini 2.5): `thinkingBudget`, from `budgetTokens` or
32 * pi's table.
33 * `summary` turns `includeThoughts` on.
34 */
35export function geminiThinkingConfig(
36 model: string,
37 request: ReasoningRequest | undefined,
38 reasoning: ModelReasoning | undefined,
39): ThinkingConfig | undefined {
40 const resolved = resolveReasoning(request, reasoning)
41 if (!resolved || !reasoning) return undefined
42 if (resolved.level === 'off') return { thinkingBudget: 0 }
43 const includeThoughts = resolved.summary
44 if (!reasoning.budget) {
45 return {
46 includeThoughts,
47 // The level values are the lowercase names of the SDK enum values.
48 thinkingLevel: resolved.value.toUpperCase() as ThinkingLevel,
49 }
50 }
51 return {
52 includeThoughts,
53 thinkingBudget: resolved.budgetTokens ?? budgetFor(model, resolved.level),
54 }
56​
57/** The Interactions API thinking fields for `chat({ reasoning })`. */
58export function interactionsThinking(
59 request: ReasoningRequest | undefined,
60 reasoning: ModelReasoning | undefined,
61): { thinking_level?: string; thinking_summaries?: 'auto' | 'none' } {
62 const resolved = resolveReasoning(request, reasoning)
63 if (!resolved || resolved.level === 'off') return {}
64 return {
65 thinking_level: resolved.value,
66 thinking_summaries: resolved.summary ? 'auto' : 'none',
67 }