@mastra/chroma 0.0.0-commonjs-20250227130920
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.
- package/.turbo/turbo-build.log +23 -0
- package/CHANGELOG.md +708 -0
- package/LICENSE +44 -0
- package/README.md +97 -0
- package/dist/_tsup-dts-rollup.d.cts +51 -0
- package/dist/_tsup-dts-rollup.d.ts +51 -0
- package/dist/index.cjs +209 -0
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +207 -0
- package/docker-compose.yaml +7 -0
- package/eslint.config.js +6 -0
- package/package.json +40 -0
- package/src/index.ts +1 -0
- package/src/vector/filter.test.ts +413 -0
- package/src/vector/filter.ts +115 -0
- package/src/vector/index.test.ts +1045 -0
- package/src/vector/index.ts +177 -0
- package/tsconfig.json +5 -0
- package/vitest.config.ts +8 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# @mastra/chroma
|
|
2
|
+
|
|
3
|
+
Vector store implementation for ChromaDB using the official chromadb client with added dimension validation, collection management, and document storage capabilities.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @mastra/chroma
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { ChromaVector } from '@mastra/chroma';
|
|
15
|
+
|
|
16
|
+
const vectorStore = new ChromaVector({
|
|
17
|
+
path: 'http://localhost:8000', // ChromaDB server URL
|
|
18
|
+
auth: { // Optional authentication
|
|
19
|
+
provider: 'token',
|
|
20
|
+
credentials: 'your-token'
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
// Create a new collection
|
|
25
|
+
await vectorStore.createIndex('my-collection', 1536, 'cosine');
|
|
26
|
+
|
|
27
|
+
// Add vectors with documents
|
|
28
|
+
const vectors = [[0.1, 0.2, ...], [0.3, 0.4, ...]];
|
|
29
|
+
const metadata = [{ text: 'doc1' }, { text: 'doc2' }];
|
|
30
|
+
const documents = ['full text 1', 'full text 2'];
|
|
31
|
+
const ids = await vectorStore.upsert(
|
|
32
|
+
'my-collection',
|
|
33
|
+
vectors,
|
|
34
|
+
metadata,
|
|
35
|
+
undefined, // auto-generate IDs
|
|
36
|
+
documents // store original text
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
// Query vectors with document filtering
|
|
40
|
+
const results = await vectorStore.query(
|
|
41
|
+
'my-collection',
|
|
42
|
+
[0.1, 0.2, ...],
|
|
43
|
+
10, // topK
|
|
44
|
+
{ text: { $eq: 'doc1' } }, // metadata filter
|
|
45
|
+
false, // includeVector
|
|
46
|
+
{ $contains: 'specific text' } // document content filter
|
|
47
|
+
);
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Configuration
|
|
51
|
+
|
|
52
|
+
Required:
|
|
53
|
+
|
|
54
|
+
- `path`: URL of your ChromaDB server
|
|
55
|
+
|
|
56
|
+
Optional:
|
|
57
|
+
|
|
58
|
+
- `auth`: Authentication configuration
|
|
59
|
+
- `provider`: Authentication provider
|
|
60
|
+
- `credentials`: Authentication credentials
|
|
61
|
+
|
|
62
|
+
## Features
|
|
63
|
+
|
|
64
|
+
- Vector similarity search with cosine, euclidean, and dot product metrics
|
|
65
|
+
- Document storage and retrieval
|
|
66
|
+
- Document content filtering
|
|
67
|
+
- Strict vector dimension validation
|
|
68
|
+
- Collection-based organization
|
|
69
|
+
- Metadata filtering support
|
|
70
|
+
- Optional vector inclusion in query results
|
|
71
|
+
- Automatic UUID generation for vectors
|
|
72
|
+
- Built-in collection caching for performance
|
|
73
|
+
- Built on top of chromadb client
|
|
74
|
+
|
|
75
|
+
## Methods
|
|
76
|
+
|
|
77
|
+
- `createIndex(indexName, dimension, metric?)`: Create a new collection
|
|
78
|
+
- `upsert(indexName, vectors, metadata?, ids?, documents?)`: Add or update vectors with optional document storage
|
|
79
|
+
- `query(indexName, queryVector, topK?, filter?, includeVector?, documentFilter?)`: Search for similar vectors with optional document filtering
|
|
80
|
+
- `listIndexes()`: List all collections
|
|
81
|
+
- `describeIndex(indexName)`: Get collection statistics
|
|
82
|
+
- `deleteIndex(indexName)`: Delete a collection
|
|
83
|
+
|
|
84
|
+
## Query Response Format
|
|
85
|
+
|
|
86
|
+
Query results include:
|
|
87
|
+
|
|
88
|
+
- `id`: Vector ID
|
|
89
|
+
- `score`: Distance/similarity score
|
|
90
|
+
- `metadata`: Associated metadata
|
|
91
|
+
- `document`: Original document text (if stored)
|
|
92
|
+
- `vector`: Original vector (if includeVector is true)
|
|
93
|
+
|
|
94
|
+
## Related Links
|
|
95
|
+
|
|
96
|
+
- [ChromaDB Documentation](https://docs.trychroma.com/)
|
|
97
|
+
- [ChromaDB API Reference](https://docs.trychroma.com/api/client)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { BaseFilterTranslator } from '@mastra/core/filter';
|
|
2
|
+
import type { Filter } from '@mastra/core/filter';
|
|
3
|
+
import type { IndexStats } from '@mastra/core/vector';
|
|
4
|
+
import { MastraVector } from '@mastra/core/vector';
|
|
5
|
+
import type { OperatorSupport } from '@mastra/core/filter';
|
|
6
|
+
import type { QueryResult } from '@mastra/core/vector';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Translator for Chroma filter queries.
|
|
10
|
+
* Maintains MongoDB-compatible syntax while ensuring proper validation
|
|
11
|
+
* and normalization of values.
|
|
12
|
+
*/
|
|
13
|
+
export declare class ChromaFilterTranslator extends BaseFilterTranslator {
|
|
14
|
+
protected getSupportedOperators(): OperatorSupport;
|
|
15
|
+
translate(filter?: Filter): Filter | undefined;
|
|
16
|
+
private translateNode;
|
|
17
|
+
private translateOperator;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
declare class ChromaVector extends MastraVector {
|
|
21
|
+
private client;
|
|
22
|
+
private collections;
|
|
23
|
+
constructor({ path, auth, }: {
|
|
24
|
+
path: string;
|
|
25
|
+
auth?: {
|
|
26
|
+
provider: string;
|
|
27
|
+
credentials: string;
|
|
28
|
+
};
|
|
29
|
+
});
|
|
30
|
+
getCollection(indexName: string, throwIfNotExists?: boolean): Promise<any>;
|
|
31
|
+
private validateVectorDimensions;
|
|
32
|
+
upsert(indexName: string, vectors: number[][], metadata?: Record<string, any>[], ids?: string[], documents?: string[]): Promise<string[]>;
|
|
33
|
+
private HnswSpaceMap;
|
|
34
|
+
createIndex(indexName: string, dimension: number, metric?: 'cosine' | 'euclidean' | 'dotproduct'): Promise<void>;
|
|
35
|
+
transformFilter(filter?: Filter): Filter | undefined;
|
|
36
|
+
query(indexName: string, queryVector: number[], topK?: number, filter?: Filter, includeVector?: boolean, documentFilter?: Filter): Promise<QueryResult[]>;
|
|
37
|
+
listIndexes(): Promise<string[]>;
|
|
38
|
+
describeIndex(indexName: string): Promise<IndexStats>;
|
|
39
|
+
deleteIndex(indexName: string): Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
export { ChromaVector }
|
|
42
|
+
export { ChromaVector as ChromaVector_alias_1 }
|
|
43
|
+
|
|
44
|
+
declare interface DocumentMetadata {
|
|
45
|
+
content?: string;
|
|
46
|
+
metadata?: Record<string, any>;
|
|
47
|
+
}
|
|
48
|
+
export { DocumentMetadata }
|
|
49
|
+
export { DocumentMetadata as DocumentMetadata_alias_1 }
|
|
50
|
+
|
|
51
|
+
export { }
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { BaseFilterTranslator } from '@mastra/core/filter';
|
|
2
|
+
import type { Filter } from '@mastra/core/filter';
|
|
3
|
+
import type { IndexStats } from '@mastra/core/vector';
|
|
4
|
+
import { MastraVector } from '@mastra/core/vector';
|
|
5
|
+
import type { OperatorSupport } from '@mastra/core/filter';
|
|
6
|
+
import type { QueryResult } from '@mastra/core/vector';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Translator for Chroma filter queries.
|
|
10
|
+
* Maintains MongoDB-compatible syntax while ensuring proper validation
|
|
11
|
+
* and normalization of values.
|
|
12
|
+
*/
|
|
13
|
+
export declare class ChromaFilterTranslator extends BaseFilterTranslator {
|
|
14
|
+
protected getSupportedOperators(): OperatorSupport;
|
|
15
|
+
translate(filter?: Filter): Filter | undefined;
|
|
16
|
+
private translateNode;
|
|
17
|
+
private translateOperator;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
declare class ChromaVector extends MastraVector {
|
|
21
|
+
private client;
|
|
22
|
+
private collections;
|
|
23
|
+
constructor({ path, auth, }: {
|
|
24
|
+
path: string;
|
|
25
|
+
auth?: {
|
|
26
|
+
provider: string;
|
|
27
|
+
credentials: string;
|
|
28
|
+
};
|
|
29
|
+
});
|
|
30
|
+
getCollection(indexName: string, throwIfNotExists?: boolean): Promise<any>;
|
|
31
|
+
private validateVectorDimensions;
|
|
32
|
+
upsert(indexName: string, vectors: number[][], metadata?: Record<string, any>[], ids?: string[], documents?: string[]): Promise<string[]>;
|
|
33
|
+
private HnswSpaceMap;
|
|
34
|
+
createIndex(indexName: string, dimension: number, metric?: 'cosine' | 'euclidean' | 'dotproduct'): Promise<void>;
|
|
35
|
+
transformFilter(filter?: Filter): Filter | undefined;
|
|
36
|
+
query(indexName: string, queryVector: number[], topK?: number, filter?: Filter, includeVector?: boolean, documentFilter?: Filter): Promise<QueryResult[]>;
|
|
37
|
+
listIndexes(): Promise<string[]>;
|
|
38
|
+
describeIndex(indexName: string): Promise<IndexStats>;
|
|
39
|
+
deleteIndex(indexName: string): Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
export { ChromaVector }
|
|
42
|
+
export { ChromaVector as ChromaVector_alias_1 }
|
|
43
|
+
|
|
44
|
+
declare interface DocumentMetadata {
|
|
45
|
+
content?: string;
|
|
46
|
+
metadata?: Record<string, any>;
|
|
47
|
+
}
|
|
48
|
+
export { DocumentMetadata }
|
|
49
|
+
export { DocumentMetadata as DocumentMetadata_alias_1 }
|
|
50
|
+
|
|
51
|
+
export { }
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var vector = require('@mastra/core/vector');
|
|
4
|
+
var chromadb = require('chromadb');
|
|
5
|
+
var filter = require('@mastra/core/filter');
|
|
6
|
+
|
|
7
|
+
// src/vector/index.ts
|
|
8
|
+
var ChromaFilterTranslator = class extends filter.BaseFilterTranslator {
|
|
9
|
+
getSupportedOperators() {
|
|
10
|
+
return {
|
|
11
|
+
...filter.BaseFilterTranslator.DEFAULT_OPERATORS,
|
|
12
|
+
logical: ["$and", "$or"],
|
|
13
|
+
array: ["$in", "$nin"],
|
|
14
|
+
element: [],
|
|
15
|
+
regex: [],
|
|
16
|
+
custom: []
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
translate(filter) {
|
|
20
|
+
if (this.isEmpty(filter)) return filter;
|
|
21
|
+
this.validateFilter(filter);
|
|
22
|
+
return this.translateNode(filter);
|
|
23
|
+
}
|
|
24
|
+
translateNode(node, currentPath = "") {
|
|
25
|
+
if (this.isRegex(node)) {
|
|
26
|
+
throw new Error("Regex is not supported in Chroma");
|
|
27
|
+
}
|
|
28
|
+
if (this.isPrimitive(node)) return this.normalizeComparisonValue(node);
|
|
29
|
+
if (Array.isArray(node)) return { $in: this.normalizeArrayValues(node) };
|
|
30
|
+
const entries = Object.entries(node);
|
|
31
|
+
const firstEntry = entries[0];
|
|
32
|
+
if (entries.length === 1 && firstEntry && this.isOperator(firstEntry[0])) {
|
|
33
|
+
const [operator, value] = firstEntry;
|
|
34
|
+
const translated = this.translateOperator(operator, value);
|
|
35
|
+
return this.isLogicalOperator(operator) ? { [operator]: translated } : translated;
|
|
36
|
+
}
|
|
37
|
+
const result = {};
|
|
38
|
+
const multiOperatorConditions = [];
|
|
39
|
+
for (const [key, value] of entries) {
|
|
40
|
+
const newPath = currentPath ? `${currentPath}.${key}` : key;
|
|
41
|
+
if (this.isOperator(key)) {
|
|
42
|
+
result[key] = this.translateOperator(key, value);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
46
|
+
const valueEntries = Object.entries(value);
|
|
47
|
+
if (valueEntries.every(([op]) => this.isOperator(op)) && valueEntries.length > 1) {
|
|
48
|
+
valueEntries.forEach(([op, opValue]) => {
|
|
49
|
+
multiOperatorConditions.push({
|
|
50
|
+
[newPath]: { [op]: this.normalizeComparisonValue(opValue) }
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (Object.keys(value).length === 0) {
|
|
56
|
+
result[newPath] = this.translateNode(value);
|
|
57
|
+
} else {
|
|
58
|
+
const hasOperators = Object.keys(value).some((k) => this.isOperator(k));
|
|
59
|
+
if (hasOperators) {
|
|
60
|
+
const normalizedValue = {};
|
|
61
|
+
for (const [op, opValue] of Object.entries(value)) {
|
|
62
|
+
normalizedValue[op] = this.isOperator(op) ? this.translateOperator(op, opValue) : opValue;
|
|
63
|
+
}
|
|
64
|
+
result[newPath] = normalizedValue;
|
|
65
|
+
} else {
|
|
66
|
+
Object.assign(result, this.translateNode(value, newPath));
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
} else {
|
|
70
|
+
result[newPath] = this.translateNode(value);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (multiOperatorConditions.length > 0) {
|
|
74
|
+
return { $and: multiOperatorConditions };
|
|
75
|
+
}
|
|
76
|
+
if (Object.keys(result).length > 1 && !currentPath) {
|
|
77
|
+
return {
|
|
78
|
+
$and: Object.entries(result).map(([key, value]) => ({ [key]: value }))
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
return result;
|
|
82
|
+
}
|
|
83
|
+
translateOperator(operator, value) {
|
|
84
|
+
if (this.isLogicalOperator(operator)) {
|
|
85
|
+
return Array.isArray(value) ? value.map((item) => this.translateNode(item)) : this.translateNode(value);
|
|
86
|
+
}
|
|
87
|
+
return this.normalizeComparisonValue(value);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// src/vector/index.ts
|
|
92
|
+
var ChromaVector = class extends vector.MastraVector {
|
|
93
|
+
client;
|
|
94
|
+
collections;
|
|
95
|
+
constructor({
|
|
96
|
+
path,
|
|
97
|
+
auth
|
|
98
|
+
}) {
|
|
99
|
+
super();
|
|
100
|
+
this.client = new chromadb.ChromaClient({
|
|
101
|
+
path,
|
|
102
|
+
auth
|
|
103
|
+
});
|
|
104
|
+
this.collections = /* @__PURE__ */ new Map();
|
|
105
|
+
}
|
|
106
|
+
async getCollection(indexName, throwIfNotExists = true) {
|
|
107
|
+
try {
|
|
108
|
+
const collection = await this.client.getCollection({ name: indexName, embeddingFunction: void 0 });
|
|
109
|
+
this.collections.set(indexName, collection);
|
|
110
|
+
} catch {
|
|
111
|
+
if (throwIfNotExists) {
|
|
112
|
+
throw new Error(`Index ${indexName} does not exist`);
|
|
113
|
+
}
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
return this.collections.get(indexName);
|
|
117
|
+
}
|
|
118
|
+
validateVectorDimensions(vectors, dimension) {
|
|
119
|
+
for (let i = 0; i < vectors.length; i++) {
|
|
120
|
+
if (vectors?.[i]?.length !== dimension) {
|
|
121
|
+
throw new Error(
|
|
122
|
+
`Vector at index ${i} has invalid dimension ${vectors?.[i]?.length}. Expected ${dimension} dimensions.`
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async upsert(indexName, vectors, metadata, ids, documents) {
|
|
128
|
+
const collection = await this.getCollection(indexName);
|
|
129
|
+
const stats = await this.describeIndex(indexName);
|
|
130
|
+
this.validateVectorDimensions(vectors, stats.dimension);
|
|
131
|
+
const generatedIds = ids || vectors.map(() => crypto.randomUUID());
|
|
132
|
+
const normalizedMetadata = metadata || vectors.map(() => ({}));
|
|
133
|
+
await collection.upsert({
|
|
134
|
+
ids: generatedIds,
|
|
135
|
+
embeddings: vectors,
|
|
136
|
+
metadatas: normalizedMetadata,
|
|
137
|
+
documents
|
|
138
|
+
});
|
|
139
|
+
return generatedIds;
|
|
140
|
+
}
|
|
141
|
+
HnswSpaceMap = {
|
|
142
|
+
cosine: "cosine",
|
|
143
|
+
euclidean: "l2",
|
|
144
|
+
dotproduct: "ip",
|
|
145
|
+
l2: "euclidean",
|
|
146
|
+
ip: "dotproduct"
|
|
147
|
+
};
|
|
148
|
+
async createIndex(indexName, dimension, metric = "cosine") {
|
|
149
|
+
if (!Number.isInteger(dimension) || dimension <= 0) {
|
|
150
|
+
throw new Error("Dimension must be a positive integer");
|
|
151
|
+
}
|
|
152
|
+
const hnswSpace = this.HnswSpaceMap[metric];
|
|
153
|
+
if (!["cosine", "l2", "ip"].includes(hnswSpace)) {
|
|
154
|
+
throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
|
|
155
|
+
}
|
|
156
|
+
await this.client.createCollection({
|
|
157
|
+
name: indexName,
|
|
158
|
+
metadata: {
|
|
159
|
+
dimension,
|
|
160
|
+
"hnsw:space": this.HnswSpaceMap[metric]
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
transformFilter(filter) {
|
|
165
|
+
const chromaFilter = new ChromaFilterTranslator();
|
|
166
|
+
const translatedFilter = chromaFilter.translate(filter);
|
|
167
|
+
return translatedFilter;
|
|
168
|
+
}
|
|
169
|
+
async query(indexName, queryVector, topK = 10, filter, includeVector = false, documentFilter) {
|
|
170
|
+
const collection = await this.getCollection(indexName, true);
|
|
171
|
+
const defaultInclude = ["documents", "metadatas", "distances"];
|
|
172
|
+
const translatedFilter = this.transformFilter(filter);
|
|
173
|
+
const results = await collection.query({
|
|
174
|
+
queryEmbeddings: [queryVector],
|
|
175
|
+
nResults: topK,
|
|
176
|
+
where: translatedFilter,
|
|
177
|
+
whereDocument: documentFilter,
|
|
178
|
+
include: includeVector ? [...defaultInclude, "embeddings"] : defaultInclude
|
|
179
|
+
});
|
|
180
|
+
return (results.ids[0] || []).map((id, index) => ({
|
|
181
|
+
id,
|
|
182
|
+
score: results.distances?.[0]?.[index] || 0,
|
|
183
|
+
metadata: results.metadatas?.[0]?.[index] || {},
|
|
184
|
+
document: results.documents?.[0]?.[index],
|
|
185
|
+
...includeVector && { vector: results.embeddings?.[0]?.[index] || [] }
|
|
186
|
+
}));
|
|
187
|
+
}
|
|
188
|
+
async listIndexes() {
|
|
189
|
+
const collections = await this.client.listCollections();
|
|
190
|
+
return collections.map((collection) => collection);
|
|
191
|
+
}
|
|
192
|
+
async describeIndex(indexName) {
|
|
193
|
+
const collection = await this.getCollection(indexName);
|
|
194
|
+
const count = await collection.count();
|
|
195
|
+
const metadata = collection.metadata;
|
|
196
|
+
const hnswSpace = metadata?.["hnsw:space"];
|
|
197
|
+
return {
|
|
198
|
+
dimension: metadata?.dimension || 0,
|
|
199
|
+
count,
|
|
200
|
+
metric: this.HnswSpaceMap[hnswSpace]
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
async deleteIndex(indexName) {
|
|
204
|
+
await this.client.deleteCollection({ name: indexName });
|
|
205
|
+
this.collections.delete(indexName);
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
exports.ChromaVector = ChromaVector;
|
package/dist/index.d.cts
ADDED
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { MastraVector } from '@mastra/core/vector';
|
|
2
|
+
import { ChromaClient } from 'chromadb';
|
|
3
|
+
import { BaseFilterTranslator } from '@mastra/core/filter';
|
|
4
|
+
|
|
5
|
+
// src/vector/index.ts
|
|
6
|
+
var ChromaFilterTranslator = class extends BaseFilterTranslator {
|
|
7
|
+
getSupportedOperators() {
|
|
8
|
+
return {
|
|
9
|
+
...BaseFilterTranslator.DEFAULT_OPERATORS,
|
|
10
|
+
logical: ["$and", "$or"],
|
|
11
|
+
array: ["$in", "$nin"],
|
|
12
|
+
element: [],
|
|
13
|
+
regex: [],
|
|
14
|
+
custom: []
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
translate(filter) {
|
|
18
|
+
if (this.isEmpty(filter)) return filter;
|
|
19
|
+
this.validateFilter(filter);
|
|
20
|
+
return this.translateNode(filter);
|
|
21
|
+
}
|
|
22
|
+
translateNode(node, currentPath = "") {
|
|
23
|
+
if (this.isRegex(node)) {
|
|
24
|
+
throw new Error("Regex is not supported in Chroma");
|
|
25
|
+
}
|
|
26
|
+
if (this.isPrimitive(node)) return this.normalizeComparisonValue(node);
|
|
27
|
+
if (Array.isArray(node)) return { $in: this.normalizeArrayValues(node) };
|
|
28
|
+
const entries = Object.entries(node);
|
|
29
|
+
const firstEntry = entries[0];
|
|
30
|
+
if (entries.length === 1 && firstEntry && this.isOperator(firstEntry[0])) {
|
|
31
|
+
const [operator, value] = firstEntry;
|
|
32
|
+
const translated = this.translateOperator(operator, value);
|
|
33
|
+
return this.isLogicalOperator(operator) ? { [operator]: translated } : translated;
|
|
34
|
+
}
|
|
35
|
+
const result = {};
|
|
36
|
+
const multiOperatorConditions = [];
|
|
37
|
+
for (const [key, value] of entries) {
|
|
38
|
+
const newPath = currentPath ? `${currentPath}.${key}` : key;
|
|
39
|
+
if (this.isOperator(key)) {
|
|
40
|
+
result[key] = this.translateOperator(key, value);
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
44
|
+
const valueEntries = Object.entries(value);
|
|
45
|
+
if (valueEntries.every(([op]) => this.isOperator(op)) && valueEntries.length > 1) {
|
|
46
|
+
valueEntries.forEach(([op, opValue]) => {
|
|
47
|
+
multiOperatorConditions.push({
|
|
48
|
+
[newPath]: { [op]: this.normalizeComparisonValue(opValue) }
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (Object.keys(value).length === 0) {
|
|
54
|
+
result[newPath] = this.translateNode(value);
|
|
55
|
+
} else {
|
|
56
|
+
const hasOperators = Object.keys(value).some((k) => this.isOperator(k));
|
|
57
|
+
if (hasOperators) {
|
|
58
|
+
const normalizedValue = {};
|
|
59
|
+
for (const [op, opValue] of Object.entries(value)) {
|
|
60
|
+
normalizedValue[op] = this.isOperator(op) ? this.translateOperator(op, opValue) : opValue;
|
|
61
|
+
}
|
|
62
|
+
result[newPath] = normalizedValue;
|
|
63
|
+
} else {
|
|
64
|
+
Object.assign(result, this.translateNode(value, newPath));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
} else {
|
|
68
|
+
result[newPath] = this.translateNode(value);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (multiOperatorConditions.length > 0) {
|
|
72
|
+
return { $and: multiOperatorConditions };
|
|
73
|
+
}
|
|
74
|
+
if (Object.keys(result).length > 1 && !currentPath) {
|
|
75
|
+
return {
|
|
76
|
+
$and: Object.entries(result).map(([key, value]) => ({ [key]: value }))
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
translateOperator(operator, value) {
|
|
82
|
+
if (this.isLogicalOperator(operator)) {
|
|
83
|
+
return Array.isArray(value) ? value.map((item) => this.translateNode(item)) : this.translateNode(value);
|
|
84
|
+
}
|
|
85
|
+
return this.normalizeComparisonValue(value);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
// src/vector/index.ts
|
|
90
|
+
var ChromaVector = class extends MastraVector {
|
|
91
|
+
client;
|
|
92
|
+
collections;
|
|
93
|
+
constructor({
|
|
94
|
+
path,
|
|
95
|
+
auth
|
|
96
|
+
}) {
|
|
97
|
+
super();
|
|
98
|
+
this.client = new ChromaClient({
|
|
99
|
+
path,
|
|
100
|
+
auth
|
|
101
|
+
});
|
|
102
|
+
this.collections = /* @__PURE__ */ new Map();
|
|
103
|
+
}
|
|
104
|
+
async getCollection(indexName, throwIfNotExists = true) {
|
|
105
|
+
try {
|
|
106
|
+
const collection = await this.client.getCollection({ name: indexName, embeddingFunction: void 0 });
|
|
107
|
+
this.collections.set(indexName, collection);
|
|
108
|
+
} catch {
|
|
109
|
+
if (throwIfNotExists) {
|
|
110
|
+
throw new Error(`Index ${indexName} does not exist`);
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
return this.collections.get(indexName);
|
|
115
|
+
}
|
|
116
|
+
validateVectorDimensions(vectors, dimension) {
|
|
117
|
+
for (let i = 0; i < vectors.length; i++) {
|
|
118
|
+
if (vectors?.[i]?.length !== dimension) {
|
|
119
|
+
throw new Error(
|
|
120
|
+
`Vector at index ${i} has invalid dimension ${vectors?.[i]?.length}. Expected ${dimension} dimensions.`
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
async upsert(indexName, vectors, metadata, ids, documents) {
|
|
126
|
+
const collection = await this.getCollection(indexName);
|
|
127
|
+
const stats = await this.describeIndex(indexName);
|
|
128
|
+
this.validateVectorDimensions(vectors, stats.dimension);
|
|
129
|
+
const generatedIds = ids || vectors.map(() => crypto.randomUUID());
|
|
130
|
+
const normalizedMetadata = metadata || vectors.map(() => ({}));
|
|
131
|
+
await collection.upsert({
|
|
132
|
+
ids: generatedIds,
|
|
133
|
+
embeddings: vectors,
|
|
134
|
+
metadatas: normalizedMetadata,
|
|
135
|
+
documents
|
|
136
|
+
});
|
|
137
|
+
return generatedIds;
|
|
138
|
+
}
|
|
139
|
+
HnswSpaceMap = {
|
|
140
|
+
cosine: "cosine",
|
|
141
|
+
euclidean: "l2",
|
|
142
|
+
dotproduct: "ip",
|
|
143
|
+
l2: "euclidean",
|
|
144
|
+
ip: "dotproduct"
|
|
145
|
+
};
|
|
146
|
+
async createIndex(indexName, dimension, metric = "cosine") {
|
|
147
|
+
if (!Number.isInteger(dimension) || dimension <= 0) {
|
|
148
|
+
throw new Error("Dimension must be a positive integer");
|
|
149
|
+
}
|
|
150
|
+
const hnswSpace = this.HnswSpaceMap[metric];
|
|
151
|
+
if (!["cosine", "l2", "ip"].includes(hnswSpace)) {
|
|
152
|
+
throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
|
|
153
|
+
}
|
|
154
|
+
await this.client.createCollection({
|
|
155
|
+
name: indexName,
|
|
156
|
+
metadata: {
|
|
157
|
+
dimension,
|
|
158
|
+
"hnsw:space": this.HnswSpaceMap[metric]
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
transformFilter(filter) {
|
|
163
|
+
const chromaFilter = new ChromaFilterTranslator();
|
|
164
|
+
const translatedFilter = chromaFilter.translate(filter);
|
|
165
|
+
return translatedFilter;
|
|
166
|
+
}
|
|
167
|
+
async query(indexName, queryVector, topK = 10, filter, includeVector = false, documentFilter) {
|
|
168
|
+
const collection = await this.getCollection(indexName, true);
|
|
169
|
+
const defaultInclude = ["documents", "metadatas", "distances"];
|
|
170
|
+
const translatedFilter = this.transformFilter(filter);
|
|
171
|
+
const results = await collection.query({
|
|
172
|
+
queryEmbeddings: [queryVector],
|
|
173
|
+
nResults: topK,
|
|
174
|
+
where: translatedFilter,
|
|
175
|
+
whereDocument: documentFilter,
|
|
176
|
+
include: includeVector ? [...defaultInclude, "embeddings"] : defaultInclude
|
|
177
|
+
});
|
|
178
|
+
return (results.ids[0] || []).map((id, index) => ({
|
|
179
|
+
id,
|
|
180
|
+
score: results.distances?.[0]?.[index] || 0,
|
|
181
|
+
metadata: results.metadatas?.[0]?.[index] || {},
|
|
182
|
+
document: results.documents?.[0]?.[index],
|
|
183
|
+
...includeVector && { vector: results.embeddings?.[0]?.[index] || [] }
|
|
184
|
+
}));
|
|
185
|
+
}
|
|
186
|
+
async listIndexes() {
|
|
187
|
+
const collections = await this.client.listCollections();
|
|
188
|
+
return collections.map((collection) => collection);
|
|
189
|
+
}
|
|
190
|
+
async describeIndex(indexName) {
|
|
191
|
+
const collection = await this.getCollection(indexName);
|
|
192
|
+
const count = await collection.count();
|
|
193
|
+
const metadata = collection.metadata;
|
|
194
|
+
const hnswSpace = metadata?.["hnsw:space"];
|
|
195
|
+
return {
|
|
196
|
+
dimension: metadata?.dimension || 0,
|
|
197
|
+
count,
|
|
198
|
+
metric: this.HnswSpaceMap[hnswSpace]
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
async deleteIndex(indexName) {
|
|
202
|
+
await this.client.deleteCollection({ name: indexName });
|
|
203
|
+
this.collections.delete(indexName);
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
export { ChromaVector };
|