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

react.md

543 lines17.0 KB

1---
2title: React Chat UI
3id: typed-headless-ui-react
4order: 1
5description: "Render a streaming chat in React with your own components. createChatHook types every tool, part, and interrupt from your chat options."
6keywords:
7 - tanstack ai
8 - createChatHook
9 - react
10 - headless ui
11 - useAppChat
12 - ToolProps
13---
14​
15`createChatHook` from `@tanstack/ai-react/ui` binds your chat options and components once. Tool calls and approvals stay typed.
16​
17Each screen then renders the chat with one hook call. You supply every visible component. There is no default markup or style.
18​
19> [!NOTE]
20> Upgrading from `@tanstack/ai-react-ui`? Read [Upgrade to 1.0](../migration/v1#chat-ui-components).
21​
22## Quick setup
23​
241. Install the packages:
25​
26<!-- ::start:tabs variant="package-manager" mode="install" -->
27​
28react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openai
29​
30<!-- ::end:tabs -->
31​
322. Put `OPENAI_API_KEY` in your server environment. Then add a `POST` route at `/api/chat`:
33​
34```ts
35import {
36 chat,
37 chatParamsFromRequest,
38 toServerSentEventsResponse,
39} from '@tanstack/ai'
40import { openaiText } from '@tanstack/ai-openai'
41​
42export async function POST(request: Request) {
43 const { messages, threadId, runId } = await chatParamsFromRequest(request)
44​
45 const stream = chat({
46 adapter: openaiText('gpt-6.1-sol'),
47 messages,
48 threadId,
49 runId,
50 })
51​
52 return toServerSentEventsResponse(stream)
54```
55​
563. Create `src/chat.tsx`:
57​
58```tsx
59import { fetchServerSentEvents } from '@tanstack/ai-react'
60import { createChatHook } from '@tanstack/ai-react/ui'
61​
62const chatOptions = {
63 connection: fetchServerSentEvents('/api/chat'),
65​
66const { useAppChat } = createChatHook({
67 options: chatOptions,
68 components: {
69 layout: ({ Messages }) => (
70 <section>
71 <Messages />
72 </section>
73 ),
74 message: ({ message, Parts }) => (
75 <article data-role={message.role}>
76 <Parts />
77 </article>
78 ),
79 },
80 partsComponents: {
81 text: ({ part }) => <p>{part.content}</p>,
82 fallback: () => null,
83 },
84})
85​
86export function ChatScreen() {
87 const chat = useAppChat({ threadId: 'support-chat' })
88​
89 return (
90 <main>
91 <chat.AppChat />
92 <form
93 onSubmit={(event) => {
94 event.preventDefault()
95 const field = event.currentTarget.elements.namedItem('message')
96 if (!(field instanceof HTMLInputElement)) return
97 const text = field.value.trim()
98 if (!text) return
99 field.value = ''
100 void chat.sendMessage(text)
101 }}
102 >
103 <input name="message" />
104 <button type="submit">Send</button>
105 </form>
106 </main>
107 )
109```
110​
1114. Render `<ChatScreen />` and send a message.
112​
113The reply streams into the page as the model writes it.
114​
115## How it works
116​
117- `createChatHook` runs once, at module scope. It binds `chatOptions` to your components.
118- `useAppChat({ threadId })` creates one chat instance. `chat.AppChat` renders that instance with your components.
119- `layout` places the message list. `message` wraps one message. `Parts` picks a component for each part of that message.
120- `partsComponents.text` renders text. `fallback` catches every part type that you did not register.
121​
122## Next steps
123​
124Each step adds one thing to the quick setup. The [chat UI recipes](./recipes/index) have the full file for each one.
125​
126### Render a tool
127​
128Add the tool to `tools` in `chatOptions`. Then register a component under the tool name in `toolsComponents`. `part.input` and `part.output` are typed from the tool schemas.
129​
130```tsx ignore
131toolsComponents: {
132 getWeather: ({ part }) => {
133 if (part.state !== 'complete') return <p>Looking up weather</p>
134 return (
135 <p>
136 {part.input?.city}: {part.output?.temperature}
137 </p>
138 )
139 },
140},
141```
142​
143The factory needs one entry for every tool in `chatOptions`. Full example: [Make a tool look right](./recipes/format-a-tool).
144​
145### Ask before a tool runs
146​
147Set `needsApproval: true` on the tool. The tool component then gets an `interrupt` prop:
148​
149```tsx ignore
150toolsComponents: {
151 deleteFile: ({ part, interrupt }) =>
152 interrupt?.status === 'pending' ? (
153 <button onClick={() => interrupt.resolveInterrupt(true)}>
154 Delete {part.input?.path}
155 </button>
156 ) : (
157 <p>{part.input?.path}</p>
158 ),
159},
160```
161​
162`resolveInterrupt(true)` approves. `resolveInterrupt(false)` denies. Full example: [Ask before a tool runs](./recipes/tool-approval).
163​
164### Ask the user your own question
165​
166Define 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:
167​
168```tsx ignore
169const choosePlan = defineInterrupt({
170 id: 'choosePlan',
171 payloadSchema: z.object({ title: z.string() }),
172 responseSchema: z.string(),
173})
174​
175// In createChatHook:
176interruptsComponents: {
177 generic: {
178 choosePlan: ({ interrupt }) => (
179 <button onClick={() => interrupt.resolveInterrupt('pro')}>
180 {interrupt.payload?.title}
181 </button>
182 ),
183 fallback: ({ interrupt }) => <p>{interrupt.reason}</p>,
184 },
185},
186```
187​
188The factory needs one entry for every interrupt id in `chatOptions`. Full example: [Ask the user your own question](./recipes/custom-interrupt).
189​
190### Read chat state inside a widget
191​
192Mapped components do not get `chat` as a prop. Call `useChatContext()` inside the widget. This also moves the composer into the layout: register it as `input`, then render `Input`.
193​
194```tsx
195import { fetchServerSentEvents } from '@tanstack/ai-react'
196import { createChatHook } from '@tanstack/ai-react/ui'
197​
198const chatOptions = {
199 connection: fetchServerSentEvents('/api/chat'),
201​
202const { useAppChat, useChatContext } = createChatHook({
203 options: chatOptions,
204 components: {
205 input: () => {
206 const chat = useChatContext()
207 return (
208 <form
209 onSubmit={(event) => {
210 event.preventDefault()
211 const field = event.currentTarget.elements.namedItem('message')
212 if (!(field instanceof HTMLInputElement)) return
213 const text = field.value.trim()
214 if (!text) return
215 field.value = ''
216 void chat.sendMessage(text)
217 }}
218 >
219 <input name="message" disabled={chat.isLoading} />
220 <button type="submit">Send</button>
221 </form>
222 )
223 },
224 layout: ({ Messages, Input }) => (
225 <main>
226 <Messages />
227 <Input />
228 </main>
229 ),
230 message: ({ Parts }) => (
231 <article>
232 <Parts />
233 </article>
234 ),
235 },
236 partsComponents: {
237 text: ({ part }) => <p>{part.content}</p>,
238 fallback: () => null,
239 },
240})
241​
242export function ChatScreen() {
243 const chat = useAppChat({ threadId: 'support-chat' })
244 return <chat.AppChat />
246```
247​
248Call `useChatContext()` only inside `chat.AppChat`. A call outside that tree throws.
249​
250### Render markdown
251​
252Model replies arrive as markdown. Register `TextPart` from `@tanstack/ai-react/ui` as the text part:
253​
254```tsx ignore
255import { TextPart } from '@tanstack/ai-react/ui'
256​
257partsComponents: {
258 text: ({ part }) => <TextPart content={part.content} />,
259 fallback: () => null,
260},
261```
262​
263`TextPart` uses [TanStack Markdown](https://tanstack.com/markdown). It escapes raw HTML and removes executable URLs. To color fenced code, read [Highlight markdown code](./markdown).
264​
265### Type a widget in its own file
266​
267Move a widget to its own file and type its props with `ToolProps`, `PartProps`, or `InterruptProps`. Pass `typeof chatOptions` and a name:
268​
269```tsx
270import { fetchServerSentEvents } from '@tanstack/ai-react'
271import { createChatHook, type ToolProps } from '@tanstack/ai-react/ui'
272import { toolDefinition } from '@tanstack/ai'
273import { z } from 'zod'
274​
275const getWeather = toolDefinition({
276 name: 'getWeather',
277 description: 'Look up weather',
278 inputSchema: z.object({ city: z.string() }),
279 outputSchema: z.object({ temperature: z.number() }),
280}).client()
281​
282const chatOptions = {
283 connection: fetchServerSentEvents('/api/chat'),
284 tools: [getWeather],
286​
287export function WeatherTool({
288 part,
289}: ToolProps<typeof chatOptions, 'getWeather'>) {
290 if (part.state !== 'complete') return <p>Looking up weather</p>
291 return (
292 <p>
293 {part.input?.city}: {part.output?.temperature}
294 </p>
295 )
297​
298export const { useAppChat } = createChatHook({
299 options: chatOptions,
300 components: {
301 layout: ({ Messages }) => <Messages />,
302 message: ({ Parts }) => (
303 <article>
304 <Parts />
305 </article>
306 ),
307 },
308 partsComponents: { fallback: () => null },
309 toolsComponents: { getWeather: WeatherTool },
310})
311```
312​
313Put `chatOptions` in a shared module so every widget file can import its type.
314​
315You now have a typed chat UI in React. Each widget is your own component.
316​
317## Advanced
318​
319### Every widget slot
320​
321| Config key | Keys | Props |
322| ------------------------------ | ----------------------------------------------------- | ------------------------------------------------------ |
323| `components` | `layout`, `message`, `input`, `queue` | `LayoutProps`, `MessageProps`, `InputProps`, `QueueProps` |
324| `partsComponents` | a part key, or `fallback` | `PartProps<typeof chatOptions, 'text'>` |
325| `toolsComponents` | each tool name in `chatOptions.tools` | `ToolProps<typeof chatOptions, 'getWeather'>` |
326| `interruptsComponents.tools` | an approval tool name | `InterruptProps<typeof chatOptions, 'deleteFile'>` |
327| `interruptsComponents.generic` | each interrupt id, plus an optional `fallback` | `InterruptProps<typeof chatOptions, 'choosePlan'>` |
328| `subagentsComponents` | each subagent name | `SubagentProps`. See [Subagents](../chat/subagents) |
329​
330Part keys:
331​
332- `text`, `thinking`, `activity`
333- `image`, `audio`, `video`, `document`
334- `toolCall`, `toolResult`
335- `structuredOutput`, `uiResource`, `subagent`
336​
337`layout` gets these components. Render them as tags, such as `<Messages />`:
338​
339- `Messages`, `Interrupts`, `Queue`, `Subagents`
340- `Input`, only when you register `input`. Without it, `<Input />` is a compile error.
341​
342`useAppChat()` takes per-instance options: `threadId` (required), `initialMessages`, `live`, and `forwardedProps`. Keep `tools`, `interrupts`, and `outputSchema` on `chatOptions`. Two instances with different `threadId` values keep separate histories:
343​
344```tsx ignore
345const chat = useAppChat({ threadId: 'support-1' })
346```
347​
348### Tool part states
349​
350| `part.state` | Meaning |
351| -------------------- | ------------------------------------------------ |
352| `awaiting-input` | The call started. No arguments yet. |
353| `input-streaming` | The model is still writing the arguments. |
354| `input-complete` | The arguments are final. |
355| `approval-requested` | The tool waits for approval. |
356| `approval-responded` | The user approved or denied. |
357| `complete` | The result arrived. |
358| `error` | The call failed. |
359​
360A tool component also gets `result`, the matching tool-result part, when one exists.
361​
362### Approval next to the tool, or in the list
363​
364A tool with `needsApproval: true` renders its approval in one of two places:
365​
366- **Next to the tool.** Read `interrupt` in the tool component. This is the default.
367- **In the list.** Register a component under `interruptsComponents.tools` with the tool name. Render `Interrupts` in the layout. The approval then leaves the message.
368​
369Do not do both for one tool. A list approval component reads `interrupt.originalArgs`, typed from the tool `inputSchema`.
370​
371### Generic interrupts and `fallback`
372​
373Generic interrupts always render in `Interrupts`. They never render inside a tool. `interruptsComponents.generic.fallback` renders:
374​
375- an interrupt id that you did not register.
376- an unbound interrupt. Something outside this chat owns it, so it cannot be resolved here.
377​
378If the copy for an unbound interrupt must be different, branch on `interrupt.kind === 'unbound'`.
379​
380### Show queued messages
381​
382By default, a message sent while a run streams waits in a [queue](../chat/queueing). Register `queue` on `components` and render `Queue` in the layout. Each item has `cancelQueued()` bound to it:
383​
384```tsx ignore
385components: {
386 layout: ({ Messages, Queue }) => (
387 <main>
388 <Messages />
389 <Queue />
390 </main>
391 ),
392 message: ({ Parts }) => <Parts />,
393 queue: ({ item }) => (
394 <div>
395 {typeof item.content === 'string' ? item.content : 'Queued'}
396 <button type="button" onClick={() => item.cancelQueued()}>
397 Cancel
398 </button>
399 </div>
400 ),
401},
402```
403​
404Type a queue item with `QueueProps<typeof chatOptions>`.
405​
406### List `input` before `layout`
407​
408If `input` is an inline `function` expression written after `layout`, TypeScript cannot see that an input is registered. Then `Input` is missing from the layout props.
409​
410To prevent this, do one of these:
411​
412- Put `input` before `layout`.
413- Use an arrow function or a named component for `input`.
414​
415If it still slips through, `<Input />` without a registered `input` warns once in development.
416​
417### Widgets in other files
418​
419A widget file that imports `useChatContext` from the factory module makes a circular import. To prevent this, call `createChatHookContexts()` in its own module first:
420​
421```tsx ignore
422// chat-contexts.ts
423import { createChatHookContexts } from '@tanstack/ai-react/ui'
424​
425export const { chatContext, partContext, interruptContext, useChatContext } =
426 createChatHookContexts()
427```
428​
429Pass `chatContext`, `partContext`, and `interruptContext` to `createChatHook` under `context`. Widget files then import `useChatContext` from the contexts module.
430​
431Part and interrupt widgets get `part` and `interrupt` as props. Do not read those from context.
432​
433### Walk messages yourself
434​
435`createChatUI` is the lower-level kit. If you map messages yourself, use it. It takes the same component maps:
436​
437```tsx group=manual-traversal
438import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
439import { createChatUI } from '@tanstack/ai-react/ui'
440import { toolDefinition } from '@tanstack/ai'
441import { z } from 'zod'
442​
443const getWeather = toolDefinition({
444 name: 'getWeather',
445 description: 'Look up weather',
446 inputSchema: z.object({ city: z.string() }),
447 outputSchema: z.object({ temperature: z.number() }),
448}).client()
449​
450const chatOptions = {
451 connection: fetchServerSentEvents('/api/chat'),
452 tools: [getWeather],
454​
455const UI = createChatUI(chatOptions, {
456 components: {
457 layout: ({ Messages }) => <Messages />,
458 message: ({ Parts }) => <article><Parts /></article>,
459 },
460 partsComponents: {
461 text: ({ part }) => <p>{part.content}</p>,
462 fallback: () => null,
463 },
464 toolsComponents: {
465 getWeather: ({ part }) => <p>{part.input?.city}</p>,
466 },
467})
468​
469export function ManualChat() {
470 const chat = useChat({ ...chatOptions, threadId: 'support-chat' })
471 return (
472 <UI.Provider chat={chat}>
473 <UI.Messages>
474 {(messages) =>
475 messages.map((message) => (
476 <UI.Message key={message.id} message={message}>
477 {(parts) =>
478 parts.map((part, index) => (
479 <span key={index}>{part.key}</span>
480 ))
481 }
482 </UI.Message>
483 ))
484 }
485 </UI.Messages>
486 </UI.Provider>
487 )
489```
490​
491You can also pick a registered widget at the call site:
492​
493```tsx group=manual-traversal
494import type { MessageProps } from '@tanstack/ai-react/ui'
495​
496function PickedWidgets({
497 message,
498}: {
499 message: MessageProps<typeof chatOptions>['message']
500}) {
501 return (
502 <UI.Message message={message}>
503 {(parts) =>
504 parts.map((part, index) => (
505 <UI.Part key={index} part={part}>
506 {(p) => (part.key === 'toolCall' ? <p.getWeather /> : <p.Render />)}
507 </UI.Part>
508 ))
509 }
510 </UI.Message>
511 )
513```
514​
515- `p.getWeather` and `p.text` are the widgets that you passed to the factory.
516- `p.Render` renders this one part the automatic way.
517- `UI.Input` exists when you register `input`.
518​
519An unknown tool name at runtime warns once in development and renders nothing.
520​
521### `TextPart` options
522​
523- `highlighter`: a synchronous `CodeHighlighter`. Its output is trusted HTML, so use `createTanStackMarkdownHighlighter` or another highlighter that escapes source text.
524- `extensions`: more TanStack Markdown extensions. The streaming extension is always on.
525- `components`: a tag-name map with normal HTML props (`href`, `className`). `inline` and `node` are not passed.
526- `className`, `userClassName`, `assistantClassName`: classes for the wrapper. Pass `role` to apply the role class.
527​
528```tsx
529import { TextPart } from '@tanstack/ai-react/ui'
530​
531export function Reply({ content }: { content: string }) {
532 return (
533 <TextPart
534 content={content}
535 components={{
536 a: (props) => <a {...props} target="_blank" rel="noreferrer" />,
537 }}
538 />
539 )
541```
542​
543If you still pass `remarkPlugins`, `rehypePlugins`, or `disableDefaultPlugins`, read [TextPart markdown](../migration/text-part-markdown).