2023-12-15 02:18:07 -05:00
|
|
|
const { EModelEndpoint, AuthKeys } = require('librechat-data-provider');
|
2023-12-10 14:54:13 -05:00
|
|
|
const { getUserKey, checkUserKeyExpiry } = require('~/server/services/UserService');
|
2024-04-21 08:31:54 -04:00
|
|
|
const { GoogleClient } = require('~/app');
|
2024-12-18 12:13:16 -05:00
|
|
|
const { isEnabled } = require('~/server/utils');
|
2023-12-10 14:54:13 -05:00
|
|
|
|
|
|
|
|
const initializeClient = async ({ req, res, endpointOption }) => {
|
2024-12-18 12:13:16 -05:00
|
|
|
const {
|
|
|
|
|
GOOGLE_KEY,
|
|
|
|
|
GOOGLE_REVERSE_PROXY,
|
|
|
|
|
GOOGLE_AUTH_HEADER,
|
|
|
|
|
PROXY,
|
|
|
|
|
} = process.env;
|
2023-12-10 14:54:13 -05:00
|
|
|
const isUserProvided = GOOGLE_KEY === 'user_provided';
|
|
|
|
|
const { key: expiresAt } = req.body;
|
|
|
|
|
|
|
|
|
|
let userKey = null;
|
|
|
|
|
if (expiresAt && isUserProvided) {
|
2024-04-21 08:31:54 -04:00
|
|
|
checkUserKeyExpiry(expiresAt, EModelEndpoint.google);
|
2023-12-10 14:54:13 -05:00
|
|
|
userKey = await getUserKey({ userId: req.user.id, name: EModelEndpoint.google });
|
|
|
|
|
}
|
|
|
|
|
|
2023-12-15 02:18:07 -05:00
|
|
|
let serviceKey = {};
|
|
|
|
|
try {
|
|
|
|
|
serviceKey = require('~/data/auth.json');
|
|
|
|
|
} catch (e) {
|
|
|
|
|
// Do nothing
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const credentials = isUserProvided
|
|
|
|
|
? userKey
|
|
|
|
|
: {
|
|
|
|
|
[AuthKeys.GOOGLE_SERVICE_KEY]: serviceKey,
|
|
|
|
|
[AuthKeys.GOOGLE_API_KEY]: GOOGLE_KEY,
|
|
|
|
|
};
|
2023-12-10 14:54:13 -05:00
|
|
|
|
2024-07-17 10:47:17 -04:00
|
|
|
const clientOptions = {};
|
|
|
|
|
|
|
|
|
|
/** @type {undefined | TBaseEndpoint} */
|
|
|
|
|
const allConfig = req.app.locals.all;
|
|
|
|
|
/** @type {undefined | TBaseEndpoint} */
|
|
|
|
|
const googleConfig = req.app.locals[EModelEndpoint.google];
|
|
|
|
|
|
|
|
|
|
if (googleConfig) {
|
|
|
|
|
clientOptions.streamRate = googleConfig.streamRate;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (allConfig) {
|
|
|
|
|
clientOptions.streamRate = allConfig.streamRate;
|
|
|
|
|
}
|
|
|
|
|
|
2023-12-15 02:18:07 -05:00
|
|
|
const client = new GoogleClient(credentials, {
|
2023-12-10 14:54:13 -05:00
|
|
|
req,
|
|
|
|
|
res,
|
|
|
|
|
reverseProxyUrl: GOOGLE_REVERSE_PROXY ?? null,
|
2024-12-18 12:13:16 -05:00
|
|
|
authHeader: isEnabled(GOOGLE_AUTH_HEADER) ?? null,
|
2023-12-10 14:54:13 -05:00
|
|
|
proxy: PROXY ?? null,
|
2024-07-17 10:47:17 -04:00
|
|
|
...clientOptions,
|
2023-12-10 14:54:13 -05:00
|
|
|
...endpointOption,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
client,
|
2023-12-15 02:18:07 -05:00
|
|
|
credentials,
|
2023-12-10 14:54:13 -05:00
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
module.exports = initializeClient;
|