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

* 🧠 feat: User Memories for Conversational Context
chore: mcp typing, use `t`
WIP: first pass, Memories UI
- Added MemoryViewer component for displaying, editing, and deleting user memories.
- Integrated data provider hooks for fetching, updating, and deleting memories.
- Implemented pagination and loading states for better user experience.
- Created unit tests for MemoryViewer to ensure functionality and interaction with data provider.
- Updated translation files to include new UI strings related to memories.
chore: move mcp-related files to own directory
chore: rename librechat-mcp to librechat-api
WIP: first pass, memory processing and data schemas
chore: linting in fileSearch.js query description
chore: rename librechat-api to @librechat/api across the project
WIP: first pass, functional memory agent
feat: add MemoryEditDialog and MemoryViewer components for managing user memories
- Introduced MemoryEditDialog for editing memory entries with validation and toast notifications.
- Updated MemoryViewer to support editing and deleting memories, including pagination and loading states.
- Enhanced data provider to handle memory updates with optional original key for better management.
- Added new localization strings for memory-related UI elements.
feat: add memory permissions management
- Implemented memory permissions in the backend, allowing roles to have specific permissions for using, creating, updating, and reading memories.
- Added new API endpoints for updating memory permissions associated with roles.
- Created a new AdminSettings component for managing memory permissions in the frontend.
- Integrated memory permissions into the existing roles and permissions schemas.
- Updated the interface to include memory settings and permissions.
- Enhanced the MemoryViewer component to conditionally render admin settings based on user roles.
- Added localization support for memory permissions in the translation files.
feat: move AdminSettings component to a new position in MemoryViewer for better visibility
refactor: clean up commented code in MemoryViewer component
feat: enhance MemoryViewer with search functionality and improve MemoryEditDialog integration
- Added a search input to filter memories in the MemoryViewer component.
- Refactored MemoryEditDialog to accept children for better customization.
- Updated MemoryViewer to utilize the new EditMemoryButton and DeleteMemoryButton components for editing and deleting memories.
- Improved localization support by adding new strings for memory filtering and deletion confirmation.
refactor: optimize memory filtering in MemoryViewer using match-sorter
- Replaced manual filtering logic with match-sorter for improved search functionality.
- Enhanced performance and readability of the filteredMemories computation.
feat: enhance MemoryEditDialog with triggerRef and improve updateMemory mutation handling
feat: implement access control for MemoryEditDialog and MemoryViewer components
refactor: remove commented out code and create runMemory method
refactor: rename role based files
feat: implement access control for memory usage in AgentClient
refactor: simplify checkVisionRequest method in AgentClient by removing commented-out code
refactor: make `agents` dir in api package
refactor: migrate Azure utilities to TypeScript and consolidate imports
refactor: move sanitizeFilename function to a new file and update imports, add related tests
refactor: update LLM configuration types and consolidate Azure options in the API package
chore: linting
chore: import order
refactor: replace getLLMConfig with getOpenAIConfig and remove unused LLM configuration file
chore: update winston-daily-rotate-file to version 5.0.0 and add object-hash dependency in package-lock.json
refactor: move primeResources and optionalChainWithEmptyCheck functions to resources.ts and update imports
refactor: move createRun function to a new run.ts file and update related imports
fix: ensure safeAttachments is correctly typed as an array of TFile
chore: add node-fetch dependency and refactor fetch-related functions into packages/api/utils, removing the old generators file
refactor: enhance TEndpointOption type by using Pick to streamline endpoint fields and add new properties for model parameters and client options
feat: implement initializeOpenAIOptions function and update OpenAI types for enhanced configuration handling
fix: update types due to new TEndpointOption typing
fix: ensure safe access to group parameters in initializeOpenAIOptions function
fix: remove redundant API key validation comment in initializeOpenAIOptions function
refactor: rename initializeOpenAIOptions to initializeOpenAI for consistency and update related documentation
refactor: decouple req.body fields and tool loading from initializeAgentOptions
chore: linting
refactor: adjust column widths in MemoryViewer for improved layout
refactor: simplify agent initialization by creating loadAgent function and removing unused code
feat: add memory configuration loading and validation functions
WIP: first pass, memory processing with config
feat: implement memory callback and artifact handling
feat: implement memory artifacts display and processing updates
feat: add memory configuration options and schema validation for validKeys
fix: update MemoryEditDialog and MemoryViewer to handle memory state and display improvements
refactor: remove padding from BookmarkTable and MemoryViewer headers for consistent styling
WIP: initial tokenLimit config and move Tokenizer to @librechat/api
refactor: update mongoMeili plugin methods to use callback for better error handling
feat: enhance memory management with token tracking and usage metrics
- Added token counting for memory entries to enforce limits and provide usage statistics.
- Updated memory retrieval and update routes to include total token usage and limit.
- Enhanced MemoryEditDialog and MemoryViewer components to display memory usage and token information.
- Refactored memory processing functions to handle token limits and provide feedback on memory capacity.
feat: implement memory artifact handling in attachment handler
- Enhanced useAttachmentHandler to process memory artifacts when receiving updates.
- Introduced handleMemoryArtifact utility to manage memory updates and deletions.
- Updated query client to reflect changes in memory state based on incoming data.
refactor: restructure web search key extraction logic
- Moved the logic for extracting API keys from the webSearchAuth configuration into a dedicated function, getWebSearchKeys.
- Updated webSearchKeys to utilize the new function for improved clarity and maintainability.
- Prevents build time errors
feat: add personalization settings and memory preferences management
- Introduced a new Personalization tab in settings to manage user memory preferences.
- Implemented API endpoints and client-side logic for updating memory preferences.
- Enhanced user interface components to reflect personalization options and memory usage.
- Updated permissions to allow users to opt out of memory features.
- Added localization support for new settings and messages related to personalization.
style: personalization switch class
feat: add PersonalizationIcon and align Side Panel UI
feat: implement memory creation functionality
- Added a new API endpoint for creating memory entries, including validation for key and value.
- Introduced MemoryCreateDialog component for user interface to facilitate memory creation.
- Integrated token limit checks to prevent exceeding user memory capacity.
- Updated MemoryViewer to include a button for opening the memory creation dialog.
- Enhanced localization support for new messages related to memory creation.
feat: enhance message processing with configurable window size
- Updated AgentClient to use a configurable message window size for processing messages.
- Introduced messageWindowSize option in memory configuration schema with a default value of 5.
- Improved logic for selecting messages to process based on the configured window size.
chore: update librechat-data-provider version to 0.7.87 in package.json and package-lock.json
chore: remove OpenAPIPlugin and its associated tests
chore: remove MIGRATION_README.md as migration tasks are completed
ci: fix backend tests
chore: remove unused translation keys from localization file
chore: remove problematic test file and unused var in AgentClient
chore: remove unused import and import directly for JSDoc
* feat: add api package build stage in Dockerfile for improved modularity
* docs: reorder build steps in contributing guide for clarity
328 lines
10 KiB
JavaScript
328 lines
10 KiB
JavaScript
const axios = require('axios');
|
|
const fs = require('fs').promises;
|
|
const FormData = require('form-data');
|
|
const { Readable } = require('stream');
|
|
const { genAzureEndpoint } = require('@librechat/api');
|
|
const { extractEnvVariable, STTProviders } = require('librechat-data-provider');
|
|
const { getCustomConfig } = require('~/server/services/Config');
|
|
const { logger } = require('~/config');
|
|
|
|
/**
|
|
* Maps MIME types to their corresponding file extensions for audio files.
|
|
* @type {Object}
|
|
*/
|
|
const MIME_TO_EXTENSION_MAP = {
|
|
// MP4 container formats
|
|
'audio/mp4': 'm4a',
|
|
'audio/x-m4a': 'm4a',
|
|
// Ogg formats
|
|
'audio/ogg': 'ogg',
|
|
'audio/vorbis': 'ogg',
|
|
'application/ogg': 'ogg',
|
|
// Wave formats
|
|
'audio/wav': 'wav',
|
|
'audio/x-wav': 'wav',
|
|
'audio/wave': 'wav',
|
|
// MP3 formats
|
|
'audio/mp3': 'mp3',
|
|
'audio/mpeg': 'mp3',
|
|
'audio/mpeg3': 'mp3',
|
|
// WebM formats
|
|
'audio/webm': 'webm',
|
|
// Additional formats
|
|
'audio/flac': 'flac',
|
|
'audio/x-flac': 'flac',
|
|
};
|
|
|
|
/**
|
|
* Gets the file extension from the MIME type.
|
|
* @param {string} mimeType - The MIME type.
|
|
* @returns {string} The file extension.
|
|
*/
|
|
function getFileExtensionFromMime(mimeType) {
|
|
// Default fallback
|
|
if (!mimeType) {
|
|
return 'webm';
|
|
}
|
|
|
|
// Direct lookup (fastest)
|
|
const extension = MIME_TO_EXTENSION_MAP[mimeType];
|
|
if (extension) {
|
|
return extension;
|
|
}
|
|
|
|
// Try to extract subtype as fallback
|
|
const subtype = mimeType.split('/')[1]?.toLowerCase();
|
|
|
|
// If subtype matches a known extension
|
|
if (['mp3', 'mp4', 'ogg', 'wav', 'webm', 'm4a', 'flac'].includes(subtype)) {
|
|
return subtype === 'mp4' ? 'm4a' : subtype;
|
|
}
|
|
|
|
// Generic checks for partial matches
|
|
if (subtype?.includes('mp4') || subtype?.includes('m4a')) {
|
|
return 'm4a';
|
|
}
|
|
if (subtype?.includes('ogg')) {
|
|
return 'ogg';
|
|
}
|
|
if (subtype?.includes('wav')) {
|
|
return 'wav';
|
|
}
|
|
if (subtype?.includes('mp3') || subtype?.includes('mpeg')) {
|
|
return 'mp3';
|
|
}
|
|
if (subtype?.includes('webm')) {
|
|
return 'webm';
|
|
}
|
|
|
|
return 'webm'; // Default fallback
|
|
}
|
|
|
|
/**
|
|
* Service class for handling Speech-to-Text (STT) operations.
|
|
* @class
|
|
*/
|
|
class STTService {
|
|
/**
|
|
* Creates an instance of STTService.
|
|
* @param {Object} customConfig - The custom configuration object.
|
|
*/
|
|
constructor(customConfig) {
|
|
this.customConfig = customConfig;
|
|
this.providerStrategies = {
|
|
[STTProviders.OPENAI]: this.openAIProvider,
|
|
[STTProviders.AZURE_OPENAI]: this.azureOpenAIProvider,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Creates a singleton instance of STTService.
|
|
* @static
|
|
* @async
|
|
* @returns {Promise<STTService>} The STTService instance.
|
|
* @throws {Error} If the custom config is not found.
|
|
*/
|
|
static async getInstance() {
|
|
const customConfig = await getCustomConfig();
|
|
if (!customConfig) {
|
|
throw new Error('Custom config not found');
|
|
}
|
|
return new STTService(customConfig);
|
|
}
|
|
|
|
/**
|
|
* Retrieves the configured STT provider and its schema.
|
|
* @returns {Promise<[string, Object]>} A promise that resolves to an array containing the provider name and its schema.
|
|
* @throws {Error} If no STT schema is set, multiple providers are set, or no provider is set.
|
|
*/
|
|
async getProviderSchema() {
|
|
const sttSchema = this.customConfig.speech.stt;
|
|
|
|
if (!sttSchema) {
|
|
throw new Error(
|
|
'No STT schema is set. Did you configure STT in the custom config (librechat.yaml)?',
|
|
);
|
|
}
|
|
|
|
const providers = Object.entries(sttSchema).filter(
|
|
([, value]) => Object.keys(value).length > 0,
|
|
);
|
|
|
|
if (providers.length !== 1) {
|
|
throw new Error(
|
|
providers.length > 1
|
|
? 'Multiple providers are set. Please set only one provider.'
|
|
: 'No provider is set. Please set a provider.',
|
|
);
|
|
}
|
|
|
|
const [provider, schema] = providers[0];
|
|
return [provider, schema];
|
|
}
|
|
|
|
/**
|
|
* Recursively removes undefined properties from an object.
|
|
* @param {Object} obj - The object to clean.
|
|
* @returns {void}
|
|
*/
|
|
removeUndefined(obj) {
|
|
Object.keys(obj).forEach((key) => {
|
|
if (obj[key] && typeof obj[key] === 'object') {
|
|
this.removeUndefined(obj[key]);
|
|
if (Object.keys(obj[key]).length === 0) {
|
|
delete obj[key];
|
|
}
|
|
} else if (obj[key] === undefined) {
|
|
delete obj[key];
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Prepares the request for the OpenAI STT provider.
|
|
* @param {Object} sttSchema - The STT schema for OpenAI.
|
|
* @param {Stream} audioReadStream - The audio data to be transcribed.
|
|
* @returns {Array} An array containing the URL, data, and headers for the request.
|
|
*/
|
|
openAIProvider(sttSchema, audioReadStream) {
|
|
const url = sttSchema?.url || 'https://api.openai.com/v1/audio/transcriptions';
|
|
const apiKey = extractEnvVariable(sttSchema.apiKey) || '';
|
|
|
|
const data = {
|
|
file: audioReadStream,
|
|
model: sttSchema.model,
|
|
};
|
|
|
|
const headers = {
|
|
'Content-Type': 'multipart/form-data',
|
|
...(apiKey && { Authorization: `Bearer ${apiKey}` }),
|
|
};
|
|
[headers].forEach(this.removeUndefined);
|
|
|
|
return [url, data, headers];
|
|
}
|
|
|
|
/**
|
|
* Prepares the request for the Azure OpenAI STT provider.
|
|
* @param {Object} sttSchema - The STT schema for Azure OpenAI.
|
|
* @param {Buffer} audioBuffer - The audio data to be transcribed.
|
|
* @param {Object} audioFile - The audio file object containing originalname, mimetype, and size.
|
|
* @returns {Array} An array containing the URL, data, and headers for the request.
|
|
* @throws {Error} If the audio file size exceeds 25MB or the audio file format is not accepted.
|
|
*/
|
|
azureOpenAIProvider(sttSchema, audioBuffer, audioFile) {
|
|
const url = `${genAzureEndpoint({
|
|
azureOpenAIApiInstanceName: extractEnvVariable(sttSchema?.instanceName),
|
|
azureOpenAIApiDeploymentName: extractEnvVariable(sttSchema?.deploymentName),
|
|
})}/audio/transcriptions?api-version=${extractEnvVariable(sttSchema?.apiVersion)}`;
|
|
|
|
const apiKey = sttSchema.apiKey ? extractEnvVariable(sttSchema.apiKey) : '';
|
|
|
|
if (audioBuffer.byteLength > 25 * 1024 * 1024) {
|
|
throw new Error('The audio file size exceeds the limit of 25MB');
|
|
}
|
|
|
|
const acceptedFormats = ['flac', 'mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'ogg', 'wav', 'webm'];
|
|
const fileFormat = audioFile.mimetype.split('/')[1];
|
|
if (!acceptedFormats.includes(fileFormat)) {
|
|
throw new Error(`The audio file format ${fileFormat} is not accepted`);
|
|
}
|
|
|
|
const formData = new FormData();
|
|
formData.append('file', audioBuffer, {
|
|
filename: audioFile.originalname,
|
|
contentType: audioFile.mimetype,
|
|
});
|
|
|
|
const headers = {
|
|
'Content-Type': 'multipart/form-data',
|
|
...(apiKey && { 'api-key': apiKey }),
|
|
};
|
|
|
|
[headers].forEach(this.removeUndefined);
|
|
|
|
return [url, formData, { ...headers, ...formData.getHeaders() }];
|
|
}
|
|
|
|
/**
|
|
* Sends an STT request to the specified provider.
|
|
* @async
|
|
* @param {string} provider - The STT provider to use.
|
|
* @param {Object} sttSchema - The STT schema for the provider.
|
|
* @param {Object} requestData - The data required for the STT request.
|
|
* @param {Buffer} requestData.audioBuffer - The audio data to be transcribed.
|
|
* @param {Object} requestData.audioFile - The audio file object containing originalname, mimetype, and size.
|
|
* @returns {Promise<string>} A promise that resolves to the transcribed text.
|
|
* @throws {Error} If the provider is invalid, the response status is not 200, or the response data is missing.
|
|
*/
|
|
async sttRequest(provider, sttSchema, { audioBuffer, audioFile }) {
|
|
const strategy = this.providerStrategies[provider];
|
|
if (!strategy) {
|
|
throw new Error('Invalid provider');
|
|
}
|
|
|
|
const fileExtension = getFileExtensionFromMime(audioFile.mimetype);
|
|
|
|
const audioReadStream = Readable.from(audioBuffer);
|
|
audioReadStream.path = `audio.${fileExtension}`;
|
|
|
|
const [url, data, headers] = strategy.call(this, sttSchema, audioReadStream, audioFile);
|
|
|
|
try {
|
|
const response = await axios.post(url, data, { headers });
|
|
|
|
if (response.status !== 200) {
|
|
throw new Error('Invalid response from the STT API');
|
|
}
|
|
|
|
if (!response.data || !response.data.text) {
|
|
throw new Error('Missing data in response from the STT API');
|
|
}
|
|
|
|
return response.data.text.trim();
|
|
} catch (error) {
|
|
logger.error(`STT request failed for provider ${provider}:`, error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Processes a speech-to-text request.
|
|
* @async
|
|
* @param {Object} req - The request object.
|
|
* @param {Object} res - The response object.
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async processTextToSpeech(req, res) {
|
|
if (!req.file) {
|
|
return res.status(400).json({ message: 'No audio file provided in the FormData' });
|
|
}
|
|
|
|
const audioBuffer = await fs.readFile(req.file.path);
|
|
const audioFile = {
|
|
originalname: req.file.originalname,
|
|
mimetype: req.file.mimetype,
|
|
size: req.file.size,
|
|
};
|
|
|
|
try {
|
|
const [provider, sttSchema] = await this.getProviderSchema();
|
|
const text = await this.sttRequest(provider, sttSchema, { audioBuffer, audioFile });
|
|
res.json({ text });
|
|
} catch (error) {
|
|
logger.error('An error occurred while processing the audio:', error);
|
|
res.sendStatus(500);
|
|
} finally {
|
|
try {
|
|
await fs.unlink(req.file.path);
|
|
logger.debug('[/speech/stt] Temp. audio upload file deleted');
|
|
} catch (error) {
|
|
logger.debug('[/speech/stt] Temp. audio upload file already deleted');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Factory function to create an STTService instance.
|
|
* @async
|
|
* @returns {Promise<STTService>} A promise that resolves to an STTService instance.
|
|
*/
|
|
async function createSTTService() {
|
|
return STTService.getInstance();
|
|
}
|
|
|
|
/**
|
|
* Wrapper function for speech-to-text processing.
|
|
* @async
|
|
* @param {Object} req - The request object.
|
|
* @param {Object} res - The response object.
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async function speechToText(req, res) {
|
|
const sttService = await createSTTService();
|
|
await sttService.processTextToSpeech(req, res);
|
|
}
|
|
|
|
module.exports = { speechToText };
|