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-12 16:48:15 -05:00
const titleConvo = async ( message , response ) => {
2023-02-06 14:57:47 -05:00
const configuration = new Configuration ( {
apiKey : process . env . OPENAI _KEY
} ) ;
const openai = new OpenAIApi ( configuration ) ;
const completion = await openai . createCompletion ( {
model : 'text-davinci-002' ,
2023-02-06 21:17:46 -05:00
prompt : ` Write a short title in title case, ideally in 5 words or less, and do not refer to the user or GPT, that summarizes this conversation: \n User:" ${ message } " \n GPT:" ${ response } " \n Title: `
2023-02-06 14:57:47 -05:00
} ) ;
2023-02-12 16:48:15 -05:00
2023-02-06 14:57:47 -05:00
return completion . data . choices [ 0 ] . text . replace ( /\n/g , '' ) ;
} ;
2023-02-12 16:48:15 -05:00
module . exports = { ask , titleConvo } ;