Open History to see the last commit
1---
2title: Streaming
3id: streaming-responses
4order: 2
5description: "Show the reply in the UI while the model writes it. Stream from the server, render with useChat, and cancel a run."
6keywords:
7 - tanstack ai
8 - streaming
9 - streaming responses
10 - real-time ai
11 - async iterable
12 - chunks
13 - useChat
14---
15
16`chat()` returns each token while the model writes the reply. `useChat` renders those tokens. Call `stop()` to cancel the run.
17
18
19## Quick setup
20
21### 1. Send the stream from the server
22
23Call `chat()`. Then wrap the result with `toServerSentEventsResponse`:
24
25```typescript
26// api/chat.ts
27import {
28 chat,
29 chatParamsFromRequest,
30 toServerSentEventsResponse,
31} from "@tanstack/ai";
32import { openaiText } from "@tanstack/ai-openai";
33
34export async function POST(request: Request) {
35 const { messages, threadId, runId } = await chatParamsFromRequest(request);
36
37 const stream = chat({
38 adapter: openaiText("gpt-6.1-sol"),
39 messages,
40 threadId,
41 runId,
42 });
43
44 return toServerSentEventsResponse(stream);
45}
46```
47
48### 2. Render the stream 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 threadId: "support-chat",
59 });
60
61 return (
62 <>
63 {messages.map((message) => (
64 <div key={message.id}>
65 {message.parts.map((part, index) =>
66 part.type === "text" ? <p key={index}>{part.content}</p> : null,
67 )}
68 </div>
69 ))}
70 <form
71 onSubmit={(event) => {
72 event.preventDefault();
73 if (input.trim() === "") {
74 return;
75 }
76 sendMessage(input);
77 setInput("");
78 }}
79 >
80 <input
81 value={input}
82 onChange={(event) => setInput(event.target.value)}
83 />
84 {isLoading ? (
85 <button type="button" onClick={stop}>
86 Stop
87 </button>
88 ) : (
89 <button type="submit">Send</button>
90 )}
91 </form>
92 </>
93 );
94}
95```
96
97Send a message. The text grows in the UI while the tokens arrive.
98
99The same pattern works in every UI framework. See [Quick Start](../getting-started/quick-start) for your framework.
100
101## How it works
102
103- `chatParamsFromRequest` reads the AG-UI body that `useChat` sends.
104- `chat()` returns a stream of events. `toServerSentEventsResponse` writes them to the response as Server-Sent Events.
105- `useChat` reads the events and updates `messages` after each chunk. `isLoading` is `true` while the run is in progress.
106
107If your network blocks SSE, pick another transport on [Transports](../transports/overview).
108
109## Cancel a run
110
111Call `stop()` on the client. The client aborts the fetch.
112
113To stop the model on the server too, give the same `AbortController` to `chat()` and to `toServerSentEventsResponse`:
114
115```typescript
116import {
117 chat,
118 chatParamsFromRequest,
119 toServerSentEventsResponse,
120} from "@tanstack/ai";
121import { openaiText } from "@tanstack/ai-openai";
122
123export async function POST(request: Request) {
124 const { messages, threadId, runId } = await chatParamsFromRequest(request);
125 const abortController = new AbortController();
126
127 const stream = chat({
128 adapter: openaiText("gpt-6.1-sol"),
129 messages,
130 threadId,
131 runId,
132 abortController,
133 });
134
135 return toServerSentEventsResponse(stream, { abortController });
136}
137```
138
139After `stop()`:
140
141- An `AbortError` is expected.
142- Pending client-tool work for that turn does not continue.
143- A later `addToolResult()` for that turn has no effect.
144
145## Where to go next
146
147- **The user sends while a reply streams.** By default, the message waits in `queue`. See [Message Queue](./queueing).
148- **You need the event types, the thread ids, or the tool parts.** See [Stream Events](./stream-events).
149- **The model thinks before it answers.** See [Thinking and Reasoning](./thinking-content).
150- **A page refresh must not lose the stream.** See [Resumable Streams](../resumable-streams/overview).
151
152## Advanced
153
154### Stream without HTTP
155
156You can iterate `chat()` yourself. Branch on `chunk.type`, then read `chunk.delta`:
157
158```typescript
159import { chat } from "@tanstack/ai";
160import { openaiText } from "@tanstack/ai-openai";
161
162const stream = chat({
163 adapter: openaiText("gpt-6.1-sol"),
164 messages: [{ role: "user", content: "Hello!" }],
165 threadId: "thread-1",
166});
167
168for await (const chunk of stream) {
169 if (chunk.type === "TEXT_MESSAGE_CONTENT") {
170 process.stdout.write(chunk.delta);
171 }
172}
173```
174
175### Client callbacks
176
177`useChat` takes two callbacks for the stream:
178
179- `onChunk`: runs for each event.
180- `onFinish`: runs with the completed message.
181
182### A bad request body
183
184If the body is not valid, `chatParamsFromRequest` throws a `Response` with status 400. If your framework does not send a thrown `Response` as the HTTP reply, catch it and return it.
185
186### Backpressure
187
188The response stream pauses `chat()` when its output queue is full. It reads more chunks when the client reads the queued data. `toHttpResponse` with NDJSON does the same.
189
190A response with `durability` does not pause. Its run keeps writing to the log.
191
192### Main-thread work on the client
193
194The shared `ChatClient` processes the chunks that are ready in order. It does not add a task between each chunk. After a fixed amount of work, it yields to keep the main thread responsive.
195
196### A stream that ends too early
197
198- **The connection drops in the middle of a line.** The client throws `StreamTruncatedError` and moves to `error`. See [Transports: Errors](../transports/overview#errors).
199- **An OpenAI or OpenRouter Responses stream ends without `response.completed`.** The adapter emits `RUN_ERROR` with code `incomplete-stream`. This applies to chat and to structured output. The text that arrived stays available. The run does not call `onFinish`.
200- **A Chat Completions stream ends without a finish.** See below.
201
202Chat Completions adapters built on `@tanstack/openai-base` also make sure that the stream finished. A started stream needs one of these:
203
204- a non-null `finish_reason`
205- a final chunk with only usage (`choices: []` with `usage`)
206
207If neither arrives, the adapter closes the open lifecycles and emits `RUN_ERROR` with code `incomplete-stream`. The partial text stays available. The run calls `onError`, skips pending server tools, and does not call `onFinish`.
208
209The usage-only rule keeps providers compatible. Usage on an earlier chunk, or usage next to a choice, does not count. The OpenAI SDK hides `[DONE]`, so this check cannot see that marker. A stream with only `[DONE]` after the content still needs a finish reason or a usage-only last chunk.