-
Notifications
You must be signed in to change notification settings - Fork 2k
/
cassandra.ts
159 lines (139 loc) Β· 4.42 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
153
154
155
156
157
158
159
import { BaseListChatMessageHistory } from "@langchain/core/chat_history";
import {
BaseMessage,
StoredMessage,
mapChatMessagesToStoredMessages,
mapStoredMessagesToChatMessages,
} from "@langchain/core/messages";
import { Client } from "cassandra-driver";
import {
CassandraClientFactory,
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 keyspace: string;
private table: string;
private client: Client;
private sessionId: string;
private tableExists: boolean;
private options: CassandraChatMessageHistoryOptions;
private queries: { insert: string; select: string; delete: string };
constructor(options: CassandraChatMessageHistoryOptions) {
super();
this.keyspace = options.keyspace;
this.table = options.table;
this.sessionId = options.sessionId;
this.tableExists = false;
this.options = options;
}
/**
* 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.client.execute(
this.queries.select,
[this.sessionId],
{ prepare: true }
);
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.client
.execute(
this.queries.insert,
[this.sessionId, type, JSON.stringify(data)],
{ prepare: true, ...this.options }
)
.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.client
.execute(this.queries.delete, [this.sessionId], {
prepare: true,
...this.options,
})
.then(() => {});
}
/**
* Method to initialize the Cassandra database.
* @returns Promise that resolves when the database has been initialized.
*/
private async ensureTable(): Promise<void> {
if (this.tableExists) {
return;
}
this.client = await CassandraClientFactory.getClient(this.options);
await this.client.execute(`
CREATE TABLE IF NOT EXISTS ${this.keyspace}.${this.table} (
session_id text,
message_ts timestamp,
message_type text,
data text,
PRIMARY KEY ((session_id), message_ts)
);
`);
this.queries = {
insert: `INSERT INTO ${this.keyspace}.${this.table} (session_id, message_ts, message_type, data) VALUES (?, toTimestamp(now()), ?, ?);`,
select: `SELECT message_type, data FROM ${this.keyspace}.${this.table} WHERE session_id = ?;`,
delete: `DELETE FROM ${this.keyspace}.${this.table} WHERE session_id = ?;`,
};
this.tableExists = true;
}
}