-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatManager.js
More file actions
62 lines (53 loc) · 1.76 KB
/
ChatManager.js
File metadata and controls
62 lines (53 loc) · 1.76 KB
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
window.ChatManager = class ChatManager {
TIMEOUT_DURATION = 60000;
chatHistory;
characterDescription;
constructor(characterDescription) {
this.chatHistory = [];
this.characterDescription = characterDescription;
}
addMessage(role, content) {
this.chatHistory.push({ role, content });
}
getChatHistory() {
return this.chatHistory;
}
cleanChatHistory() {
this.chatHistory = [];
}
async getCharacterResponse(operation = 'chat', maxTokens = 384) {
const payload = {
character: this.characterDescription,
messages: this.chatHistory,
maxTokens: maxTokens,
operation: operation,
};
return new Promise((resolve, reject) => {
const requestId = self.crypto.randomUUID();
const handleMessage = (event) => {
const { data } = event;
if (data.requestId === requestId) {
window.removeEventListener('message', handleMessage);
if (data.error) {
reject(new Error(data.error));
} else {
resolve(data.content.message);
}
}
};
window.addEventListener('message', handleMessage);
window.parent.postMessage(
{
action: 'requestLLM',
payload: payload,
requestId: requestId,
},
'*',
);
setTimeout(() => {
window.removeEventListener('message', handleMessage);
reject(new Error('Request timed out'));
}, this.TIMEOUT_DURATION);
});
}
};