Open History to see the last commit
1---
2title: "@tanstack/ai-remix"
3id: ai-remix
4order: 9
5description: "API reference for @tanstack/ai-remix: the createChat helper, generation helpers, and Remix 3 bindings for the headless TanStack AI client."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-remix"
9 - remix
10 - createChat
11 - createChatHook
12 - api reference
13---
14
15Remix 3 helpers for TanStack AI. To build your first chat, start with the [Quick Start](../getting-started/quick-start). For a typed chat layout, see [Remix Chat UI](../ui/remix).
16
17## Installation
18
19<!-- ::start:tabs variant="package-manager" mode="install" -->
20
21remix: @tanstack/ai-remix remix
22
23<!-- ::end:tabs -->
24
25`remix` is a required peer. The package publishes uncompiled source. Remix compiles the JSX through the `remix/ui` `jsxImportSource`.
26
27Every helper takes the component `Handle` as its first argument. Call it in the setup function, not in the render function.
28
29The server side is a normal route. A Remix controller action returns the same SSE `Response` as any other host:
30
31```typescript
32import {
33 chat,
34 chatParamsFromRequest,
35 toServerSentEventsResponse,
36} from "@tanstack/ai";
37import { openaiText } from "@tanstack/ai-openai";
38import { createController } from "remix/router";
39import { post, route } from "remix/routes";
40
41const routes = route({
42 chat: {
43 stream: post("/chat"),
44 },
45});
46
47export default createController(routes.chat, {
48 actions: {
49 async stream({ request }) {
50 const { messages, threadId, runId } = await chatParamsFromRequest(request);
51
52 const stream = chat({
53 adapter: openaiText("gpt-6.1-sol"),
54 messages,
55 threadId,
56 runId,
57 });
58
59 return toServerSentEventsResponse(stream);
60 },
61 },
62});
63```
64
65## `createChat(handle, options)`
66
67Holds the messages and the run state of one chat, and talks to your server route.
68
69```tsx
70import { createChat, fetchServerSentEvents } from "@tanstack/ai-remix";
71import { clientEntry, on, type Handle } from "remix/ui";
72
73export const Chat = clientEntry(
74 import.meta.url,
75 function Chat(handle: Handle) {
76 const chat = createChat(handle, {
77 connection: fetchServerSentEvents("/chat"),
78 threadId: "support-chat",
79 });
80
81 return () => (
82 <div>
83 {chat.messages.map((message) => (
84 <div key={message.id}>
85 <strong>{message.role}:</strong>
86 {message.parts
87 .filter((part) => part.type === "text")
88 .map((part) => part.content)
89 .join("")}
90 </div>
91 ))}
92 <form
93 mix={on("submit", (event) => {
94 event.preventDefault();
95 const form = event.currentTarget;
96 const text = String(new FormData(form).get("message") ?? "").trim();
97 if (text === "") {
98 return;
99 }
100 form.reset();
101 void chat.sendMessage(text);
102 })}
103 >
104 <input name="message" disabled={chat.isLoading} />
105 <button type="submit" disabled={chat.isLoading}>
106 Send
107 </button>
108 </form>
109 </div>
110 );
111 },
112);
113```
114
115Put `connection` and `tools` in setup. They are not serializable `clientEntry` props.
116
117### Options
118
119You must pass `threadId`. You must also pass `connection` or `fetcher`, not both.
120
121| Option | What it does |
122| --- | --- |
123| `connection` | Connection adapter, for example `fetchServerSentEvents("/chat")`. See [Transports](../transports/overview). |
124| `fetcher` | A function that returns a `Response` or a stream. Use it with server functions. |
125| `tools` | Client tools from `.client()`. They run when the model calls them. A `get tools()` getter is read each time a run starts. See [Client Tools](../tools/client-tools). |
126| `threadId` | Required. The id of this chat. Use a stable id for each conversation, for example the id from your route. |
127| `initialMessages` | The messages to show first. |
128| `forwardedProps` | JSON sent to the server in the AG-UI `forwardedProps` field, for example `{ model: "gpt-6.1-sol" }`. |
129| `persistence` | `true` to load the thread from the server, or a storage adapter. See [Chat Persistence](../persistence/chat-persistence). |
130| `outputSchema` | A Standard Schema. Adds typed `partial` and `final` to the return value. See [Streaming structured output](../structured-outputs/streaming). |
131| `context` | Client-only runtime context for client tools. It is not sent to the server. |
132| `live` | Subscribe in setup and unsubscribe when the handle aborts. |
133| `queue` | What `sendMessage` does while a run is busy. Default: queue the message. See [Queueing](../chat/queueing). |
134| `interrupts` | Definitions from `defineInterrupt()`. See [Interrupts](../interrupts/overview). |
135| `byok`, `byokProvider` | A keyring from `defineByok()`. See [Bring Your Own Key](../advanced/byok). |
136| `devtools` | Display options for TanStack AI Devtools. The helper always tags `framework: 'remix'`. |
137
138The helper also takes the `ChatClient` callbacks (`onResponse`, `onChunk`, `onFinish`, `onError`, `onInterruptStateChange`, `onCustomEvent`) and the other client options. See [`ChatClient` options](./ai-client#constructor-options).
139
140### Returns
141
142State fields are getters. Read them in the render function, so each paint sees the latest values. Cleanup runs when `handle.signal` aborts.
143
144| Field | What it is |
145| --- | --- |
146| `messages` | The `UIMessage` array of the chat. |
147| `sendMessage(content, options?)` | Sends a user message. `content` is a string or `{ content, id?, metadata? }`. `options` takes `whenBusy` and `body`. |
148| `isLoading` | `true` while a response streams. |
149| `error` | The last error, or `undefined`. |
150| `status` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |
151| `stop()` | Stops the current response. |
152| `reload()` | Runs the last user message again. |
153| `append(message)` | Adds a `UIMessage` or `ModelMessage` and starts a run. |
154| `addToolResult(result)` | Gives the result of a client tool by hand: `{ toolCallId, tool, output, state?, errorText? }`. |
155| `setMessages(messages)`, `clear()` | Replace or clear the messages. |
156| `queue`, `cancelQueued(id)` | Messages that wait while a run is busy. See [Queueing](../chat/queueing). |
157| `runId` | The id of the run in flight, or `null`. |
158| `interrupts` | Pending interrupts. Each item has `resolveInterrupt(...)`. See [Interrupts](../interrupts/overview). |
159| `resolveInterrupts`, `cancelInterrupts`, `retryInterrupts`, `resumeInterruptsUnsafe` | Act on all pending interrupts at once. |
160| `interruptErrors`, `resuming` | Errors from the last resume, and `true` while a resume runs. |
161| `isHydrating` | `true` while the chat loads from persistence. |
162| `hasOlderMessages`, `loadOlderMessages()` | Page in older messages. See [Chat Persistence](../persistence/chat-persistence). |
163| `isSubscribed`, `connectionStatus`, `sessionGenerating` | State of the live subscription. |
164| `partial`, `final` | Structured output. Only when you pass `outputSchema`. |
165
166### Example: tool approval
167
168A tool with `needsApproval: true` pauses the run. The pending call shows up in `interrupts`.
169
170```tsx
171import { toolDefinition } from "@tanstack/ai";
172import { createChat, fetchServerSentEvents } from "@tanstack/ai-remix";
173import { clientEntry, on, type Handle } from "remix/ui";
174import { z } from "zod";
175
176const deleteFileTool = toolDefinition({
177 name: "delete_file",
178 description: "Delete a file",
179 needsApproval: true,
180 inputSchema: z.object({ path: z.string() }),
181});
182
183export const ChatWithApproval = clientEntry(
184 import.meta.url,
185 function ChatWithApproval(handle: Handle) {
186 const chat = createChat(handle, {
187 connection: fetchServerSentEvents("/chat"),
188 threadId: "support-chat",
189 tools: [deleteFileTool],
190 });
191
192 return () => (
193 <div>
194 {chat.interrupts.map((interrupt) =>
195 interrupt.kind === "tool-approval" ? (
196 <div key={interrupt.id}>
197 <p>Approve: {interrupt.toolName}</p>
198 <button
199 type="button"
200 mix={on("click", () => interrupt.resolveInterrupt(true))}
201 >
202 Approve
203 </button>
204 <button
205 type="button"
206 mix={on("click", () => interrupt.resolveInterrupt(false))}
207 >
208 Deny
209 </button>
210 </div>
211 ) : null,
212 )}
213 </div>
214 );
215 },
216);
217```
218
219See [Tool Approval](../interrupts/tool-approval) for the server side.
220
221## `createChatHook(options)`
222
223This package does not export `createChatHook` from its main entry. `@tanstack/ai-remix/ui` has a `createChatHook` that binds chat options and typed UI components. Call it once at module scope. Then your app calls the returned factory with the handle and renders `<ui.Chat chat={chat} />`. See [Remix Chat UI](../ui/remix).
224
225## Generation hooks
226
227Each helper runs one generation request and keeps its result. See [Generation Hooks](../media/generation-hooks).
228
229| Helper | `generate()` input | `result` |
230| --- | --- | --- |
231| `createGenerateImage` | `ImageGenerateInput` | `ImageGenerationResult` |
232| `createGenerateAudio` | `AudioGenerateInput` | `AudioGenerationResult` |
233| `createGenerateSpeech` | `SpeechGenerateInput` | `TTSResult` |
234| `createTranscription` | `TranscriptionGenerateInput` | `TranscriptionResult` |
235| `createSummarize` | `SummarizeGenerateInput` | `SummarizationResult` |
236| `createGenerateVideo` | `VideoGenerateInput` | `VideoGenerateResult` |
237| `createGeneration` | Your own input type | Your own result type |
238
239```tsx
240import { createGenerateImage, fetchServerSentEvents } from "@tanstack/ai-remix";
241import { on, type Handle } from "remix/ui";
242
243function ImageGenerator(handle: Handle) {
244 const image = createGenerateImage(handle, {
245 connection: fetchServerSentEvents("/api/generate/image"),
246 threadId: "image-studio",
247 });
248
249 return () => (
250 <button
251 type="button"
252 disabled={image.isLoading}
253 mix={on("click", () => {
254 void image.generate({ prompt: "A sunset over mountains" });
255 })}
256 >
257 Generate
258 </button>
259 );
260}
261```
262
263Options: `threadId` (required), `connection` or `fetcher`, `body`, `persistence`, `byok`, `byokProvider`, `devtools`, `onResult`, `onError`, `onProgress`, `onChunk`.
264
265Returns: `generate(input)`, `result`, `isLoading`, `error`, `status`, `stop()`, `reset()`, `runId`. The state fields are getters.
266
267`createGenerateVideo` also returns `jobId` and `videoStatus`, and takes `onJobCreated` and `onStatusUpdate`.
268
269## `createRealtimeChat(handle, options)`
270
271Runs a voice conversation with a realtime model. Pass `getToken` and `adapter`. See [Realtime Chat](../media/realtime-chat).
272
273```tsx
274import { createRealtimeChat } from "@tanstack/ai-remix";
275import { openaiRealtime } from "@tanstack/ai-openai";
276import { on, type Handle } from "remix/ui";
277
278function VoiceChat(handle: Handle) {
279 const chat = createRealtimeChat(handle, {
280 getToken: () => fetch("/api/realtime-token").then((response) => response.json()),
281 adapter: openaiRealtime(),
282 });
283
284 return () => (
285 <button
286 type="button"
287 mix={on("click", () => {
288 if (chat.status === "idle") {
289 void chat.connect();
290 return;
291 }
292 void chat.disconnect();
293 })}
294 >
295 {chat.status === "idle" ? "Start" : "Stop"}
296 </button>
297 );
298}
299```
300
301Returns `status`, `error`, `mode`, `messages`, `connect()`, `disconnect()`, `startListening()`, `stopListening()`, `interrupt()`, `sendText(text)`, `sendImage(data, mimeType)`, `updateSession(config)`, plus audio levels and frequency data for visualizers.
302
303## `createAudioRecorder(handle, options?)`
304
305Records audio from the microphone. See [Audio Recording](../media/audio-recording).
306
307Returns `recording`, `isRecording`, `isSupported` (getters), `start()`, `stop()`, and `cancel()`. Pass `onComplete` to transform the recording. Then `recording` and `stop()` use the transformed type.
308
309## `createByok(handle, client)`
310
311Subscribes to a BYOK keyring. The return value is a function that gives the latest snapshot. See [Bring Your Own Key](../advanced/byok).
312
313```tsx
314import { createByok } from "@tanstack/ai-remix";
315import type { Handle } from "remix/ui";
316import { byok } from "./byok";
317
318function KeyStatus(handle: Handle) {
319 const getSnapshot = createByok(handle, byok);
320
321 return () => {
322 const openai = getSnapshot().status.openai;
323 return <p>{openai && "masked" in openai ? openai.masked : "No key"}</p>;
324 };
325}
326```
327
328The snapshot has `status`, `locked`, `prompt`, and `storageError`. Save a key from your own UI with `byok.update(provider, value)`.
329
330## `createMcpAppBridge(handle, options)`
331
332Creates an MCP App bridge for one thread. Options: `threadId`, `callEndpoint`, `chat`, `fetchImpl`, `onLink`. See [MCP Apps](../mcp/apps).
333
334## `createRegisterWebMCPTools(handle, tools, options?)`
335
336Exposes client tools to the browser WebMCP API. Remix removes them when `handle.signal` aborts. See [WebMCP Tools](../tools/webmcp).
337
338```tsx
339import { createRegisterWebMCPTools } from "@tanstack/ai-remix";
340import { clientEntry, type Handle } from "remix/ui";
341import { searchProducts } from "./tools";
342
343export const ProductsPage = clientEntry(
344 import.meta.url,
345 function ProductsPage(handle: Handle) {
346 createRegisterWebMCPTools(handle, [searchProducts], {
347 onError: (error) => console.error(error),
348 });
349 return () => null;
350 },
351);
352```
353
354Options: `toolOptions`, `context`, and `onError`. `context` is required when a tool declares a required runtime context.
355
356## `createPageWebMCPTools(handle, options?)`
357
358Reads the WebMCP tools that the page registered, 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`. See [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
359
360```ts
361import { createPageWebMCPTools } from "@tanstack/ai-remix";
362import type { Handle } from "remix/ui";
363
364export function readPageTools(handle: Handle) {
365 return createPageWebMCPTools(handle, {
366 filter: (tool) => tool.origin === location.origin,
367 });
368}
369```
370
371Options: `filter` (return `false` to skip a tool) and `onError`.
372
373## Re-exports from `@tanstack/ai-client`
374
375You can import these from `@tanstack/ai-remix` directly. See [`@tanstack/ai-client`](./ai-client) for details.
376
377| Group | Exports |
378| --- | --- |
379| Connection adapters | `fetchServerSentEvents`, `fetchHttpStream`, `fetchJson`, `xhrServerSentEvents`, `xhrHttpStream`, `webSocket`, `stream`, `rpcStream` |
380| Typed options | `createChatClientOptions`, `clientTools` |
381| Clients | `ChatClient`, `GenerationClient`, `VideoGenerationClient`, `RealtimeClient`, `AudioRecorder`, `InterruptManager` |
382| WebMCP | `registerWebMCPTools`, `getWebMCPTools`, `subscribeWebMCPTools` |
383| Errors | `UnsupportedResponseStreamError`, `StreamTruncatedError`, `DurableStreamIncompleteError`, `StreamReconnectLimitError` |
384| Stream helpers | `StreamProcessor`, chunk strategies, `parsePartialJSON`, message converters |
385
386The browser persistence adapters (`localStoragePersistence` and the others) are not re-exported here. Import them from `@tanstack/ai-client`. BYOK helpers (`defineByok`, `defaultByokStorage`, and more) are on the `@tanstack/ai-remix/byok` subpath.
387
388## Types
389
390| Type | What it is |
391| --- | --- |
392| `CreateChatOptions`, `CreateChatReturn` | The options and return value of `createChat`. |
393| `UIMessage<TTools>` | A chat message with typed parts. |
394| `InferChatMessages<T>` | The message type for a `createChatClientOptions` result. |
395| `SendMessageOptions`, `WhenBusy`, `QueueOption`, `QueuedMessage` | Send and queue types. |
396| `DeepPartial<T>` | The type of `partial` while structured output streams. |
397| `Create<Helper>Options`, `Create<Helper>Return` | Options for each helper. The generation and realtime helpers also export a return type. |
398
399Pass a plain tools array to `createChat` or `createChatClientOptions`. Tool names, inputs, and outputs stay typed without `as const`. Import `toolDefinition` from `@tanstack/ai`.