Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

wip: custom models

Dane Schneiderf2d5f1f29251
diff --git a/app/cli/api/methods.go b/app/cli/api/methods.go
index 6719abe8..1550cb90 100644
--- a/app/cli/api/methods.go
+++ b/app/cli/api/methods.go
@@ -2109,33 +2109,6 @@ func (a *Api) ListCustomModels() ([]*shared.CustomModel, *shared.ApiError) {
return models, nil
}
-func (a *Api) DeleteCustomModel(modelId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/custom_models/%s", GetApiHost(), modelId)
- req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
- if err != nil {
- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}
- }
-
- resp, err := authenticatedFastClient.Do(req)
- if err != nil {
- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
- }
- defer resp.Body.Close()
-
- if resp.StatusCode >= 400 {
- errorBody, _ := io.ReadAll(resp.Body)
-
- apiErr := HandleApiError(resp, errorBody)
- authRefreshed, apiErr := refreshAuthIfNeeded(apiErr)
- if authRefreshed {
- return a.DeleteCustomModel(modelId)
- }
- return apiErr
- }
-
- return nil
-}
-
func (a *Api) ListCustomProviders() ([]*shared.CustomProvider, *shared.ApiError) {
serverUrl := fmt.Sprintf("%s/custom_providers", GetApiHost())
resp, err := authenticatedFastClient.Get(serverUrl)
@@ -2163,32 +2136,6 @@ func (a *Api) ListCustomProviders() ([]*shared.CustomProvider, *shared.ApiError)
return providers, nil
}
-func (a *Api) DeleteCustomProvider(providerId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/custom_providers/%s", GetApiHost(), providerId)
- req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
- if err != nil {
- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}
- }
-
- resp, err := authenticatedFastClient.Do(req)
- if err != nil {
- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
- }
- defer resp.Body.Close()
-
- if resp.StatusCode >= 400 {
- errorBody, _ := io.ReadAll(resp.Body)
- apiErr := HandleApiError(resp, errorBody)
- authRefreshed, apiErr := refreshAuthIfNeeded(apiErr)
- if authRefreshed {
- return a.DeleteCustomProvider(providerId)
- }
- return apiErr
- }
-
- return nil
-}
-
func (a *Api) ListModelPacks() ([]*shared.ModelPack, *shared.ApiError) {
serverUrl := fmt.Sprintf("%s/model_sets", GetApiHost())
@@ -2219,34 +2166,6 @@ func (a *Api) ListModelPacks() ([]*shared.ModelPack, *shared.ApiError) {
}
-func (a *Api) DeleteModelPack(setId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/model_sets/%s", GetApiHost(), setId)
-
- req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
- if err != nil {
- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}
- }
-
- resp, err := authenticatedFastClient.Do(req)
- if err != nil {
- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
- }
- defer resp.Body.Close()
-
- if resp.StatusCode >= 400 {
- errorBody, _ := io.ReadAll(resp.Body)
-
- apiErr := HandleApiError(resp, errorBody)
- authRefreshed, apiErr := refreshAuthIfNeeded(apiErr)
- if authRefreshed {
- return a.DeleteModelPack(setId)
- }
- return apiErr
- }
-
- return nil
-}
-
func (a *Api) GetCreditsTransactions(pageSize, pageNum int, req shared.CreditsLogRequest) (*shared.CreditsLogResponse, *shared.ApiError) {
serverUrl := fmt.Sprintf("%s/billing/credits_transactions?size=%d&page=%d", GetApiHost(), pageSize, pageNum)
diff --git a/app/cli/cmd/model_packs.go b/app/cli/cmd/model_packs.go
index db03a457..27c0f591 100644
--- a/app/cli/cmd/model_packs.go
+++ b/app/cli/cmd/model_packs.go
@@ -6,7 +6,6 @@ import (
"plandex-cli/api"
"plandex-cli/auth"
"plandex-cli/term"
- "strconv"
shared "plandex-shared"
@@ -26,21 +25,20 @@ var modelPacksCmd = &cobra.Command{
var createModelPackCmd = &cobra.Command{
Use: "create",
Short: "Create a model pack",
- Run: customModelsCreateNotImplemented,
+ Run: customModelsNotImplemented,
}
var deleteModelPackCmd = &cobra.Command{
- Use: "delete [name-or-index]",
+ Use: "delete",
Aliases: []string{"rm"},
Short: "Delete a model pack by name or index",
- Args: cobra.MaximumNArgs(1),
- Run: deleteModelPack,
+ Run: customModelsNotImplemented,
}
var updateModelPackCmd = &cobra.Command{
Use: "update",
Short: "Update a model pack by name",
- Run: customModelsCreateNotImplemented,
+ Run: customModelsNotImplemented,
}
var showModelPackCmd = &cobra.Command{
@@ -60,81 +58,6 @@ func init() {
modelPacksCmd.Flags().BoolVarP(&allProperties, "all", "a", false, "Show all properties")
}
-func deleteModelPack(cmd *cobra.Command, args []string) {
- auth.MustResolveAuthWithOrg()
-
- term.StartSpinner("")
- modelPacks, err := api.Client.ListModelPacks()
- term.StopSpinner()
-
- if err != nil {
- term.OutputErrorAndExit("Error fetching model packs: %v", err)
- return
- }
-
- if len(modelPacks) == 0 {
- fmt.Println("πŸ€·β€β™‚οΈ No custom model packs")
- return
- }
-
- var setToDelete *shared.ModelPack
-
- if len(args) == 1 {
- input := args[0]
- // Try to parse input as index
- index, err := strconv.Atoi(input)
- if err == nil && index > 0 && index <= len(modelPacks) {
- setToDelete = modelPacks[index-1]
- } else {
- // Search by name
- for _, s := range modelPacks {
- if s.Name == input {
- setToDelete = s
- break
- }
- }
- }
- }
-
- if setToDelete == nil {
- opts := make([]string, len(modelPacks))
- for i, mp := range modelPacks {
- opts[i] = mp.Name
- }
-
- selected, err := term.SelectFromList("Select a custom model pack:", opts)
-
- if err != nil {
- term.OutputErrorAndExit("Error selecting model pack: %v", err)
- }
-
- var selectedIndex int
- for i, opt := range opts {
- if opt == selected {
- selectedIndex = i
- break
- }
- }
-
- setToDelete = modelPacks[selectedIndex]
- }
-
- term.StartSpinner("")
- err = api.Client.DeleteModelPack(setToDelete.Id)
- term.StopSpinner()
-
- if err != nil {
- term.OutputErrorAndExit("Error deleting model pack: %v", err)
- return
- }
-
- fmt.Printf("βœ… Deleted model pack %s\n", color.New(color.Bold, term.ColorHiCyan).Sprint(setToDelete.Name))
-
- fmt.Println()
-
- term.PrintCmds("", "model-packs", "model-packs --custom", "model-packs create")
-}
-
func listModelPacks(cmd *cobra.Command, args []string) {
auth.MustResolveAuthWithOrg()
diff --git a/app/cli/cmd/model_providers.go b/app/cli/cmd/model_providers.go
index af0ef46a..c89b4c5e 100644
--- a/app/cli/cmd/model_providers.go
+++ b/app/cli/cmd/model_providers.go
@@ -36,14 +36,14 @@ var addProviderCmd = &cobra.Command{
Use: "add",
Aliases: []string{"create"},
Short: "Add a custom model provider",
- Run: customModelsCreateNotImplemented,
+ Run: customModelsNotImplemented,
}
var updateProviderCmd = &cobra.Command{
Use: "update",
Aliases: []string{"edit"},
Short: "Update a custom model provider",
- Run: customModelsCreateNotImplemented,
+ Run: customModelsNotImplemented,
}
func init() {
diff --git a/app/cli/cmd/models.go b/app/cli/cmd/models.go
index e45344e9..cf45c628 100644
--- a/app/cli/cmd/models.go
+++ b/app/cli/cmd/models.go
@@ -11,6 +11,7 @@ import (
"plandex-cli/api"
"plandex-cli/auth"
+ "plandex-cli/fs"
"plandex-cli/lib"
"plandex-cli/schema"
"plandex-cli/term"
@@ -24,10 +25,9 @@ import (
)
var customModelsOnly bool
-
var allProperties bool
-var genTemplatePath string
-var updateModels bool
+var saveCustomModels bool
+var customModelsPath string
func init() {
RootCmd.AddCommand(modelsCmd)
@@ -41,8 +41,8 @@ func init() {
modelsCmd.AddCommand(deleteCustomModelCmd)
modelsCmd.AddCommand(defaultModelsCmd)
- importCustomModelCmd.Flags().StringVarP(&genTemplatePath, "generate", "g", "", "Generate a template JSON file")
- importCustomModelCmd.Flags().BoolVarP(&updateModels, "update", "u", false, "Update existing models")
+ importCustomModelCmd.Flags().BoolVar(&saveCustomModels, "save", false, "Save custom models")
+ importCustomModelCmd.Flags().StringVar(&customModelsPath, "path", "", "Path to custom models file")
listAvailableModelsCmd.Flags().BoolVarP(&customModelsOnly, "custom", "c", false, "List custom models only")
}
@@ -67,24 +67,23 @@ var listAvailableModelsCmd = &cobra.Command{
}
var importCustomModelCmd = &cobra.Command{
- Use: "import [json-file]",
- Short: "Create or update custom models, providers, and model packs from a JSON file",
+ Use: "custom",
+ Short: "Manage custom models, providers, and model packs",
Run: importCustomModels,
- Args: cobra.MaximumNArgs(1),
}
var addCustomModelCmd = &cobra.Command{
Use: "add",
Aliases: []string{"create"},
Short: "Add a custom model",
- Run: customModelsCreateNotImplemented,
+ Run: customModelsNotImplemented,
}
var updateCustomModelCmd = &cobra.Command{
Use: "update",
Aliases: []string{"edit"},
Short: "Update a custom model",
- Run: customModelsUpdateNotImplemented,
+ Run: customModelsNotImplemented,
}
var deleteCustomModelCmd = &cobra.Command{
@@ -92,14 +91,12 @@ var deleteCustomModelCmd = &cobra.Command{
Aliases: []string{"remove", "delete"},
Short: "Remove a custom model",
Args: cobra.MaximumNArgs(1),
- Run: deleteCustomModel,
+ Run: customModelsNotImplemented,
}
func importCustomModels(cmd *cobra.Command, args []string) {
auth.MustResolveAuthWithOrg()
- var jsonFile string
-
term.StartSpinner("")
errCh := make(chan *shared.ApiError, 3)
@@ -169,6 +166,23 @@ func importCustomModels(cmd *cobra.Command, args []string) {
existsById[modelPack.Name] = true
}
+ usingDefaultPath := false
+ if customModelsPath == "" {
+ usingDefaultPath = true
+ customModelsPath = filepath.Join(fs.HomePlandexDir, "custom-models.json")
+ }
+
+ exists := false
+ _, err := os.Stat(customModelsPath)
+ if err == nil {
+ exists = true
+ } else if os.IsNotExist(err) {
+ exists = false
+ } else {
+ term.OutputErrorAndExit("Error checking custom models file: %v", err)
+ return
+ }
+
if len(args) == 1 {
jsonFile = args[0]
} else if updateModels {
@@ -287,6 +301,13 @@ func importCustomModels(cmd *cobra.Command, args []string) {
}
}
+ if saveCustomModels {
+ if !exists {
+ term.OutputErrorAndExit("File not found: %s", customModelsPath)
+ return
+ }
+ }
+
term.StartSpinner("")
// Import the JSON file
jsonData, err := os.ReadFile(jsonFile)
@@ -502,83 +523,6 @@ func listAvailableModels(cmd *cobra.Command, args []string) {
}
}
-func deleteCustomModel(cmd *cobra.Command, args []string) {
- auth.MustResolveAuthWithOrg()
-
- term.StartSpinner("")
- models, apiErr := api.Client.ListCustomModels()
- term.StopSpinner()
-
- if apiErr != nil {
- term.OutputErrorAndExit("Error fetching custom models: %v", apiErr)
- return
- }
-
- if len(models) == 0 {
- fmt.Println("πŸ€·β€β™‚οΈ No custom models")
- fmt.Println()
- term.PrintCmds("", "models add")
- return
- }
-
- var modelToDelete *shared.CustomModel
-
- if len(args) == 1 {
- input := args[0]
- // Try to parse input as index
- index, err := strconv.Atoi(input)
- if err == nil && index > 0 && index <= len(models) {
- modelToDelete = models[index-1]
- } else {
- // Search by name
- for _, m := range models {
- if string(m.ModelId) == input {
- modelToDelete = m
- break
- }
- }
- }
- }
-
- if modelToDelete == nil {
- opts := make([]string, len(models))
- for i, model := range models {
- opts[i] = string(model.ModelId)
- }
-
- selected, err := term.SelectFromList("Select model to delete:", opts)
-
- if err != nil {
- term.OutputErrorAndExit("Error selecting model: %v", err)
- return
- }
-
- var selectedIndex int
- for i, opt := range opts {
- if opt == selected {
- selectedIndex = i
- break
- }
- }
-
- modelToDelete = models[selectedIndex]
- }
-
- term.StartSpinner("")
- apiErr = api.Client.DeleteCustomModel(modelToDelete.Id)
- term.StopSpinner()
-
- if apiErr != nil {
- term.OutputErrorAndExit("Error deleting custom model: %v", apiErr)
- return
- }
-
- fmt.Printf("βœ… Deleted custom model %s\n", color.New(color.Bold, term.ColorHiCyan).Sprint(string(modelToDelete.ModelId)))
-
- fmt.Println()
- term.PrintCmds("", "models available", "models add")
-}
-
func renderSettings(settings *shared.PlanSettings, allProperties bool) {
modelPack := settings.ModelPack
@@ -739,17 +683,10 @@ func renderModelPack(modelPack *shared.ModelPack, allProperties bool) {
}
-func customModelsCreateNotImplemented(cmd *cobra.Command, args []string) {
- color.New(color.Bold, color.FgHiRed).Println("⛔️ Not implemented")
- fmt.Println()
- fmt.Println("Use " + color.New(color.BgCyan, color.FgHiWhite).Sprint(" plandex models import ") + " to add custom models, providers, and model packs with a JSON file")
- os.Exit(1)
-}
-
-func customModelsUpdateNotImplemented(cmd *cobra.Command, args []string) {
+func customModelsNotImplemented(cmd *cobra.Command, args []string) {
color.New(color.Bold, color.FgHiRed).Println("⛔️ Not implemented")
fmt.Println()
- fmt.Println("Use " + color.New(color.BgCyan, color.FgHiWhite).Sprint(" plandex models import --update ") + " to update existing custom models, providers, and model packs with a JSON file")
+ fmt.Println("Use " + color.New(color.BgCyan, color.FgHiWhite).Sprint(" plandex models custom ") + " to manage custom models, providers, and model packs")
os.Exit(1)
}
diff --git a/app/cli/types/api.go b/app/cli/types/api.go
index 331a9f67..90c0bcdc 100644
--- a/app/cli/types/api.go
+++ b/app/cli/types/api.go
@@ -105,13 +105,10 @@ type ApiClient interface {
CreateCustomModels(input *shared.ModelsInput) *shared.ApiError
ListCustomModels() ([]*shared.CustomModel, *shared.ApiError)
- DeleteCustomModel(modelId string) *shared.ApiError
ListCustomProviders() ([]*shared.CustomProvider, *shared.ApiError)
- DeleteCustomProvider(providerId string) *shared.ApiError
ListModelPacks() ([]*shared.ModelPack, *shared.ApiError)
- DeleteModelPack(setId string) *shared.ApiError
GetCreditsTransactions(pageSize, pageNum int, req shared.CreditsLogRequest) (*shared.CreditsLogResponse, *shared.ApiError)
GetCreditsSummary(req shared.CreditsLogRequest) (*shared.CreditsSummaryResponse, *shared.ApiError)
diff --git a/app/server/db/models.go b/app/server/db/models.go
index 1a520516..09c75fbf 100644
--- a/app/server/db/models.go
+++ b/app/server/db/models.go
@@ -112,9 +112,15 @@ func GetCustomModel(orgId, id string) (*CustomModel, error) {
return &model, nil
}
-func DeleteCustomModel(orgId, id string) error {
- _, err := Conn.Exec(`DELETE FROM custom_models WHERE org_id = $1 AND id = $2`, orgId, id)
- return err
+func DeleteCustomModels(tx *sqlx.Tx, orgId string, ids []string) error {
+ if tx == nil {
+ return fmt.Errorf("tx is nil")
+ }
+ _, err := tx.Exec(`DELETE FROM custom_models WHERE org_id = $1 AND id = ANY($2)`, orgId, pq.Array(ids))
+ if err != nil {
+ return fmt.Errorf("error deleting custom models: %v", err)
+ }
+ return nil
}
func UpsertCustomProvider(tx *sqlx.Tx, p *CustomProvider) error {
@@ -174,9 +180,15 @@ func ListCustomProvidersForNames(orgId string, names []string) ([]*CustomProvide
return providers, err
}
-func DeleteCustomProvider(orgId, id string) error {
- _, err := Conn.Exec(`DELETE FROM custom_providers WHERE org_id = $1 AND id = $2`, orgId, id)
- return err
+func DeleteCustomProviders(tx *sqlx.Tx, orgId string, ids []string) error {
+ if tx == nil {
+ return fmt.Errorf("tx is nil")
+ }
+ _, err := tx.Exec(`DELETE FROM custom_providers WHERE org_id = $1 AND id = ANY($2)`, orgId, pq.Array(ids))
+ if err != nil {
+ return fmt.Errorf("error deleting custom providers: %v", err)
+ }
+ return nil
}
func UpsertModelPack(tx *sqlx.Tx, mp *ModelPack) error {
@@ -247,9 +259,11 @@ func ListModelPacksForNames(orgId string, names []string) ([]*ModelPack, error)
return modelPacks, err
}
-func DeleteModelPack(setId string) error {
- query := `DELETE FROM model_sets WHERE id = $1`
- _, err := Conn.Exec(query, setId)
+func DeleteModelPacks(tx *sqlx.Tx, orgId string, ids []string) error {
+ if tx == nil {
+ return fmt.Errorf("tx is nil")
+ }
+ _, err := tx.Exec(`DELETE FROM model_sets WHERE org_id = $1 AND id = ANY($2)`, orgId, pq.Array(ids))
if err != nil {
return fmt.Errorf("error deleting model pack: %v", err)
diff --git a/app/server/handlers/models.go b/app/server/handlers/models.go
index 316575b0..8b2e6eac 100644
--- a/app/server/handlers/models.go
+++ b/app/server/handlers/models.go
@@ -10,7 +10,6 @@ import (
shared "plandex-shared"
- "github.com/davecgh/go-spew/spew"
"github.com/gorilla/mux"
"github.com/jmoiron/sqlx"
)
@@ -88,8 +87,8 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {
}
}
- var customModelIds = make(map[shared.ModelId]bool)
- var customProviderNames = make(map[string]bool)
+ var existingCustomModelIds = make(map[shared.ModelId]bool)
+ var existingCustomProviderNames = make(map[string]bool)
customModels, err := db.ListCustomModels(auth.OrgId)
if err != nil {
@@ -98,45 +97,66 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {
return
}
- for _, model := range customModels {
- customModelIds[model.ModelId] = true
+ customModelPacks, err := db.ListModelPacks(auth.OrgId)
+ if err != nil {
+ log.Printf("Error fetching custom model packs: %v\n", err)
+ http.Error(w, "Failed to create custom model: "+err.Error(), http.StatusInternalServerError)
+ return
}
+ var customProviders []*db.CustomProvider
+
if os.Getenv("IS_CLOUD") == "" {
- customProviders, err := db.ListCustomProviders(auth.OrgId)
+ customProviders, err = db.ListCustomProviders(auth.OrgId)
if err != nil {
log.Printf("Error fetching custom providers: %v\n", err)
http.Error(w, "Failed to create custom model: "+err.Error(), http.StatusInternalServerError)
return
}
+ }
- for _, provider := range customProviders {
- customProviderNames[provider.Name] = true
- }
+ for _, model := range customModels {
+ existingCustomModelIds[model.ModelId] = true
+ }
+
+ for _, provider := range customProviders {
+ existingCustomProviderNames[provider.Name] = true
+ }
+
+ willUpsertModelIds := make(map[string]bool)
+ willUpsertProviderNames := make(map[string]bool)
+ willUpsertModelPackNames := make(map[string]bool)
+
+ for _, model := range modelsInput.CustomModels {
+ willUpsertModelIds[string(model.ModelId)] = true
+ }
+
+ for _, provider := range modelsInput.CustomProviders {
+ willUpsertProviderNames[provider.Name] = true
+ }
+
+ for _, modelPack := range modelsInput.CustomModelPacks {
+ willUpsertModelPackNames[modelPack.Name] = true
}
var toUpsertCustomModels []*db.CustomModel
var toUpsertCustomProviders []*db.CustomProvider
var toUpsertModelPacks []*db.ModelPack
- willCreateModelIds := make(map[string]bool)
- willCreateProviderNames := make(map[string]bool)
-
for _, provider := range modelsInput.CustomProviders {
dbProvider := db.CustomProviderFromApi(provider)
dbProvider.Id = provider.Id
dbProvider.OrgId = auth.OrgId
toUpsertCustomProviders = append(toUpsertCustomProviders, dbProvider)
- willCreateProviderNames[provider.Name] = true
}
for _, model := range modelsInput.CustomModels {
// ensure that providers are either built-in, being created, or already exist
for _, provider := range model.Providers {
if provider.Provider == shared.ModelProviderCustom {
- _, exists := customProviderNames[*provider.CustomProvider]
- _, creating := willCreateProviderNames[*provider.CustomProvider]
+ _, exists := existingCustomProviderNames[*provider.CustomProvider]
+ _, creating := willUpsertProviderNames[*provider.CustomProvider]
if !exists && !creating {
msg := fmt.Sprintf("'%s' is not a custom model provider that exists or is being created", *provider.CustomProvider)
log.Println(msg)
@@ -159,21 +179,15 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {
dbModel.OrgId = auth.OrgId
toUpsertCustomModels = append(toUpsertCustomModels, dbModel)
- willCreateModelIds[string(model.ModelId)] = true
}
- log.Println(spew.Sdump(map[string]interface{}{
- "customModelIds": customModelIds,
- "willCreateModelIds": willCreateModelIds,
- }))
-
for _, modelPack := range modelsInput.CustomModelPacks {
// ensure that all models are either built-in, being created, or already exist
allModelIds := modelPack.AllModelIds()
for _, modelId := range allModelIds {
- _, exists := customModelIds[modelId]
- _, creating := willCreateModelIds[string(modelId)]
+ _, exists := existingCustomModelIds[modelId]
+ _, creating := willUpsertModelIds[string(modelId)]
_, builtIn := shared.BuiltInBaseModelsById[modelId]
if !exists && !creating && !builtIn {
@@ -192,6 +206,28 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {
toUpsertModelPacks = append(toUpsertModelPacks, dbMp)
}
+ toDeleteCustomModelIds := []string{}
+ toDeleteCustomProviderIds := []string{}
+ toDeleteModelPackIds := []string{}
+
+ for _, model := range customModels {
+ if _, exists := willUpsertModelIds[string(model.ModelId)]; !exists {
+ toDeleteCustomModelIds = append(toDeleteCustomModelIds, model.Id)
+ }
+ }
+
+ for _, provider := range customProviders {
+ if _, exists := willUpsertProviderNames[provider.Name]; !exists {
+ toDeleteCustomProviderIds = append(toDeleteCustomProviderIds, provider.Id)
+ }
+ }
+
+ for _, modelPack := range customModelPacks {
+ if _, exists := willUpsertModelPackNames[modelPack.Name]; !exists {
+ toDeleteModelPackIds = append(toDeleteModelPackIds, modelPack.Id)
+ }
+ }
+
err = db.WithTx(r.Context(), "create custom models/providers/model packs", func(tx *sqlx.Tx) error {
for _, model := range toUpsertCustomModels {
if err := db.UpsertCustomModel(tx, model); err != nil {
@@ -211,6 +247,24 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {
}
}
+ if len(toDeleteCustomModelIds) > 0 {
+ if err := db.DeleteCustomModels(tx, auth.OrgId, toDeleteCustomModelIds); err != nil {
+ return fmt.Errorf("error deleting custom models: %w", err)
+ }
+ }
+
+ if len(toDeleteCustomProviderIds) > 0 {
+ if err := db.DeleteCustomProviders(tx, auth.OrgId, toDeleteCustomProviderIds); err != nil {
+ return fmt.Errorf("error deleting custom providers: %w", err)
+ }
+ }
+
+ if len(toDeleteModelPackIds) > 0 {
+ if err := db.DeleteModelPacks(tx, auth.OrgId, toDeleteModelPackIds); err != nil {
+ return fmt.Errorf("error deleting model packs: %w", err)
+ }
+ }
+
return nil
})
@@ -291,51 +345,6 @@ func ListCustomModelsHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Successfully fetched custom models")
}
-func DeleteCustomModelHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for DeleteAvailableModelHandler")
-
- auth := Authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if !requireMinClientVersion(w, r, CustomModelsMinClientVersion) {
- return
- }
-
- id := mux.Vars(r)["modelId"]
-
- models, err := db.ListCustomModels(auth.OrgId)
- if err != nil {
- log.Printf("Error fetching custom models: %v\n", err)
- http.Error(w, "Failed to fetch custom models: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- found := false
- for _, m := range models {
- if m.Id == id {
- found = true
- break
- }
- }
-
- if !found {
- http.Error(w, "Custom model not found", http.StatusNotFound)
- return
- }
-
- if err := db.DeleteCustomModel(auth.OrgId, id); err != nil {
- log.Printf("Error deleting custom model: %v\n", err)
- http.Error(w, "Failed to delete custom model: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.WriteHeader(http.StatusOK)
-
- log.Println("Successfully deleted custom model")
-}
-
func GetCustomProviderHandler(w http.ResponseWriter, r *http.Request) {
auth := Authenticate(w, r, true)
if auth == nil {
@@ -392,27 +401,6 @@ func ListCustomProvidersHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Successfully fetched custom providers")
}
-func DeleteCustomProviderHandler(w http.ResponseWriter, r *http.Request) {
- auth := Authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if os.Getenv("IS_CLOUD") != "" {
- http.Error(w, "Custom model providers are not supported on Plandex Cloud", http.StatusBadRequest)
- return
- }
-
- id := mux.Vars(r)["providerId"]
- if err := db.DeleteCustomProvider(auth.OrgId, id); err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- w.WriteHeader(http.StatusOK)
-
- log.Println("Successfully deleted custom provider")
-}
-
func CreateModelPackHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for CreateModelPackHandler")
@@ -472,50 +460,3 @@ func ListModelPacksHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Successfully fetched model packs")
}
-
-func DeleteModelPackHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for DeleteModelPackHandler")
-
- auth := Authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if !requireMinClientVersion(w, r, CustomModelsMinClientVersion) {
- return
- }
-
- mpId := mux.Vars(r)["setId"]
-
- packs, err := db.ListModelPacks(auth.OrgId)
- if err != nil {
- log.Printf("Error fetching model packs: %v\n", err)
- http.Error(w, "Failed to fetch model packs: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- found := false
- for _, m := range packs {
- if m.Id == mpId {
- found = true
- break
- }
- }
-
- if !found {
- http.Error(w, "Model pack not found", http.StatusNotFound)
- return
- }
-
- log.Printf("Deleting model pack with id: %s\n", mpId)
-
- if err := db.DeleteModelPack(mpId); err != nil {
- log.Printf("Error deleting model pack: %v\n", err)
- http.Error(w, "Failed to delete model pack: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.WriteHeader(http.StatusOK)
-
- log.Println("Successfully deleted model pack")
-}
diff --git a/app/server/routes/routes.go b/app/server/routes/routes.go
index f0ff24e4..f63fbc0c 100644
--- a/app/server/routes/routes.go
+++ b/app/server/routes/routes.go
@@ -165,16 +165,13 @@ func addApiRoutes(r *mux.Router, prefix string) {
HandlePlandexFn(r, prefix+"/custom_models", false, handlers.ListCustomModelsHandler).Methods("GET")
HandlePlandexFn(r, prefix+"/custom_models", false, handlers.CreateCustomModelHandler).Methods("POST")
- HandlePlandexFn(r, prefix+"/custom_models/{modelId}", false, handlers.DeleteCustomModelHandler).Methods("DELETE")
HandlePlandexFn(r, prefix+"/custom_models/{modelId}", false, handlers.GetCustomModelHandler).Methods("GET")
HandlePlandexFn(r, prefix+"/custom_providers", false, handlers.ListCustomProvidersHandler).Methods("GET")
- HandlePlandexFn(r, prefix+"/custom_providers/{providerId}", false, handlers.DeleteCustomProviderHandler).Methods("DELETE")
HandlePlandexFn(r, prefix+"/custom_providers/{providerId}", false, handlers.GetCustomProviderHandler).Methods("GET")
HandlePlandexFn(r, prefix+"/model_sets", false, handlers.ListModelPacksHandler).Methods("GET")
HandlePlandexFn(r, prefix+"/model_sets", false, handlers.CreateModelPackHandler).Methods("POST")
- HandlePlandexFn(r, prefix+"/model_sets/{setId}", false, handlers.DeleteModelPackHandler).Methods("DELETE")
HandlePlandexFn(r, prefix+"/model_sets/{setId}", false, handlers.UpdateModelPackHandler).Methods("PUT")
HandlePlandexFn(r, prefix+"/default_settings", false, handlers.GetDefaultSettingsHandler).Methods("GET")
HandlePlandexFn(r, prefix+"/default_settings", false, handlers.UpdateDefaultSettingsHandler).Methods("PUT")