@mastra/astra 0.11.4 → 0.11.7-alpha.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.
@@ -1,324 +0,0 @@
1
- import type { Db } from '@datastax/astra-db-ts';
2
- import { DataAPIClient, UUID } from '@datastax/astra-db-ts';
3
- import { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';
4
- import { MastraVector } from '@mastra/core/vector';
5
- import type {
6
- QueryResult,
7
- IndexStats,
8
- CreateIndexParams,
9
- UpsertVectorParams,
10
- QueryVectorParams,
11
- DescribeIndexParams,
12
- DeleteIndexParams,
13
- DeleteVectorParams,
14
- UpdateVectorParams,
15
- } from '@mastra/core/vector';
16
- import type { AstraVectorFilter } from './filter';
17
- import { AstraFilterTranslator } from './filter';
18
-
19
- // Mastra and Astra DB agree on cosine and euclidean, but Astra DB uses dot_product instead of dotproduct.
20
- const metricMap = {
21
- cosine: 'cosine',
22
- euclidean: 'euclidean',
23
- dotproduct: 'dot_product',
24
- } as const;
25
-
26
- export interface AstraDbOptions {
27
- token: string;
28
- endpoint: string;
29
- keyspace?: string;
30
- }
31
-
32
- type AstraQueryVectorParams = QueryVectorParams<AstraVectorFilter>;
33
-
34
- export class AstraVector extends MastraVector<AstraVectorFilter> {
35
- readonly #db: Db;
36
-
37
- constructor({ token, endpoint, keyspace }: AstraDbOptions) {
38
- super();
39
- const client = new DataAPIClient(token);
40
- this.#db = client.db(endpoint, { keyspace });
41
- }
42
-
43
- /**
44
- * Creates a new collection with the specified configuration.
45
- *
46
- * @param {string} indexName - The name of the collection to create.
47
- * @param {number} dimension - The dimension of the vectors to be stored in the collection.
48
- * @param {'cosine' | 'euclidean' | 'dotproduct'} [metric=cosine] - The metric to use to sort vectors in the collection.
49
- * @returns {Promise<void>} A promise that resolves when the collection is created.
50
- */
51
- async createIndex({ indexName, dimension, metric = 'cosine' }: CreateIndexParams): Promise<void> {
52
- if (!Number.isInteger(dimension) || dimension <= 0) {
53
- throw new MastraError({
54
- id: 'ASTRA_VECTOR_CREATE_INDEX_INVALID_DIMENSION',
55
- text: 'Dimension must be a positive integer',
56
- domain: ErrorDomain.MASTRA_VECTOR,
57
- category: ErrorCategory.USER,
58
- });
59
- }
60
- try {
61
- await this.#db.createCollection(indexName, {
62
- vector: {
63
- dimension,
64
- metric: metricMap[metric],
65
- },
66
- checkExists: false,
67
- });
68
- } catch (error: any) {
69
- new MastraError(
70
- {
71
- id: 'ASTRA_VECTOR_CREATE_INDEX_DB_ERROR',
72
- domain: ErrorDomain.MASTRA_VECTOR,
73
- category: ErrorCategory.THIRD_PARTY,
74
- details: { indexName },
75
- },
76
- error,
77
- );
78
- }
79
- }
80
-
81
- /**
82
- * Inserts or updates vectors in the specified collection.
83
- *
84
- * @param {string} indexName - The name of the collection to upsert into.
85
- * @param {number[][]} vectors - An array of vectors to upsert.
86
- * @param {Record<string, any>[]} [metadata] - An optional array of metadata objects corresponding to each vector.
87
- * @param {string[]} [ids] - An optional array of IDs corresponding to each vector. If not provided, new IDs will be generated.
88
- * @returns {Promise<string[]>} A promise that resolves to an array of IDs of the upserted vectors.
89
- */
90
- async upsert({ indexName, vectors, metadata, ids }: UpsertVectorParams): Promise<string[]> {
91
- const collection = this.#db.collection(indexName);
92
-
93
- // Generate IDs if not provided
94
- const vectorIds = ids || vectors.map(() => UUID.v7().toString());
95
-
96
- const records = vectors.map((vector, i) => ({
97
- id: vectorIds[i],
98
- $vector: vector,
99
- metadata: metadata?.[i] || {},
100
- }));
101
-
102
- try {
103
- await collection.insertMany(records);
104
- } catch (error: any) {
105
- throw new MastraError(
106
- {
107
- id: 'ASTRA_VECTOR_UPSERT_DB_ERROR',
108
- domain: ErrorDomain.MASTRA_VECTOR,
109
- category: ErrorCategory.THIRD_PARTY,
110
- details: { indexName },
111
- },
112
- error,
113
- );
114
- }
115
- return vectorIds;
116
- }
117
-
118
- transformFilter(filter?: AstraVectorFilter) {
119
- const translator = new AstraFilterTranslator();
120
- return translator.translate(filter);
121
- }
122
-
123
- /**
124
- * Queries the specified collection using a vector and optional filter.
125
- *
126
- * @param {string} indexName - The name of the collection to query.
127
- * @param {number[]} queryVector - The vector to query with.
128
- * @param {number} [topK] - The maximum number of results to return.
129
- * @param {Record<string, any>} [filter] - An optional filter to apply to the query. For more on filters in Astra DB, see the filtering reference: https://docs.datastax.com/en/astra-db-serverless/api-reference/documents.html#operators
130
- * @param {boolean} [includeVectors=false] - Whether to include the vectors in the response.
131
- * @returns {Promise<QueryResult[]>} A promise that resolves to an array of query results.
132
- */
133
- async query({
134
- indexName,
135
- queryVector,
136
- topK = 10,
137
- filter,
138
- includeVector = false,
139
- }: AstraQueryVectorParams): Promise<QueryResult[]> {
140
- const collection = this.#db.collection(indexName);
141
-
142
- const translatedFilter = this.transformFilter(filter);
143
-
144
- try {
145
- const cursor = collection.find(translatedFilter ?? {}, {
146
- sort: { $vector: queryVector },
147
- limit: topK,
148
- includeSimilarity: true,
149
- projection: {
150
- $vector: includeVector ? true : false,
151
- },
152
- });
153
-
154
- const results = await cursor.toArray();
155
-
156
- return results.map(result => ({
157
- id: result.id,
158
- score: result.$similarity,
159
- metadata: result.metadata,
160
- ...(includeVector && { vector: result.$vector }),
161
- }));
162
- } catch (error: any) {
163
- throw new MastraError(
164
- {
165
- id: 'ASTRA_VECTOR_QUERY_DB_ERROR',
166
- domain: ErrorDomain.MASTRA_VECTOR,
167
- category: ErrorCategory.THIRD_PARTY,
168
- details: { indexName },
169
- },
170
- error,
171
- );
172
- }
173
- }
174
-
175
- /**
176
- * Lists all collections in the database.
177
- *
178
- * @returns {Promise<string[]>} A promise that resolves to an array of collection names.
179
- */
180
- async listIndexes(): Promise<string[]> {
181
- try {
182
- return await this.#db.listCollections({ nameOnly: true });
183
- } catch (error: any) {
184
- throw new MastraError(
185
- {
186
- id: 'ASTRA_VECTOR_LIST_INDEXES_DB_ERROR',
187
- domain: ErrorDomain.MASTRA_VECTOR,
188
- category: ErrorCategory.THIRD_PARTY,
189
- },
190
- error,
191
- );
192
- }
193
- }
194
-
195
- /**
196
- * Retrieves statistics about a vector index.
197
- *
198
- * @param {string} indexName - The name of the index to describe
199
- * @returns A promise that resolves to the index statistics including dimension, count and metric
200
- */
201
- async describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats> {
202
- const collection = this.#db.collection(indexName);
203
- try {
204
- const optionsPromise = collection.options();
205
- const countPromise = collection.countDocuments({}, 100);
206
- const [options, count] = await Promise.all([optionsPromise, countPromise]);
207
-
208
- const keys = Object.keys(metricMap) as (keyof typeof metricMap)[];
209
- const metric = keys.find(key => metricMap[key] === options.vector?.metric);
210
- return {
211
- dimension: options.vector?.dimension!,
212
- metric,
213
- count: count,
214
- };
215
- } catch (error: any) {
216
- if (error instanceof MastraError) throw error;
217
- throw new MastraError(
218
- {
219
- id: 'ASTRA_VECTOR_DESCRIBE_INDEX_DB_ERROR',
220
- domain: ErrorDomain.MASTRA_VECTOR,
221
- category: ErrorCategory.THIRD_PARTY,
222
- details: { indexName },
223
- },
224
- error,
225
- );
226
- }
227
- }
228
-
229
- /**
230
- * Deletes the specified collection.
231
- *
232
- * @param {string} indexName - The name of the collection to delete.
233
- * @returns {Promise<void>} A promise that resolves when the collection is deleted.
234
- */
235
- async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {
236
- const collection = this.#db.collection(indexName);
237
- try {
238
- await collection.drop();
239
- } catch (error: any) {
240
- throw new MastraError(
241
- {
242
- id: 'ASTRA_VECTOR_DELETE_INDEX_DB_ERROR',
243
- domain: ErrorDomain.MASTRA_VECTOR,
244
- category: ErrorCategory.THIRD_PARTY,
245
- details: { indexName },
246
- },
247
- error,
248
- );
249
- }
250
- }
251
-
252
- /**
253
- * Updates a vector by its ID with the provided vector and/or metadata.
254
- * @param indexName - The name of the index containing the vector.
255
- * @param id - The ID of the vector to update.
256
- * @param update - An object containing the vector and/or metadata to update.
257
- * @param update.vector - An optional array of numbers representing the new vector.
258
- * @param update.metadata - An optional record containing the new metadata.
259
- * @returns A promise that resolves when the update is complete.
260
- * @throws Will throw an error if no updates are provided or if the update operation fails.
261
- */
262
- async updateVector({ indexName, id, update }: UpdateVectorParams): Promise<void> {
263
- if (!update.vector && !update.metadata) {
264
- throw new MastraError({
265
- id: 'ASTRA_VECTOR_UPDATE_NO_PAYLOAD',
266
- text: 'No updates provided for vector',
267
- domain: ErrorDomain.MASTRA_VECTOR,
268
- category: ErrorCategory.USER,
269
- details: { indexName, id },
270
- });
271
- }
272
-
273
- try {
274
- const collection = this.#db.collection(indexName);
275
- const updateDoc: Record<string, any> = {};
276
-
277
- if (update.vector) {
278
- updateDoc.$vector = update.vector;
279
- }
280
-
281
- if (update.metadata) {
282
- updateDoc.metadata = update.metadata;
283
- }
284
-
285
- await collection.findOneAndUpdate({ id }, { $set: updateDoc });
286
- } catch (error: any) {
287
- if (error instanceof MastraError) throw error;
288
- throw new MastraError(
289
- {
290
- id: 'ASTRA_VECTOR_UPDATE_FAILED_UNHANDLED',
291
- domain: ErrorDomain.MASTRA_VECTOR,
292
- category: ErrorCategory.THIRD_PARTY,
293
- details: { indexName, id },
294
- },
295
- error,
296
- );
297
- }
298
- }
299
-
300
- /**
301
- * Deletes a vector by its ID.
302
- * @param indexName - The name of the index containing the vector.
303
- * @param id - The ID of the vector to delete.
304
- * @returns A promise that resolves when the deletion is complete.
305
- * @throws Will throw an error if the deletion operation fails.
306
- */
307
- async deleteVector({ indexName, id }: DeleteVectorParams): Promise<void> {
308
- try {
309
- const collection = this.#db.collection(indexName);
310
- await collection.deleteOne({ id });
311
- } catch (error: any) {
312
- if (error instanceof MastraError) throw error;
313
- throw new MastraError(
314
- {
315
- id: 'ASTRA_VECTOR_DELETE_FAILED',
316
- domain: ErrorDomain.MASTRA_VECTOR,
317
- category: ErrorCategory.THIRD_PARTY,
318
- details: { indexName, id },
319
- },
320
- error,
321
- );
322
- }
323
- }
324
- }
@@ -1,91 +0,0 @@
1
- /**
2
- * Vector store specific prompt that details supported operators and examples.
3
- * This prompt helps users construct valid filters for Astra Vector.
4
- */
5
- export const ASTRA_PROMPT = `When querying Astra, you can ONLY use the operators listed below. Any other operators will be rejected.
6
- Important: Don't explain how to construct the filter - use the specified operators and fields to search the content and return relevant results.
7
- If a user tries to give an explicit operator that is not supported, reject the filter entirely and let them know that the operator is not supported.
8
-
9
- Basic Comparison Operators:
10
- - $eq: Exact match (default when using field: value)
11
- Example: { "category": "electronics" }
12
- - $ne: Not equal
13
- Example: { "category": { "$ne": "electronics" } }
14
- - $gt: Greater than
15
- Example: { "price": { "$gt": 100 } }
16
- - $gte: Greater than or equal
17
- Example: { "price": { "$gte": 100 } }
18
- - $lt: Less than
19
- Example: { "price": { "$lt": 100 } }
20
- - $lte: Less than or equal
21
- Example: { "price": { "$lte": 100 } }
22
-
23
- Array Operators:
24
- - $in: Match any value in array
25
- Example: { "category": { "$in": ["electronics", "books"] } }
26
- - $nin: Does not match any value in array
27
- Example: { "category": { "$nin": ["electronics", "books"] } }
28
- - $all: Match all values in array
29
- Example: { "tags": { "$all": ["premium", "sale"] } }
30
-
31
- Logical Operators:
32
- - $and: Logical AND (can be implicit or explicit)
33
- Implicit Example: { "price": { "$gt": 100 }, "category": "electronics" }
34
- Explicit Example: { "$and": [{ "price": { "$gt": 100 } }, { "category": "electronics" }] }
35
- - $or: Logical OR
36
- Example: { "$or": [{ "price": { "$lt": 50 } }, { "category": "books" }] }
37
- - $not: Logical NOT
38
- Example: { "$not": { "category": "electronics" } }
39
-
40
- Element Operators:
41
- - $exists: Check if field exists
42
- Example: { "rating": { "$exists": true } }
43
-
44
- Special Operators:
45
- - $size: Array length check
46
- Example: { "tags": { "$size": 2 } }
47
-
48
- Restrictions:
49
- - Regex patterns are not supported
50
- - Only $and, $or, and $not logical operators are supported
51
- - Nested fields are supported using dot notation
52
- - Multiple conditions on the same field are supported with both implicit and explicit $and
53
- - Empty arrays in $in/$nin will return no results
54
- - A non-empty array is required for $all operator
55
- - Only logical operators ($and, $or, $not) can be used at the top level
56
- - All other operators must be used within a field condition
57
- Valid: { "field": { "$gt": 100 } }
58
- Valid: { "$and": [...] }
59
- Invalid: { "$gt": 100 }
60
- - Logical operators must contain field conditions, not direct operators
61
- Valid: { "$and": [{ "field": { "$gt": 100 } }] }
62
- Invalid: { "$and": [{ "$gt": 100 }] }
63
- - $not operator:
64
- - Must be an object
65
- - Cannot be empty
66
- - Can be used at field level or top level
67
- - Valid: { "$not": { "field": "value" } }
68
- - Valid: { "field": { "$not": { "$eq": "value" } } }
69
- - Other logical operators ($and, $or):
70
- - Can only be used at top level or nested within other logical operators
71
- - Can not be used on a field level, or be nested inside a field
72
- - Can not be used inside an operator
73
- - Valid: { "$and": [{ "field": { "$gt": 100 } }] }
74
- - Valid: { "$or": [{ "$and": [{ "field": { "$gt": 100 } }] }] }
75
- - Invalid: { "field": { "$and": [{ "$gt": 100 }] } }
76
- - Invalid: { "field": { "$or": [{ "$gt": 100 }] } }
77
- - Invalid: { "field": { "$gt": { "$and": [{...}] } } }
78
-
79
- Example Complex Query:
80
- {
81
- "$and": [
82
- { "category": { "$in": ["electronics", "computers"] } },
83
- { "price": { "$gte": 100, "$lte": 1000 } },
84
- { "tags": { "$all": ["premium"] } },
85
- { "rating": { "$exists": true, "$gt": 4 } },
86
- { "$or": [
87
- { "stock": { "$gt": 0 } },
88
- { "preorder": true }
89
- ]}
90
- ]
91
- }`;
@@ -1,9 +0,0 @@
1
- {
2
- "extends": ["./tsconfig.json", "../../tsconfig.build.json"],
3
- "compilerOptions": {
4
- "outDir": "./dist",
5
- "rootDir": "./src"
6
- },
7
- "include": ["src/**/*"],
8
- "exclude": ["node_modules", "**/*.test.ts", "src/**/*.mock.ts"]
9
- }
package/tsconfig.json DELETED
@@ -1,5 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.node.json",
3
- "include": ["src/**/*", "tsup.config.ts"],
4
- "exclude": ["node_modules", "**/*.test.ts"]
5
- }
package/tsup.config.ts DELETED
@@ -1,17 +0,0 @@
1
- import { generateTypes } from '@internal/types-builder';
2
- import { defineConfig } from 'tsup';
3
-
4
- export default defineConfig({
5
- entry: ['src/index.ts'],
6
- format: ['esm', 'cjs'],
7
- clean: true,
8
- dts: false,
9
- splitting: true,
10
- treeshake: {
11
- preset: 'smallest',
12
- },
13
- sourcemap: true,
14
- onSuccess: async () => {
15
- await generateTypes(process.cwd());
16
- },
17
- });
package/vitest.config.ts DELETED
@@ -1,11 +0,0 @@
1
- import { defineConfig } from 'vitest/config';
2
-
3
- export default defineConfig({
4
- test: {
5
- environment: 'node',
6
- include: ['src/**/*.test.ts'],
7
- coverage: {
8
- reporter: ['text', 'json', 'html'],
9
- },
10
- },
11
- });