forked from ameramayreh/conversational-app-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConversationalAppEngine.js
219 lines (186 loc) · 8 KB
/
ConversationalAppEngine.js
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import { Configuration, OpenAIApi } from "openai";
import * as fs from 'node:fs';
const DATA_DIRECTORY_PATH = './data/';
const APP_RESOURCES_DIRECTORY_PATH = './app-resources/';
const APP_RESOURCES_WEB_BASE_PATH = '/app-resources/'
export class ConversationalAppEngine {
userMessages = {};
openai = null;
defaultMessages = [];
constructor(appClass) {
this.openai = new OpenAIApi(new Configuration({
apiKey: process.env.OPENAI_API_KEY
}));
const context = {
openai: this.openai
};
this.app = new appClass(context);
context.filesDirectoryPath = APP_RESOURCES_DIRECTORY_PATH + this.getFilesDirectoryName() + '/';
context.webBasePath = APP_RESOURCES_WEB_BASE_PATH + this.getFilesDirectoryName() + '/';
this.defaultMessages = this.app.getDefaultMessages();
if (!fs.existsSync(DATA_DIRECTORY_PATH)) {
fs.mkdirSync(DATA_DIRECTORY_PATH);
}
if (!fs.existsSync(APP_RESOURCES_DIRECTORY_PATH + this.getFilesDirectoryName())) {
fs.mkdirSync(APP_RESOURCES_DIRECTORY_PATH + this.getFilesDirectoryName());
}
this.loadData();
}
loadData() {
fs.readFile(this.getDataFileName(), 'utf8', (error, data) => {
if (error) {
console.log("Error: " + error);
} else {
this.userMessages = JSON.parse(data);
}
});
}
getDataFileName() {
return DATA_DIRECTORY_PATH + this.app.constructor.name + '-data.json';
}
getFilesDirectoryName() {
return this.app.constructor.name;
}
storeData() {
const json = JSON.stringify(this.userMessages, null, 2);
fs.writeFile(this.getDataFileName(), json, 'utf8', (error) => {
if (error) {
console.log("Error: " + error);
}
});
}
getUserChats(userid) {
const user = this.getUser(userid);
const chats = [];
for (const chatid of Object.keys(user)) {
const chat = user[chatid];
chats.push({ name: chat.name, id: chatid });
}
return chats;
}
getUser(userId) {
return this.userMessages[userId] = this.userMessages[userId] || {};
}
getChat(user, chatId) {
return user[chatId] = user[chatId] || { messages: [...this.defaultMessages], name: "", usage: [], state: {} };
}
async getUserChat(userid, chatid) {
const user = this.getUser(userid);
const chat = this.getChat(user, chatid);
const chatMessages = [];
let i = 0;
for (const message of chat.messages.slice(this.defaultMessages.length)) {
if (message.role == 'function' || message.function_call) {
continue;
}
const msg = {
message: message.role == 'assistant' ? await Promise.resolve(this.app.getTextMessage(message.content)) : message.content,
appContent: message.role == 'assistant' ? await Promise.resolve(this.app.getAppContent(message.content)) : message.content
};
if (message.role == 'assistant') {
msg.usage = chat.usage[i++];
}
chatMessages.push(msg);
}
return chatMessages;
}
deleteUserChat(userid, chatid) {
const user = this.getUser(userid);
delete user[chatid];
this.storeData();
}
postMessage(userid, chatid, message, callback) {
const user = this.getUser(userid);
const chat = this.getChat(user, chatid);
const messages = chat.messages;
const availableFunctions = this.app.getAvailableFunctions();
messages.push({ "role": "user", "content": message });
try {
this.openai.createChatCompletion({
model: this.app.model,
temperature: this.app.temperature,
messages: messages,
functions: availableFunctions
}).then(async (completion) => {
console.log("Received from ChatGPT: ");
console.log(JSON.stringify(completion.data, null, 2));
let responseMessageObject = completion.data.choices[0].message;
if (responseMessageObject.function_call) {
({ responseMessageObject, completion } = await this.handleFunctionCall(responseMessageObject, availableFunctions, completion, messages));
}
const responseMessage = responseMessageObject.content;
let chatName = await Promise.resolve(this.app.getChatNameFromMessage(responseMessage, message, chat));
if (chatName) {
chat.name = chatName;
}
messages.push(responseMessageObject);
chat.usage.push(completion.data.usage);
this.storeData();
const response = {
status: 'success',
message: await Promise.resolve(this.app.getTextMessage(responseMessage)),
appContent: await Promise.resolve(this.app.getAppContent(responseMessage)),
chatName: chat.name,
usage: completion.data.usage
};
callback(null, response);
}).catch(error => {
messages.pop();
console.error(error);
callback({
message: error?.message || error
}, null);
});
} catch (error) {
messages.pop();
console.error(error);
callback({
message: error.message || error
}, null);
}
}
async handleFunctionCall(responseMessageObject, availableFunctions, completion, messages) {
while (responseMessageObject.function_call) {
const functionName = responseMessageObject.function_call.name;
const hallucinatedFunctionMessages = [];
if (availableFunctions.find(f => f.name == functionName)) {
messages.push(responseMessageObject);
const functionParams = JSON.parse(responseMessageObject.function_call.arguments || '{}');
const functionResponse = await Promise.resolve(this.app.callFunction(responseMessageObject.function_call.name, functionParams));
messages.push({
"role": "function",
"name": functionName,
"content": functionResponse || 'none'
});
} else {
hallucinatedFunctionMessages.push(responseMessageObject);
hallucinatedFunctionMessages.push({
"role": "function",
"name": functionName,
"content": 'none'
});
}
completion = await Promise.resolve(this.openai.createChatCompletion({
model: this.app.model,
temperature: this.app.temperature,
messages: [...messages, ...hallucinatedFunctionMessages],
functions: availableFunctions
}));
console.log("Received from ChatGPT: ");
console.log(JSON.stringify(completion.data));
responseMessageObject = completion.data.choices[0].message;
}
return { responseMessageObject, completion };
}
substituteText(text) {
text = text.replaceAll('{{APP_NAME}}', this.app.appName);
text = text.replaceAll('{{CHATS_LIST_TITLE}}', this.app.chatListTitle);
text = text.replaceAll('{{NEW_CHAT}}', this.app.newChatLabel);
text = text.replaceAll('{{CONTENT_PREVIEW_PLACE_HOLDER}}', this.app.contentPreviewPlaceholder);
text = text.replaceAll('{{CHAT_START_INSTRUCTIONS}}', this.app.chatStartInstruction);
text = text.replaceAll('{{NEW_CHAT_NAME}}', this.app.newChatName);
text = text.replaceAll('{{APP_ICON}}', this.app.appIconName);
text = text.replaceAll('{{MAX_TOKENS}}', this.app.modelMaxTokens);
return text;
}
}