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

ai-remix.md

447 lines12.5 KB

1---
2title: "@tanstack/ai-remix"
3id: ai-remix
4order: 9
5description: "API reference for @tanstack/ai-remix. Remix 3 helpers including createChat for streaming chat with full type safety."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-remix"
9 - remix
10 - createChat
11 - createChatHook
12 - api reference
13---
14​
15Install `@tanstack/ai-remix`, then call `createChat(handle, options)` in a Remix setup function. The package publishes uncompiled source. Remix compiles JSX through `jsxImportSource` `remix/ui`.
16​
17For a typed headless chat UI, see [Remix Chat UI](../ui/remix). Import `createChatHook` from `@tanstack/ai-remix/ui`.
18​
19## Installation
20​
21<!-- ::start:tabs variant="package-manager" mode="install" -->
22​
23remix: @tanstack/ai-remix remix
24​
25<!-- ::end:tabs -->
26​
27`remix` is a required peer.
28​
29## `createRegisterWebMCPTools(handle, tools, options?)`
30​
31Register executable client tools for a Remix component. Remix removes them when the component `Handle` signal aborts.
32​
33For a complete setup and behavior guide, see [WebMCP Tools](../tools/webmcp).
34​
35```tsx
36import {
37 createRegisterWebMCPTools,
38 type CreateRegisterWebMCPToolsOptions,
39} from '@tanstack/ai-remix'
40import { clientEntry, type Handle } from 'remix/ui'
41import { searchProducts } from './tools'
42​
43const tools = [searchProducts]
44const options: CreateRegisterWebMCPToolsOptions<typeof tools> = {
45 onError(error) {
46 console.error(error)
47 },
49​
50export const ProductsPage = clientEntry(
51 import.meta.url,
52 function ProductsPage(handle: Handle) {
53 createRegisterWebMCPTools(handle, tools, options)
54 return () => null
55 },
57```
58​
59`CreateRegisterWebMCPToolsOptions<TTools, TContext>` contains `toolOptions`, `context`, and `onError`. The helper uses `handle.signal` for registration.
60​
61The `context` field is required when a tool declares a required runtime context.
62​
63## `createPageWebMCPTools(handle, options?)`
64​
65Read the WebMCP tools on the page as client tools. The `tools` field starts empty. When the page adds or removes a tool, the helper updates `tools` and calls `handle.update()`. Read it in a `get tools()` getter on `createChat`.
66​
67```ts
68import { createPageWebMCPTools } from '@tanstack/ai-remix'
69import type { Handle } from 'remix/ui'
70​
71export function readPageTools(handle: Handle) {
72 return createPageWebMCPTools(handle, {
73 filter: (tool) => tool.origin === location.origin,
74 })
76```
77​
78`filter` skips a tool when it returns `false`. `onError` gets a failed WebMCP read. For a complete guide, see [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
79​
80## Server
81​
82A Remix controller action can return the same SSE `Response` as any other host.
83​
84```typescript
85import {
86 chat,
87 chatParamsFromRequest,
88 toServerSentEventsResponse,
89} from '@tanstack/ai'
90import { openaiText } from '@tanstack/ai-openai'
91import { createController } from 'remix/router'
92import { post, route } from 'remix/routes'
93​
94const routes = route({
95 chat: {
96 stream: post('/chat'),
97 },
98})
99​
100export default createController(routes.chat, {
101 actions: {
102 async stream({ request }) {
103 const { messages, threadId, runId } =
104 await chatParamsFromRequest(request)
105​
106 const stream = chat({
107 adapter: openaiText('gpt-5.6'),
108 messages,
109 threadId,
110 runId,
111 })
112​
113 return toServerSentEventsResponse(stream)
114 },
115 },
116})
117```
118​
119The matching client calls `createChat` and streams from that route. See [Quick Start](../getting-started/quick-start).
120​
121## `createChat(handle, options)`
122​
123Manages chat state in a Remix component. Pass the component `Handle` as the first argument. Put `connection` and `tools` in setup. They are not serializable `clientEntry` props.
124​
125```tsx
126import { createChat, fetchServerSentEvents } from '@tanstack/ai-remix'
127import {
128 createChatClientOptions,
129 type InferChatMessages,
130} from '@tanstack/ai-client'
131import { toolDefinition } from '@tanstack/ai'
132import { clientEntry, on, type Handle } from 'remix/ui'
133import { z } from 'zod'
134​
135const updateUIDef = toolDefinition({
136 name: 'updateUI',
137 description: 'Show a notification in the UI',
138 inputSchema: z.object({ message: z.string() }),
139})
140​
141export const ChatComponent = clientEntry(
142 import.meta.url,
143 function ChatComponent(handle: Handle) {
144 let notification: string | null = null
145 const updateUI = updateUIDef.client((input) => {
146 notification = input.message
147 return { success: true }
148 })
149 const tools = [updateUI]
150​
151 const chatOptions = createChatClientOptions({
152 connection: fetchServerSentEvents('/chat'),
153 tools,
154 })
155​
156 type ChatMessages = InferChatMessages<typeof chatOptions>
157​
158 const chat = createChat(handle, chatOptions)
159​
160 return () => (
161 <div>
162 {notification}
163 {chat.isLoading ? 'Loading' : null}
164 {chat.error ? chat.error.message : null}
165 <button
166 type="button"
167 mix={on('click', () => {
168 void chat.sendMessage('hi')
169 })}
170 >
171 Send
172 </button>
173 {chat.messages.length}
174 </div>
175 )
176 },
178```
179​
180Read `chat.messages` and `chat.isLoading` in the render function so each paint sees the latest values. The default thread id is `options.threadId ?? handle.id`. When `handle.signal` aborts, cleanup runs.
181​
182### Options you pass first
183​
184Extends `ChatClientOptions` from `@tanstack/ai-client`. Pass `connection` or `fetcher`, not both. `Handle` is the first argument, not an option.
185​
186- `connection` or `fetcher` - how the helper talks to your server
187- `tools?` - client tool implementations from `.client()`. A `get tools()` getter is read each time a run starts.
188- `threadId?` - the only identity for this chat. Required when persistence is on
189- `initialMessages?` - starting transcript
190- `forwardedProps?` - JSON sent to the server on the AG-UI `forwardedProps` field
191​
192### Options you add later
193​
194- `live?` - subscribe on setup, unsubscribe on dispose
195- `queue?` - what to do when `sendMessage` runs while a turn is in flight. Default queues
196- `interrupts?` - typed interrupt definitions
197- `context?` - client-only runtime context for client tools. Not sent to the server
198- `onResponse?` / `onChunk?` / `onFinish?` / `onError?` / `onInterruptStateChange?`
199- `devtools?` - display options. The helper always tags `framework: 'remix'`
200- `body?` - deprecated. Use `forwardedProps`
201​
202Client tools run automatically.
203​
204### Returns
205​
206```typescript
207import type { UIMessage } from '@tanstack/ai-remix'
208import type { ModelMessage } from '@tanstack/ai/client'
209import type {
210 BoundInterrupts,
211 MultimodalContent,
212 ChatClientState,
213 ConnectionStatus,
214 QueuedMessage,
215 SendMessageOptions,
216} from '@tanstack/ai-client'
217​
218interface CreateChatReturn {
219 messages: Array<UIMessage>
220 sendMessage: (
221 content: string | MultimodalContent,
222 options?: SendMessageOptions,
223 ) => Promise<void>
224 append: (message: ModelMessage | UIMessage) => Promise<void>
225 addToolResult: (result: {
226 toolCallId: string
227 tool: string
228 output: unknown
229 state?: 'output-available' | 'output-error'
230 errorText?: string
231 }) => Promise<void>
232 interrupts: BoundInterrupts
233 resolveInterrupts: (approved: boolean) => void
234 reload: () => Promise<void>
235 stop: () => void
236 isLoading: boolean
237 error: Error | undefined
238 status: ChatClientState
239 isSubscribed: boolean
240 connectionStatus: ConnectionStatus
241 sessionGenerating: boolean
242 setMessages: (messages: Array<UIMessage>) => void
243 clear: () => void
244 queue: Array<QueuedMessage>
245 cancelQueued: (id: string) => void
246 runId: string | null
248```
249​
250State fields are getters. `queue` holds sends that wait while a run is busy. `runId` is the in-flight turn, or `null`.
251​
252For a tool with `needsApproval: true`, read `chat.interrupts`. Call `interrupt.resolveInterrupt(true)` on the bound `tool-approval` item.
253​
254## Connection adapters
255​
256Re-exported from `@tanstack/ai-client`:
257​
258```typescript
259import {
260 fetchServerSentEvents,
261 fetchHttpStream,
262 stream,
263 type ConnectionAdapter,
264} from '@tanstack/ai-remix'
265```
266​
267## Example: basic chat
268​
269```tsx
270import { createChat, fetchServerSentEvents } from '@tanstack/ai-remix'
271import { clientEntry, on, type Handle } from 'remix/ui'
272​
273export const Chat = clientEntry(
274 import.meta.url,
275 function Chat(handle: Handle) {
276 const chat = createChat(handle, {
277 connection: fetchServerSentEvents('/chat'),
278 })
279​
280 return () => (
281 <div>
282 {chat.messages.map((message) => (
283 <div key={message.id}>
284 <strong>{message.role}:</strong>
285 {message.parts
286 .filter((part) => part.type === 'text')
287 .map((part) => part.content)
288 .join('')}
289 </div>
290 ))}
291 <form
292 mix={on('submit', (event) => {
293 event.preventDefault()
294 const form = event.currentTarget
295 const text = String(new FormData(form).get('message') ?? '').trim()
296 if (text === '') {
297 return
298 }
299 form.reset()
300 void chat.sendMessage(text)
301 })}
302 >
303 <input name="message" disabled={chat.isLoading} />
304 <button type="submit" disabled={chat.isLoading}>
305 Send
306 </button>
307 </form>
308 </div>
309 )
310 },
312```
313​
314## Headless chat UI
315​
316For a typed chat layout with your own Remix components, see [Remix Chat UI](../ui/remix). Call `createChatHook` from `@tanstack/ai-remix/ui` once at module scope. Your app calls `createAppChat(handle)` and renders `<ui.Chat chat={chat} />`.
317​
318## Other helpers
319​
320Each helper takes the Remix `Handle` as the first argument. Call it in setup.
321​
322### `createByok(handle, client)`
323​
324Subscribe to a BYOK snapshot. The return is a getter for the latest snapshot.
325​
326```tsx
327import { createByok } from '@tanstack/ai-remix'
328import type { Handle } from 'remix/ui'
329import { byok } from './byok'
330​
331function Keys(handle: Handle) {
332 const getSnapshot = createByok(handle, byok)
333 return () => <p>{JSON.stringify(getSnapshot().status)}</p>
335```
336​
337Call `byok.update(provider, value)` from your own UI to save a key. See [Bring Your Own Key](../advanced/byok).
338​
339### `createRealtimeChat(handle, options)`
340​
341Realtime voice chat. Pass `getToken` and `adapter`.
342​
343```tsx
344import { createRealtimeChat } from '@tanstack/ai-remix'
345import { openaiRealtime } from '@tanstack/ai-openai'
346import { on, type Handle } from 'remix/ui'
347​
348function VoiceChat(handle: Handle) {
349 const chat = createRealtimeChat(handle, {
350 getToken: () => fetch('/api/realtime-token').then((response) => response.json()),
351 adapter: openaiRealtime(),
352 })
353​
354 return () => (
355 <div>
356 <p>Status: {chat.status}</p>
357 <button
358 type="button"
359 mix={on('click', () => {
360 if (chat.status === 'idle') {
361 void chat.connect()
362 return
363 }
364 chat.disconnect()
365 })}
366 >
367 {chat.status === 'idle' ? 'Start' : 'Stop'}
368 </button>
369 </div>
370 )
372```
373​
374### `createGeneration(handle, options)`
375​
376Base helper for one-shot generation. Pass `connection` or `fetcher`. Call `generate()`.
377​
378```tsx
379import { createGeneration, fetchServerSentEvents } from '@tanstack/ai-remix'
380import { on, type Handle } from 'remix/ui'
381​
382function CustomGenerator(handle: Handle) {
383 const gen = createGeneration(handle, {
384 connection: fetchServerSentEvents('/api/generate/custom'),
385 })
386​
387 return () => (
388 <div>
389 <button
390 type="button"
391 mix={on('click', () => {
392 void gen.generate({ prompt: 'Hello' })
393 })}
394 >
395 Generate
396 </button>
397 {gen.isLoading ? <p>Generating</p> : null}
398 </div>
399 )
401```
402​
403### `createGenerateImage(handle, options)`
404​
405Image generation. `generate()` accepts `ImageGenerateInput`. The result is `ImageGenerationResult`.
406​
407```tsx
408import { createGenerateImage, fetchServerSentEvents } from '@tanstack/ai-remix'
409import { on, type Handle } from 'remix/ui'
410​
411function ImageGenerator(handle: Handle) {
412 const image = createGenerateImage(handle, {
413 connection: fetchServerSentEvents('/api/generate/image'),
414 })
415​
416 return () => (
417 <div>
418 <button
419 type="button"
420 mix={on('click', () => {
421 void image.generate({ prompt: 'A sunset over mountains' })
422 })}
423 >
424 Generate
425 </button>
426 {image.isLoading ? <p>Generating</p> : null}
427 </div>
428 )
430```
431​
432The package also exports `createGenerateAudio`, `createGenerateSpeech`, `createGenerateVideo`, `createTranscription`, `createSummarize`, `createAudioRecorder`, and `createMcpAppBridge`.
433​
434## Types
435​
436Re-exported from `@tanstack/ai-client`:
437​
438- `UIMessage<TTools>`
439- `ChatClientOptions<TTools, TContext>`
440- `InferChatMessages<T>`
441- `QueuedMessage`, `SendMessageOptions`, `WhenBusy`
442​
443## Next
444​
445- [Quick Start](../getting-started/quick-start)
446- [Tools](../tools/tools)
447- [Client tools](../tools/client-tools)