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

overview.md

205 lines7.8 KB

1---
2title: Resumable Streams
3id: overview
4description: "Reconnect to a running AI response after a refresh or a dropped connection, without a second model call. Add a durability adapter and a GET handler."
5keywords:
6 - resumable streams
7 - resume stream
8 - reconnect sse
9 - reconnect ndjson
10 - delivery durability
11 - durable streams
12 - last-event-id
13---
14​
15A resumable stream keeps the reply log when the connection drops. A refresh continues that reply and does not call the model again.
16​
17The server records every chunk in a log. The client reconnects and gets only the chunks it missed.
18​
19## Quick setup
20​
21### 1. Record the stream on the server
22​
23Pass a durability adapter to the response, and add a `GET` handler that replays the log:
24​
25```ts
26import {
27 chat,
28 chatParamsFromRequest,
29 memoryStream,
30 resumeServerSentEventsResponse,
31 toServerSentEventsResponse,
32} from '@tanstack/ai'
33import { openaiText } from '@tanstack/ai-openai'
34​
35export async function POST(request: Request) {
36 const { messages, threadId, runId } = await chatParamsFromRequest(request)
37 const stream = chat({
38 adapter: openaiText('gpt-6.1-sol'),
39 messages,
40 threadId,
41 runId,
42 })
43 return toServerSentEventsResponse(stream, {
44 durability: { adapter: memoryStream(request) },
45 })
47​
48export async function GET(request: Request) {
49 // Replays the run from the durability log. No model call happens here.
50 return resumeServerSentEventsResponse({ adapter: memoryStream(request) })
52```
53​
54`memoryStream(request)` keeps the log in process memory. It needs no setup, and it is good for development.
55​
56### 2. Use any HTTP connection in the client
57​
58You do not wire anything. `useChat` reconnects by itself:
59​
60```tsx
61import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
62​
63export function Chat() {
64 const { messages, sendMessage } = useChat({
65 connection: fetchServerSentEvents('/api/chat'),
66 threadId: 'support-chat',
67 })
68 return (
69 <div>
70 {messages.map((message) => (
71 <div key={message.id}>{message.role}</div>
72 ))}
73 <button type="button" onClick={() => void sendMessage('Hello')}>
74 Send
75 </button>
76 </div>
77 )
79```
80​
81Send a long prompt. While the reply streams, turn the network off in your browser dev tools, then turn it on again. The reply continues from where it stopped.
82​
83## How it works
84​
85- The durability adapter writes every chunk to an ordered log before it sends the chunk.
86- Each event gets an opaque offset.
87- On reconnect, the client sends the last offset it got. The server replays the log from there.
88​
89The log is kept per **run**: one execution from `RUN_STARTED` to `RUN_FINISHED`, not a whole conversation. If threads and runs are new to you, see [Threads and runs](../chat/stream-events#threads-and-runs).
90​
91This is the delivery layer. It resumes a live stream. To keep the conversation after a reload or on another device, you need persistence, which is a separate layer. See [Persistence](../persistence/overview). Most apps use both.
92​
93## Guard one-time side effects
94​
95On a dropped connection, the client reconnects with the same `POST`. The log replays, so the model does not run again. But other work in your handler runs a second time. Examples are a save of the user message, a new run row, or a usage count.
96​
97`resumeFrom()` tells you which case you have. It returns the offset on a reconnect, and `null` on a new request. Make the adapter once, check it, then use it for the response:
98​
99```ts
100import {
101 chat,
102 chatParamsFromRequest,
103 memoryStream,
104 toServerSentEventsResponse,
105} from '@tanstack/ai'
106import { openaiText } from '@tanstack/ai-openai'
107// Your own one-time side effects.
108import { countUsage, saveUserMessage } from './db'
109​
110export async function POST(request: Request) {
111 const durability = memoryStream(request)
112 const { messages, threadId, runId } = await chatParamsFromRequest(request)
113​
114 // null on a new request, an offset on a reconnect. Do one-time work once.
115 if (durability.resumeFrom() === null) {
116 await saveUserMessage(threadId, messages)
117 await countUsage(runId)
118 }
119​
120 const stream = chat({
121 adapter: openaiText('gpt-6.1-sol'),
122 messages,
123 threadId,
124 runId,
125 })
126 return toServerSentEventsResponse(stream, {
127 durability: { adapter: durability },
128 })
130```
131​
132## Pick an adapter for production
133​
134`memoryStream` works in one process only. In production, requests reach many processes, so use a shared log:
135​
136| Adapter | Package | Use it for |
137| --- | --- | --- |
138| `memoryStream(request)` | `@tanstack/ai` | Development, one process |
139| `durableStream(request, options)` | `@tanstack/ai-durable-stream` | Production, on a [Durable Streams](https://durablestreams.com) backend |
140| `upstashStream(request)` | `@upstash/agentkit-tanstack-ai` | Upstash Redis Streams. A third-party adapter, see [Upstash](../community-adapters/upstash#resumable-streams) |
141​
142To change adapters, replace `memoryStream(request)`. The rest of the code stays the same.
143​
144For a different store (Redis, Postgres, a queue), implement the four-method `StreamDurability` interface. See [Custom Durability Adapter](./custom-adapter).
145​
146## Other transports
147​
148Each response helper has a matching resume helper for the `GET`:
149​
150| Response helper | Format | Resume helper | Client connection |
151| --- | --- | --- | --- |
152| `toServerSentEventsResponse` | SSE | `resumeServerSentEventsResponse` | `fetchServerSentEvents` or `xhrServerSentEvents` |
153| `toHttpResponse` | NDJSON | `resumeHttpResponse` | `fetchHttpStream` or `xhrHttpStream` |
154| `toJsonResponse` | One JSON body per request | `resumeJsonResponse` | `fetchJson` |
155​
156- The XHR connections work the same way, for runtimes without streaming `fetch`.
157- With `fetchJson`, the client polls until the run ends. See [JSON](../transports/json#long-runs-and-reloads).
158​
159## Use one WebSocket for the whole chat
160​
161SSE and NDJSON open one connection per turn. For one socket that stays open for the full conversation, use `toWebSocketStream` on the server (or `toWebSocketResponse` on Cloudflare), with the `webSocket()` connection in the client:
162​
163```ts
164import { chat, memoryStream, toWebSocketStream } from '@tanstack/ai'
165import { openaiText } from '@tanstack/ai-openai'
166import type { WebSocketLike } from '@tanstack/ai'
167​
168// `socket` is a server socket that you already accepted (see WebSockets for
169// Node and Cloudflare) and `request` is the handshake request.
170export function handleChatSocket(socket: WebSocketLike, request: Request) {
171 toWebSocketStream(socket, request, {
172 durability: (ctx) => memoryStream(ctx.request),
173 onRun: ({ messages, threadId, runId }) =>
174 chat({ adapter: openaiText('gpt-6.1-sol'), messages, threadId, runId }),
175 })
177```
178​
179```tsx
180import { useChat, webSocket } from '@tanstack/ai-react'
181​
182const connection = webSocket('/api/chat-ws')
183​
184export function Chat() {
185 const { sendMessage } = useChat({ connection, threadId: 'support-chat' })
186 return <button onClick={() => void sendMessage('Hello')}>Send</button>
188```
189​
190A dropped socket opens again with the last offset and replays only what is missing. But closing the socket stops the run on the server, so the replay ends at the drop. The reply does not continue. [WebSockets](./websockets) covers the wire protocol, reconnects, and hosting.
191​
192## Let another host take over a sandbox run
193​
194The `GET` above only *replays*. The `POST` that started the run produces the chunks, so if that host stops, the log stops growing.
195​
196A sandboxed coding agent does work that outlives the request that started it. For that case, the same `GET` can take the run over and keep it going. Pass `driver: sandboxRunDriver({ ... })` next to the adapter. See [Takeover & Detached Runs](../sandbox/takeover).
197​
198## Advanced
199​
200[Advanced](./advanced) covers these topics:
201​
202- The durability contract, and how terminal events and errors work.
203- Reconnect tuning.
204- How to attach to a run by id.
205- Cloudflare deployment, and what happens when a process stops in production.