Open History to see the last commit
1---
2title: "@tanstack/ai-vue"
3id: ai-vue
4order: 5
5description: "API reference for @tanstack/ai-vue: the useChat composable, generation composables, and Vue 3 bindings for the headless TanStack AI client."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-vue"
9 - vue
10 - vue 3
11 - useChat
12 - composables
13 - api reference
14---
15
16Vue 3 composables for TanStack AI. To build your first chat, start with the [Quick Start](../getting-started/quick-start). For a typed chat layout, see [Vue Chat UI](../ui/vue).
17
18## Installation
19
20<!-- ::start:tabs variant="package-manager" mode="install" -->
21
22vue: @tanstack/ai-vue
23
24<!-- ::end:tabs -->
25
26## `useChat(options)`
27
28Holds the messages and the run state of one chat, and talks to your server route.
29
30```vue
31<script setup lang="ts">
32import { ref } from "vue";
33import { useChat, fetchServerSentEvents } from "@tanstack/ai-vue";
34
35const input = ref("");
36const { messages, sendMessage, isLoading } = useChat({
37 connection: fetchServerSentEvents("/api/chat"),
38 threadId: "support-chat",
39});
40
41const handleSubmit = () => {
42 if (input.value.trim() && !isLoading.value) {
43 sendMessage(input.value);
44 input.value = "";
45 }
46};
47</script>
48
49<template>
50 <div>
51 <div v-for="message in messages" :key="message.id">
52 <strong>{{ message.role }}:</strong>
53 <template v-for="(part, idx) in message.parts" :key="idx">
54 <span v-if="part.type === 'text'">{{ part.content }}</span>
55 </template>
56 </div>
57 <form @submit.prevent="handleSubmit">
58 <input v-model="input" />
59 <button type="submit" :disabled="isLoading">Send</button>
60 </form>
61 </div>
62</template>
63```
64
65### Options
66
67You must pass `threadId`. You must also pass `connection` or `fetcher`, not both.
68
69| Option | What it does |
70| --- | --- |
71| `connection` | Connection adapter, for example `fetchServerSentEvents("/api/chat")`. See [Transports](../transports/overview). |
72| `fetcher` | A function that returns a `Response` or a stream. Use it with server functions. |
73| `tools` | Client tools from `.client()`. They run when the model calls them. Pass a ref or a getter to change them later. See [Client Tools](../tools/client-tools). |
74| `threadId` | Required. The id of this chat. Use a stable id for each conversation, for example the id from your route. |
75| `initialMessages` | The messages to show first. |
76| `forwardedProps` | JSON sent to the server in the AG-UI `forwardedProps` field, for example `{ model: "gpt-6.1-sol" }`. |
77| `persistence` | `true` to load the thread from the server, or a storage adapter. See [Chat Persistence](../persistence/chat-persistence). |
78| `outputSchema` | A Standard Schema. Adds typed `partial` and `final` to the return value. See [Streaming structured output](../structured-outputs/streaming). |
79| `context` | Client-only runtime context for client tools. It is not sent to the server. |
80| `live` | Subscribe while `live` is `true`. |
81| `queue` | What `sendMessage` does while a run is busy. Default: queue the message. See [Queueing](../chat/queueing). |
82| `interrupts` | Definitions from `defineInterrupt()`. See [Interrupts](../interrupts/overview). |
83| `byok`, `byokProvider` | A keyring from `defineByok()`. See [Bring Your Own Key](../advanced/byok). |
84| `devtools` | Display options for TanStack AI Devtools. |
85
86The composable also takes the `ChatClient` callbacks (`onResponse`, `onChunk`, `onFinish`, `onError`, `onInterruptStateChange`, `onCustomEvent`) and the other client options. See [`ChatClient` options](./ai-client#constructor-options).
87
88The composable watches `forwardedProps`, `context`, `queue`, and `live`. To change them after the chat starts, read reactive state in an option getter (for example `get forwardedProps() { ... }`). A change updates the current chat.
89
90### Returns
91
92State values are read-only Vue refs. Read `.value` in `<script setup>`. In `<template>`, Vue unwraps them, so use the bare name. Cleanup runs in `onScopeDispose`.
93
94| Field | What it is |
95| --- | --- |
96| `messages` | The `UIMessage` array of the chat. |
97| `sendMessage(content, options?)` | Sends a user message. `content` is a string or `{ content, id?, metadata? }`. `options` takes `whenBusy` and `body`. |
98| `isLoading` | `true` while a response streams. |
99| `error` | The last error, or `undefined`. |
100| `status` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |
101| `stop()` | Stops the current response. |
102| `reload()` | Runs the last user message again. |
103| `append(message)` | Adds a `UIMessage` or `ModelMessage` and starts a run. |
104| `addToolResult(result)` | Gives the result of a client tool by hand: `{ toolCallId, tool, output, state?, errorText? }`. |
105| `setMessages(messages)`, `clear()` | Replace or clear the messages. |
106| `queue`, `cancelQueued(id)` | Messages that wait while a run is busy. See [Queueing](../chat/queueing). |
107| `runId` | The id of the run in flight, or `null`. |
108| `interrupts` | Pending interrupts. Each item has `resolveInterrupt(...)`. See [Interrupts](../interrupts/overview). |
109| `resolveInterrupts`, `cancelInterrupts`, `retryInterrupts`, `resumeInterruptsUnsafe` | Act on all pending interrupts at once. |
110| `interruptErrors`, `resuming` | Errors from the last resume, and `true` while a resume runs. |
111| `isHydrating` | `true` while the chat loads from persistence. |
112| `hasOlderMessages`, `loadOlderMessages()` | Page in older messages. See [Chat Persistence](../persistence/chat-persistence). |
113| `isSubscribed`, `connectionStatus`, `sessionGenerating` | State of the live subscription. |
114| `partial`, `final` | Structured output. Only when you pass `outputSchema`. |
115
116### Example: tool approval
117
118A tool with `needsApproval: true` pauses the run. The pending call shows up in `interrupts`.
119
120```vue
121<script setup lang="ts">
122import { toolDefinition } from "@tanstack/ai";
123import { useChat, fetchServerSentEvents } from "@tanstack/ai-vue";
124import { z } from "zod";
125
126const deleteFileTool = toolDefinition({
127 name: "delete_file",
128 description: "Delete a file",
129 needsApproval: true,
130 inputSchema: z.object({ path: z.string() }),
131});
132
133const { interrupts } = useChat({
134 connection: fetchServerSentEvents("/api/chat"),
135 threadId: "support-chat",
136 tools: [deleteFileTool],
137});
138</script>
139
140<template>
141 <template v-for="interrupt in interrupts" :key="interrupt.id">
142 <div v-if="interrupt.kind === 'tool-approval'">
143 <p>Approve: {{ interrupt.toolName }}</p>
144 <button @click="interrupt.resolveInterrupt(true)">Approve</button>
145 <button @click="interrupt.resolveInterrupt(false)">Deny</button>
146 </div>
147 </template>
148</template>
149```
150
151See [Tool Approval](../interrupts/tool-approval) for the server side.
152
153## `createChatHook(options)`
154
155Binds chat options once at module scope and returns a `useChat` composable that uses them.
156
157```ts
158import { createChatHook, fetchServerSentEvents } from "@tanstack/ai-vue";
159
160export const { useChat: useSupportChat } = createChatHook({
161 connection: fetchServerSentEvents("/api/chat"),
162});
163
164// In a component: const chat = useSupportChat({ threadId: "support-1" })
165```
166
167The bound composable takes these per-call overrides: `threadId`, `initialMessages`, `live`, and `forwardedProps`. Keep `tools`, `interrupts`, and `outputSchema` on the factory options.
168
169`@tanstack/ai-vue/ui` has its own `createChatHook` that also returns typed UI components. See [Vue Chat UI](../ui/vue).
170
171## Generation hooks
172
173Each composable runs one generation request and keeps its result. See [Generation Hooks](../media/generation-hooks).
174
175| Composable | `generate()` input | `result` |
176| --- | --- | --- |
177| `useGenerateImage` | `ImageGenerateInput` | `ImageGenerationResult` |
178| `useGenerateAudio` | `AudioGenerateInput` | `AudioGenerationResult` |
179| `useGenerateSpeech` | `SpeechGenerateInput` | `TTSResult` |
180| `useTranscription` | `TranscriptionGenerateInput` | `TranscriptionResult` |
181| `useSummarize` | `SummarizeGenerateInput` | `SummarizationResult` |
182| `useGenerateVideo` | `VideoGenerateInput` | `VideoGenerateResult` |
183| `useGeneration` | Your own input type | Your own result type |
184
185```vue
186<script setup lang="ts">
187import { useGenerateImage, fetchServerSentEvents } from "@tanstack/ai-vue";
188
189const image = useGenerateImage({
190 connection: fetchServerSentEvents("/api/generate/image"),
191 threadId: "image-studio",
192});
193</script>
194
195<template>
196 <button
197 :disabled="image.isLoading.value"
198 @click="image.generate({ prompt: 'A mountain at sunset' })"
199 >
200 Generate
201 </button>
202</template>
203```
204
205Options: `threadId` (required), `connection` or `fetcher`, `body`, `persistence`, `byok`, `byokProvider`, `devtools`, `onResult`, `onError`, `onProgress`, `onChunk`.
206
207Returns: `generate(input)`, `result`, `isLoading`, `error`, `status`, `stop()`, `reset()`, `runId`. The state fields are read-only refs. Cleanup runs in `onScopeDispose`.
208
209`useGenerateVideo` also returns `jobId` and `videoStatus`, and takes `onJobCreated` and `onStatusUpdate`.
210
211## Realtime chat
212
213This package does not export a realtime composable. Use `RealtimeClient`, which this package re-exports. See [Realtime Chat](../media/realtime-chat).
214
215## `useAudioRecorder(options?)`
216
217Records audio from the microphone. See [Audio Recording](../media/audio-recording).
218
219Returns `recording` and `isRecording` (read-only refs), `isSupported`, `start()`, `stop()`, and `cancel()`. Pass `onComplete` to transform the recording. Then `recording` and `stop()` use the transformed type.
220
221## `useByok(client)`
222
223Subscribes to a BYOK keyring and returns a read-only ref of its snapshot. See [Bring Your Own Key](../advanced/byok).
224
225```ts
226import { computed } from "vue";
227import { useByok } from "@tanstack/ai-vue";
228import { byok } from "./byok";
229
230const snapshot = useByok(byok);
231const last4 = computed(() => {
232 const openai = snapshot.value.status.openai;
233 return openai && "masked" in openai ? openai.masked : "No key";
234});
235```
236
237The snapshot has `status`, `locked`, `prompt`, and `storageError`. Save a key from your own UI with `byok.update(provider, value)`.
238
239## MCP App bridge
240
241This package does not export a bridge composable. Use `createMcpAppBridge`, which this package re-exports. See [MCP Apps](../mcp/apps).
242
243## `useRegisterWebMCPTools(tools, options?)`
244
245Exposes client tools to the browser WebMCP API for the current Vue scope. Vue removes them when the scope is disposed. See [WebMCP Tools](../tools/webmcp).
246
247```vue
248<script setup lang="ts">
249import { useRegisterWebMCPTools } from "@tanstack/ai-vue";
250import { searchProducts } from "./tools";
251
252useRegisterWebMCPTools([searchProducts], {
253 onError: (error) => console.error(error),
254});
255</script>
256```
257
258Options: `toolOptions`, `context`, and `onError`. `context` is required when a tool declares a required runtime context.
259
260## `usePageWebMCPTools(options?)`
261
262Reads the WebMCP tools that the page registered, as client tools. The ref starts empty and updates when the page adds or removes a tool. Pass the ref to `useChat` as `tools`. See [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
263
264```ts
265import { usePageWebMCPTools } from "@tanstack/ai-vue";
266
267export function useSameOriginPageTools() {
268 return usePageWebMCPTools({
269 filter: (tool) => tool.origin === location.origin,
270 });
271}
272```
273
274Options: `filter` (return `false` to skip a tool) and `onError`.
275
276## Re-exports from `@tanstack/ai-client`
277
278You can import these from `@tanstack/ai-vue` directly. See [`@tanstack/ai-client`](./ai-client) for details.
279
280| Group | Exports |
281| --- | --- |
282| Connection adapters | `fetchServerSentEvents`, `fetchHttpStream`, `fetchJson`, `xhrServerSentEvents`, `xhrHttpStream`, `webSocket`, `stream`, `rpcStream` |
283| Typed options | `createChatClientOptions`, `clientTools` |
284| Persistence | `localStoragePersistence`, `sessionStoragePersistence`, `indexedDBPersistence` |
285| Clients | `ChatClient`, `GenerationClient`, `VideoGenerationClient`, `RealtimeClient`, `AudioRecorder`, `InterruptManager` |
286| WebMCP and MCP Apps | `registerWebMCPTools`, `getWebMCPTools`, `subscribeWebMCPTools`, `createMcpAppBridge` |
287| Errors | `UnsupportedResponseStreamError`, `StreamTruncatedError`, `DurableStreamIncompleteError`, `StreamReconnectLimitError`, `StorageUnavailableError` |
288| Stream helpers | `StreamProcessor`, chunk strategies, `parsePartialJSON`, message converters |
289
290BYOK helpers (`defineByok`, `defaultByokStorage`, and more) are on the `@tanstack/ai-vue/byok` subpath.
291
292## Types
293
294| Type | What it is |
295| --- | --- |
296| `UseChatOptions`, `UseChatReturn` | The options and return value of `useChat`. |
297| `UIMessage<TTools>` | A chat message with typed parts. |
298| `InferChatMessages<T>` | The message type for a `createChatClientOptions` result. |
299| `SendMessageOptions`, `WhenBusy`, `QueueOption`, `QueuedMessage` | Send and queue types. |
300| `DeepPartial<T>` | The type of `partial` while structured output streams. |
301| `Use<Composable>Options`, `Use<Composable>Return` | Options and return types for the generation and recorder composables. The WebMCP composables export only an options type. |
302
303Pass a plain tools array to `useChat` or `createChatClientOptions`. Tool names, inputs, and outputs stay typed without `as const`. Import `toolDefinition` from `@tanstack/ai`.