mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-09-21 21:50:49 +02:00

* wip: first pass, dropdown for selecting sequential agents * refactor: Improve agent selection logic and enhance performance in SequentialAgents component * wip: seq. agents working ideas * wip: sequential agents style change * refactor: move agent form options/submission outside of AgentConfig * refactor: prevent repeating code * refactor: simplify current agent display in SequentialAgents component * feat: persist form value handling in AgentSelect component for agent_ids * feat: first pass, sequential agnets agent update * feat: enhance message display with agent updates and empty text handling * chore: update Icon component to use EModelEndpoint for agent endpoints * feat: update content type checks in BaseClient to use constants for better readability * feat: adjust max context tokens calculation to use 90% of the model's max tokens * feat: first pass, agent run message pruning * chore: increase max listeners for abort controller to prevent memory leaks * feat: enhance runAgent function to include current index count map for improved token tracking * chore: update @librechat/agents dependency to version 2.2.5 * feat: update icons and style of SequentialAgents component for improved UI consistency * feat: add AdvancedButton and AdvancedPanel components for enhanced agent settings navigation, update styling for agent form * chore: adjust minimum height of AdvancedPanel component for better layout consistency * chore: update @librechat/agents dependency to version 2.2.6 * feat: enhance message formatting by incorporating tool set into agent message processing, in order to allow better mix/matching of agents (as tool calls for tools not found in set will be stringified) * refactor: reorder components in AgentConfig for improved readability and maintainability * refactor: enhance layout of AgentUpdate component for improved visual structure * feat: add DeepSeek provider to Bedrock settings and schemas * feat: enhance link styling in mobile.css for better visibility and accessibility * fix: update banner model import in update banner script; export Banner model * refactor: `duplicateAgentHandler` to include tool_resources only for OCR context files * feat: add 'qwen-vl' to visionModels for enhanced model support * fix: change image format from JPEG to PNG in DALLE3 response * feat: reorganize Advanced components and add localizations * refactor: simplify JSX structure in AgentChain component to defer container styling to parent * feat: add FormInput component for reusable input handling * feat: make agent recursion limit configurable from builder * feat: add support for agent capabilities chain in AdvancedPanel and update data-provider version * feat: add maxRecursionLimit configuration for agents and update related documentation * fix: update CONFIG_VERSION to 1.2.3 in data provider configuration * feat: replace recursion limit input with MaxAgentSteps component and enhance input handling * feat: enhance AgentChain component with hover card for additional information and update related labels * fix: pass request and response objects to `createActionTool` when using assistant actions to prevent auth error * feat: update AgentChain component layout to include agent count display * feat: increase default max listeners and implement capability check function for agent chain * fix: update link styles in mobile.css for better visibility in dark mode * chore: temp. remove agents package while bumping shared packages * chore: update @langchain/google-genai package to version 0.1.11 * chore: update @langchain/google-vertexai package to version 0.2.2 * chore: add @librechat/agents package at version 2.2.8 * feat: add deepseek.r1 model with token rate and context values for bedrock
273 lines
7.4 KiB
JavaScript
273 lines
7.4 KiB
JavaScript
const path = require('path');
|
|
const crypto = require('crypto');
|
|
const {
|
|
Capabilities,
|
|
EModelEndpoint,
|
|
isAgentsEndpoint,
|
|
AgentCapabilities,
|
|
isAssistantsEndpoint,
|
|
defaultRetrievalModels,
|
|
defaultAssistantsVersion,
|
|
} = require('librechat-data-provider');
|
|
const { Providers } = require('@librechat/agents');
|
|
const partialRight = require('lodash/partialRight');
|
|
const { sendMessage } = require('./streamResponse');
|
|
|
|
/** Helper function to escape special characters in regex
|
|
* @param {string} string - The string to escape.
|
|
* @returns {string} The escaped string.
|
|
*/
|
|
function escapeRegExp(string) {
|
|
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
}
|
|
|
|
const addSpaceIfNeeded = (text) => (text.length > 0 && !text.endsWith(' ') ? text + ' ' : text);
|
|
|
|
const base = { message: true, initial: true };
|
|
const createOnProgress = (
|
|
{ generation = '', onProgress: _onProgress } = {
|
|
generation: '',
|
|
onProgress: null,
|
|
},
|
|
) => {
|
|
let i = 0;
|
|
let tokens = addSpaceIfNeeded(generation);
|
|
|
|
const basePayload = Object.assign({}, base, { text: tokens || '' });
|
|
|
|
const progressCallback = (chunk, { res, ...rest }) => {
|
|
basePayload.text = basePayload.text + chunk;
|
|
|
|
const payload = Object.assign({}, basePayload, rest);
|
|
sendMessage(res, payload);
|
|
if (_onProgress) {
|
|
_onProgress(payload);
|
|
}
|
|
if (i === 0) {
|
|
basePayload.initial = false;
|
|
}
|
|
i++;
|
|
};
|
|
|
|
const sendIntermediateMessage = (res, payload, extraTokens = '') => {
|
|
basePayload.text = basePayload.text + extraTokens;
|
|
const message = Object.assign({}, basePayload, payload);
|
|
sendMessage(res, message);
|
|
if (i === 0) {
|
|
basePayload.initial = false;
|
|
}
|
|
i++;
|
|
};
|
|
|
|
const onProgress = (opts) => {
|
|
return partialRight(progressCallback, opts);
|
|
};
|
|
|
|
const getPartialText = () => {
|
|
return basePayload.text;
|
|
};
|
|
|
|
return { onProgress, getPartialText, sendIntermediateMessage };
|
|
};
|
|
|
|
const handleText = async (response) => {
|
|
let { text } = response;
|
|
response.text = text;
|
|
return text;
|
|
};
|
|
|
|
const isObject = (item) => item && typeof item === 'object' && !Array.isArray(item);
|
|
const getString = (input) => (isObject(input) ? JSON.stringify(input) : input);
|
|
|
|
function formatSteps(steps) {
|
|
let output = '';
|
|
|
|
for (let i = 0; i < steps.length; i++) {
|
|
const step = steps[i];
|
|
const actionInput = getString(step.action.toolInput);
|
|
const observation = step.observation;
|
|
|
|
if (actionInput === 'N/A' || observation?.trim()?.length === 0) {
|
|
continue;
|
|
}
|
|
|
|
output += `Input: ${actionInput}\nOutput: ${getString(observation)}`;
|
|
|
|
if (steps.length > 1 && i !== steps.length - 1) {
|
|
output += '\n---\n';
|
|
}
|
|
}
|
|
|
|
return output;
|
|
}
|
|
|
|
function formatAction(action) {
|
|
const formattedAction = {
|
|
plugin: action.tool,
|
|
input: getString(action.toolInput),
|
|
thought: action.log.includes('Thought: ')
|
|
? action.log.split('\n')[0].replace('Thought: ', '')
|
|
: action.log.split('\n')[0],
|
|
};
|
|
|
|
formattedAction.thought = getString(formattedAction.thought);
|
|
|
|
if (action.tool.toLowerCase() === 'self-reflection' || formattedAction.plugin === 'N/A') {
|
|
formattedAction.inputStr = `{\n\tthought: ${formattedAction.input}${
|
|
!formattedAction.thought.includes(formattedAction.input)
|
|
? ' - ' + formattedAction.thought
|
|
: ''
|
|
}\n}`;
|
|
formattedAction.inputStr = formattedAction.inputStr.replace('N/A - ', '');
|
|
} else {
|
|
const hasThought = formattedAction.thought.length > 0;
|
|
const thought = hasThought ? `\n\tthought: ${formattedAction.thought}` : '';
|
|
formattedAction.inputStr = `{\n\tplugin: ${formattedAction.plugin}\n\tinput: ${formattedAction.input}\n${thought}}`;
|
|
}
|
|
|
|
return formattedAction;
|
|
}
|
|
|
|
/**
|
|
* Checks if the given value is truthy by being either the boolean `true` or a string
|
|
* that case-insensitively matches 'true'.
|
|
*
|
|
* @function
|
|
* @param {string|boolean|null|undefined} value - The value to check.
|
|
* @returns {boolean} Returns `true` if the value is the boolean `true` or a case-insensitive
|
|
* match for the string 'true', otherwise returns `false`.
|
|
* @example
|
|
*
|
|
* isEnabled("True"); // returns true
|
|
* isEnabled("TRUE"); // returns true
|
|
* isEnabled(true); // returns true
|
|
* isEnabled("false"); // returns false
|
|
* isEnabled(false); // returns false
|
|
* isEnabled(null); // returns false
|
|
* isEnabled(); // returns false
|
|
*/
|
|
function isEnabled(value) {
|
|
if (typeof value === 'boolean') {
|
|
return value;
|
|
}
|
|
if (typeof value === 'string') {
|
|
return value.toLowerCase().trim() === 'true';
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Checks if the provided value is 'user_provided'.
|
|
*
|
|
* @param {string} value - The value to check.
|
|
* @returns {boolean} - Returns true if the value is 'user_provided', otherwise false.
|
|
*/
|
|
const isUserProvided = (value) => value === 'user_provided';
|
|
|
|
/**
|
|
* Generate the configuration for a given key and base URL.
|
|
* @param {string} key
|
|
* @param {string} [baseURL]
|
|
* @param {string} [endpoint]
|
|
* @returns {boolean | { userProvide: boolean, userProvideURL?: boolean }}
|
|
*/
|
|
function generateConfig(key, baseURL, endpoint) {
|
|
if (!key) {
|
|
return false;
|
|
}
|
|
|
|
/** @type {{ userProvide: boolean, userProvideURL?: boolean }} */
|
|
const config = { userProvide: isUserProvided(key) };
|
|
|
|
if (baseURL) {
|
|
config.userProvideURL = isUserProvided(baseURL);
|
|
}
|
|
|
|
const assistants = isAssistantsEndpoint(endpoint);
|
|
const agents = isAgentsEndpoint(endpoint);
|
|
if (assistants) {
|
|
config.retrievalModels = defaultRetrievalModels;
|
|
config.capabilities = [
|
|
Capabilities.code_interpreter,
|
|
Capabilities.image_vision,
|
|
Capabilities.retrieval,
|
|
Capabilities.actions,
|
|
Capabilities.tools,
|
|
];
|
|
}
|
|
|
|
if (agents) {
|
|
config.capabilities = [
|
|
AgentCapabilities.execute_code,
|
|
AgentCapabilities.file_search,
|
|
AgentCapabilities.artifacts,
|
|
AgentCapabilities.actions,
|
|
AgentCapabilities.tools,
|
|
AgentCapabilities.ocr,
|
|
AgentCapabilities.chain,
|
|
];
|
|
}
|
|
|
|
if (assistants && endpoint === EModelEndpoint.azureAssistants) {
|
|
config.version = defaultAssistantsVersion.azureAssistants;
|
|
} else if (assistants) {
|
|
config.version = defaultAssistantsVersion.assistants;
|
|
}
|
|
|
|
return config;
|
|
}
|
|
|
|
/**
|
|
* Normalize the endpoint name to system-expected value.
|
|
* @param {string} name
|
|
* @returns {string}
|
|
*/
|
|
function normalizeEndpointName(name = '') {
|
|
return name.toLowerCase() === Providers.OLLAMA ? Providers.OLLAMA : name;
|
|
}
|
|
|
|
/**
|
|
* Sanitize a filename by removing any directory components, replacing non-alphanumeric characters
|
|
* @param {string} inputName
|
|
* @returns {string}
|
|
*/
|
|
function sanitizeFilename(inputName) {
|
|
// Remove any directory components
|
|
let name = path.basename(inputName);
|
|
|
|
// Replace any non-alphanumeric characters except for '.' and '-'
|
|
name = name.replace(/[^a-zA-Z0-9.-]/g, '_');
|
|
|
|
// Ensure the name doesn't start with a dot (hidden file in Unix-like systems)
|
|
if (name.startsWith('.') || name === '') {
|
|
name = '_' + name;
|
|
}
|
|
|
|
// Limit the length of the filename
|
|
const MAX_LENGTH = 255;
|
|
if (name.length > MAX_LENGTH) {
|
|
const ext = path.extname(name);
|
|
const nameWithoutExt = path.basename(name, ext);
|
|
name =
|
|
nameWithoutExt.slice(0, MAX_LENGTH - ext.length - 7) +
|
|
'-' +
|
|
crypto.randomBytes(3).toString('hex') +
|
|
ext;
|
|
}
|
|
|
|
return name;
|
|
}
|
|
|
|
module.exports = {
|
|
isEnabled,
|
|
handleText,
|
|
formatSteps,
|
|
escapeRegExp,
|
|
formatAction,
|
|
isUserProvided,
|
|
generateConfig,
|
|
addSpaceIfNeeded,
|
|
createOnProgress,
|
|
sanitizeFilename,
|
|
normalizeEndpointName,
|
|
};
|