-
Notifications
You must be signed in to change notification settings - Fork 2k
/
mongodb.ts
48 lines (40 loc) · 1.4 KB
/
mongodb.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
import { Collection, Document as MongoDBDocument, ObjectId } from "mongodb";
import { BaseMessage, BaseListChatMessageHistory } from "../../schema/index.js";
import {
mapChatMessagesToStoredMessages,
mapStoredMessagesToChatMessages,
} from "./utils.js";
export interface MongoDBChatMessageHistoryInput {
collection: Collection<MongoDBDocument>;
sessionId: string;
}
export class MongoDBChatMessageHistory extends BaseListChatMessageHistory {
lc_namespace = ["langchain", "stores", "message", "mongodb"];
private collection: Collection<MongoDBDocument>;
private sessionId: string;
constructor({ collection, sessionId }: MongoDBChatMessageHistoryInput) {
super();
this.collection = collection;
this.sessionId = sessionId;
}
async getMessages(): Promise<BaseMessage[]> {
const document = await this.collection.findOne({
_id: new ObjectId(this.sessionId),
});
const messages = document?.messages || [];
return mapStoredMessagesToChatMessages(messages);
}
async addMessage(message: BaseMessage): Promise<void> {
const messages = mapChatMessagesToStoredMessages([message]);
await this.collection.updateOne(
{ _id: new ObjectId(this.sessionId) },
{
$push: { messages: { $each: messages } },
},
{ upsert: true }
);
}
async clear(): Promise<void> {
await this.collection.deleteOne({ _id: new ObjectId(this.sessionId) });
}
}