-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
cassandra.ts
152 lines (130 loc) Β· 4.13 KB
/
cassandra.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
import { BaseListChatMessageHistory } from "@langchain/core/chat_history";
import {
BaseMessage,
StoredMessage,
mapChatMessagesToStoredMessages,
mapStoredMessagesToChatMessages,
} from "@langchain/core/messages";
import {
Column,
CassandraTable,
CassandraClientArgs,
} from "../../utils/cassandra.js";
export interface CassandraChatMessageHistoryOptions
extends CassandraClientArgs {
keyspace: string;
table: string;
sessionId: string;
}
/**
* Class for storing chat message history within Cassandra. It extends the
* BaseListChatMessageHistory class and provides methods to get, add, and
* clear messages.
* @example
* ```typescript
* const chatHistory = new CassandraChatMessageHistory({
* cloud: {
* secureConnectBundle: "<path to your secure bundle>",
* },
* credentials: {
* username: "token",
* password: "<your Cassandra access token>",
* },
* keyspace: "langchain",
* table: "message_history",
* sessionId: "<some unique session identifier>",
* });
*
* const chain = new ConversationChain({
* llm: new ChatOpenAI(),
* memory: chatHistory,
* });
*
* const response = await chain.invoke({
* input: "What did I just say my name was?",
* });
* console.log({ response });
* ```
*/
export class CassandraChatMessageHistory extends BaseListChatMessageHistory {
lc_namespace = ["langchain", "stores", "message", "cassandra"];
private cassandraTable: CassandraTable;
private sessionId: string;
private options: CassandraChatMessageHistoryOptions;
private colSessionId: Column;
private colMessageTs: Column;
private colMessageType: Column;
private colData: Column;
constructor(options: CassandraChatMessageHistoryOptions) {
super();
this.sessionId = options.sessionId;
this.options = options;
this.colSessionId = { name: "session_id", type: "text", partition: true };
this.colMessageTs = { name: "message_ts", type: "timestamp" };
this.colMessageType = { name: "message_type", type: "text" };
this.colData = { name: "data", type: "text" };
}
/**
* Method to get all the messages stored in the Cassandra database.
* @returns Array of stored BaseMessage instances.
*/
public async getMessages(): Promise<BaseMessage[]> {
await this.ensureTable();
const resultSet = await this.cassandraTable.select(
[this.colMessageType, this.colData],
[{ name: "session_id", value: this.sessionId }]
);
const storedMessages: StoredMessage[] = resultSet.rows.map((row) => ({
type: row.message_type,
data: JSON.parse(row.data),
}));
const baseMessages = mapStoredMessagesToChatMessages(storedMessages);
return baseMessages;
}
/**
* Method to add a new message to the Cassandra database.
* @param message The BaseMessage instance to add.
* @returns A promise that resolves when the message has been added.
*/
public async addMessage(message: BaseMessage): Promise<void> {
await this.ensureTable();
const messages = mapChatMessagesToStoredMessages([message]);
const { type, data } = messages[0];
return this.cassandraTable
.upsert(
[[this.sessionId, type, Date.now(), JSON.stringify(data)]],
[
this.colSessionId,
this.colMessageType,
this.colMessageTs,
this.colData,
]
)
.then(() => {});
}
/**
* Method to clear all the messages from the Cassandra database.
* @returns A promise that resolves when all messages have been cleared.
*/
public async clear(): Promise<void> {
await this.ensureTable();
return this.cassandraTable
.delete({ name: this.colSessionId.name, value: this.sessionId })
.then(() => {});
}
/**
* Method to initialize the Cassandra database.
* @returns Promise that resolves when the database has been initialized.
*/
private async ensureTable(): Promise<void> {
if (this.cassandraTable) {
return;
}
const tableConfig = {
...this.options,
primaryKey: [this.colSessionId, this.colMessageTs],
nonKeyColumns: [this.colMessageType, this.colData],
};
this.cassandraTable = await new CassandraTable(tableConfig);
}
}