mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-28 06:08:50 +01:00
refactor: Encrypt & Expire User Provided Keys, feat: Rate Limiting (#874)
* docs: make_your_own.md formatting fix for mkdocs * feat: add express-mongo-sanitize feat: add login/registration rate limiting * chore: remove unnecessary console log * wip: remove token handling from localStorage to encrypted DB solution * refactor: minor change to UserService * fix mongo query and add keys route to server * fix backend controllers and simplify schema/crud * refactor: rename token to key to separate from access/refresh tokens, setTokenDialog -> setKeyDialog * refactor(schemas): TEndpointOption token -> key * refactor(api): use new encrypted key retrieval system * fix(SetKeyDialog): fix key prop error * fix(abortMiddleware): pass random UUID if messageId is not generated yet for proper error display on frontend * fix(getUserKey): wrong prop passed in arg, adds error handling * fix: prevent message without conversationId from saving to DB, prevents branching on the frontend to a new top-level branch * refactor: change wording of multiple display messages * refactor(checkExpiry -> checkUserKeyExpiry): move to UserService file * fix: type imports from common * refactor(SubmitButton): convert to TS * refactor(key.ts): change localStorage map key name * refactor: add new custom tailwind classes to better match openAI colors * chore: remove unnecessary warning and catch ScreenShot error * refactor: move userKey frontend logic to hooks and remove use of localStorage and instead query the DB * refactor: invalidate correct query key, memoize userKey hook, conditionally render SetKeyDialog to avoid unnecessary calls, refactor SubmitButton props and useEffect for showing 'provide key first' * fix(SetKeyDialog): use enum-like object for expiry values feat(Dropdown): add optionsClassName to dynamically change dropdown options container classes * fix: handle edge case where user had provided a key but the server changes to env variable for keys * refactor(OpenAI/titleConvo): move titling to client to retain authorized credentials in message lifecycle for titling * fix(azure): handle user_provided keys correctly for azure * feat: send user Id to OpenAI to differentiate users in completion requests * refactor(OpenAI/titleConvo): adding tokens helps minimize LLM from using the language in title response * feat: add delete endpoint for keys * chore: remove throttling of title * feat: add 'Data controls' to Settings, add 'Revoke' keys feature in Key Dialog and Data controls * refactor: reorganize PluginsClient files in langchain format * feat: use langchain for titling convos * chore: cleanup titling convo, with fallback to original method, escape braces, use only snippet for language detection * refactor: move helper functions to appropriate langchain folders for reusability * fix: userProvidesKey handling for gptPlugins * fix: frontend handling of plugins key * chore: cleanup logging and ts-ignore SSE * fix: forwardRef misuse in DangerButton * fix(GoogleConfig/FileUpload): localize errors and simplify validation with zod * fix: cleanup google logging and fix user provided key handling * chore: remove titling from google * chore: removing logging from browser endpoint * wip: fix menu flicker * feat: useLocalStorage hook * feat: add Tooltip for UI * refactor(EndpointMenu): utilize Tooltip and useLocalStorage, remove old 'New Chat' slide-over * fix(e2e): use testId for endpoint menu trigger * chore: final touches to EndpointMenu before future refactor to declutter component * refactor(localization): change select endpoint to open menu and add translations * chore: add final prop to error message response * ci: minor edits to facilitate testing * ci: new e2e test which tests for new key setting/revoking features
This commit is contained in:
parent
64f1557852
commit
4ca43fb53d
122 changed files with 1933 additions and 966 deletions
|
|
@ -1,5 +1,6 @@
|
|||
require('dotenv').config();
|
||||
const { KeyvFile } = require('keyv-file');
|
||||
const { getUserKey, checkUserKeyExpiry } = require('../server/services/UserService');
|
||||
|
||||
const askBing = async ({
|
||||
text,
|
||||
|
|
@ -13,9 +14,21 @@ const askBing = async ({
|
|||
clientId,
|
||||
invocationId,
|
||||
toneStyle,
|
||||
token,
|
||||
key: expiresAt,
|
||||
onProgress,
|
||||
userId,
|
||||
}) => {
|
||||
const isUserProvided = process.env.BINGAI_TOKEN === 'user_provided';
|
||||
|
||||
let key = null;
|
||||
if (expiresAt && isUserProvided) {
|
||||
checkUserKeyExpiry(
|
||||
expiresAt,
|
||||
'Your BingAI Cookies have expired. Please provide your cookies again.',
|
||||
);
|
||||
key = await getUserKey({ userId, name: 'bingAI' });
|
||||
}
|
||||
|
||||
const { BingAIClient } = await import('@waylaidwanderer/chatgpt-api');
|
||||
const store = {
|
||||
store: new KeyvFile({ filename: './data/cache.json' }),
|
||||
|
|
@ -24,9 +37,9 @@ const askBing = async ({
|
|||
const bingAIClient = new BingAIClient({
|
||||
// "_U" cookie from bing.com
|
||||
// userToken:
|
||||
// process.env.BINGAI_TOKEN == 'user_provided' ? token : process.env.BINGAI_TOKEN ?? null,
|
||||
// isUserProvided ? key : process.env.BINGAI_TOKEN ?? null,
|
||||
// If the above doesn't work, provide all your cookies as a string instead
|
||||
cookies: process.env.BINGAI_TOKEN == 'user_provided' ? token : process.env.BINGAI_TOKEN ?? null,
|
||||
cookies: isUserProvided ? key : process.env.BINGAI_TOKEN ?? null,
|
||||
debug: false,
|
||||
cache: store,
|
||||
host: process.env.BINGAI_HOST || null,
|
||||
|
|
|
|||
|
|
@ -1,17 +1,29 @@
|
|||
require('dotenv').config();
|
||||
const { KeyvFile } = require('keyv-file');
|
||||
const { getUserKey, checkUserKeyExpiry } = require('../server/services/UserService');
|
||||
|
||||
const browserClient = async ({
|
||||
text,
|
||||
parentMessageId,
|
||||
conversationId,
|
||||
model,
|
||||
token,
|
||||
key: expiresAt,
|
||||
onProgress,
|
||||
onEventMessage,
|
||||
abortController,
|
||||
userId,
|
||||
}) => {
|
||||
const isUserProvided = process.env.CHATGPT_TOKEN === 'user_provided';
|
||||
|
||||
let key = null;
|
||||
if (expiresAt && isUserProvided) {
|
||||
checkUserKeyExpiry(
|
||||
expiresAt,
|
||||
'Your ChatGPT Access Token has expired. Please provide your token again.',
|
||||
);
|
||||
key = await getUserKey({ userId, name: 'chatGPTBrowser' });
|
||||
}
|
||||
|
||||
const { ChatGPTBrowserClient } = await import('@waylaidwanderer/chatgpt-api');
|
||||
const store = {
|
||||
store: new KeyvFile({ filename: './data/cache.json' }),
|
||||
|
|
@ -20,13 +32,12 @@ const browserClient = async ({
|
|||
const clientOptions = {
|
||||
// Warning: This will expose your access token to a third party. Consider the risks before using this.
|
||||
reverseProxyUrl:
|
||||
process.env.CHATGPT_REVERSE_PROXY || 'https://ai.fakeopen.com/api/conversation',
|
||||
process.env.CHATGPT_REVERSE_PROXY ?? 'https://ai.fakeopen.com/api/conversation',
|
||||
// Access token from https://chat.openai.com/api/auth/session
|
||||
accessToken:
|
||||
process.env.CHATGPT_TOKEN == 'user_provided' ? token : process.env.CHATGPT_TOKEN ?? null,
|
||||
accessToken: isUserProvided ? key : process.env.CHATGPT_TOKEN ?? null,
|
||||
model: model,
|
||||
debug: false,
|
||||
proxy: process.env.PROXY || null,
|
||||
proxy: process.env.PROXY ?? null,
|
||||
user: userId,
|
||||
};
|
||||
|
||||
|
|
@ -37,8 +48,6 @@ const browserClient = async ({
|
|||
options = { ...options, parentMessageId, conversationId };
|
||||
}
|
||||
|
||||
console.log('gptBrowser clientOptions', clientOptions);
|
||||
|
||||
if (parentMessageId === '00000000-0000-0000-0000-000000000000') {
|
||||
delete options.conversationId;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@ const TextStream = require('./TextStream');
|
|||
const { RecursiveCharacterTextSplitter } = require('langchain/text_splitter');
|
||||
const { ChatOpenAI } = require('langchain/chat_models/openai');
|
||||
const { loadSummarizationChain } = require('langchain/chains');
|
||||
const { refinePrompt } = require('./prompts/refinePrompt');
|
||||
const { getConvo, getMessages, saveMessage, updateMessage, saveConvo } = require('../../models');
|
||||
const { addSpaceIfNeeded } = require('../../server/utils');
|
||||
const { refinePrompt } = require('./prompts');
|
||||
|
||||
class BaseClient {
|
||||
constructor(apiKey, options = {}) {
|
||||
|
|
@ -55,6 +55,7 @@ class BaseClient {
|
|||
|
||||
const { isEdited, isContinued } = opts;
|
||||
const user = opts.user ?? null;
|
||||
this.user = user;
|
||||
const saveOptions = this.getSaveOptions();
|
||||
this.abortController = opts.abortController ?? new AbortController();
|
||||
const conversationId = opts.conversationId ?? crypto.randomUUID();
|
||||
|
|
@ -407,7 +408,6 @@ class BaseClient {
|
|||
|
||||
const { generation = '' } = opts;
|
||||
|
||||
this.user = user;
|
||||
// It's not necessary to push to currentMessages
|
||||
// depending on subclass implementation of handling messages
|
||||
// When this is an edit, all messages are already in currentMessages, both user and response
|
||||
|
|
@ -600,6 +600,14 @@ class BaseClient {
|
|||
// Sum the number of tokens in all properties and add `tokensPerMessage` for metadata
|
||||
return propertyTokenCounts.reduce((a, b) => a + b, tokensPerMessage);
|
||||
}
|
||||
|
||||
async sendPayload(payload, opts = {}) {
|
||||
if (opts && typeof opts === 'object') {
|
||||
this.setOptions(opts);
|
||||
}
|
||||
|
||||
return await this.sendCompletion(payload, opts);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = BaseClient;
|
||||
|
|
|
|||
|
|
@ -29,7 +29,8 @@ class GoogleClient extends BaseClient {
|
|||
|
||||
jwtClient.authorize((err) => {
|
||||
if (err) {
|
||||
console.log(err);
|
||||
console.error('Error: jwtClient failed to authorize');
|
||||
console.error(err.message);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
|
@ -247,7 +248,8 @@ class GoogleClient extends BaseClient {
|
|||
console.debug(result);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
console.error('Error: failed to send completion to Google');
|
||||
console.error(err.message);
|
||||
}
|
||||
|
||||
if (!blocked) {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ const {
|
|||
get_encoding: getEncoding,
|
||||
} = require('@dqbd/tiktoken');
|
||||
const { maxTokensMap, genAzureChatCompletion } = require('../../utils');
|
||||
const { runTitleChain } = require('./chains');
|
||||
const { createLLM } = require('./llm');
|
||||
|
||||
// Cache to store Tiktoken instances
|
||||
const tokenizersCache = {};
|
||||
|
|
@ -105,6 +107,7 @@ class OpenAIClient extends BaseClient {
|
|||
|
||||
if (this.options.reverseProxyUrl) {
|
||||
this.completionsUrl = this.options.reverseProxyUrl;
|
||||
this.langchainProxy = this.options.reverseProxyUrl.match(/.*v1/)[0];
|
||||
} else if (isChatGptModel) {
|
||||
this.completionsUrl = 'https://api.openai.com/v1/chat/completions';
|
||||
} else {
|
||||
|
|
@ -116,7 +119,7 @@ class OpenAIClient extends BaseClient {
|
|||
}
|
||||
|
||||
if (this.azureEndpoint && this.options.debug) {
|
||||
console.debug(`Using Azure endpoint: ${this.azureEndpoint}`, this.azure);
|
||||
console.debug('Using Azure endpoint');
|
||||
}
|
||||
|
||||
return this;
|
||||
|
|
@ -315,6 +318,7 @@ class OpenAIClient extends BaseClient {
|
|||
let reply = '';
|
||||
let result = null;
|
||||
let streamResult = null;
|
||||
this.modelOptions.user = this.user;
|
||||
if (typeof opts.onProgress === 'function') {
|
||||
await this.getCompletion(
|
||||
payload,
|
||||
|
|
@ -373,6 +377,64 @@ class OpenAIClient extends BaseClient {
|
|||
content: response.text,
|
||||
});
|
||||
}
|
||||
|
||||
async titleConvo({ text, responseText = '' }) {
|
||||
let title = 'New Chat';
|
||||
const convo = `||>User:
|
||||
"${text}"
|
||||
||>Response:
|
||||
"${JSON.stringify(responseText)}"`;
|
||||
|
||||
const modelOptions = {
|
||||
model: 'gpt-3.5-turbo-0613',
|
||||
temperature: 0.2,
|
||||
presence_penalty: 0,
|
||||
frequency_penalty: 0,
|
||||
max_tokens: 16,
|
||||
};
|
||||
|
||||
const configOptions = {};
|
||||
|
||||
if (this.langchainProxy) {
|
||||
configOptions.basePath = this.langchainProxy;
|
||||
}
|
||||
|
||||
try {
|
||||
const llm = createLLM({
|
||||
modelOptions,
|
||||
configOptions,
|
||||
openAIApiKey: this.apiKey,
|
||||
azure: this.azure,
|
||||
});
|
||||
|
||||
title = await runTitleChain({ llm, text, convo });
|
||||
} catch (e) {
|
||||
console.error(e.message);
|
||||
console.log('There was an issue generating title with LangChain, trying the old method...');
|
||||
modelOptions.model = 'gpt-3.5-turbo';
|
||||
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. Do not mention the language. All first letters of every word should be capitalized and write the title in User Language only.
|
||||
|
||||
${convo}
|
||||
|
||||
||>Title:`,
|
||||
},
|
||||
];
|
||||
|
||||
try {
|
||||
title = (await this.sendPayload(instructionsPayload, { modelOptions })).replaceAll('"', '');
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
console.log('There was another issue generating the title, see error above.');
|
||||
}
|
||||
}
|
||||
|
||||
console.log('CONVERSATION TITLE', title);
|
||||
return title;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OpenAIClient;
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
const OpenAIClient = require('./OpenAIClient');
|
||||
const { CallbackManager } = require('langchain/callbacks');
|
||||
const { HumanChatMessage, AIChatMessage } = require('langchain/schema');
|
||||
const { initializeCustomAgent, initializeFunctionsAgent } = require('./agents/');
|
||||
const { addImages, createLLM, buildErrorInput, buildPromptPrefix } = require('./agents/methods/');
|
||||
const { SelfReflectionTool } = require('./tools/');
|
||||
const { initializeCustomAgent, initializeFunctionsAgent } = require('./agents');
|
||||
const { addImages, buildErrorInput, buildPromptPrefix } = require('./output_parsers');
|
||||
const { SelfReflectionTool } = require('./tools');
|
||||
const { loadTools } = require('./tools/util');
|
||||
const { createLLM } = require('./llm');
|
||||
|
||||
class PluginsClient extends OpenAIClient {
|
||||
constructor(apiKey, options = {}) {
|
||||
|
|
@ -28,9 +29,9 @@ class PluginsClient extends OpenAIClient {
|
|||
super.setOptions(options);
|
||||
this.isGpt3 = this.modelOptions.model.startsWith('gpt-3');
|
||||
|
||||
if (this.options.reverseProxyUrl) {
|
||||
this.langchainProxy = this.options.reverseProxyUrl.match(/.*v1/)[0];
|
||||
}
|
||||
// if (this.options.reverseProxyUrl) {
|
||||
// this.langchainProxy = this.options.reverseProxyUrl.match(/.*v1/)[0];
|
||||
// }
|
||||
}
|
||||
|
||||
getSaveOptions() {
|
||||
|
|
|
|||
5
api/app/clients/chains/index.js
Normal file
5
api/app/clients/chains/index.js
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
const runTitleChain = require('./runTitleChain');
|
||||
|
||||
module.exports = {
|
||||
runTitleChain,
|
||||
};
|
||||
43
api/app/clients/chains/runTitleChain.js
Normal file
43
api/app/clients/chains/runTitleChain.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
const { z } = require('zod');
|
||||
const { langPrompt, createTitlePrompt } = require('../prompts');
|
||||
const { escapeBraces, getSnippet } = require('../output_parsers');
|
||||
const { createStructuredOutputChainFromZod } = require('langchain/chains/openai_functions');
|
||||
|
||||
const langSchema = z.object({
|
||||
language: z.string().describe('The language of the input text (full noun, no abbreviations).'),
|
||||
});
|
||||
|
||||
const createLanguageChain = ({ llm }) =>
|
||||
createStructuredOutputChainFromZod(langSchema, {
|
||||
prompt: langPrompt,
|
||||
llm,
|
||||
// verbose: true,
|
||||
});
|
||||
|
||||
const titleSchema = z.object({
|
||||
title: z.string().describe('The title-cased title of the conversation in the given language.'),
|
||||
});
|
||||
const createTitleChain = ({ llm, convo }) => {
|
||||
const titlePrompt = createTitlePrompt({ convo });
|
||||
return createStructuredOutputChainFromZod(titleSchema, {
|
||||
prompt: titlePrompt,
|
||||
llm,
|
||||
// verbose: true,
|
||||
});
|
||||
};
|
||||
|
||||
const runTitleChain = async ({ llm, text, convo }) => {
|
||||
let snippet = text;
|
||||
try {
|
||||
snippet = getSnippet(text);
|
||||
} catch (e) {
|
||||
console.log('Error getting snippet of text for titleChain');
|
||||
console.log(e);
|
||||
}
|
||||
const languageChain = createLanguageChain({ llm });
|
||||
const titleChain = createTitleChain({ llm, convo: escapeBraces(convo) });
|
||||
const { language } = await languageChain.run(snippet);
|
||||
return (await titleChain.run(language)).title;
|
||||
};
|
||||
|
||||
module.exports = runTitleChain;
|
||||
5
api/app/clients/llm/index.js
Normal file
5
api/app/clients/llm/index.js
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
const createLLM = require('./createLLM');
|
||||
|
||||
module.exports = {
|
||||
createLLM,
|
||||
};
|
||||
38
api/app/clients/output_parsers/handleInputs.js
Normal file
38
api/app/clients/output_parsers/handleInputs.js
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
// Escaping curly braces is necessary for LangChain to correctly process the prompt
|
||||
function escapeBraces(str) {
|
||||
return str
|
||||
.replace(/({{2,})|(}{2,})/g, (match) => `${match[0]}`)
|
||||
.replace(/{|}/g, (match) => `${match}${match}`);
|
||||
}
|
||||
|
||||
function getSnippet(text) {
|
||||
let limit = 50;
|
||||
let splitText = escapeBraces(text).split(' ');
|
||||
|
||||
if (splitText.length === 1 && splitText[0].length > limit) {
|
||||
return splitText[0].substring(0, limit);
|
||||
}
|
||||
|
||||
let result = '';
|
||||
let spaceCount = 0;
|
||||
|
||||
for (let i = 0; i < splitText.length; i++) {
|
||||
if (result.length + splitText[i].length <= limit) {
|
||||
result += splitText[i] + ' ';
|
||||
spaceCount++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
||||
if (spaceCount == 10) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result.trim();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
escapeBraces,
|
||||
getSnippet,
|
||||
};
|
||||
|
|
@ -1,8 +1,4 @@
|
|||
const {
|
||||
instructions,
|
||||
imageInstructions,
|
||||
errorInstructions,
|
||||
} = require('../../prompts/instructions');
|
||||
const { instructions, imageInstructions, errorInstructions } = require('../prompts');
|
||||
|
||||
function getActions(actions = [], functionsAgent = false) {
|
||||
let output = 'Internal thoughts & actions taken:\n"';
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
const addImages = require('./addImages');
|
||||
const createLLM = require('./createLLM');
|
||||
const handleInputs = require('./handleInputs');
|
||||
const handleOutputs = require('./handleOutputs');
|
||||
|
||||
module.exports = {
|
||||
addImages,
|
||||
createLLM,
|
||||
...handleInputs,
|
||||
...handleOutputs,
|
||||
};
|
||||
9
api/app/clients/prompts/index.js
Normal file
9
api/app/clients/prompts/index.js
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
const instructions = require('./instructions');
|
||||
const titlePrompts = require('./titlePrompts');
|
||||
const refinePrompts = require('./refinePrompts');
|
||||
|
||||
module.exports = {
|
||||
...refinePrompts,
|
||||
...instructions,
|
||||
...titlePrompts,
|
||||
};
|
||||
33
api/app/clients/prompts/titlePrompts.js
Normal file
33
api/app/clients/prompts/titlePrompts.js
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
const {
|
||||
ChatPromptTemplate,
|
||||
SystemMessagePromptTemplate,
|
||||
HumanMessagePromptTemplate,
|
||||
} = require('langchain/prompts');
|
||||
|
||||
const langPrompt = new ChatPromptTemplate({
|
||||
promptMessages: [
|
||||
SystemMessagePromptTemplate.fromTemplate('Detect the language used in the following text.'),
|
||||
HumanMessagePromptTemplate.fromTemplate('{inputText}'),
|
||||
],
|
||||
inputVariables: ['inputText'],
|
||||
});
|
||||
|
||||
const createTitlePrompt = ({ convo }) => {
|
||||
const titlePrompt = new ChatPromptTemplate({
|
||||
promptMessages: [
|
||||
SystemMessagePromptTemplate.fromTemplate(
|
||||
`Write a concise title for this conversation in the given language. Title in 5 Words or Less. No Punctuation or Quotation. All first letters of every word must be capitalized (resembling title-case), written in the given Language.
|
||||
${convo}`,
|
||||
),
|
||||
HumanMessagePromptTemplate.fromTemplate('Language: {language}'),
|
||||
],
|
||||
inputVariables: ['language'],
|
||||
});
|
||||
|
||||
return titlePrompt;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
langPrompt,
|
||||
createTitlePrompt,
|
||||
};
|
||||
|
|
@ -1,13 +1,11 @@
|
|||
const { browserClient } = require('./chatgpt-browser');
|
||||
const { askBing } = require('./bingai');
|
||||
const clients = require('./clients');
|
||||
const titleConvo = require('./titleConvo');
|
||||
const titleConvoBing = require('./titleConvoBing');
|
||||
|
||||
module.exports = {
|
||||
browserClient,
|
||||
askBing,
|
||||
titleConvo,
|
||||
titleConvoBing,
|
||||
...clients,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,57 +0,0 @@
|
|||
const throttle = require('lodash/throttle');
|
||||
const { genAzureChatCompletion, getAzureCredentials } = require('../utils/');
|
||||
|
||||
const titleConvo = async ({ text, response, openAIApiKey, azure = false }) => {
|
||||
let title = 'New Chat';
|
||||
const ChatGPTClient = (await import('@waylaidwanderer/chatgpt-api')).default;
|
||||
|
||||
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.
|
||||
|
||||
||>User:
|
||||
"${text}"
|
||||
||>Response:
|
||||
"${JSON.stringify(response?.text)}"
|
||||
|
||||
||>Title:`,
|
||||
};
|
||||
|
||||
const options = {
|
||||
azure,
|
||||
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,
|
||||
};
|
||||
|
||||
let apiKey = openAIApiKey ?? process.env.OPENAI_API_KEY;
|
||||
|
||||
if (azure) {
|
||||
apiKey = process.env.AZURE_API_KEY;
|
||||
titleGenClientOptions.reverseProxyUrl = genAzureChatCompletion(getAzureCredentials());
|
||||
}
|
||||
|
||||
const titleGenClient = new ChatGPTClient(apiKey, titleGenClientOptions);
|
||||
const result = await titleGenClient.getCompletion([instructionsPayload], null);
|
||||
title = result.choices[0].message.content.replace(/\s+/g, ' ').replaceAll('"', '').trim();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
console.log('There was an issue generating title, see error above');
|
||||
}
|
||||
|
||||
console.log('CONVERSATION TITLE', title);
|
||||
return title;
|
||||
};
|
||||
|
||||
const throttledTitleConvo = throttle(titleConvo, 1000);
|
||||
|
||||
module.exports = throttledTitleConvo;
|
||||
|
|
@ -21,6 +21,9 @@ module.exports = {
|
|||
model = null,
|
||||
}) {
|
||||
try {
|
||||
if (!conversationId) {
|
||||
return console.log('Message not saved: no conversationId');
|
||||
}
|
||||
// may also need to update the conversation here
|
||||
await Message.findOneAndUpdate(
|
||||
{ messageId },
|
||||
|
|
|
|||
|
|
@ -3,97 +3,13 @@ const bcrypt = require('bcryptjs');
|
|||
const jwt = require('jsonwebtoken');
|
||||
const Joi = require('joi');
|
||||
const DebugControl = require('../utils/debug.js');
|
||||
const userSchema = require('./schema/userSchema.js');
|
||||
|
||||
function log({ title, parameters }) {
|
||||
DebugControl.log.functionName(title);
|
||||
DebugControl.log.parameters(parameters);
|
||||
}
|
||||
|
||||
const Session = mongoose.Schema({
|
||||
refreshToken: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
});
|
||||
|
||||
const userSchema = mongoose.Schema(
|
||||
{
|
||||
name: {
|
||||
type: String,
|
||||
},
|
||||
username: {
|
||||
type: String,
|
||||
lowercase: true,
|
||||
default: '',
|
||||
},
|
||||
email: {
|
||||
type: String,
|
||||
required: [true, 'can\'t be blank'],
|
||||
lowercase: true,
|
||||
unique: true,
|
||||
match: [/\S+@\S+\.\S+/, 'is invalid'],
|
||||
index: true,
|
||||
},
|
||||
emailVerified: {
|
||||
type: Boolean,
|
||||
required: true,
|
||||
default: false,
|
||||
},
|
||||
password: {
|
||||
type: String,
|
||||
trim: true,
|
||||
minlength: 8,
|
||||
maxlength: 128,
|
||||
},
|
||||
avatar: {
|
||||
type: String,
|
||||
required: false,
|
||||
},
|
||||
provider: {
|
||||
type: String,
|
||||
required: true,
|
||||
default: 'local',
|
||||
},
|
||||
role: {
|
||||
type: String,
|
||||
default: 'USER',
|
||||
},
|
||||
googleId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true,
|
||||
},
|
||||
facebookId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true,
|
||||
},
|
||||
openidId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true,
|
||||
},
|
||||
githubId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true,
|
||||
},
|
||||
discordId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true,
|
||||
},
|
||||
plugins: {
|
||||
type: Array,
|
||||
default: [],
|
||||
},
|
||||
refreshToken: {
|
||||
type: [Session],
|
||||
},
|
||||
},
|
||||
{ timestamps: true },
|
||||
);
|
||||
|
||||
//Remove refreshToken from the response
|
||||
userSchema.set('toJSON', {
|
||||
transform: function (_doc, ret) {
|
||||
|
|
|
|||
|
|
@ -7,8 +7,13 @@ const {
|
|||
} = require('./Message');
|
||||
const { getConvoTitle, getConvo, saveConvo } = require('./Conversation');
|
||||
const { getPreset, getPresets, savePreset, deletePresets } = require('./Preset');
|
||||
const User = require('./User');
|
||||
const Key = require('./schema/keySchema');
|
||||
|
||||
module.exports = {
|
||||
User,
|
||||
Key,
|
||||
|
||||
getMessages,
|
||||
saveMessage,
|
||||
updateMessage,
|
||||
|
|
|
|||
25
api/models/schema/keySchema.js
Normal file
25
api/models/schema/keySchema.js
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
const mongoose = require('mongoose');
|
||||
|
||||
const keySchema = mongoose.Schema({
|
||||
userId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
ref: 'User',
|
||||
required: true,
|
||||
},
|
||||
name: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
value: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
expiresAt: {
|
||||
type: Date,
|
||||
expires: 0,
|
||||
},
|
||||
});
|
||||
|
||||
keySchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
|
||||
|
||||
module.exports = mongoose.model('Key', keySchema);
|
||||
88
api/models/schema/userSchema.js
Normal file
88
api/models/schema/userSchema.js
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
const mongoose = require('mongoose');
|
||||
|
||||
const Session = mongoose.Schema({
|
||||
refreshToken: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
});
|
||||
|
||||
const userSchema = mongoose.Schema(
|
||||
{
|
||||
name: {
|
||||
type: String,
|
||||
},
|
||||
username: {
|
||||
type: String,
|
||||
lowercase: true,
|
||||
default: '',
|
||||
},
|
||||
email: {
|
||||
type: String,
|
||||
required: [true, 'can\'t be blank'],
|
||||
lowercase: true,
|
||||
unique: true,
|
||||
match: [/\S+@\S+\.\S+/, 'is invalid'],
|
||||
index: true,
|
||||
},
|
||||
emailVerified: {
|
||||
type: Boolean,
|
||||
required: true,
|
||||
default: false,
|
||||
},
|
||||
password: {
|
||||
type: String,
|
||||
trim: true,
|
||||
minlength: 8,
|
||||
maxlength: 128,
|
||||
},
|
||||
avatar: {
|
||||
type: String,
|
||||
required: false,
|
||||
},
|
||||
provider: {
|
||||
type: String,
|
||||
required: true,
|
||||
default: 'local',
|
||||
},
|
||||
role: {
|
||||
type: String,
|
||||
default: 'USER',
|
||||
},
|
||||
googleId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true,
|
||||
},
|
||||
facebookId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true,
|
||||
},
|
||||
openidId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true,
|
||||
},
|
||||
githubId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true,
|
||||
},
|
||||
discordId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true,
|
||||
},
|
||||
plugins: {
|
||||
type: Array,
|
||||
default: [],
|
||||
},
|
||||
refreshToken: {
|
||||
type: [Session],
|
||||
},
|
||||
},
|
||||
{ timestamps: true },
|
||||
);
|
||||
|
||||
module.exports = userSchema;
|
||||
|
|
@ -35,6 +35,8 @@
|
|||
"dotenv": "^16.0.3",
|
||||
"eslint": "^8.41.0",
|
||||
"express": "^4.18.2",
|
||||
"express-mongo-sanitize": "^2.2.0",
|
||||
"express-rate-limit": "^6.9.0",
|
||||
"express-session": "^1.17.3",
|
||||
"googleapis": "^118.0.0",
|
||||
"handlebars": "^4.7.7",
|
||||
|
|
@ -64,7 +66,7 @@
|
|||
},
|
||||
"devDependencies": {
|
||||
"jest": "^29.5.0",
|
||||
"nodemon": "^2.0.20",
|
||||
"nodemon": "^3.0.1",
|
||||
"path": "^0.12.7",
|
||||
"supertest": "^6.3.3"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
const express = require('express');
|
||||
const mongoSanitize = require('express-mongo-sanitize');
|
||||
const connectDb = require('../lib/db/connectDb');
|
||||
const indexSync = require('../lib/db/indexSync');
|
||||
const path = require('path');
|
||||
|
|
@ -23,6 +24,7 @@ const startServer = async () => {
|
|||
// Middleware
|
||||
app.use(errorController);
|
||||
app.use(express.json({ limit: '3mb' }));
|
||||
app.use(mongoSanitize());
|
||||
app.use(express.urlencoded({ extended: true, limit: '3mb' }));
|
||||
app.use(express.static(path.join(projectPath, 'dist')));
|
||||
app.use(express.static(path.join(projectPath, 'public')));
|
||||
|
|
@ -38,7 +40,7 @@ const startServer = async () => {
|
|||
// OAUTH
|
||||
app.use(passport.initialize());
|
||||
passport.use(await jwtLogin());
|
||||
passport.use(await passportLogin());
|
||||
passport.use(passportLogin());
|
||||
|
||||
if (process.env.ALLOW_SOCIAL_LOGIN === 'true') {
|
||||
configureSocialLogins(app);
|
||||
|
|
@ -47,6 +49,7 @@ const startServer = async () => {
|
|||
app.use('/oauth', routes.oauth);
|
||||
// API Endpoints
|
||||
app.use('/api/auth', routes.auth);
|
||||
app.use('/api/keys', routes.keys);
|
||||
app.use('/api/user', routes.user);
|
||||
app.use('/api/search', routes.search);
|
||||
app.use('/api/ask', routes.ask);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
const crypto = require('crypto');
|
||||
const { saveMessage, getConvo, getConvoTitle } = require('../../models');
|
||||
const { sendMessage, handleError } = require('../utils');
|
||||
const abortControllers = require('./abortControllers');
|
||||
|
|
@ -73,12 +74,13 @@ const handleAbortError = async (res, req, error, data) => {
|
|||
const respondWithError = async () => {
|
||||
const errorMessage = {
|
||||
sender,
|
||||
messageId,
|
||||
messageId: messageId ?? crypto.randomUUID(),
|
||||
conversationId,
|
||||
parentMessageId,
|
||||
unfinished: false,
|
||||
cancelled: false,
|
||||
error: true,
|
||||
final: true,
|
||||
text: error.message,
|
||||
isCreatedByUser: false,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
const abortMiddleware = require('./abortMiddleware');
|
||||
const setHeaders = require('./setHeaders');
|
||||
const loginLimiter = require('./loginLimiter');
|
||||
const requireJwtAuth = require('./requireJwtAuth');
|
||||
const registerLimiter = require('./registerLimiter');
|
||||
const requireLocalAuth = require('./requireLocalAuth');
|
||||
const validateEndpoint = require('./validateEndpoint');
|
||||
const validateMessageReq = require('./validateMessageReq');
|
||||
|
|
@ -10,7 +12,9 @@ const validateRegistration = require('./validateRegistration');
|
|||
module.exports = {
|
||||
...abortMiddleware,
|
||||
setHeaders,
|
||||
loginLimiter,
|
||||
requireJwtAuth,
|
||||
registerLimiter,
|
||||
requireLocalAuth,
|
||||
validateEndpoint,
|
||||
validateMessageReq,
|
||||
|
|
|
|||
12
api/server/middleware/loginLimiter.js
Normal file
12
api/server/middleware/loginLimiter.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
const rateLimit = require('express-rate-limit');
|
||||
const windowMs = (process.env?.LOGIN_WINDOW ?? 5) * 60 * 1000; // default: 5 minutes
|
||||
const max = process.env?.LOGIN_MAX ?? 7; // default: limit each IP to 7 requests per windowMs
|
||||
const windowInMinutes = windowMs / 60000;
|
||||
|
||||
const loginLimiter = rateLimit({
|
||||
windowMs,
|
||||
max,
|
||||
message: `Too many login attempts from this IP, please try again after ${windowInMinutes} minutes.`,
|
||||
});
|
||||
|
||||
module.exports = loginLimiter;
|
||||
12
api/server/middleware/registerLimiter.js
Normal file
12
api/server/middleware/registerLimiter.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
const rateLimit = require('express-rate-limit');
|
||||
const windowMs = (process.env?.REGISTER_WINDOW ?? 60) * 60 * 1000; // default: 1 hour
|
||||
const max = process.env?.REGISTER_MAX ?? 5; // default: limit each IP to 5 registrations per windowMs
|
||||
const windowInMinutes = windowMs / 60000;
|
||||
|
||||
const registerLimiter = rateLimit({
|
||||
windowMs,
|
||||
max,
|
||||
message: `Too many accounts created from this IP, please try again after ${windowInMinutes} minutes`,
|
||||
});
|
||||
|
||||
module.exports = registerLimiter;
|
||||
|
|
@ -87,7 +87,7 @@ router.post(
|
|||
getAbortData,
|
||||
);
|
||||
|
||||
const { client } = initializeClient(req, endpointOption);
|
||||
const { client } = await initializeClient(req, endpointOption);
|
||||
|
||||
let response = await client.sendMessage(text, {
|
||||
getIds,
|
||||
|
|
@ -135,7 +135,7 @@ router.post(
|
|||
conversationId,
|
||||
sender: getResponseSender(endpointOption),
|
||||
messageId: responseMessageId,
|
||||
parentMessageId: userMessageId,
|
||||
parentMessageId: userMessageId ?? parentMessageId,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ router.post('/', requireJwtAuth, setHeaders, async (req, res) => {
|
|||
// build endpoint option
|
||||
const endpointOption = {
|
||||
model: req.body?.model ?? 'text-davinci-002-render-sha',
|
||||
token: req.body?.token ?? null,
|
||||
key: req.body?.key ?? null,
|
||||
};
|
||||
|
||||
// const availableModels = getChatGPTBrowserModels();
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ router.post('/', requireJwtAuth, setHeaders, async (req, res) => {
|
|||
systemMessage: req.body?.systemMessage ?? null,
|
||||
context: req.body?.context ?? null,
|
||||
toneStyle: req.body?.toneStyle ?? 'creative',
|
||||
token: req.body?.token ?? null,
|
||||
key: req.body?.key ?? null,
|
||||
};
|
||||
} else {
|
||||
endpointOption = {
|
||||
|
|
@ -56,7 +56,7 @@ router.post('/', requireJwtAuth, setHeaders, async (req, res) => {
|
|||
clientId: req.body?.clientId ?? null,
|
||||
invocationId: req.body?.invocationId ?? null,
|
||||
toneStyle: req.body?.toneStyle ?? 'creative',
|
||||
token: req.body?.token ?? null,
|
||||
key: req.body?.key ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -139,6 +139,7 @@ const ask = async ({
|
|||
try {
|
||||
let response = await askBing({
|
||||
text,
|
||||
userId: req.user.id,
|
||||
parentMessageId: userParentMessageId,
|
||||
conversationId: bingConversationId ?? conversationId,
|
||||
...endpointOption,
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const crypto = require('crypto');
|
||||
const { titleConvo, GoogleClient } = require('../../../app');
|
||||
const { GoogleClient } = require('../../../app');
|
||||
const { saveMessage, getConvoTitle, saveConvo, getConvo } = require('../../../models');
|
||||
const { handleError, sendMessage, createOnProgress } = require('../../utils');
|
||||
const { getUserKey, checkUserKeyExpiry } = require('../../services/UserService');
|
||||
const { requireJwtAuth, setHeaders } = require('../../middleware');
|
||||
|
||||
router.post('/', requireJwtAuth, setHeaders, async (req, res) => {
|
||||
|
|
@ -19,7 +20,7 @@ router.post('/', requireJwtAuth, setHeaders, async (req, res) => {
|
|||
const endpointOption = {
|
||||
examples: req.body?.examples ?? [{ input: { content: '' }, output: { content: '' } }],
|
||||
promptPrefix: req.body?.promptPrefix ?? null,
|
||||
token: req.body?.token ?? null,
|
||||
key: req.body?.key ?? null,
|
||||
modelOptions: {
|
||||
model: req.body?.model ?? 'chat-bison',
|
||||
modelLabel: req.body?.modelLabel ?? null,
|
||||
|
|
@ -88,17 +89,22 @@ const ask = async ({ text, endpointOption, parentMessageId = null, conversationI
|
|||
|
||||
const abortController = new AbortController();
|
||||
|
||||
const isUserProvided = process.env.PALM_KEY === 'user_provided';
|
||||
|
||||
let key;
|
||||
if (endpointOption.token) {
|
||||
key = JSON.parse(endpointOption.token);
|
||||
delete endpointOption.token;
|
||||
if (endpointOption.key && isUserProvided) {
|
||||
checkUserKeyExpiry(
|
||||
endpointOption.key,
|
||||
'Your GOOGLE_TOKEN has expired. Please provide your token again.',
|
||||
);
|
||||
key = await getUserKey({ userId: req.user.id, name: 'google' });
|
||||
key = JSON.parse(key);
|
||||
delete endpointOption.key;
|
||||
console.log('Using service account key provided by User for PaLM models');
|
||||
}
|
||||
|
||||
try {
|
||||
if (!key) {
|
||||
key = require('../../../data/auth.json');
|
||||
}
|
||||
key = require('../../../data/auth.json');
|
||||
} catch (e) {
|
||||
console.log('No \'auth.json\' file (service account key) found in /api/data/ for PaLM models');
|
||||
}
|
||||
|
|
@ -146,14 +152,6 @@ const ask = async ({ text, endpointOption, parentMessageId = null, conversationI
|
|||
responseMessage: response,
|
||||
});
|
||||
res.end();
|
||||
|
||||
if (parentMessageId == '00000000-0000-0000-0000-000000000000') {
|
||||
const title = await titleConvo({ text, response });
|
||||
await saveConvo(req.user.id, {
|
||||
conversationId,
|
||||
title,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
const errorMessage = {
|
||||
|
|
|
|||
|
|
@ -158,7 +158,7 @@ router.post(
|
|||
|
||||
try {
|
||||
endpointOption.tools = await validateTools(user, endpointOption.tools);
|
||||
const { client, azure, openAIApiKey } = initializeClient(req, endpointOption);
|
||||
const { client } = await initializeClient(req, endpointOption);
|
||||
|
||||
let response = await client.sendMessage(text, {
|
||||
user,
|
||||
|
|
@ -204,14 +204,14 @@ router.post(
|
|||
responseMessage: response,
|
||||
});
|
||||
res.end();
|
||||
addTitle(req, {
|
||||
text,
|
||||
newConvo,
|
||||
response,
|
||||
openAIApiKey,
|
||||
parentMessageId,
|
||||
azure: !!azure,
|
||||
});
|
||||
|
||||
if (parentMessageId == '00000000-0000-0000-0000-000000000000' && newConvo) {
|
||||
addTitle(req, {
|
||||
text,
|
||||
response,
|
||||
client,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
const partialText = getPartialText();
|
||||
handleAbortError(res, req, error, {
|
||||
|
|
@ -219,7 +219,7 @@ router.post(
|
|||
conversationId,
|
||||
sender: getResponseSender(endpointOption),
|
||||
messageId: responseMessageId,
|
||||
parentMessageId: userMessageId,
|
||||
parentMessageId: userMessageId ?? parentMessageId,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -94,7 +94,7 @@ router.post(
|
|||
);
|
||||
|
||||
try {
|
||||
const { client, openAIApiKey } = initializeClient(req, endpointOption);
|
||||
const { client } = await initializeClient(req, endpointOption);
|
||||
|
||||
let response = await client.sendMessage(text, {
|
||||
user,
|
||||
|
|
@ -136,14 +136,13 @@ router.post(
|
|||
});
|
||||
res.end();
|
||||
|
||||
addTitle(req, {
|
||||
text,
|
||||
newConvo,
|
||||
response,
|
||||
openAIApiKey,
|
||||
parentMessageId,
|
||||
azure: endpointOption.endpoint === 'azureOpenAI',
|
||||
});
|
||||
if (parentMessageId == '00000000-0000-0000-0000-000000000000' && newConvo) {
|
||||
addTitle(req, {
|
||||
text,
|
||||
response,
|
||||
client,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
const partialText = getPartialText();
|
||||
handleAbortError(res, req, error, {
|
||||
|
|
@ -151,7 +150,7 @@ router.post(
|
|||
conversationId,
|
||||
sender: getResponseSender(endpointOption),
|
||||
messageId: responseMessageId,
|
||||
parentMessageId: userMessageId,
|
||||
parentMessageId: userMessageId ?? parentMessageId,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -7,15 +7,21 @@ const {
|
|||
} = require('../controllers/AuthController');
|
||||
const { loginController } = require('../controllers/auth/LoginController');
|
||||
const { logoutController } = require('../controllers/auth/LogoutController');
|
||||
const { requireJwtAuth, requireLocalAuth, validateRegistration } = require('../middleware');
|
||||
const {
|
||||
loginLimiter,
|
||||
registerLimiter,
|
||||
requireJwtAuth,
|
||||
requireLocalAuth,
|
||||
validateRegistration,
|
||||
} = require('../middleware');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
//Local
|
||||
router.post('/logout', requireJwtAuth, logoutController);
|
||||
router.post('/login', requireLocalAuth, loginController);
|
||||
router.post('/login', loginLimiter, requireLocalAuth, loginController);
|
||||
// router.post('/refresh', requireJwtAuth, refreshController);
|
||||
router.post('/register', validateRegistration, registrationController);
|
||||
router.post('/register', registerLimiter, validateRegistration, registrationController);
|
||||
router.post('/requestPasswordReset', resetPasswordRequestController);
|
||||
router.post('/resetPassword', resetPasswordController);
|
||||
|
||||
|
|
|
|||
|
|
@ -87,7 +87,7 @@ router.post(
|
|||
getAbortData,
|
||||
);
|
||||
|
||||
const { client } = initializeClient(req, endpointOption);
|
||||
const { client } = await initializeClient(req, endpointOption);
|
||||
|
||||
let response = await client.sendMessage(text, {
|
||||
user: req.user.id,
|
||||
|
|
@ -136,7 +136,7 @@ router.post(
|
|||
conversationId,
|
||||
sender: getResponseSender(endpointOption),
|
||||
messageId: responseMessageId,
|
||||
parentMessageId: userMessageId,
|
||||
parentMessageId: userMessageId ?? parentMessageId,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -128,7 +128,7 @@ router.post(
|
|||
|
||||
try {
|
||||
endpointOption.tools = await validateTools(user, endpointOption.tools);
|
||||
const { client } = initializeClient(req, endpointOption);
|
||||
const { client } = await initializeClient(req, endpointOption);
|
||||
|
||||
let response = await client.sendMessage(text, {
|
||||
user,
|
||||
|
|
@ -182,7 +182,7 @@ router.post(
|
|||
conversationId,
|
||||
sender: getResponseSender(endpointOption),
|
||||
messageId: responseMessageId,
|
||||
parentMessageId: userMessageId,
|
||||
parentMessageId: userMessageId ?? parentMessageId,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ router.post(
|
|||
);
|
||||
|
||||
try {
|
||||
const { client } = initializeClient(req, endpointOption);
|
||||
const { client } = await initializeClient(req, endpointOption);
|
||||
|
||||
let response = await client.sendMessage(text, {
|
||||
user: req.user.id,
|
||||
|
|
@ -138,7 +138,7 @@ router.post(
|
|||
conversationId,
|
||||
sender: getResponseSender(endpointOption),
|
||||
messageId: responseMessageId,
|
||||
parentMessageId: userMessageId,
|
||||
parentMessageId: userMessageId ?? parentMessageId,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -8,9 +8,9 @@ const { addOpenAPISpecs } = require('../../app/clients/tools/util/addOpenAPISpec
|
|||
const openAIApiKey = process.env.OPENAI_API_KEY;
|
||||
const azureOpenAIApiKey = process.env.AZURE_API_KEY;
|
||||
const useAzurePlugins = !!process.env.PLUGINS_USE_AZURE;
|
||||
const userProvidedOpenAI = openAIApiKey
|
||||
? openAIApiKey === 'user_provided'
|
||||
: azureOpenAIApiKey === 'user_provided';
|
||||
const userProvidedOpenAI = useAzurePlugins
|
||||
? azureOpenAIApiKey === 'user_provided'
|
||||
: openAIApiKey === 'user_provided';
|
||||
|
||||
const fetchOpenAIModels = async (opts = { azure: false, plugins: false }, _models = []) => {
|
||||
let models = _models.slice() ?? [];
|
||||
|
|
@ -81,9 +81,6 @@ const getOpenAIModels = async (opts = { azure: false, plugins: false }) => {
|
|||
}
|
||||
|
||||
if (userProvidedOpenAI) {
|
||||
console.warn(
|
||||
`When setting OPENAI_API_KEY to 'user_provided', ${key} must be set manually or default values will be used`,
|
||||
);
|
||||
return models;
|
||||
}
|
||||
|
||||
|
|
@ -161,6 +158,7 @@ router.get('/', async function (req, res) {
|
|||
plugins,
|
||||
availableAgents: ['classic', 'functions'],
|
||||
userProvide: userProvidedOpenAI,
|
||||
azure: useAzurePlugins,
|
||||
}
|
||||
: false;
|
||||
const bingAI = process.env.BINGAI_TOKEN
|
||||
|
|
|
|||
|
|
@ -1,7 +1,21 @@
|
|||
const { AnthropicClient } = require('../../../../app');
|
||||
const { getUserKey, checkUserKeyExpiry } = require('../../../services/UserService');
|
||||
|
||||
const initializeClient = (req) => {
|
||||
let anthropicApiKey = req.body?.token ?? process.env.ANTHROPIC_API_KEY;
|
||||
const initializeClient = async (req) => {
|
||||
const { ANTHROPIC_API_KEY } = process.env;
|
||||
const { key: expiresAt } = req.body;
|
||||
|
||||
const isUserProvided = ANTHROPIC_API_KEY === 'user_provided';
|
||||
|
||||
let key = null;
|
||||
if (expiresAt && isUserProvided) {
|
||||
checkUserKeyExpiry(
|
||||
expiresAt,
|
||||
'Your ANTHROPIC_API_KEY has expired. Please provide your API key again.',
|
||||
);
|
||||
key = await getUserKey({ userId: req.user.id, name: 'anthropic' });
|
||||
}
|
||||
let anthropicApiKey = isUserProvided ? key : ANTHROPIC_API_KEY;
|
||||
const client = new AnthropicClient(anthropicApiKey);
|
||||
return {
|
||||
client,
|
||||
|
|
|
|||
|
|
@ -1,22 +1,43 @@
|
|||
const { PluginsClient } = require('../../../../app');
|
||||
const { getAzureCredentials } = require('../../../../utils');
|
||||
const { getUserKey, checkUserKeyExpiry } = require('../../../services/UserService');
|
||||
|
||||
const initializeClient = (req, endpointOption) => {
|
||||
const initializeClient = async (req, endpointOption) => {
|
||||
const { PROXY, OPENAI_API_KEY, AZURE_API_KEY, PLUGINS_USE_AZURE, OPENAI_REVERSE_PROXY } =
|
||||
process.env;
|
||||
const { key: expiresAt } = req.body;
|
||||
const clientOptions = {
|
||||
debug: true,
|
||||
reverseProxyUrl: process.env.OPENAI_REVERSE_PROXY || null,
|
||||
proxy: process.env.PROXY || null,
|
||||
// debug: true,
|
||||
reverseProxyUrl: OPENAI_REVERSE_PROXY ?? null,
|
||||
proxy: PROXY ?? null,
|
||||
...endpointOption,
|
||||
};
|
||||
|
||||
let openAIApiKey = req.body?.token ?? process.env.OPENAI_API_KEY;
|
||||
if (process.env.PLUGINS_USE_AZURE) {
|
||||
clientOptions.azure = getAzureCredentials();
|
||||
const isUserProvided = PLUGINS_USE_AZURE
|
||||
? AZURE_API_KEY === 'user_provided'
|
||||
: OPENAI_API_KEY === 'user_provided';
|
||||
|
||||
let key = null;
|
||||
if (expiresAt && isUserProvided) {
|
||||
checkUserKeyExpiry(
|
||||
expiresAt,
|
||||
'Your OpenAI API key has expired. Please provide your API key again.',
|
||||
);
|
||||
key = await getUserKey({
|
||||
userId: req.user.id,
|
||||
name: PLUGINS_USE_AZURE ? 'azureOpenAI' : 'openAI',
|
||||
});
|
||||
}
|
||||
|
||||
let openAIApiKey = isUserProvided ? key : OPENAI_API_KEY;
|
||||
|
||||
if (PLUGINS_USE_AZURE) {
|
||||
clientOptions.azure = isUserProvided ? JSON.parse(key) : getAzureCredentials();
|
||||
openAIApiKey = clientOptions.azure.azureOpenAIApiKey;
|
||||
}
|
||||
|
||||
if (openAIApiKey && openAIApiKey.includes('azure') && !clientOptions.azure) {
|
||||
clientOptions.azure = JSON.parse(req.body?.token) ?? getAzureCredentials();
|
||||
clientOptions.azure = isUserProvided ? JSON.parse(key) : getAzureCredentials();
|
||||
openAIApiKey = clientOptions.azure.azureOpenAIApiKey;
|
||||
}
|
||||
const client = new PluginsClient(openAIApiKey, clientOptions);
|
||||
|
|
|
|||
|
|
@ -1,22 +1,11 @@
|
|||
const { titleConvo } = require('../../../../app');
|
||||
const { saveConvo } = require('../../../../models');
|
||||
|
||||
const addTitle = async (
|
||||
req,
|
||||
{ text, azure, response, newConvo, parentMessageId, openAIApiKey },
|
||||
) => {
|
||||
if (parentMessageId == '00000000-0000-0000-0000-000000000000' && newConvo) {
|
||||
const title = await titleConvo({
|
||||
text,
|
||||
azure,
|
||||
response,
|
||||
openAIApiKey,
|
||||
});
|
||||
await saveConvo(req.user.id, {
|
||||
conversationId: response.conversationId,
|
||||
title,
|
||||
});
|
||||
}
|
||||
const addTitle = async (req, { text, response, client }) => {
|
||||
const title = await client.titleConvo({ text, responseText: response?.text });
|
||||
await saveConvo(req.user.id, {
|
||||
conversationId: response.conversationId,
|
||||
title,
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = addTitle;
|
||||
|
|
|
|||
|
|
@ -1,19 +1,34 @@
|
|||
const { OpenAIClient } = require('../../../../app');
|
||||
const { getAzureCredentials } = require('../../../../utils');
|
||||
const { getUserKey, checkUserKeyExpiry } = require('../../../services/UserService');
|
||||
|
||||
const initializeClient = (req, endpointOption) => {
|
||||
const initializeClient = async (req, endpointOption) => {
|
||||
const { PROXY, OPENAI_API_KEY, AZURE_API_KEY, OPENAI_REVERSE_PROXY } = process.env;
|
||||
const { key: expiresAt, endpoint } = req.body;
|
||||
const clientOptions = {
|
||||
// debug: true,
|
||||
// contextStrategy: 'refine',
|
||||
reverseProxyUrl: process.env.OPENAI_REVERSE_PROXY || null,
|
||||
proxy: process.env.PROXY || null,
|
||||
reverseProxyUrl: OPENAI_REVERSE_PROXY ?? null,
|
||||
proxy: PROXY ?? null,
|
||||
...endpointOption,
|
||||
};
|
||||
|
||||
let openAIApiKey = req.body?.token ?? process.env.OPENAI_API_KEY;
|
||||
const isUserProvided =
|
||||
endpoint === 'openAI' ? OPENAI_API_KEY === 'user_provided' : AZURE_API_KEY === 'user_provided';
|
||||
|
||||
if (process.env.AZURE_API_KEY && endpointOption.endpoint === 'azureOpenAI') {
|
||||
clientOptions.azure = JSON.parse(req.body?.token) ?? getAzureCredentials();
|
||||
let key = null;
|
||||
if (expiresAt && isUserProvided) {
|
||||
checkUserKeyExpiry(
|
||||
expiresAt,
|
||||
'Your OpenAI API key has expired. Please provide your API key again.',
|
||||
);
|
||||
key = await getUserKey({ userId: req.user.id, name: endpoint });
|
||||
}
|
||||
|
||||
let openAIApiKey = isUserProvided ? key : OPENAI_API_KEY;
|
||||
|
||||
if (process.env.AZURE_API_KEY && endpoint === 'azureOpenAI') {
|
||||
clientOptions.azure = isUserProvided ? JSON.parse(key) : getAzureCredentials();
|
||||
openAIApiKey = clientOptions.azure.azureOpenAIApiKey;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ const prompts = require('./prompts');
|
|||
const search = require('./search');
|
||||
const tokenizer = require('./tokenizer');
|
||||
const auth = require('./auth');
|
||||
const keys = require('./keys');
|
||||
const oauth = require('./oauth');
|
||||
const { router: endpoints } = require('./endpoints');
|
||||
const plugins = require('./plugins');
|
||||
|
|
@ -22,6 +23,7 @@ module.exports = {
|
|||
presets,
|
||||
prompts,
|
||||
auth,
|
||||
keys,
|
||||
oauth,
|
||||
user,
|
||||
tokenizer,
|
||||
|
|
|
|||
35
api/server/routes/keys.js
Normal file
35
api/server/routes/keys.js
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { updateUserKey, deleteUserKey, getUserKeyExpiry } = require('../services/UserService');
|
||||
const { requireJwtAuth } = require('../middleware/');
|
||||
|
||||
router.put('/', requireJwtAuth, async (req, res) => {
|
||||
await updateUserKey({ userId: req.user.id, ...req.body });
|
||||
res.status(201).send();
|
||||
});
|
||||
|
||||
router.delete('/:name', requireJwtAuth, async (req, res) => {
|
||||
const { name } = req.params;
|
||||
await deleteUserKey({ userId: req.user.id, name });
|
||||
res.status(204).send();
|
||||
});
|
||||
|
||||
router.delete('/', requireJwtAuth, async (req, res) => {
|
||||
const { all } = req.query;
|
||||
|
||||
if (all !== 'true') {
|
||||
return res.status(400).send({ error: 'Specify either all=true to delete.' });
|
||||
}
|
||||
|
||||
await deleteUserKey({ userId: req.user.id, all: true });
|
||||
|
||||
res.status(204).send();
|
||||
});
|
||||
|
||||
router.get('/', requireJwtAuth, async (req, res) => {
|
||||
const { name } = req.query;
|
||||
const response = await getUserKeyExpiry({ userId: req.user.id, name });
|
||||
res.status(200).send(response);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
const passport = require('passport');
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { loginLimiter } = require('../middleware');
|
||||
const config = require('../../../config/loader');
|
||||
const domains = config.domains;
|
||||
const isProduction = config.isProduction;
|
||||
|
|
@ -10,6 +11,7 @@ const isProduction = config.isProduction;
|
|||
*/
|
||||
router.get(
|
||||
'/google',
|
||||
loginLimiter,
|
||||
passport.authenticate('google', {
|
||||
scope: ['openid', 'profile', 'email'],
|
||||
session: false,
|
||||
|
|
@ -37,6 +39,7 @@ router.get(
|
|||
|
||||
router.get(
|
||||
'/facebook',
|
||||
loginLimiter,
|
||||
passport.authenticate('facebook', {
|
||||
scope: ['public_profile'],
|
||||
profileFields: ['id', 'email', 'name'],
|
||||
|
|
@ -66,6 +69,7 @@ router.get(
|
|||
|
||||
router.get(
|
||||
'/openid',
|
||||
loginLimiter,
|
||||
passport.authenticate('openid', {
|
||||
session: false,
|
||||
}),
|
||||
|
|
@ -91,6 +95,7 @@ router.get(
|
|||
|
||||
router.get(
|
||||
'/github',
|
||||
loginLimiter,
|
||||
passport.authenticate('github', {
|
||||
scope: ['user:email', 'read:user'],
|
||||
session: false,
|
||||
|
|
@ -118,6 +123,7 @@ router.get(
|
|||
|
||||
router.get(
|
||||
'/discord',
|
||||
loginLimiter,
|
||||
passport.authenticate('discord', {
|
||||
scope: ['identify', 'email'],
|
||||
session: false,
|
||||
|
|
|
|||
|
|
@ -1,19 +1,18 @@
|
|||
const User = require('../../models/User');
|
||||
const { User, Key } = require('../../models');
|
||||
const { encrypt, decrypt } = require('../utils');
|
||||
|
||||
const updateUserPluginsService = async (user, pluginKey, action) => {
|
||||
try {
|
||||
if (action === 'install') {
|
||||
const response = await User.updateOne(
|
||||
return await User.updateOne(
|
||||
{ _id: user._id },
|
||||
{ $set: { plugins: [...user.plugins, pluginKey] } },
|
||||
);
|
||||
return response;
|
||||
} else if (action === 'uninstall') {
|
||||
const response = await User.updateOne(
|
||||
return await User.updateOne(
|
||||
{ _id: user._id },
|
||||
{ $set: { plugins: user.plugins.filter((plugin) => plugin !== pluginKey) } },
|
||||
);
|
||||
return response;
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
|
|
@ -21,4 +20,58 @@ const updateUserPluginsService = async (user, pluginKey, action) => {
|
|||
}
|
||||
};
|
||||
|
||||
module.exports = { updateUserPluginsService };
|
||||
const getUserKey = async ({ userId, name }) => {
|
||||
const keyValue = await Key.findOne({ userId, name }).lean();
|
||||
if (!keyValue) {
|
||||
throw new Error('User-provided key not found');
|
||||
}
|
||||
return decrypt(keyValue.value);
|
||||
};
|
||||
|
||||
const getUserKeyExpiry = async ({ userId, name }) => {
|
||||
const keyValue = await Key.findOne({ userId, name }).lean();
|
||||
if (!keyValue) {
|
||||
return { expiresAt: null };
|
||||
}
|
||||
return { expiresAt: keyValue.expiresAt };
|
||||
};
|
||||
|
||||
const updateUserKey = async ({ userId, name, value, expiresAt }) => {
|
||||
const encryptedValue = encrypt(value);
|
||||
return await Key.findOneAndUpdate(
|
||||
{ userId, name },
|
||||
{
|
||||
userId,
|
||||
name,
|
||||
value: encryptedValue,
|
||||
expiresAt: new Date(expiresAt),
|
||||
},
|
||||
{ upsert: true, new: true },
|
||||
).lean();
|
||||
};
|
||||
|
||||
const deleteUserKey = async ({ userId, name, all = false }) => {
|
||||
if (all) {
|
||||
return await Key.deleteMany({ userId });
|
||||
}
|
||||
|
||||
await Key.findOneAndDelete({ userId, name }).lean();
|
||||
};
|
||||
|
||||
const checkUserKeyExpiry = (expiresAt, message) => {
|
||||
const expiresAtDate = new Date(expiresAt);
|
||||
if (expiresAtDate < new Date()) {
|
||||
const expiryStr = `User-provided key expired at ${expiresAtDate.toLocaleString()}`;
|
||||
const errorMessage = message ? `${message}\n${expiryStr}` : expiryStr;
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
updateUserPluginsService,
|
||||
getUserKey,
|
||||
getUserKeyExpiry,
|
||||
updateUserKey,
|
||||
deleteUserKey,
|
||||
checkUserKeyExpiry,
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue