@convex-dev/rag 0.1.7

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 (113) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +371 -0
  3. package/dist/client/_generated/_ignore.d.ts +1 -0
  4. package/dist/client/_generated/_ignore.d.ts.map +1 -0
  5. package/dist/client/_generated/_ignore.js +3 -0
  6. package/dist/client/_generated/_ignore.js.map +1 -0
  7. package/dist/client/defaultChunker.d.ts +15 -0
  8. package/dist/client/defaultChunker.d.ts.map +1 -0
  9. package/dist/client/defaultChunker.js +148 -0
  10. package/dist/client/defaultChunker.js.map +1 -0
  11. package/dist/client/fileUtils.d.ts +24 -0
  12. package/dist/client/fileUtils.d.ts.map +1 -0
  13. package/dist/client/fileUtils.js +179 -0
  14. package/dist/client/fileUtils.js.map +1 -0
  15. package/dist/client/index.d.ts +442 -0
  16. package/dist/client/index.d.ts.map +1 -0
  17. package/dist/client/index.js +597 -0
  18. package/dist/client/index.js.map +1 -0
  19. package/dist/client/types.d.ts +29 -0
  20. package/dist/client/types.d.ts.map +1 -0
  21. package/dist/client/types.js +2 -0
  22. package/dist/client/types.js.map +1 -0
  23. package/dist/component/_generated/api.d.ts +439 -0
  24. package/dist/component/_generated/api.d.ts.map +1 -0
  25. package/dist/component/_generated/api.js +22 -0
  26. package/dist/component/_generated/api.js.map +1 -0
  27. package/dist/component/_generated/dataModel.d.ts +60 -0
  28. package/dist/component/_generated/server.d.ts +149 -0
  29. package/dist/component/_generated/server.d.ts.map +1 -0
  30. package/dist/component/_generated/server.js +74 -0
  31. package/dist/component/_generated/server.js.map +1 -0
  32. package/dist/component/chunks.d.ts +139 -0
  33. package/dist/component/chunks.d.ts.map +1 -0
  34. package/dist/component/chunks.js +413 -0
  35. package/dist/component/chunks.js.map +1 -0
  36. package/dist/component/convex.config.d.ts +3 -0
  37. package/dist/component/convex.config.d.ts.map +1 -0
  38. package/dist/component/convex.config.js +6 -0
  39. package/dist/component/convex.config.js.map +1 -0
  40. package/dist/component/embeddings/importance.d.ts +21 -0
  41. package/dist/component/embeddings/importance.d.ts.map +1 -0
  42. package/dist/component/embeddings/importance.js +67 -0
  43. package/dist/component/embeddings/importance.js.map +1 -0
  44. package/dist/component/embeddings/index.d.ts +23 -0
  45. package/dist/component/embeddings/index.d.ts.map +1 -0
  46. package/dist/component/embeddings/index.js +54 -0
  47. package/dist/component/embeddings/index.js.map +1 -0
  48. package/dist/component/embeddings/tables.d.ts +39 -0
  49. package/dist/component/embeddings/tables.d.ts.map +1 -0
  50. package/dist/component/embeddings/tables.js +53 -0
  51. package/dist/component/embeddings/tables.js.map +1 -0
  52. package/dist/component/entries.d.ts +167 -0
  53. package/dist/component/entries.d.ts.map +1 -0
  54. package/dist/component/entries.js +409 -0
  55. package/dist/component/entries.js.map +1 -0
  56. package/dist/component/filters.d.ts +46 -0
  57. package/dist/component/filters.d.ts.map +1 -0
  58. package/dist/component/filters.js +72 -0
  59. package/dist/component/filters.js.map +1 -0
  60. package/dist/component/namespaces.d.ts +131 -0
  61. package/dist/component/namespaces.d.ts.map +1 -0
  62. package/dist/component/namespaces.js +222 -0
  63. package/dist/component/namespaces.js.map +1 -0
  64. package/dist/component/schema.d.ts +1697 -0
  65. package/dist/component/schema.d.ts.map +1 -0
  66. package/dist/component/schema.js +88 -0
  67. package/dist/component/schema.js.map +1 -0
  68. package/dist/component/search.d.ts +20 -0
  69. package/dist/component/search.d.ts.map +1 -0
  70. package/dist/component/search.js +69 -0
  71. package/dist/component/search.js.map +1 -0
  72. package/dist/package.json +3 -0
  73. package/dist/react/index.d.ts +2 -0
  74. package/dist/react/index.d.ts.map +1 -0
  75. package/dist/react/index.js +6 -0
  76. package/dist/react/index.js.map +1 -0
  77. package/dist/shared.d.ts +479 -0
  78. package/dist/shared.d.ts.map +1 -0
  79. package/dist/shared.js +98 -0
  80. package/dist/shared.js.map +1 -0
  81. package/package.json +97 -0
  82. package/src/client/_generated/_ignore.ts +1 -0
  83. package/src/client/defaultChunker.test.ts +243 -0
  84. package/src/client/defaultChunker.ts +183 -0
  85. package/src/client/fileUtils.ts +179 -0
  86. package/src/client/index.test.ts +475 -0
  87. package/src/client/index.ts +1125 -0
  88. package/src/client/setup.test.ts +28 -0
  89. package/src/client/types.ts +69 -0
  90. package/src/component/_generated/api.d.ts +439 -0
  91. package/src/component/_generated/api.js +23 -0
  92. package/src/component/_generated/dataModel.d.ts +60 -0
  93. package/src/component/_generated/server.d.ts +149 -0
  94. package/src/component/_generated/server.js +90 -0
  95. package/src/component/chunks.test.ts +915 -0
  96. package/src/component/chunks.ts +555 -0
  97. package/src/component/convex.config.ts +7 -0
  98. package/src/component/embeddings/importance.test.ts +249 -0
  99. package/src/component/embeddings/importance.ts +75 -0
  100. package/src/component/embeddings/index.test.ts +482 -0
  101. package/src/component/embeddings/index.ts +99 -0
  102. package/src/component/embeddings/tables.ts +114 -0
  103. package/src/component/entries.test.ts +341 -0
  104. package/src/component/entries.ts +546 -0
  105. package/src/component/filters.ts +119 -0
  106. package/src/component/namespaces.ts +299 -0
  107. package/src/component/schema.ts +106 -0
  108. package/src/component/search.test.ts +445 -0
  109. package/src/component/search.ts +97 -0
  110. package/src/component/setup.test.ts +5 -0
  111. package/src/react/index.ts +7 -0
  112. package/src/shared.ts +247 -0
  113. package/src/vitest.config.ts +7 -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,371 @@
1
+ # Convex Agent RAG Component
2
+
3
+ [![npm version](https://badge.fury.io/js/@convex-dev%2Fmemory.svg)](https://badge.fury.io/js/@convex-dev%2Fmemory)
4
+
5
+ <!-- START: Include on https://convex.dev/components -->
6
+
7
+ A component for semantic search, usually used to look up context for LLMs.
8
+ Use with an Agent for Retrieval-Augmented Generation (RAG).
9
+
10
+ ## ✨ Key Features
11
+
12
+ - **Add Content**: Add or replace content with text chunks and embeddings.
13
+ - **Semantic Search**: Vector-based search using configurable embedding models
14
+ - **Namespaces**: Organize content into namespaces for per-user search.
15
+ - **Custom Filtering**: Filter content with custom indexed fields.
16
+ - **Importance Weighting**: Weight content by providing a 0 to 1 "importance".
17
+ - **Chunk Context**: Get surrounding chunks for better context.
18
+ - **Graceful Migrations**: Migrate content or whole namespaces without disruption.
19
+
20
+ Found a bug? Feature request? [File it here](https://github.com/get-convex/rag/issues).
21
+
22
+ ## Pre-requisite: Convex
23
+
24
+ You'll need an existing Convex project to use the component.
25
+ Convex is a hosted backend platform, including a database, serverless functions,
26
+ and a ton more you can learn about [here](https://docs.convex.dev/get-started).
27
+
28
+ Run `npm create convex` or follow any of the [quickstarts](https://docs.convex.dev/home) to set one up.
29
+
30
+ ## Installation
31
+
32
+ Install the component package:
33
+
34
+ ```ts
35
+ npm install @convex-dev/rag
36
+ ```
37
+
38
+ Create a `convex.config.ts` file in your app's `convex/` folder and install the component by calling `use`:
39
+
40
+ ```ts
41
+ // convex/convex.config.ts
42
+ import { defineApp } from "convex/server";
43
+ import rag from "@convex-dev/rag/convex.config";
44
+
45
+ const app = defineApp();
46
+ app.use(rag);
47
+
48
+ export default app;
49
+ ```
50
+
51
+ ## Basic Setup
52
+
53
+ ```ts
54
+ // convex/example.ts
55
+ import { components } from "./_generated/api";
56
+ import { RAG } from "@convex-dev/rag";
57
+ // Any AI SDK model that supports embeddings will work.
58
+ import { openai } from "@ai-sdk/openai";
59
+
60
+ const rag = new RAG<FilterTypes>(components.rag, {
61
+ filterNames: ["category", "contentType", "categoryAndType"],
62
+ textEmbeddingModel: openai.embedding("text-embedding-3-small"),
63
+ embeddingDimension: 1536,
64
+ });
65
+
66
+ // Optional: Add type safety to your filters.
67
+ type FilterTypes = {
68
+ category: string;
69
+ contentType: string;
70
+ categoryAndType: { category: string; contentType: string };
71
+ };
72
+ ```
73
+
74
+ ## Usage Examples
75
+
76
+ ### Add RAG Entries
77
+
78
+ Add content with text chunks.
79
+ It will embed the chunks automatically if you don't provide them.
80
+
81
+ ```ts
82
+ export const add = action({
83
+ args: { text: v.string() },
84
+ handler: async (ctx, { text }) => {
85
+ // Add the text to a namespace shared by all users.
86
+ await rag.add(ctx, {
87
+ namespace: "all-users",
88
+ chunks: text.split("\n\n"),
89
+ });
90
+ },
91
+ });
92
+ ```
93
+
94
+ ### Add Entries with filters from a URL
95
+
96
+ Here's a simple example fetching content from a URL to add.
97
+
98
+ It also adds filters to the entry, so you can search for it later by
99
+ category, contentType, or both.
100
+
101
+ ```ts
102
+ export const add = action({
103
+ args: { url: v.string(), category: v.string() },
104
+ handler: async (ctx, { url, category }) => {
105
+ const response = await fetch(url);
106
+ const content = await response.text();
107
+ const contentType = response.headers.get("content-type");
108
+
109
+ const { entryId } = await rag.add(ctx, {
110
+ namespace: "global", // namespace can be any string
111
+ key: url,
112
+ chunks: content.split("\n\n"),
113
+ filterValues: [
114
+ { name: "category", value: category },
115
+ { name: "contentType", value: contentType },
116
+ // To get an AND filter, use a filter with a more complex value.
117
+ { name: "categoryAndType", value: { category, contentType } },
118
+ ],
119
+ });
120
+
121
+ return { entryId };
122
+ },
123
+ });
124
+ ```
125
+
126
+ Note: The `textSplitter` here could be LangChain, Mastra, or otherwise.
127
+ See below for more details.
128
+
129
+ ### Add Entries Asynchronously using File Storage
130
+
131
+ For large files, you can upload them to file storage, then provide a chunker
132
+ action to split them into chunks.
133
+
134
+ In `convex/http.ts`:
135
+ ```ts
136
+ import { corsRouter } from "convex-helpers/server/cors";
137
+ import { httpRouter } from "convex/server";
138
+ import { internal } from "./_generated/api.js";
139
+ import { DataModel } from "./_generated/dataModel.js";
140
+ import { httpAction } from "./_generated/server.js";
141
+ import { rag } from "./example.js";
142
+
143
+ const cors = corsRouter(httpRouter());
144
+
145
+ cors.route({
146
+ path: "/upload",
147
+ method: "POST",
148
+ handler: httpAction(async (ctx, request) => {
149
+ const storageId = await ctx.storage.store(await request.blob());
150
+ await rag.addAsync(ctx, {
151
+ namespace: "all-files",
152
+ chunkerAction: internal.http.chunkerAction,
153
+ onComplete: internal.http.handleEntryComplete,
154
+ metadata: { storageId },
155
+ });
156
+ return new Response();
157
+ }),
158
+ });
159
+
160
+ export const chunkerAction = rag.defineChunkerAction(async (ctx, args) => {
161
+ const storageId = args.entry.metadata!.storageId;
162
+ const file = await ctx.storage.get(storageId);
163
+ const text = await new TextDecoder().decode(await file!.arrayBuffer());
164
+ return { chunks: text.split("\n\n") };
165
+ });
166
+
167
+ export const handleEntryComplete = rag.defineOnComplete<DataModel>(
168
+ async (ctx, { replacedEntry, entry, namespace, error }) => {
169
+ if (error) {
170
+ await rag.delete(ctx, { entryId: entry.entryId });
171
+ return;
172
+ }
173
+ // You can associate the entry with your own data here. This will commit
174
+ // in the same transaction as the entry becoming ready.
175
+ }
176
+ );
177
+
178
+ export default cors.http;
179
+ ```
180
+
181
+ You can upload files directly to a Convex action, httpAction, or upload url.
182
+ See the [docs](https://docs.convex.dev/file-storage/upload-files) for details.
183
+
184
+ ### Semantic Search
185
+
186
+ Search across content with vector similarity
187
+
188
+ - `text` is a string with the full content of the results, for convenience.
189
+ It is in order of the entries, with titles at each entry boundary, and
190
+ separators between non-sequential chunks. See below for more details.
191
+ - `results` is an array of matching chunks with scores and more metadata.
192
+ - `entries` is an array of the entries that matched the query.
193
+ Each result has a `entryId` referencing one of these source entries.
194
+
195
+ ```ts
196
+ export const search = action({
197
+ args: {
198
+ query: v.string(),
199
+ },
200
+ handler: async (ctx, args) => {
201
+
202
+ const { results, text, entries } = await rag.search(ctx, {
203
+ namespace: "global",
204
+ query: args.query,
205
+ limit: 10
206
+ vectorScoreThreshold: 0.5, // Only return results with a score >= 0.5
207
+ });
208
+
209
+ return { results, text, entries };
210
+ },
211
+ });
212
+ ```
213
+
214
+ ### Filtered Search
215
+
216
+ Search with metadata filters:
217
+
218
+ ```ts
219
+ export const searchByCategory = action({
220
+ args: {
221
+ query: v.string(),
222
+ category: v.string(),
223
+ },
224
+ handler: async (ctx, args) => {
225
+ const userId = await getUserId(ctx);
226
+ if (!userId) throw new Error("Unauthorized");
227
+
228
+ const results = await rag.search(ctx, {
229
+ namespace: userId,
230
+ query: args.query,
231
+ filters: [{ name: "category", value: args.category }],
232
+ limit: 10,
233
+ });
234
+
235
+ return results;
236
+ },
237
+ });
238
+ ```
239
+
240
+ ### Add surrounding chunks to results for context
241
+
242
+ Instead of getting just the single matching chunk, you can request
243
+ surrounding chunks so there's more context to the result.
244
+
245
+ Note: If there are results that have overlapping ranges, it will not return
246
+ duplicate chunks, but instead give priority to adding the "before" context
247
+ to each chunk.
248
+ For example if you requested 2 before and 1 after, and your results were for
249
+ the same entryId indexes 1, 4, and 7, the results would be:
250
+ ```ts
251
+ [
252
+ // Only one before chunk available, and leaves chunk2 for the next result.
253
+ { order: 1, content: [chunk0, chunk1], startOrder: 0, ... },
254
+ // 2 before chunks available, but leaves chunk5 for the next result.
255
+ { order: 4, content: [chunk2, chunk3, chunk4], startOrder: 2, ... },
256
+ // 2 before chunks available, and includes one after chunk.
257
+ { order: 7, content: [chunk5, chunk6, chunk7, chunk8], startOrder: 5, ... },
258
+ ]
259
+ ```
260
+
261
+ ```ts
262
+ export const searchWithContext = action({
263
+ args: {
264
+ query: v.string(),
265
+ userId: v.string(),
266
+ },
267
+ handler: async (ctx, args) => {
268
+ const { results, text, entries } = await rag.search(ctx, {
269
+ namespace: args.userId,
270
+ query: args.query,
271
+ chunkContext: { before: 2, after: 1 }, // Include 2 chunks before, 1 after
272
+ limit: 5,
273
+ });
274
+
275
+ return { results, text, entries };
276
+ },
277
+ });
278
+ ```
279
+
280
+ ### Formatting results
281
+
282
+ Formatting the results for use in a prompt depends a bit on the use case.
283
+ By default, the results will be sorted by score, not necessarily in the order
284
+ they appear in the original text. You may want to sort them by the order they
285
+ appear in the original text so they follow the flow of the original document.
286
+
287
+ For convenienct, the `text` field of the search results is a string formatted
288
+ with `...` separating non-sequential chunks, `---` separating entries, and
289
+ `# Title:` at each entry boundary (if titles are available).
290
+
291
+ ```ts
292
+ const { text } = await rag.search(ctx, { ... });
293
+ console.log(text);
294
+ ```
295
+
296
+ ```txt
297
+ # Title 1:
298
+ Chunk 1 contents
299
+ Chunk 2 contents
300
+ ...
301
+ Chunk 8 contents
302
+ Chunk 9 contents
303
+ ---
304
+ # Title 2:
305
+ Chunk 4 contents
306
+ Chunk 5 contents
307
+ ```
308
+
309
+ There is also a `text` field on each entry that is the full text of the entry,
310
+ similarly formatted with `...` separating non-sequential chunks, if you want
311
+ to format each entry differently.
312
+
313
+ For a fully custom format, you can use the `results` field and entries directly:
314
+
315
+ ```ts
316
+ const { results, text, entries } = await rag.search(ctx, {
317
+ namespace: args.userId,
318
+ query: args.query,
319
+ chunkContext: { before: 2, after: 1 }, // Include 2 chunks before, 1 after
320
+ limit: 5,
321
+ vectorScoreThreshold: 0.5, // Only return results with a score >= 0.5
322
+ });
323
+
324
+ // Get results in the order of the entries (highest score first)
325
+ const contexts = entries.map((e) => {
326
+ const ranges = results
327
+ .filter((r) => r.entryId === e.entryId)
328
+ .sort((a, b) => a.startOrder - b.startOrder);
329
+ let text = (e.title ?? "") + ":\n\n";
330
+ let previousEnd = 0;
331
+ for (const range of ranges) {
332
+ if (range.startOrder !== previousEnd) {
333
+ text += "\n...\n";
334
+ }
335
+ text += range.content.map((c) => c.text).join("\n");
336
+ previousEnd = range.startOrder + range.content.length;
337
+ }
338
+ return {
339
+ ...e,
340
+ entryId: e.entryId as EntryId,
341
+ filterValues: e.filterValues as EntryFilterValues<FitlerSchemas>[],
342
+ text,
343
+ };
344
+ }).map((e) => (e.title ? `# ${e.title}:\n${e.text}` : e.text));
345
+
346
+ await generateText({
347
+ model: openai.chat("gpt-4o-mini"),
348
+ prompt: "Use the following context:\n\n" + contexts.join("\n---\n") +
349
+ "\n\n---\n\n Based on the context, answer the question:\n\n" + args.query,
350
+ });
351
+ ```
352
+
353
+ ### Lifecycle Management
354
+
355
+ Delete an entry:
356
+
357
+ ```ts
358
+ export const delete = mutation({
359
+ args: { entryId: vEntry },
360
+ handler: async (ctx, args) => {
361
+ await rag.delete(ctx, {
362
+ entryId: args.entryId,
363
+ });
364
+ },
365
+ });
366
+ ```
367
+
368
+ See more example usage in [example.ts](./example/convex/example.ts).
369
+
370
+ Run the example with `npm i && npm run example`.
371
+ <!-- END: Include on https://convex.dev/components -->
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=_ignore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_ignore.d.ts","sourceRoot":"","sources":["../../../src/client/_generated/_ignore.ts"],"names":[],"mappings":""}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ // This is only here so convex-test can detect a _generated folder
3
+ //# sourceMappingURL=_ignore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_ignore.js","sourceRoot":"","sources":["../../../src/client/_generated/_ignore.ts"],"names":[],"mappings":";AAAA,kEAAkE"}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Chunk text for embedding.
3
+ *
4
+ * By default, it will chunk into paragraphs and target
5
+ * 200-2000 characters per chunk (only less than 1 line if the hard limit is reached).
6
+ */
7
+ export declare function defaultChunker(text: string, { minLines, minCharsSoftLimit, maxCharsSoftLimit, maxCharsHardLimit, delimiter, }?: {
8
+ minLines?: number;
9
+ minCharsSoftLimit?: number;
10
+ maxCharsSoftLimit?: number;
11
+ maxCharsHardLimit?: number;
12
+ delimiter?: string;
13
+ }): string[];
14
+ export default defaultChunker;
15
+ //# sourceMappingURL=defaultChunker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defaultChunker.d.ts","sourceRoot":"","sources":["../../src/client/defaultChunker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,EACZ,EACE,QAAY,EACZ,iBAAuB,EACvB,iBAAwB,EACxB,iBAAyB,EACzB,SAAkB,GACnB,GAAE;IACD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,CAAC;CACf,GACL,MAAM,EAAE,CA6FV;AAoED,eAAe,cAAc,CAAC"}