-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
ipfs_datastore.ts
66 lines (51 loc) · 1.87 KB
/
ipfs_datastore.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
import { BaseListChatMessageHistory } from "@langchain/core/chat_history";
import {
type BaseMessage,
mapChatMessagesToStoredMessages,
mapStoredMessagesToChatMessages,
} from "@langchain/core/messages";
import * as cborg from "cborg";
import { type Datastore, Key } from "interface-datastore";
import all from "it-all";
export interface IPFSDatastoreChatMessageHistoryInput {
sessionId: string;
}
export interface IPFSDatastoreChatMessageHistoryProps {
datastore: Datastore;
sessionId: string;
}
export class IPFSDatastoreChatMessageHistory extends BaseListChatMessageHistory {
readonly lc_namespace = ["langchain", "stores", "message", "datastore"];
readonly sessionId: string;
private readonly datastore: Datastore;
constructor({ datastore, sessionId }: IPFSDatastoreChatMessageHistoryProps) {
super({ sessionId });
this.datastore = datastore;
this.sessionId = sessionId;
}
async getMessages(): Promise<BaseMessage[]> {
const data = await all(
this.datastore.query({ prefix: `/${this.sessionId}` })
);
const messages = data.map((d) => cborg.decode(d.value));
return mapStoredMessagesToChatMessages(messages);
}
async addMessage(message: BaseMessage): Promise<void> {
await this.addMessages([message]);
}
async addMessages(messages: BaseMessage[]): Promise<void> {
const { length } = await all(
this.datastore.queryKeys({ prefix: `/${this.sessionId}` })
);
const serializedMessages = mapChatMessagesToStoredMessages(messages);
const pairs = serializedMessages.map((message, index) => ({
key: new Key(`/${this.sessionId}/${index + length}`),
value: cborg.encode(message),
}));
await all(this.datastore.putMany(pairs));
}
async clear(): Promise<void> {
const keys = this.datastore.queryKeys({ prefix: `/${this.sessionId}` });
await all(this.datastore.deleteMany(keys));
}
}