SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
import { Request } from 'express';
import Joi from 'joi';
import { USER_CUSTOM_LLM_SETTINGS_KEY } from '../../constants';
import { LLMService } from '../../services/LLMHelper/LLMService.class';
import { vault } from '../../services/SmythVault.class';
import * as teamData from '../../services/team-data.service';
import { uid } from '../../services/utils.service';
import { setVaultKeys } from './vault.helper';
/**
* User Custom LLM Helper
*
* Manages user custom LLM configurations with the following data structure:
* {
* id: {
* name: <the friendly name>,
* id: <id of the entry>,
* modelId: <the model id entered by the user>,
* baseURL: <base url>,
* fallbackLLM: <llm ID from builtin LLMs>
* }
* }
*
* The 'id' is generated using uid() like custom-llm, not normalized from name.
* This provides the same ID generation pattern as custom-llm but without ACL restrictions.
*/
//#region - Type Definitions
export interface UserCustomLLMInputParams {
id?: string;
name: string;
modelId: string;
baseURL: string;
provider: string;
contextWindow?: number;
maxOutputTokens?: number;
fallbackLLM?: string;
features?: string[];
teamId?: string;
userEmail?: string;
credentials?: {
apiKey?: string;
isUserKey?: boolean;
};
}
export interface UserCustomLLMInfo extends Omit<UserCustomLLMInputParams, 'teamId' | 'userEmail'> {
id: string; // Always present in stored data
credentials?: {
apiKey?: string;
isUserKey?: boolean;
};
}
interface UserCustomLLMModel {
isUserCustomLLM: boolean;
[key: string]: any;
}
//#endregion - Type Definitions
//#region - Validation Schema
const userCustomLLMValidationSchema = Joi.object({
id: Joi.string()
.optional()
.pattern(/^[a-zA-Z0-9-_]+$/)
.max(80),
name: Joi.string().trim().required().min(1).max(80),
modelId: Joi.string().trim().required().min(1).max(200),
baseURL: Joi.string()
.trim()
.required()
.uri({ scheme: ['http', 'https'] })
.max(500),
provider: Joi.string().trim().required().valid('OpenAI', 'Ollama'),
contextWindow: Joi.number().integer().min(2048).max(2000000).optional(),
maxOutputTokens: Joi.number().integer().min(256).max(200000).optional(),
fallbackLLM: Joi.string().trim().optional().allow('').max(100),
features: Joi.array().items(Joi.string()).optional(),
teamId: Joi.string().optional(),
userEmail: Joi.string().optional(),
credentials: Joi.object({
apiKey: Joi.string().max(10000).optional().allow(''),
isUserKey: Joi.boolean().optional(),
})
.optional()
.allow(null), // Allow null or empty object {} to signal explicit removal of credentials
});
//#endregion - Validation Schema
//#region - Core Functions
/**
* Saves a user custom LLM configuration
* @param req - Express request object
* @param params - User Custom LLM parameters
* @returns Promise with the saved data
*/
async function saveUserCustomLLM(req: Request, params: UserCustomLLMInputParams) {
try {
// Trim all string parameters
const trimmedParams = {
...params,
name: params.name?.trim(),
modelId: params.modelId?.trim(),
baseURL: params.baseURL?.trim(),
provider: params.provider?.trim(),
fallbackLLM: params.fallbackLLM?.trim(),
features: params.features || ['text'],
credentials: params.credentials,
};
const teamId = params.teamId || req?._team?.id;
// userEmail is required for vault key management when storing API keys.
// The vault service uses it to track ownership, maintain audit trails,
// and manage access control for sensitive credentials.
const userEmail = params.userEmail || req?._user?.email;
if (!teamId || !userEmail) {
throw new Error('Team ID and user email are required');
}
// Validate input parameters
const { error } = userCustomLLMValidationSchema.validate(trimmedParams);
if (error) {
throw new Error(`Invalid request. ${error.message}`);
}
// Generate or use provided ID - using uid() like custom-llm
const entryId = trimmedParams.id || uid().toLowerCase();
const isUpdate = !!trimmedParams.id; // Check if this is an update operation
// If updating, get existing model to preserve credentials if needed
let existingModel: UserCustomLLMInfo | null = null;
if (isUpdate) {
existingModel = await getUserCustomLLMByEntryId(req, entryId);
// Check if user is explicitly removing the API key (credentials set to empty object means remove)
const isRemovingCredentials =
trimmedParams.credentials &&
typeof trimmedParams.credentials === 'object' &&
Object.keys(trimmedParams.credentials).length === 0;
if (
existingModel?.credentials?.isUserKey &&
existingModel.credentials?.apiKey &&
isRemovingCredentials
) {
// Extract the key name from the template variable and delete from vault
const apiKeyTemplateVariable = existingModel.credentials.apiKey;
const match = apiKeyTemplateVariable.match(/\{\{KEY\((.+?)\)\}\}/);
if (match && match[1]) {
const apiKeyName = match[1];
try {
await vault.delete(apiKeyName, teamId, req);
console.log(`Deleted vault key: ${apiKeyName}`);
} catch (vaultError) {
console.warn('Error deleting vault key during update:', vaultError?.message);
}
}
}
}
// Create the user custom LLM data object
const userCustomLLMData: UserCustomLLMInfo = {
id: entryId,
name: trimmedParams.name,
modelId: trimmedParams.modelId,
baseURL: trimmedParams.baseURL,
provider: trimmedParams.provider,
contextWindow: trimmedParams.contextWindow,
maxOutputTokens: trimmedParams.maxOutputTokens,
fallbackLLM: trimmedParams.fallbackLLM,
features: trimmedParams.features,
};
// Handle API key storage if provided
// Check if the provided apiKey is an actual key (not a template variable)
const hasActualApiKey =
trimmedParams.credentials?.apiKey &&
trimmedParams.credentials?.isUserKey &&
!trimmedParams.credentials.apiKey.startsWith('{{KEY(');
// Check if user explicitly wants to remove credentials (empty object)
const shouldRemoveCredentials =
trimmedParams.credentials &&
typeof trimmedParams.credentials === 'object' &&
Object.keys(trimmedParams.credentials).length === 0;
if (shouldRemoveCredentials) {
// User explicitly removed the API key - set credentials to empty object
// The key has already been deleted from vault in the earlier check
userCustomLLMData.credentials = {} as UserCustomLLMInfo['credentials'];
} else if (hasActualApiKey) {
// User is providing a new API key (creating new model or updating existing key)
const apiKey = trimmedParams.credentials.apiKey.trim();
// Generate a unique name for the API key in vault
const apiKeyName = `User Custom Model API Key (${entryId})`;
// Save the API key to vault with _hidden scope
const keyEntries = [
{
id: apiKeyName,
scope: ['_hidden'],
name: apiKeyName,
key: apiKey,
metadata: {
field: 'apiKey',
userCustomLLMEntryId: entryId,
userCustomLLMEntryName: trimmedParams.name,
},
},
];
await setVaultKeys({
req,
teamId,
userEmail,
keyEntries,
});
// Store the vault key reference as a template variable in the model data
userCustomLLMData.credentials = {
apiKey: `{{KEY(${apiKeyName})}}`,
isUserKey: true,
};
} else if (
trimmedParams.credentials?.apiKey &&
trimmedParams.credentials.apiKey.startsWith('{{KEY(')
) {
// Frontend sent the template variable back - preserve it as is
// This happens when user updates other fields without modifying the API key
userCustomLLMData.credentials = {
apiKey: trimmedParams.credentials.apiKey,
isUserKey: true,
};
} else if (isUpdate && existingModel?.credentials) {
// Updating model, no credentials provided in params, but model has existing credentials
// Preserve the existing credentials
userCustomLLMData.credentials = existingModel.credentials;
}
// If none of the above, credentials will be undefined (no API key)
// Save to team settings
const result = await teamData.saveTeamSettingsObj({
req,
settingKey: USER_CUSTOM_LLM_SETTINGS_KEY,
entryId,
data: userCustomLLMData,
});
if (!result.success) {
throw new Error(result.error || 'Failed to save user custom LLM configuration');
}
return { data: { id: entryId, name: trimmedParams.name } };
} catch (error) {
console.error('Error saving user custom LLM model:', error?.message);
throw error;
}
}
/**
* Gets a user custom LLM configuration by name
* @param req - Express request object
* @param modelName - The name of the model to retrieve
* @returns Promise with the model info or empty object
*/
async function getUserCustomLLMByName(
req: Request,
modelName: string,
): Promise<UserCustomLLMInfo | {}> {
try {
const allUserCustomModels = await teamData.getTeamSettingsObj(
req,
USER_CUSTOM_LLM_SETTINGS_KEY,
);
let modelInfo = {};
if (allUserCustomModels && typeof allUserCustomModels === 'object') {
for (const [key, model] of Object.entries(allUserCustomModels)) {
if (model && typeof model === 'object' && model.name === modelName) {
// Ensure id is present, using object key as fallback for legacy entries
modelInfo = { ...model, id: model.id || key };
break;
}
}
}
return modelInfo;
} catch (error) {
console.error('Error getting user custom LLM by name:', error?.message);
return {};
}
}
/**
* Gets a user custom LLM configuration by entry ID
* @param req - Express request object
* @param entryId - The ID of the entry to retrieve
* @returns Promise with the model info
*/
async function getUserCustomLLMByEntryId(
req: Request,
entryId: string,
): Promise<UserCustomLLMInfo | null> {
try {
const allUserCustomModels = await teamData.getTeamSettingsObj(
req,
USER_CUSTOM_LLM_SETTINGS_KEY,
);
if (!allUserCustomModels || typeof allUserCustomModels !== 'object') {
return null;
}
const model = allUserCustomModels[entryId];
if (!model || typeof model !== 'object') {
return null;
}
// Ensure id is present
return { ...model, id: model.id || entryId };
} catch (error) {
console.error('Error getting user custom LLM by entry ID:', error?.message);
throw error;
}
}
/**
* Retrieves all user custom LLM models for a team.
* Filters models to only return those marked as user custom LLMs.
* Returns an empty object if no models are found or if an error occurs.
*
* @param req - Express request object containing team information
* @returns Promise resolving to a record of UserCustomLLMModel objects keyed by model ID, or empty object on error
*/
async function getAllUserCustomLLMs(req: Request): Promise<Record<string, UserCustomLLMModel>> {
try {
const llmProvider = new LLMService();
const allCustomModels = await llmProvider.getCustomModels(req);
if (!allCustomModels || typeof allCustomModels !== 'object') {
return {};
}
// Filter models to only include those marked as user custom LLMs
const userCustomModels: Record<string, UserCustomLLMModel> = {};
for (const [modelId, model] of Object.entries(allCustomModels)) {
if (
model &&
typeof model === 'object' &&
'isUserCustomLLM' in model &&
(model as UserCustomLLMModel).isUserCustomLLM === true
) {
userCustomModels[modelId] = model as UserCustomLLMModel;
}
}
return userCustomModels;
} catch {
return {};
}
}
/**
* Deletes a user custom LLM configuration
* @param req - Express request object
* @param entryId - The ID of the entry to delete
* @returns Promise with the result
*/
async function deleteUserCustomLLM(req: Request, entryId: string) {
try {
const teamId = req?._team?.id;
// Get the model info to check if it has an API key stored in vault
const modelInfo = await getUserCustomLLMByEntryId(req, entryId);
if (modelInfo?.credentials?.isUserKey && modelInfo.credentials?.apiKey) {
const apiKeyTemplateVariable = modelInfo.credentials.apiKey;
const match = apiKeyTemplateVariable.match(/\{\{KEY\((.+?)\)\}\}/);
if (match && match[1]) {
const apiKeyName = match[1];
// Try to delete the vault key, but don't fail if it doesn't exist
try {
await vault.delete(apiKeyName, teamId, req);
} catch (vaultError) {
console.warn('Error deleting vault key:', vaultError?.message);
}
}
}
const result = await teamData.deleteTeamSettingsObj(req, USER_CUSTOM_LLM_SETTINGS_KEY, entryId);
if (!result.success) {
throw new Error(result.error || 'Failed to delete user custom LLM configuration');
}
return result;
} catch (error) {
console.error('Error deleting user custom LLM model:', error?.message);
throw error;
}
}
//#endregion - Core Functions
//#region - Export Helper Object
export const userCustomLLMHelper = {
saveUserCustomLLM,
getUserCustomLLMByName,
getUserCustomLLMByEntryId,
getAllUserCustomLLMs,
deleteUserCustomLLM,
};
//#endregion - Export Helper Object