mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-09-22 06:00:56 +02:00

* 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
191 lines
5.3 KiB
JavaScript
191 lines
5.3 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const { getResponseSender } = require('../endpoints/schemas');
|
|
const { validateTools } = require('../../../app');
|
|
const { initializeClient } = require('../endpoints/gptPlugins');
|
|
const { saveMessage, getConvoTitle, getConvo } = require('../../../models');
|
|
const { sendMessage, createOnProgress, formatSteps, formatAction } = require('../../utils');
|
|
const {
|
|
handleAbort,
|
|
createAbortController,
|
|
handleAbortError,
|
|
setHeaders,
|
|
requireJwtAuth,
|
|
validateEndpoint,
|
|
buildEndpointOption,
|
|
} = require('../../middleware');
|
|
|
|
router.post('/abort', requireJwtAuth, handleAbort());
|
|
|
|
router.post(
|
|
'/',
|
|
requireJwtAuth,
|
|
validateEndpoint,
|
|
buildEndpointOption,
|
|
setHeaders,
|
|
async (req, res) => {
|
|
let {
|
|
text,
|
|
generation,
|
|
endpointOption,
|
|
conversationId,
|
|
responseMessageId,
|
|
isContinued = false,
|
|
parentMessageId = null,
|
|
overrideParentMessageId = null,
|
|
} = req.body;
|
|
console.log('edit log');
|
|
console.dir({ text, generation, isContinued, conversationId, endpointOption }, { depth: null });
|
|
let metadata;
|
|
let userMessage;
|
|
let lastSavedTimestamp = 0;
|
|
let saveDelay = 100;
|
|
const userMessageId = parentMessageId;
|
|
const user = req.user.id;
|
|
|
|
const plugin = {
|
|
loading: true,
|
|
inputs: [],
|
|
latest: null,
|
|
outputs: null,
|
|
};
|
|
|
|
const addMetadata = (data) => (metadata = data);
|
|
const getIds = (data) => {
|
|
userMessage = data.userMessage;
|
|
responseMessageId = data.responseMessageId;
|
|
};
|
|
|
|
const {
|
|
onProgress: progressCallback,
|
|
sendIntermediateMessage,
|
|
getPartialText,
|
|
} = createOnProgress({
|
|
generation,
|
|
onProgress: ({ text: partialText }) => {
|
|
const currentTimestamp = Date.now();
|
|
|
|
if (plugin.loading === true) {
|
|
plugin.loading = false;
|
|
}
|
|
|
|
if (currentTimestamp - lastSavedTimestamp > saveDelay) {
|
|
lastSavedTimestamp = currentTimestamp;
|
|
saveMessage({
|
|
messageId: responseMessageId,
|
|
sender: getResponseSender(endpointOption),
|
|
conversationId,
|
|
parentMessageId: overrideParentMessageId || userMessageId,
|
|
text: partialText,
|
|
model: endpointOption.modelOptions.model,
|
|
unfinished: true,
|
|
cancelled: false,
|
|
error: false,
|
|
});
|
|
}
|
|
|
|
if (saveDelay < 500) {
|
|
saveDelay = 500;
|
|
}
|
|
},
|
|
});
|
|
|
|
const onAgentAction = (action, start = false) => {
|
|
const formattedAction = formatAction(action);
|
|
plugin.inputs.push(formattedAction);
|
|
plugin.latest = formattedAction.plugin;
|
|
if (!start) {
|
|
saveMessage(userMessage);
|
|
}
|
|
sendIntermediateMessage(res, { plugin });
|
|
// console.log('PLUGIN ACTION', formattedAction);
|
|
};
|
|
|
|
const onChainEnd = (data) => {
|
|
let { intermediateSteps: steps } = data;
|
|
plugin.outputs = steps && steps[0].action ? formatSteps(steps) : 'An error occurred.';
|
|
plugin.loading = false;
|
|
saveMessage(userMessage);
|
|
sendIntermediateMessage(res, { plugin });
|
|
// console.log('CHAIN END', plugin.outputs);
|
|
};
|
|
|
|
const getAbortData = () => ({
|
|
sender: getResponseSender(endpointOption),
|
|
conversationId,
|
|
messageId: responseMessageId,
|
|
parentMessageId: overrideParentMessageId ?? userMessageId,
|
|
text: getPartialText(),
|
|
plugin: { ...plugin, loading: false },
|
|
userMessage,
|
|
});
|
|
const { abortController, onStart } = createAbortController(
|
|
res,
|
|
req,
|
|
endpointOption,
|
|
getAbortData,
|
|
);
|
|
|
|
try {
|
|
endpointOption.tools = await validateTools(user, endpointOption.tools);
|
|
const { client } = await initializeClient(req, endpointOption);
|
|
|
|
let response = await client.sendMessage(text, {
|
|
user,
|
|
generation,
|
|
isContinued,
|
|
isEdited: true,
|
|
conversationId,
|
|
parentMessageId,
|
|
responseMessageId,
|
|
overrideParentMessageId,
|
|
getIds,
|
|
onAgentAction,
|
|
onChainEnd,
|
|
onStart,
|
|
addMetadata,
|
|
...endpointOption,
|
|
onProgress: progressCallback.call(null, {
|
|
res,
|
|
text,
|
|
plugin,
|
|
parentMessageId: overrideParentMessageId || userMessageId,
|
|
}),
|
|
abortController,
|
|
});
|
|
|
|
if (overrideParentMessageId) {
|
|
response.parentMessageId = overrideParentMessageId;
|
|
}
|
|
|
|
if (metadata) {
|
|
response = { ...response, ...metadata };
|
|
}
|
|
|
|
console.log('CLIENT RESPONSE');
|
|
console.dir(response, { depth: null });
|
|
response.plugin = { ...plugin, loading: false };
|
|
await saveMessage(response);
|
|
|
|
sendMessage(res, {
|
|
title: await getConvoTitle(req.user.id, conversationId),
|
|
final: true,
|
|
conversation: await getConvo(req.user.id, conversationId),
|
|
requestMessage: userMessage,
|
|
responseMessage: response,
|
|
});
|
|
res.end();
|
|
} catch (error) {
|
|
const partialText = getPartialText();
|
|
handleAbortError(res, req, error, {
|
|
partialText,
|
|
conversationId,
|
|
sender: getResponseSender(endpointOption),
|
|
messageId: responseMessageId,
|
|
parentMessageId: userMessageId ?? parentMessageId,
|
|
});
|
|
}
|
|
},
|
|
);
|
|
|
|
module.exports = router;
|