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

ai-svelte.md

307 lines13.5 KB

1---
2title: "@tanstack/ai-svelte"
3id: ai-svelte
4order: 6
5description: "API reference for @tanstack/ai-svelte: the createChat factory, generation factories, and Svelte 5 rune bindings for the headless TanStack AI client."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-svelte"
9 - svelte
10 - svelte 5
11 - createChat
12 - runes
13 - api reference
14---
15​
16Svelte 5 factory functions for TanStack AI, built on runes. To build your first chat, start with the [Quick Start](../getting-started/quick-start). For a typed chat layout, see [Svelte Chat UI](../ui/svelte).
17​
18## Installation
19​
20<!-- ::start:tabs variant="package-manager" mode="install" -->
21​
22svelte: @tanstack/ai-svelte
23​
24<!-- ::end:tabs -->
25​
26The factories are functions, not hooks, so their names start with `create`. Call them during component init.
27​
28## `createChat(options)`
29​
30Holds the messages and the run state of one chat, and talks to your server route.
31​
32```svelte
33<script lang="ts">
34 import { createChat, fetchServerSentEvents } from "@tanstack/ai-svelte";
35​
36 let input = $state("");
37 const chat = createChat({
38 connection: fetchServerSentEvents("/api/chat"),
39 threadId: "support-chat",
40 });
41​
42 const handleSubmit = (e: Event) => {
43 e.preventDefault();
44 if (input.trim() && !chat.isLoading) {
45 chat.sendMessage(input);
46 input = "";
47 }
48 };
49</script>
50​
51{#each chat.messages as message (message.id)}
52 <div>
53 <strong>{message.role}:</strong>
54 {#each message.parts as part}
55 {#if part.type === "text"}<span>{part.content}</span>{/if}
56 {/each}
57 </div>
58{/each}
59<form onsubmit={handleSubmit}>
60 <input bind:value={input} />
61 <button type="submit" disabled={chat.isLoading}>Send</button>
62</form>
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. Read reactive state in a `get tools()` 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 when the chat is created. |
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 factory also takes the `ChatClient` callbacks (`onResponse`, `onChunk`, `onFinish`, `onError`, `onInterruptStateChange`, `onCustomEvent`) and the other client options. See [`ChatClient` options](./ai-client#constructor-options).
87​
88To change `forwardedProps` or `context` after the chat starts, call `chat.updateForwardedProps(value)` or `chat.updateContext(value)`.
89​
90### Returns
91​
92State fields are reactive getters backed by `$state`. Read them on the object, for example `chat.messages`. Do not destructure them, or you keep only the first value.
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| `updateForwardedProps(value)`, `updateContext(value)` | Change `forwardedProps` or `context` for the next sends. |
116| `dispose()` | Ends the chat client and releases devtools. |
117​
118When the component is destroyed, the chat drops its connection and keeps its messages. When you are done with the chat, call `dispose()` yourself.
119​
120### Example: tool approval
121​
122A tool with `needsApproval: true` pauses the run. The pending call shows up in `interrupts`.
123​
124```svelte
125<script lang="ts">
126 import { toolDefinition } from "@tanstack/ai";
127 import { createChat, fetchServerSentEvents } from "@tanstack/ai-svelte";
128 import { z } from "zod";
129​
130 const deleteFileTool = toolDefinition({
131 name: "delete_file",
132 description: "Delete a file",
133 needsApproval: true,
134 inputSchema: z.object({ path: z.string() }),
135 });
136​
137 const chat = createChat({
138 connection: fetchServerSentEvents("/api/chat"),
139 threadId: "support-chat",
140 tools: [deleteFileTool],
141 });
142</script>
143​
144{#each chat.interrupts as interrupt (interrupt.id)}
145 {#if interrupt.kind === "tool-approval"}
146 <div>
147 <p>Approve: {interrupt.toolName}</p>
148 <button onclick={() => interrupt.resolveInterrupt(true)}>Approve</button>
149 <button onclick={() => interrupt.resolveInterrupt(false)}>Deny</button>
150 </div>
151 {/if}
152{/each}
153```
154​
155See [Tool Approval](../interrupts/tool-approval) for the server side.
156​
157## `createChatHook(options)`
158​
159Binds chat options once at module scope and returns a `createChat` factory that uses them.
160​
161```ts
162import { createChatHook, fetchServerSentEvents } from "@tanstack/ai-svelte";
163​
164export const { createChat: createSupportChat } = createChatHook({
165 connection: fetchServerSentEvents("/api/chat"),
166});
167​
168// In a component: const chat = createSupportChat({ threadId: "support-1" })
169```
170​
171The bound factory takes these per-call overrides: `threadId`, `initialMessages`, `live`, and `forwardedProps`. Keep `tools`, `interrupts`, and `outputSchema` on the factory options.
172​
173`@tanstack/ai-svelte/ui` has its own `createChatHook` that also returns typed UI components. See [Svelte Chat UI](../ui/svelte).
174​
175## Generation hooks
176​
177Each factory runs one generation request and keeps its result. See [Generation Hooks](../media/generation-hooks).
178​
179| Factory | `generate()` input | `result` |
180| --- | --- | --- |
181| `createGenerateImage` | `ImageGenerateInput` | `ImageGenerationResult` |
182| `createGenerateAudio` | `AudioGenerateInput` | `AudioGenerationResult` |
183| `createGenerateSpeech` | `SpeechGenerateInput` | `TTSResult` |
184| `createTranscription` | `TranscriptionGenerateInput` | `TranscriptionResult` |
185| `createSummarize` | `SummarizeGenerateInput` | `SummarizationResult` |
186| `createGenerateVideo` | `VideoGenerateInput` | `VideoGenerateResult` |
187| `createGeneration` | Your own input type | Your own result type |
188​
189```svelte
190<script lang="ts">
191 import { createGenerateImage, fetchServerSentEvents } from "@tanstack/ai-svelte";
192​
193 const image = createGenerateImage({
194 connection: fetchServerSentEvents("/api/generate/image"),
195 threadId: "image-studio",
196 });
197</script>
198​
199<button
200 disabled={image.isLoading}
201 onclick={() => image.generate({ prompt: "A mountain at sunset" })}
203 Generate
204</button>
205```
206​
207Options: `threadId` (required), `connection` or `fetcher`, `body`, `persistence`, `byok`, `byokProvider`, `devtools`, `onResult`, `onError`, `onProgress`, `onChunk`.
208​
209Returns: `generate(input)`, `result`, `isLoading`, `error`, `status`, `stop()`, `reset()`, `runId`, `updateBody(body)`, and `dispose()`. The state fields are reactive getters. The factories do not clean up on their own. When you are done, call `dispose()`.
210​
211`createGenerateVideo` also returns `jobId` and `videoStatus`, and takes `onJobCreated` and `onStatusUpdate`.
212​
213## Realtime chat
214​
215This package does not export a realtime factory. Use `RealtimeClient`, which this package re-exports. See [Realtime Chat](../media/realtime-chat).
216​
217## `createAudioRecorder(options?)`
218​
219Records audio from the microphone. See [Audio Recording](../media/audio-recording).
220​
221Returns `recording`, `isRecording`, `isSupported` (reactive getters), `start()`, `stop()`, and `cancel()`. Pass `onComplete` to transform the recording. Then `recording` and `stop()` use the transformed type.
222​
223## `createByok(client)`
224​
225Subscribes to a BYOK keyring. The return value has a reactive `snapshot` getter. See [Bring Your Own Key](../advanced/byok).
226​
227```svelte
228<script lang="ts">
229 import { createByok } from "@tanstack/ai-svelte";
230 import { byok } from "./byok";
231​
232 const byokState = createByok(byok);
233 const openai = $derived(byokState.snapshot.status.openai);
234</script>
235​
236<p>{openai && "masked" in openai ? openai.masked : "No key"}</p>
237```
238​
239Keep the object and read `byokState.snapshot` in markup or `$derived`. If you destructure `snapshot`, you keep only the first value. The snapshot has `status`, `locked`, `prompt`, and `storageError`. Save a key from your own UI with `byok.update(provider, value)`.
240​
241## MCP App bridge
242​
243This package does not export a bridge factory. Use `createMcpAppBridge`, which this package re-exports. See [MCP Apps](../mcp/apps).
244​
245## `createRegisterWebMCPTools(tools, options?)`
246​
247Exposes client tools to the browser WebMCP API. Call it during component init. Svelte removes the tools when the component is destroyed. See [WebMCP Tools](../tools/webmcp).
248​
249```svelte
250<script lang="ts">
251 import { createRegisterWebMCPTools } from "@tanstack/ai-svelte";
252 import { searchProducts } from "./tools";
253​
254 createRegisterWebMCPTools([searchProducts], {
255 onError: (error) => console.error(error),
256 });
257</script>
258```
259​
260Options: `toolOptions`, `context`, and `onError`. `context` is required when a tool declares a required runtime context.
261​
262## `createPageWebMCPTools(options?)`
263​
264Reads the WebMCP tools that the page registered, 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`. See [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
265​
266```svelte
267<script lang="ts">
268 import { createPageWebMCPTools } from "@tanstack/ai-svelte";
269​
270 const page = createPageWebMCPTools({
271 filter: (tool) => tool.origin === location.origin,
272 });
273</script>
274​
275<p>{page.tools.length} page tools</p>
276```
277​
278Options: `filter` (return `false` to skip a tool) and `onError`.
279​
280## Re-exports from `@tanstack/ai-client`
281​
282You can import these from `@tanstack/ai-svelte` directly. See [`@tanstack/ai-client`](./ai-client) for details.
283​
284| Group | Exports |
285| --- | --- |
286| Connection adapters | `fetchServerSentEvents`, `fetchHttpStream`, `fetchJson`, `xhrServerSentEvents`, `xhrHttpStream`, `webSocket`, `stream`, `rpcStream` |
287| Typed options | `createChatClientOptions`, `clientTools` |
288| Persistence | `localStoragePersistence`, `sessionStoragePersistence`, `indexedDBPersistence` |
289| Clients | `ChatClient`, `GenerationClient`, `VideoGenerationClient`, `RealtimeClient`, `AudioRecorder`, `InterruptManager` |
290| WebMCP and MCP Apps | `registerWebMCPTools`, `getWebMCPTools`, `subscribeWebMCPTools`, `createMcpAppBridge` |
291| Errors | `UnsupportedResponseStreamError`, `StreamTruncatedError`, `DurableStreamIncompleteError`, `StreamReconnectLimitError`, `StorageUnavailableError` |
292| Stream helpers | `StreamProcessor`, chunk strategies, `parsePartialJSON`, message converters |
293​
294BYOK helpers (`defineByok`, `defaultByokStorage`, and more) are on the `@tanstack/ai-svelte/byok` subpath.
295​
296## Types
297​
298| Type | What it is |
299| --- | --- |
300| `CreateChatOptions`, `CreateChatReturn` | The options and return value of `createChat`. |
301| `UIMessage<TTools>` | A chat message with typed parts. |
302| `InferChatMessages<T>` | The message type for a `createChatClientOptions` result. |
303| `SendMessageOptions`, `WhenBusy`, `QueueOption`, `QueuedMessage` | Send and queue types. |
304| `DeepPartial<T>` | The type of `partial` while structured output streams. |
305| `Create<Factory>Options`, `Create<Factory>Return` | Options and return types for the generation and recorder factories. The WebMCP factories export only an options type. |
306​
307Pass a plain tools array to `createChat` or `createChatClientOptions`. Tool names, inputs, and outputs stay typed without `as const`. Import `toolDefinition` from `@tanstack/ai`.