-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathchat_history.ts
69 lines (60 loc) · 1.79 KB
/
chat_history.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
import {
Collection,
Document as MongoDBDocument,
type PushOperator,
} from "mongodb";
import { BaseListChatMessageHistory } from "@langchain/core/chat_history";
import {
BaseMessage,
StoredMessage,
mapChatMessagesToStoredMessages,
mapStoredMessagesToChatMessages,
} from "@langchain/core/messages";
export interface MongoDBChatMessageHistoryInput {
collection: Collection<MongoDBDocument>;
sessionId: string;
}
/**
* @example
* ```typescript
* const chatHistory = new MongoDBChatMessageHistory({
* collection: myCollection,
* sessionId: 'unique-session-id',
* });
* const messages = await chatHistory.getMessages();
* await chatHistory.clear();
* ```
*/
export class MongoDBChatMessageHistory extends BaseListChatMessageHistory {
lc_namespace = ["langchain", "stores", "message", "mongodb"];
private collection: Collection<MongoDBDocument>;
private sessionId: string;
private idKey = "sessionId";
constructor({ collection, sessionId }: MongoDBChatMessageHistoryInput) {
super();
this.collection = collection;
this.sessionId = sessionId;
}
async getMessages(): Promise<BaseMessage[]> {
const document = await this.collection.findOne({
[this.idKey]: this.sessionId,
});
const messages = document?.messages || [];
return mapStoredMessagesToChatMessages(messages);
}
async addMessage(message: BaseMessage): Promise<void> {
const messages = mapChatMessagesToStoredMessages([message]);
await this.collection.updateOne(
{ [this.idKey]: this.sessionId },
{
$push: { messages: { $each: messages } } as PushOperator<{
messages: StoredMessage[];
}>,
},
{ upsert: true }
);
}
async clear(): Promise<void> {
await this.collection.deleteOne({ [this.idKey]: this.sessionId });
}
}