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

streaming.md

154 lines5.5 KB

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);
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​
48The response stream pauses `chat()` when its output queue is full. It reads more chunks when the client consumes the queued data. This also applies to `toHttpResponse` with NDJSON. A response with `durability` does not pause, so its run keeps writing to the log.
49​
50## 2. Render with `useChat`
51​
52```tsx
53import { useState } from "react";
54import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
55​
56export function Chat() {
57 const [input, setInput] = useState("");
58 const { messages, sendMessage, isLoading, stop } = useChat({
59 connection: fetchServerSentEvents("/api/chat"),
60 });
61​
62 return (
63 <>
64 {messages.map((message) => (
65 <div key={message.id}>
66 {message.parts.map((part, index) =>
67 part.type === "text" ? <p key={index}>{part.content}</p> : null,
68 )}
69 </div>
70 ))}
71 <form
72 onSubmit={(event) => {
73 event.preventDefault();
74 if (input.trim() === "") {
75 return;
76 }
77 sendMessage(input);
78 setInput("");
79 }}
80 >
81 <input
82 value={input}
83 onChange={(event) => setInput(event.target.value)}
84 />
85 {isLoading ? (
86 <button type="button" onClick={stop}>
87 Stop
88 </button>
89 ) : (
90 <button type="submit">Send</button>
91 )}
92 </form>
93 </>
94 );
96```
97​
98`messages` updates as chunks arrive. `isLoading` is `true` while the run is in flight.
99​
100The 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.
101​
102The same pattern works in every UI framework. See [Quick Start](../getting-started/quick-start).
103​
104If SSE is blocked, pick another transport on [Transports](../transports/overview).
105​
106## 3. Cancel a run
107​
108Call `stop()`. The client aborts the fetch.
109​
110Pass the same `AbortController` to `chat()` and `toServerSentEventsResponse` so the server stops the model too:
111​
112```typescript
113import {
114 chat,
115 chatParamsFromRequest,
116 toServerSentEventsResponse,
117} from "@tanstack/ai";
118import { openaiText } from "@tanstack/ai-openai";
119​
120export async function POST(request: Request) {
121 const { messages, threadId, runId } = await chatParamsFromRequest(request);
122 const abortController = new AbortController();
123​
124 const stream = chat({
125 adapter: openaiText("gpt-5.6"),
126 messages,
127 threadId,
128 runId,
129 abortController,
130 });
131​
132 return toServerSentEventsResponse(stream, { abortController });
134```
135​
136`AbortError` from `stop()` is expected. Pending client-tool work for that turn does not resume. A later `addToolResult()` for that turn is ignored.
137​
138A dropped connection mid-line throws `StreamTruncatedError`. The client then moves to `error`. See [Transports: Errors](../transports/overview#errors).
139​
140For 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`.
141​
142Chat Completions adapters built on `@tanstack/openai-base` also check completion in `chat()`. A started stream needs a non-null `finish_reason` or a final usage-only chunk (`choices: []` with `usage`). Otherwise, the adapter closes open lifecycles and emits `RUN_ERROR` with code `incomplete-stream`. Partial text remains available. The run calls `onError`, skips pending server tools, and does not call `onFinish`.
143​
144The usage-only exception preserves provider compatibility. Usage on an earlier chunk or alongside a choice does not satisfy it. The OpenAI SDK hides `[DONE]`, so this check cannot verify that marker. A stream with only `[DONE]` after content still needs a finish reason or usage-only tail to succeed.
145​
146## Later
147​
148- **No HTTP.** Iterate `chat()` yourself. Branch on `chunk.type === "TEXT_MESSAGE_CONTENT"`. Then read `chunk.delta`.
149- **Callbacks.** `onChunk` fires on each event. `onFinish` fires with the completed message.
150- **Send while a reply is in flight.** Messages wait in `queue` by default. See [Message Queue](./queueing).
151- **Event types, thread ids, and tool parts.** See [Stream Events](./stream-events).
152- **Thinking tokens or a refresh mid-stream.** See [Thinking and Reasoning](./thinking-content) and [Resumable Streams](../resumable-streams/overview).
153​
154Send a message. Text grows in the UI as tokens arrive.