ai-resumable-stream 3.0.0 → 3.1.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 +210 -238
- package/dist/{adapter-D9qrs60B.d.mts → adapter-CTz0z2k0.d.mts} +25 -4
- package/dist/adapters/redis/index.d.mts +10 -4
- package/dist/adapters/redis/index.mjs +104 -23
- package/dist/adapters/s3-express/index.d.mts +1 -1
- package/dist/adapters/s3-express/index.mjs +96 -64
- package/dist/ai-sdk/index.d.mts +2 -2
- package/dist/ai-sdk/index.mjs +1 -1
- package/dist/{core-BteCDwPY.mjs → core-DAlVpiTc.mjs} +68 -19
- package/dist/{core-CE_FvT5z.d.mts → core-DmhblcmG.d.mts} +34 -3
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,17 +9,17 @@
|
|
|
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. The library stores chunks as they are produced. Clients can then resume an interrupted stream, and any request can stop an active stream.
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
You choose where the chunks are stored. The library includes adapters for Redis and S3 Express. You can also write your own adapter by implementing four methods.
|
|
15
15
|
|
|
16
16
|
**Why?**
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
A stream does not keep its data. After a chunk is sent, it is gone. This causes two problems.
|
|
19
19
|
|
|
20
|
-
**Resume
|
|
20
|
+
**Resume:** The server does not record which chunks it has sent. When a client disconnects (network drop, page reload, tab switch), the stream continues on the server, but the client misses the chunks that are sent during that time. The server can only replay the missed chunks if they are stored somewhere.
|
|
21
21
|
|
|
22
|
-
**Stop
|
|
22
|
+
**Stop:** The request that stops a stream is not the request that started it. When the user clicks "Stop generating", the client sends a new HTTP request, but the stream runs in a different request or process. The two requests need a shared place to pass the stop signal.
|
|
23
23
|
|
|
24
24
|
## Install
|
|
25
25
|
|
|
@@ -27,7 +27,7 @@ Streams are ephemeral. Once data flows through, it is gone. That creates two har
|
|
|
27
27
|
npm install ai-resumable-stream
|
|
28
28
|
```
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
Install the optional peer dependencies for the features you use:
|
|
31
31
|
|
|
32
32
|
| Package | Needed for |
|
|
33
33
|
| -------------------- | ----------------------------------------- |
|
|
@@ -39,7 +39,7 @@ Optional peer dependencies, one per feature you use:
|
|
|
39
39
|
> Version compatibility:
|
|
40
40
|
>
|
|
41
41
|
> - Use [`ai-resumable-stream@1.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v1.x) for AI SDK v6
|
|
42
|
-
> - Use [`ai-resumable-stream@2.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v2.x) and later for AI SDK v7
|
|
42
|
+
> - Use [`ai-resumable-stream@2.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v2.x) or [`ai-resumable-stream@3.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v3.x) and later for AI SDK v7
|
|
43
43
|
|
|
44
44
|
## Quick start
|
|
45
45
|
|
|
@@ -62,28 +62,47 @@ const context = createResumableUIMessageStream({
|
|
|
62
62
|
});
|
|
63
63
|
```
|
|
64
64
|
|
|
65
|
-
Then
|
|
65
|
+
Then use the context in your three routes:
|
|
66
66
|
|
|
67
67
|
```ts
|
|
68
|
+
import { streamText, toUIMessageStream, type UIMessage } from "ai";
|
|
69
|
+
|
|
68
70
|
// POST /chat/:chatId
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
71
|
+
export async function send(chatId: string, messages: Array<UIMessage>) {
|
|
72
|
+
const abortController = new AbortController();
|
|
73
|
+
|
|
74
|
+
const result = streamText({
|
|
75
|
+
model: openai(`gpt-4o`),
|
|
76
|
+
messages,
|
|
77
|
+
abortSignal: abortController.signal,
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
81
|
+
streamId: chatId,
|
|
82
|
+
abortController,
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
return stream;
|
|
86
|
+
}
|
|
73
87
|
|
|
74
88
|
// GET /chat/:chatId/stream
|
|
75
|
-
|
|
76
|
-
|
|
89
|
+
export async function resume(chatId: string) {
|
|
90
|
+
const stream = await context.resumeStream({ streamId: chatId });
|
|
91
|
+
|
|
92
|
+
return stream ?? new Response(null, { status: 204 });
|
|
93
|
+
}
|
|
77
94
|
|
|
78
95
|
// POST /chat/:chatId/stop
|
|
79
|
-
|
|
96
|
+
export async function stop(chatId: string) {
|
|
97
|
+
await context.stopStream({ streamId: chatId });
|
|
98
|
+
}
|
|
80
99
|
```
|
|
81
100
|
|
|
82
101
|
## Usage
|
|
83
102
|
|
|
84
103
|
### `startStream`
|
|
85
104
|
|
|
86
|
-
Starts a stream and
|
|
105
|
+
Starts a stream and stores the chunks as they are produced. Returns the stream for the client, the stream id and the generation id.
|
|
87
106
|
|
|
88
107
|
> [!TIP]
|
|
89
108
|
> The returned stream is both a `ReadableStream` and an async iterable, so `return stream` and `yield* stream` both work.
|
|
@@ -92,7 +111,7 @@ Starts a stream and persists chunks as they are produced. Returns the stream for
|
|
|
92
111
|
import { streamText, toUIMessageStream } from "ai";
|
|
93
112
|
|
|
94
113
|
async function sendMessage(chatId: string, messages: UIMessage[]) {
|
|
95
|
-
// Optional:
|
|
114
|
+
// Optional: `streamText` sees the stop signal and aborts the HTTP request
|
|
96
115
|
const abortController = new AbortController();
|
|
97
116
|
|
|
98
117
|
const result = streamText({
|
|
@@ -112,15 +131,36 @@ async function sendMessage(chatId: string, messages: UIMessage[]) {
|
|
|
112
131
|
}
|
|
113
132
|
```
|
|
114
133
|
|
|
115
|
-
| Option
|
|
116
|
-
|
|
|
117
|
-
| `streamId`
|
|
118
|
-
| `
|
|
119
|
-
| `
|
|
134
|
+
| Option | Type | Description |
|
|
135
|
+
| ------------------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
136
|
+
| `streamId` | `string` | Id of the stream. Use it to resume or stop the stream. Defaults to a generated id, returned as `streamId` |
|
|
137
|
+
| `generationId` | `string` | Id of this generation. Use it to resume or stop only this generation. Must be unique within the stream id. Defaults to a generated id, returned as `generationId` |
|
|
138
|
+
| `abortController` | `AbortController` | Aborted when the stream is stopped. Created by the library if you do not pass one |
|
|
139
|
+
| `onStopSubscriptionError` | `(error: unknown) => void` | Called when the subscription to stop requests fails. The stream continues, but it cannot be stopped |
|
|
140
|
+
| `onFinish` | `() => void \| Promise<void>` | Called after the source stream has ended, also after an error or a stop. Errors thrown by the callback are ignored |
|
|
141
|
+
|
|
142
|
+
#### Abort controller
|
|
143
|
+
|
|
144
|
+
You can always stop a stream. If you do not pass an `abortController`, the library creates one.
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
// Without an abortController: a stop cancels the source stream
|
|
148
|
+
await context.startStream(toUIMessageStream({ stream: result.stream }), { streamId });
|
|
149
|
+
|
|
150
|
+
// With abortController: `streamText` sees the signal and aborts the HTTP request
|
|
151
|
+
const abortController = new AbortController();
|
|
152
|
+
const result = streamText({ model, messages, abortSignal: abortController.signal });
|
|
153
|
+
await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
154
|
+
streamId,
|
|
155
|
+
abortController,
|
|
156
|
+
});
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
We recommend that you pass your own `abortController` and give its signal to `streamText`. A stop then aborts the request to the provider directly, and the AI SDK emits its `abort` chunk and calls `onAbort`. Without it, a stop only cancels the source stream, and the cancellation must propagate back to `streamText`.
|
|
120
160
|
|
|
121
161
|
### `resumeStream`
|
|
122
162
|
|
|
123
|
-
|
|
163
|
+
Resumes an existing stream. The returned stream first replays all chunks produced so far and then continues with the new chunks. Pass `generationId` to resume a specific generation. Omit it to resume the current generation of the stream id. Returns `null` when there is nothing to resume.
|
|
124
164
|
|
|
125
165
|
```ts
|
|
126
166
|
async function resumeMessage(chatId: string) {
|
|
@@ -137,69 +177,94 @@ async function resumeMessage(chatId: string) {
|
|
|
137
177
|
}
|
|
138
178
|
```
|
|
139
179
|
|
|
140
|
-
The
|
|
180
|
+
The result is `null` in three cases. The library does not tell you which case applies:
|
|
141
181
|
|
|
142
|
-
- no stream was
|
|
143
|
-
- the stream already completed
|
|
144
|
-
- the producer died or was stopped
|
|
182
|
+
- no stream was started with that id
|
|
183
|
+
- the stream has already completed
|
|
184
|
+
- the producer died or was stopped before the stream completed
|
|
145
185
|
|
|
146
|
-
If your application
|
|
186
|
+
If your application must know whether a stream completed or was cut off, store that information together with the message.
|
|
147
187
|
|
|
148
188
|
### `stopStream`
|
|
149
189
|
|
|
150
|
-
|
|
190
|
+
Stops a running stream. Pass `generationId` to stop a specific generation. Omit it to stop the current generation of the stream id.
|
|
151
191
|
|
|
152
192
|
```ts
|
|
153
|
-
async function stopMessage(chatId: string) {
|
|
154
|
-
await
|
|
193
|
+
async function stopMessage(chatId: string, messageId?: string) {
|
|
194
|
+
await context.stopStream({ streamId: chatId, generationId: messageId });
|
|
155
195
|
}
|
|
156
196
|
```
|
|
157
197
|
|
|
158
|
-
|
|
198
|
+
A stop request with a generation id can arrive before that generation listens for stop requests, or before it starts. Both included adapters store the request, and the generation stops as soon as it starts to listen. A stop request without a generation id applies to the generation that is current at the time of the request. If there is no current generation, the request is not stored and has no effect.
|
|
159
199
|
|
|
160
|
-
|
|
200
|
+
See [Identifiers](#identifiers) for details about stream ids and generation ids.
|
|
161
201
|
|
|
162
|
-
|
|
202
|
+
## Identifiers
|
|
163
203
|
|
|
164
|
-
|
|
165
|
-
- **Pass the assistant message id** when you need to address one specific stream.
|
|
166
|
-
- **Omit it** and one is generated. `startStream` returns it.
|
|
204
|
+
A stream has two ids. If you do not pass an id, `startStream` generates it and returns both ids.
|
|
167
205
|
|
|
168
|
-
|
|
206
|
+
- **`streamId`** identifies the stream. A stream can run more than once. Each run is a generation.
|
|
207
|
+
- **`generationId`** identifies one generation of the stream.
|
|
169
208
|
|
|
170
|
-
|
|
209
|
+
Each call to `startStream` creates a new generation. The generation that started last is the current generation of the stream id.
|
|
171
210
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
await streams.startStream(toUIMessageStream({ stream: result.stream }), { streamId });
|
|
211
|
+
> [!TIP]
|
|
212
|
+
> Most applications only need the stream id. Use an id that the client already knows, for example the chat id or the session id. A client that reconnects can then call `resumeStream({ streamId: chatId })` without any other id.
|
|
175
213
|
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
})
|
|
214
|
+
### Stream ID
|
|
215
|
+
|
|
216
|
+
With only a stream id, `resumeStream` and `stopStream` apply to the current generation.
|
|
217
|
+
|
|
218
|
+
```
|
|
219
|
+
startStream({ streamId: "chat-1" }) ──▶ generation A
|
|
220
|
+
startStream({ streamId: "chat-1" }) ──▶ generation B (current)
|
|
221
|
+
|
|
222
|
+
resumeStream({ streamId: "chat-1" }) ──▶ generation B
|
|
223
|
+
stopStream({ streamId: "chat-1" }) ──▶ generation B
|
|
183
224
|
```
|
|
184
225
|
|
|
185
|
-
|
|
226
|
+
If you start a stream with a stream id that is already in use, the new generation becomes the current generation. A resume then returns only the chunks of the new generation. Generation A continues to run until its source stream ends, but the stream id alone no longer reaches it. When generation A ends, its cleanup does not affect generation B.
|
|
227
|
+
|
|
228
|
+
### Generation ID
|
|
229
|
+
|
|
230
|
+
With a stream id and a generation id, `resumeStream` and `stopStream` apply only to that generation, also after a newer generation has started.
|
|
231
|
+
|
|
232
|
+
```
|
|
233
|
+
startStream({ streamId: "chat-1", generationId: "msg-1" }) ──▶ generation msg-1
|
|
234
|
+
startStream({ streamId: "chat-1", generationId: "msg-2" }) ──▶ generation msg-2 (current)
|
|
235
|
+
|
|
236
|
+
resumeStream({ streamId: "chat-1" }) ──▶ generation msg-2
|
|
237
|
+
resumeStream({ streamId: "chat-1", generationId: "msg-1" }) ──▶ generation msg-1
|
|
238
|
+
stopStream({ streamId: "chat-1", generationId: "msg-1" }) ──▶ generation msg-1
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Use a generation id when generations of the same stream id can overlap. Example: a client stops a generation while a new generation with the same stream id starts. The stop request must stop only the old generation, not the new one.
|
|
242
|
+
|
|
243
|
+
Use an id that the client already knows, for example the id of the user message that it sent. The client can then resume or stop that generation without a server-generated id.
|
|
244
|
+
|
|
245
|
+
> [!WARNING]
|
|
246
|
+
> A generation id must be unique within its stream id. Do not use it again, for example when you retry the same message. The library does not check this, and resume and stop do not work correctly for a generation id that is used twice.
|
|
186
247
|
|
|
187
248
|
## Adapters
|
|
188
249
|
|
|
189
|
-
| Import |
|
|
190
|
-
| ----------------------------------------- |
|
|
191
|
-
| `ai-resumable-stream/adapters/redis` |
|
|
192
|
-
| `ai-resumable-stream/adapters/s3-express` | One appendable object
|
|
250
|
+
| Adapter | Import | Where chunks live | Resume needs a live producer | Cost model |
|
|
251
|
+
| ------------------------- | ----------------------------------------- | ----------------------------------- | ---------------------------- | -------------------------------- |
|
|
252
|
+
| [Redis](#redis) | `ai-resumable-stream/adapters/redis` | Memory of the producing process | Yes | Your Redis instance |
|
|
253
|
+
| [S3 Express](#s3-express) | `ai-resumable-stream/adapters/s3-express` | One appendable object in the bucket | No | One billed `PutObject` per flush |
|
|
193
254
|
|
|
194
255
|
### Redis
|
|
195
256
|
|
|
196
|
-
This adapter requires two Redis clients
|
|
257
|
+
This adapter requires two Redis clients, because pub/sub needs a separate connection. The library connects the clients if they are not connected yet, but it never disconnects them. You manage the connection lifecycle in your application and can reuse the clients for all streams.
|
|
258
|
+
|
|
259
|
+
> [!NOTE]
|
|
260
|
+
> You need to install `redis` to use this adapter. Both v5 and v6 are supported.
|
|
197
261
|
|
|
198
262
|
```ts
|
|
199
263
|
import { createClient } from "redis";
|
|
200
264
|
import { createRedisAdapter } from "ai-resumable-stream/adapters/redis";
|
|
201
265
|
import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
|
|
202
266
|
|
|
267
|
+
// Important: publisher and subscriber must be separate clients
|
|
203
268
|
const publisher = createClient({ url: process.env.REDIS_URL });
|
|
204
269
|
const subscriber = createClient({ url: process.env.REDIS_URL });
|
|
205
270
|
|
|
@@ -210,64 +275,25 @@ const context = createResumableUIMessageStream({
|
|
|
210
275
|
});
|
|
211
276
|
```
|
|
212
277
|
|
|
213
|
-
| Option | Type | Required | Description
|
|
214
|
-
| ------------ | ------------- | -------- |
|
|
215
|
-
| `publisher` | `RedisClient` | Yes |
|
|
216
|
-
| `subscriber` | `RedisClient` | Yes | Must be separate
|
|
217
|
-
| `keyPrefix` | `string` | No |
|
|
218
|
-
|
|
219
|
-
#### How it works
|
|
220
|
-
|
|
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.
|
|
222
|
-
|
|
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.
|
|
224
|
-
|
|
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.
|
|
278
|
+
| Option | Type | Required | Description |
|
|
279
|
+
| ------------ | ------------- | -------- | --------------------------------------------------------------------------------------------------------- |
|
|
280
|
+
| `publisher` | `RedisClient` | Yes | Client that sends commands and publishes messages |
|
|
281
|
+
| `subscriber` | `RedisClient` | Yes | Client for subscriptions. Must be a separate client, because a subscribed connection cannot send commands |
|
|
282
|
+
| `keyPrefix` | `string` | No | Prefix for all keys and channels. Defaults to `ai-resumable-stream` |
|
|
226
283
|
|
|
227
284
|
> [!IMPORTANT]
|
|
228
285
|
> **A stream is only resumable while its producer is alive.**
|
|
229
286
|
|
|
230
|
-
|
|
231
|
-
sequenceDiagram
|
|
232
|
-
participant Client
|
|
233
|
-
participant Server
|
|
234
|
-
participant Redis
|
|
235
|
-
|
|
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
|
|
245
|
-
|
|
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
|
|
256
|
-
|
|
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
|
-
```
|
|
287
|
+
See [docs/adapter-redis.md](https://github.com/zirkelc/ai-resumable-stream/blob/main/docs/adapter-redis.md) for how it works, a sequence diagram and a full example.
|
|
265
288
|
|
|
266
289
|
### S3 Express
|
|
267
290
|
|
|
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
|
|
291
|
+
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`. You create the client, so you control the credentials, the region and the retry behaviour.
|
|
269
292
|
|
|
270
|
-
|
|
293
|
+
The chunks are stored in the bucket, not in the memory of the producing process. A resume reads the chunks from the bucket. It does not need a response from the producing process, and any instance with access to the bucket can serve it.
|
|
294
|
+
|
|
295
|
+
> [!NOTE]
|
|
296
|
+
> You need to install `@aws-sdk/client-s3` to use this adapter.
|
|
271
297
|
|
|
272
298
|
```ts
|
|
273
299
|
import { S3Client } from "@aws-sdk/client-s3";
|
|
@@ -279,143 +305,71 @@ const adapter = createS3ExpressAdapter({
|
|
|
279
305
|
});
|
|
280
306
|
```
|
|
281
307
|
|
|
282
|
-
| Option | Type | Default | Description
|
|
283
|
-
| ---------------------- | ---------- | --------------------- |
|
|
284
|
-
| `client` | `S3Client` | |
|
|
285
|
-
| `bucket` | `string` | | A directory bucket in an Availability Zone
|
|
286
|
-
| `prefix` | `string` | `ai-resumable-stream` |
|
|
287
|
-
| `flushIntervalMs` | `number` | `250` |
|
|
288
|
-
| `batchSize` | `number` | `50` |
|
|
289
|
-
| `resumePollIntervalMs` | `number` | `500` |
|
|
290
|
-
| `stopPollIntervalMs` | `number` | `1000` |
|
|
291
|
-
| `heartbeatMs` | `number` | `5000` |
|
|
292
|
-
| `deadAfterMs` | `number` | `30000` |
|
|
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`.
|
|
308
|
+
| Option | Type | Default | Description |
|
|
309
|
+
| ---------------------- | ---------- | --------------------- | --------------------------------------------------------------------------------------------------- |
|
|
310
|
+
| `client` | `S3Client` | | The S3 client. You create and configure it |
|
|
311
|
+
| `bucket` | `string` | | A directory bucket in an Availability Zone |
|
|
312
|
+
| `prefix` | `string` | `ai-resumable-stream` | Prefix for all keys. Use it as the filter of the lifecycle rule |
|
|
313
|
+
| `flushIntervalMs` | `number` | `250` | Maximum time that chunks stay in memory before they are written |
|
|
314
|
+
| `batchSize` | `number` | `50` | Number of buffered chunks that triggers a write |
|
|
315
|
+
| `resumePollIntervalMs` | `number` | `500` | Interval at which a resumed stream checks for new chunks |
|
|
316
|
+
| `stopPollIntervalMs` | `number` | `1000` | Interval at which a producer checks for a stop request |
|
|
317
|
+
| `heartbeatMs` | `number` | `5000` | Interval at which an idle producer records that it is alive |
|
|
318
|
+
| `deadAfterMs` | `number` | `30000` | Time without writes after which a producer is considered dead. Must be at least twice `heartbeatMs` |
|
|
366
319
|
|
|
367
320
|
> [!WARNING]
|
|
368
|
-
>
|
|
321
|
+
> The adapter does not delete objects when a stream finishes. Set a lifecycle expiration rule on the bucket with `prefix` as the filter, and grant `s3express:CreateSession` with `ReadWrite` to `lifecycle.s3.amazonaws.com` in the bucket policy. Without this grant, the rule does nothing and the objects are never deleted. See [Cleanup](https://github.com/zirkelc/ai-resumable-stream/blob/main/docs/adapter-s3-express.md#cleanup).
|
|
369
322
|
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
```sh
|
|
373
|
-
S3_EXPRESS_BUCKET=my-streams--use1-az4--x-s3 AWS_REGION=us-east-1 pnpm test integration
|
|
374
|
-
```
|
|
323
|
+
See [docs/adapter-s3-express.md](https://github.com/zirkelc/ai-resumable-stream/blob/main/docs/adapter-s3-express.md) for how it works, the storage layout, a sequence diagram, cost and liveness details, and a full example.
|
|
375
324
|
|
|
376
325
|
### Custom `StreamAdapter`
|
|
377
326
|
|
|
378
|
-
|
|
327
|
+
Implement the `StreamAdapter` interface against the store you want and pass the object as `adapter`.
|
|
379
328
|
|
|
380
329
|
```ts
|
|
381
330
|
import type { StreamAdapter } from "ai-resumable-stream";
|
|
382
331
|
|
|
383
332
|
const adapter: StreamAdapter = {
|
|
384
|
-
createStream({ streamId, chunks, waitUntil }) { ... },
|
|
385
|
-
resumeStream({ streamId }) { ... },
|
|
386
|
-
requestStop({ streamId }) { ... },
|
|
387
|
-
onStopRequested({ streamId, onStop }) { ... },
|
|
333
|
+
createStream({ streamId, generationId, chunks, waitUntil }) { ... },
|
|
334
|
+
resumeStream({ streamId, generationId }) { ... },
|
|
335
|
+
requestStop({ streamId, generationId }) { ... },
|
|
336
|
+
onStopRequested({ streamId, generationId, onStop }) { ... },
|
|
388
337
|
};
|
|
389
338
|
```
|
|
390
339
|
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
| `requestStop` | Safe to call for an unknown or finished stream |
|
|
396
|
-
| `onStopRequested` | Producer-side listener. Returns a function that removes it |
|
|
340
|
+
- **`createStream`** is called when a stream starts. It receives the stream id, the generation id and a `ReadableStream<string>` of encoded chunks. First, it discards any state left over from an earlier stream with the same id, so a reused id never replays old chunks. Then it makes `generationId` the current generation of the stream id and consumes the chunks in the background until the stream ends. The returned promise resolves as soon as the stream can be resumed, not when it is complete.
|
|
341
|
+
- **`resumeStream`** is called when a client reconnects. It returns every chunk produced so far, in the original order, and then continues with the new chunks until the stream ends. With a `generationId`, it resumes that generation. Without one, it resumes the current generation of the stream id. It returns `null` when the id is unknown, the stream has already finished, or its data has expired.
|
|
342
|
+
- **`requestStop`** is called by the process that wants to stop a stream. With a `generationId`, it stops that generation. Without one, it stops the current generation of the stream id. It must not fail when the stream is unknown or already finished, and it should store the request if the generation does not listen yet.
|
|
343
|
+
- **`onStopRequested`** is called by the producing process when a stream starts. It registers a listener for one generation that calls `onStop` when a stop signal arrives. If a stop request was stored before the listener was registered, the listener also calls `onStop` for that request. It returns a function that removes only this listener.
|
|
397
344
|
|
|
398
|
-
|
|
345
|
+
The adapter must treat the chunks as opaque strings. If your store needs a special format, for example escaping or a length prefix, the adapter adds it on write and removes it on read.
|
|
399
346
|
|
|
400
|
-
`requestStop` and `onStopRequested` usually run in different processes, so the stop signal
|
|
347
|
+
`requestStop` and `onStopRequested` usually run in different processes, so the stop signal must also go through the store, for example by a subscription or a poll. Store the stop signal per generation, so that a stop never reaches a different generation of the same stream id. `startStream` does not await `onStopRequested`. If `onStopRequested` rejects, the only effect is that the generation cannot be stopped.
|
|
401
348
|
|
|
402
|
-
The tests in [`src/__tests__/conformance-suite.ts`](./src/__tests__/conformance-suite.ts) run against both
|
|
349
|
+
The tests in [`src/__tests__/conformance-suite.ts`](./src/__tests__/conformance-suite.ts) run against both included adapters. They cover the behaviour that an adapter must have:
|
|
350
|
+
|
|
351
|
+
- a resume replays the past chunks and then continues with the new chunks
|
|
352
|
+
- chunks are still stored after the client disconnects
|
|
353
|
+
- a reused stream id does not replay the chunks of the previous stream
|
|
354
|
+
- a stop also ends the stream of a client that resumed
|
|
355
|
+
- a stop with a generation id only stops that generation, also when it was requested before that generation started
|
|
356
|
+
- an older generation can be resumed while a newer generation is current
|
|
403
357
|
|
|
404
358
|
## Advanced
|
|
405
359
|
|
|
406
360
|
### Chunk types
|
|
407
361
|
|
|
408
|
-
The root export
|
|
362
|
+
The root export works with any chunk type and does not depend on `ai`. The `ai-sdk` subpath export is preconfigured for the `UIMessageChunk` type of the AI SDK:
|
|
409
363
|
|
|
410
364
|
```ts
|
|
411
365
|
import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
|
|
412
366
|
|
|
413
|
-
const
|
|
367
|
+
const context = createResumableUIMessageStream({ adapter });
|
|
414
368
|
```
|
|
415
369
|
|
|
416
|
-
|
|
370
|
+
This is the same as `createResumableStream({ adapter, codec: uiMessageChunkCodec })`. The codec validates each chunk when it is read. An invalid chunk, for example one written by an older version of your application, is dropped and does not fail the resume.
|
|
417
371
|
|
|
418
|
-
For
|
|
372
|
+
For other chunk types, pass your own `StreamCodec`:
|
|
419
373
|
|
|
420
374
|
```ts
|
|
421
375
|
import { createResumableStream, type StreamCodec } from "ai-resumable-stream";
|
|
@@ -425,27 +379,27 @@ const codec: StreamCodec<MyChunk> = {
|
|
|
425
379
|
decode: (data) => JSON.parse(data) as MyChunk,
|
|
426
380
|
};
|
|
427
381
|
|
|
428
|
-
const
|
|
382
|
+
const context = createResumableStream({ adapter, codec });
|
|
429
383
|
```
|
|
430
384
|
|
|
431
|
-
`decode`
|
|
385
|
+
`decode` can return `undefined` to drop a chunk that it cannot decode. One invalid chunk then does not fail the full resume.
|
|
432
386
|
|
|
433
387
|
### Serverless
|
|
434
388
|
|
|
435
|
-
|
|
389
|
+
The library continues to store chunks after the response has been sent. On serverless runtimes, pass `waitUntil` so that the runtime keeps the function alive until all chunks are stored:
|
|
436
390
|
|
|
437
391
|
```ts
|
|
438
392
|
import { waitUntil } from "@vercel/functions";
|
|
439
393
|
|
|
440
|
-
const
|
|
394
|
+
const context = createResumableUIMessageStream({ adapter, waitUntil });
|
|
441
395
|
```
|
|
442
396
|
|
|
443
397
|
### Finish
|
|
444
398
|
|
|
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
|
|
399
|
+
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 caught and ignored.
|
|
446
400
|
|
|
447
401
|
```typescript
|
|
448
|
-
const stream = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
402
|
+
const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
449
403
|
onFinish: async () => {
|
|
450
404
|
await saveChat({ chatId, activeStreamId: null });
|
|
451
405
|
},
|
|
@@ -454,16 +408,16 @@ const stream = await context.startStream(toUIMessageStream({ stream: result.stre
|
|
|
454
408
|
|
|
455
409
|
## Examples
|
|
456
410
|
|
|
457
|
-
|
|
411
|
+
The [`examples/`](./examples) folder contains one runnable example for each adapter. Each example starts a stream, disconnects the client before the stream ends, resumes the stream by its id, and then stops a second stream with `stopStream`.
|
|
458
412
|
|
|
459
413
|
```sh
|
|
460
|
-
pnpm example:redis # a
|
|
461
|
-
pnpm example:s3-express # an in-memory bucket
|
|
414
|
+
pnpm example:redis # starts a temporary Redis server
|
|
415
|
+
pnpm example:s3-express # uses an in-memory bucket
|
|
462
416
|
```
|
|
463
417
|
|
|
464
418
|
### tRPC
|
|
465
419
|
|
|
466
|
-
Server-side procedures
|
|
420
|
+
Server-side procedures to send, resume and stop. The chat id is used as the stream id, so you do not have to store a separate stream id.
|
|
467
421
|
|
|
468
422
|
```ts
|
|
469
423
|
// server/router.ts
|
|
@@ -477,7 +431,7 @@ import { publicProcedure, router } from "./trpc";
|
|
|
477
431
|
const publisher = createClient({ url: process.env.REDIS_URL });
|
|
478
432
|
const subscriber = createClient({ url: process.env.REDIS_URL });
|
|
479
433
|
|
|
480
|
-
const
|
|
434
|
+
const context = createResumableUIMessageStream({
|
|
481
435
|
adapter: createRedisAdapter({ publisher, subscriber }),
|
|
482
436
|
});
|
|
483
437
|
|
|
@@ -495,7 +449,7 @@ export const appRouter = router({
|
|
|
495
449
|
abortSignal: abortController.signal,
|
|
496
450
|
});
|
|
497
451
|
|
|
498
|
-
const { stream } = await
|
|
452
|
+
const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
499
453
|
streamId: chatId,
|
|
500
454
|
abortController,
|
|
501
455
|
onFinish: async () => {
|
|
@@ -509,7 +463,7 @@ export const appRouter = router({
|
|
|
509
463
|
resumeMessage: publicProcedure.input(z.object({ chatId: z.string() })).mutation(async function* ({
|
|
510
464
|
input,
|
|
511
465
|
}): AsyncGenerator<UIMessageChunk> {
|
|
512
|
-
const stream = await
|
|
466
|
+
const stream = await context.resumeStream({ streamId: input.chatId });
|
|
513
467
|
if (!stream) return;
|
|
514
468
|
|
|
515
469
|
yield* stream;
|
|
@@ -518,7 +472,7 @@ export const appRouter = router({
|
|
|
518
472
|
stopMessage: publicProcedure
|
|
519
473
|
.input(z.object({ chatId: z.string() }))
|
|
520
474
|
.mutation(async ({ input }) => {
|
|
521
|
-
await
|
|
475
|
+
await context.stopStream({ streamId: input.chatId });
|
|
522
476
|
|
|
523
477
|
return { success: true };
|
|
524
478
|
}),
|
|
@@ -534,7 +488,7 @@ function createResumableStream<CHUNK>(options: CreateResumableStreamOptions<CHUN
|
|
|
534
488
|
startStream: (
|
|
535
489
|
source: ReadableStream<CHUNK>,
|
|
536
490
|
options?: StartStreamOptions,
|
|
537
|
-
) => Promise<
|
|
491
|
+
) => Promise<StartStreamResult<CHUNK>>;
|
|
538
492
|
resumeStream: (options: ResumeStreamOptions) => Promise<AsyncIterableStream<CHUNK> | null>;
|
|
539
493
|
stopStream: (options: StopStreamOptions) => Promise<void>;
|
|
540
494
|
};
|
|
@@ -548,29 +502,39 @@ type CreateResumableStreamOptions<CHUNK> = {
|
|
|
548
502
|
|
|
549
503
|
type StartStreamOptions = {
|
|
550
504
|
streamId?: string;
|
|
505
|
+
generationId?: string;
|
|
551
506
|
abortController?: AbortController;
|
|
507
|
+
onStopSubscriptionError?: (error: unknown) => void;
|
|
552
508
|
onFinish?: () => void | Promise<void>;
|
|
553
509
|
};
|
|
554
510
|
|
|
511
|
+
type StartStreamResult<CHUNK> = {
|
|
512
|
+
streamId: string;
|
|
513
|
+
generationId: string;
|
|
514
|
+
stream: AsyncIterableStream<CHUNK>;
|
|
515
|
+
};
|
|
516
|
+
|
|
555
517
|
type ResumeStreamOptions = {
|
|
556
518
|
streamId: string;
|
|
519
|
+
generationId?: string;
|
|
557
520
|
};
|
|
558
521
|
|
|
559
522
|
type StopStreamOptions = {
|
|
560
523
|
streamId: string;
|
|
524
|
+
generationId?: string;
|
|
561
525
|
};
|
|
562
526
|
```
|
|
563
527
|
|
|
564
|
-
| Option | Type | Required | Description
|
|
565
|
-
| ------------ | -------------------- | -------- |
|
|
566
|
-
| `adapter` | `StreamAdapter` | Yes |
|
|
567
|
-
| `codec` | `StreamCodec<CHUNK>` | Yes |
|
|
568
|
-
| `waitUntil` | `(promise) => void` | No | Keeps the
|
|
569
|
-
| `generateId` | `() => string` | No | Generates
|
|
528
|
+
| Option | Type | Required | Description |
|
|
529
|
+
| ------------ | -------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
530
|
+
| `adapter` | `StreamAdapter` | Yes | Stores the chunks and transports stop requests |
|
|
531
|
+
| `codec` | `StreamCodec<CHUNK>` | Yes | Converts chunks to strings for the adapter, and back |
|
|
532
|
+
| `waitUntil` | `(promise) => void` | No | Keeps the process alive until all chunks are stored. Only needed on serverless runtimes |
|
|
533
|
+
| `generateId` | `() => string` | No | Generates the stream id and the generation id when you do not pass them to `startStream`. Must return a new id on each call. Defaults to `crypto.randomUUID` |
|
|
570
534
|
|
|
571
535
|
### `createResumableUIMessageStream`
|
|
572
536
|
|
|
573
|
-
|
|
537
|
+
Same as `createResumableStream`, with `codec` set to `uiMessageChunkCodec`.
|
|
574
538
|
|
|
575
539
|
```ts
|
|
576
540
|
function createResumableUIMessageStream(
|
|
@@ -584,12 +548,20 @@ function createResumableUIMessageStream(
|
|
|
584
548
|
type StreamAdapter = {
|
|
585
549
|
createStream(options: {
|
|
586
550
|
streamId: string;
|
|
551
|
+
generationId: string;
|
|
587
552
|
chunks: ReadableStream<string>;
|
|
588
553
|
waitUntil?: (promise: Promise<unknown>) => void;
|
|
589
554
|
}): Promise<void>;
|
|
590
|
-
resumeStream(options: {
|
|
591
|
-
|
|
592
|
-
|
|
555
|
+
resumeStream(options: {
|
|
556
|
+
streamId: string;
|
|
557
|
+
generationId?: string;
|
|
558
|
+
}): Promise<ReadableStream<string> | null>;
|
|
559
|
+
requestStop(options: { streamId: string; generationId?: string }): Promise<void>;
|
|
560
|
+
onStopRequested(options: {
|
|
561
|
+
streamId: string;
|
|
562
|
+
generationId: string;
|
|
563
|
+
onStop: () => void;
|
|
564
|
+
}): Promise<() => void>;
|
|
593
565
|
};
|
|
594
566
|
```
|
|
595
567
|
|