ai-resumable-stream 2.0.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +445 -262
- package/dist/adapter-D9qrs60B.d.mts +61 -0
- package/dist/adapters/redis/index.d.mts +48 -0
- package/dist/adapters/redis/index.mjs +177 -0
- package/dist/adapters/s3-express/index.d.mts +65 -0
- package/dist/adapters/s3-express/index.mjs +719 -0
- package/dist/ai-sdk/index.d.mts +23 -0
- package/dist/ai-sdk/index.mjs +37 -0
- package/dist/core-BteCDwPY.mjs +124 -0
- package/dist/core-CE_FvT5z.d.mts +76 -0
- package/dist/index.d.mts +3 -78
- package/dist/index.mjs +2 -195
- package/package.json +24 -5
package/README.md
CHANGED
|
@@ -9,80 +9,46 @@
|
|
|
9
9
|
|
|
10
10
|
</div>
|
|
11
11
|
|
|
12
|
-
This library provides resumable streaming for UI message streams created by [`streamText()`](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text) in the AI SDK.
|
|
12
|
+
This library provides resumable streaming for UI message streams created by [`streamText()`](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text) in the AI SDK. Chunks are persisted as they are produced, allowing clients to resume interrupted streams or stop active streams from anywhere.
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
Streams are ephemeral — once data flows through, it's gone. This creates two hard problems:
|
|
14
|
+
Where the chunks go is your choice. Two adapters ship; a third is four methods.
|
|
17
15
|
|
|
18
|
-
**
|
|
19
|
-
|
|
20
|
-
**Stop is hard** because the client requesting "stop" isn't the same request that started the stream. The user clicks "Stop generating", which fires a new HTTP request, but the original stream is running in a different request/process. Without a central coordination point, you can't signal across requests.
|
|
16
|
+
**Why?**
|
|
21
17
|
|
|
22
|
-
|
|
18
|
+
Streams are ephemeral. Once data flows through, it is gone. That creates two hard problems.
|
|
23
19
|
|
|
24
|
-
|
|
25
|
-
- **Stopping**: Stop signals are broadcast to any process running the stream
|
|
20
|
+
**Resume is hard** because the server does not track what it has sent. A client that disconnects (network drop, page reload, tab switch) loses everything that arrived while it was away, while the stream keeps running on the server. When reconnecting, there's no way to replay missed chunks without persisting them somewhere.
|
|
26
21
|
|
|
27
|
-
|
|
22
|
+
**Stop is hard** because the client requesting "stop" is not the request that started the stream. The user clicks "Stop generating", which fires a new HTTP request, but the original stream is running in a different request/process. Without a central coordination point, you can't signal across requests.
|
|
28
23
|
|
|
29
|
-
|
|
30
|
-
sequenceDiagram
|
|
31
|
-
participant Client
|
|
32
|
-
participant Server
|
|
33
|
-
participant Redis
|
|
34
|
-
|
|
35
|
-
rect rgb(240, 248, 255)
|
|
36
|
-
Note over Client,Redis: Start Stream
|
|
37
|
-
Client->>Server: sendMessage()
|
|
38
|
-
Server->>Server: streamText()
|
|
39
|
-
Server->>Redis: Subscribe to stop channel
|
|
40
|
-
Server->>Redis: Subscribe to stream channel
|
|
41
|
-
Server->>Redis: Store chunks (UI-to-SSE conversion)
|
|
42
|
-
Server-->>Client: Stream chunks
|
|
43
|
-
end
|
|
44
|
-
|
|
45
|
-
rect rgb(240, 255, 240)
|
|
46
|
-
Note over Client,Redis: Resume Stream
|
|
47
|
-
Client->>Server: resumeMessage()
|
|
48
|
-
Server->>Redis: Subscribe to stream channel
|
|
49
|
-
Redis-->>Server: Replay stored chunks
|
|
50
|
-
Server-->>Client: Stream past chunks (SSE-to-UI conversion)
|
|
51
|
-
Redis-->>Server: Receive new chunks
|
|
52
|
-
Server-->>Client: Stream new chunks (SSE-to-UI conversion)
|
|
53
|
-
end
|
|
24
|
+
## Install
|
|
54
25
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
Client->>Server: stopStream()
|
|
58
|
-
Server->>Redis: Publish to stop channel
|
|
59
|
-
Redis-->>Server: Notify subscriber
|
|
60
|
-
Server->>Server: AbortController.abort()
|
|
61
|
-
end
|
|
26
|
+
```sh
|
|
27
|
+
npm install ai-resumable-stream
|
|
62
28
|
```
|
|
63
29
|
|
|
64
|
-
|
|
30
|
+
Optional peer dependencies, one per feature you use:
|
|
65
31
|
|
|
66
|
-
|
|
32
|
+
| Package | Needed for |
|
|
33
|
+
| -------------------- | ----------------------------------------- |
|
|
34
|
+
| `redis` | `ai-resumable-stream/adapters/redis` |
|
|
35
|
+
| `@aws-sdk/client-s3` | `ai-resumable-stream/adapters/s3-express` |
|
|
36
|
+
| `ai` | `ai-resumable-stream/ai-sdk` |
|
|
67
37
|
|
|
68
38
|
> [!NOTE]
|
|
69
39
|
> Version compatibility:
|
|
70
40
|
>
|
|
71
41
|
> - Use [`ai-resumable-stream@1.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v1.x) for AI SDK v6
|
|
72
|
-
> - Use [`ai-resumable-stream@2.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v2.x) for AI SDK v7
|
|
73
|
-
|
|
74
|
-
```bash
|
|
75
|
-
npm install ai-resumable-stream@1 redis # AI SDK v6
|
|
76
|
-
npm install ai-resumable-stream@2 redis # AI SDK v7
|
|
77
|
-
```
|
|
42
|
+
> - Use [`ai-resumable-stream@2.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v2.x) and later for AI SDK v7
|
|
78
43
|
|
|
79
|
-
##
|
|
44
|
+
## Quick start
|
|
80
45
|
|
|
81
|
-
|
|
46
|
+
Create one context and reuse it for every stream.
|
|
82
47
|
|
|
83
|
-
```
|
|
48
|
+
```ts
|
|
84
49
|
import { createClient } from "redis";
|
|
85
|
-
import {
|
|
50
|
+
import { createRedisAdapter } from "ai-resumable-stream/adapters/redis";
|
|
51
|
+
import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
|
|
86
52
|
|
|
87
53
|
const publisher = createClient({ url: process.env.REDIS_URL });
|
|
88
54
|
const subscriber = createClient({ url: process.env.REDIS_URL });
|
|
@@ -91,81 +57,74 @@ const subscriber = createClient({ url: process.env.REDIS_URL });
|
|
|
91
57
|
await publisher.connect();
|
|
92
58
|
await subscriber.connect();
|
|
93
59
|
|
|
94
|
-
const context =
|
|
95
|
-
|
|
96
|
-
publisher,
|
|
97
|
-
subscriber,
|
|
60
|
+
const context = createResumableUIMessageStream({
|
|
61
|
+
adapter: createRedisAdapter({ publisher, subscriber }),
|
|
98
62
|
});
|
|
99
63
|
```
|
|
100
64
|
|
|
101
|
-
|
|
65
|
+
Then wire three routes.
|
|
102
66
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
| `waitUntil` | `(promise: Promise) => void` | No | Keep serverless function alive until stream completes |
|
|
67
|
+
```ts
|
|
68
|
+
// POST /chat/:chatId
|
|
69
|
+
const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
70
|
+
streamId: chatId,
|
|
71
|
+
});
|
|
72
|
+
return stream;
|
|
110
73
|
|
|
74
|
+
// GET /chat/:chatId/stream
|
|
75
|
+
const stream = await context.resumeStream({ streamId: chatId });
|
|
76
|
+
return stream ?? new Response(null, { status: 204 });
|
|
77
|
+
|
|
78
|
+
// POST /chat/:chatId/stop
|
|
79
|
+
await context.stopStream({ streamId: chatId });
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Usage
|
|
111
83
|
|
|
112
84
|
### `startStream`
|
|
113
85
|
|
|
114
|
-
|
|
86
|
+
Starts a stream and persists chunks as they are produced. Returns the stream for the client that started it, plus the id it was registered under.
|
|
115
87
|
|
|
116
88
|
> [!TIP]
|
|
117
|
-
> The stream
|
|
118
|
-
> That means you can use `return stream` or `yield* stream`.
|
|
89
|
+
> The returned stream is both a `ReadableStream` and an async iterable, so `return stream` and `yield* stream` both work.
|
|
119
90
|
|
|
120
|
-
```
|
|
91
|
+
```ts
|
|
121
92
|
import { streamText, toUIMessageStream } from "ai";
|
|
122
93
|
|
|
123
|
-
async function sendMessage() {
|
|
124
|
-
// Optional:
|
|
94
|
+
async function sendMessage(chatId: string, messages: UIMessage[]) {
|
|
95
|
+
// Optional: lets `streamText` see the stop signal
|
|
125
96
|
const abortController = new AbortController();
|
|
126
97
|
|
|
127
|
-
// Create resumable stream context
|
|
128
|
-
const context = await createResumableUIMessageStream({
|
|
129
|
-
streamId: `stream-123`,
|
|
130
|
-
publisher,
|
|
131
|
-
subscriber,
|
|
132
|
-
abortController,
|
|
133
|
-
});
|
|
134
|
-
|
|
135
98
|
const result = streamText({
|
|
136
|
-
model: `gpt-4o
|
|
137
|
-
|
|
138
|
-
// Optional: pass abort signal to enable stopping
|
|
99
|
+
model: openai(`gpt-4o`),
|
|
100
|
+
messages,
|
|
139
101
|
abortSignal: abortController.signal,
|
|
140
102
|
});
|
|
141
103
|
|
|
142
|
-
|
|
143
|
-
|
|
104
|
+
const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
105
|
+
// Optional: generates a stream id if not supplied
|
|
106
|
+
streamId: chatId,
|
|
107
|
+
abortController,
|
|
108
|
+
});
|
|
144
109
|
|
|
145
110
|
// Return stream to client
|
|
146
111
|
return stream;
|
|
147
112
|
}
|
|
148
113
|
```
|
|
149
114
|
|
|
150
|
-
|
|
115
|
+
| Option | Type | Description |
|
|
116
|
+
| ----------------- | ----------------------------- | ------------------------------------------------------------------------------------------------- |
|
|
117
|
+
| `streamId` | `string` | Defaults to a generated id, returned as `streamId` |
|
|
118
|
+
| `abortController` | `AbortController` | Created if not supplied, so a stream is always stoppable |
|
|
119
|
+
| `onFinish` | `() => void \| Promise<void>` | Runs once the source has ended, on every exit path including errors and stops. Errors are ignored |
|
|
151
120
|
|
|
152
|
-
|
|
121
|
+
### `resumeStream`
|
|
153
122
|
|
|
154
|
-
|
|
155
|
-
> The stream returned by `resumeStream` is both a readable stream and an async iterable.
|
|
156
|
-
> That means you can use `return stream` or `yield* stream`.
|
|
123
|
+
Resume an existing stream and replays every chunk produced so far, then follows the rest live. Returns `null` when there is nothing to resume.
|
|
157
124
|
|
|
158
|
-
```
|
|
159
|
-
async function resumeMessage() {
|
|
160
|
-
|
|
161
|
-
const context = await createResumableUIMessageStream({
|
|
162
|
-
streamId: `stream-123`,
|
|
163
|
-
publisher,
|
|
164
|
-
subscriber,
|
|
165
|
-
});
|
|
166
|
-
|
|
167
|
-
// Try to resume an existing stream
|
|
168
|
-
const stream = await context.resumeStream();
|
|
125
|
+
```ts
|
|
126
|
+
async function resumeMessage(chatId: string) {
|
|
127
|
+
const stream = await context.resumeStream({ streamId: chatId });
|
|
169
128
|
|
|
170
129
|
// If no stream exists, return early
|
|
171
130
|
if (!stream) {
|
|
@@ -178,247 +137,471 @@ async function resumeMessage() {
|
|
|
178
137
|
}
|
|
179
138
|
```
|
|
180
139
|
|
|
181
|
-
|
|
140
|
+
The stream is `null` in three cases that are deliberately indistinguishable:
|
|
182
141
|
|
|
183
|
-
|
|
142
|
+
- no stream was ever started under that id
|
|
143
|
+
- the stream already completed
|
|
144
|
+
- the producer died or was stopped part way through
|
|
184
145
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
subscriber,
|
|
191
|
-
});
|
|
146
|
+
If your application needs to tell a truncated stream from a complete one, record that next to the message you persist.
|
|
147
|
+
|
|
148
|
+
### `stopStream`
|
|
149
|
+
|
|
150
|
+
Stop an active stream.
|
|
192
151
|
|
|
193
|
-
|
|
152
|
+
```ts
|
|
153
|
+
async function stopMessage(chatId: string) {
|
|
154
|
+
await streams.stopStream({ streamId: chatId });
|
|
194
155
|
}
|
|
195
156
|
```
|
|
196
157
|
|
|
197
|
-
##
|
|
158
|
+
## Stream IDs
|
|
198
159
|
|
|
199
|
-
|
|
160
|
+
A stream is addressed by one `streamId` that you choose, and that id is a pointer rather than the stream itself. Each call to `startStream` creates a generation, which is one run of that id, and repoints the id at it. `resumeStream({ streamId })` resolves the pointer and follows the generation it names, and `stopStream({ streamId })` reaches whichever producer holds the id at the time. There is no second key to store or clear.
|
|
200
161
|
|
|
201
|
-
|
|
162
|
+
The indirection is what makes an id safe to reuse. Starting a new stream under an id that is already in use repoints it, so a resume gets the new stream and none of the old one's chunks, and a producer that is still shutting down cannot tear down the generation that replaced it.
|
|
202
163
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
164
|
+
- **Pass the chat id** in most applications. It encodes "at most one active stream per chat", and a reconnecting client needs nothing else to call `resumeStream({ streamId: chatId })`.
|
|
165
|
+
- **Pass the assistant message id** when you need to address one specific stream.
|
|
166
|
+
- **Omit it** and one is generated. `startStream` returns it.
|
|
167
|
+
|
|
168
|
+
## Stopping
|
|
169
|
+
|
|
170
|
+
Stopping is always possible, because a controller is always available. This works even if you didn't pass an `abortController` directly to `startStream(..., { abortController })`, because one is created automatically if not supplied, ensuring that a stream is always stoppable.
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
// Without an abortController: stopping cancels the source, which propagates upstream
|
|
174
|
+
await streams.startStream(toUIMessageStream({ stream: result.stream }), { streamId });
|
|
175
|
+
|
|
176
|
+
// With abortController: `streamText` sees the signal
|
|
177
|
+
const abortController = new AbortController();
|
|
178
|
+
const result = streamText({ model, messages, abortSignal: abortController.signal });
|
|
179
|
+
await streams.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
180
|
+
streamId,
|
|
181
|
+
abortController,
|
|
182
|
+
});
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
It's recommended to always pass your own `abortController`. Handing the signal to `streamText` aborts the provider request directly and lets the AI SDK emit its `abort` chunk and run `onAbort`, instead of relying on cancellation travelling back up the pipe.
|
|
186
|
+
|
|
187
|
+
## Adapters
|
|
188
|
+
|
|
189
|
+
| Import | Store |
|
|
190
|
+
| ----------------------------------------- | --------------------------------------------------------------------------- |
|
|
191
|
+
| `ai-resumable-stream/adapters/redis` | Redis, via [`resumable-stream`](https://github.com/vercel/resumable-stream) |
|
|
192
|
+
| `ai-resumable-stream/adapters/s3-express` | One appendable object per stream, in an S3 Express One Zone bucket |
|
|
193
|
+
|
|
194
|
+
### Redis
|
|
195
|
+
|
|
196
|
+
This adapter requires two Redis clients (pub/sub needs separate connections). Both `redis` v5 and v6 are supported. The clients will be connected automatically, if not already connected, but the library won't disconnect them afterwards. That means you can manage the connection lifecycle in your application and reuse clients across multiple streams.
|
|
197
|
+
|
|
198
|
+
```ts
|
|
207
199
|
import { createClient } from "redis";
|
|
208
|
-
import {
|
|
209
|
-
import {
|
|
200
|
+
import { createRedisAdapter } from "ai-resumable-stream/adapters/redis";
|
|
201
|
+
import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
|
|
210
202
|
|
|
211
203
|
const publisher = createClient({ url: process.env.REDIS_URL });
|
|
212
204
|
const subscriber = createClient({ url: process.env.REDIS_URL });
|
|
213
205
|
|
|
214
|
-
|
|
215
|
-
sendMessage: publicProcedure
|
|
216
|
-
.input(z.object({ chatId: z.string(), message: z.custom<UIMessage>() }))
|
|
217
|
-
.mutation(async function* ({ input }): AsyncGenerator<UIMessageChunk> {
|
|
218
|
-
const { chatId, message } = input;
|
|
206
|
+
const adapter = createRedisAdapter({ publisher, subscriber });
|
|
219
207
|
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
208
|
+
const context = createResumableUIMessageStream({
|
|
209
|
+
adapter,
|
|
210
|
+
});
|
|
211
|
+
```
|
|
223
212
|
|
|
224
|
-
|
|
213
|
+
| Option | Type | Required | Description |
|
|
214
|
+
| ------------ | ------------- | -------- | ------------------------------------------------------------------- |
|
|
215
|
+
| `publisher` | `RedisClient` | Yes | Issues commands |
|
|
216
|
+
| `subscriber` | `RedisClient` | Yes | Must be separate: a subscribed connection cannot issue commands |
|
|
217
|
+
| `keyPrefix` | `string` | No | Namespaces every key and channel. Defaults to `ai-resumable-stream` |
|
|
225
218
|
|
|
226
|
-
|
|
227
|
-
streamId: activeStreamId,
|
|
228
|
-
publisher,
|
|
229
|
-
subscriber,
|
|
230
|
-
abortController,
|
|
231
|
-
});
|
|
219
|
+
#### How it works
|
|
232
220
|
|
|
233
|
-
|
|
234
|
-
model: openai("gpt-4o"),
|
|
235
|
-
messages: [message],
|
|
236
|
-
abortSignal: abortController.signal,
|
|
237
|
-
onEnd: async () => {
|
|
238
|
-
// TODO: Clear the active stream when finished
|
|
239
|
-
await saveChat({ chatId, activeStreamId: null });
|
|
240
|
-
},
|
|
241
|
-
});
|
|
221
|
+
This adapter is built on [`resumable-stream`](https://github.com/vercel/resumable-stream). Chunks are never stored in Redis itself. They live in the memory of the process that produces them and reach late subscribers over pub/sub, so Redis carries the signalling and a small pointer per stream, not the messages. There is no chunk retention to configure.
|
|
242
222
|
|
|
243
|
-
|
|
223
|
+
Each stream id points at a generation, which is one run of that id. That pointer is the only key the adapter writes, and it carries a 24 hour expiry so a producer that dies without cleaning up leaves nothing behind for long. Starting a new stream under an id that is already in use moves the pointer to a fresh generation, so a producer that is still shutting down cannot tear down the stream that replaced it. The pointer is deleted as soon as the source ends, which is why a resume request arriving during teardown is told there is nothing to resume instead of racing it.
|
|
244
224
|
|
|
245
|
-
|
|
246
|
-
}),
|
|
225
|
+
Stop requests travel on a separate pub/sub channel. A producer subscribes to the channel for its stream id when the stream starts, and aborts its controller when a message arrives, no matter which process published it.
|
|
247
226
|
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
}): AsyncGenerator<UIMessageChunk> {
|
|
251
|
-
const { chatId } = input;
|
|
227
|
+
> [!IMPORTANT]
|
|
228
|
+
> **A stream is only resumable while its producer is alive.**
|
|
252
229
|
|
|
253
|
-
|
|
254
|
-
|
|
230
|
+
```mermaid
|
|
231
|
+
sequenceDiagram
|
|
232
|
+
participant Client
|
|
233
|
+
participant Server
|
|
234
|
+
participant Redis
|
|
255
235
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
236
|
+
rect rgb(240, 248, 255)
|
|
237
|
+
Note over Client,Redis: startStream
|
|
238
|
+
Client->>Server: POST /chat
|
|
239
|
+
Server->>Redis: SUBSCRIBE stop channel
|
|
240
|
+
Server->>Redis: SET generation pointer
|
|
241
|
+
Server->>Server: streamText()
|
|
242
|
+
Server->>Redis: PUBLISH chunks
|
|
243
|
+
Server-->>Client: stream chunks
|
|
244
|
+
end
|
|
261
245
|
|
|
262
|
-
|
|
263
|
-
|
|
246
|
+
rect rgb(240, 255, 240)
|
|
247
|
+
Note over Client,Redis: resumeStream
|
|
248
|
+
Client->>Server: GET /chat/:chatId/stream
|
|
249
|
+
Server->>Redis: GET generation pointer
|
|
250
|
+
Server->>Redis: SUBSCRIBE stream channel
|
|
251
|
+
Redis-->>Server: replay from the producer's buffer
|
|
252
|
+
Server-->>Client: past chunks
|
|
253
|
+
Redis-->>Server: new chunks
|
|
254
|
+
Server-->>Client: live chunks
|
|
255
|
+
end
|
|
264
256
|
|
|
265
|
-
|
|
266
|
-
|
|
257
|
+
rect rgb(255, 248, 240)
|
|
258
|
+
Note over Client,Redis: stopStream
|
|
259
|
+
Client->>Server: POST /chat/:chatId/stop
|
|
260
|
+
Server->>Redis: PUBLISH stop
|
|
261
|
+
Redis-->>Server: deliver to the producer
|
|
262
|
+
Server->>Server: abortController.abort()
|
|
263
|
+
end
|
|
264
|
+
```
|
|
267
265
|
|
|
268
|
-
|
|
269
|
-
.input(z.object({ chatId: z.string() }))
|
|
270
|
-
.mutation(async ({ input }) => {
|
|
271
|
-
const { chatId } = input;
|
|
266
|
+
### S3 Express
|
|
272
267
|
|
|
273
|
-
|
|
274
|
-
const { activeStreamId } = await getChat(chatId);
|
|
268
|
+
This adapter requires an [S3 Express One Zone](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-one-zone.html) directory bucket and an `S3Client` that you build yourself, so credentials, region and retry behaviour stay with your application.
|
|
275
269
|
|
|
276
|
-
|
|
277
|
-
streamId: activeStreamId,
|
|
278
|
-
publisher,
|
|
279
|
-
subscriber,
|
|
280
|
-
});
|
|
270
|
+
Chunks are held in the bucket rather than in the memory of the process producing them. A resume is served by reading the object, so it does not depend on the producing process answering, and any instance with access to the bucket can serve it.
|
|
281
271
|
|
|
282
|
-
|
|
272
|
+
```ts
|
|
273
|
+
import { S3Client } from "@aws-sdk/client-s3";
|
|
274
|
+
import { createS3ExpressAdapter } from "ai-resumable-stream/adapters/s3-express";
|
|
283
275
|
|
|
284
|
-
|
|
285
|
-
|
|
276
|
+
const adapter = createS3ExpressAdapter({
|
|
277
|
+
client: new S3Client({ region: `us-east-1` }),
|
|
278
|
+
bucket: `my-streams--use1-az4--x-s3`,
|
|
286
279
|
});
|
|
287
280
|
```
|
|
288
281
|
|
|
282
|
+
| Option | Type | Default | Description |
|
|
283
|
+
| ---------------------- | ---------- | --------------------- | ----------------------------------------------------------------------------- |
|
|
284
|
+
| `client` | `S3Client` | | Built and configured by you |
|
|
285
|
+
| `bucket` | `string` | | A directory bucket in an Availability Zone |
|
|
286
|
+
| `prefix` | `string` | `ai-resumable-stream` | Namespaces every key. Point the lifecycle rule at it |
|
|
287
|
+
| `flushIntervalMs` | `number` | `250` | How long chunks may sit in memory before being written |
|
|
288
|
+
| `batchSize` | `number` | `50` | Forces a write once this many chunks are buffered |
|
|
289
|
+
| `resumePollIntervalMs` | `number` | `500` | How often a resuming reader looks for new bytes |
|
|
290
|
+
| `stopPollIntervalMs` | `number` | `1000` | How often a producer checks for a stop request |
|
|
291
|
+
| `heartbeatMs` | `number` | `5000` | How often an idle producer records that it is alive |
|
|
292
|
+
| `deadAfterMs` | `number` | `30000` | Silence after which a producer is presumed dead. At least twice `heartbeatMs` |
|
|
293
|
+
|
|
294
|
+
#### How it works
|
|
295
|
+
|
|
296
|
+
A stream is one object in the bucket, appended to as chunks are produced. Chunks are buffered in memory and written once `batchSize` of them have collected or `flushIntervalMs` has passed, whichever comes first, so a stream costs one request per flush rather than one per chunk.
|
|
297
|
+
|
|
298
|
+
Each stream id points at a generation, which is one run of that id, and the pointer is a small object next to the log. Every key the adapter writes sits under the generation, the stop marker included. A producer that has been superseded therefore cannot append into the log of the stream that replaced it, and a stop request cannot reach a generation other than the one it was resolved against.
|
|
299
|
+
|
|
300
|
+
Stop requests are an object too. `stopStream` writes a marker under the current generation, and the producer checks for it every `stopPollIntervalMs` and aborts its controller when it appears.
|
|
301
|
+
|
|
302
|
+
> [!IMPORTANT]
|
|
303
|
+
> The bucket must be an [S3 Express One Zone](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-one-zone.html) directory bucket in an Availability Zone. Appends exist nowhere else in S3, and they are what make a stream one object rather than one object per batch.
|
|
304
|
+
|
|
305
|
+
**How a stream is stored.** One appendable object, holding chunks, liveness and completion in the same log. A resuming reader replays the whole backlog in a single ranged read, then follows the tail at one request per poll.
|
|
306
|
+
|
|
307
|
+
```
|
|
308
|
+
{prefix}/{streamId}/current pointer to the current generation
|
|
309
|
+
{prefix}/{streamId}/{generationId}/0 the log
|
|
310
|
+
{prefix}/{streamId}/{generationId}/stop stop marker
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
```mermaid
|
|
314
|
+
sequenceDiagram
|
|
315
|
+
participant Client
|
|
316
|
+
participant Server
|
|
317
|
+
participant S3 as S3 Express
|
|
318
|
+
|
|
319
|
+
rect rgb(240, 248, 255)
|
|
320
|
+
Note over Client,S3: startStream
|
|
321
|
+
Client->>Server: POST /chat
|
|
322
|
+
Server->>S3: PutObject log (format version)
|
|
323
|
+
Server->>S3: PutObject pointer
|
|
324
|
+
Server->>Server: streamText()
|
|
325
|
+
par write the log
|
|
326
|
+
loop every flushIntervalMs
|
|
327
|
+
Server->>S3: PutObject append (chunks)
|
|
328
|
+
end
|
|
329
|
+
and watch for a stop
|
|
330
|
+
loop every stopPollIntervalMs
|
|
331
|
+
Server->>S3: HeadObject stop marker
|
|
332
|
+
end
|
|
333
|
+
end
|
|
334
|
+
Server-->>Client: stream chunks
|
|
335
|
+
end
|
|
336
|
+
|
|
337
|
+
rect rgb(240, 255, 240)
|
|
338
|
+
Note over Client,S3: resumeStream
|
|
339
|
+
Client->>Server: GET /chat/:chatId/stream
|
|
340
|
+
Server->>S3: GetObject pointer
|
|
341
|
+
Server->>S3: GetObject Range bytes=0-
|
|
342
|
+
S3-->>Server: the whole backlog, one request
|
|
343
|
+
Server-->>Client: past chunks
|
|
344
|
+
loop every resumePollIntervalMs
|
|
345
|
+
Server->>S3: GetObject Range bytes=N-
|
|
346
|
+
S3-->>Server: new records, or 416 for none
|
|
347
|
+
Server-->>Client: live chunks
|
|
348
|
+
end
|
|
349
|
+
end
|
|
350
|
+
|
|
351
|
+
rect rgb(255, 248, 240)
|
|
352
|
+
Note over Client,S3: stopStream
|
|
353
|
+
Client->>Server: POST /chat/:chatId/stop
|
|
354
|
+
Server->>S3: GetObject pointer
|
|
355
|
+
Server->>S3: PutObject stop marker
|
|
356
|
+
S3-->>Server: the producer's next poll finds it
|
|
357
|
+
Server->>Server: abortController.abort()
|
|
358
|
+
end
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
Every flush is one billed `PutObject`, and that is where the cost of a stream sits. Raising `flushIntervalMs` reduces the number of writes in proportion, and adds the same amount to how far behind a resuming reader runs. Reads are charged at a much lower rate. Run the producer in the same Availability Zone as the bucket, since AWS documents access from another zone as slower.
|
|
362
|
+
|
|
363
|
+
A producer with nothing to write records a heartbeat every `heartbeatMs`, and both ends judge liveness on S3's clock rather than the caller's. A log that has not been written to for `deadAfterMs` is treated as having a dead producer, so `resumeStream` returns `null` and a reader already following it ends.
|
|
364
|
+
|
|
365
|
+
Nothing is deleted when a stream finishes, because a reader may still be draining it. Set a [lifecycle expiration rule](https://docs.aws.amazon.com/AmazonS3/latest/userguide/directory-buckets-objects-lifecycle.html) on the bucket covering `prefix`.
|
|
366
|
+
|
|
367
|
+
> [!WARNING]
|
|
368
|
+
> Lifecycle on a directory bucket does nothing unless the bucket policy grants `s3express:CreateSession` with `ReadWrite` to `lifecycle.s3.amazonaws.com`. Without it, objects accumulate silently.
|
|
369
|
+
|
|
370
|
+
No local emulator implements appends, so the tests run against an in-memory bucket. To check that model against the real thing:
|
|
371
|
+
|
|
372
|
+
```sh
|
|
373
|
+
S3_EXPRESS_BUCKET=my-streams--use1-az4--x-s3 AWS_REGION=us-east-1 pnpm test integration
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
### Custom `StreamAdapter`
|
|
377
|
+
|
|
378
|
+
A `StreamAdapter` is four methods. Implement them against the store you want and pass the object as `adapter`.
|
|
379
|
+
|
|
380
|
+
```ts
|
|
381
|
+
import type { StreamAdapter } from "ai-resumable-stream";
|
|
382
|
+
|
|
383
|
+
const adapter: StreamAdapter = {
|
|
384
|
+
createStream({ streamId, chunks, waitUntil }) { ... },
|
|
385
|
+
resumeStream({ streamId }) { ... },
|
|
386
|
+
requestStop({ streamId }) { ... },
|
|
387
|
+
onStopRequested({ streamId, onStop }) { ... },
|
|
388
|
+
};
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
| Method | Contract |
|
|
392
|
+
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
393
|
+
| `createStream` | Discards any state left from a previous stream with the same id, registers the id, consumes `chunks` in the background. Resolves once resumable, not once complete |
|
|
394
|
+
| `resumeStream` | Chunks already produced, then those still to come. `null` when unknown, finished, or expired |
|
|
395
|
+
| `requestStop` | Safe to call for an unknown or finished stream |
|
|
396
|
+
| `onStopRequested` | Producer-side listener. Returns a function that removes it |
|
|
397
|
+
|
|
398
|
+
`createStream` receives a `ReadableStream<string>` of encoded chunks. It has to consume that stream in the background until it ends, and `resumeStream` has to return the same strings in the same order, followed by the ones still to come. The strings are opaque, so any framing they need to survive your store is the adapter's own concern.
|
|
399
|
+
|
|
400
|
+
`requestStop` and `onStopRequested` usually run in different processes, so the stop signal has to travel through the store as well, by a subscription, a poll, or whatever the backend offers.
|
|
401
|
+
|
|
402
|
+
The tests in [`src/__tests__/conformance-suite.ts`](./src/__tests__/conformance-suite.ts) run against both shipped adapters and cover what an adapter has to get right: replay followed by live chunks on resume, persistence that continues after the client disconnects, a reused id that discards the previous stream's chunks, and a stop that reaches a reader who resumed.
|
|
403
|
+
|
|
289
404
|
## Advanced
|
|
290
405
|
|
|
291
|
-
###
|
|
406
|
+
### Chunk types
|
|
292
407
|
|
|
293
|
-
The
|
|
408
|
+
The root export is generic over the chunk type and has no dependency on `ai`. The `ai-sdk` subpath binds it to the AI SDK:
|
|
294
409
|
|
|
295
|
-
```
|
|
296
|
-
|
|
297
|
-
const publisher = createClient({ url: redisUrl });
|
|
298
|
-
const subscriber = createClient({ url: redisUrl });
|
|
299
|
-
|
|
300
|
-
// Library connects if needed
|
|
301
|
-
const context = await createResumableUIMessageStream({
|
|
302
|
-
streamId: "stream-123",
|
|
303
|
-
publisher, // Will connect if not already connected
|
|
304
|
-
subscriber, // Will connect if not already connected
|
|
305
|
-
});
|
|
410
|
+
```ts
|
|
411
|
+
import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
|
|
306
412
|
|
|
307
|
-
|
|
308
|
-
await publisher.quit();
|
|
309
|
-
await subscriber.quit();
|
|
413
|
+
const streams = createResumableUIMessageStream({ adapter });
|
|
310
414
|
```
|
|
311
415
|
|
|
312
|
-
|
|
416
|
+
That is exactly `createResumableStream({ adapter, codec: uiMessageChunkCodec })`. Chunks are validated on the way back, so one written by an older version of your application is dropped rather than failing the resume.
|
|
313
417
|
|
|
314
|
-
|
|
418
|
+
For anything else, supply a `StreamCodec`:
|
|
315
419
|
|
|
316
|
-
|
|
420
|
+
```ts
|
|
421
|
+
import { createResumableStream, type StreamCodec } from "ai-resumable-stream";
|
|
317
422
|
|
|
318
|
-
|
|
319
|
-
|
|
423
|
+
const codec: StreamCodec<MyChunk> = {
|
|
424
|
+
encode: (chunk) => JSON.stringify(chunk),
|
|
425
|
+
decode: (data) => JSON.parse(data) as MyChunk,
|
|
426
|
+
};
|
|
320
427
|
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
|
|
428
|
+
const streams = createResumableStream({ adapter, codec });
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
`decode` may return `undefined` to drop a chunk it cannot represent, so one bad chunk never fails an entire resume.
|
|
432
|
+
|
|
433
|
+
### Serverless
|
|
324
434
|
|
|
325
|
-
|
|
435
|
+
Persistence outlives the response, so the runtime has to be told to wait for it:
|
|
326
436
|
|
|
327
|
-
|
|
328
|
-
|
|
437
|
+
```ts
|
|
438
|
+
import { waitUntil } from "@vercel/functions";
|
|
329
439
|
|
|
330
|
-
|
|
331
|
-
resolve();
|
|
440
|
+
const streams = createResumableUIMessageStream({ adapter, waitUntil });
|
|
332
441
|
```
|
|
333
442
|
|
|
334
|
-
###
|
|
443
|
+
### Finish
|
|
335
444
|
|
|
336
|
-
The `
|
|
445
|
+
The `onFinish` callback is invoked after the source stream has ended and the adapter stream was closed. Use it for cleanup tasks like removing the active stream ID from the database. Errors thrown by `onFinish` are silently caught.
|
|
337
446
|
|
|
338
447
|
```typescript
|
|
339
448
|
const stream = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
340
|
-
|
|
449
|
+
onFinish: async () => {
|
|
341
450
|
await saveChat({ chatId, activeStreamId: null });
|
|
342
451
|
},
|
|
343
452
|
});
|
|
344
453
|
```
|
|
345
454
|
|
|
346
|
-
|
|
455
|
+
## Examples
|
|
456
|
+
|
|
457
|
+
Two runnable demos live in [`examples/`](./examples), one per adapter. Each starts a stream, disconnects the client part way through, resumes it by id, and then stops a second stream from elsewhere.
|
|
458
|
+
|
|
459
|
+
```sh
|
|
460
|
+
pnpm example:redis # a throwaway Redis, started for you
|
|
461
|
+
pnpm example:s3-express # an in-memory bucket, since no emulator implements appends
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
### tRPC
|
|
465
|
+
|
|
466
|
+
Server-side procedures for sending, resuming, and stopping. The chat id is the stream id, so no active-stream pointer has to be stored or cleared.
|
|
467
|
+
|
|
468
|
+
```ts
|
|
469
|
+
// server/router.ts
|
|
470
|
+
import { z } from "zod";
|
|
471
|
+
import { streamText, toUIMessageStream, type UIMessage, type UIMessageChunk } from "ai";
|
|
472
|
+
import { createClient } from "redis";
|
|
473
|
+
import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
|
|
474
|
+
import { createRedisAdapter } from "ai-resumable-stream/adapters/redis";
|
|
475
|
+
import { publicProcedure, router } from "./trpc";
|
|
476
|
+
|
|
477
|
+
const publisher = createClient({ url: process.env.REDIS_URL });
|
|
478
|
+
const subscriber = createClient({ url: process.env.REDIS_URL });
|
|
479
|
+
|
|
480
|
+
const streams = createResumableUIMessageStream({
|
|
481
|
+
adapter: createRedisAdapter({ publisher, subscriber }),
|
|
482
|
+
});
|
|
483
|
+
|
|
484
|
+
export const appRouter = router({
|
|
485
|
+
sendMessage: publicProcedure
|
|
486
|
+
.input(z.object({ chatId: z.string(), message: z.custom<UIMessage>() }))
|
|
487
|
+
.mutation(async function* ({ input }): AsyncGenerator<UIMessageChunk> {
|
|
488
|
+
const { chatId, message } = input;
|
|
489
|
+
|
|
490
|
+
const abortController = new AbortController();
|
|
491
|
+
|
|
492
|
+
const result = streamText({
|
|
493
|
+
model: openai(`gpt-4o`),
|
|
494
|
+
messages: [message],
|
|
495
|
+
abortSignal: abortController.signal,
|
|
496
|
+
});
|
|
497
|
+
|
|
498
|
+
const { stream } = await streams.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
499
|
+
streamId: chatId,
|
|
500
|
+
abortController,
|
|
501
|
+
onFinish: async () => {
|
|
502
|
+
await saveAssistantMessage(chatId, await result.text);
|
|
503
|
+
},
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
yield* stream;
|
|
507
|
+
}),
|
|
508
|
+
|
|
509
|
+
resumeMessage: publicProcedure.input(z.object({ chatId: z.string() })).mutation(async function* ({
|
|
510
|
+
input,
|
|
511
|
+
}): AsyncGenerator<UIMessageChunk> {
|
|
512
|
+
const stream = await streams.resumeStream({ streamId: input.chatId });
|
|
513
|
+
if (!stream) return;
|
|
514
|
+
|
|
515
|
+
yield* stream;
|
|
516
|
+
}),
|
|
517
|
+
|
|
518
|
+
stopMessage: publicProcedure
|
|
519
|
+
.input(z.object({ chatId: z.string() }))
|
|
520
|
+
.mutation(async ({ input }) => {
|
|
521
|
+
await streams.stopStream({ streamId: input.chatId });
|
|
522
|
+
|
|
523
|
+
return { success: true };
|
|
524
|
+
}),
|
|
525
|
+
});
|
|
526
|
+
```
|
|
347
527
|
|
|
348
528
|
## API Reference
|
|
349
529
|
|
|
350
|
-
### `
|
|
530
|
+
### `createResumableStream`
|
|
351
531
|
|
|
352
|
-
```
|
|
353
|
-
|
|
532
|
+
```ts
|
|
533
|
+
function createResumableStream<CHUNK>(options: CreateResumableStreamOptions<CHUNK>): {
|
|
354
534
|
startStream: (
|
|
355
|
-
|
|
535
|
+
source: ReadableStream<CHUNK>,
|
|
356
536
|
options?: StartStreamOptions,
|
|
357
|
-
) => Promise<AsyncIterableStream<
|
|
358
|
-
resumeStream: () => Promise<AsyncIterableStream<
|
|
359
|
-
stopStream: () => Promise<void>;
|
|
360
|
-
}
|
|
537
|
+
) => Promise<{ streamId: string; stream: AsyncIterableStream<CHUNK> }>;
|
|
538
|
+
resumeStream: (options: ResumeStreamOptions) => Promise<AsyncIterableStream<CHUNK> | null>;
|
|
539
|
+
stopStream: (options: StopStreamOptions) => Promise<void>;
|
|
540
|
+
};
|
|
361
541
|
|
|
362
|
-
type
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
subscriber: Redis;
|
|
366
|
-
abortController?: AbortController;
|
|
542
|
+
type CreateResumableStreamOptions<CHUNK> = {
|
|
543
|
+
adapter: StreamAdapter;
|
|
544
|
+
codec: StreamCodec<CHUNK>;
|
|
367
545
|
waitUntil?: (promise: Promise<unknown>) => void;
|
|
546
|
+
generateId?: () => string;
|
|
368
547
|
};
|
|
369
548
|
|
|
370
549
|
type StartStreamOptions = {
|
|
371
|
-
|
|
372
|
-
|
|
550
|
+
streamId?: string;
|
|
551
|
+
abortController?: AbortController;
|
|
552
|
+
onFinish?: () => void | Promise<void>;
|
|
373
553
|
};
|
|
374
|
-
```
|
|
375
|
-
|
|
376
|
-
### Return Values
|
|
377
554
|
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
async function startStream(
|
|
382
|
-
stream: ReadableStream<UIMessageChunk>,
|
|
383
|
-
options?: StartStreamOptions,
|
|
384
|
-
): Promise<AsyncIterableStream<UIMessageChunk>>;
|
|
555
|
+
type ResumeStreamOptions = {
|
|
556
|
+
streamId: string;
|
|
557
|
+
};
|
|
385
558
|
|
|
386
|
-
type
|
|
387
|
-
|
|
388
|
-
onFlush?: () => void | Promise<void>;
|
|
559
|
+
type StopStreamOptions = {
|
|
560
|
+
streamId: string;
|
|
389
561
|
};
|
|
390
562
|
```
|
|
391
563
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
If the promise rejects, the producer tears down normally. If the source stream errors, the `keepAlive` promise is not awaited.
|
|
564
|
+
| Option | Type | Required | Description |
|
|
565
|
+
| ------------ | -------------------- | -------- | ----------------------------------------------------------------------------------- |
|
|
566
|
+
| `adapter` | `StreamAdapter` | Yes | Where chunks are stored and how stop requests travel |
|
|
567
|
+
| `codec` | `StreamCodec<CHUNK>` | Yes | Translates between chunks and the strings an adapter stores |
|
|
568
|
+
| `waitUntil` | `(promise) => void` | No | Keeps the host process alive until persistence finishes. Omit on long-lived servers |
|
|
569
|
+
| `generateId` | `() => string` | No | Generates a stream id when `startStream` is not given one |
|
|
399
570
|
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
A callback invoked after the Redis stream is closed and the producer has torn down, regardless of how the stream ended (complete, error, or abort). Use it for cleanup tasks like removing the active stream ID from the database. Errors thrown by `onFlush` are silently caught.
|
|
403
|
-
|
|
404
|
-
When used together with `keepAlive`, `onFlush` fires after the `keepAlive` promise resolves and the producer tears down.
|
|
571
|
+
### `createResumableUIMessageStream`
|
|
405
572
|
|
|
406
|
-
|
|
573
|
+
The same, with `codec` fixed to `uiMessageChunkCodec`.
|
|
407
574
|
|
|
408
|
-
```
|
|
409
|
-
|
|
575
|
+
```ts
|
|
576
|
+
function createResumableUIMessageStream(
|
|
577
|
+
options: Omit<CreateResumableStreamOptions<UIMessageChunk>, `codec`>,
|
|
578
|
+
): { startStream; resumeStream; stopStream };
|
|
410
579
|
```
|
|
411
580
|
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
581
|
+
### `StreamAdapter`
|
|
582
|
+
|
|
583
|
+
```ts
|
|
584
|
+
type StreamAdapter = {
|
|
585
|
+
createStream(options: {
|
|
586
|
+
streamId: string;
|
|
587
|
+
chunks: ReadableStream<string>;
|
|
588
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
589
|
+
}): Promise<void>;
|
|
590
|
+
resumeStream(options: { streamId: string }): Promise<ReadableStream<string> | null>;
|
|
591
|
+
requestStop(options: { streamId: string }): Promise<void>;
|
|
592
|
+
onStopRequested(options: { streamId: string; onStop: () => void }): Promise<() => void>;
|
|
593
|
+
};
|
|
594
|
+
```
|
|
417
595
|
|
|
418
|
-
|
|
596
|
+
### `StreamCodec`
|
|
419
597
|
|
|
420
|
-
```
|
|
421
|
-
|
|
598
|
+
```ts
|
|
599
|
+
type StreamCodec<CHUNK> = {
|
|
600
|
+
encode(chunk: CHUNK): string;
|
|
601
|
+
decode(data: string): CHUNK | undefined | Promise<CHUNK | undefined>;
|
|
602
|
+
};
|
|
422
603
|
```
|
|
423
604
|
|
|
424
|
-
|
|
605
|
+
## License
|
|
606
|
+
|
|
607
|
+
MIT
|