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

svelte.md

285 lines8.5 KB

1---
2title: Svelte Chat UI
3id: typed-headless-ui-svelte
4order: 4
5description: "Render a streaming chat in Svelte 5 with your own components. createChatHook types every tool, part, and interrupt, and snippets place the pieces."
6keywords:
7 - tanstack ai
8 - createChatHook
9 - svelte
10 - headless ui
11 - ToolProps
12---
13​
14`createChatHook` from `@tanstack/ai-svelte/ui` binds your chat options and components once. Tool calls and approvals stay typed.
15​
16Each screen then creates a chat with `createAppChat()` and renders it with `UIChat`. 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​
24svelte: @tanstack/ai @tanstack/ai-svelte @tanstack/ai-openai
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 three widget files in `src/lib/chat/`. `Layout.svelte` places the message list:
53​
54```svelte
55<script lang="ts">
56 import type { Snippet } from 'svelte'
57​
58 let { messages }: { messages: Snippet } = $props()
59</script>
60​
61<section>
62 {@render messages()}
63</section>
64```
65​
66`Message.svelte` wraps one message:
67​
68```svelte
69<script lang="ts">
70 import type { Snippet } from 'svelte'
71 import type { MessageProps } from '@tanstack/ai-svelte/ui'
72 import type { chatOptions } from './chat-ui'
73​
74 let {
75 message,
76 parts,
77 }: MessageProps<typeof chatOptions> & { parts: Snippet } = $props()
78</script>
79​
80<article data-role={message.role}>
81 {@render parts()}
82</article>
83```
84​
85`Text.svelte` renders a text part:
86​
87```svelte
88<script lang="ts">
89 import type { PartProps } from '@tanstack/ai-svelte/ui'
90 import type { chatOptions } from './chat-ui'
91​
92 let { part }: PartProps<typeof chatOptions, 'text'> = $props()
93</script>
94​
95<p>{part.content}</p>
96```
97​
984. Create `src/lib/chat/chat-ui.ts`:
99​
100```ts ignore
101import { fetchServerSentEvents } from '@tanstack/ai-svelte'
102import { createChatHook } from '@tanstack/ai-svelte/ui'
103import Layout from './Layout.svelte'
104import Message from './Message.svelte'
105import Text from './Text.svelte'
106​
107export const chatOptions = {
108 connection: fetchServerSentEvents('/api/chat'),
110​
111export const { createAppChat, ui } = createChatHook({
112 options: chatOptions,
113 components: { layout: Layout, message: Message },
114 partsComponents: { text: Text },
115})
116```
117​
1185. Create `src/lib/chat/Chat.svelte`:
119​
120```svelte
121<script lang="ts">
122 import { UIChat } from '@tanstack/ai-svelte/ui'
123 import { createAppChat, ui } from './chat-ui'
124​
125 const chat = createAppChat({ threadId: 'support-chat' })
126 let draft = $state('')
127​
128 function send(event: SubmitEvent) {
129 event.preventDefault()
130 const text = draft.trim()
131 if (!text) return
132 draft = ''
133 void chat.sendMessage(text)
134 }
135</script>
136​
137<main>
138 <UIChat {ui} {chat} />
139 <form onsubmit={send}>
140 <input bind:value={draft} />
141 <button type="submit">Send</button>
142 </form>
143</main>
144```
145​
1466. Render `<Chat />` and send a message.
147​
148The reply streams into the page as the model writes it.
149​
150## How it works
151​
152- `createChatHook` runs once, at module scope. It binds `chatOptions` to your components. It returns `ui`, the descriptor that `UIChat` reads.
153- `createAppChat({ threadId })` creates one chat instance. `UIChat` renders that instance with your components.
154- `layout` gets the `messages`, `interrupts`, `queue`, and `input` snippets. `message` gets one message plus the `parts` snippet.
155- `partsComponents.text` renders text. A part type with no component renders nothing and warns once in development. Register `partsComponents.fallback` to catch those parts.
156​
157## Next steps
158​
159Each 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 Svelte.
160​
161### Render a tool
162​
163Add the tool to `tools` in `chatOptions`. Then register a component under the tool name in `toolsComponents`. Type its props with `ToolProps`:
164​
165```svelte
166<script lang="ts">
167 import type { ToolProps } from '@tanstack/ai-svelte/ui'
168 import type { chatOptions } from './chat-ui'
169​
170 let { part }: ToolProps<typeof chatOptions, 'getWeather'> = $props()
171</script>
172​
173{#if part.state === 'complete'}
174 <p>{part.input?.city}: {part.output?.temperature}</p>
175{:else}
176 <p>Looking up weather</p>
177{/if}
178```
179​
180The factory needs one entry for every tool in `chatOptions`. Full example: [Make a tool look right](./recipes/format-a-tool).
181​
182### Ask before a tool runs
183​
184Set `needsApproval: true` on the tool. The tool component then gets an `interrupt` prop:
185​
186```svelte
187<script lang="ts">
188 import type { ToolProps } from '@tanstack/ai-svelte/ui'
189 import type { chatOptions } from './chat-ui'
190​
191 let { part, interrupt }: ToolProps<typeof chatOptions, 'deleteFile'> =
192 $props()
193</script>
194​
195{#if interrupt?.status === 'pending'}
196 <button onclick={() => interrupt?.resolveInterrupt(true)}>
197 Delete {part.input?.path}
198 </button>
199{:else}
200 <p>{part.input?.path}</p>
201{/if}
202```
203​
204`resolveInterrupt(true)` approves. `resolveInterrupt(false)` denies. Full example: [Ask before a tool runs](./recipes/tool-approval).
205​
206### Ask the user your own question
207​
208Define the question with `defineInterrupt`. Add it to `interrupts` in `chatOptions`. Register a component under its id in `interruptsComponents.generic`, and render the `interrupts` snippet in the layout:
209​
210```svelte
211<script lang="ts">
212 import type { InterruptProps } from '@tanstack/ai-svelte/ui'
213 import type { chatOptions } from './chat-ui'
214​
215 let { interrupt }: InterruptProps<typeof chatOptions, 'choosePlan'> =
216 $props()
217</script>
218​
219<button onclick={() => interrupt.resolveInterrupt('pro')}>
220 {interrupt.payload?.title}
221</button>
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()` inside the widget. This also moves the composer into the layout. Create `Input.svelte`:
229​
230```svelte
231<script lang="ts">
232 import { ui } from './chat-ui'
233​
234 const chat = ui.useChatContext()
235 let draft = $state('')
236​
237 function send(event: SubmitEvent) {
238 event.preventDefault()
239 const text = draft.trim()
240 if (!text) return
241 draft = ''
242 void chat.sendMessage(text)
243 }
244</script>
245​
246<form onsubmit={send}>
247 <input bind:value={draft} disabled={chat.isLoading} />
248 <button type="submit">Send</button>
249</form>
250```
251​
252Register it as `components.input`. Then render `{@render input()}` in `Layout.svelte`, and remove the form from `Chat.svelte`.
253​
254Call `ui.useChatContext()` only inside `UIChat` or `UIProvider`. A call outside that tree throws.
255​
256### Render markdown
257​
258`@tanstack/ai-svelte/ui` has no `TextPart` component. Render `part.content` in your own text part, with the markdown library of your choice.
259​
260### Type a widget in its own file
261​
262Every widget above is already in its own file. Type its `$props()` with `ToolProps`, `PartProps`, `InterruptProps`, or `MessageProps`. Pass `typeof chatOptions` and a name.
263​
264You now have a typed chat UI in Svelte. Each widget is your own component.
265​
266## Advanced
267​
268### Slots and props
269​
270The config keys, part keys, and prop types are the same as in React. See [Every widget slot](./react#every-widget-slot). In Svelte, components place content with snippets:
271​
272- `layout`: the `messages`, `interrupts`, `queue`, and `input` snippets.
273- `message`: the `message` prop and the `parts` snippet.
274​
275`createAppChat()` takes per-instance options: `threadId` (required), `initialMessages`, `live`, and `forwardedProps`.
276​
277### Approvals and generic interrupts
278​
279- A tool approval renders in the tool when you read the `interrupt` prop.
280- To show it in the list instead, register a component under `interruptsComponents.tools` and render the `interrupts` snippet.
281- 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'`.
282​
283### Show queued messages
284​
285Register `queue` on `components`, then render `{@render queue()}` in the layout. A queue component gets one `item`. Call `item.cancelQueued()` to drop it.