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 — SolidJS primitives including useChat for streaming chat with full type safety."
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, providing convenient SolidJS bindings for the headless client.
17
18## Installation
19
20```bash
21npm install @tanstack/ai-solid
22```
23
24## `useChat(options?)`
25
26Main primitive for managing chat state in SolidJS with full type safety.
27
28```typescript
29import { useChat, fetchServerSentEvents } from "@tanstack/ai-solid";
30import {
31 clientTools,
32 createChatClientOptions,
33 type InferChatMessages
34} from "@tanstack/ai-client";
35
36function ChatComponent() {
37 // Create client tool implementations
38 const updateUI = updateUIDef.client((input) => {
39 setNotification(input.message);
40 return { success: true };
41 });
42
43 // Create typed tools array (no 'as const' needed!)
44 const tools = clientTools(updateUI);
45
46 const chatOptions = createChatClientOptions({
47 connection: fetchServerSentEvents("/api/chat"),
48 tools,
49 });
50
51 // Fully typed messages!
52 type ChatMessages = InferChatMessages<typeof chatOptions>;
53
54 const { messages, sendMessage, isLoading, error, addToolApprovalResponse } =
55 useChat(chatOptions);
56
57 return <div>{/* Chat UI with typed messages */}</div>;
58}
59```
60
61### Options
62
63Extends `ChatClientOptions` from `@tanstack/ai-client`:
64
65- `connection` - Connection adapter (required)
66- `tools?` - Array of client tool implementations (with `.client()` method)
67- `initialMessages?` - Initial messages array
68- `id?` - Unique identifier for this chat instance
69- `threadId?` - Thread ID for AG-UI run correlation. Persists across sends; auto-generated if omitted
70- `forwardedProps?` - Arbitrary client-controlled JSON forwarded to the server in the AG-UI `RunAgentInput.forwardedProps` field (e.g., `{ provider: 'openai', model: 'gpt-4o' }`)
71- `body?` - **Deprecated.** Use `forwardedProps` instead. Still works for backward compatibility; values are merged into `forwardedProps` on the wire
72- `onResponse?` - Callback when response is received
73- `onChunk?` - Callback when stream chunk is received
74- `onFinish?` - Callback when response finishes
75- `onError?` - Callback when error occurs
76- `streamProcessor?` - Stream processing configuration
77
78**Note:** Client tools are now automatically executed - no `onToolCall` callback needed!
79
80### Returns
81
82```typescript
83interface UseChatReturn {
84 messages: Accessor<UIMessage[]>;
85 sendMessage: (content: string) => Promise<void>;
86 append: (message: ModelMessage | UIMessage) => Promise<void>;
87 addToolResult: (result: {
88 toolCallId: string;
89 tool: string;
90 output: any;
91 state?: "output-available" | "output-error";
92 errorText?: string;
93 }) => Promise<void>;
94 addToolApprovalResponse: (response: {
95 id: string;
96 approved: boolean;
97 }) => Promise<void>;
98 reload: () => Promise<void>;
99 stop: () => void;
100 isLoading: Accessor<boolean>;
101 error: Accessor<Error | undefined>;
102 setMessages: (messages: UIMessage[]) => void;
103 clear: () => void;
104}
105```
106
107**Note:** Unlike React, `messages`, `isLoading`, and `error` are SolidJS `Accessor` functions, so you need to call them to get their values (e.g., `messages()` instead of just `messages`).
108
109## Connection Adapters
110
111Re-exported from `@tanstack/ai-client` for convenience:
112
113```typescript
114import {
115 fetchServerSentEvents,
116 fetchHttpStream,
117 stream,
118 type ConnectionAdapter,
119} from "@tanstack/ai-solid";
120```
121
122## Example: Basic Chat
123
124```typescript
125import { createSignal, For } from "solid-js";
126import { useChat, fetchServerSentEvents } from "@tanstack/ai-solid";
127
128export function Chat() {
129 const [input, setInput] = createSignal("");
130
131 const { messages, sendMessage, isLoading } = useChat({
132 connection: fetchServerSentEvents("/api/chat"),
133 });
134
135 const handleSubmit = (e: Event) => {
136 e.preventDefault();
137 if (input().trim() && !isLoading()) {
138 sendMessage(input());
139 setInput("");
140 }
141 };
142
143 return (
144 <div>
145 <div>
146 <For each={messages()}>
147 {(message) => (
148 <div>
149 <strong>{message.role}:</strong>
150 <For each={message.parts}>
151 {(part) => {
152 if (part.type === "thinking") {
153 return (
154 <div class="text-sm text-gray-500 italic">
155 💭 Thinking: {part.content}
156 </div>
157 );
158 }
159 if (part.type === "text") {
160 return <span>{part.content}</span>;
161 }
162 return null;
163 }}
164 </For>
165 </div>
166 )}
167 </For>
168 </div>
169 <form onSubmit={handleSubmit}>
170 <input
171 value={input()}
172 onInput={(e) => setInput(e.currentTarget.value)}
173 disabled={isLoading()}
174 />
175 <button type="submit" disabled={isLoading()}>
176 Send
177 </button>
178 </form>
179 </div>
180 );
181}
182```
183
184## Example: Tool Approval
185
186```typescript
187import { For, Show } from "solid-js";
188import { useChat, fetchServerSentEvents } from "@tanstack/ai-solid";
189
190export function ChatWithApproval() {
191 const { messages, sendMessage, addToolApprovalResponse } = useChat({
192 connection: fetchServerSentEvents("/api/chat"),
193 });
194
195 return (
196 <div>
197 <For each={messages()}>
198 {(message) => (
199 <For each={message.parts}>
200 {(part) => (
201 <Show
202 when={
203 part.type === "tool-call" &&
204 part.state === "approval-requested" &&
205 part.approval
206 }
207 >
208 <div>
209 <p>Approve: {part.name}</p>
210 <button
211 onClick={() =>
212 addToolApprovalResponse({
213 id: part.approval!.id,
214 approved: true,
215 })
216 }
217 >
218 Approve
219 </button>
220 <button
221 onClick={() =>
222 addToolApprovalResponse({
223 id: part.approval!.id,
224 approved: false,
225 })
226 }
227 >
228 Deny
229 </button>
230 </div>
231 </Show>
232 )}
233 </For>
234 )}
235 </For>
236 </div>
237 );
238}
239```
240
241## Example: Client Tools with Type Safety
242
243```typescript
244import { useChat, fetchServerSentEvents } from "@tanstack/ai-solid";
245import {
246 clientTools,
247 createChatClientOptions,
248 type InferChatMessages
249} from "@tanstack/ai-client";
250import { updateUIDef, saveToStorageDef } from "./tool-definitions";
251import { createSignal, For } from "solid-js";
252
253export function ChatWithClientTools() {
254 const [notification, setNotification] = createSignal(null);
255
256 // Create client implementations
257 const updateUI = updateUIDef.client((input) => {
258 // ✅ input is fully typed!
259 setNotification({ message: input.message, type: input.type });
260 return { success: true };
261 });
262
263 const saveToStorage = saveToStorageDef.client((input) => {
264 localStorage.setItem(input.key, input.value);
265 return { saved: true };
266 });
267
268 // Create typed tools array (no 'as const' needed!)
269 const tools = clientTools(updateUI, saveToStorage);
270
271 const { messages, sendMessage } = useChat({
272 connection: fetchServerSentEvents("/api/chat"),
273 tools, // ✅ Automatic execution, full type safety
274 });
275
276 return (
277 <div>
278 <For each={messages()}>
279 {(message) => (
280 <For each={message.parts}>
281 {(part) => {
282 if (part.type === "tool-call" && part.name === "updateUI") {
283 // ✅ part.input and part.output are fully typed!
284 return <div>Tool executed: {part.name}</div>;
285 }
286 }}
287 </For>
288 )}
289 </For>
290 </div>
291 );
292}
293```
294
295## `createChatClientOptions(options)`
296
297Helper to create typed chat options (re-exported from `@tanstack/ai-client`).
298
299```typescript
300import {
301 clientTools,
302 createChatClientOptions,
303 type InferChatMessages
304} from "@tanstack/ai-client";
305
306// Create typed tools array (no 'as const' needed!)
307const tools = clientTools(tool1, tool2);
308
309const chatOptions = createChatClientOptions({
310 connection: fetchServerSentEvents("/api/chat"),
311 tools,
312});
313
314type Messages = InferChatMessages<typeof chatOptions>;
315```
316
317## Types
318
319Re-exported from `@tanstack/ai-client`:
320
321- `UIMessage<TTools>` - Message type with tool type parameter
322- `MessagePart<TTools>` - Message part with tool type parameter
323- `TextPart` - Text content part
324- `ThinkingPart` - Thinking content part
325- `ToolCallPart<TTools>` - Tool call part (discriminated union)
326- `ToolResultPart` - Tool result part
327- `ChatClientOptions<TTools>` - Chat client options
328- `ConnectionAdapter` - Connection adapter interface
329- `InferChatMessages<T>` - Extract message type from options
330- `ChatRequestBody` - Request body type
331
332Re-exported from `@tanstack/ai`:
333
334- `toolDefinition()` - Create isomorphic tool definition
335- `ToolDefinitionInstance` - Tool definition type
336- `ClientTool` - Client tool type
337- `ServerTool` - Server tool type
338
339## Next Steps
340
341- [Getting Started](../getting-started/quick-start) - Learn the basics
342- [Tools Guide](../tools/tools) - Learn about the isomorphic tool system
343- [Client Tools](../tools/client-tools) - Learn about client-side tools