LibreChat/api/app/titleConvo.js

65 lines
2 KiB
JavaScript
Raw Normal View History

2023-03-02 13:52:41 -05:00
const { Configuration, OpenAIApi } = require('openai');
const _ = require('lodash');
2023-03-02 13:52:41 -05: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
};
return proxyConfig;
};
2023-03-13 15:55:18 +08:00
2023-03-31 03:22:57 +08:00
const titleConvo = async ({ endpoint, text, response }) => {
2023-03-15 15:21:04 -04:00
let title = 'New Chat';
const ChatGPTClient = (await import('@waylaidwanderer/chatgpt-api')).default;
2023-03-28 19:50:37 -04:00
try {
const instructionsPayload = {
role: 'system',
content: `Detect user language and write in the same language an extremely concise title for this conversation, which you must accurately detect. Write in the detected language. Title in 5 Words or Less. No Punctuation or Quotation. All first letters of every word should be capitalized and complete only the title in User Language only.
2023-03-28 19:50:37 -04:00
||>User:
"${text}"
||>Response:
"${JSON.stringify(response?.text)}"
||>Title:`
};
const options = {
reverseProxyUrl: process.env.OPENAI_REVERSE_PROXY || null,
proxy: process.env.PROXY || null
};
const titleGenClientOptions = JSON.parse(JSON.stringify(options));
titleGenClientOptions.modelOptions = {
model: 'gpt-3.5-turbo',
temperature: 0,
presence_penalty: 0,
frequency_penalty: 0
};
2023-03-15 15:21:04 -04:00
const titleGenClient = new ChatGPTClient(process.env.OPENAI_KEY, titleGenClientOptions);
const result = await titleGenClient.getCompletion([instructionsPayload], null);
title = result.choices[0].message.content.replace(/\s+/g, ' ').trim();
2023-03-15 15:21:04 -04:00
} 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 15:21:04 -04:00
module.exports = throttledTitleConvo;