Open History to see the last commit
1import {
2 reasoningBudget,
3 resolveReasoning,
4} from '@tanstack/ai/adapter-internals'
5import type { ModelReasoning, ReasoningRequest } from '@tanstack/ai'
6
7type AnthropicEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
8
9const EFFORTS: ReadonlyArray<string> = ['low', 'medium', 'high', 'xhigh', 'max']
10const isEffort = (value: string): value is AnthropicEffort =>
11 EFFORTS.includes(value)
12
13/**
14 * The Claude models with adaptive thinking: 4.6 and later (pi's list). An
15 * older model with effort levels, such as Opus 4.5, still thinks with a
16 * token budget.
17 */
18const ADAPTIVE_THINKING = /opus-4-[6-9]|sonnet-4-[6-9]|opus-5|sonnet-5|fable-5/
19
20/** The Messages API thinking fields for one request. */
21export interface AnthropicThinkingFields {
22 thinking?:
23 | { type: 'adaptive'; display: 'summarized' | 'omitted' }
24 | { type: 'enabled'; budget_tokens: number }
25 | { type: 'disabled' }
26 output_config?: { effort: AnthropicEffort }
27}
28
29/**
30 * The thinking fields for `chat({ reasoning })`:
31 * - `off`: thinking disabled. A model that cannot stop thinking never gets
32 * here, because the clamp moves `off` to its lowest level.
33 * - a budget model without adaptive thinking, or a request with
34 * `budgetTokens`: `thinking.type: 'enabled'` with the budget (pi's table
35 * when the request sets none).
36 * - otherwise adaptive thinking with the model's effort for the level.
37 * `summary` picks whether the thinking text streams back.
38 */
39export function anthropicThinking(
40 model: string,
41 request: ReasoningRequest | undefined,
42 reasoning: ModelReasoning | undefined,
43): AnthropicThinkingFields {
44 const resolved = resolveReasoning(request, reasoning)
45 if (!resolved || !reasoning) return {}
46 if (resolved.level === 'off') return { thinking: { type: 'disabled' } }
47 const budgetOnly =
48 reasoning.budget &&
49 (resolved.budgetTokens !== undefined || !ADAPTIVE_THINKING.test(model))
50 if (budgetOnly)
51 return {
52 thinking: {
53 type: 'enabled',
54 budget_tokens: reasoningBudget({
55 level: resolved.level,
56 summary: resolved.summary,
57 ...(resolved.budgetTokens !== undefined
58 ? { budgetTokens: resolved.budgetTokens }
59 : {}),
60 }),
61 },
62 }
63 const thinking = {
64 type: 'adaptive' as const,
65 display: resolved.summary ? ('summarized' as const) : ('omitted' as const),
66 }
67 const effort = resolved.value
68 if (!isEffort(effort)) return { thinking }
69 return { thinking, output_config: { effort } }
70}