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

runtime-adapter-switching.md

288 lines8.9 KB

1---
2title: Runtime Adapter Switching
3id: runtime-adapter-switching
4order: 6
5description: "Let users pick the LLM provider at runtime. Each adapter keeps its types, and the chat history keeps working when the provider changes."
6keywords:
7 - tanstack ai
8 - runtime switching
9 - multi-provider
10 - adapter factory
11 - type safety
12 - dynamic adapter
13---
14​
15One endpoint can call Claude for one turn and GPT for the next. The history stays typed across the switch.
16​
17Keep a map of adapter factories on the server. The client sends the provider that the user picked, and the server picks the adapter from the map.
18​
19## Quick setup
20​
21### 1. Pick the adapter on the server
22​
23```typescript
24// api/chat.ts
25import {
26 chat,
27 chatParamsFromRequest,
28 toServerSentEventsResponse,
29} from '@tanstack/ai'
30import { anthropicText } from '@tanstack/ai-anthropic'
31import { openaiText } from '@tanstack/ai-openai'
32​
33const adapters = {
34 anthropic: () => anthropicText('claude-sonnet-5-5'),
35 openai: () => openaiText('gpt-6.1-sol'),
37​
38type Provider = keyof typeof adapters
39​
40function isProvider(value: unknown): value is Provider {
41 return value === 'anthropic' || value === 'openai'
43​
44export async function POST(request: Request) {
45 const params = await chatParamsFromRequest(request)
46 const requested = params.forwardedProps.provider
47 const provider: Provider = isProvider(requested) ? requested : 'openai'
48​
49 const stream = chat({
50 adapter: adapters[provider](),
51 messages: params.messages,
52 threadId: params.threadId,
53 })
54​
55 return toServerSentEventsResponse(stream)
57```
58​
59### 2. Send the provider from the client
60​
61```tsx
62import { useState } from 'react'
63import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
64​
65export function ProviderChat() {
66 const [provider, setProvider] = useState('anthropic')
67 const { sendMessage } = useChat({
68 connection: fetchServerSentEvents('/api/chat'),
69 threadId: 'support-chat',
70 forwardedProps: { provider },
71 })
72​
73 return (
74 <>
75 <select
76 aria-label="Provider"
77 value={provider}
78 onChange={(event) => setProvider(event.target.value)}
79 >
80 <option value="anthropic">Claude</option>
81 <option value="openai">GPT</option>
82 </select>
83 <button onClick={() => sendMessage('Keep going')}>Send</button>
84 </>
85 )
87```
88​
89Switch the provider in the middle of a thread. The next answer comes from the new model, with the full history.
90​
91## How it works
92​
93The adapter factory takes the model name as its first argument. The adapter keeps the model, so `chat()` needs no separate `model` option.
94​
95- You get autocomplete for the model name where you write the map.
96- A wrong model name is a compile error.
97- Each entry in the map keeps its own types, so you need no casts.
98​
99Treat `forwardedProps` as client input. The `isProvider` check accepts only the names in your map.
100​
101## Keep saved history when you switch
102​
103You start a thread on Claude, then switch to GPT. The thinking signatures and tool call IDs of Claude mean nothing to OpenAI. If you send them as they are, the request fails.
104​
105You do not have to fix this yourself. Keep the message metadata when you save and send the history. `chat()` does the rest. On the server, `chatParamsFromRequest` keeps the message metadata for you.
106​
107Each assistant message records where it came from, in `metadata.tanstack.source`:
108​
109```json
110{ "provider": "anthropic", "api": "anthropic-messages", "model": "claude-sonnet-5-5" }
111```
112​
113When the next call goes to a different source, the adapter changes the request:
114​
115- It drops signatures and redacted thinking.
116- It sends readable thinking as plain text.
117- It rewrites tool call IDs to the shape that the new API accepts. Each result keeps its call.
118- An OpenAI-compatible or OpenRouter adapter can know that the model has no image input. Then it sends no images from tool results. See [Images in Tool Results](./multimodal-content#images-in-tool-results).
119​
120Each request also cleans the history:
121​
122- An answer that failed or was aborted is left out, with its tool results.
123- A tool call with no result gets the result `No result provided`.
124​
125All of this changes only the request. Your saved history stays the same. A message with no `source` counts as same-source, so its signatures go back as they are.
126​
127## Advanced
128​
129### The factory and the class
130​
131The factory and the adapter class give the same adapter:
132​
133```typescript
134import { openaiText, OpenAITextAdapter } from '@tanstack/ai-openai'
135​
136const adapter1 = openaiText('gpt-6.1-sol')
137const adapter2 = new OpenAITextAdapter(
138 { apiKey: process.env.OPENAI_API_KEY ?? '' },
139 'gpt-6.1-sol',
141​
142// The model is stored on the adapter
143console.log(adapter1.model) // 'gpt-6.1-sol'
144```
145​
146`chat()` reads the model from `adapter.model`.
147​
148### Replace a switch statement
149​
150Do you have a `switch` that sets an adapter and a model in two variables? Replace it with the map of factories from the quick setup. Each factory creates the adapter with its model, so the `chat()` call needs no casts.
151​
152### Full example with four providers
153​
154A TanStack Start route that serves OpenAI, Anthropic, Gemini, and Ollama:
155​
156```typescript ignore
157import { createFileRoute } from '@tanstack/react-router'
158import {
159 chat,
160 chatParamsFromRequest,
161 toServerSentEventsResponse,
162} from '@tanstack/ai'
163import { anthropicText } from '@tanstack/ai-anthropic'
164import { geminiText } from '@tanstack/ai-gemini'
165import { ollamaText } from '@tanstack/ai-ollama'
166import { openaiText } from '@tanstack/ai-openai'
167​
168const adapters = {
169 anthropic: () => anthropicText('claude-sonnet-5-5'),
170 gemini: () => geminiText('gemini-3.8-flash'),
171 ollama: () => ollamaText('mistral:7b'),
172 openai: () => openaiText('gpt-6.1-sol'),
174​
175type Provider = keyof typeof adapters
176​
177function isProvider(value: unknown): value is Provider {
178 return (
179 value === 'anthropic' ||
180 value === 'gemini' ||
181 value === 'ollama' ||
182 value === 'openai'
183 )
185​
186export const Route = createFileRoute('/api/chat')({
187 server: {
188 handlers: {
189 POST: async ({ request }) => {
190 const abortController = new AbortController()
191 const params = await chatParamsFromRequest(request)
192 // `forwardedProps` is the AG-UI field that `useChat({ forwardedProps })` sets.
193 const requested = params.forwardedProps.provider
194 const provider: Provider = isProvider(requested) ? requested : 'openai'
195​
196 const stream = chat({
197 adapter: adapters[provider](),
198 systemPrompts: ['You are a helpful assistant.'],
199 messages: params.messages,
200 threadId: params.threadId,
201 abortController,
202 })
203​
204 return toServerSentEventsResponse(stream, { abortController })
205 },
206 },
207 },
208})
209```
210​
211### Image adapters
212​
213The same pattern works for image generation. Image adapters do not all accept the same shape of `size`, so each entry in the map carries its own `size`:
214​
215```typescript
216import { generateImage } from '@tanstack/ai'
217import { geminiImage } from '@tanstack/ai-gemini'
218import { openaiImage } from '@tanstack/ai-openai'
219​
220const imageAdapters = {
221 openai: () => ({ adapter: openaiImage('gpt-image-2.5-sunburst'), size: '1024x1024' as const }),
222 gemini: () => ({ adapter: geminiImage('gemini-3.1-flash-image'), size: '16:9_4K' as const }),
224​
225export async function POST(request: Request) {
226 const body: unknown = await request.json()
227 const requested =
228 typeof body === 'object' && body !== null && 'provider' in body
229 ? body.provider
230 : undefined
231 const { adapter, size } =
232 requested === 'gemini' ? imageAdapters.gemini() : imageAdapters.openai()
233​
234 const result = await generateImage({
235 adapter,
236 prompt: 'A beautiful sunset over mountains',
237 threadId: 'thread-1',
238 size,
239 })
240​
241 return Response.json(result)
243```
244​
245`size` is specific to the provider:
246​
247- Gemini 3.x native image models take a `'<aspectRatio>_<tier>'` string, for example `'16:9_4K'`.
248- OpenAI and Imagen models take pixel dimensions, for example `'1024x1024'`.
249​
250### Summarize adapters
251​
252The same pattern works for summarization:
253​
254```typescript
255import { summarize } from '@tanstack/ai'
256import { anthropicSummarize } from '@tanstack/ai-anthropic'
257import { openaiSummarize } from '@tanstack/ai-openai'
258​
259type SummarizeProvider = 'openai' | 'anthropic'
260​
261const summarizeAdapters: Record<
262 SummarizeProvider,
263 () => ReturnType<typeof openaiSummarize | typeof anthropicSummarize>
264> = {
265 openai: () => openaiSummarize('gpt-5.4-mini'),
266 anthropic: () => anthropicSummarize('claude-sonnet-5-5'),
268​
269export async function POST(request: Request) {
270 const body: unknown = await request.json()
271 if (typeof body !== 'object' || body === null) {
272 return new Response('Bad request', { status: 400 })
273 }
274 const provider: SummarizeProvider =
275 'provider' in body && body.provider === 'anthropic' ? 'anthropic' : 'openai'
276 const text = 'text' in body && typeof body.text === 'string' ? body.text : ''
277​
278 const result = await summarize({
279 adapter: summarizeAdapters[provider](),
280 text,
281 threadId: 'thread-1',
282 maxLength: 100,
283 style: 'concise',
284 })
285​
286 return Response.json(result)
288```