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

ai-react.md

317 lines8.2 KB

1---
2title: "@tanstack/ai-react"
3slug: /api/ai-react
4order: 3
5---
6​
7React hooks for TanStack AI, providing convenient React bindings for the headless client.
8​
9## Installation
10​
11```bash
12npm install @tanstack/ai-react
13```
14​
15## `useChat(options?)`
16​
17Main hook for managing chat state in React with full type safety.
18​
19```typescript
20import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
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>;
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: 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: boolean;
90 error: Error | undefined;
91 setMessages: (messages: UIMessage[]) => void;
92 clear: () => void;
94```
95​
96## Connection Adapters
97​
98Re-exported from `@tanstack/ai-client` for convenience:
99​
100```typescript
101import {
102 fetchServerSentEvents,
103 fetchHttpStream,
104 stream,
105 type ConnectionAdapter,
106} from "@tanstack/ai-react";
107```
108​
109## Example: Basic Chat
110​
111```typescript
112import { useState } from "react";
113import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
114​
115export function Chat() {
116 const [input, setInput] = useState("");
117​
118 const { messages, sendMessage, isLoading } = useChat({
119 connection: fetchServerSentEvents("/api/chat"),
120 });
121​
122 const handleSubmit = (e: React.FormEvent) => {
123 e.preventDefault();
124 if (input.trim() && !isLoading) {
125 sendMessage(input);
126 setInput("");
127 }
128 };
129​
130 return (
131 <div>
132 <div>
133 {messages.map((message) => (
134 <div key={message.id}>
135 <strong>{message.role}:</strong>
136 {message.parts.map((part, idx) => {
137 if (part.type === "thinking") {
138 return (
139 <div key={idx} className="text-sm text-gray-500 italic">
140 💭 Thinking: {part.content}
141 </div>
142 );
143 }
144 if (part.type === "text") {
145 return <span key={idx}>{part.content}</span>;
146 }
147 return null;
148 })}
149 </div>
150 ))}
151 </div>
152 <form onSubmit={handleSubmit}>
153 <input
154 value={input}
155 onChange={(e) => setInput(e.target.value)}
156 disabled={isLoading}
157 />
158 <button type="submit" disabled={isLoading}>
159 Send
160 </button>
161 </form>
162 </div>
163 );
165```
166​
167## Example: Tool Approval
168​
169```typescript
170import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
171​
172export function ChatWithApproval() {
173 const { messages, sendMessage, addToolApprovalResponse } = useChat({
174 connection: fetchServerSentEvents("/api/chat"),
175 });
176​
177 return (
178 <div>
179 {messages.map((message) =>
180 message.parts.map((part) => {
181 if (
182 part.type === "tool-call" &&
183 part.state === "approval-requested" &&
184 part.approval
185 ) {
186 return (
187 <div key={part.id}>
188 <p>Approve: {part.name}</p>
189 <button
190 onClick={() =>
191 addToolApprovalResponse({
192 id: part.approval!.id,
193 approved: true,
194 })
195 }
196 >
197 Approve
198 </button>
199 <button
200 onClick={() =>
201 addToolApprovalResponse({
202 id: part.approval!.id,
203 approved: false,
204 })
205 }
206 >
207 Deny
208 </button>
209 </div>
210 );
211 }
212 return null;
213 })
214 )}
215 </div>
216 );
218```
219​
220## Example: Client Tools with Type Safety
221​
222```typescript
223import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
224import {
225 clientTools,
226 createChatClientOptions,
227 type InferChatMessages
228} from "@tanstack/ai-client";
229import { updateUIDef, saveToStorageDef } from "./tool-definitions";
230import { useState } from "react";
231​
232export function ChatWithClientTools() {
233 const [notification, setNotification] = useState(null);
234​
235 // Create client implementations
236 const updateUI = updateUIDef.client((input) => {
237 // ✅ input is fully typed!
238 setNotification({ message: input.message, type: input.type });
239 return { success: true };
240 });
241​
242 const saveToStorage = saveToStorageDef.client((input) => {
243 localStorage.setItem(input.key, input.value);
244 return { saved: true };
245 });
246​
247 // Create typed tools array (no 'as const' needed!)
248 const tools = clientTools(updateUI, saveToStorage);
249​
250 const { messages, sendMessage } = useChat({
251 connection: fetchServerSentEvents("/api/chat"),
252 tools, // ✅ Automatic execution, full type safety
253 });
254​
255 return (
256 <div>
257 {messages.map((message) =>
258 message.parts.map((part) => {
259 if (part.type === "tool-call" && part.name === "updateUI") {
260 // ✅ part.input and part.output are fully typed!
261 return <div>Tool executed: {part.name}</div>;
262 }
263 })
264 )}
265 </div>
266 );
268```
269​
270## `createChatClientOptions(options)`
271​
272Helper to create typed chat options (re-exported from `@tanstack/ai-client`).
273​
274```typescript
275import {
276 clientTools,
277 createChatClientOptions,
278 type InferChatMessages
279} from "@tanstack/ai-client";
280​
281// Create typed tools array (no 'as const' needed!)
282const tools = clientTools(tool1, tool2);
283​
284const chatOptions = createChatClientOptions({
285 connection: fetchServerSentEvents("/api/chat"),
286 tools,
287});
288​
289type Messages = InferChatMessages<typeof chatOptions>;
290```
291​
292## Types
293​
294Re-exported from `@tanstack/ai-client`:
295​
296- `UIMessage<TTools>` - Message type with tool type parameter
297- `MessagePart<TTools>` - Message part with tool type parameter
298- `TextPart` - Text content part
299- `ThinkingPart` - Thinking content part
300- `ToolCallPart<TTools>` - Tool call part (discriminated union)
301- `ToolResultPart` - Tool result part
302- `ChatClientOptions<TTools>` - Chat client options
303- `ConnectionAdapter` - Connection adapter interface
304- `InferChatMessages<T>` - Extract message type from options
305​
306Re-exported from `@tanstack/ai`:
307​
308- `toolDefinition()` - Create isomorphic tool definition
309- `ToolDefinitionInstance` - Tool definition type
310- `ClientTool` - Client tool type
311- `ServerTool` - Server tool type
312​
313## Next Steps
314​
315- [Getting Started](../getting-started/quick-start) - Learn the basics
316- [Tools Guide](../guides/tools) - Learn about the isomorphic tool system
317- [Client Tools](../guides/client-tools) - Learn about client-side tools