-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathstorage.ts
221 lines (198 loc) Β· 6.1 KB
/
storage.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { BaseStore } from "@langchain/core/stores";
import { Collection, Document as MongoDocument } from "mongodb";
/**
* Type definition for the input parameters required to initialize an
* instance of the MongoDBStoreInput class.
*/
export interface MongoDBStoreInput {
collection: Collection<MongoDocument>;
/**
* The amount of keys to retrieve per batch when yielding keys.
* @default 1000
*/
yieldKeysScanBatchSize?: number;
/**
* The namespace to use for the keys in the database.
*/
namespace?: string;
/**
* The primary key to use for the database.
* @default "_id"
*/
primaryKey?: string;
}
/**
* Class that extends the BaseStore class to interact with a MongoDB
* database. It provides methods for getting, setting, and deleting data,
* as well as yielding keys from the database.
* @example
* ```typescript
* const client = new MongoClient(process.env.MONGODB_ATLAS_URI);
* const collection = client.db("dbName").collection("collectionName");
* const store = new MongoDBStore({
* collection,
* });
*
* const docs = [
* [uuidv4(), "Dogs are tough."],
* [uuidv4(), "Cats are tough."],
* ];
* const encoder = new TextEncoder();
* const docsAsKVPairs: Array<[string, Uint8Array]> = docs.map(
* (doc) => [doc[0], encoder.encode(doc[1])]
* );
* await store.mset(docsAsKVPairs);
* ```
*/
export class MongoDBStore extends BaseStore<string, Uint8Array> {
lc_namespace = ["langchain", "storage", "mongodb"];
collection: Collection<MongoDocument>;
protected namespace?: string;
protected yieldKeysScanBatchSize = 1000;
primaryKey = "_id";
constructor(fields: MongoDBStoreInput) {
super(fields);
this.collection = fields.collection;
this.primaryKey = fields.primaryKey ?? this.primaryKey;
this.yieldKeysScanBatchSize =
fields.yieldKeysScanBatchSize ?? this.yieldKeysScanBatchSize;
this.namespace = fields.namespace;
}
_getPrefixedKey(key: string) {
if (this.namespace) {
const delimiter = "/";
return `${this.namespace}${delimiter}${key}`;
}
return key;
}
_getDeprefixedKey(key: string) {
if (this.namespace) {
const delimiter = "/";
return key.slice(this.namespace.length + delimiter.length);
}
return key;
}
/**
* Gets multiple keys from the MongoDB database.
* @param keys Array of keys to be retrieved.
* @returns An array of retrieved values.
*/
async mget(keys: string[]) {
const prefixedKeys = keys.map(this._getPrefixedKey.bind(this));
const retrievedValues = await this.collection
.find({
[this.primaryKey]: { $in: prefixedKeys },
})
.toArray();
const encoder = new TextEncoder();
const valueMap = new Map(
retrievedValues.map((item) => [item[this.primaryKey], item])
);
return prefixedKeys.map((prefixedKey) => {
const value = valueMap.get(prefixedKey);
if (!value) {
return undefined;
}
if (!("value" in value)) {
return undefined;
} else if (typeof value.value === "object") {
return encoder.encode(JSON.stringify(value.value));
} else if (typeof value.value === "string") {
return encoder.encode(value.value);
} else {
throw new Error("Unexpected value type");
}
});
}
/**
* Sets multiple keys in the MongoDB database.
* @param keyValuePairs Array of key-value pairs to be set.
* @returns Promise that resolves when all keys have been set.
*/
async mset(keyValuePairs: [string, Uint8Array][]): Promise<void> {
const decoder = new TextDecoder();
const updates = keyValuePairs.map(([key, value]) => {
const decodedValue = decoder.decode(value);
return [
{ [this.primaryKey]: this._getPrefixedKey(key) },
{
$set: {
[this.primaryKey]: this._getPrefixedKey(key),
...{ value: decodedValue },
},
},
];
});
await this.collection.bulkWrite(
updates.map(([filter, update]) => ({
updateOne: {
filter,
update,
upsert: true,
},
}))
);
}
/**
* Deletes multiple keys from the MongoDB database.
* @param keys Array of keys to be deleted.
* @returns Promise that resolves when all keys have been deleted.
*/
async mdelete(keys: string[]): Promise<void> {
const allKeysWithPrefix = keys.map(this._getPrefixedKey.bind(this));
await this.collection.deleteMany({
[this.primaryKey]: { $in: allKeysWithPrefix },
});
}
/**
* Yields keys from the MongoDB database.
* @param prefix Optional prefix to filter the keys. A wildcard (*) is always appended to the end.
* @returns An AsyncGenerator that yields keys from the MongoDB database.
*/
async *yieldKeys(prefix?: string): AsyncGenerator<string> {
let regexPattern;
if (prefix) {
// Convert wildcard (*) to regex equivalent (.*)
// Escape special regex characters in prefix to ensure they are treated as literals
const escapedPrefix = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regexPrefix = escapedPrefix.endsWith("*")
? escapedPrefix.slice(0, -1)
: escapedPrefix;
regexPattern = `^${this._getPrefixedKey(regexPrefix)}.*`;
} else {
regexPattern = `^${this._getPrefixedKey(".*")}`;
}
let totalDocsYielded = 0;
let cursor = await this.collection
.find(
{
[this.primaryKey]: { $regex: regexPattern },
},
{
batchSize: this.yieldKeysScanBatchSize,
}
)
.toArray();
for (const key of cursor) {
yield this._getDeprefixedKey(key[this.primaryKey]);
}
totalDocsYielded += cursor.length;
while (cursor.length !== 0) {
cursor = await this.collection
.find(
{
[this.primaryKey]: { $regex: regexPattern },
},
{
batchSize: this.yieldKeysScanBatchSize,
skip: totalDocsYielded,
}
)
.toArray();
for (const key of cursor) {
yield this._getDeprefixedKey(key[this.primaryKey]);
}
totalDocsYielded += cursor.length;
}
}
}