mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-01-11 21:18:51 +01: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
291 lines
9.2 KiB
TypeScript
291 lines
9.2 KiB
TypeScript
import { logger } from '@librechat/data-schemas';
|
|
import { EModelEndpoint, EToolResources, AgentCapabilities } from 'librechat-data-provider';
|
|
import type { AgentToolResources, TFile, AgentBaseResource } from 'librechat-data-provider';
|
|
import type { FilterQuery, QueryOptions, ProjectionType } from 'mongoose';
|
|
import type { IMongoFile, IUser } from '@librechat/data-schemas';
|
|
import type { Request as ServerRequest } from 'express';
|
|
import type { AppConfig } from '~/types/';
|
|
|
|
/**
|
|
* Function type for retrieving files from the database
|
|
* @param filter - MongoDB filter query for files
|
|
* @param _sortOptions - Sorting options (currently unused)
|
|
* @param selectFields - Field selection options
|
|
* @param options - Additional options including userId and agentId for access control
|
|
* @returns Promise resolving to array of files
|
|
*/
|
|
export type TGetFiles = (
|
|
filter: FilterQuery<IMongoFile>,
|
|
_sortOptions: ProjectionType<IMongoFile> | null | undefined,
|
|
selectFields: QueryOptions<IMongoFile> | null | undefined,
|
|
options?: { userId?: string; agentId?: string },
|
|
) => Promise<Array<TFile>>;
|
|
|
|
/**
|
|
* Helper function to add a file to a specific tool resource category
|
|
* Prevents duplicate files within the same resource category
|
|
* @param params - Parameters object
|
|
* @param params.file - The file to add to the resource
|
|
* @param params.resourceType - The type of tool resource (e.g., execute_code, file_search, image_edit)
|
|
* @param params.tool_resources - The agent's tool resources object to update
|
|
* @param params.processedResourceFiles - Set tracking processed files per resource type
|
|
*/
|
|
const addFileToResource = ({
|
|
file,
|
|
resourceType,
|
|
tool_resources,
|
|
processedResourceFiles,
|
|
}: {
|
|
file: TFile;
|
|
resourceType: EToolResources;
|
|
tool_resources: AgentToolResources;
|
|
processedResourceFiles: Set<string>;
|
|
}): void => {
|
|
if (!file.file_id) {
|
|
return;
|
|
}
|
|
|
|
const resourceKey = `${resourceType}:${file.file_id}`;
|
|
if (processedResourceFiles.has(resourceKey)) {
|
|
return;
|
|
}
|
|
|
|
const resource = tool_resources[resourceType as keyof AgentToolResources] ?? {};
|
|
if (!resource.files) {
|
|
(tool_resources[resourceType as keyof AgentToolResources] as AgentBaseResource) = {
|
|
...resource,
|
|
files: [],
|
|
};
|
|
}
|
|
|
|
// Check if already exists in the files array
|
|
const resourceFiles = tool_resources[resourceType as keyof AgentToolResources]?.files;
|
|
const alreadyExists = resourceFiles?.some((f: TFile) => f.file_id === file.file_id);
|
|
|
|
if (!alreadyExists) {
|
|
resourceFiles?.push(file);
|
|
processedResourceFiles.add(resourceKey);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Categorizes a file into the appropriate tool resource based on its properties
|
|
* Files are categorized as:
|
|
* - execute_code: Files with fileIdentifier metadata
|
|
* - file_search: Files marked as embedded
|
|
* - image_edit: Image files in the request file set with dimensions
|
|
* @param params - Parameters object
|
|
* @param params.file - The file to categorize
|
|
* @param params.tool_resources - The agent's tool resources to update
|
|
* @param params.requestFileSet - Set of file IDs from the current request
|
|
* @param params.processedResourceFiles - Set tracking processed files per resource type
|
|
*/
|
|
const categorizeFileForToolResources = ({
|
|
file,
|
|
tool_resources,
|
|
requestFileSet,
|
|
processedResourceFiles,
|
|
}: {
|
|
file: TFile;
|
|
tool_resources: AgentToolResources;
|
|
requestFileSet: Set<string>;
|
|
processedResourceFiles: Set<string>;
|
|
}): void => {
|
|
if (file.metadata?.fileIdentifier) {
|
|
addFileToResource({
|
|
file,
|
|
resourceType: EToolResources.execute_code,
|
|
tool_resources,
|
|
processedResourceFiles,
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (file.embedded === true) {
|
|
addFileToResource({
|
|
file,
|
|
resourceType: EToolResources.file_search,
|
|
tool_resources,
|
|
processedResourceFiles,
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (
|
|
requestFileSet.has(file.file_id) &&
|
|
file.type.startsWith('image') &&
|
|
file.height &&
|
|
file.width
|
|
) {
|
|
addFileToResource({
|
|
file,
|
|
resourceType: EToolResources.image_edit,
|
|
tool_resources,
|
|
processedResourceFiles,
|
|
});
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Primes resources for agent execution by processing attachments and tool resources
|
|
* This function:
|
|
* 1. Fetches OCR files if OCR is enabled
|
|
* 2. Processes attachment files
|
|
* 3. Categorizes files into appropriate tool resources
|
|
* 4. Prevents duplicate files across all sources
|
|
*
|
|
* @param params - Parameters object
|
|
* @param params.req - Express request object
|
|
* @param params.appConfig - Application configuration object
|
|
* @param params.getFiles - Function to retrieve files from database
|
|
* @param params.requestFileSet - Set of file IDs from the current request
|
|
* @param params.attachments - Promise resolving to array of attachment files
|
|
* @param params.tool_resources - Existing tool resources for the agent
|
|
* @returns Promise resolving to processed attachments and updated tool resources
|
|
*/
|
|
export const primeResources = async ({
|
|
req,
|
|
appConfig,
|
|
getFiles,
|
|
requestFileSet,
|
|
attachments: _attachments,
|
|
tool_resources: _tool_resources,
|
|
agentId,
|
|
}: {
|
|
req: ServerRequest & { user?: IUser };
|
|
appConfig: AppConfig;
|
|
requestFileSet: Set<string>;
|
|
attachments: Promise<Array<TFile | null>> | undefined;
|
|
tool_resources: AgentToolResources | undefined;
|
|
getFiles: TGetFiles;
|
|
agentId?: string;
|
|
}): Promise<{
|
|
attachments: Array<TFile | undefined> | undefined;
|
|
tool_resources: AgentToolResources | undefined;
|
|
}> => {
|
|
try {
|
|
/**
|
|
* Array to collect all unique files that will be returned as attachments
|
|
* Files are added from OCR results and attachment promises, with duplicates prevented
|
|
*/
|
|
const attachments: Array<TFile> = [];
|
|
/**
|
|
* Set of file IDs already added to the attachments array
|
|
* Used to prevent duplicate files from being added multiple times
|
|
* Pre-populated with files from non-OCR tool_resources to prevent re-adding them
|
|
*/
|
|
const attachmentFileIds = new Set<string>();
|
|
/**
|
|
* Set tracking which files have been added to specific tool resource categories
|
|
* Format: "resourceType:fileId" (e.g., "execute_code:file123")
|
|
* Prevents the same file from being added multiple times to the same resource
|
|
*/
|
|
const processedResourceFiles = new Set<string>();
|
|
/**
|
|
* The agent's tool resources object that will be updated with categorized files
|
|
* Initialized from input parameter or empty object if not provided
|
|
*/
|
|
const tool_resources = _tool_resources ?? {};
|
|
|
|
// Track existing files in tool_resources to prevent duplicates within resources
|
|
for (const [resourceType, resource] of Object.entries(tool_resources)) {
|
|
if (resource?.files && Array.isArray(resource.files)) {
|
|
for (const file of resource.files) {
|
|
if (file?.file_id) {
|
|
processedResourceFiles.add(`${resourceType}:${file.file_id}`);
|
|
// Files from non-OCR resources should not be added to attachments from _attachments
|
|
if (resourceType !== EToolResources.ocr) {
|
|
attachmentFileIds.add(file.file_id);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
const isOCREnabled = (
|
|
appConfig?.endpoints?.[EModelEndpoint.agents]?.capabilities ?? []
|
|
).includes(AgentCapabilities.ocr);
|
|
|
|
if (tool_resources[EToolResources.ocr]?.file_ids && isOCREnabled) {
|
|
const context = await getFiles(
|
|
{
|
|
file_id: { $in: tool_resources.ocr.file_ids },
|
|
},
|
|
{},
|
|
{},
|
|
{ userId: req.user?.id, agentId },
|
|
);
|
|
|
|
for (const file of context) {
|
|
if (!file?.file_id) {
|
|
continue;
|
|
}
|
|
|
|
// Clear from attachmentFileIds if it was pre-added
|
|
attachmentFileIds.delete(file.file_id);
|
|
|
|
// Add to attachments
|
|
attachments.push(file);
|
|
attachmentFileIds.add(file.file_id);
|
|
|
|
// Categorize for tool resources
|
|
categorizeFileForToolResources({
|
|
file,
|
|
tool_resources,
|
|
requestFileSet,
|
|
processedResourceFiles,
|
|
});
|
|
}
|
|
}
|
|
|
|
if (!_attachments) {
|
|
return { attachments: attachments.length > 0 ? attachments : undefined, tool_resources };
|
|
}
|
|
|
|
const files = await _attachments;
|
|
|
|
for (const file of files) {
|
|
if (!file) {
|
|
continue;
|
|
}
|
|
|
|
categorizeFileForToolResources({
|
|
file,
|
|
tool_resources,
|
|
requestFileSet,
|
|
processedResourceFiles,
|
|
});
|
|
|
|
if (file.file_id && attachmentFileIds.has(file.file_id)) {
|
|
continue;
|
|
}
|
|
|
|
attachments.push(file);
|
|
if (file.file_id) {
|
|
attachmentFileIds.add(file.file_id);
|
|
}
|
|
}
|
|
|
|
return { attachments: attachments.length > 0 ? attachments : [], tool_resources };
|
|
} catch (error) {
|
|
logger.error('Error priming resources', error);
|
|
|
|
// Safely try to get attachments without rethrowing
|
|
let safeAttachments: Array<TFile | undefined> = [];
|
|
if (_attachments) {
|
|
try {
|
|
const attachmentFiles = await _attachments;
|
|
safeAttachments = (attachmentFiles?.filter((file) => !!file) ?? []) as Array<TFile>;
|
|
} catch (attachmentError) {
|
|
// If attachments promise is also rejected, just use empty array
|
|
logger.error('Error resolving attachments in catch block', attachmentError);
|
|
safeAttachments = [];
|
|
}
|
|
}
|
|
|
|
return {
|
|
attachments: safeAttachments,
|
|
tool_resources: _tool_resources,
|
|
};
|
|
}
|
|
};
|