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

ai-vue.md

488 lines15.8 KB

1---
2title: "@tanstack/ai-vue"
3id: ai-vue
4order: 5
5description: "API reference for @tanstack/ai-vue — Vue 3 composables including useChat for streaming chat with full type safety."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-vue"
9 - vue
10 - vue 3
11 - useChat
12 - composables
13 - api reference
14---
15​
16Vue composables for TanStack AI, providing convenient Vue 3 bindings for the headless client.
17​
18For a typed headless chat UI, see [Vue Chat UI](../ui/vue).
19​
20## Installation
21​
22<!-- ::start:tabs variant="package-manager" mode="install" -->
23​
24vue: @tanstack/ai-vue
25​
26<!-- ::end:tabs -->
27​
28## `useRegisterWebMCPTools(tools, options?)`
29​
30Register executable client tools for the current Vue scope. Vue removes them when the scope is disposed.
31​
32For a complete setup and behavior guide, see [WebMCP Tools](../tools/webmcp).
33​
34```vue
35<script setup lang="ts">
36import {
37 useRegisterWebMCPTools,
38 type UseRegisterWebMCPToolsOptions,
39} from "@tanstack/ai-vue";
40import { searchProducts } from "./tools";
41​
42const tools = [searchProducts];
43const options: UseRegisterWebMCPToolsOptions<typeof tools> = {
44 onError(error) {
45 console.error(error);
46 },
47};
48​
49useRegisterWebMCPTools(tools, options);
50</script>
51```
52​
53`UseRegisterWebMCPToolsOptions<TTools, TContext>` contains `toolOptions`, `context`, and `onError`. The composable owns the registration signal.
54​
55The `context` field is required when a tool declares a required runtime context.
56​
57## `usePageWebMCPTools(options?)`
58​
59Read the WebMCP tools on the page as client tools. The ref starts empty and updates when the page adds or removes a tool. Pass the ref to `useChat` as `tools`.
60​
61```ts
62import { usePageWebMCPTools } from "@tanstack/ai-vue";
63​
64export function useSameOriginPageTools() {
65 return usePageWebMCPTools({
66 filter: (tool) => tool.origin === location.origin,
67 });
69```
70​
71`filter` skips a tool when it returns `false`. `onError` gets a failed WebMCP read. For a complete guide, see [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
72​
73## `createChatHook(options)`
74​
75Bind `chatOptions` once at module scope. Call `useChat()` in the screen to create the instance. Per-call overrides may set `threadId`, `initialMessages`, `live`, and `forwardedProps`. They must not change `tools`, `interrupts`, or `outputSchema`.
76​
77```ts
78import { createChatHook, fetchServerSentEvents } from "@tanstack/ai-vue";
79​
80const chatOptions = {
81 connection: fetchServerSentEvents("/api/chat"),
82};
83​
84const { useChat } = createChatHook(chatOptions);
85​
86const chat = useChat({ threadId: "support-1" });
87```
88​
89`useChat(chatOptions)` from this package still works when you want to pass the full object at the call site. Rename the bound composable if both are in one file: `const { useChat: useSupportChat } = createChatHook(chatOptions)`.
90​
91## `useChat(options?)`
92​
93Main composable for managing chat state in Vue with full type safety.
94​
95```typescript
96import { useChat, fetchServerSentEvents } from "@tanstack/ai-vue";
97import {
98 createChatClientOptions,
99 type InferChatMessages,
100} from "@tanstack/ai-client";
101import { toolDefinition } from "@tanstack/ai";
102import { z } from "zod";
103import { ref } from "vue";
104​
105const updateUIDef = toolDefinition({
106 name: "updateUI",
107 description: "Show a notification in the UI",
108 inputSchema: z.object({ message: z.string() }),
109});
110​
111const notification = ref<string | null>(null);
112​
113// In <script setup>
114const updateUI = updateUIDef.client((input) => {
115 notification.value = input.message;
116 return { success: true };
117});
118​
119const tools = [updateUI];
120​
121const chatOptions = createChatClientOptions({
122 connection: fetchServerSentEvents("/api/chat"),
123 tools,
124});
125​
126// Fully typed messages!
127type ChatMessages = InferChatMessages<typeof chatOptions>;
128​
129const { messages, sendMessage, isLoading, error, addToolApprovalResponse } =
130 useChat(chatOptions);
131```
132​
133### Options
134​
135Extends `ChatClientOptions` from `@tanstack/ai-client` (minus internal state callbacks):
136​
137- `connection` - Connection adapter (required)
138- `tools?` - Array of client tool implementations (with `.client()` method). Pass a ref or getter to change the tools after the chat is created.
139- `initialMessages?` - Initial messages array
140- `threadId?` - The only identity for this chat. Required when persistence is on. If omitted, minted after mount.
141- `forwardedProps?` - Arbitrary client-controlled JSON forwarded to the server in the AG-UI `RunAgentInput.forwardedProps` field (reactive -- changes are synced automatically via `watch`)
142- `body?` - **Deprecated.** Use `forwardedProps` instead. Still works for backward compatibility; values are merged into `forwardedProps` on the wire (reactive)
143- `byok?` - Optional BYOK keyring from `defineByok`. On each send the client prepares the resolved provider and stamps `x-byok-*` request headers. Keys never go in the body
144- `byokProvider?` - Optional function that returns the provider slug for this chat. If it returns a slug, only that key is prepared and sent. Otherwise the merged `provider` from `forwardedProps`, `body`, and per-call `sendMessage` `body` is used. Later sources win. If no slug resolves, the send throws instead of attaching every stored key
145- `context?` - Typed client-local runtime context passed to client tool implementations (reactive). This value is not serialized to the server
146- `live?` - Enable live subscription mode (auto-subscribes/unsubscribes)
147- `onResponse?` - Callback when response is received
148- `onChunk?` - Callback when stream chunk is received
149- `onFinish?` - Callback when response finishes
150- `onError?` - Callback when error occurs
151- `onInterruptStateChange?` - Callback when interrupt state changes; context source is `hydrate` for restored state and `live` for streamed or client-initiated updates
152- `onCustomEvent?` - Callback for custom stream events
153- `streamProcessor?` - Stream processing configuration
154​
155**Note:** Client tools are now automatically executed - no `onToolCall` callback needed!
156​
157### Returns
158​
159```typescript
160import type { DeepReadonly, ShallowRef } from "vue";
161import type { UIMessage } from "@tanstack/ai-vue";
162import type { ModelMessage } from "@tanstack/ai/client";
163import type {
164 MultimodalContent,
165 ChatClientState,
166 ConnectionStatus,
167 SendMessageOptions,
168} from "@tanstack/ai-client";
169​
170interface UseChatReturn {
171 messages: DeepReadonly<ShallowRef<UIMessage[]>>;
172 sendMessage: (
173 content: string | MultimodalContent,
174 options?: SendMessageOptions,
175 ) => Promise<void>;
176 append: (message: ModelMessage | UIMessage) => Promise<void>;
177 addToolResult: (result: {
178 toolCallId: string;
179 tool: string;
180 output: any;
181 state?: "output-available" | "output-error";
182 errorText?: string;
183 }) => Promise<void>;
184 addToolApprovalResponse: (response: {
185 id: string;
186 approved: boolean;
187 }) => Promise<void>;
188 reload: () => Promise<void>;
189 stop: () => void;
190 isLoading: DeepReadonly<ShallowRef<boolean>>;
191 error: DeepReadonly<ShallowRef<Error | undefined>>;
192 status: DeepReadonly<ShallowRef<ChatClientState>>;
193 isSubscribed: DeepReadonly<ShallowRef<boolean>>;
194 connectionStatus: DeepReadonly<ShallowRef<ConnectionStatus>>;
195 sessionGenerating: DeepReadonly<ShallowRef<boolean>>;
196 setMessages: (messages: UIMessage[]) => void;
197 clear: () => void;
199```
200​
201**Note:** Reactive state (`messages`, `isLoading`, `error`, `status`, `isSubscribed`, `connectionStatus`, `sessionGenerating`) is wrapped in `DeepReadonly<ShallowRef<T>>`. In `<script setup>` read the underlying value with `.value` (e.g., `messages.value`); in `<template>` Vue auto-unwraps the ref, so use the bare name (e.g., `v-for="m in messages"`). Cleanup is automatic via `onScopeDispose`.
202​
203## `useByok(client)`
204​
205Subscribe to a `ByokClient` snapshot in Vue. The return value is a `DeepReadonly<ShallowRef<ByokSnapshot>>`.
206​
207```typescript
208import { useByok } from "@tanstack/ai-vue";
209import { byok } from "./byok";
210​
211const snapshot = useByok(byok);
212const openai = snapshot.value.status.openai;
213const last4 = openai && "masked" in openai ? openai.masked : "No key";
214```
215​
216`snapshot.value` has `status`, `locked`, and `prompt`. Call `byok.update(provider, value)` from your own UI to save a key. See [Bring Your Own Key](../advanced/byok).
217​
218## Connection Adapters
219​
220Re-exported from `@tanstack/ai-client` for convenience:
221​
222```typescript
223import {
224 fetchServerSentEvents,
225 fetchHttpStream,
226 stream,
227 type ConnectionAdapter,
228} from "@tanstack/ai-vue";
229```
230​
231## Example: Basic Chat
232​
233```vue
234<script setup lang="ts">
235import { ref } from "vue";
236import { useChat, fetchServerSentEvents } from "@tanstack/ai-vue";
237​
238const input = ref("");
239​
240const { messages, sendMessage, isLoading } = useChat({
241 connection: fetchServerSentEvents("/api/chat"),
242});
243​
244const handleSubmit = () => {
245 if (input.value.trim() && !isLoading.value) {
246 sendMessage(input.value);
247 input.value = "";
248 }
249};
250</script>
251​
252<template>
253 <div>
254 <div>
255 <div v-for="message in messages" :key="message.id">
256 <strong>{{ message.role }}:</strong>
257 <template v-for="(part, idx) in message.parts" :key="idx">
258 <div
259 v-if="part.type === 'thinking'"
260 class="text-sm text-gray-500 italic"
261 >
262 Thinking: {{ part.content }}
263 </div>
264 <span v-else-if="part.type === 'text'">{{ part.content }}</span>
265 </template>
266 </div>
267 </div>
268 <form @submit.prevent="handleSubmit">
269 <input v-model="input" :disabled="isLoading" />
270 <button type="submit" :disabled="isLoading">Send</button>
271 </form>
272 </div>
273</template>
274```
275​
276## Example: Tool Approval
277​
278```vue
279<script setup lang="ts">
280import { useChat, fetchServerSentEvents } from "@tanstack/ai-vue";
281​
282const { messages, sendMessage, addToolApprovalResponse } = useChat({
283 connection: fetchServerSentEvents("/api/chat"),
284});
285</script>
286​
287<template>
288 <div>
289 <template v-for="message in messages" :key="message.id">
290 <template v-for="part in message.parts" :key="part.id">
291 <div
292 v-if="
293 part.type === 'tool-call' &&
294 part.state === 'approval-requested' &&
295 part.approval
296 "
297 >
298 <p>Approve: {{ part.name }}</p>
299 <button
300 @click="
301 addToolApprovalResponse({
302 id: part.approval!.id,
303 approved: true,
304 })
305 "
306 >
307 Approve
308 </button>
309 <button
310 @click="
311 addToolApprovalResponse({
312 id: part.approval!.id,
313 approved: false,
314 })
315 "
316 >
317 Deny
318 </button>
319 </div>
320 </template>
321 </template>
322 </div>
323</template>
324```
325​
326## Example: Client Tools with Type Safety
327​
328```vue
329<script setup lang="ts">
330import { ref } from "vue";
331import { useChat, fetchServerSentEvents } from "@tanstack/ai-vue";
332import {
333 createChatClientOptions,
334 type InferChatMessages,
335} from "@tanstack/ai-client";
336import { toolDefinition } from "@tanstack/ai";
337import { z } from "zod";
338​
339const updateUIDef = toolDefinition({
340 name: "updateUI",
341 description: "Show a notification in the UI",
342 inputSchema: z.object({ message: z.string(), type: z.string() }),
343});
344​
345const saveToStorageDef = toolDefinition({
346 name: "saveToStorage",
347 description: "Save a value to localStorage",
348 inputSchema: z.object({ key: z.string(), value: z.string() }),
349});
350​
351const notification = ref<{ message: string; type: string } | null>(null);
352​
353// Create client implementations
354const updateUI = updateUIDef.client((input) => {
355 // input is fully typed!
356 notification.value = { message: input.message, type: input.type };
357 return { success: true };
358});
359​
360const saveToStorage = saveToStorageDef.client((input) => {
361 localStorage.setItem(input.key, input.value);
362 return { saved: true };
363});
364​
365// Create typed tools array (no 'as const' needed!)
366const tools = [updateUI, saveToStorage];
367​
368const { messages, sendMessage } = useChat({
369 connection: fetchServerSentEvents("/api/chat"),
370 tools, // Automatic execution, full type safety
371});
372</script>
373​
374<template>
375 <div>
376 <template v-for="message in messages" :key="message.id">
377 <template v-for="(part, idx) in message.parts" :key="idx">
378 <div v-if="part.type === 'tool-call' && part.name === 'updateUI'">
379 Tool executed: {{ part.name }}
380 </div>
381 </template>
382 </template>
383 </div>
384</template>
385```
386​
387## Generation Composables
388​
389Vue composables for one-shot generation tasks (images, speech, transcription, summarization, video). All share the same pattern: provide a `connection` or `fetcher`, call `generate()`, and read reactive state.
390​
391### `useGeneration(options)`
392​
393Base composable for custom generation types. All specialized composables below are built on this.
394​
395```typescript
396import { useGeneration } from "@tanstack/ai-vue";
397import { fetchServerSentEvents } from "@tanstack/ai-client";
398​
399const { generate, result, isLoading, error, status, stop, reset } =
400 useGeneration({
401 connection: fetchServerSentEvents("/api/generate/custom"),
402 });
403```
404​
405**Options:** `connection?`, `fetcher?`, `threadId?`, `body?`, `onResult?`, `onError?`, `onProgress?`, `onChunk?`
406​
407**Returns:** `generate`, `result`, `isLoading`, `error`, `status`, `stop`, `reset`, `runId` -- all reactive state is `DeepReadonly<ShallowRef<T>>`.
408​
409### `useGenerateImage(options)`
410​
411Image generation composable. `generate()` accepts `ImageGenerateInput`, result is `ImageGenerationResult`.
412​
413### `useGenerateSpeech(options)`
414​
415Text-to-speech composable. `generate()` accepts `SpeechGenerateInput`, result is `TTSResult`.
416​
417### `useTranscription(options)`
418​
419Audio transcription composable. `generate()` accepts `TranscriptionGenerateInput`, result is `TranscriptionResult`.
420​
421### `useSummarize(options)`
422​
423Text summarization composable. `generate()` accepts `SummarizeGenerateInput`, result is `SummarizationResult`.
424​
425### `useGenerateVideo(options)`
426​
427Video generation composable with job polling. Returns additional `jobId` and `videoStatus` refs. Accepts extra `onJobCreated?` and `onStatusUpdate?` callbacks.
428​
429All generation composables automatically clean up via `onScopeDispose`.
430​
431## `createChatClientOptions(options)`
432​
433Helper to create typed chat options (re-exported from `@tanstack/ai-client`).
434​
435```typescript
436import {
437 createChatClientOptions,
438 type InferChatMessages,
439} from "@tanstack/ai-client";
440import { fetchServerSentEvents } from "@tanstack/ai-vue";
441import { tool1, tool2 } from "./tools";
442​
443// Create typed tools array (no 'as const' needed!)
444const tools = [tool1, tool2];
445​
446const chatOptions = createChatClientOptions({
447 connection: fetchServerSentEvents("/api/chat"),
448 tools,
449});
450​
451type Messages = InferChatMessages<typeof chatOptions>;
452```
453​
454## Types
455​
456Re-exported from `@tanstack/ai-client`:
457​
458- `UIMessage<TTools>` - Message type with tool type parameter
459- `MessagePart<TTools>` - Message part with tool type parameter
460- `TextPart` - Text content part
461- `ThinkingPart` - Thinking content part
462- `ToolCallPart<TTools>` - Tool call part (discriminated union)
463- `ToolResultPart` - Tool result part
464- `ChatClientOptions<TTools, TContext>` - Chat client options with typed client runtime context
465- `ConnectionAdapter` - Connection adapter interface
466- `InferChatMessages<T>` - Extract message type from options
467- `ChatRequestBody` - Request body type
468- `GenerationClientState` - Generation lifecycle state
469- `ImageGenerateInput` - Image generation input type
470- `SpeechGenerateInput` - Speech generation input type
471- `TranscriptionGenerateInput` - Transcription input type
472- `SummarizeGenerateInput` - Summarization input type
473- `VideoGenerateInput` - Video generation input type
474- `VideoGenerateResult` - Video generation result type
475- `VideoStatusInfo` - Video job status info
476​
477Re-exported from `@tanstack/ai`:
478​
479- `toolDefinition()` - Create isomorphic tool definition
480- `ToolDefinitionInstance` - Tool definition type
481- `ClientTool` - Client tool type
482- `ServerTool` - Server tool type
483​
484## Next Steps
485​
486- [Getting Started](../getting-started/quick-start) - Learn the basics
487- [Tools Guide](../tools/tools) - Learn about the isomorphic tool system
488- [Client Tools](../tools/client-tools) - Learn about client-side tools