Open History to see the last commit
1---
2title: Tree-Shaking
3id: tree-shaking
4order: 7
5description: "TanStack AI's tree-shakeable architecture — import only the activities and adapters you use for minimal bundle size across chat, image, and speech."
6keywords:
7 - tanstack ai
8 - tree-shaking
9 - bundle size
10 - modular imports
11 - performance
12 - tree-shakeable
13---
14
15TanStack AI is designed from the ground up for maximum tree-shakeability. The entire system—from activity functions to adapters—uses a functional, modular architecture that ensures you only bundle the code you actually use.
16
17## Design Philosophy
18
19Instead of a monolithic API that includes everything, TanStack AI provides:
20
21- **Individual activity functions** - Import only the activities you need (`chat`, `summarize`, etc.)
22- **Individual adapter functions** - Import only the adapters you need (`openaiText`, `openaiSummarize`, etc.)
23- **Functional API design** - Pure functions that can be easily eliminated by bundlers
24- **Separate modules** - Each activity and adapter lives in its own module
25
26This design means that if you only use `chat` with OpenAI, you won't bundle code for summarization, image generation, or other providers.
27
28## Activity Functions
29
30Each AI activity is exported as a separate function from `@tanstack/ai`:
31
32```ts
33// Import only the activities you need
34import { chat } from '@tanstack/ai' // Chat/text generation
35import { summarize } from '@tanstack/ai' // Summarization
36import { generateImage } from '@tanstack/ai' // Image generation
37import { generateSpeech } from '@tanstack/ai' // Text-to-speech
38import { generateTranscription } from '@tanstack/ai' // Audio transcription
39import { generateVideo } from '@tanstack/ai' // Video generation
40import { generateLiveVideo } from '@tanstack/ai' // Live video sessions
41import { generateWorld } from '@tanstack/ai' // Live world sessions
42```
43
44### Example: Chat Only
45
46If you only need chat functionality:
47
48```ts
49// Only chat code is bundled
50import { chat } from '@tanstack/ai'
51import { openaiText } from '@tanstack/ai-openai'
52
53const stream = chat({
54 adapter: openaiText('gpt-5.5'),
55 messages: [{ role: 'user', content: 'Hello!' }],
56})
57```
58
59Your bundle will **not** include:
60- Summarization logic
61- Image generation logic
62- Other activity implementations
63
64## Adapter Functions
65
66Each provider package exports individual adapter functions for each activity type:
67
68### OpenAI
69
70```ts
71import {
72 openaiText, // Chat/text generation
73 openaiSummarize, // Summarization
74 openaiImage, // Image generation
75 openaiSpeech, // Text-to-speech
76 openaiTranscription, // Audio transcription
77 openaiVideo, // Video generation
78} from '@tanstack/ai-openai'
79```
80
81### Anthropic
82
83```ts
84import {
85 anthropicText, // Chat/text generation
86 anthropicSummarize, // Summarization
87} from '@tanstack/ai-anthropic'
88```
89
90### Gemini
91
92```ts
93import {
94 geminiText, // Chat/text generation
95 geminiSummarize, // Summarization
96 geminiImage, // Image generation
97 geminiSpeech, // Text-to-speech (experimental)
98} from '@tanstack/ai-gemini'
99```
100
101### Ollama
102
103```ts
104import {
105 ollamaText, // Chat/text generation
106 ollamaSummarize, // Summarization
107} from '@tanstack/ai-ollama'
108```
109
110## Complete Example
111
112Here's how the tree-shakeable design works in practice:
113
114```ts
115// Only import what you need
116import { chat } from '@tanstack/ai'
117import { openaiText } from '@tanstack/ai-openai'
118
119// Chat generation - returns AsyncIterable<StreamChunk>
120const chatResult = chat({
121 adapter: openaiText('gpt-5.5'),
122 messages: [{ role: 'user', content: 'Hello!' }],
123})
124
125for await (const chunk of chatResult) {
126 console.log(chunk)
127}
128```
129
130**What gets bundled:**
131- ✅ `chat` function and its dependencies
132- ✅ `openaiText` adapter and its dependencies
133- ✅ Chat-specific streaming and tool handling logic
134
135**What doesn't get bundled:**
136- ❌ `summarize` function
137- ❌ `generateImage` function
138- ❌ Other adapter implementations (Anthropic, Gemini, etc.)
139- ❌ Other activity implementations
140
141## Using Multiple Activities
142
143If you need multiple activities, import only what you use:
144
145```ts
146import { chat, summarize } from '@tanstack/ai'
147import {
148 openaiText,
149 openaiSummarize
150} from '@tanstack/ai-openai'
151
152// Each activity is independent
153const chatResult = chat({
154 adapter: openaiText('gpt-5.5'),
155 messages: [{ role: 'user', content: 'Hello!' }],
156})
157
158const summarizeResult = await summarize({
159 adapter: openaiSummarize('gpt-5.4-mini'),
160 text: 'Long text to summarize...',
161})
162```
163
164Each activity is in its own module, so bundlers can eliminate unused ones.
165
166## Type Safety
167
168The tree-shakeable design doesn't sacrifice type safety. Each adapter provides full type safety for its supported models:
169
170```ts ignore
171import { openaiText, type OpenAIChatModel } from '@tanstack/ai-openai'
172
173const adapter = openaiText('gpt-5.5')
174
175// TypeScript knows the exact models supported
176const model: OpenAIChatModel = 'gpt-5.5' // ✓ Valid
177const model2: OpenAIChatModel = 'invalid' // ✗ Type error
178```
179
180## Create Options Functions
181
182The `create___Options` functions are also tree-shakeable:
183
184```ts
185import {
186 createChatOptions,
187 createImageOptions
188} from '@tanstack/ai'
189import { openaiText } from '@tanstack/ai-openai'
190
191// Only import what you need
192const chatOptions = createChatOptions({
193 adapter: openaiText('gpt-5.5'),
194})
195```
196
197## Bundle Size Benefits
198
199The functional, modular design provides significant bundle size benefits:
200
201### Importing Everything (Less Efficient)
202
203```ts
204// ❌ Importing more than needed
205import * as ai from '@tanstack/ai'
206import * as openai from '@tanstack/ai-openai'
207
208// This bundles all exports from both packages
209```
210
211### Importing Only What You Need (Recommended)
212
213```ts
214// ✅ Only what you use gets bundled
215import { chat } from '@tanstack/ai'
216import { openaiText } from '@tanstack/ai-openai'
217
218// You only get:
219// - Chat activity implementation
220// - OpenAI text adapter
221// - Chat-specific dependencies
222```
223
224### Real-World Impact
225
226For a typical chat application, importing a single activity and one adapter pulls in substantially less code than bundling every activity and every provider adapter. Because each activity and adapter lives in its own side-effect-free module, your bundler drops everything you don't reference — so the more providers and activities the library supports, the larger the difference between a focused import and a namespace import.
227
228## How It Works
229
230The tree-shakeability is achieved through:
231
2321. **ES Module exports** - Each function is a named export, not a default export
2332. **Separate modules** - Each activity and adapter lives in its own file
2343. **No side effects** - Functions are pure and don't have module-level side effects
2354. **Functional composition** - Functions compose together, allowing dead code elimination
2365. **Type-only imports** - Type imports are stripped at build time
237
238Modern bundlers (Vite, Webpack, Rollup, esbuild) can easily eliminate unused code because:
239
240- Functions are statically analyzable
241- No dynamic imports of unused code
242- No module-level side effects
243- Clear dependency graphs
244
245## Best Practices
246
2471. **Import only what you need** - Don't import entire namespaces
2482. **Use specific adapter functions** - Import `openaiText` not `openai`
2493. **Separate activities by route** - Different API routes can use different activities
2504. **Lazy load when possible** - Use dynamic imports for code-split routes
2515. **Keep mobile chat bundles client-only** - React Native and Expo chat screens
252 should import `useChat` and chat connection adapters, not provider SDKs,
253 server response helpers, React DOM UI, devtools UI, or other framework
254 packages. See [Quick Start: React Native](../getting-started/quick-start-react-native)
255 for the server-only provider boundary and mobile transport setup.
256
257```ts
258// ✅ Good - Only imports chat
259import { chat } from '@tanstack/ai'
260import { openaiText } from '@tanstack/ai-openai'
261
262// ❌ Bad - Imports everything
263import * as ai from '@tanstack/ai'
264import * as openai from '@tanstack/ai-openai'
265```
266
267## Adapter Types
268
269Each adapter type implements a specific interface:
270
271- `ChatAdapter` - Provides `chatStream()` method for streaming chat responses
272- `SummarizeAdapter` - Provides `summarize()` method for text summarization
273- `ImageAdapter` - Provides `generateImage()` method for image generation
274- `TTSAdapter` - Provides `generateSpeech()` method for text-to-speech
275- `TranscriptionAdapter` - Provides `generateTranscription()` method for audio transcription
276- `VideoAdapter` - Provides `generateVideo()` method for video generation
277- `LiveVideoAdapter` - Provides `createLiveVideo()` method for live video sessions
278- `WorldAdapter` - Provides `createWorld()` method for live world sessions and world jobs
279
280All adapters have a `kind` property that indicates their type:
281
282```ts
283import { openaiText, openaiSummarize } from '@tanstack/ai-openai'
284
285const chatAdapter = openaiText('gpt-5.5')
286console.log(chatAdapter.kind) // 'text'
287
288const summarizeAdapter = openaiSummarize('gpt-5.4-mini')
289console.log(summarizeAdapter.kind) // 'summarize'
290```
291
292## Summary
293
294TanStack AI's tree-shakeable design means:
295
296- ✅ **Smaller bundles** - Only include code you actually use
297- ✅ **Faster load times** - Less JavaScript to download and parse
298- ✅ **Better performance** - Less code means faster execution
299- ✅ **Type safety** - Full TypeScript support without runtime overhead
300- ✅ **Flexibility** - Mix and match activities and adapters as needed
301
302The functional, modular architecture ensures that modern bundlers can eliminate unused code effectively, resulting in optimal bundle sizes for your application.