ai-resumable-stream 2.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 +421 -266
- package/dist/adapter-CTz0z2k0.d.mts +82 -0
- package/dist/adapters/redis/index.d.mts +54 -0
- package/dist/adapters/redis/index.mjs +258 -0
- package/dist/adapters/s3-express/index.d.mts +65 -0
- package/dist/adapters/s3-express/index.mjs +751 -0
- package/dist/ai-sdk/index.d.mts +23 -0
- package/dist/ai-sdk/index.mjs +37 -0
- package/dist/core-DAlVpiTc.mjs +173 -0
- package/dist/core-DmhblcmG.d.mts +107 -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. The library stores chunks as they are produced. Clients can then resume an interrupted stream, and any request can stop an active stream.
|
|
13
|
+
|
|
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.
|
|
13
15
|
|
|
14
16
|
**Why?**
|
|
15
17
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
**Resume
|
|
19
|
-
|
|
20
|
-
**Stop
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
## How It Works
|
|
28
|
-
|
|
29
|
-
```mermaid
|
|
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
|
|
54
|
-
|
|
55
|
-
rect rgb(255, 248, 240)
|
|
56
|
-
Note over Client,Redis: Stop Stream
|
|
57
|
-
Client->>Server: stopStream()
|
|
58
|
-
Server->>Redis: Publish to stop channel
|
|
59
|
-
Redis-->>Server: Notify subscriber
|
|
60
|
-
Server->>Server: AbortController.abort()
|
|
61
|
-
end
|
|
18
|
+
A stream does not keep its data. After a chunk is sent, it is gone. This causes two problems.
|
|
19
|
+
|
|
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
|
+
|
|
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
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npm install ai-resumable-stream
|
|
62
28
|
```
|
|
63
29
|
|
|
64
|
-
|
|
30
|
+
Install the optional peer dependencies for the features 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) or [`ai-resumable-stream@3.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v3.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,114 @@ 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 use the context in your three routes:
|
|
102
66
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
67
|
+
```ts
|
|
68
|
+
import { streamText, toUIMessageStream, type UIMessage } from "ai";
|
|
69
|
+
|
|
70
|
+
// POST /chat/:chatId
|
|
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
|
+
}
|
|
87
|
+
|
|
88
|
+
// GET /chat/:chatId/stream
|
|
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
|
+
}
|
|
94
|
+
|
|
95
|
+
// POST /chat/:chatId/stop
|
|
96
|
+
export async function stop(chatId: string) {
|
|
97
|
+
await context.stopStream({ streamId: chatId });
|
|
98
|
+
}
|
|
99
|
+
```
|
|
110
100
|
|
|
101
|
+
## Usage
|
|
111
102
|
|
|
112
103
|
### `startStream`
|
|
113
104
|
|
|
114
|
-
|
|
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.
|
|
115
106
|
|
|
116
107
|
> [!TIP]
|
|
117
|
-
> The stream
|
|
118
|
-
> That means you can use `return stream` or `yield* stream`.
|
|
108
|
+
> The returned stream is both a `ReadableStream` and an async iterable, so `return stream` and `yield* stream` both work.
|
|
119
109
|
|
|
120
|
-
```
|
|
110
|
+
```ts
|
|
121
111
|
import { streamText, toUIMessageStream } from "ai";
|
|
122
112
|
|
|
123
|
-
async function sendMessage() {
|
|
124
|
-
// Optional:
|
|
113
|
+
async function sendMessage(chatId: string, messages: UIMessage[]) {
|
|
114
|
+
// Optional: `streamText` sees the stop signal and aborts the HTTP request
|
|
125
115
|
const abortController = new AbortController();
|
|
126
116
|
|
|
127
|
-
// Create resumable stream context
|
|
128
|
-
const context = await createResumableUIMessageStream({
|
|
129
|
-
streamId: `stream-123`,
|
|
130
|
-
publisher,
|
|
131
|
-
subscriber,
|
|
132
|
-
abortController,
|
|
133
|
-
});
|
|
134
|
-
|
|
135
117
|
const result = streamText({
|
|
136
|
-
model: `gpt-4o
|
|
137
|
-
|
|
138
|
-
// Optional: pass abort signal to enable stopping
|
|
118
|
+
model: openai(`gpt-4o`),
|
|
119
|
+
messages,
|
|
139
120
|
abortSignal: abortController.signal,
|
|
140
121
|
});
|
|
141
122
|
|
|
142
|
-
|
|
143
|
-
|
|
123
|
+
const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
124
|
+
// Optional: generates a stream id if not supplied
|
|
125
|
+
streamId: chatId,
|
|
126
|
+
abortController,
|
|
127
|
+
});
|
|
144
128
|
|
|
145
129
|
// Return stream to client
|
|
146
130
|
return stream;
|
|
147
131
|
}
|
|
148
132
|
```
|
|
149
133
|
|
|
150
|
-
|
|
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 |
|
|
151
141
|
|
|
152
|
-
|
|
142
|
+
#### Abort controller
|
|
153
143
|
|
|
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`.
|
|
144
|
+
You can always stop a stream. If you do not pass an `abortController`, the library creates one.
|
|
157
145
|
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
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
|
+
```
|
|
166
158
|
|
|
167
|
-
|
|
168
|
-
|
|
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`.
|
|
160
|
+
|
|
161
|
+
### `resumeStream`
|
|
162
|
+
|
|
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.
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
async function resumeMessage(chatId: string) {
|
|
167
|
+
const stream = await context.resumeStream({ streamId: chatId });
|
|
169
168
|
|
|
170
169
|
// If no stream exists, return early
|
|
171
170
|
if (!stream) {
|
|
@@ -178,247 +177,403 @@ async function resumeMessage() {
|
|
|
178
177
|
}
|
|
179
178
|
```
|
|
180
179
|
|
|
181
|
-
|
|
180
|
+
The result is `null` in three cases. The library does not tell you which case applies:
|
|
182
181
|
|
|
183
|
-
|
|
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
|
|
184
185
|
|
|
185
|
-
|
|
186
|
-
async function stopMessage() {
|
|
187
|
-
const context = await createResumableUIMessageStream({
|
|
188
|
-
streamId: `stream-123`,
|
|
189
|
-
publisher,
|
|
190
|
-
subscriber,
|
|
191
|
-
});
|
|
186
|
+
If your application must know whether a stream completed or was cut off, store that information together with the message.
|
|
192
187
|
|
|
193
|
-
|
|
188
|
+
### `stopStream`
|
|
189
|
+
|
|
190
|
+
Stops a running stream. Pass `generationId` to stop a specific generation. Omit it to stop the current generation of the stream id.
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
async function stopMessage(chatId: string, messageId?: string) {
|
|
194
|
+
await context.stopStream({ streamId: chatId, generationId: messageId });
|
|
194
195
|
}
|
|
195
196
|
```
|
|
196
197
|
|
|
197
|
-
|
|
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.
|
|
198
199
|
|
|
199
|
-
|
|
200
|
+
See [Identifiers](#identifiers) for details about stream ids and generation ids.
|
|
200
201
|
|
|
201
|
-
|
|
202
|
+
## Identifiers
|
|
202
203
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
204
|
+
A stream has two ids. If you do not pass an id, `startStream` generates it and returns both ids.
|
|
205
|
+
|
|
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.
|
|
208
|
+
|
|
209
|
+
Each call to `startStream` creates a new generation. The generation that started last is the current generation of the stream id.
|
|
210
|
+
|
|
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.
|
|
213
|
+
|
|
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
|
|
224
|
+
```
|
|
225
|
+
|
|
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.
|
|
247
|
+
|
|
248
|
+
## Adapters
|
|
249
|
+
|
|
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 |
|
|
254
|
+
|
|
255
|
+
### Redis
|
|
256
|
+
|
|
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.
|
|
261
|
+
|
|
262
|
+
```ts
|
|
207
263
|
import { createClient } from "redis";
|
|
208
|
-
import {
|
|
209
|
-
import {
|
|
264
|
+
import { createRedisAdapter } from "ai-resumable-stream/adapters/redis";
|
|
265
|
+
import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
|
|
210
266
|
|
|
267
|
+
// Important: publisher and subscriber must be separate clients
|
|
211
268
|
const publisher = createClient({ url: process.env.REDIS_URL });
|
|
212
269
|
const subscriber = createClient({ url: process.env.REDIS_URL });
|
|
213
270
|
|
|
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;
|
|
271
|
+
const adapter = createRedisAdapter({ publisher, subscriber });
|
|
219
272
|
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
273
|
+
const context = createResumableUIMessageStream({
|
|
274
|
+
adapter,
|
|
275
|
+
});
|
|
276
|
+
```
|
|
223
277
|
|
|
224
|
-
|
|
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` |
|
|
225
283
|
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
publisher,
|
|
229
|
-
subscriber,
|
|
230
|
-
abortController,
|
|
231
|
-
});
|
|
284
|
+
> [!IMPORTANT]
|
|
285
|
+
> **A stream is only resumable while its producer is alive.**
|
|
232
286
|
|
|
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
|
-
});
|
|
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.
|
|
242
288
|
|
|
243
|
-
|
|
289
|
+
### S3 Express
|
|
244
290
|
|
|
245
|
-
|
|
246
|
-
}),
|
|
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.
|
|
247
292
|
|
|
248
|
-
|
|
249
|
-
input,
|
|
250
|
-
}): AsyncGenerator<UIMessageChunk> {
|
|
251
|
-
const { chatId } = input;
|
|
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.
|
|
252
294
|
|
|
253
|
-
|
|
254
|
-
|
|
295
|
+
> [!NOTE]
|
|
296
|
+
> You need to install `@aws-sdk/client-s3` to use this adapter.
|
|
255
297
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
subscriber,
|
|
260
|
-
});
|
|
298
|
+
```ts
|
|
299
|
+
import { S3Client } from "@aws-sdk/client-s3";
|
|
300
|
+
import { createS3ExpressAdapter } from "ai-resumable-stream/adapters/s3-express";
|
|
261
301
|
|
|
262
|
-
|
|
263
|
-
|
|
302
|
+
const adapter = createS3ExpressAdapter({
|
|
303
|
+
client: new S3Client({ region: `us-east-1` }),
|
|
304
|
+
bucket: `my-streams--use1-az4--x-s3`,
|
|
305
|
+
});
|
|
306
|
+
```
|
|
264
307
|
|
|
265
|
-
|
|
266
|
-
|
|
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` |
|
|
267
319
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
.mutation(async ({ input }) => {
|
|
271
|
-
const { chatId } = input;
|
|
320
|
+
> [!WARNING]
|
|
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).
|
|
272
322
|
|
|
273
|
-
|
|
274
|
-
const { activeStreamId } = await getChat(chatId);
|
|
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.
|
|
275
324
|
|
|
276
|
-
|
|
277
|
-
streamId: activeStreamId,
|
|
278
|
-
publisher,
|
|
279
|
-
subscriber,
|
|
280
|
-
});
|
|
325
|
+
### Custom `StreamAdapter`
|
|
281
326
|
|
|
282
|
-
|
|
327
|
+
Implement the `StreamAdapter` interface against the store you want and pass the object as `adapter`.
|
|
283
328
|
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
329
|
+
```ts
|
|
330
|
+
import type { StreamAdapter } from "ai-resumable-stream";
|
|
331
|
+
|
|
332
|
+
const adapter: StreamAdapter = {
|
|
333
|
+
createStream({ streamId, generationId, chunks, waitUntil }) { ... },
|
|
334
|
+
resumeStream({ streamId, generationId }) { ... },
|
|
335
|
+
requestStop({ streamId, generationId }) { ... },
|
|
336
|
+
onStopRequested({ streamId, generationId, onStop }) { ... },
|
|
337
|
+
};
|
|
287
338
|
```
|
|
288
339
|
|
|
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.
|
|
344
|
+
|
|
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.
|
|
346
|
+
|
|
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.
|
|
348
|
+
|
|
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
|
|
357
|
+
|
|
289
358
|
## Advanced
|
|
290
359
|
|
|
291
|
-
###
|
|
360
|
+
### Chunk types
|
|
292
361
|
|
|
293
|
-
The
|
|
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:
|
|
294
363
|
|
|
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
|
-
});
|
|
364
|
+
```ts
|
|
365
|
+
import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
|
|
306
366
|
|
|
307
|
-
|
|
308
|
-
await publisher.quit();
|
|
309
|
-
await subscriber.quit();
|
|
367
|
+
const context = createResumableUIMessageStream({ adapter });
|
|
310
368
|
```
|
|
311
369
|
|
|
312
|
-
|
|
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.
|
|
313
371
|
|
|
314
|
-
|
|
372
|
+
For other chunk types, pass your own `StreamCodec`:
|
|
315
373
|
|
|
316
|
-
|
|
374
|
+
```ts
|
|
375
|
+
import { createResumableStream, type StreamCodec } from "ai-resumable-stream";
|
|
317
376
|
|
|
318
|
-
|
|
319
|
-
|
|
377
|
+
const codec: StreamCodec<MyChunk> = {
|
|
378
|
+
encode: (chunk) => JSON.stringify(chunk),
|
|
379
|
+
decode: (data) => JSON.parse(data) as MyChunk,
|
|
380
|
+
};
|
|
320
381
|
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
|
|
382
|
+
const context = createResumableStream({ adapter, codec });
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
`decode` can return `undefined` to drop a chunk that it cannot decode. One invalid chunk then does not fail the full resume.
|
|
324
386
|
|
|
325
|
-
|
|
387
|
+
### Serverless
|
|
326
388
|
|
|
327
|
-
|
|
328
|
-
await saveAssistantMessage(result);
|
|
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:
|
|
329
390
|
|
|
330
|
-
|
|
331
|
-
|
|
391
|
+
```ts
|
|
392
|
+
import { waitUntil } from "@vercel/functions";
|
|
393
|
+
|
|
394
|
+
const context = createResumableUIMessageStream({ adapter, waitUntil });
|
|
332
395
|
```
|
|
333
396
|
|
|
334
|
-
###
|
|
397
|
+
### Finish
|
|
335
398
|
|
|
336
|
-
The `
|
|
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.
|
|
337
400
|
|
|
338
401
|
```typescript
|
|
339
|
-
const stream = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
340
|
-
|
|
402
|
+
const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
403
|
+
onFinish: async () => {
|
|
341
404
|
await saveChat({ chatId, activeStreamId: null });
|
|
342
405
|
},
|
|
343
406
|
});
|
|
344
407
|
```
|
|
345
408
|
|
|
346
|
-
|
|
409
|
+
## Examples
|
|
410
|
+
|
|
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`.
|
|
412
|
+
|
|
413
|
+
```sh
|
|
414
|
+
pnpm example:redis # starts a temporary Redis server
|
|
415
|
+
pnpm example:s3-express # uses an in-memory bucket
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
### tRPC
|
|
419
|
+
|
|
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.
|
|
421
|
+
|
|
422
|
+
```ts
|
|
423
|
+
// server/router.ts
|
|
424
|
+
import { z } from "zod";
|
|
425
|
+
import { streamText, toUIMessageStream, type UIMessage, type UIMessageChunk } from "ai";
|
|
426
|
+
import { createClient } from "redis";
|
|
427
|
+
import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
|
|
428
|
+
import { createRedisAdapter } from "ai-resumable-stream/adapters/redis";
|
|
429
|
+
import { publicProcedure, router } from "./trpc";
|
|
430
|
+
|
|
431
|
+
const publisher = createClient({ url: process.env.REDIS_URL });
|
|
432
|
+
const subscriber = createClient({ url: process.env.REDIS_URL });
|
|
433
|
+
|
|
434
|
+
const context = createResumableUIMessageStream({
|
|
435
|
+
adapter: createRedisAdapter({ publisher, subscriber }),
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
export const appRouter = router({
|
|
439
|
+
sendMessage: publicProcedure
|
|
440
|
+
.input(z.object({ chatId: z.string(), message: z.custom<UIMessage>() }))
|
|
441
|
+
.mutation(async function* ({ input }): AsyncGenerator<UIMessageChunk> {
|
|
442
|
+
const { chatId, message } = input;
|
|
443
|
+
|
|
444
|
+
const abortController = new AbortController();
|
|
445
|
+
|
|
446
|
+
const result = streamText({
|
|
447
|
+
model: openai(`gpt-4o`),
|
|
448
|
+
messages: [message],
|
|
449
|
+
abortSignal: abortController.signal,
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
453
|
+
streamId: chatId,
|
|
454
|
+
abortController,
|
|
455
|
+
onFinish: async () => {
|
|
456
|
+
await saveAssistantMessage(chatId, await result.text);
|
|
457
|
+
},
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
yield* stream;
|
|
461
|
+
}),
|
|
462
|
+
|
|
463
|
+
resumeMessage: publicProcedure.input(z.object({ chatId: z.string() })).mutation(async function* ({
|
|
464
|
+
input,
|
|
465
|
+
}): AsyncGenerator<UIMessageChunk> {
|
|
466
|
+
const stream = await context.resumeStream({ streamId: input.chatId });
|
|
467
|
+
if (!stream) return;
|
|
468
|
+
|
|
469
|
+
yield* stream;
|
|
470
|
+
}),
|
|
471
|
+
|
|
472
|
+
stopMessage: publicProcedure
|
|
473
|
+
.input(z.object({ chatId: z.string() }))
|
|
474
|
+
.mutation(async ({ input }) => {
|
|
475
|
+
await context.stopStream({ streamId: input.chatId });
|
|
476
|
+
|
|
477
|
+
return { success: true };
|
|
478
|
+
}),
|
|
479
|
+
});
|
|
480
|
+
```
|
|
347
481
|
|
|
348
482
|
## API Reference
|
|
349
483
|
|
|
350
|
-
### `
|
|
484
|
+
### `createResumableStream`
|
|
351
485
|
|
|
352
|
-
```
|
|
353
|
-
|
|
486
|
+
```ts
|
|
487
|
+
function createResumableStream<CHUNK>(options: CreateResumableStreamOptions<CHUNK>): {
|
|
354
488
|
startStream: (
|
|
355
|
-
|
|
489
|
+
source: ReadableStream<CHUNK>,
|
|
356
490
|
options?: StartStreamOptions,
|
|
357
|
-
) => Promise<
|
|
358
|
-
resumeStream: () => Promise<AsyncIterableStream<
|
|
359
|
-
stopStream: () => Promise<void>;
|
|
360
|
-
}
|
|
491
|
+
) => Promise<StartStreamResult<CHUNK>>;
|
|
492
|
+
resumeStream: (options: ResumeStreamOptions) => Promise<AsyncIterableStream<CHUNK> | null>;
|
|
493
|
+
stopStream: (options: StopStreamOptions) => Promise<void>;
|
|
494
|
+
};
|
|
361
495
|
|
|
362
|
-
type
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
subscriber: Redis;
|
|
366
|
-
abortController?: AbortController;
|
|
496
|
+
type CreateResumableStreamOptions<CHUNK> = {
|
|
497
|
+
adapter: StreamAdapter;
|
|
498
|
+
codec: StreamCodec<CHUNK>;
|
|
367
499
|
waitUntil?: (promise: Promise<unknown>) => void;
|
|
500
|
+
generateId?: () => string;
|
|
368
501
|
};
|
|
369
502
|
|
|
370
503
|
type StartStreamOptions = {
|
|
371
|
-
|
|
372
|
-
|
|
504
|
+
streamId?: string;
|
|
505
|
+
generationId?: string;
|
|
506
|
+
abortController?: AbortController;
|
|
507
|
+
onStopSubscriptionError?: (error: unknown) => void;
|
|
508
|
+
onFinish?: () => void | Promise<void>;
|
|
373
509
|
};
|
|
374
|
-
```
|
|
375
|
-
|
|
376
|
-
### Return Values
|
|
377
510
|
|
|
378
|
-
|
|
511
|
+
type StartStreamResult<CHUNK> = {
|
|
512
|
+
streamId: string;
|
|
513
|
+
generationId: string;
|
|
514
|
+
stream: AsyncIterableStream<CHUNK>;
|
|
515
|
+
};
|
|
379
516
|
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
): Promise<AsyncIterableStream<UIMessageChunk>>;
|
|
517
|
+
type ResumeStreamOptions = {
|
|
518
|
+
streamId: string;
|
|
519
|
+
generationId?: string;
|
|
520
|
+
};
|
|
385
521
|
|
|
386
|
-
type
|
|
387
|
-
|
|
388
|
-
|
|
522
|
+
type StopStreamOptions = {
|
|
523
|
+
streamId: string;
|
|
524
|
+
generationId?: string;
|
|
389
525
|
};
|
|
390
526
|
```
|
|
391
527
|
|
|
392
|
-
|
|
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` |
|
|
393
534
|
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
A promise that defers closing the Redis stream until it resolves. This keeps the resumable-stream producer alive after the source stream ends, so late resume requests (e.g. during post-stream DB writes) can still be served from the in-memory chunk buffer.
|
|
397
|
-
|
|
398
|
-
If the promise rejects, the producer tears down normally. If the source stream errors, the `keepAlive` promise is not awaited.
|
|
399
|
-
|
|
400
|
-
##### `onFlush`
|
|
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.
|
|
535
|
+
### `createResumableUIMessageStream`
|
|
405
536
|
|
|
406
|
-
|
|
537
|
+
Same as `createResumableStream`, with `codec` set to `uiMessageChunkCodec`.
|
|
407
538
|
|
|
408
|
-
```
|
|
409
|
-
|
|
539
|
+
```ts
|
|
540
|
+
function createResumableUIMessageStream(
|
|
541
|
+
options: Omit<CreateResumableStreamOptions<UIMessageChunk>, `codec`>,
|
|
542
|
+
): { startStream; resumeStream; stopStream };
|
|
410
543
|
```
|
|
411
544
|
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
545
|
+
### `StreamAdapter`
|
|
546
|
+
|
|
547
|
+
```ts
|
|
548
|
+
type StreamAdapter = {
|
|
549
|
+
createStream(options: {
|
|
550
|
+
streamId: string;
|
|
551
|
+
generationId: string;
|
|
552
|
+
chunks: ReadableStream<string>;
|
|
553
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
554
|
+
}): Promise<void>;
|
|
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>;
|
|
565
|
+
};
|
|
566
|
+
```
|
|
417
567
|
|
|
418
|
-
|
|
568
|
+
### `StreamCodec`
|
|
419
569
|
|
|
420
|
-
```
|
|
421
|
-
|
|
570
|
+
```ts
|
|
571
|
+
type StreamCodec<CHUNK> = {
|
|
572
|
+
encode(chunk: CHUNK): string;
|
|
573
|
+
decode(data: string): CHUNK | undefined | Promise<CHUNK | undefined>;
|
|
574
|
+
};
|
|
422
575
|
```
|
|
423
576
|
|
|
424
|
-
|
|
577
|
+
## License
|
|
578
|
+
|
|
579
|
+
MIT
|