mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-16 16:30:15 +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
322 lines
9.8 KiB
JavaScript
322 lines
9.8 KiB
JavaScript
const axios = require('axios');
|
|
const fs = require('fs').promises;
|
|
const FormData = require('form-data');
|
|
const { Readable } = require('stream');
|
|
const { logger } = require('@librechat/data-schemas');
|
|
const { genAzureEndpoint } = require('@librechat/api');
|
|
const { extractEnvVariable, STTProviders } = require('librechat-data-provider');
|
|
const { getAppConfig } = require('~/server/services/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 {
|
|
constructor() {
|
|
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() {
|
|
return new STTService();
|
|
}
|
|
|
|
/**
|
|
* Retrieves the configured STT provider and its schema.
|
|
* @param {ServerRequest} req - The request object.
|
|
* @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(req) {
|
|
const appConfig = await getAppConfig({
|
|
role: req?.user?.role,
|
|
});
|
|
const sttSchema = appConfig?.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 processSpeechToText(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(req);
|
|
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 {
|
|
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.processSpeechToText(req, res);
|
|
}
|
|
|
|
module.exports = { speechToText };
|