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