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

preact.md

68 lines2.1 KB

1---
2title: Preact Chat UI
3id: typed-headless-ui-preact
4order: 5
5description: "Build a typed, headless Preact chat UI with createChatHook. The API matches React."
6keywords:
7 - tanstack ai
8 - createChatHook
9 - preact
10 - headless ui
11 - ToolProps
12---
13​
14Install `@tanstack/ai-preact`. Import the UI factory from `@tanstack/ai-preact/ui`. Call `createChatHook({ options, ...components })` once at module scope. Your app calls `useAppChat()` to create the instance. Render `<chat.AppChat />`.
15​
16The factory API matches [React](./react). Widgets are Preact components. Import hooks from `preact/hooks` or `preact/compat` in your widgets if you need them.
17​
18The factory needs a `toolsComponents` entry for every tool name in `chatOptions`. It also needs an `interruptsComponents.generic` entry for every interrupt id. `generic.fallback` is optional.
19​
20The server route matches the [React page](./react). The [chat UI recipes](./recipes/index) show the same option groups. The code there is React, and the shape carries over.
21​
22## Client
23​
24```tsx
25import { fetchServerSentEvents } from '@tanstack/ai-preact'
26import { createChatHook } from '@tanstack/ai-preact/ui'
27import { toolDefinition } from '@tanstack/ai'
28import { z } from 'zod'
29​
30const getWeather = toolDefinition({
31 name: 'getWeather',
32 description: 'Look up weather',
33 inputSchema: z.object({ city: z.string() }),
34 outputSchema: z.object({ temperature: z.number() }),
35}).client()
36​
37const chatOptions = {
38 connection: fetchServerSentEvents('/api/chat'),
39 tools: [getWeather],
41​
42const { useAppChat } = createChatHook({
43 options: chatOptions,
44 components: {
45 layout: (props) => (
46 <main>
47 <props.Messages />
48 <props.Interrupts />
49 <props.Queue />
50 </main>
51 ),
52 message: (props) => (
53 <article>
54 <props.Parts />
55 </article>
56 ),
57 },
58 partsComponents: { fallback: (props) => <span>{props.part.type}</span> },
59 toolsComponents: {
60 getWeather: (props) => <strong>{props.part.input?.city}</strong>,
61 },
62})
63​
64export function ChatScreen() {
65 const chat = useAppChat()
66 return <chat.AppChat />
68```