diff --git a/core/config/model_config.go b/core/config/model_config.go index 952398d5bb58..d56d92fac585 100644 --- a/core/config/model_config.go +++ b/core/config/model_config.go @@ -77,6 +77,7 @@ type ModelConfig struct { Description string `yaml:"description,omitempty" json:"description,omitempty"` Usage string `yaml:"usage,omitempty" json:"usage,omitempty"` + Disabled *bool `yaml:"disabled,omitempty" json:"disabled,omitempty"` Options []string `yaml:"options,omitempty" json:"options,omitempty"` Overrides []string `yaml:"overrides,omitempty" json:"overrides,omitempty"` @@ -548,6 +549,11 @@ func (c *ModelConfig) GetModelTemplate() string { return c.modelTemplate } +// IsDisabled returns true if the model is disabled +func (c *ModelConfig) IsDisabled() bool { + return c.Disabled != nil && *c.Disabled +} + type ModelConfigUsecase int const ( diff --git a/core/http/endpoints/localai/toggle_model.go b/core/http/endpoints/localai/toggle_model.go new file mode 100644 index 000000000000..3d673d7ca811 --- /dev/null +++ b/core/http/endpoints/localai/toggle_model.go @@ -0,0 +1,148 @@ +package localai + +import ( + "fmt" + "net/http" + "net/url" + "os" + + "github.com/labstack/echo/v4" + "github.com/mudler/LocalAI/core/config" + "github.com/mudler/LocalAI/pkg/model" + "github.com/mudler/LocalAI/pkg/utils" + + "gopkg.in/yaml.v3" +) + +// ToggleModelEndpoint handles enabling or disabling a model from being loaded on demand. +// When disabled, the model remains in the collection but will not be loaded when requested. +// +// @Summary Toggle model enabled/disabled status +// @Description Enable or disable a model from being loaded on demand. Disabled models remain installed but cannot be loaded. +// @Tags config +// @Param name path string true "Model name" +// @Param action path string true "Action: 'enable' or 'disable'" +// @Success 200 {object} ModelResponse +// @Failure 400 {object} ModelResponse +// @Failure 404 {object} ModelResponse +// @Failure 500 {object} ModelResponse +// @Router /api/models/{name}/{action} [put] +func ToggleStateModelEndpoint(cl *config.ModelConfigLoader, ml *model.ModelLoader, appConfig *config.ApplicationConfig) echo.HandlerFunc { + return func(c echo.Context) error { + modelName := c.Param("name") + if decoded, err := url.PathUnescape(modelName); err == nil { + modelName = decoded + } + if modelName == "" { + return c.JSON(http.StatusBadRequest, ModelResponse{ + Success: false, + Error: "Model name is required", + }) + } + + action := c.Param("action") + if action != "enable" && action != "disable" { + return c.JSON(http.StatusBadRequest, ModelResponse{ + Success: false, + Error: "Action must be 'enable' or 'disable'", + }) + } + + // Get existing model config + modelConfig, exists := cl.GetModelConfig(modelName) + if !exists { + return c.JSON(http.StatusNotFound, ModelResponse{ + Success: false, + Error: "Model configuration not found", + }) + } + + // Get the config file path + configPath := modelConfig.GetModelConfigFile() + if configPath == "" { + return c.JSON(http.StatusNotFound, ModelResponse{ + Success: false, + Error: "Model configuration file not found", + }) + } + + // Verify the path is trusted + if err := utils.VerifyPath(configPath, appConfig.SystemState.Model.ModelsPath); err != nil { + return c.JSON(http.StatusForbidden, ModelResponse{ + Success: false, + Error: "Model configuration not trusted: " + err.Error(), + }) + } + + // Read the existing config file + configData, err := os.ReadFile(configPath) + if err != nil { + return c.JSON(http.StatusInternalServerError, ModelResponse{ + Success: false, + Error: "Failed to read configuration file: " + err.Error(), + }) + } + + // Parse the YAML config as a generic map to preserve all fields + var configMap map[string]interface{} + if err := yaml.Unmarshal(configData, &configMap); err != nil { + return c.JSON(http.StatusInternalServerError, ModelResponse{ + Success: false, + Error: "Failed to parse configuration file: " + err.Error(), + }) + } + + // Update the disabled field + disabled := action == "disable" + if disabled { + configMap["disabled"] = true + } else { + // Remove the disabled key entirely when enabling (clean YAML) + delete(configMap, "disabled") + } + + // Marshal back to YAML + updatedData, err := yaml.Marshal(configMap) + if err != nil { + return c.JSON(http.StatusInternalServerError, ModelResponse{ + Success: false, + Error: "Failed to serialize configuration: " + err.Error(), + }) + } + + // Write updated config back to file + if err := os.WriteFile(configPath, updatedData, 0644); err != nil { + return c.JSON(http.StatusInternalServerError, ModelResponse{ + Success: false, + Error: "Failed to write configuration file: " + err.Error(), + }) + } + + // Reload model configurations from disk + if err := cl.LoadModelConfigsFromPath(appConfig.SystemState.Model.ModelsPath, appConfig.ToConfigLoaderOptions()...); err != nil { + return c.JSON(http.StatusInternalServerError, ModelResponse{ + Success: false, + Error: "Failed to reload configurations: " + err.Error(), + }) + } + + // If disabling, also shutdown the model if it's currently running + if disabled { + if err := ml.ShutdownModel(modelName); err != nil { + // Log but don't fail - the config was saved successfully + fmt.Printf("Warning: Failed to shutdown model '%s' during disable: %v\n", modelName, err) + } + } + + msg := fmt.Sprintf("Model '%s' has been %sd successfully.", modelName, action) + if disabled { + msg += " The model will not be loaded on demand until re-enabled." + } + + return c.JSON(http.StatusOK, ModelResponse{ + Success: true, + Message: msg, + Filename: configPath, + }) + } +} diff --git a/core/http/middleware/request.go b/core/http/middleware/request.go index 4fc93d553815..8e03ad956c32 100644 --- a/core/http/middleware/request.go +++ b/core/http/middleware/request.go @@ -167,6 +167,17 @@ func (re *RequestExtractor) SetModelAndConfig(initializer func() schema.LocalAIR } } + // Check if the model is disabled + if cfg != nil && cfg.IsDisabled() { + return c.JSON(http.StatusForbidden, schema.ErrorResponse{ + Error: &schema.APIError{ + Message: fmt.Sprintf("model %q is disabled and cannot be loaded. Enable it via the System page or API to use it.", modelName), + Code: http.StatusForbidden, + Type: "model_disabled", + }, + }) + } + c.Set(CONTEXT_LOCALS_KEY_LOCALAI_REQUEST, input) c.Set(CONTEXT_LOCALS_KEY_MODEL_CONFIG, cfg) diff --git a/core/http/react-ui/src/pages/Manage.jsx b/core/http/react-ui/src/pages/Manage.jsx index dab3ccc132ea..4c301dfa73f7 100644 --- a/core/http/react-ui/src/pages/Manage.jsx +++ b/core/http/react-ui/src/pages/Manage.jsx @@ -24,6 +24,7 @@ export default function Manage() { const [reinstallingBackends, setReinstallingBackends] = useState(new Set()) const [confirmDialog, setConfirmDialog] = useState(null) const [distributedMode, setDistributedMode] = useState(false) + const [togglingModels, setTogglingModels] = useState(new Set()) const handleTabChange = (tab) => { setActiveTab(tab) @@ -99,6 +100,28 @@ export default function Manage() { }) } + const handleToggleModel = async (modelId, currentlyDisabled) => { + const action = currentlyDisabled ? 'enable' : 'disable' + setTogglingModels(prev => new Set(prev).add(modelId)) + try { + await modelsApi.toggleState(modelId, action) + addToast(`Model ${modelId} ${action}d`, 'success') + refetchModels() + if (!currentlyDisabled) { + // Model was just disabled, refresh loaded models since it may have been shut down + setTimeout(fetchLoadedModels, 500) + } + } catch (err) { + addToast(`Failed to ${action} model: ${err.message}`, 'error') + } finally { + setTogglingModels(prev => { + const next = new Set(prev) + next.delete(modelId) + return next + }) + } + } + const handleReload = async () => { setReloading(true) try { @@ -219,11 +242,11 @@ export default function Manage() { {models.map(model => ( - +
- - + + {model.id} - {loadedModelIds.has(model.id) ? ( + {model.disabled ? ( + + Disabled + + ) : loadedModelIds.has(model.id) ? ( Running @@ -265,7 +292,8 @@ export default function Manage() {
-
+
+ {/* Stop button - shown when model is loaded */} {loadedModelIds.has(model.id) && ( )} + {/* Toggle switch for enabling/disabling model loading on demand */} +