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.

add api key field for user custom model

Forhad Hosaina4de8889d42d
diff --git a/packages/app/src/backend/routes/api/page/vault.ts b/packages/app/src/backend/routes/api/page/vault.ts
index bd0356fd..4cd4fe13 100644
--- a/packages/app/src/backend/routes/api/page/vault.ts
+++ b/packages/app/src/backend/routes/api/page/vault.ts
@@ -769,11 +769,14 @@ router.delete('/custom-llm/:provider/:id', customLLMRouteMiddlewares, async (req
*/
const handleUserCustomLLMSave = async (req, res) => {
const teamId = req?._team?.id;
+ const userEmail = req?._user?.email;
const id = req.params?.id; // This will be undefined for POST requests
try {
const saveUserCustomLLM = await userCustomLLMHelper.saveUserCustomLLM(req, {
id,
+ teamId,
+ userEmail,
...req.body,
});
@@ -835,6 +838,26 @@ router.get('/user-custom-llm/:id', includeTeamDetails, async (req, res) => {
}
});
+/**
+ * Get a specific user custom LLM model by ID with decrypted credentials
+ * GET /user-custom-llm/:id/with-credentials
+ */
+router.get('/user-custom-llm/:id/with-credentials', includeTeamDetails, async (req, res) => {
+ try {
+ const entryId = req.params.id;
+ const modelInfo = await userCustomLLMHelper.getUserCustomLLMWithCredentials(req, entryId);
+
+ if (!modelInfo) {
+ 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 user custom LLM model with credentials:', error?.message);
+ res.status(500).json({ success: false, error: 'Error getting user custom LLM model.' });
+ }
+});
+
/**
* Get a user custom LLM model with credentials by name
* GET /user-custom-llm/with-credentials/:name
diff --git a/packages/app/src/backend/routes/router.helpers/userCustomLLM.helper.ts b/packages/app/src/backend/routes/router.helpers/userCustomLLM.helper.ts
index 30c25031..c3a7d3ac 100644
--- a/packages/app/src/backend/routes/router.helpers/userCustomLLM.helper.ts
+++ b/packages/app/src/backend/routes/router.helpers/userCustomLLM.helper.ts
@@ -2,8 +2,10 @@ 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
@@ -34,10 +36,20 @@ export interface UserCustomLLMInputParams {
maxOutputTokens?: number;
fallbackLLM?: string;
features?: string[];
+ teamId?: string;
+ userEmail?: string;
+ credentials?: {
+ apiKey?: string;
+ isUserKey?: boolean;
+ };
}
-export interface UserCustomLLMInfo extends UserCustomLLMInputParams {
+export interface UserCustomLLMInfo extends Omit<UserCustomLLMInputParams, 'teamId' | 'userEmail'> {
id: string; // Always present in stored data
+ credentials?: {
+ apiKey?: string;
+ isUserKey?: boolean;
+ };
}
interface UserCustomLLMModel {
@@ -64,6 +76,14 @@ const userCustomLLMValidationSchema = Joi.object({
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
@@ -85,8 +105,16 @@ async function saveUserCustomLLM(req: Request, params: UserCustomLLMInputParams)
provider: params.provider?.trim(),
fallbackLLM: params.fallbackLLM?.trim(),
features: params.features || ['text'],
+ credentials: params.credentials,
};
+ const teamId = params.teamId || req?._team?.id;
+ 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) {
@@ -95,6 +123,40 @@ async function saveUserCustomLLM(req: Request, params: UserCustomLLMInputParams)
// 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 = {
@@ -109,6 +171,74 @@ async function saveUserCustomLLM(req: Request, params: UserCustomLLMInputParams)
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,
@@ -232,6 +362,75 @@ async function getAllUserCustomLLMs(req: Request): Promise<Record<string, UserCu
}
}
+/**
+ * Gets a user custom LLM configuration with credentials (API key from vault)
+ * @param req - Express request object
+ * @param entryId - The ID of the entry to retrieve
+ * @returns Promise with the model info including decrypted API key
+ */
+async function getUserCustomLLMWithCredentials(
+ req: Request,
+ entryId: string,
+): Promise<UserCustomLLMInfo | null> {
+ try {
+ const teamId = req?._team?.id;
+ const accessToken = req?.user?.accessToken;
+ const idToken = req?.session?.idToken;
+
+ if (!teamId) {
+ throw new Error('Team ID is required');
+ }
+
+ // Get the model info first
+ const modelInfo = await getUserCustomLLMByEntryId(req, entryId);
+
+ if (!modelInfo) {
+ return null;
+ }
+
+ // If the model has credentials with a vault key template variable, retrieve the actual key
+ if (modelInfo.credentials?.isUserKey && modelInfo.credentials?.apiKey) {
+ const apiKeyTemplateVariable = modelInfo.credentials.apiKey;
+
+ // Extract the key name from the template variable {{KEY(...)}}
+ const match = apiKeyTemplateVariable.match(/\{\{KEY\((.+?)\)\}\}/);
+
+ if (match && match[1]) {
+ const apiKeyName = match[1];
+
+ // Retrieve the key from vault
+ try {
+ const keyEntry = await vault.get(
+ {
+ team: teamId,
+ keyName: apiKeyName,
+ },
+ req,
+ );
+
+ // Return the model info with the decrypted API key
+ return {
+ ...modelInfo,
+ credentials: {
+ apiKey: keyEntry?.key || '',
+ isUserKey: true,
+ },
+ };
+ } catch (vaultError) {
+ console.warn('Error retrieving API key from vault:', vaultError?.message);
+ // Return model info without the key if vault retrieval fails
+ return modelInfo;
+ }
+ }
+ }
+
+ return modelInfo;
+ } catch (error) {
+ console.error('Error getting user custom LLM with credentials:', error?.message);
+ throw error;
+ }
+}
+
/**
* Deletes a user custom LLM configuration
* @param req - Express request object
@@ -240,6 +439,27 @@ async function getAllUserCustomLLMs(req: Request): Promise<Record<string, UserCu
*/
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) {
@@ -259,6 +479,7 @@ export const userCustomLLMHelper = {
saveUserCustomLLM,
getUserCustomLLMByName,
getUserCustomLLMByEntryId,
+ getUserCustomLLMWithCredentials,
getAllUserCustomLLMs,
deleteUserCustomLLM,
};
diff --git a/packages/app/src/react/features/vault/components/create-user-custom-model-modal.tsx b/packages/app/src/react/features/vault/components/create-user-custom-model-modal.tsx
index 7ba0af00..72699027 100644
--- a/packages/app/src/react/features/vault/components/create-user-custom-model-modal.tsx
+++ b/packages/app/src/react/features/vault/components/create-user-custom-model-modal.tsx
@@ -20,8 +20,10 @@ import {
import { Spinner } from '@src/react/shared/components/ui/spinner';
import { CUSTOM_LLM_FEATURES } from '@src/shared/constants/custom-llm.constants';
import { LLMRegistry } from '@src/shared/services/LLMRegistry.service';
-import React, { useEffect, useMemo, useState } from 'react';
+import { generateKeyTemplateVar } from '@src/shared/utils';
+import React, { useEffect, useMemo, useRef, useState } from 'react';
import type { UserCustomModel } from '../types/types';
+import { userCustomModelService } from '../vault-business-logic';
/**
* SVG icon for info tooltips
@@ -31,6 +33,46 @@ const infoIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"
<path d="M12.0057 15.6932V11.3936M12 8.35426V8.29102" stroke="#757575" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`;
+/**
+ * SVG icon for showing password (eye icon)
+ */
+const EyeIcon = () => (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
+ <circle cx="12" cy="12" r="3" />
+ </svg>
+);
+
+/**
+ * SVG icon for hiding password (eye-slash icon)
+ */
+const EyeOffIcon = () => (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
+ <line x1="1" y1="1" x2="23" y2="23" />
+ </svg>
+);
+
interface CreateUserCustomModelModalProps {
isOpen: boolean;
onClose: () => void;
@@ -51,6 +93,26 @@ const getTempBadge = (tags: string[]) => {
return tags.filter((tag) => TEMP_BADGES?.[tag?.toLowerCase()]).join(' ');
};
+/**
+ * Extracts the key name from a vault key template variable
+ * @param templateVariable - The template variable string (e.g., "{{KEY(My API Key)}}")
+ * @returns The extracted key name or empty string if not a valid template variable
+ */
+const extractKeyNameFromTemplate = (templateVariable: string): string => {
+ const match = templateVariable?.match(/\{\{KEY\((.+?)\)\}\}/);
+ return match ? match[1] : '';
+};
+
+/**
+ * Transforms the base URL by removing '.forbidden' from it
+ * @param url - The URL to transform
+ * @returns The transformed URL with '.forbidden' removed
+ */
+const transformBaseURL = (url: string): string => {
+ if (!url) return url;
+ return url.replace(/\.forbidden/gi, '');
+};
+
export function CreateUserCustomModelModal({
isOpen,
onClose,
@@ -67,8 +129,21 @@ export function CreateUserCustomModelModal({
maxOutputTokens: undefined as number | undefined,
fallbackLLM: '',
features: ['text'],
+ apiKey: '',
+ apiKeyName: '',
});
+ const [showApiKey, setShowApiKey] = useState(false);
+ const [isApiKeyFromVault, setIsApiKeyFromVault] = useState(false);
+ const [isLoadingApiKey, setIsLoadingApiKey] = useState(false);
+ const [showApiKeyPassword, setShowApiKeyPassword] = useState(false);
+ const [hasRevealedApiKey, setHasRevealedApiKey] = useState(false);
+ const [hasModifiedApiKey, setHasModifiedApiKey] = useState(false);
+ const [shouldRemoveApiKey, setShouldRemoveApiKey] = useState(false);
+
+ // Track if modal was just opened to distinguish from data updates
+ const prevIsOpenRef = useRef(isOpen);
+
const fallbackOptions = useMemo(() => {
return LLMRegistry.getSortedModelsByFeatures('tools').map((model) => {
let badge = getTempBadge(model.tags);
@@ -80,19 +155,62 @@ export function CreateUserCustomModelModal({
});
}, []);
+ /**
+ * Memoize serialized editModel to properly track deep changes
+ * This ensures we detect changes in nested objects like credentials
+ */
+ const editModelKey = useMemo(() => {
+ return JSON.stringify(editModel);
+ }, [editModel]);
+
+ /**
+ * Effect to populate form data when modal opens or editModel changes
+ * This ensures formData ALWAYS updates when editModel changes, including credentials
+ */
useEffect(() => {
+ // Detect if modal is transitioning from closed to open
+ const isModalOpening = isOpen && !prevIsOpenRef.current;
+ prevIsOpenRef.current = isOpen;
+
+ // Only process when modal is open
+ if (!isOpen) {
+ return;
+ }
+
if (editModel) {
- setFormData({
- name: editModel.name,
- modelId: editModel.modelId,
- baseURL: editModel.baseURL,
- provider: editModel.provider,
+ // Extract API key info from template variable if present
+ const apiKeyTemplateVariable = editModel.credentials?.apiKey || '';
+ const extractedKeyName = extractKeyNameFromTemplate(apiKeyTemplateVariable);
+ const hasVaultKey = editModel.credentials?.isUserKey === true && extractedKeyName !== '';
+
+ // Update formData with latest editModel values
+ // Only update apiKey field if it's currently empty (not revealed) or if modal is just opening
+ setFormData((prev) => ({
+ name: editModel.name || '',
+ modelId: editModel.modelId || '',
+ baseURL: editModel.baseURL || '',
+ provider: editModel.provider || '',
contextWindow: editModel.contextWindow,
maxOutputTokens: editModel.maxOutputTokens,
fallbackLLM: editModel.fallbackLLM || '',
features: editModel.features || ['text'],
- });
+ // Preserve revealed apiKey if user has revealed it, otherwise clear it
+ apiKey: hasRevealedApiKey && prev.apiKey ? prev.apiKey : '',
+ apiKeyName: extractedKeyName,
+ }));
+
+ setIsApiKeyFromVault(hasVaultKey);
+
+ // Only reset reveal states when modal is first opening, not on data updates
+ if (isModalOpening) {
+ setShowApiKey(false);
+ setShowApiKeyPassword(false);
+ setHasRevealedApiKey(false);
+ setHasModifiedApiKey(false);
+ setShouldRemoveApiKey(false);
+ }
} else {
+ // Reset form for creating new model
setFormData({
name: '',
modelId: '',
@@ -102,9 +220,21 @@ export function CreateUserCustomModelModal({
maxOutputTokens: undefined,
fallbackLLM: '',
features: ['text'],
+ apiKey: '',
+ apiKeyName: '',
});
+ setIsApiKeyFromVault(false);
+ setShowApiKey(false);
+ setShowApiKeyPassword(false);
+ setHasRevealedApiKey(false);
+ setHasModifiedApiKey(false);
+ setShouldRemoveApiKey(false);
}
- }, [editModel, isOpen, fallbackOptions]);
+ // We use editModelKey instead of editModel directly to ensure deep change detection
+ // editModelKey is a memoized JSON string that changes whenever editModel's properties change
+ // Note: We don't include hasRevealedApiKey in dependencies to avoid re-running when user reveals key
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isOpen, editModelKey]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
@@ -118,7 +248,47 @@ export function CreateUserCustomModelModal({
return;
}
- onSubmit(formData);
+ // Prepare the submission data
+ // Apply transformer to remove '.forbidden' in case user manually entered it or it wasn't cleaned
+ const cleanedBaseURL = transformBaseURL(formData.baseURL);
+
+ const submissionData: Omit<UserCustomModel, 'id'> = {
+ name: formData.name,
+ modelId: formData.modelId,
+ baseURL: cleanedBaseURL,
+ provider: formData.provider,
+ contextWindow: formData.contextWindow,
+ maxOutputTokens: formData.maxOutputTokens,
+ fallbackLLM: formData.fallbackLLM,
+ features: formData.features,
+ };
+
+ // Handle API key credentials based on different scenarios:
+ // IMPORTANT: Only update credentials when user explicitly modifies the API key
+ if (shouldRemoveApiKey) {
+ // User clicked "Remove Key" - set credentials to empty object to signal removal
+ // The backend will handle deleting the key from vault
+ submissionData.credentials = {} as typeof submissionData.credentials;
+ } else if (editModel?.credentials && !hasModifiedApiKey) {
+ // Scenario: Editing a model that has existing credentials, and user hasn't modified the key
+ // Preserve the existing credentials (template variable) unchanged
+ // This ensures we don't accidentally reset the key when updating other fields
+ submissionData.credentials = editModel.credentials;
+ } else if (hasModifiedApiKey || (!editModel && formData.apiKey?.trim())) {
+ // Scenario 1: User has modified the API key (revealed and changed it)
+ // Scenario 2: Creating new model with an API key
+ // Only include credentials if there's actually a key value
+ if (formData.apiKey?.trim()) {
+ submissionData.credentials = {
+ apiKey: formData.apiKey.trim(),
+ isUserKey: true,
+ };
+ }
+ }
+ // If none of the above conditions match, credentials won't be included (undefined)
+ // This means: editing a model without credentials, or creating without a key
+
+ onSubmit(submissionData);
};
const handleInputChange = (field: string, value: string) => {
@@ -128,6 +298,19 @@ export function CreateUserCustomModelModal({
}));
};
+ /**
+ * Handles API key input changes and marks it as modified
+ * @param value - The new API key value
+ */
+ const handleApiKeyChange = (value: string) => {
+ setFormData((prev) => ({
+ ...prev,
+ apiKey: value,
+ }));
+ // Mark the API key as modified when user types in the field
+ setHasModifiedApiKey(true);
+ };
+
/**
* Handles numeric input changes for context window and max output tokens
* @param field - The field name to update
@@ -163,12 +346,12 @@ export function CreateUserCustomModelModal({
setFormData((prev) => {
const currentFeatures = prev.features;
const isCurrentlySelected = currentFeatures.includes(featureValue);
-
+
// If feature is selected, remove it; otherwise, add it
const newFeatures = isCurrentlySelected
? currentFeatures.filter((f) => f !== featureValue)
: [...currentFeatures, featureValue];
-
+
// Ensure at least one feature is selected; default to 'text' if none
if (newFeatures.length === 0) {
return {
@@ -176,7 +359,7 @@ export function CreateUserCustomModelModal({
features: ['text'],
};
}
-
+
return {
...prev,
features: newFeatures,
@@ -184,12 +367,84 @@ export function CreateUserCustomModelModal({
});
};
+ /**
+ * Handles revealing the API key from vault
+ * Fetches the decrypted API key and populates the form field
+ * If key cannot be retrieved, sets empty value allowing user to enter a new key
+ */
+ const handleRevealApiKey = async () => {
+ if (!editModel?.id) return;
+
+ setIsLoadingApiKey(true);
+ try {
+ const modelWithCredentials = await userCustomModelService.getUserCustomModelWithCredentials(
+ editModel.id,
+ );
+
+ // Validate that we received an actual API key, not a template variable
+ const apiKey = modelWithCredentials.credentials?.apiKey || '';
+
+ // Check if we got the actual key or if it's still a template variable
+ // If it's a template or empty, set empty string so user can enter a new key
+ const actualKey = apiKey && !apiKey.startsWith('{{KEY(') ? apiKey : '';
+
+ setFormData((prev) => ({
+ ...prev,
+ apiKey: actualKey,
+ }));
+
+ setShowApiKey(true);
+ setHasRevealedApiKey(true); // Mark that user has revealed the key - now it can be updated
+ } catch {
+ // If fetching fails, set empty value so user can enter a new key
+ setFormData((prev) => ({
+ ...prev,
+ apiKey: '',
+ }));
+
+ setShowApiKey(true);
+ setHasRevealedApiKey(true);
+ } finally {
+ setIsLoadingApiKey(false);
+ }
+ };
+
+ /**
+ * Handles removing the API key from the model
+ * Sets a flag that will delete the key from vault when the form is submitted
+ */
+ const handleRemoveApiKey = () => {
+ setShouldRemoveApiKey(true);
+ // Keep isApiKeyFromVault true so we can show a proper "will be removed" message
+ // Don't switch to input mode
+ };
+
const isFormValid =
formData.name?.trim() &&
formData.modelId?.trim() &&
formData.baseURL?.trim() &&
formData.provider?.trim();
+ /**
+ * Handles closing the modal and ensures state is properly reset
+ */
+ const handleClose = () => {
+ // Reset reveal state when closing without saving
+ setShowApiKey(false);
+ setShowApiKeyPassword(false);
+ setHasRevealedApiKey(false);
+ setHasModifiedApiKey(false);
+ setShouldRemoveApiKey(false);
+ // Clear any revealed API key data
+ if (isApiKeyFromVault) {
+ setFormData((prev) => ({
+ ...prev,
+ apiKey: '',
+ }));
+ }
+ onClose();
+ };
+
// Filter features to only show Text Completion and Function calling/Tool Use
const userCustomModelFeatures = CUSTOM_LLM_FEATURES.filter(
(feature) => feature.value === 'text' || feature.value === 'tools',
@@ -200,7 +455,7 @@ export function CreateUserCustomModelModal({
open={isOpen}
onOpenChange={(open) => {
if (!open && !isProcessing) {
- onClose();
+ handleClose();
}
}}
>
@@ -327,7 +582,119 @@ export function CreateUserCustomModelModal({
<div className="space-y-2">
<div className="mb-2">
- <Label htmlFor="contextWindow" className="text-base font-normal mr-2 text-[#1E1E1E]">
+ <Label htmlFor="apiKey" className="text-base font-normal mr-2 text-[#1E1E1E]">
+ API Key {isApiKeyFromVault && '(Stored in Vault)'}
+ </Label>
+ <ToolTip
+ text="Optional API key for your custom model. The key will be securely stored in your team vault. Leave empty if your model does not require authentication."
+ classes="w-[240px] text-center"
+ placement="right"
+ >
+ <div
+ dangerouslySetInnerHTML={{ __html: infoIcon }}
+ className="w-4 h-4 text-gray-400"
+ />
+ </ToolTip>
+ </div>
+ {shouldRemoveApiKey ? (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <div className="flex-1 p-3 bg-red-50 border border-red-200 rounded-md">
+ <p className="text-sm text-red-700 font-medium">
+ API key will be removed from vault when you save
+ </p>
+ </div>
+ <CustomButton
+ type="button"
+ variant="secondary"
+ handleClick={() => setShouldRemoveApiKey(false)}
+ className="whitespace-nowrap"
+ label="Undo"
+ />
+ </div>
+ <p className="text-xs text-gray-500">
+ Click &apos;Undo&apos; to cancel the removal, or &apos;
+ {editModel ? 'Update Model' : 'Create Model'}&apos; to confirm and delete the
+ key from vault.
+ </p>
+ </div>
+ ) : isApiKeyFromVault && !showApiKey ? (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Input
+ id="apiKeyName"
+ type="text"
+ value={generateKeyTemplateVar(formData.apiKeyName)}
+ disabled
+ fullWidth
+ className="w-full bg-gray-50"
+ />
+ <CustomButton
+ type="button"
+ variant="secondary"
+ handleClick={handleRevealApiKey}
+ disabled={isLoadingApiKey}
+ className="whitespace-nowrap"
+ addIcon={isLoadingApiKey}
+ Icon={isLoadingApiKey ? <Spinner size="sm" /> : undefined}
+ label={isLoadingApiKey ? 'Loading...' : 'Reveal Key'}
+ />
+ <CustomButton
+ type="button"
+ variant="secondary"
+ handleClick={handleRemoveApiKey}
+ className="whitespace-nowrap bg-red-50 text-red-600 hover:bg-red-100"
+ label="Remove Key"
+ />
+ </div>
+ <p className="text-xs text-gray-500">
+ This API key is stored securely in the vault as a template variable. Click
+ &apos;Reveal Key&apos; to view or update it, or &apos;Remove Key&apos; to delete
+ it.
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ <div className="relative">
+ <Input
+ id="apiKey"
+ type={showApiKeyPassword ? 'text' : 'password'}
+ value={formData.apiKey}
+ onChange={(e) => handleApiKeyChange(e.target.value)}
+ placeholder="sk-..."
+ fullWidth
+ className="w-full pr-10"
+ />
+ <button
+ type="button"
+ onClick={() => setShowApiKeyPassword(!showApiKeyPassword)}
+ className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 focus:outline-none transition-colors"
+ aria-label={showApiKeyPassword ? 'Hide API key' : 'Show API key'}
+ >
+ {showApiKeyPassword ? <EyeOffIcon /> : <EyeIcon />}
+ </button>
+ </div>
+ {isApiKeyFromVault && showApiKey && (
+ <p className="text-xs text-gray-500">
+ Enter a new API key to update the existing one. Changes will only be saved if
+ you modify the key.
+ </p>
+ )}
+ {!isApiKeyFromVault && formData.apiKey && (
+ <p className="text-xs text-gray-500">
+ This key will be securely stored in your team vault.
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+
+ <div className="space-y-2">
+ <div className="mb-2">
+ <Label
+ htmlFor="contextWindow"
+ className="text-base font-normal mr-2 text-[#1E1E1E]"
+ >
Context Window
</Label>
<ToolTip
@@ -357,7 +724,10 @@ export function CreateUserCustomModelModal({
<div className="space-y-2">
<div className="mb-2">
- <Label htmlFor="maxOutputTokens" className="text-base font-normal mr-2 text-[#1E1E1E]">
+ <Label
+ htmlFor="maxOutputTokens"
+ className="text-base font-normal mr-2 text-[#1E1E1E]"
+ >
Maximum Output Tokens
</Label>
<ToolTip
@@ -377,7 +747,9 @@ export function CreateUserCustomModelModal({
min="1024"
max="200000"
step="4"
- value={formData.maxOutputTokens !== undefined ? String(formData.maxOutputTokens) : ''}
+ value={
+ formData.maxOutputTokens !== undefined ? String(formData.maxOutputTokens) : ''
+ }
onChange={(e) => handleNumericInputChange('maxOutputTokens', e.target.value)}
placeholder="4096"
fullWidth
@@ -454,7 +826,7 @@ export function CreateUserCustomModelModal({
<CustomButton
type="button"
variant="secondary"
- handleClick={onClose}
+ handleClick={handleClose}
disabled={isProcessing}
className="flex-1"
label="Cancel"
diff --git a/packages/app/src/react/features/vault/components/user-custom-models.tsx b/packages/app/src/react/features/vault/components/user-custom-models.tsx
index 5f0776ae..35d2e1ab 100644
--- a/packages/app/src/react/features/vault/components/user-custom-models.tsx
+++ b/packages/app/src/react/features/vault/components/user-custom-models.tsx
@@ -80,7 +80,10 @@ export function UserCustomModels({ pageAccess }: { pageAccess: { write: boolean
modelId: editingModel.id,
updatedFields: data,
});
+
successToast('Custom model updated successfully');
+
+ // Close modal - the cache has been updated with complete data including credentials
setEditingModel(undefined);
} catch (error) {
console.error('Error updating user custom model:', error);
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 313f3268..d1fb7fc9 100644
--- a/packages/app/src/react/features/vault/hooks/use-vault.tsx
+++ b/packages/app/src/react/features/vault/hooks/use-vault.tsx
@@ -318,7 +318,21 @@ export function useUpdateUserCustomModel() {
modelId: string;
updatedFields: Partial<UserCustomModel>;
}) => userCustomModelService.updateUserCustomModel(modelId, updatedFields),
- onSuccess: () => {
+ onSuccess: (data, variables) => {
+ // Immediately update the cache with the complete data from server response
+ // This includes credentials with the transformed API key template variable
+ queryClient.setQueryData<UserCustomModel[]>(
+ USER_CUSTOM_MODEL_QUERY_KEYS.USER_CUSTOM_MODELS,
+ (oldData) => {
+ if (!oldData) return oldData;
+ return oldData.map((model) =>
+ model.id === variables.modelId
+ ? data // Use the complete data returned from server
+ : model,
+ );
+ },
+ );
+ // Also invalidate to trigger a background refetch for server sync
queryClient.invalidateQueries({ queryKey: USER_CUSTOM_MODEL_QUERY_KEYS.USER_CUSTOM_MODELS });
},
});
diff --git a/packages/app/src/react/features/vault/types/types.ts b/packages/app/src/react/features/vault/types/types.ts
index 3c460dd8..87ed0fb0 100644
--- a/packages/app/src/react/features/vault/types/types.ts
+++ b/packages/app/src/react/features/vault/types/types.ts
@@ -212,4 +212,19 @@ export interface UserCustomModel {
* List of features supported by the model (e.g., 'text', 'tools')
*/
features?: string[];
+
+ /**
+ * Credentials configuration for the model (optional)
+ */
+ credentials?: {
+ /**
+ * API key name or vault key template variable (e.g., {{KEY(API Key Name)}})
+ */
+ apiKey?: string;
+
+ /**
+ * Indicates if this is a user-provided key stored in vault
+ */
+ isUserKey?: boolean;
+ };
}
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 d49e889a..d8325b01 100644
--- a/packages/app/src/react/features/vault/vault-business-logic.ts
+++ b/packages/app/src/react/features/vault/vault-business-logic.ts
@@ -432,7 +432,7 @@ export const apiKeyService = {
fetchAPIKeys: async (): Promise<{ keys?: ApiKey[]; error?: string }> => {
try {
const response = await fetch(
- '/api/page/vault/keys?excludeScope=global,' + VAULT_SCOPE_AGENT_LLM,
+ '/api/page/vault/keys?excludeScope=global,_hidden,' + VAULT_SCOPE_AGENT_LLM,
{
method: 'GET',
headers: {
@@ -678,13 +678,16 @@ export const userCustomModelService = {
id: value.id || id,
name: value.name,
modelId: value.modelId,
- baseURL: value.baseURL,
+ // Transform baseURL to remove '.forbidden' added by backend for security
+ baseURL: value.baseURL?.replace(/\.forbidden/gi, '') || value.baseURL,
provider: value.provider,
// Check for new field name first, then fall back to old field name
contextWindow: value.contextWindow !== undefined ? value.contextWindow : value.tokens,
- maxOutputTokens: value.maxOutputTokens !== undefined ? value.maxOutputTokens : value.completionTokens,
+ maxOutputTokens:
+ value.maxOutputTokens !== undefined ? value.maxOutputTokens : value.completionTokens,
fallbackLLM: value.fallbackLLM || '', // Provide default empty string for backward compatibility with cached data
features: value.features,
+ credentials: value.credentials, // Include credentials info (apiKey template variable, isUserKey flag)
}));
return models;
@@ -761,17 +764,60 @@ export const userCustomModelService = {
throw new Error(result.error || 'Failed to update user custom model');
}
- // Return the updated model
+ // After updating, fetch the complete model to ensure we have the latest transformed data
+ // This is especially important for credentials which get transformed into template variables
+ const freshModelResponse = await fetch(`/api/page/vault/user-custom-llm/${modelId}`, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (!freshModelResponse.ok) {
+ // If fetch fails, return data from update response as fallback
+ return {
+ id: modelId,
+ name: result.data.name || updatedFields.name || '',
+ modelId: result.data.modelId || updatedFields.modelId || '',
+ baseURL: result.data.baseURL?.replace(/\.forbidden/gi, '') || updatedFields.baseURL || '',
+ provider: result.data.provider || updatedFields.provider || '',
+ contextWindow:
+ result.data.contextWindow !== undefined
+ ? result.data.contextWindow
+ : updatedFields.contextWindow,
+ maxOutputTokens:
+ result.data.maxOutputTokens !== undefined
+ ? result.data.maxOutputTokens
+ : updatedFields.maxOutputTokens,
+ fallbackLLM: result.data.fallbackLLM || updatedFields.fallbackLLM || '',
+ features: result.data.features || updatedFields.features || [],
+ credentials: result.data.credentials,
+ };
+ }
+
+ const freshResult = await freshModelResponse.json();
+ if (!freshResult.success) {
+ throw new Error(freshResult.error || 'Failed to fetch updated model');
+ }
+
+ const freshModel = freshResult.data;
+
+ // Return the complete fresh model with all transformed data including credentials
return {
id: modelId,
- name: result.data.name,
- modelId: updatedFields.modelId || '',
- baseURL: updatedFields.baseURL || '',
- provider: updatedFields.provider || '',
- contextWindow: updatedFields.contextWindow,
- maxOutputTokens: updatedFields.maxOutputTokens,
- fallbackLLM: updatedFields.fallbackLLM || '',
- features: updatedFields.features,
+ name: freshModel.name || '',
+ modelId: freshModel.modelId || '',
+ baseURL: freshModel.baseURL?.replace(/\.forbidden/gi, '') || '',
+ provider: freshModel.provider || '',
+ contextWindow:
+ freshModel.contextWindow !== undefined ? freshModel.contextWindow : freshModel.tokens,
+ maxOutputTokens:
+ freshModel.maxOutputTokens !== undefined
+ ? freshModel.maxOutputTokens
+ : freshModel.completionTokens,
+ fallbackLLM: freshModel.fallbackLLM || '',
+ features: freshModel.features || [],
+ credentials: freshModel.credentials, // Credentials with transformed API key template variable
};
} catch (error) {
console.error('Error updating user custom model:', error);
@@ -779,6 +825,57 @@ export const userCustomModelService = {
}
},
+ /**
+ * Gets a user custom LLM model with decrypted credentials
+ */
+ getUserCustomModelWithCredentials: async (modelId: string): Promise<UserCustomModel> => {
+ try {
+ const response = await fetch(`/api/page/vault/user-custom-llm/${modelId}/with-credentials`, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to get user custom model with credentials');
+ }
+
+ const result = await response.json();
+ if (!result.success) {
+ throw new Error(result.error || 'Failed to get user custom model with credentials');
+ }
+
+ const modelData = result.data;
+
+ // Transform the data to match UserCustomModel format
+ const transformedModel: UserCustomModel = {
+ id: modelData.id,
+ name: modelData.name,
+ modelId: modelData.modelId,
+ // Remove '.forbidden' from baseURL if present
+ baseURL: modelData.baseURL?.replace(/\.forbidden/gi, '') || modelData.baseURL,
+ provider: modelData.provider,
+ contextWindow:
+ modelData.contextWindow !== undefined ? modelData.contextWindow : modelData.tokens,
+ maxOutputTokens:
+ modelData.maxOutputTokens !== undefined
+ ? modelData.maxOutputTokens
+ : modelData.completionTokens,
+ fallbackLLM: modelData.fallbackLLM || '',
+ features: modelData.features || ['text'],
+ credentials: modelData.credentials,
+ };
+
+ return transformedModel;
+ } catch (error) {
+ console.error('Error getting user custom model with credentials:', error);
+ throw new Error(
+ error.error || error.message || 'Failed to get user custom model with credentials',
+ );
+ }
+ },
+
/**
* Deletes a user custom LLM model
*/