Open History to see the last commit
1---
2title: Streaming
3id: streaming-responses
4order: 2
5description: "Show AI tokens in the UI as they arrive. Server stream, client useChat, cancel, and callbacks."
6keywords:
7 - tanstack ai
8 - streaming
9 - streaming responses
10 - real-time ai
11 - async iterable
12 - chunks
13 - useChat
14---
15
16You send a message. The UI sits still until the model is done. That wait feels broken.
17
18Stream the reply. Tokens show up as the model writes them.
19
20## 1. Send the stream from the server
21
22Call `chat()`. Then wrap the result with `toServerSentEventsResponse`:
23
24```typescript
25import {
26 chat,
27 chatParamsFromRequest,
28 toServerSentEventsResponse,
29} from "@tanstack/ai";
30import { openaiText } from "@tanstack/ai-openai";
31
32export async function POST(request: Request) {
33 const { messages, threadId, runId } = await chatParamsFromRequest(request);
34
35 const stream = chat({
36 adapter: openaiText("gpt-5.6"),
37 messages,
38 threadId,
39 runId,
40 });
41
42 return toServerSentEventsResponse(stream);
43}
44```
45
46`chatParamsFromRequest` reads the AG-UI body that `useChat` sends. If the body is invalid, it throws a `Response` with status 400. If your framework does not map a thrown `Response` to HTTP 400, catch it and return it.
47
48## 2. Render with `useChat`
49
50```tsx
51import { useState } from "react";
52import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
53
54export function Chat() {
55 const [input, setInput] = useState("");
56 const { messages, sendMessage, isLoading, stop } = useChat({
57 connection: fetchServerSentEvents("/api/chat"),
58 });
59
60 return (
61 <>
62 {messages.map((message) => (
63 <div key={message.id}>
64 {message.parts.map((part, index) =>
65 part.type === "text" ? <p key={index}>{part.content}</p> : null,
66 )}
67 </div>
68 ))}
69 <form
70 onSubmit={(event) => {
71 event.preventDefault();
72 if (input.trim() === "") {
73 return;
74 }
75 sendMessage(input);
76 setInput("");
77 }}
78 >
79 <input
80 value={input}
81 onChange={(event) => setInput(event.target.value)}
82 />
83 {isLoading ? (
84 <button type="button" onClick={stop}>
85 Stop
86 </button>
87 ) : (
88 <button type="submit">Send</button>
89 )}
90 </form>
91 </>
92 );
93}
94```
95
96`messages` updates as chunks arrive. `isLoading` is `true` while the run is in flight.
97
98The shared `ChatClient` processes ready chunks in order without inserting a task between each chunk. It yields after bounded processing work to keep the main thread responsive.
99
100The same pattern works in every UI framework. See [Quick Start](../getting-started/quick-start).
101
102If SSE is blocked, pick another transport on [Connection Adapters](./connection-adapters).
103
104## 3. Cancel a run
105
106Call `stop()`. The client aborts the fetch.
107
108Pass the same `AbortController` to `chat()` and `toServerSentEventsResponse` so the server stops the model too:
109
110```typescript
111import {
112 chat,
113 chatParamsFromRequest,
114 toServerSentEventsResponse,
115} from "@tanstack/ai";
116import { openaiText } from "@tanstack/ai-openai";
117
118export async function POST(request: Request) {
119 const { messages, threadId, runId } = await chatParamsFromRequest(request);
120 const abortController = new AbortController();
121
122 const stream = chat({
123 adapter: openaiText("gpt-5.6"),
124 messages,
125 threadId,
126 runId,
127 abortController,
128 });
129
130 return toServerSentEventsResponse(stream, { abortController });
131}
132```
133
134`AbortError` from `stop()` is expected. Pending client-tool work for that turn does not resume. A later `addToolResult()` for that turn is ignored.
135
136A dropped connection mid-line throws `StreamTruncatedError`. The client then moves to `error`. See [Connection Adapters](./connection-adapters).
137
138For OpenAI and OpenRouter Responses, a stream that ends without `response.completed` emits `RUN_ERROR` with code `incomplete-stream`. This applies to chat and to structured output. Text received before the error remains available. The run does not call `onFinish`.
139
140## Later
141
142- **No HTTP.** Iterate `chat()` yourself. Branch on `chunk.type === "TEXT_MESSAGE_CONTENT"`. Then read `chunk.delta`.
143- **Callbacks.** `onChunk` fires on each event. `onFinish` fires with the completed message.
144- **Send while a reply is in flight.** Messages wait in `queue` by default. See [Message Queue](./queueing).
145- **Event types, thread ids, and tool parts.** See [Stream Events](./stream-events).
146- **Thinking tokens or a refresh mid-stream.** See [Thinking and Reasoning](./thinking-content) and [Resumable Streams](../resumable-streams/overview).
147
148Send a message. Text grows in the UI as tokens arrive.