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

remix.md

304 lines9.5 KB

1---
2title: Remix Chat UI
3id: typed-headless-ui-remix
4order: 7
5description: "Render a streaming chat in Remix 3 with your own components. createChatHook types every tool, part, and interrupt, and widgets are Remix setup functions."
6keywords:
7 - tanstack ai
8 - createChatHook
9 - remix
10 - headless ui
11 - ToolProps
12---
13​
14`createChatHook` from `@tanstack/ai-remix/ui` binds your chat options and components once. Tool calls and approvals stay typed.
15​
16Each screen then creates a chat with `createAppChat(handle, { threadId })` and renders it with `ui.Chat`. Each widget is a Remix setup function that reads `handle.props`. You supply every visible component. There is no default markup or style.
17​
18## Quick setup
19​
201. Install the packages:
21​
22<!-- ::start:tabs variant="package-manager" mode="install" -->
23​
24remix: @tanstack/ai @tanstack/ai-remix @tanstack/ai-openai remix
25​
26<!-- ::end:tabs -->
27​
282. Put `OPENAI_API_KEY` in your server environment. Then add a `POST` route at `/api/chat`:
29​
30```ts
31import {
32 chat,
33 chatParamsFromRequest,
34 toServerSentEventsResponse,
35} from '@tanstack/ai'
36import { openaiText } from '@tanstack/ai-openai'
37​
38export async function POST(request: Request) {
39 const { messages, threadId, runId } = await chatParamsFromRequest(request)
40​
41 const stream = chat({
42 adapter: openaiText('gpt-6.1-sol'),
43 messages,
44 threadId,
45 runId,
46 })
47​
48 return toServerSentEventsResponse(stream)
50```
51​
523. Create `app/chat.tsx`:
53​
54```tsx
55import { fetchServerSentEvents } from '@tanstack/ai-remix'
56import {
57 createChatHook,
58 type LayoutProps,
59 type MessageProps,
60 type PartProps,
61} from '@tanstack/ai-remix/ui'
62import { clientEntry, on, type Handle } from 'remix/ui'
63​
64const chatOptions = {
65 connection: fetchServerSentEvents('/api/chat'),
67​
68const { createAppChat, ui } = createChatHook({
69 options: chatOptions,
70 components: {
71 layout(handle: Handle<LayoutProps<typeof chatOptions>>) {
72 return () => {
73 const { Messages } = handle.props
74 return (
75 <section>
76 <Messages />
77 </section>
78 )
79 }
80 },
81 message(handle: Handle<MessageProps<typeof chatOptions>>) {
82 return () => {
83 const { message, Parts } = handle.props
84 return (
85 <article data-role={message.role}>
86 <Parts />
87 </article>
88 )
89 }
90 },
91 },
92 partsComponents: {
93 text(handle: Handle<PartProps<typeof chatOptions, 'text'>>) {
94 return () => <p>{handle.props.part.content}</p>
95 },
96 fallback() {
97 return () => null
98 },
99 },
100})
101​
102export const ChatScreen = clientEntry(
103 import.meta.url,
104 function ChatScreen(handle: Handle) {
105 const chat = createAppChat(handle, { threadId: 'support-chat' })
106​
107 return () => (
108 <main>
109 <ui.Chat chat={chat} />
110 <form
111 mix={on('submit', (event) => {
112 event.preventDefault()
113 const form = event.currentTarget
114 const text = String(new FormData(form).get('message') ?? '').trim()
115 if (text === '') {
116 return
117 }
118 form.reset()
119 void chat.sendMessage(text)
120 })}
121 >
122 <input name="message" />
123 <button type="submit">Send</button>
124 </form>
125 </main>
126 )
127 },
129```
130​
1314. Render `<ChatScreen />` and send a message.
132​
133The reply streams into the page as the model writes it.
134​
135## How it works
136​
137- `createChatHook` runs once, at module scope. It binds `chatOptions` to your components. It returns `ui`, the kit with `ui.Chat`.
138- `createAppChat(handle, { threadId })` creates one chat instance inside a setup function. `ui.Chat` renders that instance with your components.
139- `layout` places the message list. `message` wraps one message. `Parts` picks a component for each part of that message.
140- `partsComponents.text` renders text. `fallback` catches every part type that you did not register.
141​
142Render `Messages` and `Parts` as tags, such as `<Messages />`, not as function calls.
143​
144## Next steps
145​
146Each step adds one thing to the quick setup. The [chat UI recipes](./recipes/index) have the full file for each one. The recipes use React, and the option names are the same in Remix.
147​
148### Render a tool
149​
150Add the tool to `tools` in `chatOptions`. Then register a component under the tool name in `toolsComponents`. Type its handle with `ToolProps`:
151​
152```tsx ignore
153toolsComponents: {
154 getWeather(handle: Handle<ToolProps<typeof chatOptions, 'getWeather'>>) {
155 return () => {
156 const { part } = handle.props
157 if (part.state !== 'complete') return <p>Looking up weather</p>
158 return (
159 <p>
160 {part.input?.city}: {part.output?.temperature}
161 </p>
162 )
163 }
164 },
165},
166```
167​
168The factory needs one entry for every tool in `chatOptions`. Full example: [Make a tool look right](./recipes/format-a-tool).
169​
170### Ask before a tool runs
171​
172Set `needsApproval: true` on the tool. The tool component then gets an `interrupt` prop:
173​
174```tsx ignore
175toolsComponents: {
176 deleteFile(handle: Handle<ToolProps<typeof chatOptions, 'deleteFile'>>) {
177 return () => {
178 const { part, interrupt } = handle.props
179 if (interrupt?.status !== 'pending') return <p>{part.input?.path}</p>
180 return (
181 <button
182 mix={on('click', () => interrupt.resolveInterrupt(true))}
183 >
184 Delete {part.input?.path}
185 </button>
186 )
187 }
188 },
189},
190```
191​
192`resolveInterrupt(true)` approves. `resolveInterrupt(false)` denies. Full example: [Ask before a tool runs](./recipes/tool-approval).
193​
194### Ask the user your own question
195​
196Define the question with `defineInterrupt`. Add it to `interrupts` in `chatOptions`. Register a component under its id in `interruptsComponents.generic`, and render `Interrupts` in the layout:
197​
198```tsx ignore
199const choosePlan = defineInterrupt({
200 id: 'choosePlan',
201 payloadSchema: z.object({ title: z.string() }),
202 responseSchema: z.string(),
203})
204​
205// In createChatHook:
206interruptsComponents: {
207 generic: {
208 choosePlan(
209 handle: Handle<InterruptProps<typeof chatOptions, 'choosePlan'>>,
210 ) {
211 return () => {
212 const { interrupt } = handle.props
213 return (
214 <button mix={on('click', () => interrupt.resolveInterrupt('pro'))}>
215 {interrupt.payload?.title}
216 </button>
217 )
218 }
219 },
220 },
221},
222```
223​
224The factory needs one entry for every interrupt id in `chatOptions`. Full example: [Ask the user your own question](./recipes/custom-interrupt).
225​
226### Read chat state inside a widget
227​
228Mapped components do not get `chat` as a prop. Import `ui` and call `ui.useChatContext(handle)` inside the widget. This also moves the composer into the layout. Create `app/chat-input.tsx`:
229​
230```tsx ignore
231import { on, type Handle, type RemixNode } from 'remix/ui'
232import { ui } from './chat'
233​
234export function ChatInput(handle: Handle): () => RemixNode {
235 const chat = ui.useChatContext(handle)
236​
237 return () => (
238 <form
239 mix={on('submit', (event) => {
240 event.preventDefault()
241 const form = event.currentTarget
242 const text = String(new FormData(form).get('message') ?? '').trim()
243 if (text === '') {
244 return
245 }
246 form.reset()
247 void chat.sendMessage(text)
248 })}
249 >
250 <input name="message" disabled={chat.isLoading} />
251 <button type="submit">Send</button>
252 </form>
253 )
255```
256​
257Then:
258​
2591. Export `ui` from `app/chat.tsx`.
2602. Register `input: ChatInput` on `components`.
2613. Render `<Input />` in the layout, from `handle.props`.
2624. Remove the form from `ChatScreen`.
263​
264The return type on `ChatInput` stops a circular type between the widget and the `ui` that registers it. Call `ui.useChatContext(handle)` only under `ui.Chat` or `ui.Provider`. A call outside that tree throws.
265​
266### Render markdown
267​
268`TextPart` from `@tanstack/ai-remix/ui` renders the content as plain text, with no markdown. To render markdown, render `part.content` in your own text part with the markdown library of your choice.
269​
270### Type a widget in its own file
271​
272Type the `handle.props` of a widget with `ToolProps`, `PartProps`, `InterruptProps`, `LayoutProps`, or `MessageProps`. Pass `typeof chatOptions` and a name. Share `chatOptions` from its own module:
273​
274```tsx ignore
275import type { ToolProps } from '@tanstack/ai-remix/ui'
276import type { Handle } from 'remix/ui'
277import { chatOptions } from './chat-options'
278​
279export function WeatherTool(
280 handle: Handle<ToolProps<typeof chatOptions, 'getWeather'>>,
281) {
282 return () => <strong>{handle.props.part.input?.city}</strong>
284```
285​
286You now have a typed chat UI in Remix. Each widget is your own component.
287​
288## Advanced
289​
290### Slots and props
291​
292The config keys, part keys, and prop types are the same as in React. See [Every widget slot](./react#every-widget-slot). In Remix, `layout` gets `Messages`, `Interrupts`, `Queue`, and `Input`. If you render `Input` with no registered `input`, it renders nothing and warns once in development.
293​
294`createAppChat(handle, overrides)` takes per-instance options: `threadId` (required), `initialMessages`, `live`, and `forwardedProps`.
295​
296### Approvals and generic interrupts
297​
298- A tool approval renders in the tool when you read the `interrupt` prop.
299- To show it in the list instead, register a component under `interruptsComponents.tools` and render `Interrupts`.
300- Generic interrupts always render in the list. `generic.fallback` renders an unregistered id and an unbound interrupt. If the copy must be different, branch on `interrupt.kind === 'unbound'`.
301​
302### Show queued messages
303​
304Register `queue` on `components`, then render `<Queue />` in the layout. A queue component gets one `item`. Call `item.cancelQueued()` to drop it.