@convex-dev/persistent-text-streaming 0.0.1

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.
Files changed (82) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +188 -0
  3. package/dist/commonjs/client/index.d.ts +89 -0
  4. package/dist/commonjs/client/index.d.ts.map +1 -0
  5. package/dist/commonjs/client/index.js +133 -0
  6. package/dist/commonjs/client/index.js.map +1 -0
  7. package/dist/commonjs/component/_generated/api.d.ts +14 -0
  8. package/dist/commonjs/component/_generated/api.d.ts.map +1 -0
  9. package/dist/commonjs/component/_generated/api.js +22 -0
  10. package/dist/commonjs/component/_generated/api.js.map +1 -0
  11. package/dist/commonjs/component/_generated/server.d.ts +64 -0
  12. package/dist/commonjs/component/_generated/server.d.ts.map +1 -0
  13. package/dist/commonjs/component/_generated/server.js +74 -0
  14. package/dist/commonjs/component/_generated/server.js.map +1 -0
  15. package/dist/commonjs/component/convex.config.d.ts +3 -0
  16. package/dist/commonjs/component/convex.config.d.ts.map +1 -0
  17. package/dist/commonjs/component/convex.config.js +3 -0
  18. package/dist/commonjs/component/convex.config.js.map +1 -0
  19. package/dist/commonjs/component/crons.d.ts +3 -0
  20. package/dist/commonjs/component/crons.d.ts.map +1 -0
  21. package/dist/commonjs/component/crons.js +7 -0
  22. package/dist/commonjs/component/crons.js.map +1 -0
  23. package/dist/commonjs/component/lib.d.ts +21 -0
  24. package/dist/commonjs/component/lib.d.ts.map +1 -0
  25. package/dist/commonjs/component/lib.js +134 -0
  26. package/dist/commonjs/component/lib.js.map +1 -0
  27. package/dist/commonjs/component/schema.d.ts +23 -0
  28. package/dist/commonjs/component/schema.d.ts.map +1 -0
  29. package/dist/commonjs/component/schema.js +13 -0
  30. package/dist/commonjs/component/schema.js.map +1 -0
  31. package/dist/commonjs/package.json +3 -0
  32. package/dist/commonjs/react/index.d.ts +23 -0
  33. package/dist/commonjs/react/index.d.ts.map +1 -0
  34. package/dist/commonjs/react/index.js +131 -0
  35. package/dist/commonjs/react/index.js.map +1 -0
  36. package/dist/esm/client/index.d.ts +89 -0
  37. package/dist/esm/client/index.d.ts.map +1 -0
  38. package/dist/esm/client/index.js +133 -0
  39. package/dist/esm/client/index.js.map +1 -0
  40. package/dist/esm/component/_generated/api.d.ts +14 -0
  41. package/dist/esm/component/_generated/api.d.ts.map +1 -0
  42. package/dist/esm/component/_generated/api.js +22 -0
  43. package/dist/esm/component/_generated/api.js.map +1 -0
  44. package/dist/esm/component/_generated/server.d.ts +64 -0
  45. package/dist/esm/component/_generated/server.d.ts.map +1 -0
  46. package/dist/esm/component/_generated/server.js +74 -0
  47. package/dist/esm/component/_generated/server.js.map +1 -0
  48. package/dist/esm/component/convex.config.d.ts +3 -0
  49. package/dist/esm/component/convex.config.d.ts.map +1 -0
  50. package/dist/esm/component/convex.config.js +3 -0
  51. package/dist/esm/component/convex.config.js.map +1 -0
  52. package/dist/esm/component/crons.d.ts +3 -0
  53. package/dist/esm/component/crons.d.ts.map +1 -0
  54. package/dist/esm/component/crons.js +7 -0
  55. package/dist/esm/component/crons.js.map +1 -0
  56. package/dist/esm/component/lib.d.ts +21 -0
  57. package/dist/esm/component/lib.d.ts.map +1 -0
  58. package/dist/esm/component/lib.js +134 -0
  59. package/dist/esm/component/lib.js.map +1 -0
  60. package/dist/esm/component/schema.d.ts +23 -0
  61. package/dist/esm/component/schema.d.ts.map +1 -0
  62. package/dist/esm/component/schema.js +13 -0
  63. package/dist/esm/component/schema.js.map +1 -0
  64. package/dist/esm/package.json +3 -0
  65. package/dist/esm/react/index.d.ts +23 -0
  66. package/dist/esm/react/index.d.ts.map +1 -0
  67. package/dist/esm/react/index.js +131 -0
  68. package/dist/esm/react/index.js.map +1 -0
  69. package/package.json +89 -0
  70. package/react/package.json +5 -0
  71. package/src/client/index.ts +223 -0
  72. package/src/component/_generated/api.d.ts +80 -0
  73. package/src/component/_generated/api.js +23 -0
  74. package/src/component/_generated/dataModel.d.ts +60 -0
  75. package/src/component/_generated/server.d.ts +149 -0
  76. package/src/component/_generated/server.js +90 -0
  77. package/src/component/convex.config.ts +3 -0
  78. package/src/component/crons.ts +13 -0
  79. package/src/component/lib.test.ts +9 -0
  80. package/src/component/lib.ts +149 -0
  81. package/src/component/schema.ts +21 -0
  82. package/src/react/index.ts +158 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,188 @@
1
+ # Convex Component: Persistent Text Streaming
2
+
3
+ [![npm version](https://badge.fury.io/js/@convex-dev%2Fpersistent-text-streaming.svg)](https://badge.fury.io/js/@convex-dev%2Fpersistent-text-streaming)
4
+
5
+ <!-- START: Include on https://convex.dev/components -->
6
+
7
+ This Convex component enables persistent text streaming. It provides a React hook
8
+ for streaming text from HTTP actions while simultaneously storing the data in the
9
+ database. This persistence allows the text to be accessed after the stream ends
10
+ or by other users.
11
+
12
+ The most common use case is for AI chat applications. The example app (found in the
13
+ `example` directory) is a just such a simple chat app that demonstrates use of the
14
+ component.
15
+
16
+ Here's what you'll end up with! The left browser window is streaming the chat body to the client,
17
+ and the right browser window is subscribed to the chat body via a database query. The
18
+ message is only updated in the database on sentence boundaries, whereas the HTTP
19
+ stream sends tokens as they come:
20
+
21
+ ![example-animation](./anim.gif)
22
+
23
+ ## Pre-requisite: Convex
24
+
25
+ You'll need an existing Convex project to use the component.
26
+ Convex is a hosted backend platform, including a database, serverless functions,
27
+ and a ton more you can learn about [here](https://docs.convex.dev/get-started).
28
+
29
+ Run `npm create convex` or follow any of the [quickstarts](https://docs.convex.dev/home) to set one up.
30
+
31
+ ## Installation
32
+
33
+ See [`example/`](./example/convex/) for a working demo.
34
+
35
+ 1. Install the Persistent Text Streaming component:
36
+
37
+ ```bash
38
+ npm install @convex-dev/persistent-text-streaming
39
+ ```
40
+
41
+ 2. Create a [`convex.config.ts`](./example/convex/convex.config.ts) file in your
42
+ app's `convex/` folder and install the component by calling `use`:
43
+
44
+ ```ts
45
+ // convex/convex.config.ts
46
+ import { defineApp } from "convex/server";
47
+ import persistentTextStreaming from "@convex-dev/persistent-text-streaming/convex.config";
48
+
49
+ const app = defineApp();
50
+ app.use(persistentTextStreaming);
51
+ export default app;
52
+ ```
53
+
54
+ ## Usage
55
+
56
+ Here's a simple example of how to use the component:
57
+
58
+ In `convex/chat.ts`:
59
+
60
+ ```ts
61
+ const persistentTextStreaming = new PersistentTextStreaming(
62
+ components.persistentTextStreaming
63
+ );
64
+
65
+ // Create a stream using the component and store the id in the database with
66
+ // our chat message.
67
+ export const createChat = mutation({
68
+ args: {
69
+ prompt: v.string(),
70
+ },
71
+ handler: async (ctx, args) => {
72
+ const streamId = await persistentTextStreaming.createStream(ctx);
73
+ const chatId = await ctx.db.insert("chats", {
74
+ title: "...",
75
+ prompt: args.prompt,
76
+ stream: streamId,
77
+ });
78
+ return chatId;
79
+ },
80
+ });
81
+
82
+ // Create a query that returns the chat body.
83
+ export const getChatBody = query({
84
+ args: {
85
+ streamId: StreamIdValidator,
86
+ },
87
+ handler: async (ctx, args) => {
88
+ return await persistentTextStreaming.getStreamBody(
89
+ ctx,
90
+ args.streamId as StreamId
91
+ );
92
+ },
93
+ });
94
+
95
+ // Create an HTTP action that generates chunks of the chat body
96
+ // and uses the component to stream them to the client and save them to the database.
97
+ export const streamChat = httpAction(async (ctx, request) => {
98
+ const generateChat = async (ctx, request, streamId, chunkAppender) => {
99
+ await chunkAppender("Hi there!");
100
+ await chunkAppender("How are you?");
101
+ await chunkAppender("Pretend I'm an AI or something!");
102
+ };
103
+
104
+ const response = await persistentTextStreaming.stream(
105
+ ctx,
106
+ request,
107
+ body.streamId as StreamId,
108
+ generateChat
109
+ );
110
+
111
+ // Set CORS headers appropriately.
112
+ response.headers.set("Access-Control-Allow-Origin", "*");
113
+ response.headers.set("Vary", "Origin");
114
+ return response;
115
+ });
116
+ ```
117
+
118
+ You need to expose this HTTP endpoint in your app, `http.ts`:
119
+
120
+ ```ts
121
+ http.route({
122
+ path: "/chat-stream",
123
+ method: "POST",
124
+ handler: streamChat,
125
+ });
126
+ ```
127
+
128
+ Finally, in your app, you can now create chats and them subscribe to them
129
+ via stream and/or database query as optimal:
130
+
131
+ ```ts
132
+ // chat-input.tsx, maybe?
133
+ const createChat = useMutation(api.chat.createChat);
134
+ const formSubmit = async (e: React.FormEvent) => {
135
+ e.preventDefault();
136
+ const chatId = await createChat({
137
+ prompt: inputValue,
138
+ });
139
+ };
140
+
141
+ // chat-message.tsx, maybe?
142
+ import { useStream } from "@convex-dev/persistent-text-streaming/react";
143
+
144
+ // ...
145
+
146
+ // In our component:
147
+ const { text, status } = useStream(
148
+ api.chat.getChatBody, // The query to call for the full stream body
149
+ new URL(`${convexSiteUrl}/chat-stream`), // The HTTP endpoint for streaming
150
+ driven, // True if this browser session created this chat and should generate the stream
151
+ chat.streamId as StreamId // The streamId from the chat database record
152
+ );
153
+ ```
154
+
155
+ ## Design Philosophy
156
+
157
+ This component balances HTTP streaming with database persistence to try to
158
+ maximize the benefits of both. To understand why this balance is beneficial,
159
+ let's examine each approach in isolation.
160
+
161
+ - **HTTP streaming only**: If your app _only_ uses HTTP streaming, then the
162
+ original browser that made the request will have a great, high-performance
163
+ streaming experience. But if that HTTP connection is lost, if the browser
164
+ window is reloaded, if other users want to view the same chat, or this
165
+ users wants to revisit the conversation later, it won't be possible. The
166
+ conversation is only ephemeral because it was never stored on the server.
167
+
168
+ - **Database Persistence Only**: If your app _only_ uses database persistence,
169
+ it's true that the conversation will be available for as long as you want.
170
+ Additionally, Convex's subscriptions will ensure the chat message is updated
171
+ as new text chunks are generated. However, there are a few downsides: one,
172
+ the entire chat body needs to be resent every time it is changed, which is a
173
+ lot redundant bandwidth to push into the database and over the websockets to
174
+ all connected clients. Two, you'll need to make a difficult tradeoff between
175
+ interactivity and efficiency. If you write every single small chunk to the
176
+ database, this will get quite slow and expensive. But if you batch up the chunks
177
+ into, say, paragraphs, then the user experience will feel laggy.
178
+
179
+ This component combines the best of both worlds. The original browser that
180
+ makes the request will still have a great, high-performance streaming experience.
181
+ But the chat body is also stored in the database, so it can be accessed by the
182
+ client even after the stream has finished, or by other users, etc.
183
+
184
+ ## Background
185
+
186
+ This component is largely based on the Stack post [AI Chat with HTTP Streaming](https://stack.convex.dev/ai-chat-with-http-streaming).
187
+
188
+ <!-- END: Include on https://convex.dev/components -->
@@ -0,0 +1,89 @@
1
+ import { Expand, FunctionReference, GenericActionCtx, GenericDataModel, GenericMutationCtx, GenericQueryCtx } from "convex/server";
2
+ import { GenericId } from "convex/values";
3
+ import { api } from "../component/_generated/api";
4
+ import { StreamStatus } from "../component/schema";
5
+ export type StreamId = string & {
6
+ __isStreamId: true;
7
+ };
8
+ export declare const StreamIdValidator: import("convex/values").VString<string, "required">;
9
+ export type StreamBody = {
10
+ text: string;
11
+ status: StreamStatus;
12
+ };
13
+ export type ChunkAppender = (text: string) => Promise<void>;
14
+ export type StreamWriter<A extends GenericActionCtx<GenericDataModel>> = (ctx: A, request: Request, streamId: StreamId, chunkAppender: ChunkAppender) => Promise<void>;
15
+ export declare class PersistentTextStreaming {
16
+ component: UseApi<typeof api>;
17
+ options?: object | undefined;
18
+ constructor(component: UseApi<typeof api>, options?: object | undefined);
19
+ /**
20
+ * Create a new stream. This will return a stream ID that can be used
21
+ * in an HTTP action to stream data back out to the client while also
22
+ * permanently persisting the final stream in the database.
23
+ *
24
+ * @param ctx - A convex context capable of running mutations.
25
+ * @returns The ID of the new stream.
26
+ * @example
27
+ * ```ts
28
+ * const streaming = new PersistentTextStreaming(api);
29
+ * const streamId = await streaming.createStream(ctx);
30
+ * await streaming.stream(ctx, request, streamId, async (ctx, req, id, append) => {
31
+ * await append("Hello ");
32
+ * await append("World!");
33
+ * });
34
+ * ```
35
+ */
36
+ createStream(ctx: RunMutationCtx): Promise<StreamId>;
37
+ /**
38
+ * Get the body of a stream. This will return the full text of the stream
39
+ * and the status of the stream.
40
+ *
41
+ * @param ctx - A convex context capable of running queries.
42
+ * @param streamId - The ID of the stream to get the body of.
43
+ * @returns The body of the stream and the status of the stream.
44
+ * @example
45
+ * ```ts
46
+ * const streaming = new PersistentTextStreaming(api);
47
+ * const { text, status } = await streaming.getStreamBody(ctx, streamId);
48
+ * ```
49
+ */
50
+ getStreamBody(ctx: RunQueryCtx, streamId: StreamId): Promise<StreamBody>;
51
+ /**
52
+ * Inside an HTTP action, this will stream data back to the client while
53
+ * also persisting the final stream in the database.
54
+ *
55
+ * @param ctx - A convex context capable of running actions.
56
+ * @param request - The HTTP request object.
57
+ * @param streamId - The ID of the stream.
58
+ * @param streamWriter - A function that generates chunks and writes them
59
+ * to the stream with the given `StreamWriter`.
60
+ * @returns A promise that resolves to an HTTP response. You may need to adjust
61
+ * the headers of this response for CORS, etc.
62
+ * @example
63
+ * ```ts
64
+ * const streaming = new PersistentTextStreaming(api);
65
+ * const streamId = await streaming.createStream(ctx);
66
+ * const response = await streaming.stream(ctx, request, streamId, async (ctx, req, id, append) => {
67
+ * await append("Hello ");
68
+ * await append("World!");
69
+ * });
70
+ * ```
71
+ */
72
+ stream<A extends GenericActionCtx<GenericDataModel>>(ctx: A, request: Request, streamId: StreamId, streamWriter: StreamWriter<A>): Promise<Response>;
73
+ private addChunk;
74
+ private setStreamStatus;
75
+ }
76
+ type RunQueryCtx = {
77
+ runQuery: GenericQueryCtx<GenericDataModel>["runQuery"];
78
+ };
79
+ type RunMutationCtx = {
80
+ runMutation: GenericMutationCtx<GenericDataModel>["runMutation"];
81
+ };
82
+ export type OpaqueIds<T> = T extends GenericId<infer _T> | string ? string : T extends (infer U)[] ? OpaqueIds<U>[] : T extends ArrayBuffer ? ArrayBuffer : T extends object ? {
83
+ [K in keyof T]: OpaqueIds<T[K]>;
84
+ } : T;
85
+ export type UseApi<API> = Expand<{
86
+ [mod in keyof API]: API[mod] extends FunctionReference<infer FType, "public", infer FArgs, infer FReturnType, infer FComponentPath> ? FunctionReference<FType, "internal", OpaqueIds<FArgs>, OpaqueIds<FReturnType>, FComponentPath> : UseApi<API[mod]>;
87
+ }>;
88
+ export {};
89
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,MAAM,EACN,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,EAChB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,SAAS,EAAK,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,GAAG,EAAE,MAAM,6BAA6B,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnD,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAAE,YAAY,EAAE,IAAI,CAAA;CAAE,CAAC;AACvD,eAAO,MAAM,iBAAiB,qDAAa,CAAC;AAC5C,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,YAAY,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAC5D,MAAM,MAAM,YAAY,CAAC,CAAC,SAAS,gBAAgB,CAAC,gBAAgB,CAAC,IAAI,CACvE,GAAG,EAAE,CAAC,EACN,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,aAAa,KACzB,OAAO,CAAC,IAAI,CAAC,CAAC;AAQnB,qBAAa,uBAAuB;IAEzB,SAAS,EAAE,MAAM,CAAC,OAAO,GAAG,CAAC;IAC7B,OAAO,CAAC;gBADR,SAAS,EAAE,MAAM,CAAC,OAAO,GAAG,CAAC,EAC7B,OAAO,CAAC,oBAAQ;IAGzB;;;;;;;;;;;;;;;;OAgBG;IAEG,YAAY,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,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,SAAS,CAAC,WAAW,CAAC,EACtB,cAAc,CACf,GACD,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;CACrB,CAAC,CAAC"}
@@ -0,0 +1,133 @@
1
+ import { v } from "convex/values";
2
+ export const StreamIdValidator = v.string();
3
+ // TODO -- make more flexible. # of bytes, etc?
4
+ const hasDelimeter = (text) => {
5
+ return text.includes(".") || text.includes("!") || text.includes("?");
6
+ };
7
+ // TODO -- some sort of wrapper with easy ergonomics for working with LLMs?
8
+ export class PersistentTextStreaming {
9
+ component;
10
+ options;
11
+ constructor(component, options) {
12
+ this.component = component;
13
+ this.options = options;
14
+ }
15
+ /**
16
+ * Create a new stream. This will return a stream ID that can be used
17
+ * in an HTTP action to stream data back out to the client while also
18
+ * permanently persisting the final stream in the database.
19
+ *
20
+ * @param ctx - A convex context capable of running mutations.
21
+ * @returns The ID of the new stream.
22
+ * @example
23
+ * ```ts
24
+ * const streaming = new PersistentTextStreaming(api);
25
+ * const streamId = await streaming.createStream(ctx);
26
+ * await streaming.stream(ctx, request, streamId, async (ctx, req, id, append) => {
27
+ * await append("Hello ");
28
+ * await append("World!");
29
+ * });
30
+ * ```
31
+ */
32
+ async createStream(ctx) {
33
+ const id = await ctx.runMutation(this.component.lib.createStream);
34
+ return id;
35
+ }
36
+ /**
37
+ * Get the body of a stream. This will return the full text of the stream
38
+ * and the status of the stream.
39
+ *
40
+ * @param ctx - A convex context capable of running queries.
41
+ * @param streamId - The ID of the stream to get the body of.
42
+ * @returns The body of the stream and the status of the stream.
43
+ * @example
44
+ * ```ts
45
+ * const streaming = new PersistentTextStreaming(api);
46
+ * const { text, status } = await streaming.getStreamBody(ctx, streamId);
47
+ * ```
48
+ */
49
+ async getStreamBody(ctx, streamId) {
50
+ const { text, status } = await ctx.runQuery(this.component.lib.getStreamText, { streamId });
51
+ return { text, status: status };
52
+ }
53
+ /**
54
+ * Inside an HTTP action, this will stream data back to the client while
55
+ * also persisting the final stream in the database.
56
+ *
57
+ * @param ctx - A convex context capable of running actions.
58
+ * @param request - The HTTP request object.
59
+ * @param streamId - The ID of the stream.
60
+ * @param streamWriter - A function that generates chunks and writes them
61
+ * to the stream with the given `StreamWriter`.
62
+ * @returns A promise that resolves to an HTTP response. You may need to adjust
63
+ * the headers of this response for CORS, etc.
64
+ * @example
65
+ * ```ts
66
+ * const streaming = new PersistentTextStreaming(api);
67
+ * const streamId = await streaming.createStream(ctx);
68
+ * const response = await streaming.stream(ctx, request, streamId, async (ctx, req, id, append) => {
69
+ * await append("Hello ");
70
+ * await append("World!");
71
+ * });
72
+ * ```
73
+ */
74
+ async stream(ctx, request, streamId, streamWriter) {
75
+ const streamState = await ctx.runQuery(this.component.lib.getStreamStatus, {
76
+ streamId,
77
+ });
78
+ if (streamState !== "pending") {
79
+ console.log("Stream was already started");
80
+ return new Response("", {
81
+ status: 205,
82
+ });
83
+ }
84
+ // Create a TransformStream to handle streaming data
85
+ const { readable, writable } = new TransformStream();
86
+ const writer = writable.getWriter();
87
+ const textEncoder = new TextEncoder();
88
+ let pending = "";
89
+ const doStream = async () => {
90
+ const chunkAppender = async (text) => {
91
+ // write to this handler's response stream on every update
92
+ await writer.write(textEncoder.encode(text));
93
+ pending += text;
94
+ // write to the database periodically, like at the end of sentences
95
+ if (hasDelimeter(text)) {
96
+ await this.addChunk(ctx, streamId, pending, false);
97
+ pending = "";
98
+ }
99
+ };
100
+ try {
101
+ await streamWriter(ctx, request, streamId, chunkAppender);
102
+ }
103
+ catch (e) {
104
+ await this.setStreamStatus(ctx, streamId, "error");
105
+ await writer.close();
106
+ throw e;
107
+ }
108
+ // Success? Flush any last updates
109
+ await this.addChunk(ctx, streamId, pending, true);
110
+ await writer.close();
111
+ };
112
+ // Kick off the streaming, but don't await it.
113
+ void doStream();
114
+ // Send the readable back to the browser
115
+ return new Response(readable);
116
+ }
117
+ // Internal helper -- add a chunk to the stream.
118
+ async addChunk(ctx, streamId, text, final) {
119
+ await ctx.runMutation(this.component.lib.addChunk, {
120
+ streamId,
121
+ text,
122
+ final,
123
+ });
124
+ }
125
+ // Internal helper -- set the status of a stream.
126
+ async setStreamStatus(ctx, streamId, status) {
127
+ await ctx.runMutation(this.component.lib.setStreamStatus, {
128
+ streamId,
129
+ status,
130
+ });
131
+ }
132
+ }
133
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAAa,CAAC,EAAE,MAAM,eAAe,CAAC;AAK7C,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;AAc5C,+CAA+C;AAC/C,MAAM,YAAY,GAAG,CAAC,IAAY,EAAE,EAAE;IACpC,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AACxE,CAAC,CAAC;AAEF,2EAA2E;AAC3E,MAAM,OAAO,uBAAuB;IAEzB;IACA;IAFT,YACS,SAA6B,EAC7B,OAAgB;QADhB,cAAS,GAAT,SAAS,CAAoB;QAC7B,YAAO,GAAP,OAAO,CAAS;IACtB,CAAC;IAEJ;;;;;;;;;;;;;;;;OAgBG;IAEH,KAAK,CAAC,YAAY,CAAC,GAAmB;QACpC,MAAM,EAAE,GAAG,MAAM,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QAClE,OAAO,EAAc,CAAC;IACxB,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,KAAK,CAAC,aAAa,CACjB,GAAgB,EAChB,QAAkB;QAElB,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,CAAC,QAAQ,CACzC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,aAAa,EAChC,EAAE,QAAQ,EAAE,CACb,CAAC;QACF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,aAAa,CAAC,CAAC;aAC3D;YAAC,OAAO,CAAC,EAAE;gBACV,MAAM,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;gBACnD,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;gBACrB,MAAM,CAAC,CAAC;aACT;YAED,kCAAkC;YAClC,MAAM,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;YAElD,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QACvB,CAAC,CAAC;QAEF,8CAA8C;QAC9C,KAAK,QAAQ,EAAE,CAAC;QAEhB,wCAAwC;QACxC,OAAO,IAAI,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAChC,CAAC;IAED,gDAAgD;IACxC,KAAK,CAAC,QAAQ,CACpB,GAAmB,EACnB,QAAkB,EAClB,IAAY,EACZ,KAAc;QAEd,MAAM,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,EAAE;YACjD,QAAQ;YACR,IAAI;YACJ,KAAK;SACN,CAAC,CAAC;IACL,CAAC;IAED,iDAAiD;IACzC,KAAK,CAAC,eAAe,CAC3B,GAAmB,EACnB,QAAkB,EAClB,MAAoB;QAEpB,MAAM,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,eAAe,EAAE;YACxD,QAAQ;YACR,MAAM;SACP,CAAC,CAAC;IACL,CAAC;CACF"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * A utility for referencing Convex functions in your app's API.
3
+ *
4
+ * Usage:
5
+ * ```js
6
+ * const myFunctionReference = api.myModule.myFunction;
7
+ * ```
8
+ */
9
+ export const api: import("convex/server").AnyApi;
10
+ export const internal: import("convex/server").AnyApi;
11
+ export const components: {
12
+ [x: string]: import("../../../node_modules/convex/dist/esm-types/server/components").AnyComponentReference;
13
+ };
14
+ //# sourceMappingURL=api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../../../src/component/_generated/api.js"],"names":[],"mappings":"AAYA;;;;;;;GAOG;AACH,iDAA0B;AAC1B,sDAA+B;AAC/B;;EAA8C"}
@@ -0,0 +1,22 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `api` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+ import { anyApi, componentsGeneric } from "convex/server";
11
+ /**
12
+ * A utility for referencing Convex functions in your app's API.
13
+ *
14
+ * Usage:
15
+ * ```js
16
+ * const myFunctionReference = api.myModule.myFunction;
17
+ * ```
18
+ */
19
+ export const api = anyApi;
20
+ export const internal = anyApi;
21
+ export const components = componentsGeneric();
22
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../../../../src/component/_generated/api.js"],"names":[],"mappings":"AAAA,oBAAoB;AACpB;;;;;;;GAOG;AAEH,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAE1D;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,GAAG,GAAG,MAAM,CAAC;AAC1B,MAAM,CAAC,MAAM,QAAQ,GAAG,MAAM,CAAC;AAC/B,MAAM,CAAC,MAAM,UAAU,GAAG,iBAAiB,EAAE,CAAC"}