-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
feat(webui): add import/edit model page #6050
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
f40d67c
feat(webui): add import/edit model page
mudler aacfecb
Convert to a YAML editor
mudler 287dbe7
Pass by the baseurl
mudler 229b6dc
Fixups
mudler 47a7ce8
Add tests
mudler acf677b
Simplify
mudler 500ee32
Improve visibility of the yaml editor
mudler aa91153
Add test file
mudler bf76708
Make reset work
mudler 28d4f92
Emit error only if we can't delete the model yaml file
mudler File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,228 @@ | ||
package localai | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"os" | ||
"path/filepath" | ||
"strings" | ||
|
||
"github.com/gofiber/fiber/v2" | ||
"github.com/mudler/LocalAI/core/config" | ||
httpUtils "github.com/mudler/LocalAI/core/http/utils" | ||
"github.com/mudler/LocalAI/internal" | ||
"github.com/mudler/LocalAI/pkg/utils" | ||
|
||
"gopkg.in/yaml.v3" | ||
) | ||
|
||
// GetEditModelPage renders the edit model page with current configuration | ||
func GetEditModelPage(cl *config.ModelConfigLoader, appConfig *config.ApplicationConfig) fiber.Handler { | ||
return func(c *fiber.Ctx) error { | ||
modelName := c.Params("name") | ||
if modelName == "" { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Model name is required", | ||
} | ||
return c.Status(400).JSON(response) | ||
} | ||
|
||
modelConfig, exists := cl.GetModelConfig(modelName) | ||
if !exists { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Model configuration not found", | ||
} | ||
return c.Status(404).JSON(response) | ||
} | ||
|
||
configData, err := yaml.Marshal(modelConfig) | ||
if err != nil { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Failed to marshal configuration: " + err.Error(), | ||
} | ||
return c.Status(500).JSON(response) | ||
} | ||
|
||
// Marshal the config to JSON for the template | ||
configJSON, err := json.Marshal(modelConfig) | ||
if err != nil { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Failed to marshal configuration: " + err.Error(), | ||
} | ||
return c.Status(500).JSON(response) | ||
} | ||
|
||
// Render the edit page with the current configuration | ||
templateData := struct { | ||
Title string | ||
ModelName string | ||
Config *config.ModelConfig | ||
ConfigJSON string | ||
ConfigYAML string | ||
BaseURL string | ||
Version string | ||
}{ | ||
Title: "LocalAI - Edit Model " + modelName, | ||
ModelName: modelName, | ||
Config: &modelConfig, | ||
ConfigJSON: string(configJSON), | ||
ConfigYAML: string(configData), | ||
BaseURL: httpUtils.BaseURL(c), | ||
Version: internal.PrintableVersion(), | ||
} | ||
|
||
return c.Render("views/model-editor", templateData) | ||
} | ||
} | ||
|
||
// EditModelEndpoint handles updating existing model configurations | ||
func EditModelEndpoint(cl *config.ModelConfigLoader, appConfig *config.ApplicationConfig) fiber.Handler { | ||
return func(c *fiber.Ctx) error { | ||
modelName := c.Params("name") | ||
if modelName == "" { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Model name is required", | ||
} | ||
return c.Status(400).JSON(response) | ||
} | ||
|
||
// Get the raw body | ||
body := c.Body() | ||
if len(body) == 0 { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Request body is empty", | ||
} | ||
return c.Status(400).JSON(response) | ||
} | ||
|
||
// Check content type to determine how to parse | ||
contentType := string(c.Context().Request.Header.ContentType()) | ||
var req config.ModelConfig | ||
var err error | ||
|
||
if strings.Contains(contentType, "application/json") { | ||
// Parse JSON | ||
if err := json.Unmarshal(body, &req); err != nil { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Failed to parse JSON: " + err.Error(), | ||
} | ||
return c.Status(400).JSON(response) | ||
} | ||
} else if strings.Contains(contentType, "application/x-yaml") || strings.Contains(contentType, "text/yaml") { | ||
// Parse YAML | ||
if err := yaml.Unmarshal(body, &req); err != nil { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Failed to parse YAML: " + err.Error(), | ||
} | ||
return c.Status(400).JSON(response) | ||
} | ||
} else { | ||
// Try to auto-detect format | ||
if strings.TrimSpace(string(body))[0] == '{' { | ||
// Looks like JSON | ||
if err := json.Unmarshal(body, &req); err != nil { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Failed to parse JSON: " + err.Error(), | ||
} | ||
return c.Status(400).JSON(response) | ||
} | ||
} else { | ||
// Assume YAML | ||
if err := yaml.Unmarshal(body, &req); err != nil { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Failed to parse YAML: " + err.Error(), | ||
} | ||
return c.Status(400).JSON(response) | ||
} | ||
} | ||
} | ||
|
||
// Validate required fields | ||
if req.Name == "" { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Name is required", | ||
} | ||
return c.Status(400).JSON(response) | ||
} | ||
|
||
// Load the existing configuration | ||
configPath := filepath.Join(appConfig.SystemState.Model.ModelsPath, modelName+".yaml") | ||
if err := utils.InTrustedRoot(configPath, appConfig.SystemState.Model.ModelsPath); err != nil { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Model configuration not trusted: " + err.Error(), | ||
} | ||
return c.Status(404).JSON(response) | ||
} | ||
|
||
// Set defaults | ||
req.SetDefaults() | ||
|
||
// Validate the configuration | ||
if !req.Validate() { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Validation failed", | ||
Details: []string{"Configuration validation failed. Please check your YAML syntax and required fields."}, | ||
} | ||
return c.Status(400).JSON(response) | ||
} | ||
|
||
// Create the YAML file | ||
yamlData, err := yaml.Marshal(req) | ||
if err != nil { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Failed to marshal configuration: " + err.Error(), | ||
} | ||
return c.Status(500).JSON(response) | ||
} | ||
|
||
// Write to file | ||
if err := os.WriteFile(configPath, yamlData, 0644); err != nil { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Failed to write configuration file: " + err.Error(), | ||
} | ||
return c.Status(500).JSON(response) | ||
} | ||
|
||
// Reload configurations | ||
if err := cl.LoadModelConfigsFromPath(appConfig.SystemState.Model.ModelsPath); err != nil { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Failed to reload configurations: " + err.Error(), | ||
} | ||
return c.Status(500).JSON(response) | ||
} | ||
|
||
// Preload the model | ||
if err := cl.Preload(appConfig.SystemState.Model.ModelsPath); err != nil { | ||
response := ModelResponse{ | ||
Success: false, | ||
Error: "Failed to preload model: " + err.Error(), | ||
} | ||
return c.Status(500).JSON(response) | ||
} | ||
|
||
// Return success response | ||
response := ModelResponse{ | ||
Success: true, | ||
Message: fmt.Sprintf("Model '%s' updated successfully", modelName), | ||
Filename: configPath, | ||
Config: req, | ||
} | ||
return c.JSON(response) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
package localai_test | ||
|
||
import ( | ||
"bytes" | ||
"io" | ||
"net/http/httptest" | ||
"os" | ||
"path/filepath" | ||
|
||
"github.com/gofiber/fiber/v2" | ||
"github.com/mudler/LocalAI/core/config" | ||
. "github.com/mudler/LocalAI/core/http/endpoints/localai" | ||
"github.com/mudler/LocalAI/pkg/system" | ||
. "github.com/onsi/ginkgo/v2" | ||
. "github.com/onsi/gomega" | ||
) | ||
|
||
var _ = Describe("Edit Model test", func() { | ||
|
||
var tempDir string | ||
BeforeEach(func() { | ||
var err error | ||
tempDir, err = os.MkdirTemp("", "localai-test") | ||
Expect(err).ToNot(HaveOccurred()) | ||
}) | ||
AfterEach(func() { | ||
os.RemoveAll(tempDir) | ||
}) | ||
|
||
Context("Edit Model endpoint", func() { | ||
It("should edit a model", func() { | ||
systemState, err := system.GetSystemState( | ||
system.WithModelPath(filepath.Join(tempDir)), | ||
) | ||
Expect(err).ToNot(HaveOccurred()) | ||
|
||
applicationConfig := config.NewApplicationConfig( | ||
config.WithSystemState(systemState), | ||
) | ||
//modelLoader := model.NewModelLoader(systemState, true) | ||
modelConfigLoader := config.NewModelConfigLoader(systemState.Model.ModelsPath) | ||
|
||
// Define Fiber app. | ||
app := fiber.New() | ||
app.Put("/import-model", ImportModelEndpoint(modelConfigLoader, applicationConfig)) | ||
|
||
requestBody := bytes.NewBufferString(`{"name": "foo", "backend": "foo", "model": "foo"}`) | ||
|
||
req := httptest.NewRequest("PUT", "/import-model", requestBody) | ||
resp, err := app.Test(req, 5000) | ||
Expect(err).ToNot(HaveOccurred()) | ||
|
||
body, err := io.ReadAll(resp.Body) | ||
defer resp.Body.Close() | ||
Expect(err).ToNot(HaveOccurred()) | ||
Expect(string(body)).To(ContainSubstring("Model configuration created successfully")) | ||
Expect(resp.StatusCode).To(Equal(fiber.StatusOK)) | ||
|
||
app.Get("/edit-model/:name", EditModelEndpoint(modelConfigLoader, applicationConfig)) | ||
requestBody = bytes.NewBufferString(`{"name": "foo", "parameters": { "model": "foo"}}`) | ||
|
||
req = httptest.NewRequest("GET", "/edit-model/foo", requestBody) | ||
resp, _ = app.Test(req, 1) | ||
|
||
body, err = io.ReadAll(resp.Body) | ||
defer resp.Body.Close() | ||
Expect(err).ToNot(HaveOccurred()) | ||
Expect(string(body)).To(ContainSubstring(`"model":"foo"`)) | ||
Expect(resp.StatusCode).To(Equal(fiber.StatusOK)) | ||
}) | ||
}) | ||
}) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.