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

* WIP: app.locals refactoring
WIP: appConfig
fix: update memory configuration retrieval to use getAppConfig based on user role
fix: update comment for AppConfig interface to clarify purpose
🏷️ refactor: Update tests to use getAppConfig for endpoint configurations
ci: Update AppService tests to initialize app config instead of app.locals
ci: Integrate getAppConfig into remaining tests
refactor: Update multer storage destination to use promise-based getAppConfig and improve error handling in tests
refactor: Rename initializeAppConfig to setAppConfig and update related tests
ci: Mock getAppConfig in various tests to provide default configurations
refactor: Update convertMCPToolsToPlugins to use mcpManager for server configuration and adjust related tests
chore: rename `Config/getAppConfig` -> `Config/app`
fix: streamline OpenAI image tools configuration by removing direct appConfig dependency and using function parameters
chore: correct parameter documentation for imageOutputType in ToolService.js
refactor: remove `getCustomConfig` dependency in config route
refactor: update domain validation to use appConfig for allowed domains
refactor: use appConfig registration property
chore: remove app parameter from AppService invocation
refactor: update AppConfig interface to correct registration and turnstile configurations
refactor: remove getCustomConfig dependency and use getAppConfig in PluginController, multer, and MCP services
refactor: replace getCustomConfig with getAppConfig in STTService, TTSService, and related files
refactor: replace getCustomConfig with getAppConfig in Conversation and Message models, update tempChatRetention functions to use AppConfig type
refactor: update getAppConfig calls in Conversation and Message models to include user role for temporary chat expiration
ci: update related tests
refactor: update getAppConfig call in getCustomConfigSpeech to include user role
fix: update appConfig usage to access allowedDomains from actions instead of registration
refactor: enhance AppConfig to include fileStrategies and update related file strategy logic
refactor: update imports to use normalizeEndpointName from @librechat/api and remove redundant definitions
chore: remove deprecated unused RunManager
refactor: get balance config primarily from appConfig
refactor: remove customConfig dependency for appConfig and streamline loadConfigModels logic
refactor: remove getCustomConfig usage and use app config in file citations
refactor: consolidate endpoint loading logic into loadEndpoints function
refactor: update appConfig access to use endpoints structure across various services
refactor: implement custom endpoints configuration and streamline endpoint loading logic
refactor: update getAppConfig call to include user role parameter
refactor: streamline endpoint configuration and enhance appConfig usage across services
refactor: replace getMCPAuthMap with getUserMCPAuthMap and remove unused getCustomConfig file
refactor: add type annotation for loadedEndpoints in loadEndpoints function
refactor: move /services/Files/images/parse to TS API
chore: add missing FILE_CITATIONS permission to IRole interface
refactor: restructure toolkits to TS API
refactor: separate manifest logic into its own module
refactor: consolidate tool loading logic into a new tools module for startup logic
refactor: move interface config logic to TS API
refactor: migrate checkEmailConfig to TypeScript and update imports
refactor: add FunctionTool interface and availableTools to AppConfig
refactor: decouple caching and DB operations from AppService, make part of consolidated `getAppConfig`
WIP: fix tests
* fix: rebase conflicts
* refactor: remove app.locals references
* refactor: replace getBalanceConfig with getAppConfig in various strategies and middleware
* refactor: replace appConfig?.balance with getBalanceConfig in various controllers and clients
* test: add balance configuration to titleConvo method in AgentClient tests
* chore: remove unused `openai-chat-tokens` package
* chore: remove unused imports in initializeMCPs.js
* refactor: update balance configuration to use getAppConfig instead of getBalanceConfig
* refactor: integrate configMiddleware for centralized configuration handling
* refactor: optimize email domain validation by removing unnecessary async calls
* refactor: simplify multer storage configuration by removing async calls
* refactor: reorder imports for better readability in user.js
* refactor: replace getAppConfig calls with req.config for improved performance
* chore: replace getAppConfig calls with req.config in tests for centralized configuration handling
* chore: remove unused override config
* refactor: add configMiddleware to endpoint route and replace getAppConfig with req.config
* chore: remove customConfig parameter from TTSService constructor
* refactor: pass appConfig from request to processFileCitations for improved configuration handling
* refactor: remove configMiddleware from endpoint route and retrieve appConfig directly in getEndpointsConfig if not in `req.config`
* test: add mockAppConfig to processFileCitations tests for improved configuration handling
* fix: pass req.config to hasCustomUserVars and call without await after synchronous refactor
* fix: type safety in useExportConversation
* refactor: retrieve appConfig using getAppConfig in PluginController and remove configMiddleware from plugins route, to avoid always retrieving when plugins are cached
* chore: change `MongoUser` typedef to `IUser`
* fix: Add `user` and `config` fields to ServerRequest and update JSDoc type annotations from Express.Request to ServerRequest
* fix: remove unused setAppConfig mock from Server configuration tests
417 lines
14 KiB
JavaScript
417 lines
14 KiB
JavaScript
const { logger } = require('@librechat/data-schemas');
|
|
const { SerpAPI } = require('@langchain/community/tools/serpapi');
|
|
const { Calculator } = require('@langchain/community/tools/calculator');
|
|
const { mcpToolPattern, loadWebSearchAuth } = require('@librechat/api');
|
|
const { EnvVar, createCodeExecutionTool, createSearchTool } = require('@librechat/agents');
|
|
const { Tools, Constants, EToolResources, replaceSpecialVars } = require('librechat-data-provider');
|
|
const {
|
|
availableTools,
|
|
manifestToolMap,
|
|
// Basic Tools
|
|
GoogleSearchAPI,
|
|
// Structured Tools
|
|
DALLE3,
|
|
FluxAPI,
|
|
OpenWeather,
|
|
StructuredSD,
|
|
StructuredACS,
|
|
TraversaalSearch,
|
|
StructuredWolfram,
|
|
createYouTubeTools,
|
|
TavilySearchResults,
|
|
createOpenAIImageTools,
|
|
} = require('../');
|
|
const { primeFiles: primeCodeFiles } = require('~/server/services/Files/Code/process');
|
|
const { createFileSearchTool, primeFiles: primeSearchFiles } = require('./fileSearch');
|
|
const { getUserPluginAuthValue } = require('~/server/services/PluginService');
|
|
const { createMCPTool, createMCPTools } = require('~/server/services/MCP');
|
|
const { loadAuthValues } = require('~/server/services/Tools/credentials');
|
|
const { getCachedTools } = require('~/server/services/Config');
|
|
|
|
/**
|
|
* Validates the availability and authentication of tools for a user based on environment variables or user-specific plugin authentication values.
|
|
* Tools without required authentication or with valid authentication are considered valid.
|
|
*
|
|
* @param {Object} user The user object for whom to validate tool access.
|
|
* @param {Array<string>} tools An array of tool identifiers to validate. Defaults to an empty array.
|
|
* @returns {Promise<Array<string>>} A promise that resolves to an array of valid tool identifiers.
|
|
*/
|
|
const validateTools = async (user, tools = []) => {
|
|
try {
|
|
const validToolsSet = new Set(tools);
|
|
const availableToolsToValidate = availableTools.filter((tool) =>
|
|
validToolsSet.has(tool.pluginKey),
|
|
);
|
|
|
|
/**
|
|
* Validates the credentials for a given auth field or set of alternate auth fields for a tool.
|
|
* If valid admin or user authentication is found, the function returns early. Otherwise, it removes the tool from the set of valid tools.
|
|
*
|
|
* @param {string} authField The authentication field or fields (separated by "||" for alternates) to validate.
|
|
* @param {string} toolName The identifier of the tool being validated.
|
|
*/
|
|
const validateCredentials = async (authField, toolName) => {
|
|
const fields = authField.split('||');
|
|
for (const field of fields) {
|
|
const adminAuth = process.env[field];
|
|
if (adminAuth && adminAuth.length > 0) {
|
|
return;
|
|
}
|
|
|
|
let userAuth = null;
|
|
try {
|
|
userAuth = await getUserPluginAuthValue(user, field);
|
|
} catch (err) {
|
|
if (field === fields[fields.length - 1] && !userAuth) {
|
|
throw err;
|
|
}
|
|
}
|
|
if (userAuth && userAuth.length > 0) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
validToolsSet.delete(toolName);
|
|
};
|
|
|
|
for (const tool of availableToolsToValidate) {
|
|
if (!tool.authConfig || tool.authConfig.length === 0) {
|
|
continue;
|
|
}
|
|
|
|
for (const auth of tool.authConfig) {
|
|
await validateCredentials(auth.authField, tool.pluginKey);
|
|
}
|
|
}
|
|
|
|
return Array.from(validToolsSet.values());
|
|
} catch (err) {
|
|
logger.error('[validateTools] There was a problem validating tools', err);
|
|
throw new Error(err);
|
|
}
|
|
};
|
|
|
|
/** @typedef {typeof import('@langchain/core/tools').Tool} ToolConstructor */
|
|
/** @typedef {import('@langchain/core/tools').Tool} Tool */
|
|
|
|
/**
|
|
* Initializes a tool with authentication values for the given user, supporting alternate authentication fields.
|
|
* Authentication fields can have alternates separated by "||", and the first defined variable will be used.
|
|
*
|
|
* @param {string} userId The user ID for which the tool is being loaded.
|
|
* @param {Array<string>} authFields Array of strings representing the authentication fields. Supports alternate fields delimited by "||".
|
|
* @param {ToolConstructor} ToolConstructor The constructor function for the tool to be initialized.
|
|
* @param {Object} options Optional parameters to be passed to the tool constructor alongside authentication values.
|
|
* @returns {() => Promise<Tool>} An Async function that, when called, asynchronously initializes and returns an instance of the tool with authentication.
|
|
*/
|
|
const loadToolWithAuth = (userId, authFields, ToolConstructor, options = {}) => {
|
|
return async function () {
|
|
const authValues = await loadAuthValues({ userId, authFields });
|
|
return new ToolConstructor({ ...options, ...authValues, userId });
|
|
};
|
|
};
|
|
|
|
/**
|
|
* @param {string} toolKey
|
|
* @returns {Array<string>}
|
|
*/
|
|
const getAuthFields = (toolKey) => {
|
|
return manifestToolMap[toolKey]?.authConfig.map((auth) => auth.authField) ?? [];
|
|
};
|
|
|
|
/**
|
|
*
|
|
* @param {object} params
|
|
* @param {string} params.user
|
|
* @param {Record<string, Record<string, string>>} [object.userMCPAuthMap]
|
|
* @param {AbortSignal} [object.signal]
|
|
* @param {Pick<Agent, 'id' | 'provider' | 'model'>} [params.agent]
|
|
* @param {string} [params.model]
|
|
* @param {EModelEndpoint} [params.endpoint]
|
|
* @param {LoadToolOptions} [params.options]
|
|
* @param {boolean} [params.useSpecs]
|
|
* @param {Array<string>} params.tools
|
|
* @param {boolean} [params.functions]
|
|
* @param {boolean} [params.returnMap]
|
|
* @param {AppConfig['webSearch']} [params.webSearch]
|
|
* @param {AppConfig['fileStrategy']} [params.fileStrategy]
|
|
* @param {AppConfig['imageOutputType']} [params.imageOutputType]
|
|
* @returns {Promise<{ loadedTools: Tool[], toolContextMap: Object<string, any> } | Record<string,Tool>>}
|
|
*/
|
|
const loadTools = async ({
|
|
user,
|
|
agent,
|
|
model,
|
|
signal,
|
|
endpoint,
|
|
userMCPAuthMap,
|
|
tools = [],
|
|
options = {},
|
|
functions = true,
|
|
returnMap = false,
|
|
webSearch,
|
|
fileStrategy,
|
|
imageOutputType,
|
|
}) => {
|
|
const toolConstructors = {
|
|
flux: FluxAPI,
|
|
calculator: Calculator,
|
|
google: GoogleSearchAPI,
|
|
open_weather: OpenWeather,
|
|
wolfram: StructuredWolfram,
|
|
'stable-diffusion': StructuredSD,
|
|
'azure-ai-search': StructuredACS,
|
|
traversaal_search: TraversaalSearch,
|
|
tavily_search_results_json: TavilySearchResults,
|
|
};
|
|
|
|
const customConstructors = {
|
|
serpapi: async (_toolContextMap) => {
|
|
const authFields = getAuthFields('serpapi');
|
|
let envVar = authFields[0] ?? '';
|
|
let apiKey = process.env[envVar];
|
|
if (!apiKey) {
|
|
apiKey = await getUserPluginAuthValue(user, envVar);
|
|
}
|
|
return new SerpAPI(apiKey, {
|
|
location: 'Austin,Texas,United States',
|
|
hl: 'en',
|
|
gl: 'us',
|
|
});
|
|
},
|
|
youtube: async (_toolContextMap) => {
|
|
const authFields = getAuthFields('youtube');
|
|
const authValues = await loadAuthValues({ userId: user, authFields });
|
|
return createYouTubeTools(authValues);
|
|
},
|
|
image_gen_oai: async (toolContextMap) => {
|
|
const authFields = getAuthFields('image_gen_oai');
|
|
const authValues = await loadAuthValues({ userId: user, authFields });
|
|
const imageFiles = options.tool_resources?.[EToolResources.image_edit]?.files ?? [];
|
|
let toolContext = '';
|
|
for (let i = 0; i < imageFiles.length; i++) {
|
|
const file = imageFiles[i];
|
|
if (!file) {
|
|
continue;
|
|
}
|
|
if (i === 0) {
|
|
toolContext =
|
|
'Image files provided in this request (their image IDs listed in order of appearance) available for image editing:';
|
|
}
|
|
toolContext += `\n\t- ${file.file_id}`;
|
|
if (i === imageFiles.length - 1) {
|
|
toolContext += `\n\nInclude any you need in the \`image_ids\` array when calling \`${EToolResources.image_edit}_oai\`. You may also include previously referenced or generated image IDs.`;
|
|
}
|
|
}
|
|
if (toolContext) {
|
|
toolContextMap.image_edit_oai = toolContext;
|
|
}
|
|
return createOpenAIImageTools({
|
|
...authValues,
|
|
isAgent: !!agent,
|
|
req: options.req,
|
|
imageOutputType,
|
|
fileStrategy,
|
|
imageFiles,
|
|
});
|
|
},
|
|
};
|
|
|
|
const requestedTools = {};
|
|
|
|
if (functions === true) {
|
|
toolConstructors.dalle = DALLE3;
|
|
}
|
|
|
|
/** @type {ImageGenOptions} */
|
|
const imageGenOptions = {
|
|
isAgent: !!agent,
|
|
req: options.req,
|
|
fileStrategy,
|
|
processFileURL: options.processFileURL,
|
|
returnMetadata: options.returnMetadata,
|
|
uploadImageBuffer: options.uploadImageBuffer,
|
|
};
|
|
|
|
const toolOptions = {
|
|
flux: imageGenOptions,
|
|
dalle: imageGenOptions,
|
|
'stable-diffusion': imageGenOptions,
|
|
serpapi: { location: 'Austin,Texas,United States', hl: 'en', gl: 'us' },
|
|
};
|
|
|
|
/** @type {Record<string, string>} */
|
|
const toolContextMap = {};
|
|
const cachedTools = (await getCachedTools({ userId: user, includeGlobal: true })) ?? {};
|
|
const requestedMCPTools = {};
|
|
|
|
for (const tool of tools) {
|
|
if (tool === Tools.execute_code) {
|
|
requestedTools[tool] = async () => {
|
|
const authValues = await loadAuthValues({
|
|
userId: user,
|
|
authFields: [EnvVar.CODE_API_KEY],
|
|
});
|
|
const codeApiKey = authValues[EnvVar.CODE_API_KEY];
|
|
const { files, toolContext } = await primeCodeFiles(
|
|
{
|
|
...options,
|
|
agentId: agent?.id,
|
|
},
|
|
codeApiKey,
|
|
);
|
|
if (toolContext) {
|
|
toolContextMap[tool] = toolContext;
|
|
}
|
|
const CodeExecutionTool = createCodeExecutionTool({
|
|
user_id: user,
|
|
files,
|
|
...authValues,
|
|
});
|
|
CodeExecutionTool.apiKey = codeApiKey;
|
|
return CodeExecutionTool;
|
|
};
|
|
continue;
|
|
} else if (tool === Tools.file_search) {
|
|
requestedTools[tool] = async () => {
|
|
const { files, toolContext } = await primeSearchFiles({
|
|
...options,
|
|
agentId: agent?.id,
|
|
});
|
|
if (toolContext) {
|
|
toolContextMap[tool] = toolContext;
|
|
}
|
|
return createFileSearchTool({ req: options.req, files, entity_id: agent?.id });
|
|
};
|
|
continue;
|
|
} else if (tool === Tools.web_search) {
|
|
const result = await loadWebSearchAuth({
|
|
userId: user,
|
|
loadAuthValues,
|
|
webSearchConfig: webSearch,
|
|
});
|
|
const { onSearchResults, onGetHighlights } = options?.[Tools.web_search] ?? {};
|
|
requestedTools[tool] = async () => {
|
|
toolContextMap[tool] = `# \`${tool}\`:
|
|
Current Date & Time: ${replaceSpecialVars({ text: '{{iso_datetime}}' })}
|
|
1. **Execute immediately without preface** when using \`${tool}\`.
|
|
2. **After the search, begin with a brief summary** that directly addresses the query without headers or explaining your process.
|
|
3. **Structure your response clearly** using Markdown formatting (Level 2 headers for sections, lists for multiple points, tables for comparisons).
|
|
4. **Cite sources properly** according to the citation anchor format, utilizing group anchors when appropriate.
|
|
5. **Tailor your approach to the query type** (academic, news, coding, etc.) while maintaining an expert, journalistic, unbiased tone.
|
|
6. **Provide comprehensive information** with specific details, examples, and as much relevant context as possible from search results.
|
|
7. **Avoid moralizing language.**
|
|
`.trim();
|
|
return createSearchTool({
|
|
...result.authResult,
|
|
onSearchResults,
|
|
onGetHighlights,
|
|
logger,
|
|
});
|
|
};
|
|
continue;
|
|
} else if (tool && cachedTools && mcpToolPattern.test(tool)) {
|
|
const [toolName, serverName] = tool.split(Constants.mcp_delimiter);
|
|
if (toolName === Constants.mcp_all) {
|
|
const currentMCPGenerator = async (index) =>
|
|
createMCPTools({
|
|
req: options.req,
|
|
res: options.res,
|
|
index,
|
|
serverName,
|
|
userMCPAuthMap,
|
|
model: agent?.model ?? model,
|
|
provider: agent?.provider ?? endpoint,
|
|
signal,
|
|
});
|
|
requestedMCPTools[serverName] = [currentMCPGenerator];
|
|
continue;
|
|
}
|
|
const currentMCPGenerator = async (index) =>
|
|
createMCPTool({
|
|
index,
|
|
req: options.req,
|
|
res: options.res,
|
|
toolKey: tool,
|
|
userMCPAuthMap,
|
|
model: agent?.model ?? model,
|
|
provider: agent?.provider ?? endpoint,
|
|
signal,
|
|
});
|
|
requestedMCPTools[serverName] = requestedMCPTools[serverName] || [];
|
|
requestedMCPTools[serverName].push(currentMCPGenerator);
|
|
continue;
|
|
}
|
|
|
|
if (customConstructors[tool]) {
|
|
requestedTools[tool] = async () => customConstructors[tool](toolContextMap);
|
|
continue;
|
|
}
|
|
|
|
if (toolConstructors[tool]) {
|
|
const options = toolOptions[tool] || {};
|
|
const toolInstance = loadToolWithAuth(
|
|
user,
|
|
getAuthFields(tool),
|
|
toolConstructors[tool],
|
|
options,
|
|
);
|
|
requestedTools[tool] = toolInstance;
|
|
continue;
|
|
}
|
|
}
|
|
|
|
if (returnMap) {
|
|
return requestedTools;
|
|
}
|
|
|
|
const toolPromises = [];
|
|
for (const tool of tools) {
|
|
const validTool = requestedTools[tool];
|
|
if (validTool) {
|
|
toolPromises.push(
|
|
validTool().catch((error) => {
|
|
logger.error(`Error loading tool ${tool}:`, error);
|
|
return null;
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|
|
const loadedTools = (await Promise.all(toolPromises)).flatMap((plugin) => plugin || []);
|
|
const mcpToolPromises = [];
|
|
/** MCP server tools are initialized sequentially by server */
|
|
let index = -1;
|
|
for (const [serverName, generators] of Object.entries(requestedMCPTools)) {
|
|
index++;
|
|
for (const generator of generators) {
|
|
try {
|
|
if (generator && generators.length === 1) {
|
|
mcpToolPromises.push(
|
|
generator(index).catch((error) => {
|
|
logger.error(`Error loading ${serverName} tools:`, error);
|
|
return null;
|
|
}),
|
|
);
|
|
continue;
|
|
}
|
|
const mcpTool = await generator(index);
|
|
if (Array.isArray(mcpTool)) {
|
|
loadedTools.push(...mcpTool);
|
|
} else if (mcpTool) {
|
|
loadedTools.push(mcpTool);
|
|
}
|
|
} catch (error) {
|
|
logger.error(`Error loading MCP tool for server ${serverName}:`, error);
|
|
}
|
|
}
|
|
}
|
|
loadedTools.push(...(await Promise.all(mcpToolPromises)).flatMap((plugin) => plugin || []));
|
|
return { loadedTools, toolContextMap };
|
|
};
|
|
|
|
module.exports = {
|
|
loadToolWithAuth,
|
|
validateTools,
|
|
loadTools,
|
|
};
|