2023-03-02 13:52:41 -05:00
const { Configuration , OpenAIApi } = require ( 'openai' ) ;
2023-03-15 12:47:30 -04:00
const _ = require ( 'lodash' ) ;
2023-03-02 13:52:41 -05:00
2023-03-22 09:38:38 -04:00
const proxyEnvToAxiosProxy = proxyString => {
2023-03-13 15:55:18 +08:00
if ( ! proxyString ) return null ;
const regex = /^([^:]+):\/\/(?:([^:@]*):?([^:@]*)@)?([^:]+)(?::(\d+))?/ ;
const [ , protocol , username , password , host , port ] = proxyString . match ( regex ) ;
const proxyConfig = {
protocol ,
host ,
port : port ? parseInt ( port ) : undefined ,
auth : username && password ? { username , password } : undefined
} ;
2023-03-15 12:47:30 -04:00
return proxyConfig ;
} ;
2023-03-13 15:55:18 +08:00
2023-03-15 15:21:04 -04:00
const titleConvo = async ( { model , text , response } ) => {
let title = 'New Chat' ;
2023-03-22 09:38:38 -04:00
const request = {
model : 'gpt-3.5-turbo' ,
messages : [
{
role : 'system' ,
content :
2023-03-29 01:50:57 +08:00
"You are a title-generator with one job: giving a conversation, detect the language and titling the conversation provided by a user, using the same language. The requirement are: 1. If possible, generate in 5 words or less, 2. Using title case, 3. must give the title using the language as the user said. 4. Don't refer to the participants of the conversation. 5. Do not include punctuation or quotation marks. 6. Your response should be in title case, exclusively containing the title. 7. don't say anything except the title."
2023-03-22 09:38:38 -04:00
} ,
{
role : 'user' ,
2023-03-29 01:50:57 +08:00
content : ` User: \n " ${ text } " \n \n ${ model } : \n " ${ JSON . stringify ( response ? . text ) } " \n \n `
2023-03-22 09:38:38 -04:00
}
] ,
temperature : 0 ,
presence _penalty : 0 ,
frequency _penalty : 0
} ;
// console.log('REQUEST', request);
2023-03-15 15:21:04 -04:00
try {
const configuration = new Configuration ( {
apiKey : process . env . OPENAI _KEY
} ) ;
const openai = new OpenAIApi ( configuration ) ;
2023-03-22 09:38:38 -04:00
const completion = await openai . createChatCompletion ( request , {
proxy : proxyEnvToAxiosProxy ( process . env . PROXY || null )
} ) ;
2023-03-15 15:21:04 -04:00
//eslint-disable-next-line
title = completion . data . choices [ 0 ] . message . content . replace ( /["\.]/g , '' ) ;
} catch ( e ) {
console . error ( e ) ;
console . log ( 'There was an issue generating title, see error above' ) ;
}
console . log ( 'CONVERSATION TITLE' , title ) ;
return title ;
2023-03-02 13:52:41 -05:00
} ;
2023-03-15 15:21:04 -04:00
const throttledTitleConvo = _ . throttle ( titleConvo , 1000 ) ;
2023-03-15 12:47:30 -04:00
2023-03-15 15:21:04 -04:00
module . exports = throttledTitleConvo ;