Open History to see the last commit
1---
2title: Runtime Adapter Switching
3id: runtime-adapter-switching
4order: 6
5description: "Let users switch between LLM providers at runtime in TanStack AI while keeping full TypeScript type safety for each adapter's model options."
6keywords:
7 - tanstack ai
8 - runtime switching
9 - multi-provider
10 - adapter factory
11 - type safety
12 - dynamic adapter
13---
14
15Learn how to build interfaces where users can switch between LLM providers at runtime while maintaining full TypeScript type safety.
16
17## The Simple Approach
18
19With TanStack AI, the model is passed directly to the adapter factory function. This gives you full type safety and autocomplete at the point of definition:
20
21```typescript
22import { chat, toServerSentEventsResponse } from '@tanstack/ai'
23import { anthropicText } from '@tanstack/ai-anthropic'
24import { openaiText } from '@tanstack/ai-openai'
25
26type Provider = 'openai' | 'anthropic'
27
28// Define adapters with their models - autocomplete works here!
29const adapters = {
30 anthropic: () => anthropicText('claude-sonnet-4-6'), // ✅ Autocomplete!
31 openai: () => openaiText('gpt-5.5'), // ✅ Autocomplete!
32}
33
34async function handleRequest(request: Request) {
35 // In your request handler:
36 const body = await request.json()
37 const provider: Provider = body.forwardedProps?.provider || 'openai'
38
39 const stream = chat({
40 adapter: adapters[provider](),
41 messages: body.messages,
42 })
43}
44```
45
46## Why This Works
47
48Each adapter factory function accepts a model name as its first argument and returns a fully typed adapter:
49
50```typescript
51import { openaiText, OpenAITextAdapter } from '@tanstack/ai-openai'
52
53// These are equivalent:
54const adapter1 = openaiText('gpt-5.5')
55const adapter2 = new OpenAITextAdapter({ apiKey: process.env.OPENAI_API_KEY! }, 'gpt-5.5')
56
57// The model is stored on the adapter
58console.log(adapter1.model) // 'gpt-5.5'
59```
60
61When you pass an adapter to `chat()`, it uses the model from `adapter.model`. This means:
62
63- **Full autocomplete** - When typing the model name, TypeScript knows valid options
64- **Type validation** - Invalid model names cause compile errors
65- **Clean code** - No separate `model` parameter needed
66
67## Full Example
68
69Here's a complete example showing a multi-provider chat API:
70
71```typescript ignore
72import { createFileRoute } from '@tanstack/react-router'
73import { chat, maxIterations, toServerSentEventsResponse } from '@tanstack/ai'
74import { openaiText } from '@tanstack/ai-openai'
75import { anthropicText } from '@tanstack/ai-anthropic'
76import { geminiText } from '@tanstack/ai-gemini'
77import { ollamaText } from '@tanstack/ai-ollama'
78
79type Provider = 'openai' | 'anthropic' | 'gemini' | 'ollama'
80
81// Define adapters with their models
82const adapters = {
83 anthropic: () => anthropicText('claude-sonnet-4-6'),
84 gemini: () => geminiText('gemini-3-flash-preview'),
85 ollama: () => ollamaText('mistral:7b'),
86 openai: () => openaiText('gpt-5.5'),
87}
88
89export const Route = createFileRoute('/api/chat')({
90 server: {
91 handlers: {
92 POST: async ({ request }) => {
93 const abortController = new AbortController()
94 const body = await request.json()
95 // `forwardedProps` is the AG-UI field set by `useChat({ forwardedProps })`.
96 // The legacy `body.data.provider` access still works (mirrored on the
97 // wire for backward compatibility) but `forwardedProps` is preferred.
98 const provider: Provider = body.forwardedProps?.provider || 'openai'
99
100 const stream = chat({
101 adapter: adapters[provider](),
102 tools: [...],
103 systemPrompts: [...],
104 messages: body.messages,
105 abortController,
106 })
107
108 return toServerSentEventsResponse(stream, { abortController })
109 },
110 },
111 },
112})
113```
114
115## Using with Image Adapters
116
117The same pattern works for image generation. Unlike the text and summarize adapters above, image adapters don't all accept the same shape of `size` — so it travels alongside its adapter in the provider map instead of being passed once for every branch:
118
119```typescript
120import { generateImage } from '@tanstack/ai'
121import { openaiImage } from '@tanstack/ai-openai'
122import { geminiImage } from '@tanstack/ai-gemini'
123
124type ImageProvider = 'openai' | 'gemini'
125
126const imageAdapters = {
127 openai: () => ({ adapter: openaiImage('gpt-image-2'), size: '1024x1024' as const }),
128 gemini: () => ({ adapter: geminiImage('gemini-3.1-flash-image'), size: '16:9_4K' as const }),
129}
130
131export async function POST(request: Request) {
132 const body = await request.json()
133 const provider: ImageProvider = body.provider ?? 'openai'
134 const { adapter, size } = imageAdapters[provider]()
135
136 const result = await generateImage({
137 adapter,
138 prompt: 'A beautiful sunset over mountains',
139 size,
140 })
141
142 return Response.json(result)
143}
144```
145
146`size` is provider-specific, which is why it cannot be a single literal shared across branches. Gemini 3.x native image models take a `'<aspectRatio>_<tier>'` string (for example `'16:9_4K'`). `gemini-2.5-flash-image` takes a bare ratio with no suffix (for example `'16:9'`). OpenAI and Imagen models take pixel dimensions (for example `'1024x1024'`).
147
148## Using with Summarize Adapters
149
150And for summarization:
151
152```typescript
153import { summarize } from '@tanstack/ai'
154import { openaiSummarize } from '@tanstack/ai-openai'
155import { anthropicSummarize } from '@tanstack/ai-anthropic'
156
157type SummarizeProvider = 'openai' | 'anthropic'
158
159const summarizeAdapters: Record<SummarizeProvider, () => ReturnType<typeof openaiSummarize | typeof anthropicSummarize>> = {
160 openai: () => openaiSummarize('gpt-5.4-mini'),
161 anthropic: () => anthropicSummarize('claude-sonnet-4-6'),
162}
163
164export async function POST(request: Request) {
165 const body = await request.json()
166 const provider: SummarizeProvider = body.provider ?? 'openai'
167 const longDocument: string = body.text
168
169 const result = await summarize({
170 adapter: summarizeAdapters[provider](),
171 text: longDocument,
172 maxLength: 100,
173 style: 'concise',
174 })
175
176 return Response.json(result)
177}
178```
179
180## Migration from Switch Statements
181
182If you have existing code using switch statements, here's how to migrate:
183
184### Before
185
186```typescript ignore
187let adapter
188let model
189
190switch (provider) {
191 case 'anthropic':
192 adapter = anthropicText()
193 model = 'claude-sonnet-4-6'
194 break
195 case 'openai':
196 default:
197 adapter = openaiText()
198 model = 'gpt-5.5'
199 break
200}
201
202const stream = chat({
203 adapter: adapter as any,
204 model: model as any,
205 messages,
206})
207```
208
209### After
210
211```typescript
212import { chat, toServerSentEventsResponse } from '@tanstack/ai'
213import { anthropicText } from '@tanstack/ai-anthropic'
214import { openaiText } from '@tanstack/ai-openai'
215
216type AfterProvider = 'openai' | 'anthropic'
217
218const adapters = {
219 anthropic: () => anthropicText('claude-sonnet-4-6'),
220 openai: () => openaiText('gpt-5.5'),
221}
222
223export async function POST(request: Request) {
224 const body = await request.json()
225 const provider: AfterProvider = body.forwardedProps?.provider ?? 'openai'
226
227 const stream = chat({
228 adapter: adapters[provider](),
229 messages: body.messages,
230 })
231
232 return toServerSentEventsResponse(stream)
233}
234```
235
236The key changes:
237
2381. Replace the switch statement with an object of factory functions
2392. Each factory function creates an adapter with the model included
2403. No more `as any` casts - full type safety!