@mastra/chroma 0.1.0-alpha.28

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.
@@ -0,0 +1,153 @@
1
+ import { Filter } from '@mastra/core/filter';
2
+ import { MastraVector, QueryResult, IndexStats } from '@mastra/core/vector';
3
+ import { ChromaClient } from 'chromadb';
4
+
5
+ import { ChromaFilterTranslator } from './filter';
6
+
7
+ export class ChromaVector extends MastraVector {
8
+ private client: ChromaClient;
9
+ private collections: Map<string, any>;
10
+
11
+ constructor({
12
+ path,
13
+ auth,
14
+ }: {
15
+ path: string;
16
+ auth?: {
17
+ provider: string;
18
+ credentials: string;
19
+ };
20
+ }) {
21
+ super();
22
+ this.client = new ChromaClient({
23
+ path,
24
+ auth,
25
+ });
26
+ this.collections = new Map();
27
+ }
28
+
29
+ private async getCollection(indexName: string, throwIfNotExists: boolean = true) {
30
+ try {
31
+ const collection = await this.client.getCollection({ name: indexName, embeddingFunction: undefined as any });
32
+ this.collections.set(indexName, collection);
33
+ } catch (error) {
34
+ if (throwIfNotExists) {
35
+ throw new Error(`Index ${indexName} does not exist`);
36
+ }
37
+ return null;
38
+ }
39
+ return this.collections.get(indexName);
40
+ }
41
+
42
+ private validateVectorDimensions(vectors: number[][], dimension: number): void {
43
+ for (let i = 0; i < vectors.length; i++) {
44
+ if (vectors?.[i]?.length !== dimension) {
45
+ throw new Error(
46
+ `Vector at index ${i} has invalid dimension ${vectors?.[i]?.length}. Expected ${dimension} dimensions.`,
47
+ );
48
+ }
49
+ }
50
+ }
51
+
52
+ async upsert(
53
+ indexName: string,
54
+ vectors: number[][],
55
+ metadata?: Record<string, any>[],
56
+ ids?: string[],
57
+ ): Promise<string[]> {
58
+ const collection = await this.getCollection(indexName);
59
+
60
+ // Get index stats to check dimension
61
+ const stats = await this.describeIndex(indexName);
62
+
63
+ // Validate vector dimensions
64
+ this.validateVectorDimensions(vectors, stats.dimension);
65
+
66
+ // Generate IDs if not provided
67
+ const generatedIds = ids || vectors.map(() => crypto.randomUUID());
68
+
69
+ // Ensure metadata exists for each vector
70
+ const normalizedMetadata = metadata || vectors.map(() => ({}));
71
+
72
+ await collection.upsert({
73
+ ids: generatedIds,
74
+ embeddings: vectors,
75
+ metadatas: normalizedMetadata,
76
+ });
77
+
78
+ return generatedIds;
79
+ }
80
+
81
+ async createIndex(
82
+ indexName: string,
83
+ dimension: number,
84
+ metric: 'cosine' | 'euclidean' | 'dotproduct' = 'cosine',
85
+ ): Promise<void> {
86
+ if (!Number.isInteger(dimension) || dimension <= 0) {
87
+ throw new Error('Dimension must be a positive integer');
88
+ }
89
+ await this.client.createCollection({
90
+ name: indexName,
91
+ metadata: {
92
+ dimension,
93
+ metric,
94
+ },
95
+ });
96
+ }
97
+
98
+ transformFilter(filter?: Filter) {
99
+ const chromaFilter = new ChromaFilterTranslator();
100
+ const translatedFilter = chromaFilter.translate(filter);
101
+ return translatedFilter;
102
+ }
103
+ async query(
104
+ indexName: string,
105
+ queryVector: number[],
106
+ topK: number = 10,
107
+ filter?: Filter,
108
+ includeVector: boolean = false,
109
+ ): Promise<QueryResult[]> {
110
+ const collection = await this.getCollection(indexName, true);
111
+
112
+ const defaultInclude = ['documents', 'metadatas', 'distances'];
113
+
114
+ const translatedFilter = this.transformFilter(filter);
115
+
116
+ const results = await collection.query({
117
+ queryEmbeddings: [queryVector],
118
+ nResults: topK,
119
+ where: translatedFilter,
120
+ include: includeVector ? [...defaultInclude, 'embeddings'] : defaultInclude,
121
+ });
122
+
123
+ // Transform ChromaDB results to QueryResult format
124
+ return (results.ids[0] || []).map((id: string, index: number) => ({
125
+ id,
126
+ score: results.distances?.[0]?.[index] || 0,
127
+ metadata: results.metadatas?.[0]?.[index] || {},
128
+ ...(includeVector && { vector: results.embeddings?.[0]?.[index] || [] }),
129
+ }));
130
+ }
131
+
132
+ async listIndexes(): Promise<string[]> {
133
+ const collections = await this.client.listCollections();
134
+ return collections.map(collection => collection);
135
+ }
136
+
137
+ async describeIndex(indexName: string): Promise<IndexStats> {
138
+ const collection = await this.getCollection(indexName);
139
+ const count = await collection.count();
140
+ const metadata = collection.metadata;
141
+
142
+ return {
143
+ dimension: metadata?.dimension || 0,
144
+ count,
145
+ metric: metadata?.metric as 'cosine' | 'euclidean' | 'dotproduct',
146
+ };
147
+ }
148
+
149
+ async deleteIndex(indexName: string): Promise<void> {
150
+ await this.client.deleteCollection({ name: indexName });
151
+ this.collections.delete(indexName);
152
+ }
153
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "moduleResolution": "bundler",
5
+ "outDir": "./dist",
6
+ "rootDir": "./src"
7
+ },
8
+ "include": ["src/**/*"],
9
+ "exclude": ["node_modules", "**/*.test.ts"]
10
+ }
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ environment: 'node',
6
+ include: ['src/**/*.test.ts'],
7
+ },
8
+ });