@mastra/chroma 0.0.0-storage-20250225005900 → 0.0.0-vnextWorkflows-20250417075051

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,9 +1,32 @@
1
- import { type Filter } from '@mastra/core/filter';
2
- import { MastraVector, type QueryResult, type IndexStats } from '@mastra/core/vector';
1
+ import { MastraVector } from '@mastra/core/vector';
2
+ import type {
3
+ QueryResult,
4
+ IndexStats,
5
+ CreateIndexParams,
6
+ UpsertVectorParams,
7
+ QueryVectorParams,
8
+ ParamsToArgs,
9
+ QueryVectorArgs,
10
+ UpsertVectorArgs,
11
+ } from '@mastra/core/vector';
12
+
13
+ import type { VectorFilter } from '@mastra/core/vector/filter';
3
14
  import { ChromaClient } from 'chromadb';
4
-
15
+ import type { UpdateRecordsParams, Collection } from 'chromadb';
5
16
  import { ChromaFilterTranslator } from './filter';
6
17
 
18
+ interface ChromaUpsertVectorParams extends UpsertVectorParams {
19
+ documents?: string[];
20
+ }
21
+
22
+ type ChromaUpsertArgs = [...UpsertVectorArgs, string[]?];
23
+
24
+ interface ChromaQueryVectorParams extends QueryVectorParams {
25
+ documentFilter?: VectorFilter;
26
+ }
27
+
28
+ type ChromaQueryArgs = [...QueryVectorArgs, VectorFilter?];
29
+
7
30
  export class ChromaVector extends MastraVector {
8
31
  private client: ChromaClient;
9
32
  private collections: Map<string, any>;
@@ -26,11 +49,11 @@ export class ChromaVector extends MastraVector {
26
49
  this.collections = new Map();
27
50
  }
28
51
 
29
- private async getCollection(indexName: string, throwIfNotExists: boolean = true) {
52
+ async getCollection(indexName: string, throwIfNotExists: boolean = true) {
30
53
  try {
31
54
  const collection = await this.client.getCollection({ name: indexName, embeddingFunction: undefined as any });
32
55
  this.collections.set(indexName, collection);
33
- } catch (error) {
56
+ } catch {
34
57
  if (throwIfNotExists) {
35
58
  throw new Error(`Index ${indexName} does not exist`);
36
59
  }
@@ -49,12 +72,11 @@ export class ChromaVector extends MastraVector {
49
72
  }
50
73
  }
51
74
 
52
- async upsert(
53
- indexName: string,
54
- vectors: number[][],
55
- metadata?: Record<string, any>[],
56
- ids?: string[],
57
- ): Promise<string[]> {
75
+ async upsert(...args: ParamsToArgs<ChromaUpsertVectorParams> | ChromaUpsertArgs): Promise<string[]> {
76
+ const params = this.normalizeArgs<ChromaUpsertVectorParams, ChromaUpsertArgs>('upsert', args, ['documents']);
77
+
78
+ const { indexName, vectors, metadata, ids, documents } = params;
79
+
58
80
  const collection = await this.getCollection(indexName);
59
81
 
60
82
  // Get index stats to check dimension
@@ -73,50 +95,60 @@ export class ChromaVector extends MastraVector {
73
95
  ids: generatedIds,
74
96
  embeddings: vectors,
75
97
  metadatas: normalizedMetadata,
98
+ documents: documents,
76
99
  });
77
100
 
78
101
  return generatedIds;
79
102
  }
80
103
 
81
- async createIndex(
82
- indexName: string,
83
- dimension: number,
84
- metric: 'cosine' | 'euclidean' | 'dotproduct' = 'cosine',
85
- ): Promise<void> {
104
+ private HnswSpaceMap = {
105
+ cosine: 'cosine',
106
+ euclidean: 'l2',
107
+ dotproduct: 'ip',
108
+ l2: 'euclidean',
109
+ ip: 'dotproduct',
110
+ };
111
+
112
+ async createIndex(...args: ParamsToArgs<CreateIndexParams>): Promise<void> {
113
+ const params = this.normalizeArgs<CreateIndexParams>('createIndex', args);
114
+
115
+ const { indexName, dimension, metric = 'cosine' } = params;
116
+
86
117
  if (!Number.isInteger(dimension) || dimension <= 0) {
87
118
  throw new Error('Dimension must be a positive integer');
88
119
  }
120
+ const hnswSpace = this.HnswSpaceMap[metric];
121
+ if (!['cosine', 'l2', 'ip'].includes(hnswSpace)) {
122
+ throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
123
+ }
89
124
  await this.client.createCollection({
90
125
  name: indexName,
91
126
  metadata: {
92
127
  dimension,
93
- metric,
128
+ 'hnsw:space': this.HnswSpaceMap[metric],
94
129
  },
95
130
  });
96
131
  }
97
132
 
98
- transformFilter(filter?: Filter) {
99
- const chromaFilter = new ChromaFilterTranslator();
100
- const translatedFilter = chromaFilter.translate(filter);
101
- return translatedFilter;
133
+ transformFilter(filter?: VectorFilter) {
134
+ const translator = new ChromaFilterTranslator();
135
+ return translator.translate(filter);
102
136
  }
103
- async query(
104
- indexName: string,
105
- queryVector: number[],
106
- topK: number = 10,
107
- filter?: Filter,
108
- includeVector: boolean = false,
109
- ): Promise<QueryResult[]> {
137
+ async query(...args: ParamsToArgs<ChromaQueryVectorParams> | ChromaQueryArgs): Promise<QueryResult[]> {
138
+ const params = this.normalizeArgs<ChromaQueryVectorParams, ChromaQueryArgs>('query', args, ['documentFilter']);
139
+
140
+ const { indexName, queryVector, topK = 10, filter, includeVector = false, documentFilter } = params;
141
+
110
142
  const collection = await this.getCollection(indexName, true);
111
143
 
112
144
  const defaultInclude = ['documents', 'metadatas', 'distances'];
113
145
 
114
146
  const translatedFilter = this.transformFilter(filter);
115
-
116
147
  const results = await collection.query({
117
148
  queryEmbeddings: [queryVector],
118
149
  nResults: topK,
119
150
  where: translatedFilter,
151
+ whereDocument: documentFilter,
120
152
  include: includeVector ? [...defaultInclude, 'embeddings'] : defaultInclude,
121
153
  });
122
154
 
@@ -125,6 +157,7 @@ export class ChromaVector extends MastraVector {
125
157
  id,
126
158
  score: results.distances?.[0]?.[index] || 0,
127
159
  metadata: results.metadatas?.[0]?.[index] || {},
160
+ document: results.documents?.[0]?.[index],
128
161
  ...(includeVector && { vector: results.embeddings?.[0]?.[index] || [] }),
129
162
  }));
130
163
  }
@@ -139,10 +172,12 @@ export class ChromaVector extends MastraVector {
139
172
  const count = await collection.count();
140
173
  const metadata = collection.metadata;
141
174
 
175
+ const hnswSpace = metadata?.['hnsw:space'] as 'cosine' | 'l2' | 'ip';
176
+
142
177
  return {
143
178
  dimension: metadata?.dimension || 0,
144
179
  count,
145
- metric: metadata?.metric as 'cosine' | 'euclidean' | 'dotproduct',
180
+ metric: this.HnswSpaceMap[hnswSpace] as 'cosine' | 'euclidean' | 'dotproduct',
146
181
  };
147
182
  }
148
183
 
@@ -150,4 +185,37 @@ export class ChromaVector extends MastraVector {
150
185
  await this.client.deleteCollection({ name: indexName });
151
186
  this.collections.delete(indexName);
152
187
  }
188
+
189
+ async updateIndexById(
190
+ indexName: string,
191
+ id: string,
192
+ update: { vector?: number[]; metadata?: Record<string, any> },
193
+ ): Promise<void> {
194
+ if (!update.vector && !update.metadata) {
195
+ throw new Error('No updates provided');
196
+ }
197
+
198
+ const collection: Collection = await this.getCollection(indexName, true);
199
+
200
+ const updateOptions: UpdateRecordsParams = { ids: [id] };
201
+
202
+ if (update?.vector) {
203
+ updateOptions.embeddings = [update.vector];
204
+ }
205
+
206
+ if (update?.metadata) {
207
+ updateOptions.metadatas = [update.metadata];
208
+ }
209
+
210
+ return await collection.update(updateOptions);
211
+ }
212
+
213
+ async deleteIndexById(indexName: string, id: string): Promise<void> {
214
+ try {
215
+ const collection: Collection = await this.getCollection(indexName, true);
216
+ await collection.delete({ ids: [id] });
217
+ } catch (error: any) {
218
+ throw new Error(`Failed to delete index by id: ${id} for index name: ${indexName}: ${error.message}`);
219
+ }
220
+ }
153
221
  }
@@ -1,19 +0,0 @@
1
-
2
- 
3
- > @mastra/chroma@0.1.5-alpha.0 build /Users/ward/projects/mastra/mastra/stores/chroma
4
- > tsup src/index.ts --format esm --experimental-dts --clean --treeshake
5
-
6
- CLI Building entry: src/index.ts
7
- CLI Using tsconfig: tsconfig.json
8
- CLI tsup v8.3.6
9
- TSC Build start
10
- TSC ⚡️ Build success in 1648ms
11
- DTS Build start
12
- CLI Target: es2022
13
- Analysis will use the bundled TypeScript version 5.7.3
14
- Writing package typings: /Users/ward/projects/mastra/mastra/stores/chroma/dist/_tsup-dts-rollup.d.ts
15
- DTS ⚡️ Build success in 1410ms
16
- CLI Cleaning output folder
17
- ESM Build start
18
- ESM dist/index.js 6.49 KB
19
- ESM ⚡️ Build success in 157ms
package/LICENSE DELETED
@@ -1,44 +0,0 @@
1
- Elastic License 2.0 (ELv2)
2
-
3
- **Acceptance**
4
- By using the software, you agree to all of the terms and conditions below.
5
-
6
- **Copyright License**
7
- The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below
8
-
9
- **Limitations**
10
- You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
11
-
12
- You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
13
-
14
- You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor’s trademarks is subject to applicable law.
15
-
16
- **Patents**
17
- The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
18
-
19
- **Notices**
20
- You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
21
-
22
- If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
23
-
24
- **No Other Rights**
25
- These terms do not imply any licenses other than those expressly granted in these terms.
26
-
27
- **Termination**
28
- If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
29
-
30
- **No Liability**
31
- As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.
32
-
33
- **Definitions**
34
- The _licensor_ is the entity offering these terms, and the _software_ is the software the licensor makes available under these terms, including any portion of it.
35
-
36
- _you_ refers to the individual or entity agreeing to these terms.
37
-
38
- _your company_ is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. _control_ means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
39
-
40
- _your licenses_ are all the licenses granted to you for the software under these terms.
41
-
42
- _use_ means anything you do with the software requiring one of your licenses.
43
-
44
- _trademark_ means trademarks, service marks, and similar rights.