2023-02-04 20:09:02 -05:00
|
|
|
require('dotenv').config();
|
2023-02-05 19:41:24 -05:00
|
|
|
const Keyv = require('keyv');
|
2023-02-06 14:57:47 -05:00
|
|
|
const { Configuration, OpenAIApi } = require('openai');
|
2023-02-05 19:41:24 -05:00
|
|
|
const messageStore = new Keyv(process.env.MONGODB_URI, { namespace: 'chatgpt' });
|
2023-02-04 20:09:02 -05:00
|
|
|
|
2023-02-05 19:41:24 -05:00
|
|
|
const ask = async (question, progressCallback, convo) => {
|
2023-02-04 20:49:01 -05:00
|
|
|
const { ChatGPTAPI } = await import('chatgpt');
|
2023-02-05 19:41:24 -05:00
|
|
|
const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_KEY, messageStore });
|
|
|
|
|
let options = {
|
2023-02-06 13:28:21 -05:00
|
|
|
onProgress: async (partialRes) => {
|
2023-02-05 19:41:24 -05:00
|
|
|
if (partialRes.text.length > 0) {
|
2023-02-06 13:28:21 -05:00
|
|
|
await progressCallback(partialRes);
|
2023-02-05 19:41:24 -05:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (!!convo.parentMessageId && !!convo.conversationId) {
|
|
|
|
|
options = { ...options, ...convo };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const res = await api.sendMessage(question, options);
|
2023-02-04 20:49:01 -05:00
|
|
|
return res;
|
|
|
|
|
};
|
2023-02-04 20:09:02 -05:00
|
|
|
|
2023-02-06 14:57:47 -05:00
|
|
|
const titleConversation = async (message, response) => {
|
|
|
|
|
const configuration = new Configuration({
|
|
|
|
|
apiKey: process.env.OPENAI_KEY
|
|
|
|
|
});
|
|
|
|
|
const openai = new OpenAIApi(configuration);
|
|
|
|
|
const completion = await openai.createCompletion({
|
|
|
|
|
model: 'text-davinci-002',
|
|
|
|
|
prompt: `Make a short title (goal: 5 words or less) in title case summarizing this conversation:\nuser:"${message}"\nGPT:"${response}"\nTitle: `
|
|
|
|
|
});
|
|
|
|
|
console.log(completion.data.choices[0].text);
|
|
|
|
|
return completion.data.choices[0].text.replace(/\n/g, '');
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
module.exports = { ask, titleConversation };
|