-
Notifications
You must be signed in to change notification settings - Fork 0
/
openAi.js
53 lines (45 loc) · 1.42 KB
/
openAi.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
const { encode } = require("gpt-3-encoder");
const langdetect = require("langdetect");
function countTokens(text) {
const tokens = encode(text);
return tokens.length;
}
async function getChatCompletion(message) {
const url = "https://api.openai.com/v1/chat/completions";
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
};
const data = {
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: process.env.SYSTEM_PROMPT },
...message,
],
};
try {
const tokens = countTokens(
data.messages.reduce((final, current) => {
return final + current.content;
}, ""),
);
if (tokens > 3000) {
if (message.length > 1) {
return "Sorry, I can't respond anymore in this thread. 🙅♂️ Please start a new thread to begin a fresh conversation. 🌟💬";
}
return '📝 "Oops, message too long! Can you be briefer, please? 😅"';
}
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(data),
});
const json = await response.json();
const chatgptResponse = json?.choices?.[0].message?.content;
return { lang: langdetect.detectOne(chatgptResponse), chatgptResponse };
} catch (error) {
console.error("Error:", error.message);
return null;
}
}
module.exports = { getChatCompletion, countTokens };