Open History to see the last commit
1import type { AnyTextAdapter } from '@tanstack/ai'
2
3/**
4 * Sampling options moved off the root of `chat()` into provider-native
5 * `modelOptions` (the generic root `maxTokens` was removed). These examples
6 * resolve the adapter dynamically, so the provider-native token-cap key isn't
7 * known until runtime — map a generic token cap to the right wire key from the
8 * adapter's `name`. Ollama nests sampling under `options`.
9 *
10 * Spread the result into the `modelOptions` of a `chat()` / `generate()` call:
11 *
12 * ```ts
13 * chat({ adapter, messages, modelOptions: { ...maxTokensModelOptions(adapter, maxTokens) } })
14 * ```
15 */
16export function maxTokensModelOptions(
17 adapter: AnyTextAdapter,
18 maxTokens: number | undefined,
19): Record<string, unknown> {
20 if (maxTokens === undefined) return {}
21 switch (adapter.name) {
22 case 'ollama':
23 return { options: { num_predict: maxTokens } }
24 case 'openai':
25 return { max_output_tokens: maxTokens }
26 case 'anthropic':
27 case 'grok':
28 return { max_tokens: maxTokens }
29 case 'gemini':
30 return { maxOutputTokens: maxTokens }
31 case 'groq':
32 return { max_completion_tokens: maxTokens }
33 case 'openrouter':
34 return { maxCompletionTokens: maxTokens }
35 case 'openrouter-responses':
36 return { maxOutputTokens: maxTokens }
37 // Note: the OpenAI Chat Completions adapter ('openai-chat') is intentionally
38 // omitted — its token key depends on the model (`max_tokens` vs
39 // `max_completion_tokens` for reasoning models), so it can't be resolved
40 // from the adapter name alone. These examples only resolve Responses-API
41 // OpenAI adapters. Unknown names drop the cap rather than risk a wrong key.
42 default:
43 return {}
44 }
45}