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

vue.md

414 lines12.6 KB

1---
2title: Vue Chat UI
3id: typed-headless-ui-vue
4order: 3
5description: "Render a streaming chat in Vue with your own components. createChatHook types every tool, part, and interrupt, and slots place the pieces."
6keywords:
7 - tanstack ai
8 - createChatHook
9 - vue
10 - headless ui
11 - ToolProps
12---
13​
14`createChatHook` from `@tanstack/ai-vue/ui` binds your chat options and components once. Tool calls and approvals stay typed.
15​
16Each screen then creates a chat with `useAppChat()` and renders it with `UIChat`. You supply every visible component. There is no default markup or style.
17​
18> [!NOTE]
19> Upgrading from `@tanstack/ai-vue-ui`? Read [Upgrade to 1.0](../migration/v1#chat-ui-components).
20​
21## Quick setup
22​
231. Install the packages:
24​
25<!-- ::start:tabs variant="package-manager" mode="install" -->
26​
27vue: @tanstack/ai @tanstack/ai-vue @tanstack/ai-openai
28​
29<!-- ::end:tabs -->
30​
312. Put `OPENAI_API_KEY` in your server environment. Then add a `POST` route at `/api/chat`:
32​
33```ts
34import {
35 chat,
36 chatParamsFromRequest,
37 toServerSentEventsResponse,
38} from '@tanstack/ai'
39import { openaiText } from '@tanstack/ai-openai'
40​
41export async function POST(request: Request) {
42 const { messages, threadId, runId } = await chatParamsFromRequest(request)
43​
44 const stream = chat({
45 adapter: openaiText('gpt-6.1-sol'),
46 messages,
47 threadId,
48 runId,
49 })
50​
51 return toServerSentEventsResponse(stream)
53```
54​
553. Create `src/chat-ui.ts`:
56​
57```ts
58import { defineComponent, h } from 'vue'
59import { fetchServerSentEvents } from '@tanstack/ai-vue'
60import { createChatHook } from '@tanstack/ai-vue/ui'
61​
62const chatOptions = {
63 connection: fetchServerSentEvents('/api/chat'),
65​
66export const { useAppChat, ui } = createChatHook({
67 options: chatOptions,
68 components: {
69 layout: defineComponent((_, { slots }) => () =>
70 h('section', slots.messages?.()),
71 ),
72 message: defineComponent({
73 props: ['message'],
74 setup(props, { slots }) {
75 return () =>
76 h('article', { 'data-role': props.message.role }, slots.parts?.())
77 },
78 }),
79 },
80 partsComponents: {
81 text: defineComponent({
82 props: ['part'],
83 setup(props) {
84 return () => h('p', props.part.content)
85 },
86 }),
87 fallback: defineComponent(() => () => null),
88 },
89})
90```
91​
924. Create `src/Chat.vue`:
93​
94```vue
95<script setup lang="ts">
96import { ref } from 'vue'
97import { UIChat } from '@tanstack/ai-vue/ui'
98import { ui, useAppChat } from './chat-ui'
99​
100const chat = useAppChat({ threadId: 'support-chat' })
101const draft = ref('')
102​
103function send() {
104 const text = draft.value.trim()
105 if (!text) return
106 draft.value = ''
107 void chat.sendMessage(text)
109</script>
110​
111<template>
112 <main>
113 <UIChat :ui="ui" :chat="chat" />
114 <form @submit.prevent="send">
115 <input v-model="draft" />
116 <button type="submit">Send</button>
117 </form>
118 </main>
119</template>
120```
121​
1225. Render `<Chat />` and send a message.
123​
124The reply streams into the page as the model writes it.
125​
126## How it works
127​
128- `createChatHook` runs once, at module scope. It binds `chatOptions` to your components. It returns `ui`, the descriptor that `UIChat` reads.
129- `useAppChat({ threadId })` creates one chat instance. `UIChat` renders that instance with your components.
130- `layout` places the message list with the `messages` slot. `message` gets one message plus a `parts` slot. The `parts` slot picks a component for each part.
131- `partsComponents.text` renders text. `fallback` catches every part type that you did not register.
132​
133## Next steps
134​
135Each 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 Vue.
136​
137### Render a tool
138​
139Add the tool to `tools` in `chatOptions`. Then register a component under the tool name in `toolsComponents`. A tool component gets the `part`, `result`, and `interrupt` props.
140​
141```ts ignore
142toolsComponents: {
143 getWeather: defineComponent({
144 props: ['part'],
145 setup(props) {
146 return () =>
147 props.part.state === 'complete'
148 ? h('p', `${props.part.input?.city}: ${props.part.output?.temperature}`)
149 : h('p', 'Looking up weather')
150 },
151 }),
152},
153```
154​
155The factory needs one entry for every tool in `chatOptions`. Full example: [Make a tool look right](./recipes/format-a-tool).
156​
157### Ask before a tool runs
158​
159Set `needsApproval: true` on the tool. The tool component then gets an `interrupt` prop:
160​
161```ts ignore
162toolsComponents: {
163 deleteFile: defineComponent({
164 props: ['part', 'interrupt'],
165 setup(props) {
166 return () =>
167 props.interrupt?.status === 'pending'
168 ? h(
169 'button',
170 { onClick: () => props.interrupt.resolveInterrupt(true) },
171 `Delete ${props.part.input?.path}`,
172 )
173 : h('p', props.part.input?.path)
174 },
175 }),
176},
177```
178​
179`resolveInterrupt(true)` approves. `resolveInterrupt(false)` denies. Full example: [Ask before a tool runs](./recipes/tool-approval).
180​
181### Ask the user your own question
182​
183Define the question with `defineInterrupt`. Add it to `interrupts` in `chatOptions`. Register a component under its id in `interruptsComponents.generic`, and render the `interrupts` slot in the layout:
184​
185```ts ignore
186const choosePlan = defineInterrupt({
187 id: 'choosePlan',
188 payloadSchema: z.object({ title: z.string() }),
189 responseSchema: z.string(),
190})
191​
192// In createChatHook:
193interruptsComponents: {
194 generic: {
195 choosePlan: defineComponent({
196 props: ['interrupt'],
197 setup(props) {
198 return () =>
199 h(
200 'button',
201 { onClick: () => props.interrupt.resolveInterrupt('pro') },
202 props.interrupt.payload?.title,
203 )
204 },
205 }),
206 },
207},
208```
209​
210The factory needs one entry for every interrupt id in `chatOptions`. Full example: [Ask the user your own question](./recipes/custom-interrupt).
211​
212### Read chat state inside a widget
213​
214Mapped components do not get `chat` as a prop. Read the chat from context inside the widget. This also moves the composer into the layout: register it as `input`, then render the `input` slot.
215​
216A widget that the factory registers cannot read `ui` from the same call. Create the context first with `createChatHookContexts()`, and pass its `chatKey` under `context`:
217​
218```ts
219import { defineComponent, h, ref } from 'vue'
220import { fetchServerSentEvents } from '@tanstack/ai-vue'
221import {
222 createChatHook,
223 createChatHookContexts,
224} from '@tanstack/ai-vue/ui'
225​
226const { chatKey, useChatContext } = createChatHookContexts()
227​
228const ChatInput = defineComponent(() => {
229 const chat = useChatContext()
230 const draft = ref('')
231​
232 return () =>
233 h(
234 'form',
235 {
236 onSubmit: (event: Event) => {
237 event.preventDefault()
238 const text = draft.value.trim()
239 if (!text) return
240 draft.value = ''
241 void chat.sendMessage(text)
242 },
243 },
244 [
245 h('input', {
246 value: draft.value,
247 disabled: chat.isLoading.value,
248 onInput: (event: Event) => {
249 if (event.target instanceof HTMLInputElement) {
250 draft.value = event.target.value
251 }
252 },
253 }),
254 h('button', { type: 'submit' }, 'Send'),
255 ],
256 )
257})
258​
259const chatOptions = {
260 connection: fetchServerSentEvents('/api/chat'),
262​
263export const { useAppChat, ui } = createChatHook({
264 options: chatOptions,
265 context: { chatKey },
266 components: {
267 input: ChatInput,
268 layout: defineComponent((_, { slots }) => () =>
269 h('main', [slots.messages?.(), slots.input?.()]),
270 ),
271 message: defineComponent((_, { slots }) => () =>
272 h('article', slots.parts?.()),
273 ),
274 },
275 partsComponents: { fallback: defineComponent(() => () => null) },
276})
277```
278​
279In Vue, `chat.messages`, `chat.isLoading`, and `chat.error` are refs. Read them with `.value` in script. Call `useChatContext()` only inside `UIChat` or `UIProvider`. A call outside that tree throws.
280​
281### Render markdown
282​
283Model replies arrive as markdown. Register `TextPart` from `@tanstack/ai-vue/ui` as the text part:
284​
285```ts ignore
286import { TextPart } from '@tanstack/ai-vue/ui'
287​
288partsComponents: {
289 text: defineComponent({
290 props: ['part'],
291 setup(props) {
292 return () => h(TextPart, { content: props.part.content })
293 },
294 }),
295},
296```
297​
298`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).
299​
300### Type a widget in its own file
301​
302Move a widget to its own file and type its props with `ToolProps`, `PartProps`, or `InterruptProps`. Pass `typeof chatOptions` and a name:
303​
304```ts
305import { defineComponent, h } from 'vue'
306import { fetchServerSentEvents } from '@tanstack/ai-vue'
307import { createChatHook, type ToolProps } from '@tanstack/ai-vue/ui'
308import { toolDefinition } from '@tanstack/ai'
309import { z } from 'zod'
310​
311const getWeather = toolDefinition({
312 name: 'getWeather',
313 description: 'Look up weather',
314 inputSchema: z.object({ city: z.string() }),
315 outputSchema: z.object({ temperature: z.number() }),
316}).client()
317​
318const chatOptions = {
319 connection: fetchServerSentEvents('/api/chat'),
320 tools: [getWeather],
322​
323export const WeatherTool = defineComponent(
324 (props: ToolProps<typeof chatOptions, 'getWeather'>) => {
325 return () => h('strong', props.part.input?.city)
326 },
328​
329export const { useAppChat, ui } = createChatHook({
330 options: chatOptions,
331 components: {
332 layout: defineComponent((_, { slots }) => () =>
333 h('div', [slots.messages?.(), slots.interrupts?.(), slots.input?.()]),
334 ),
335 message: defineComponent((_, { slots }) => () => h('article', slots.parts?.())),
336 },
337 partsComponents: { fallback: defineComponent(() => () => null) },
338 toolsComponents: { getWeather: WeatherTool },
339})
340```
341​
342Put `chatOptions` in a shared module so every widget file can import its type.
343​
344You now have a typed chat UI in Vue. Each widget is your own component.
345​
346## Advanced
347​
348### Slots and props
349​
350The config keys, part keys, and prop types are the same as in React. See [Every widget slot](./react#every-widget-slot). In Vue, components place content with slots:
351​
352- `layout`: the `messages`, `interrupts`, `queue`, and `input` slots.
353- `message`: the `message` prop and the `parts` slot.
354​
355`useAppChat()` takes per-instance options: `threadId` (required), `initialMessages`, `live`, and `forwardedProps`.
356​
357### Approvals and generic interrupts
358​
359- A tool approval renders in the tool when you read the `interrupt` prop.
360- To show it in the list instead, register a component under `interruptsComponents.tools` and render the `interrupts` slot.
361- 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'`.
362​
363### Use `ui.useChatContext()` in a child file
364​
365A child component in its own file can import `ui` and call `ui.useChatContext()`. Inside the factory module, declare the child after the `createChatHook` call. Annotate it as `Component`, so its type does not depend on the components map that renders it:
366​
367```ts
368import { defineComponent, h } from 'vue'
369import type { Component } from 'vue'
370import { fetchServerSentEvents } from '@tanstack/ai-vue'
371import { createChatHook, UIChat } from '@tanstack/ai-vue/ui'
372​
373const chatOptions = {
374 connection: fetchServerSentEvents('/api/chat'),
376​
377const { useAppChat, ui } = createChatHook({
378 options: chatOptions,
379 components: {
380 layout: defineComponent((_, { slots }) => () =>
381 h('main', [h(StatusLine), slots.messages?.()]),
382 ),
383 message: defineComponent((_, { slots }) => () => h('article', slots.parts?.())),
384 },
385 partsComponents: { fallback: defineComponent(() => () => null) },
386})
387​
388// h(StatusLine) runs only at render time, so this order is safe.
389const StatusLine: Component = defineComponent({
390 setup() {
391 const chat = ui.useChatContext()
392 return () => h('p', `${chat.messages.value.length} messages`)
393 },
394})
395​
396export default defineComponent({
397 setup() {
398 const chat = useAppChat({ threadId: 'support-chat' })
399 return () => h(UIChat, { ui, chat })
400 },
401})
402```
403​
404### Walk messages yourself
405​
406`UIMessages` has a default slot with `{ messages }`. `UIMessage` has a default slot with `{ parts }`. Pass `ui` to each one.
407​
408### `TextPart` options
409​
410- `highlighter`: a synchronous `CodeHighlighter`. Its output is trusted HTML, so use `createTanStackMarkdownHighlighter` or another highlighter that escapes source text.
411- `extensions`: more TanStack Markdown extensions. The streaming extension is always on.
412- `class`, `userClass`, `assistantClass`: classes for the wrapper. Pass `role` to apply the role class.
413​
414If you still pass `remarkPlugins`, `rehypePlugins`, or `disableDefaultPlugins`, read [TextPart markdown](../migration/text-part-markdown).