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.

register routes for Local LLM

Forhad Hosain7855be600947
diff --git a/packages/app/src/backend/constants.ts b/packages/app/src/backend/constants.ts
index 39f91349..7d020f8f 100644
--- a/packages/app/src/backend/constants.ts
+++ b/packages/app/src/backend/constants.ts
@@ -5,6 +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 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 30ab6773..558cef0b 100644
--- a/packages/app/src/backend/routes/api/page/vault.ts
+++ b/packages/app/src/backend/routes/api/page/vault.ts
@@ -18,6 +18,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 { getVaultKeys, setVaultKey } from '../../router.utils';
const router = express.Router();
@@ -358,12 +359,10 @@ router.get('/oauth-connections', includeTeamDetails, async (req, res) => {
res.json(sanitizedSettings);
} catch (error) {
console.error('Error fetching OAuth connections:', error?.message);
- res
- .status(500)
- .json({
- success: false,
- error: 'An unexpected error occurred while fetching OAuth connections.',
- });
+ res.status(500).json({
+ success: false,
+ error: 'An unexpected error occurred while fetching OAuth connections.',
+ });
}
});
@@ -514,12 +513,10 @@ router.put('/oauth-connections', includeTeamDetails, async (req, res) => {
res.json({ success: true, data: finalDataToSave }); // Respond with the data that was saved
} catch (error) {
console.error(`[PUT /oauth-connections] Error processing request for ${entryId}:`, error);
- res
- .status(500)
- .json({
- success: false,
- error: 'An unexpected error occurred while saving the OAuth connection.',
- });
+ res.status(500).json({
+ success: false,
+ error: 'An unexpected error occurred while saving the OAuth connection.',
+ });
}
});
@@ -549,12 +546,10 @@ router.delete('/oauth-connections/:connectionId', includeTeamDetails, async (req
res.status(200).json({ success: true });
} catch (error) {
console.error(`Error deleting OAuth connection ${connectionId}:`, error);
- res
- .status(500)
- .json({
- success: false,
- error: 'An unexpected error occurred while deleting the OAuth connection.',
- });
+ res.status(500).json({
+ success: false,
+ error: 'An unexpected error occurred while deleting the OAuth connection.',
+ });
}
});
@@ -599,9 +594,22 @@ router.put('/recommended-models/:providerId', includeTeamDetails, async (req, re
res.send({ success: true, data: result?.data });
});
-export default router;
+// TODO: Refactor this file by splitting it into separate modules for better organization.
+// Suggested structure:
+// - vault/index.ts
+// - vault/custom-llm.ts
+// - vault/local-llm.ts
+
+// #region Custom LLM Routes
+/**
+ * Custom LLM Routes
+ *
+ * Provides endpoints for managing team-specific custom LLM models:
+ * - CRUD operations for custom LLM configurations
+ * - Access control based on team subscription and user permissions
+ * - Cache management for custom model data
+ */
-// #region Custom LLM
const customLLMAccessMw = async (req: any, res: any, next: any) => {
//* should be called after `includeTeamDetails` middleware to get the team details
const teamDetails: Team = req._team;
@@ -733,3 +741,146 @@ router.delete('/custom-llm/:provider/:id', customLLMRouteMiddlewares, async (req
}
});
// #endregion
+
+// #region Local LLM Routes
+/**
+ * Local 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
+ * - Secure credential access via with-credentials endpoint
+ *
+ * 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>
+ * }
+ * }
+ */
+
+/**
+ * Create or update a local LLM model
+ */
+const handleLocalLLMSave = 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, {
+ id,
+ ...req.body,
+ });
+
+ // Delete the local LLM model cache
+ await cacheClient.del(config.cache.getCustomModelsCacheKey(teamId)).catch((error) => {
+ console.warn('Error deleting local LLM model cache:', error?.message);
+ });
+
+ res.status(200).json({ success: true, data: saveLocalLLM.data });
+ } catch (error) {
+ console.error('Error saving local LLM model:', error?.message);
+ res.status(500).json({ success: false, error: 'Error saving local LLM model.' });
+ }
+};
+
+/**
+ * Create a new local LLM model
+ * POST /local-llm/
+ */
+router.post('/local-llm/', includeTeamDetails, handleLocalLLMSave);
+
+/**
+ * Update an existing local LLM model
+ * PUT /local-llm/:id
+ */
+router.put('/local-llm/:id', includeTeamDetails, handleLocalLLMSave);
+
+/**
+ * Get all local LLM models
+ * GET /local-llm
+ */
+router.get('/local-llm', includeTeamDetails, async (req, res) => {
+ try {
+ const allLocalModels = await localLLMHelper.getAllLocalLLMs(req);
+ res.status(200).json({ success: true, data: allLocalModels });
+ } catch (error) {
+ console.error('Error getting local LLM models:', error?.message);
+ res.status(500).json({ success: false, error: 'Error getting local LLM models.' });
+ }
+});
+
+/**
+ * Get a specific local LLM model by ID
+ * GET /local-llm/:id
+ */
+router.get('/local-llm/:id', includeTeamDetails, async (req, res) => {
+ try {
+ const entryId = req.params.id;
+ const modelInfo = await localLLMHelper.getLocalLLMByEntryId(req, entryId);
+
+ if (!modelInfo) {
+ return res.status(404).json({ success: false, error: 'Local 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.' });
+ }
+});
+
+/**
+ * Get a local LLM model with credentials by name
+ * GET /local-llm/with-credentials/:name
+ */
+router.get('/local-llm/with-credentials/:name', includeTeamDetails, async (req, res) => {
+ try {
+ const modelName = req.params.name;
+ const modelInfo = await localLLMHelper.getLocalLLMByName(req, modelName);
+
+ if (!modelInfo || Object.keys(modelInfo).length === 0) {
+ return res.status(404).json({ success: false, error: 'Local 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);
+ res
+ .status(500)
+ .json({ success: false, error: 'Error getting local LLM model with credentials.' });
+ }
+});
+
+/**
+ * Delete a local LLM model
+ * DELETE /local-llm/:id
+ */
+router.delete('/local-llm/:id', includeTeamDetails, async (req, res) => {
+ try {
+ const teamId = req?._team?.id;
+ const id = req.params.id;
+
+ const deleteResult = await localLLMHelper.deleteLocalLLM(req, id);
+
+ // Delete the local LLM model cache
+ await cacheClient.del(config.cache.getCustomModelsCacheKey(teamId)).catch((error) => {
+ console.warn('Error deleting local 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.' });
+ }
+});
+
+// #endregion
+
+export default router;
diff --git a/packages/app/src/backend/routes/router.helpers/localLLM.helper.ts b/packages/app/src/backend/routes/router.helpers/localLLM.helper.ts
new file mode 100644
index 00000000..5e2ab478
--- /dev/null
+++ b/packages/app/src/backend/routes/router.helpers/localLLM.helper.ts
@@ -0,0 +1,250 @@
+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