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