-
Notifications
You must be signed in to change notification settings - Fork 324
/
ChromaVectorStore.ts
177 lines (162 loc) · 4.88 KB
/
ChromaVectorStore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import type {
AddParams,
ChromaClientParams,
Collection,
QueryResponse,
Where,
WhereDocument,
} from "chromadb";
import { ChromaClient, IncludeEnum } from "chromadb";
import type { BaseNode } from "../../Node.js";
import { MetadataMode } from "../../Node.js";
import {
VectorStoreBase,
VectorStoreQueryMode,
type IEmbedModel,
type VectorStoreNoEmbedModel,
type VectorStoreQuery,
type VectorStoreQueryResult,
} from "./types.js";
import { metadataDictToNode, nodeToMetadata } from "./utils.js";
type ChromaDeleteOptions = {
where?: Where;
whereDocument?: WhereDocument;
};
type ChromaQueryOptions = {
whereDocument?: WhereDocument;
};
const DEFAULT_TEXT_KEY = "text";
export class ChromaVectorStore
extends VectorStoreBase
implements VectorStoreNoEmbedModel
{
storesText: boolean = true;
flatMetadata: boolean = true;
textKey: string;
private chromaClient: ChromaClient;
private collection: Collection | null = null;
private collectionName: string;
constructor(
init: {
collectionName: string;
textKey?: string;
chromaClientParams?: ChromaClientParams;
} & Partial<IEmbedModel>,
) {
super(init.embedModel);
this.collectionName = init.collectionName;
this.chromaClient = new ChromaClient(init.chromaClientParams);
this.textKey = init.textKey ?? DEFAULT_TEXT_KEY;
}
client(): ChromaClient {
return this.chromaClient;
}
async getCollection(): Promise<Collection> {
if (!this.collection) {
const coll = await this.chromaClient.getOrCreateCollection({
name: this.collectionName,
});
this.collection = coll;
}
return this.collection;
}
private getDataToInsert(nodes: BaseNode[]): AddParams {
const metadatas = nodes.map((node) =>
nodeToMetadata(node, true, this.textKey, this.flatMetadata),
);
return {
embeddings: nodes.map((node) => node.getEmbedding()),
ids: nodes.map((node) => node.id_),
metadatas,
documents: nodes.map((node) => node.getContent(MetadataMode.NONE)),
};
}
async add(nodes: BaseNode[]): Promise<string[]> {
if (!nodes || nodes.length === 0) {
return [];
}
const dataToInsert = this.getDataToInsert(nodes);
const collection = await this.getCollection();
await collection.add(dataToInsert);
return nodes.map((node) => node.id_);
}
async delete(
refDocId: string,
deleteOptions?: ChromaDeleteOptions,
): Promise<void> {
const collection = await this.getCollection();
await collection.delete({
ids: [refDocId],
where: deleteOptions?.where,
whereDocument: deleteOptions?.whereDocument,
});
}
async query(
query: VectorStoreQuery,
options?: ChromaQueryOptions,
): Promise<VectorStoreQueryResult> {
if (query.docIds) {
throw new Error("ChromaDB does not support querying by docIDs");
}
if (query.mode != VectorStoreQueryMode.DEFAULT) {
throw new Error("ChromaDB does not support querying by mode");
}
// fixme: type is broken
let chromaWhere: any = {};
if (query.filters?.filters) {
query.filters.filters.map((filter) => {
const filterKey = filter.key;
const filterValue = filter.value;
if (filterKey in chromaWhere || "$or" in chromaWhere) {
if (!chromaWhere["$or"]) {
chromaWhere = {
$or: [
{
...chromaWhere,
},
{
[filterKey]: filterValue,
},
],
};
} else {
chromaWhere["$or"].push({
[filterKey]: filterValue,
});
}
} else {
chromaWhere[filterKey] = filterValue;
}
});
}
const collection = await this.getCollection();
const queryResponse: QueryResponse = await collection.query({
queryEmbeddings: query.queryEmbedding ?? undefined,
queryTexts: query.queryStr ?? undefined,
nResults: query.similarityTopK,
where: Object.keys(chromaWhere).length ? chromaWhere : undefined,
whereDocument: options?.whereDocument,
//ChromaDB doesn't return the result embeddings by default so we need to include them
include: [
IncludeEnum.Distances,
IncludeEnum.Metadatas,
IncludeEnum.Documents,
IncludeEnum.Embeddings,
],
});
const vectorStoreQueryResult: VectorStoreQueryResult = {
nodes: queryResponse.ids[0].map((id, index) => {
const text = (queryResponse.documents as string[][])[0][index];
const metaData = queryResponse.metadatas[0][index] ?? {};
const node = metadataDictToNode(metaData);
node.setContent(text);
return node;
}),
similarities: (queryResponse.distances as number[][])[0].map(
(distance) => 1 - distance,
),
ids: queryResponse.ids[0],
};
return vectorStoreQueryResult;
}
}