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

migration.md

551 lines15.6 KB

1---
2title: Migration Guide
3id: migration
4order: 1
5description: "Migrate existing TanStack AI code to the latest version — adapter function splits, flattened options, renamed modelOptions, and the old embedding() API's replacement by embed()."
6keywords:
7 - tanstack ai
8 - migration
9 - upgrade
10 - breaking changes
11 - tree-shaking
12 - modelOptions
13 - toServerSentEventsStream
14---
15​
16This guide helps you migrate from the previous version of TanStack AI to the latest version. The major changes focus on improved tree-shaking, clearer API naming, and simplified configuration.
17​
18## Overview of Changes
19​
20The main breaking changes in this release are:
21​
221. **Adapter functions split** - Adapters are now split into activity-specific functions for optimal tree-shaking
232. **Common options flattened** - Options are now flattened in the config instead of nested
243. **`providerOptions` renamed** - Now called `modelOptions` for clarity
254. **`toResponseStream` renamed** - Now called `toServerSentEventsStream` for clarity
265. **Embeddings removed, then reintroduced** - The old `embedding()` API was removed; embeddings are back as the new `embed()` activity with multimodal support
276. **Provider tools moved to `/tools`** - Import provider tools from each adapter's `/tools` subpath
287. **`stream: false` returns `{ text, chunks }`** - `chat({ stream: false })` and `streamToText()` resolve to an object, not a string
29​
30## 1. Adapter Functions Split
31​
32Adapters have been split into activity-specific functions to enable optimal tree-shaking. Instead of importing a monolithic adapter, you now import specific functions for each activity type.
33​
34### Before
35​
36```typescript ignore
37import { chat } from '@tanstack/ai'
38import { openai } from '@tanstack/ai-openai'
39​
40const stream = chat({
41 adapter: openai(),
42 model: 'gpt-5.2',
43 messages: [{ role: 'user', content: 'Hello!' }],
44})
45```
46​
47### After
48​
49```typescript
50import { chat } from '@tanstack/ai'
51import { openaiText } from '@tanstack/ai-openai'
52​
53const stream = chat({
54 adapter: openaiText('gpt-5.2'),
55 messages: [{ role: 'user', content: 'Hello!' }],
56})
57```
58​
59### Key Changes
60​
61- **Model is passed to adapter factory** - The model name is now passed directly to the adapter function (e.g., `openaiText('gpt-5.2')`)
62- **No separate `model` parameter** - The model is stored on the adapter, so you don't need to pass it separately to `chat()`
63- **Activity-specific imports** - Import only what you need (e.g., `openaiText`, `openaiSummarize`, `openaiImage`)
64​
65### All Adapter Functions
66​
67Each provider package now exports activity-specific functions:
68​
69#### OpenAI
70​
71```typescript
72import {
73 openaiText, // Chat/text generation
74 openaiSummarize, // Summarization
75 openaiImage, // Image generation
76 openaiSpeech, // Text-to-speech
77 openaiTranscription, // Audio transcription
78 openaiVideo, // Video generation
79} from '@tanstack/ai-openai'
80```
81​
82#### Anthropic
83​
84```typescript
85import {
86 anthropicText, // Chat/text generation
87 anthropicSummarize, // Summarization
88} from '@tanstack/ai-anthropic'
89```
90​
91#### Gemini
92​
93```typescript
94import {
95 geminiText, // Chat/text generation
96 geminiSummarize, // Summarization
97 geminiImage, // Image generation
98 geminiSpeech, // Text-to-speech (experimental)
99} from '@tanstack/ai-gemini'
100```
101​
102#### Ollama
103​
104```typescript
105import {
106 ollamaText, // Chat/text generation
107 ollamaSummarize, // Summarization
108} from '@tanstack/ai-ollama'
109```
110​
111### Migration Example
112​
113Here's a complete example of migrating adapter usage:
114​
115#### Before
116​
117```typescript ignore
118import { chat } from '@tanstack/ai'
119import { openai } from '@tanstack/ai-openai'
120import { anthropic } from '@tanstack/ai-anthropic'
121​
122type Provider = 'openai' | 'anthropic'
123​
124function getAdapter(provider: Provider) {
125 switch (provider) {
126 case 'openai':
127 return openai()
128 case 'anthropic':
129 return anthropic()
130 }
132​
133const stream = chat({
134 adapter: getAdapter(provider),
135 model: provider === 'openai' ? 'gpt-5.2' : 'claude-sonnet-4-5',
136 messages,
137})
138```
139​
140#### After
141​
142```typescript
143import { chat } from '@tanstack/ai'
144import { openaiText } from '@tanstack/ai-openai'
145import { anthropicText } from '@tanstack/ai-anthropic'
146​
147type Provider = 'openai' | 'anthropic'
148​
149const messages = [{ role: 'user' as const, content: 'Hello!' }]
150​
151const adapters = {
152 openai: () => openaiText('gpt-5.2'),
153 anthropic: () => anthropicText('claude-sonnet-4-5'),
155​
156const provider: Provider = 'openai'
157​
158const stream = chat({
159 adapter: adapters[provider](),
160 messages,
161})
162```
163​
164## 2. Common Options Flattened
165​
166Common options that were previously nested in an `options` object are now flattened directly in the config.
167​
168### Before
169​
170```typescript ignore
171const stream = chat({
172 adapter: openai(),
173 model: 'gpt-5.2',
174 messages,
175 options: {
176 temperature: 0.7,
177 maxTokens: 1000,
178 topP: 0.9,
179 },
180})
181```
182​
183### After
184​
185```typescript ignore
186const stream = chat({
187 adapter: openaiText('gpt-5.2'),
188 messages,
189 temperature: 0.7,
190 maxTokens: 1000,
191 topP: 0.9,
192})
193```
194​
195### Available Options
196​
197These options are now available at the top level:
198​
199- `temperature` - Controls randomness (0.0 to 2.0)
200- `topP` - Nucleus sampling parameter
201- `maxTokens` - Maximum tokens to generate
202- `metadata` - Additional metadata to attach
203​
204> **Heads up — sampling has since moved (breaking).** In a later release, the sampling props (`temperature`, `topP`, `maxTokens`) were removed from the root of `chat()` and now live in provider-native `modelOptions`. Passing them at the root no longer type-checks or takes effect. See [Moving Sampling Options into modelOptions](./sampling-options-to-model-options) for the codemod and provider-native key names. `metadata` stays at the root.
205​
206## 3. `providerOptions` → `modelOptions`
207​
208The `providerOptions` parameter has been renamed to `modelOptions` for clarity. This parameter contains model-specific options that vary by provider and model.
209​
210### Before
211​
212```typescript ignore
213const stream = chat({
214 adapter: openai(),
215 model: 'gpt-5.2',
216 messages,
217 providerOptions: {
218 // OpenAI-specific options
219 responseFormat: { type: 'json_object' },
220 logitBias: { '123': 1.0 },
221 },
222})
223```
224​
225### After
226​
227```typescript ignore
228const stream = chat({
229 adapter: openaiText('gpt-5.2'),
230 messages,
231 modelOptions: {
232 // OpenAI-specific options
233 responseFormat: { type: 'json_object' },
234 logitBias: { '123': 1.0 },
235 },
236})
237```
238​
239### Type Safety
240​
241`modelOptions` is fully typed based on the adapter and model you're using:
242​
243```typescript ignore
244import { openaiText } from '@tanstack/ai-openai'
245​
246const adapter = openaiText('gpt-5.2')
247​
248// TypeScript knows the exact modelOptions type for gpt-5.2
249const stream = chat({
250 adapter,
251 messages,
252 modelOptions: {
253 // Autocomplete and type checking for gpt-5.2 options
254 responseFormat: { type: 'json_object' },
255 },
256})
257```
258​
259## 4. `toResponseStream` → `toServerSentEventsStream`
260​
261The `toResponseStream` function has been renamed to `toServerSentEventsStream` to better reflect its purpose. Additionally, the API has changed slightly.
262​
263### Before
264​
265```typescript ignore
266import { chat, toResponseStream } from '@tanstack/ai'
267import { openai } from '@tanstack/ai-openai'
268​
269export async function POST(request: Request) {
270 const { messages } = await request.json()
271 const abortController = new AbortController()
272​
273 const stream = chat({
274 adapter: openai(),
275 model: 'gpt-5.2',
276 messages,
277 abortController,
278 })
279​
280 return toResponseStream(stream, { abortController })
282```
283​
284### After
285​
286```typescript
287import { chat, toServerSentEventsStream } from '@tanstack/ai'
288import { openaiText } from '@tanstack/ai-openai'
289​
290export async function POST(request: Request) {
291 const { messages } = await request.json()
292 const abortController = new AbortController()
293​
294 const stream = chat({
295 adapter: openaiText('gpt-5.2'),
296 messages,
297 abortController,
298 })
299​
300 const readableStream = toServerSentEventsStream(stream, abortController)
301 return new Response(readableStream, {
302 headers: {
303 'Content-Type': 'text/event-stream',
304 'Cache-Control': 'no-cache',
305 Connection: 'keep-alive',
306 },
307 })
309```
310​
311### Key Changes
312​
313- **Function renamed** - `toResponseStream` → `toServerSentEventsStream`
314- **Returns ReadableStream** - Now returns a `ReadableStream` instead of a `Response`
315- **Manual Response creation** - You create the `Response` object yourself with appropriate headers
316- **AbortController parameter** - Passed as a separate parameter instead of in options
317​
318### Alternative: HTTP Stream Format
319​
320If you need HTTP stream format (newline-delimited JSON) instead of SSE, use `toHttpStream`:
321​
322```typescript ignore
323import { toHttpStream } from '@tanstack/ai'
324​
325const readableStream = toHttpStream(stream, abortController)
326return new Response(readableStream, {
327 headers: {
328 'Content-Type': 'application/x-ndjson',
329 },
330})
331```
332​
333## 5. Embeddings Removed, Then Reintroduced as `embed()`
334​
335The original `embedding()` function was removed from TanStack AI. Embeddings have since returned as a new activity with a different API: a single `embed()` function with multimodal input support and per-model type safety. The old `embedding()` name and adapter factories (like `openaiEmbed()`) are not coming back.
336​
337### Before
338​
339```typescript ignore
340import { embedding } from '@tanstack/ai'
341import { openaiEmbed } from '@tanstack/ai-openai'
342​
343const result = await embedding({
344 adapter: openaiEmbed(),
345 model: 'text-embedding-3-small',
346 input: 'Hello, world!',
347})
348```
349​
350### After
351​
352```typescript
353import { embed } from '@tanstack/ai'
354import { openaiEmbedding } from '@tanstack/ai-openai'
355​
356const result = await embed({
357 adapter: openaiEmbedding('text-embedding-3-small'),
358 input: 'Hello, world!',
359})
360​
361console.log(result.embeddings[0]?.vector)
362```
363​
364Key differences from the old API:
365​
366- **Model moves into the adapter factory** - `openaiEmbedding('text-embedding-3-small')` instead of a separate `model` option, matching every other activity
367- **Single function for one or many inputs** - `input` accepts a single item or an array; the result always has an `embeddings` array with one vector per input item
368- **Multimodal inputs** - models like Cohere embed-v4.0 and Amazon Titan Multimodal accept image parts and fused text+image items
369- **Top-level `dimensions`** - request Matryoshka dimensions without provider-specific options
370​
371See the [Embeddings guide](../embeddings.md) for full usage.
372​
373## 6. Provider Tools Moved to `/tools` Subpath
374​
375Provider-specific tools (web search, code execution, computer use, etc.) are now
376exported from a dedicated `/tools` subpath on every adapter package. This keeps
377tool imports tree-shakeable and avoids name collisions between providers.
378​
379The only breaking change is in `@tanstack/ai-openrouter`:
380`createWebSearchTool` has been removed from the package root, renamed to
381`webSearchTool`, and moved to `@tanstack/ai-openrouter/tools`. Every other
382provider tool (Anthropic, OpenAI, Gemini) is newly exported — no existing
383import breaks.
384​
385### Before
386​
387```typescript ignore
388import { createWebSearchTool } from '@tanstack/ai-openrouter'
389​
390const tools = [
391 createWebSearchTool({ engine: 'native', maxResults: 5 }),
393```
394​
395### After
396​
397```typescript
398import { webSearchTool } from '@tanstack/ai-openrouter/tools'
399​
400const tools = [
401 webSearchTool({ engine: 'native', maxResults: 5 }),
403```
404​
405### Key Changes
406​
407- **Import path is now `/tools`** — matches the existing `/adapters` subpath
408 pattern used elsewhere in each provider package.
409- **Factory renamed** — `createWebSearchTool` → `webSearchTool`. The `create*`
410 prefix has been dropped to align with every other provider
411 (`webSearchTool` in `@tanstack/ai-anthropic/tools`,
412 `@tanstack/ai-openai/tools`, etc.).
413- **Runtime behavior is unchanged** — the factory accepts the same config
414 object and returns a tool that works identically in `chat({ tools: [...] })`.
415- **Type-level gating is new** — if you pass a provider tool to a model that
416 doesn't support it (per the model's `supports.tools` array), you now get a
417 type error on the `tools` array. User-defined `toolDefinition()` tools are
418 unaffected.
419​
420For the full list of available provider tools and which models support each
421one, see [Provider Tools](../tools/provider-tools.md).
422​
423## 7. `stream: false` Returns `{ text, chunks }`
424​
425`chat({ stream: false })` and `streamToText(stream)` now resolve to a `ChatResult` object, not a string. Take `text` from the result.
426​
427### Before
428​
429```typescript ignore
430import { chat, streamToText } from '@tanstack/ai'
431import { openaiText } from '@tanstack/ai-openai'
432​
433const text = await chat({
434 adapter: openaiText('gpt-5.6'),
435 messages: [{ role: 'user', content: 'Hello!' }],
436 stream: false,
437})
438​
439const stream = chat({
440 adapter: openaiText('gpt-5.6'),
441 messages: [{ role: 'user', content: 'Hello!' }],
442})
443const streamedText = await streamToText(stream)
444```
445​
446### After
447​
448```typescript
449import { chat, streamToText } from '@tanstack/ai'
450import { openaiText } from '@tanstack/ai-openai'
451​
452const { text } = await chat({
453 adapter: openaiText('gpt-5.6'),
454 messages: [{ role: 'user', content: 'Hello!' }],
455 stream: false,
456})
457​
458const stream = chat({
459 adapter: openaiText('gpt-5.6'),
460 messages: [{ role: 'user', content: 'Hello!' }],
461})
462const { text: streamedText } = await streamToText(stream)
463```
464​
465`text` is the same string as before. The new `chunks` array holds every chunk of the run, so you can also read tool calls, usage, and interrupts. See [`chat()` returns](../api/ai.md#returns).
466​
467With `outputSchema`, `stream: false` still resolves to the parsed object.
468​
469## Complete Migration Example
470​
471Here's a complete example showing all the changes together:
472​
473### Before
474​
475```typescript ignore
476import { chat, toResponseStream } from '@tanstack/ai'
477import { openai } from '@tanstack/ai-openai'
478​
479export async function POST(request: Request) {
480 const { messages } = await request.json()
481 const abortController = new AbortController()
482​
483 const stream = chat({
484 adapter: openai(),
485 model: 'gpt-5.2',
486 messages,
487 options: {
488 temperature: 0.7,
489 maxTokens: 1000,
490 },
491 providerOptions: {
492 responseFormat: { type: 'json_object' },
493 },
494 abortController,
495 })
496​
497 return toResponseStream(stream, { abortController })
499```
500​
501### After
502​
503```typescript ignore
504import { chat, toServerSentEventsStream } from '@tanstack/ai'
505import { openaiText } from '@tanstack/ai-openai'
506​
507export async function POST(request: Request) {
508 const { messages } = await request.json()
509 const abortController = new AbortController()
510​
511 const stream = chat({
512 adapter: openaiText('gpt-5.2'),
513 messages,
514 // Sampling now lives in provider-native `modelOptions` (OpenAI Responses
515 // keys: `temperature`, `max_output_tokens`). `metadata` stays at the root.
516 modelOptions: {
517 temperature: 0.7,
518 max_output_tokens: 1000,
519 responseFormat: { type: 'json_object' },
520 },
521 abortController,
522 })
523​
524 const readableStream = toServerSentEventsStream(stream, abortController)
525 return new Response(readableStream, {
526 headers: {
527 'Content-Type': 'text/event-stream',
528 'Cache-Control': 'no-cache',
529 Connection: 'keep-alive',
530 },
531 })
533```
534​
535## Benefits of These Changes
536​
5371. **Better Tree-Shaking** - Import only what you need, resulting in smaller bundle sizes
5382. **Clearer API** - Function names clearly indicate their purpose
5393. **Type Safety** - Model-specific options are fully typed
5404. **Simpler Configuration** - Flattened options are easier to work with
5415. **Focused Scope** - Removed features that are better handled elsewhere
542​
543## Need Help?
544​
545If you encounter issues during migration:
546​
5471. Check the [Tree-Shaking Guide](../advanced/tree-shaking) for details on the new adapter structure
5482. Review the [API Reference](../api/ai) for complete function signatures
5493. Look at the [examples](../getting-started/quick-start) for working code samples
550​
551​