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