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