Skip to content

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.

rename local models to user custom models

Forhad Hosainc7eaedda4ca4
diff --git a/packages/app/src/backend/constants.ts b/packages/app/src/backend/constants.ts
index 7d020f8f..f8440cab 100644
--- a/packages/app/src/backend/constants.ts
+++ b/packages/app/src/backend/constants.ts
@@ -5,7 +5,7 @@ export const S3_MONTHLY_PURGE_LIFECYCLE_TAG = 'ExpirationPolicy=DeleteMonthly';
export const HUBSPOT_PORTAL_ID = '20645624';
export const CUSTOM_LLM_SETTINGS_KEY = 'custom-llm';
-export const LOCAL_LLM_SETTINGS_KEY = 'local-llm';
+export const USER_CUSTOM_LLM_SETTINGS_KEY = 'user-custom-llm';
export const SMYTH_LLM_PROVIDERS_SETTINGS_KEY = 'smyth-llm-providers';
export const DEFAULT_SMYTH_LLM_PROVIDERS_SETTINGS = {
diff --git a/packages/app/src/backend/routes/api/page/vault.ts b/packages/app/src/backend/routes/api/page/vault.ts
index 558cef0b..db186af6 100644
--- a/packages/app/src/backend/routes/api/page/vault.ts
+++ b/packages/app/src/backend/routes/api/page/vault.ts
@@ -7,7 +7,6 @@ import {
} from '../../../constants';
import { includeTeamDetails } from '../../../middlewares/auth.mw';
import { cacheClient } from '../../../services/cache.service';
-import { LLMService } from '../../../services/LLMHelper/LLMService.class';
import Vault from '../../../services/SmythVault.class';
import {
deleteTeamSettingsObj,
@@ -18,7 +17,7 @@ import { Team } from '../../../types';
import { isSmythStaff } from '../../../utils';
import { isCustomLLMAllowed } from '../../../utils/customLLM';
import { customLLMHelper } from '../../router.helpers/customLLM.helper';
-import { localLLMHelper } from '../../router.helpers/localLLM.helper';
+import { userCustomLLMHelper } from '../../router.helpers/userCustomLLM.helper';
import { getVaultKeys, setVaultKey } from '../../router.utils';
const router = express.Router();
@@ -598,7 +597,7 @@ router.put('/recommended-models/:providerId', includeTeamDetails, async (req, re
// Suggested structure:
// - vault/index.ts
// - vault/custom-llm.ts
-// - vault/local-llm.ts
+// - vault/user-custom-llm.ts
// #region Custom LLM Routes
/**
@@ -669,9 +668,8 @@ router.put('/custom-llm/:id', customLLMRouteMiddlewares, handleCustomLLMSave);
router.get('/custom-llm', includeTeamDetails, async (req, res) => {
try {
- const llmProvider = new LLMService();
- const allCustomModels = await llmProvider.getCustomModels(req);
- res.status(200).json({ success: true, data: allCustomModels });
+ const enterpriseModels = await customLLMHelper.getAllEnterpriseModels(req);
+ res.status(200).json({ success: true, data: enterpriseModels });
} catch (error) {
res.status(500).json({ success: false, error: 'Error getting custom LLM models.' });
}
@@ -742,14 +740,14 @@ router.delete('/custom-llm/:provider/:id', customLLMRouteMiddlewares, async (req
});
// #endregion
-// #region Local LLM Routes
+// #region User Custom LLM Routes
/**
- * Local LLM Routes
+ * User Custom LLM Routes
*
- * Provides endpoints for managing team-specific local LLM models:
- * - CRUD operations for local LLM configurations
- * - No access control checks (ACL) required
- * - Cache management for local model data
+ * Provides endpoints for managing team-specific user custom LLM models:
+ * - CRUD operations for user custom LLM configurations
+ * - No access control checks (ACL) required - available for all users
+ * - Cache management for user custom model data
* - Secure credential access via with-credentials endpoint
*
* Data structure:
@@ -765,119 +763,119 @@ router.delete('/custom-llm/:provider/:id', customLLMRouteMiddlewares, async (req
*/
/**
- * Create or update a local LLM model
+ * Create or update a user custom LLM model
*/
-const handleLocalLLMSave = async (req, res) => {
+const handleUserCustomLLMSave = async (req, res) => {
const teamId = req?._team?.id;
const id = req.params?.id; // This will be undefined for POST requests
try {
- const saveLocalLLM = await localLLMHelper.saveLocalLLM(req, {
+ const saveUserCustomLLM = await userCustomLLMHelper.saveUserCustomLLM(req, {
id,
...req.body,
});
- // Delete the local LLM model cache
+ // Delete the user custom LLM model cache
await cacheClient.del(config.cache.getCustomModelsCacheKey(teamId)).catch((error) => {
- console.warn('Error deleting local LLM model cache:', error?.message);
+ console.warn('Error deleting user custom LLM model cache:', error?.message);
});
- res.status(200).json({ success: true, data: saveLocalLLM.data });
+ res.status(200).json({ success: true, data: saveUserCustomLLM.data });
} catch (error) {
- console.error('Error saving local LLM model:', error?.message);
- res.status(500).json({ success: false, error: 'Error saving local LLM model.' });
+ console.error('Error saving user custom LLM model:', error?.message);
+ res.status(500).json({ success: false, error: 'Error saving user custom LLM model.' });
}
};
/**
- * Create a new local LLM model
- * POST /local-llm/
+ * Create a new user custom LLM model
+ * POST /user-custom-llm/
*/
-router.post('/local-llm/', includeTeamDetails, handleLocalLLMSave);
+router.post('/user-custom-llm/', includeTeamDetails, handleUserCustomLLMSave);
/**
- * Update an existing local LLM model
- * PUT /local-llm/:id
+ * Update an existing user custom LLM model
+ * PUT /user-custom-llm/:id
*/
-router.put('/local-llm/:id', includeTeamDetails, handleLocalLLMSave);
+router.put('/user-custom-llm/:id', includeTeamDetails, handleUserCustomLLMSave);
/**
- * Get all local LLM models
- * GET /local-llm
+ * Get all user custom LLM models
+ * GET /user-custom-llm
*/
-router.get('/local-llm', includeTeamDetails, async (req, res) => {
+router.get('/user-custom-llm', includeTeamDetails, async (req, res) => {
try {
- const allLocalModels = await localLLMHelper.getAllLocalLLMs(req);
- res.status(200).json({ success: true, data: allLocalModels });
+ const allUserCustomModels = await userCustomLLMHelper.getAllUserCustomLLMs(req);
+ res.status(200).json({ success: true, data: allUserCustomModels });
} catch (error) {
- console.error('Error getting local LLM models:', error?.message);
- res.status(500).json({ success: false, error: 'Error getting local LLM models.' });
+ console.error('Error getting user custom LLM models:', error?.message);
+ res.status(500).json({ success: false, error: 'Error getting user custom LLM models.' });
}
});
/**
- * Get a specific local LLM model by ID
- * GET /local-llm/:id
+ * Get a specific user custom LLM model by ID
+ * GET /user-custom-llm/:id
*/
-router.get('/local-llm/:id', includeTeamDetails, async (req, res) => {
+router.get('/user-custom-llm/:id', includeTeamDetails, async (req, res) => {
try {
const entryId = req.params.id;
- const modelInfo = await localLLMHelper.getLocalLLMByEntryId(req, entryId);
+ const modelInfo = await userCustomLLMHelper.getUserCustomLLMByEntryId(req, entryId);
if (!modelInfo) {
- return res.status(404).json({ success: false, error: 'Local LLM model not found.' });
+ return res.status(404).json({ success: false, error: 'User custom LLM model not found.' });
}
res.status(200).json({ success: true, data: modelInfo });
} catch (error) {
- console.error('Error getting local LLM model:', error?.message);
- res.status(500).json({ success: false, error: 'Error getting local LLM model.' });
+ console.error('Error getting user custom LLM model:', error?.message);
+ res.status(500).json({ success: false, error: 'Error getting user custom LLM model.' });
}
});
/**
- * Get a local LLM model with credentials by name
- * GET /local-llm/with-credentials/:name
+ * Get a user custom LLM model with credentials by name
+ * GET /user-custom-llm/with-credentials/:name
*/
-router.get('/local-llm/with-credentials/:name', includeTeamDetails, async (req, res) => {
+router.get('/user-custom-llm/with-credentials/:name', includeTeamDetails, async (req, res) => {
try {
const modelName = req.params.name;
- const modelInfo = await localLLMHelper.getLocalLLMByName(req, modelName);
+ const modelInfo = await userCustomLLMHelper.getUserCustomLLMByName(req, modelName);
if (!modelInfo || Object.keys(modelInfo).length === 0) {
- return res.status(404).json({ success: false, error: 'Local LLM model not found.' });
+ return res.status(404).json({ success: false, error: 'User custom LLM model not found.' });
}
// Return the full model configuration including credentials (baseUrl, etc.)
res.status(200).json({ success: true, data: modelInfo });
} catch (error) {
- console.error('Error getting local LLM model with credentials:', error?.message);
+ console.error('Error getting user custom LLM model with credentials:', error?.message);
res
.status(500)
- .json({ success: false, error: 'Error getting local LLM model with credentials.' });
+ .json({ success: false, error: 'Error getting user custom LLM model with credentials.' });
}
});
/**
- * Delete a local LLM model
- * DELETE /local-llm/:id
+ * Delete a user custom LLM model
+ * DELETE /user-custom-llm/:id
*/
-router.delete('/local-llm/:id', includeTeamDetails, async (req, res) => {
+router.delete('/user-custom-llm/:id', includeTeamDetails, async (req, res) => {
try {
const teamId = req?._team?.id;
const id = req.params.id;
- const deleteResult = await localLLMHelper.deleteLocalLLM(req, id);
+ const deleteResult = await userCustomLLMHelper.deleteUserCustomLLM(req, id);
- // Delete the local LLM model cache
+ // Delete the user custom LLM model cache
await cacheClient.del(config.cache.getCustomModelsCacheKey(teamId)).catch((error) => {
- console.warn('Error deleting local LLM model cache:', error?.message);
+ console.warn('Error deleting user custom LLM model cache:', error?.message);
});
res.status(200).json({ success: true, data: deleteResult.data });
} catch (error) {
- console.error('Error deleting local LLM model:', error?.message);
- res.status(500).json({ success: false, error: 'Error deleting local LLM model.' });
+ console.error('Error deleting user custom LLM model:', error?.message);
+ res.status(500).json({ success: false, error: 'Error deleting user custom LLM model.' });
}
});
diff --git a/packages/app/src/backend/routes/router.helpers/customLLM.helper.ts b/packages/app/src/backend/routes/router.helpers/customLLM.helper.ts
index 3c333f40..08b9babe 100644
--- a/packages/app/src/backend/routes/router.helpers/customLLM.helper.ts
+++ b/packages/app/src/backend/routes/router.helpers/customLLM.helper.ts
@@ -1,5 +1,6 @@
import Joi from 'joi';
+import { LLMService } from '@src/backend/services/LLMHelper/LLMService.class';
import { Request } from 'express';
import {
BEDROCK_REGIONS,
@@ -35,6 +36,11 @@ interface BaseInputParams extends AuthInfo {
};
}
+interface CustomLLMModel {
+ isCustomLLM: boolean;
+ [key: string]: any;
+}
+
type BedrockModelInputParams = BaseInputParams & {
settings: {
keyId: string;
@@ -64,14 +70,10 @@ export type CustomLLMInfo = CustomLLMInputParams & {
//#region - Functions to export
async function saveCustomLLM(req: Request, params: CustomLLMInputParams) {
- try {
- if (params.provider === 'Bedrock') {
- return await _saveBedrockModel(req, params as BedrockModelInputParams);
- } else if (params.provider === 'VertexAI') {
- return await _saveVertexAIModel(req, params as VertexAIModelInputParams);
- }
- } catch (error) {
- throw error;
+ if (params.provider === 'Bedrock') {
+ return await _saveBedrockModel(req, params as BedrockModelInputParams);
+ } else if (params.provider === 'VertexAI') {
+ return await _saveVertexAIModel(req, params as VertexAIModelInputParams);
}
}
@@ -83,22 +85,18 @@ interface DeleteCustomLLMParams extends AuthInfo {
async function deleteCustomLLM(params: DeleteCustomLLMParams) {
const { req, teamId, id, provider } = params;
- try {
- if (provider === 'Bedrock') {
- return await vault.deleteMultiple({
- req,
- team: teamId,
- entryIds: [`AWS Key ID (${id})`, `AWS Secret Key (${id})`, `AWS Session Key (${id})`],
- });
- } else if (provider === 'VertexAI') {
- return await vault.deleteMultiple({
- req,
- team: teamId,
- entryIds: [`Google JSON Credentials (${id})`],
- });
- }
- } catch (error) {
- throw error;
+ if (provider === 'Bedrock') {
+ return await vault.deleteMultiple({
+ req,
+ team: teamId,
+ entryIds: [`AWS Key ID (${id})`, `AWS Secret Key (${id})`, `AWS Session Key (${id})`],
+ });
+ } else if (provider === 'VertexAI') {
+ return await vault.deleteMultiple({
+ req,
+ team: teamId,
+ entryIds: [`Google JSON Credentials (${id})`],
+ });
}
}
@@ -107,14 +105,10 @@ async function getCustomLLMWithCredentials(
) {
const { provider } = params;
- try {
- if (provider === 'Bedrock') {
- return await _getBedrockModel(params);
- } else if (provider === 'VertexAI') {
- return await _getVertexAIModel(params);
- }
- } catch (error) {
- throw error;
+ if (provider === 'Bedrock') {
+ return await _getBedrockModel(params);
+ } else if (provider === 'VertexAI') {
+ return await _getVertexAIModel(params);
}
}
@@ -138,11 +132,44 @@ async function getCustomLLMByName(req: Request, modelName: string): Promise<Cust
}
async function getCustomLLMByEntryId(req: Request, entryId: string) {
+ const allCustomModels = await teamData.getTeamSettingsObj(req, CUSTOM_LLM_SETTINGS_KEY);
+ return allCustomModels[entryId];
+}
+
+/**
+ * Retrieves all enterprise custom LLM models for a team.
+ * Filters models to only return those marked as 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 CustomLLMModel objects keyed by model ID, or empty object on error
+ */
+async function getAllEnterpriseModels(req: Request): Promise<Record<string, CustomLLMModel>> {
try {
- const allCustomModels = await teamData.getTeamSettingsObj(req, CUSTOM_LLM_SETTINGS_KEY);
- return allCustomModels[entryId];
- } catch (error) {
- throw error;
+ const llmProvider = new LLMService();
+ const allCustomModels = await llmProvider.getCustomModels(req);
+
+ if (!allCustomModels || typeof allCustomModels !== 'object') {
+ return {};
+ }
+
+ // Filter models to only include those marked as custom LLMs
+ const enterpriseModels: Record<string, CustomLLMModel> = {};
+
+ for (const [modelId, model] of Object.entries(allCustomModels)) {
+ if (
+ model &&
+ typeof model === 'object' &&
+ 'isCustomLLM' in model &&
+ (model as CustomLLMModel).isCustomLLM === true
+ ) {
+ enterpriseModels[modelId] = model as CustomLLMModel;
+ }
+ }
+
+ return enterpriseModels;
+ } catch {
+ return {};
}
}
//#endregion - Functions to export
@@ -472,4 +499,5 @@ export const customLLMHelper = {
getCustomLLMWithCredentials,
getCustomLLMByName,
getCustomLLMByEntryId,
+ getAllEnterpriseModels,
};
diff --git a/packages/app/src/backend/routes/router.helpers/localLLM.helper.ts b/packages/app/src/backend/routes/router.helpers/localLLM.helper.ts
deleted file mode 100644
index 5e2ab478..00000000
--- a/packages/app/src/backend/routes/router.helpers/localLLM.helper.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-import { Request } from 'express';
-import Joi from 'joi';
-import { LOCAL_LLM_SETTINGS_KEY } from '../../constants';
-import * as teamData from '../../services/team-data.service';
-import { uid } from '../../services/utils.service';
-
-/**
- * Local LLM Helper
- *
- * Manages local 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 the normalized version of 'name'.
- * Example: "Deepseek r1 001" -> "Deepseek-r1-001"
- */
-
-//#region - Type Definitions
-export interface LocalLLMInputParams {
- id?: string;
- name: string;
- modelId: string;
- baseUrl: string;
- fallbackLLM: string;
-}
-
-export interface LocalLLMInfo extends LocalLLMInputParams {
- id: string; // Always present in stored data
-}
-//#endregion - Type Definitions
-
-//#region - Utility Functions
-/**
- * Normalizes a name to create a valid ID
- * Converts spaces and special characters to hyphens, removes multiple consecutive hyphens
- * @param name - The friendly name to normalize
- * @returns The normalized ID
- * @example normalizeName("Deepseek r1 001") -> "Deepseek-r1-001"
- */
-export function normalizeName(name: string): string {
- if (!name || typeof name !== 'string') {
- return '';
- }
-
- return name
- .trim()
- .replace(/[^a-zA-Z0-9]+/g, '-') // Replace non-alphanumeric characters with hyphens
- .replace(/^-+|-+$/g, '') // Remove leading/trailing hyphens
- .replace(/-+/g, '-'); // Replace multiple consecutive hyphens with single hyphen
-}
-//#endregion - Utility Functions
-
-//#region - Validation Schema
-const localLLMValidationSchema = Joi.object({
- id: Joi.string()
- .optional()
- .pattern(/^[a-zA-Z0-9-_]+$/)
- .max(80),
- name: Joi.string().required().min(1).max(80).trim(),
- modelId: Joi.string().required().min(1).max(200).trim(),
- baseUrl: Joi.string()
- .required()
- .uri({ scheme: ['http', 'https'] })
- .max(500)
- .trim(),
- fallbackLLM: Joi.string().required().min(1).max(100).trim(),
-});
-//#endregion - Validation Schema
-
-//#region - Core Functions
-/**
- * Saves a local LLM configuration
- * @param req - Express request object
- * @param params - Local LLM parameters
- * @returns Promise with the saved data
- */
-async function saveLocalLLM(req: Request, params: LocalLLMInputParams) {
- try {
- // Trim all string parameters
- const trimmedParams = {
- ...params,
- name: params.name?.trim(),
- modelId: params.modelId?.trim(),
- baseUrl: params.baseUrl?.trim(),
- fallbackLLM: params.fallbackLLM?.trim(),
- };
-
- // Validate input parameters
- const { error } = localLLMValidationSchema.validate(trimmedParams);
- if (error) {
- throw new Error(`Invalid request. ${error.message}`);
- }
-
- // Generate or use provided ID
- let entryId = trimmedParams.id;
- if (!entryId) {
- const normalizedName = normalizeName(trimmedParams.name);
- entryId = normalizedName || uid().toLowerCase();
- }
-
- // Create the local LLM data object
- const localLLMData: LocalLLMInfo = {
- id: entryId,
- name: trimmedParams.name,
- modelId: trimmedParams.modelId,
- baseUrl: trimmedParams.baseUrl,
- fallbackLLM: trimmedParams.fallbackLLM,
- };
-
- // Save to team settings
- const result = await teamData.saveTeamSettingsObj({
- req,
- settingKey: LOCAL_LLM_SETTINGS_KEY,
- entryId,
- data: localLLMData,
- });
-
- if (!result.success) {
- throw new Error(result.error || 'Failed to save local LLM configuration');
- }
-
- return { data: { id: entryId, name: trimmedParams.name } };
- } catch (error) {
- console.error('Error saving local LLM model:', error?.message);
- throw error;
- }
-}
-
-/**
- * Gets a local 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 getLocalLLMByName(req: Request, modelName: string): Promise<LocalLLMInfo | {}> {
- try {
- const allLocalModels = await teamData.getTeamSettingsObj(req, LOCAL_LLM_SETTINGS_KEY);
- let modelInfo = {};
-
- if (allLocalModels && typeof allLocalModels === 'object') {
- for (const [key, model] of Object.entries(allLocalModels)) {
- 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 local LLM by name:', error?.message);
- return {};
- }
-}
-
-/**
- * Gets a local 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 getLocalLLMByEntryId(req: Request, entryId: string): Promise<LocalLLMInfo | null> {
- try {
- const allLocalModels = await teamData.getTeamSettingsObj(req, LOCAL_LLM_SETTINGS_KEY);
-
- if (!allLocalModels || typeof allLocalModels !== 'object') {
- return null;
- }
-
- const model = allLocalModels[entryId];
- if (!model || typeof model !== 'object') {
- return null;
- }
-
- // Ensure id is present
- return { ...model, id: model.id || entryId };
- } catch (error) {
- console.error('Error getting local LLM by entry ID:', error?.message);
- throw error;
- }
-}
-
-/**
- * Gets all local LLM configurations for a team
- * @param req - Express request object
- * @returns Promise with all local models
- */
-async function getAllLocalLLMs(req: Request): Promise<Record<string, LocalLLMInfo>> {
- try {
- const allLocalModels = await teamData.getTeamSettingsObj(req, LOCAL_LLM_SETTINGS_KEY);
-
- if (!allLocalModels || typeof allLocalModels !== 'object') {
- return {};
- }
-
- // Ensure all entries have proper id field
- const normalizedModels: Record<string, LocalLLMInfo> = {};
- for (const [key, model] of Object.entries(allLocalModels)) {
- if (model && typeof model === 'object') {
- normalizedModels[key] = { ...model, id: model.id || key };
- }
- }
-
- return normalizedModels;
- } catch (error) {
- console.error('Error getting all local LLMs:', error?.message);
- return {};
- }
-}
-
-/**
- * Deletes a local LLM configuration
- * @param req - Express request object
- * @param entryId - The ID of the entry to delete
- * @returns Promise with the result
- */
-async function deleteLocalLLM(req: Request, entryId: string) {
- try {
- const result = await teamData.deleteTeamSettingsObj(req, LOCAL_LLM_SETTINGS_KEY, entryId);
-
- if (!result.success) {
- throw new Error(result.error || 'Failed to delete local LLM configuration');
- }
-
- return result;
- } catch (error) {
- console.error('Error deleting local LLM model:', error?.message);
- throw error;
- }
-}
-//#endregion - Core Functions
-
-//#region - Export Helper Object
-export const localLLMHelper = {
- saveLocalLLM,
- getLocalLLMByName,
- getLocalLLMByEntryId,
- getAllLocalLLMs,
- deleteLocalLLM,
- normalizeName,
-};
-//#endregion - Export Helper Object
diff --git a/packages/app/src/backend/routes/router.helpers/userCustomLLM.helper.ts b/packages/app/src/backend/routes/router.helpers/userCustomLLM.helper.ts
new file mode 100644
index 00000000..e4219f82
--- /dev/null
+++ b/packages/app/src/backend/routes/router.helpers/userCustomLLM.helper.ts
@@ -0,0 +1,251 @@
+import { Request } from 'express';
+import Joi from 'joi';
+import { USER_CUSTOM_LLM_SETTINGS_KEY } from '../../constants';
+import { LLMService } from '../../services/LLMHelper/LLMService.class';
+import * as teamData from '../../services/team-data.service';
+import { uid } from '../../services/utils.service';
+
+/**
+ * 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;
+ fallbackLLM: string;
+}
+
+export interface UserCustomLLMInfo extends UserCustomLLMInputParams {
+ id: string; // Always present in stored data
+}
+
+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().required().min(1).max(80).trim(),
+ modelId: Joi.string().required().min(1).max(200).trim(),
+ baseUrl: Joi.string()
+ .required()
+ .uri({ scheme: ['http', 'https'] })
+ .max(500)
+ .trim(),
+ fallbackLLM: Joi.string().required().min(1).max(100).trim(),
+});
+//#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(),
+ fallbackLLM: params.fallbackLLM?.trim(),
+ };
+
+ // 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();
+
+ // Create the user custom LLM data object
+ const userCustomLLMData: UserCustomLLMInfo = {
+ id: entryId,
+ name: trimmedParams.name,
+ modelId: trimmedParams.modelId,
+ baseUrl: trimmedParams.baseUrl,
+ fallbackLLM: trimmedParams.fallbackLLM,
+ };
+
+ // 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 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
diff --git a/packages/app/src/react/features/vault/components/create-local-model-modal.tsx b/packages/app/src/react/features/vault/components/create-user-custom-model-modal.tsx
similarity index 90%
rename from packages/app/src/react/features/vault/components/create-local-model-modal.tsx
rename to packages/app/src/react/features/vault/components/create-user-custom-model-modal.tsx
index 49290e30..115adbf7 100644
--- a/packages/app/src/react/features/vault/components/create-local-model-modal.tsx
+++ b/packages/app/src/react/features/vault/components/create-user-custom-model-modal.tsx
@@ -18,23 +18,23 @@ import {
import { Spinner } from '@src/react/shared/components/ui/spinner';
import { LLMRegistry } from '@src/shared/services/LLMRegistry.service';
import React, { useEffect, useState } from 'react';
-import type { LocalModel } from '../types/types';
+import type { UserCustomModel } from '../types/types';
-interface CreateLocalModelModalProps {
+interface CreateUserCustomModelModalProps {
isOpen: boolean;
onClose: () => void;
- onSubmit: (data: Omit<LocalModel, 'id'>) => void;
- editModel?: LocalModel;
+ onSubmit: (data: Omit<UserCustomModel, 'id'>) => void;
+ editModel?: UserCustomModel;
isProcessing: boolean;
}
-export function CreateLocalModelModal({
+export function CreateUserCustomModelModal({
isOpen,
onClose,
onSubmit,
editModel,
isProcessing,
-}: CreateLocalModelModalProps) {
+}: CreateUserCustomModelModalProps) {
const [formData, setFormData] = useState({
name: '',
modelId: '',
@@ -121,7 +121,7 @@ export function CreateLocalModelModal({
<DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-xl text-[#1E1E1E]">
- {editModel ? 'Edit Local Model' : 'Setup Local Model'}
+ {editModel ? 'Edit Custom Model' : 'Setup Custom Model'}
</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
@@ -134,7 +134,7 @@ export function CreateLocalModelModal({
type="text"
value={formData.name}
onChange={(e) => handleInputChange('name', e.target.value)}
- placeholder="Local Model example v1.3"
+ placeholder="My Custom Model"
fullWidth
className="w-full"
/>
@@ -227,21 +227,21 @@ export function CreateLocalModelModal({
);
}
-interface DeleteLocalModelModalProps {
+interface DeleteUserCustomModelModalProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
- model?: LocalModel;
+ model?: UserCustomModel;
isProcessing: boolean;
}
-export function DeleteLocalModelModal({
+export function DeleteUserCustomModelModal({
isOpen,
onClose,
onConfirm,
model,
isProcessing,
-}: DeleteLocalModelModalProps) {
+}: DeleteUserCustomModelModalProps) {
if (!model) return null;
if (!isOpen) {
@@ -253,8 +253,8 @@ export function DeleteLocalModelModal({
onClose={onClose}
label={isProcessing ? 'Deleting...' : 'Delete'}
handleConfirm={onConfirm}
- message="Delete Local Model"
- lowMsg={`Are you sure you want to delete the local model "${model.name}"? This action cannot be undone.`}
+ message="Delete Custom Model"
+ lowMsg={`Are you sure you want to delete the user custom model "${model.name}"? This action cannot be undone.`}
isLoading={isProcessing}
width="max-w-[600px] w-[calc(100vw_-_-20px)]"
confirmBtnClasses="bg-red-600 hover:bg-red-700 text-white"
diff --git a/packages/app/src/react/features/vault/components/local-models.tsx b/packages/app/src/react/features/vault/components/user-custom-models.tsx
similarity index 75%
rename from packages/app/src/react/features/vault/components/local-models.tsx
rename to packages/app/src/react/features/vault/components/user-custom-models.tsx
index 151d1aa1..f5346471 100644
--- a/packages/app/src/react/features/vault/components/local-models.tsx
+++ b/packages/app/src/react/features/vault/components/user-custom-models.tsx
@@ -5,30 +5,33 @@ import { Tooltip } from 'flowbite-react';
import { Info, Pencil, PlusCircle, Trash2 } from 'lucide-react';
import { useState } from 'react';
import {
- useCreateLocalModel,
- useDeleteLocalModel,
- useLocalModels,
- useUpdateLocalModel,
+ useCreateUserCustomModel,
+ useDeleteUserCustomModel,
+ useUpdateUserCustomModel,
+ useUserCustomModels,
} from '../hooks/use-vault';
-import type { LocalModel } from '../types/types';
-import { CreateLocalModelModal, DeleteLocalModelModal } from './create-local-model-modal';
+import type { UserCustomModel } from '../types/types';
+import {
+ CreateUserCustomModelModal,
+ DeleteUserCustomModelModal,
+} from './create-user-custom-model-modal';
-export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } }) {
+export function UserCustomModels({ pageAccess }: { pageAccess: { write: boolean } }) {
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
- const [editingModel, setEditingModel] = useState<LocalModel | undefined>();
+ const [editingModel, setEditingModel] = useState<UserCustomModel | undefined>();
const [isProcessing, setIsProcessing] = useState(false);
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
- const [modelToDelete, setModelToDelete] = useState<LocalModel | undefined>();
+ const [modelToDelete, setModelToDelete] = useState<UserCustomModel | undefined>();
// Fetch models
- const { data: models = [], isLoading, error } = useLocalModels();
+ const { data: models = [], isLoading, error } = useUserCustomModels();
// Mutations
- const createModel = useCreateLocalModel();
- const updateModel = useUpdateLocalModel();
- const deleteModel = useDeleteLocalModel();
+ const createModel = useCreateUserCustomModel();
+ const updateModel = useUpdateUserCustomModel();
+ const deleteModel = useDeleteUserCustomModel();
- const handleCreateModel = async (data: Omit<LocalModel, 'id'>) => {
+ const handleCreateModel = async (data: Omit<UserCustomModel, 'id'>) => {
// Check for duplicate names (case-insensitive)
const existingModel = models.find(
(model) =>
@@ -38,24 +41,26 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
);
if (existingModel) {
- errorToast('A local model with this name already exists. Please choose a different name.');
+ errorToast(
+ 'A user custom model with this name already exists. Please choose a different name.',
+ );
return;
}
setIsProcessing(true);
try {
await createModel.mutateAsync(data);
- successToast('Local model created successfully');
+ successToast('Custom model created successfully');
setIsCreateModalOpen(false);
} catch (error) {
- console.error('Error creating local model:', error);
- errorToast('Failed to create local model');
+ console.error('Error creating user custom model:', error);
+ errorToast('Failed to create user custom model');
} finally {
setIsProcessing(false);
}
};
- const handleUpdateModel = async (data: Omit<LocalModel, 'id'>) => {
+ const handleUpdateModel = async (data: Omit<UserCustomModel, 'id'>) => {
if (!editingModel) return;
// Check for duplicate names (case-insensitive)
@@ -67,7 +72,9 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
);
if (existingModel) {
- errorToast('A local model with this name already exists. Please choose a different name.');
+ errorToast(
+ 'A user custom model with this name already exists. Please choose a different name.',
+ );
return;
}
@@ -77,11 +84,11 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
modelId: editingModel.id,
updatedFields: data,
});
- successToast('Local model updated successfully');
+ successToast('Custom model updated successfully');
setEditingModel(undefined);
} catch (error) {
- console.error('Error updating local model:', error);
- errorToast('Failed to update local model');
+ console.error('Error updating user custom model:', error);
+ errorToast('Failed to update user custom model');
} finally {
setIsProcessing(false);
}
@@ -93,22 +100,22 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
setIsProcessing(true);
try {
await deleteModel.mutateAsync({ modelId: modelToDelete.id });
- successToast('Local model deleted successfully');
+ successToast('Custom model deleted successfully');
setIsDeleteModalOpen(false);
setModelToDelete(undefined);
} catch (error) {
- console.error('Error deleting local model:', error);
- errorToast('Failed to delete local model');
+ console.error('Error deleting user custom model:', error);
+ errorToast('Failed to delete user custom model');
} finally {
setIsProcessing(false);
}
};
- const handleEditModel = (model: LocalModel) => {
+ const handleEditModel = (model: UserCustomModel) => {
setEditingModel(model);
};
- const handleDeleteClick = (model: LocalModel) => {
+ const handleDeleteClick = (model: UserCustomModel) => {
setModelToDelete(model);
setIsDeleteModalOpen(true);
};
@@ -131,7 +138,7 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
<div className="rounded-lg border border-red-200 bg-red-50 p-4">
<div className="flex items-center gap-2 text-red-800">
<Info className="h-4 w-4" />
- <span className="font-medium">Error loading local models</span>
+ <span className="font-medium">Error loading custom models</span>
</div>
<p className="mt-1 text-sm text-red-600">
{error instanceof Error ? error.message : 'An unexpected error occurred'}
@@ -144,10 +151,10 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
<div className="w-full p-6 rounded-lg border border-solid border-[#d9d9d9] flex-col justify-start items-start gap-3 flex">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2 self-stretch text-[#1e1e1e] text-lg font-semibold font-['Inter'] leading-snug">
- Local Models
+ Custom Models
<Tooltip
className="w-72 text-center"
- content="Local models allow you to connect to your own LLM instances running locally or on your infrastructure"
+ content="Custom models allow you to connect to your own LLM instances running locally or on your infrastructure"
>
<Info className="w-4 h-4" />
</Tooltip>
@@ -160,7 +167,7 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
) : (
<>
{models.length === 0 ? (
- <div className="py-4 text-center text-gray-500">No local models found</div>
+ <div className="py-4 text-center text-gray-500">No custom models found</div>
) : (
<div className="overflow-x-auto">
<div className="min-w-[500px]">
@@ -168,7 +175,7 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
<div key={model.id} className="flex items-center justify-between">
<div className="flex items-center gap-2">
<span className="inline-flex h-5 items-center rounded-md bg-blue-100 px-2 text-xs font-medium text-blue-800">
- Local
+ Custom
</span>
<span className="font-medium text-[#374151] max-w-[200px] truncate">
{model.name}
@@ -214,7 +221,7 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
addIcon
Icon={<PlusCircle className="mr-2 h-4 w-4" />}
handleClick={() => setIsCreateModalOpen(true)}
- label="Add Local Model"
+ label="Add Custom Model"
/>
</div>
)}
@@ -223,7 +230,7 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
</div>
{/* Create/Edit Modal */}
- <CreateLocalModelModal
+ <CreateUserCustomModelModal
isOpen={isCreateModalOpen || !!editingModel}
onClose={editingModel ? handleCloseEditModal : handleCloseCreateModal}
onSubmit={editingModel ? handleUpdateModel : handleCreateModel}
@@ -232,7 +239,7 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
/>
{/* Delete Modal */}
- <DeleteLocalModelModal
+ <DeleteUserCustomModelModal
isOpen={isDeleteModalOpen}
onClose={handleCloseDeleteModal}
onConfirm={handleDeleteModel}
@@ -243,4 +250,4 @@ export function LocalModels({ pageAccess }: { pageAccess: { write: boolean } })
);
}
-export default LocalModels;
+export default UserCustomModels;
diff --git a/packages/app/src/react/features/vault/hooks/use-vault.tsx b/packages/app/src/react/features/vault/hooks/use-vault.tsx
index cc83f9b9..313f3268 100644
--- a/packages/app/src/react/features/vault/hooks/use-vault.tsx
+++ b/packages/app/src/react/features/vault/hooks/use-vault.tsx
@@ -2,14 +2,14 @@ import type {
ApiKey,
ApiKeysResponse,
EnterpriseModel,
- LocalModel,
+ UserCustomModel,
UserModel,
} from '@react/features/vault/types/types';
import {
apiKeyService,
enterpriseModelService,
- localModelService,
recommendedModelsService,
+ userCustomModelService,
userModelService,
vaultService,
} from '@react/features/vault/vault-business-logic';
@@ -283,31 +283,31 @@ export function useUpdateRecommendedModel() {
});
}
-// Local Model Hooks
-const LOCAL_MODEL_QUERY_KEYS = {
- LOCAL_MODELS: ['localModels'],
+// User Custom Model Hooks
+const USER_CUSTOM_MODEL_QUERY_KEYS = {
+ USER_CUSTOM_MODELS: ['userCustomModels'],
} as const;
-export function useLocalModels() {
+export function useUserCustomModels() {
return useQuery({
- queryKey: LOCAL_MODEL_QUERY_KEYS.LOCAL_MODELS,
- queryFn: () => localModelService.getLocalModels(),
+ queryKey: USER_CUSTOM_MODEL_QUERY_KEYS.USER_CUSTOM_MODELS,
+ queryFn: () => userCustomModelService.getUserCustomModels(),
});
}
-export function useCreateLocalModel() {
+export function useCreateUserCustomModel() {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: (modelDetails: Omit<LocalModel, 'id'>) =>
- localModelService.createLocalModel(modelDetails),
+ mutationFn: (modelDetails: Omit<UserCustomModel, 'id'>) =>
+ userCustomModelService.createUserCustomModel(modelDetails),
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: LOCAL_MODEL_QUERY_KEYS.LOCAL_MODELS });
+ queryClient.invalidateQueries({ queryKey: USER_CUSTOM_MODEL_QUERY_KEYS.USER_CUSTOM_MODELS });
},
});
}
-export function useUpdateLocalModel() {
+export function useUpdateUserCustomModel() {
const queryClient = useQueryClient();
return useMutation({
@@ -316,21 +316,21 @@ export function useUpdateLocalModel() {
updatedFields,
}: {
modelId: string;
- updatedFields: Partial<LocalModel>;
- }) => localModelService.updateLocalModel(modelId, updatedFields),
+ updatedFields: Partial<UserCustomModel>;
+ }) => userCustomModelService.updateUserCustomModel(modelId, updatedFields),
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: LOCAL_MODEL_QUERY_KEYS.LOCAL_MODELS });
+ queryClient.invalidateQueries({ queryKey: USER_CUSTOM_MODEL_QUERY_KEYS.USER_CUSTOM_MODELS });
},
});
}
-export function useDeleteLocalModel() {
+export function useDeleteUserCustomModel() {
const queryClient = useQueryClient();
return useMutation<void, Error, { modelId: string }>({
- mutationFn: ({ modelId }) => localModelService.deleteLocalModel(modelId),
+ mutationFn: ({ modelId }) => userCustomModelService.deleteUserCustomModel(modelId),
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: LOCAL_MODEL_QUERY_KEYS.LOCAL_MODELS });
+ queryClient.invalidateQueries({ queryKey: USER_CUSTOM_MODEL_QUERY_KEYS.USER_CUSTOM_MODELS });
},
});
}
diff --git a/packages/app/src/react/features/vault/pages/VaultPage.tsx b/packages/app/src/react/features/vault/pages/VaultPage.tsx
index 042fc2a6..c6de2ad0 100644
--- a/packages/app/src/react/features/vault/pages/VaultPage.tsx
+++ b/packages/app/src/react/features/vault/pages/VaultPage.tsx
@@ -9,9 +9,9 @@ import React, { useMemo } from 'react';
import { CiExport } from 'react-icons/ci';
import { ApiKeys } from '../components/api-keys';
import { EnterpriseModels } from '../components/enterprise-models';
-import LocalModels from '../components/local-models';
import { OAuthConnections } from '../components/oauth-connections';
import { RecommendedModels } from '../components/recommended-models';
+import UserCustomModels from '../components/user-custom-models';
import { UserModels } from '../components/user-models';
import { useVault } from '../hooks/use-vault';
@@ -83,7 +83,7 @@ export default function VaultPage() {
)}
<UserModels pageAccess={pageAccess} />
- <LocalModels pageAccess={pageAccess} />
+ <UserCustomModels pageAccess={pageAccess} />
<EnterpriseModels pageAccess={pageAccess} />
<OAuthConnections />
diff --git a/packages/app/src/react/features/vault/types/types.ts b/packages/app/src/react/features/vault/types/types.ts
index 902ee74b..312c9117 100644
--- a/packages/app/src/react/features/vault/types/types.ts
+++ b/packages/app/src/react/features/vault/types/types.ts
@@ -165,9 +165,9 @@ export interface ApiKeysResponse {
}
/**
- * Represents a local LLM model in the system
+ * Represents a user custom LLM model in the system
*/
-export interface LocalModel {
+export interface UserCustomModel {
/**
* Unique identifier for the model
*/
@@ -184,7 +184,7 @@ export interface LocalModel {
modelId: string;
/**
- * Base URL for the local model API
+ * Base URL for the user custom model API
*/
baseUrl: string;
diff --git a/packages/app/src/react/features/vault/vault-business-logic.ts b/packages/app/src/react/features/vault/vault-business-logic.ts
index ea8bd417..ec527cb5 100644
--- a/packages/app/src/react/features/vault/vault-business-logic.ts
+++ b/packages/app/src/react/features/vault/vault-business-logic.ts
@@ -4,7 +4,13 @@ import {
} from '@src/shared/constants/custom-llm.constants';
import { VAULT_SCOPE_AGENT_LLM } from '@src/shared/constants/general';
import { customModels } from '@src/shared/custom-models';
-import type { ApiKey, BuiltInModel, EnterpriseModel, LocalModel, UserModel } from './types/types';
+import type {
+ ApiKey,
+ BuiltInModel,
+ EnterpriseModel,
+ UserCustomModel,
+ UserModel,
+} from './types/types';
export interface Provider {
id: string;
@@ -611,15 +617,15 @@ export const providerService = {
},
};
-export const localModelService = {
- localModels: [],
+export const userCustomModelService = {
+ userCustomModels: [],
/**
- * Fetches all local LLM models for the current team
+ * Fetches all user custom LLM models for the current team
*/
- getLocalModels: async (): Promise<LocalModel[]> => {
+ getUserCustomModels: async (): Promise<UserCustomModel[]> => {
try {
- const response = await fetch('/api/page/vault/local-llm', {
+ const response = await fetch('/api/page/vault/user-custom-llm', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
@@ -627,15 +633,15 @@ export const localModelService = {
});
if (!response.ok) {
- throw new Error('Failed to fetch local models');
+ throw new Error('Failed to fetch user custom models');
}
const result = await response.json();
if (!result.success) {
- throw new Error(result.error || 'Failed to fetch local models');
+ throw new Error(result.error || 'Failed to fetch user custom models');
}
- // Convert the local LLM data to our LocalModel format
+ // Convert the user custom LLM data to our UserCustomModel format
const models = Object.entries(result.data || {}).map(([id, value]: [string, any]) => ({
id: value.id || id,
name: value.name,
@@ -646,17 +652,19 @@ export const localModelService = {
return models;
} catch (error) {
- console.error('Error fetching local models:', error);
+ console.error('Error fetching user custom models:', error);
return [];
}
},
/**
- * Creates a new local LLM model
+ * Creates a new user custom LLM model
*/
- createLocalModel: async (modelDetails: Omit<LocalModel, 'id'>): Promise<LocalModel> => {
+ createUserCustomModel: async (
+ modelDetails: Omit<UserCustomModel, 'id'>,
+ ): Promise<UserCustomModel> => {
try {
- const response = await fetch('/api/page/vault/local-llm/', {
+ const response = await fetch('/api/page/vault/user-custom-llm/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -665,12 +673,12 @@ export const localModelService = {
});
if (!response.ok) {
- throw new Error('Failed to create local model');
+ throw new Error('Failed to create user custom model');
}
const result = await response.json();
if (!result.success) {
- throw new Error(result.error || 'Failed to create local model');
+ throw new Error(result.error || 'Failed to create user custom model');
}
// Return the created model with the generated ID
@@ -682,20 +690,20 @@ export const localModelService = {
fallbackLLM: modelDetails.fallbackLLM,
};
} catch (error) {
- console.error('Error creating local model:', error);
- throw new Error(error.error || error.message || 'Failed to create local model');
+ console.error('Error creating user custom model:', error);
+ throw new Error(error.error || error.message || 'Failed to create user custom model');
}
},
/**
- * Updates an existing local LLM model
+ * Updates an existing user custom LLM model
*/
- updateLocalModel: async (
+ updateUserCustomModel: async (
modelId: string,
- updatedFields: Partial<LocalModel>,
- ): Promise<LocalModel> => {
+ updatedFields: Partial<UserCustomModel>,
+ ): Promise<UserCustomModel> => {
try {
- const response = await fetch(`/api/page/vault/local-llm/${modelId}`, {
+ const response = await fetch(`/api/page/vault/user-custom-llm/${modelId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
@@ -704,12 +712,12 @@ export const localModelService = {
});
if (!response.ok) {
- throw new Error('Failed to update local model');
+ throw new Error('Failed to update user custom model');
}
const result = await response.json();
if (!result.success) {
- throw new Error(result.error || 'Failed to update local model');
+ throw new Error(result.error || 'Failed to update user custom model');
}
// Return the updated model
@@ -721,17 +729,17 @@ export const localModelService = {
fallbackLLM: updatedFields.fallbackLLM || '',
};
} catch (error) {
- console.error('Error updating local model:', error);
- throw new Error(error.error || error.message || 'Failed to update local model');
+ console.error('Error updating user custom model:', error);
+ throw new Error(error.error || error.message || 'Failed to update user custom model');
}
},
/**
- * Deletes a local LLM model
+ * Deletes a user custom LLM model
*/
- deleteLocalModel: async (modelId: string): Promise<void> => {
+ deleteUserCustomModel: async (modelId: string): Promise<void> => {
try {
- const response = await fetch(`/api/page/vault/local-llm/${modelId}`, {
+ const response = await fetch(`/api/page/vault/user-custom-llm/${modelId}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
@@ -739,16 +747,16 @@ export const localModelService = {
});
if (!response.ok) {
- throw new Error('Failed to delete local model');
+ throw new Error('Failed to delete user custom model');
}
const result = await response.json();
if (!result.success) {
- throw new Error(result.error || 'Failed to delete local model');
+ throw new Error(result.error || 'Failed to delete user custom model');
}
} catch (error) {
- console.error('Error deleting local model:', error);
- throw new Error(error.error || error.message || 'Failed to delete local model');
+ console.error('Error deleting user custom model:', error);
+ throw new Error(error.error || error.message || 'Failed to delete user custom model');
}
},
};