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

ai-svelte.md

475 lines15.8 KB

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