From 3fb6b9d631d399104778cf8d4a79facd23ed8853 Mon Sep 17 00:00:00 2001 From: 5quan <150108903+5quan@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:37:23 +0800 Subject: [PATCH] fix(kb): let the update API set vlm_config (#3704) * fix(kb): let update API set vlm_config UpdateKnowledgeBaseRequest only carried name/description/config, so the PUT /knowledge-bases/:id endpoint could never change a knowledge base's multimodal (VLM) config, even though CreateKnowledgeBase accepts a top-level vlm_config. Thread an optional vlm_config through the handler and service so the update path mirrors create (nil = no change). Fixes #1723 * test(kb): pass the vlm_config argument in tests added on main * fix(kb): accept only model-managed vlm_config fields on update The update API copied the request's VLMConfig wholesale, so a caller could set the legacy ModelName/BaseURL/APIKey/InterfaceType fields and have the VLM client call BaseURL directly, outside model management and its SSRF checks. Only Enabled/ModelID/DescriptionLanguage/ CustomInstructions are taken now; legacy fields keep their stored value. A referenced model must exist and be a VLLM model (400 otherwise), and disabling clears ModelID, matching the initialization config endpoint. * fix(kb): validate and gate vlm_config on the update API - Enforce the 4000-character custom_instructions cap (types.ValidateKnowledgeBasePromptInstructions), as create and /initialization/config already do. - vlm_config is a KB setting: require kbSettingsAccess (owner workspace or admin share) like /initialization/config, so share editors get 403. - Stored legacy model_name/base_url keep IsEnabled() true on their own, so disabling returned 200 but left VLM on, and managed -> disabled fell back to the old endpoint. Clear them when the request enables a managed model_id, or disables VLM without echoing back the stored model_name+base_url (GET-then-PUT keeps legacy on). Request legacy fields are only compared, never written. Enabling without model_id on a non-legacy KB is now a 400 instead of a silent no-op. - Document the vlm_config semantics in the KB API reference. * fix(kb): keep the legacy VLM endpoint only for pure legacy knowledge bases CreateKnowledgeBase stores vlm_config as sent, so a managed model_id can sit next to legacy model_name/base_url; resolveVLM then uses the managed model. The update's keep-legacy paths (disable echoing the stored legacy fields, enabled=true without model_id) cleared model_id but kept the legacy fields, so IsEnabled() stayed true and image calls moved to the stored base_url. Those paths now apply only when no model_id is stored. On a mixed config a disable clears everything, and enabled=true without model_id is a 400, the same as on any managed knowledge base. --------- Co-authored-by: wizardchen --- .../agent/tools/query_knowledge_graph_test.go | 1 + .../service/datasource_service_test.go | 2 +- internal/application/service/knowledgebase.go | 81 +++++ .../knowledgebase_image_config_test.go | 4 +- .../service/knowledgebase_vlm_update_test.go | 276 ++++++++++++++++++ internal/handler/knowledgebase.go | 21 +- .../handler/knowledgebase_vlm_update_test.go | 92 ++++++ internal/types/interfaces/knowledgebase.go | 3 +- website-docs/04-api/02-api-knowledge.md | 1 + 9 files changed, 475 insertions(+), 6 deletions(-) create mode 100644 internal/application/service/knowledgebase_vlm_update_test.go create mode 100644 internal/handler/knowledgebase_vlm_update_test.go diff --git a/internal/agent/tools/query_knowledge_graph_test.go b/internal/agent/tools/query_knowledge_graph_test.go index 8a67f17b..24fc7d81 100644 --- a/internal/agent/tools/query_knowledge_graph_test.go +++ b/internal/agent/tools/query_knowledge_graph_test.go @@ -52,6 +52,7 @@ func (s *stubKnowledgeBaseService) UpdateKnowledgeBase( string, string, *types.KnowledgeBaseConfig, + *types.VLMConfig, ) (*types.KnowledgeBase, error) { return nil, nil } diff --git a/internal/application/service/datasource_service_test.go b/internal/application/service/datasource_service_test.go index 09fc9300..b404f9b2 100644 --- a/internal/application/service/datasource_service_test.go +++ b/internal/application/service/datasource_service_test.go @@ -93,7 +93,7 @@ func (s *processSyncKBService) ListKnowledgeBasesByTenantID(context.Context, uin } func (s *processSyncKBService) UpdateKnowledgeBase( - context.Context, string, string, string, *types.KnowledgeBaseConfig, + context.Context, string, string, string, *types.KnowledgeBaseConfig, *types.VLMConfig, ) (*types.KnowledgeBase, error) { return nil, nil } diff --git a/internal/application/service/knowledgebase.go b/internal/application/service/knowledgebase.go index 97716672..94a5818b 100644 --- a/internal/application/service/knowledgebase.go +++ b/internal/application/service/knowledgebase.go @@ -475,6 +475,74 @@ func (s *knowledgeBaseService) FillKnowledgeBaseCounts(ctx context.Context, kb * return nil } +// resolveUpdatedVLMConfig builds the VLM config an update request asks for. +// Only the model-managed fields are taken from the request: the legacy +// ModelName/BaseURL/APIKey/InterfaceType fields make the VLM client call +// BaseURL directly, bypassing model management and its SSRF checks, so they +// are never written from the request. A referenced model must exist and be a +// VLM model. +// +// Stored legacy fields keep VLMConfig.IsEnabled() true on their own, so they +// are cleared when the request enables a managed model, or when it disables +// VLM without echoing back the stored model_name and base_url (the shape a +// GET-then-PUT round trip sends). Request legacy fields are only compared. +// +// Only a pure legacy KB (no stored ModelID) keeps its legacy endpoint on an +// echo or on enabled=true without a model_id. A config that carries a managed +// ModelID next to legacy fields (CreateKnowledgeBase stores the request as +// is) is treated as managed: clearing ModelID while keeping the legacy +// fields would silently move image calls to the stored BaseURL. +func (s *knowledgeBaseService) resolveUpdatedVLMConfig( + ctx context.Context, current, requested types.VLMConfig, +) (types.VLMConfig, error) { + next := current + next.Enabled = requested.Enabled + next.ModelID = strings.TrimSpace(requested.ModelID) + next.DescriptionLanguage = strings.TrimSpace(requested.DescriptionLanguage) + next.CustomInstructions = strings.TrimSpace(requested.CustomInstructions) + if err := types.ValidateKnowledgeBasePromptInstructions(&types.KnowledgeBase{VLMConfig: next}); err != nil { + return types.VLMConfig{}, apperrors.NewBadRequestError("vlm_config: " + err.Error()) + } + pureLegacy := current.ModelID == "" && current.ModelName != "" && current.BaseURL != "" + if !next.Enabled { + next.ModelID = "" + legacyEcho := pureLegacy && + requested.ModelName == current.ModelName && requested.BaseURL == current.BaseURL + if !legacyEcho { + clearLegacyVLMFields(&next) + } + return next, nil + } + if next.ModelID == "" { + if !pureLegacy { + return types.VLMConfig{}, apperrors.NewBadRequestError( + "vlm_config.model_id is required when enabled") + } + return next, nil + } + model, err := s.modelService.GetModelByID(ctx, next.ModelID) + if errors.Is(err, ErrModelNotFound) { + return types.VLMConfig{}, apperrors.NewBadRequestError("vlm_config.model_id: model not found") + } + if err != nil { + return types.VLMConfig{}, fmt.Errorf("get vlm model %s: %w", next.ModelID, err) + } + if model.Type != types.ModelTypeVLLM { + return types.VLMConfig{}, apperrors.NewBadRequestError( + fmt.Sprintf("vlm_config.model_id: model type is %s, want %s", model.Type, types.ModelTypeVLLM)) + } + clearLegacyVLMFields(&next) + return next, nil +} + +// clearLegacyVLMFields drops the pre-model-management inline VLM endpoint. +func clearLegacyVLMFields(cfg *types.VLMConfig) { + cfg.ModelName = "" + cfg.BaseURL = "" + cfg.APIKey = "" + cfg.InterfaceType = "" +} + // UpdateKnowledgeBase updates a knowledge base's mutable properties. // // IMPORTANT — vector_store_id immutability contract: @@ -497,6 +565,7 @@ func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context, name string, description string, config *types.KnowledgeBaseConfig, + vlmConfig *types.VLMConfig, ) (*types.KnowledgeBase, error) { if id == "" { logger.Error(ctx, "Knowledge base ID is empty") @@ -569,6 +638,18 @@ func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context, } } } + // Apply multimodal (vision) config only when the caller provided it, + // mirroring the nil-means-no-change semantics used above. + if vlmConfig != nil { + next, err := s.resolveUpdatedVLMConfig(ctx, kb.VLMConfig, *vlmConfig) + if err != nil { + return nil, err + } + if kb.VLMConfig != next { + changedFields = append(changedFields, "vlm_config") + } + kb.VLMConfig = next + } kb.UpdatedAt = time.Now() kb.EnsureDefaults() diff --git a/internal/application/service/knowledgebase_image_config_test.go b/internal/application/service/knowledgebase_image_config_test.go index ddef0dc4..778b2d95 100644 --- a/internal/application/service/knowledgebase_image_config_test.go +++ b/internal/application/service/knowledgebase_image_config_test.go @@ -52,7 +52,7 @@ func TestUpdateKnowledgeBase_KeepsImageConfigWhenRequestOmitsIt(t *testing.T) { // The whole config is present but the image section is absent — this is the // shape every existing client sends. updated, err := svc.UpdateKnowledgeBase(ctxWithTenant(1), stored.ID, "renamed", "desc", - &types.KnowledgeBaseConfig{}) + &types.KnowledgeBaseConfig{}, nil) require.NoError(t, err) got := updated.ImageProcessingConfig @@ -80,7 +80,7 @@ func TestUpdateKnowledgeBase_ReplacesImageConfigWhenRequestCarriesIt(t *testing. updated, err := svc.UpdateKnowledgeBase(ctxWithTenant(1), stored.ID, stored.Name, stored.Description, &types.KnowledgeBaseConfig{ ImageProcessingConfig: &types.ImageProcessingConfig{ModelID: "vlm-image-2"}, - }) + }, nil) require.NoError(t, err) got := updated.ImageProcessingConfig diff --git a/internal/application/service/knowledgebase_vlm_update_test.go b/internal/application/service/knowledgebase_vlm_update_test.go new file mode 100644 index 00000000..39fdd046 --- /dev/null +++ b/internal/application/service/knowledgebase_vlm_update_test.go @@ -0,0 +1,276 @@ +package service + +import ( + "context" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + apperrors "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// vlmUpdateModelService resolves models from a fixed table, enough for the +// model check the KB update applies to vlm_config. +type vlmUpdateModelService struct { + interfaces.ModelService + models map[string]*types.Model +} + +func (m *vlmUpdateModelService) GetModelByID(_ context.Context, id string) (*types.Model, error) { + if model, ok := m.models[id]; ok { + return model, nil + } + return nil, ErrModelNotFound +} + +func newVLMUpdateService(repo *fakeKBRepo) *knowledgeBaseService { + return &knowledgeBaseService{repo: repo, modelService: &vlmUpdateModelService{models: map[string]*types.Model{ + "vlm-1": {ID: "vlm-1", Type: types.ModelTypeVLLM}, + "chat-1": {ID: "chat-1", Type: types.ModelTypeKnowledgeQA}, + }}} +} + +// TestUpdateKnowledgeBaseAppliesVLMConfig guards issue #1723: the KB update +// API previously had no way to change a knowledge base's multimodal (VLM) +// config, because neither the HTTP request nor the service method carried it. +func TestUpdateKnowledgeBaseAppliesVLMConfig(t *testing.T) { + repo := newFakeKBRepo() + repo.rows["kb-1"] = &types.KnowledgeBase{ID: "kb-1", Name: "old", TenantID: 1} + svc := newVLMUpdateService(repo) + ctx := context.Background() + + // nil vlmConfig must preserve whatever is already stored. + kb, err := svc.UpdateKnowledgeBase(ctx, "kb-1", "n", "d", nil, nil) + require.NoError(t, err) + assert.False(t, kb.VLMConfig.Enabled, "absent vlm_config must not enable multimodal") + + // Providing vlm_config must persist it — this was silently dropped before #1723. + kb, err = svc.UpdateKnowledgeBase(ctx, "kb-1", "n", "d", nil, + &types.VLMConfig{Enabled: true, ModelID: "vlm-1"}) + require.NoError(t, err) + assert.True(t, kb.VLMConfig.Enabled) + assert.Equal(t, "vlm-1", kb.VLMConfig.ModelID) + + // Disabling clears the model, like the initialization config endpoint does. + kb, err = svc.UpdateKnowledgeBase(ctx, "kb-1", "n", "d", nil, + &types.VLMConfig{Enabled: false, ModelID: "vlm-1"}) + require.NoError(t, err) + assert.False(t, kb.VLMConfig.Enabled) + assert.Empty(t, kb.VLMConfig.ModelID) +} + +func newLegacyVLMKB() *types.KnowledgeBase { + return &types.KnowledgeBase{ + ID: "kb-1", Name: "old", TenantID: 1, + VLMConfig: types.VLMConfig{ + ModelName: "stored", BaseURL: "https://stored.example", APIKey: "sk", InterfaceType: "openai", + }, + } +} + +// The legacy fields point the VLM client straight at BaseURL, outside model +// management and its SSRF checks, so the update API never writes them from the +// request. Switching to a managed model clears the stored ones, so a later +// disable cannot fall back to the old endpoint. +func TestUpdateKnowledgeBaseManagedVLMClearsLegacyFields(t *testing.T) { + repo := newFakeKBRepo() + repo.rows["kb-1"] = newLegacyVLMKB() + svc := newVLMUpdateService(repo) + ctx := context.Background() + + kb, err := svc.UpdateKnowledgeBase(ctx, "kb-1", "n", "d", nil, &types.VLMConfig{ + Enabled: true, ModelID: "vlm-1", + ModelName: "evil", BaseURL: "http://169.254.169.254", APIKey: "k", InterfaceType: "ollama", + }) + require.NoError(t, err) + assert.Equal(t, "vlm-1", kb.VLMConfig.ModelID) + assert.Empty(t, kb.VLMConfig.ModelName) + assert.Empty(t, kb.VLMConfig.BaseURL) + assert.Empty(t, kb.VLMConfig.APIKey) + assert.Empty(t, kb.VLMConfig.InterfaceType) + + kb, err = svc.UpdateKnowledgeBase(ctx, "kb-1", "n", "d", nil, &types.VLMConfig{Enabled: false}) + require.NoError(t, err) + assert.False(t, kb.VLMConfig.IsEnabled(), "disable after managed must not fall back to legacy") +} + +// An explicit disable on a legacy KB must actually turn VLM off: the stored +// ModelName/BaseURL alone keep IsEnabled() true, so they are cleared too. +func TestUpdateKnowledgeBaseDisablesLegacyVLM(t *testing.T) { + cases := map[string]types.VLMConfig{ + "plain disable": {Enabled: false}, + "disable other legacy": {Enabled: false, ModelName: "stored", BaseURL: "http://169.254.169.254"}, + } + for name, req := range cases { + t.Run(name, func(t *testing.T) { + repo := newFakeKBRepo() + repo.rows["kb-1"] = newLegacyVLMKB() + svc := newVLMUpdateService(repo) + + kb, err := svc.UpdateKnowledgeBase(context.Background(), "kb-1", "n", "d", nil, &req) + require.NoError(t, err) + assert.False(t, kb.VLMConfig.IsEnabled()) + assert.Empty(t, kb.VLMConfig.ModelName) + assert.Empty(t, kb.VLMConfig.BaseURL) + assert.Empty(t, kb.VLMConfig.APIKey) + }) + } +} + +// GET returns model_name/base_url verbatim with enabled=false for a legacy KB; +// PUTting that body back is an unrelated save and must keep legacy VLM on. +func TestUpdateKnowledgeBaseLegacyVLMEchoKeepsLegacy(t *testing.T) { + repo := newFakeKBRepo() + repo.rows["kb-1"] = newLegacyVLMKB() + svc := newVLMUpdateService(repo) + ctx := context.Background() + + kb, err := svc.UpdateKnowledgeBase(ctx, "kb-1", "n", "d", nil, &types.VLMConfig{ + Enabled: false, ModelName: "stored", BaseURL: "https://stored.example", + }) + require.NoError(t, err) + assert.True(t, kb.VLMConfig.IsEnabled()) + assert.Equal(t, newLegacyVLMKB().VLMConfig, kb.VLMConfig) + + // enabled=true without a model_id keeps a legacy KB as it is. + kb, err = svc.UpdateKnowledgeBase(ctx, "kb-1", "n", "d", nil, &types.VLMConfig{Enabled: true}) + require.NoError(t, err) + assert.True(t, kb.VLMConfig.IsEnabled()) + assert.Equal(t, "https://stored.example", kb.VLMConfig.BaseURL) +} + +// Enabling without a model on a non-legacy KB would store Enabled=true while +// IsEnabled() stays false; reject it instead. +func TestUpdateKnowledgeBaseRejectsEnableWithoutModel(t *testing.T) { + repo := newFakeKBRepo() + repo.rows["kb-1"] = &types.KnowledgeBase{ID: "kb-1", Name: "old", TenantID: 1} + svc := newVLMUpdateService(repo) + + _, err := svc.UpdateKnowledgeBase(context.Background(), "kb-1", "n", "d", nil, &types.VLMConfig{Enabled: true}) + + appErr, ok := apperrors.IsAppError(err) + require.True(t, ok, "error = %v, want an AppError", err) + assert.Equal(t, http.StatusBadRequest, appErr.HTTPCode) + assert.False(t, repo.rows["kb-1"].VLMConfig.Enabled) +} + +// custom_instructions has the same 4000-character cap as create and +// /initialization/config. +func TestUpdateKnowledgeBaseRejectsOverlongVLMInstructions(t *testing.T) { + repo := newFakeKBRepo() + repo.rows["kb-1"] = &types.KnowledgeBase{ + ID: "kb-1", Name: "old", TenantID: 1, + VLMConfig: types.VLMConfig{Enabled: true, ModelID: "vlm-1", CustomInstructions: "keep"}, + } + svc := newVLMUpdateService(repo) + ctx := context.Background() + + _, err := svc.UpdateKnowledgeBase(ctx, "kb-1", "n", "d", nil, &types.VLMConfig{ + Enabled: true, ModelID: "vlm-1", + CustomInstructions: strings.Repeat("字", types.MaxCustomPromptInstructionsLength+1), + }) + appErr, ok := apperrors.IsAppError(err) + require.True(t, ok, "error = %v, want an AppError", err) + assert.Equal(t, http.StatusBadRequest, appErr.HTTPCode) + assert.Equal(t, "keep", repo.rows["kb-1"].VLMConfig.CustomInstructions) + + kb, err := svc.UpdateKnowledgeBase(ctx, "kb-1", "n", "d", nil, &types.VLMConfig{ + Enabled: true, ModelID: "vlm-1", + CustomInstructions: strings.Repeat("字", types.MaxCustomPromptInstructionsLength), + }) + require.NoError(t, err) + assert.Len(t, []rune(kb.VLMConfig.CustomInstructions), types.MaxCustomPromptInstructionsLength) +} + +// A vlm_config that names a missing model or a non-VLM model is rejected as a +// bad request and leaves the stored VLM config alone. +func TestUpdateKnowledgeBaseRejectsInvalidVLMModel(t *testing.T) { + for _, modelID := range []string{"missing", "chat-1"} { + t.Run(modelID, func(t *testing.T) { + repo := newFakeKBRepo() + repo.rows["kb-1"] = &types.KnowledgeBase{ID: "kb-1", Name: "old", TenantID: 1} + svc := newVLMUpdateService(repo) + + _, err := svc.UpdateKnowledgeBase(context.Background(), "kb-1", "n", "d", nil, + &types.VLMConfig{Enabled: true, ModelID: modelID}) + + appErr, ok := apperrors.IsAppError(err) + require.True(t, ok, "error = %v, want an AppError", err) + assert.Equal(t, http.StatusBadRequest, appErr.HTTPCode) + assert.False(t, repo.rows["kb-1"].VLMConfig.Enabled) + }) + } +} + +// CreateKnowledgeBase stores vlm_config as sent, so a managed model_id can sit +// next to legacy model_name/base_url. resolveVLM uses the managed model then; +// an update must not drop model_id and leave the legacy endpoint in charge. +func newMixedVLMKB() *types.KnowledgeBase { + kb := newLegacyVLMKB() + kb.VLMConfig.Enabled = true + kb.VLMConfig.ModelID = "vlm-1" + return kb +} + +func TestUpdateKnowledgeBaseMixedVLMDisableClearsLegacy(t *testing.T) { + cases := map[string]types.VLMConfig{ + "plain disable": {Enabled: false}, + "disable echoing stored legacy": { + Enabled: false, ModelID: "vlm-1", ModelName: "stored", BaseURL: "https://stored.example", + }, + } + for name, req := range cases { + t.Run(name, func(t *testing.T) { + repo := newFakeKBRepo() + repo.rows["kb-1"] = newMixedVLMKB() + svc := newVLMUpdateService(repo) + + kb, err := svc.UpdateKnowledgeBase(context.Background(), "kb-1", "n", "d", nil, &req) + require.NoError(t, err) + assert.False(t, kb.VLMConfig.IsEnabled(), "disable must not fall back to the stored base_url") + assert.Empty(t, kb.VLMConfig.ModelID) + assert.Empty(t, kb.VLMConfig.ModelName) + assert.Empty(t, kb.VLMConfig.BaseURL) + assert.Empty(t, kb.VLMConfig.APIKey) + }) + } +} + +// enabled=true without model_id is only a no-op for a pure legacy KB. On a +// mixed config it would drop the managed model and run on the legacy +// endpoint, so it is rejected like on any other managed KB. +func TestUpdateKnowledgeBaseMixedVLMEnableWithoutModelRejected(t *testing.T) { + repo := newFakeKBRepo() + repo.rows["kb-1"] = newMixedVLMKB() + svc := newVLMUpdateService(repo) + + _, err := svc.UpdateKnowledgeBase(context.Background(), "kb-1", "n", "d", nil, &types.VLMConfig{ + Enabled: true, ModelName: "stored", BaseURL: "https://stored.example", + }) + + appErr, ok := apperrors.IsAppError(err) + require.True(t, ok, "error = %v, want an AppError", err) + assert.Equal(t, http.StatusBadRequest, appErr.HTTPCode) + assert.Equal(t, newMixedVLMKB().VLMConfig, repo.rows["kb-1"].VLMConfig) +} + +// Echoing the managed model_id keeps it and drops the legacy fields. +func TestUpdateKnowledgeBaseMixedVLMKeepsManagedModel(t *testing.T) { + repo := newFakeKBRepo() + repo.rows["kb-1"] = newMixedVLMKB() + svc := newVLMUpdateService(repo) + + kb, err := svc.UpdateKnowledgeBase(context.Background(), "kb-1", "n", "d", nil, &types.VLMConfig{ + Enabled: true, ModelID: "vlm-1", ModelName: "stored", BaseURL: "https://stored.example", + }) + require.NoError(t, err) + assert.Equal(t, "vlm-1", kb.VLMConfig.ModelID) + assert.True(t, kb.VLMConfig.IsEnabled()) + assert.Empty(t, kb.VLMConfig.ModelName) + assert.Empty(t, kb.VLMConfig.BaseURL) +} diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.go index 9db3ed2a..7d097924 100644 --- a/internal/handler/knowledgebase.go +++ b/internal/handler/knowledgebase.go @@ -737,6 +737,10 @@ type UpdateKnowledgeBaseRequest struct { Name string `json:"name" binding:"required"` Description string `json:"description"` Config *types.KnowledgeBaseConfig `json:"config"` + // VLMConfig updates the knowledge base's multimodal (vision) config. + // Optional: nil means "no change", mirroring how CreateKnowledgeBase + // accepts a top-level vlm_config. + VLMConfig *types.VLMConfig `json:"vlm_config"` } // UpdateKnowledgeBase godoc @@ -757,7 +761,7 @@ func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) { logger.Info(ctx, "Start updating knowledge base") // Validate and get the knowledge base - _, id, _, permission, err := h.validateAndGetKnowledgeBase(c) + currentKB, id, _, permission, err := h.validateAndGetKnowledgeBase(c) if err != nil { c.Error(err) return @@ -776,6 +780,14 @@ func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) { c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error())) return } + // The VLM model is a KB setting: like PUT /initialization/config, only the + // owner workspace or an admin share may change it, not a share editor. + if req.VLMConfig != nil { + if _, err := kbSettingsAccess(c, currentKB); err != nil { + _ = c.Error(err) + return + } + } if req.Config != nil { probe := &types.KnowledgeBase{ ChunkingConfig: req.Config.ChunkingConfig, @@ -795,8 +807,13 @@ func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) { secutils.SanitizeForLog(id), secutils.SanitizeForLog(req.Name)) // Update the knowledge base - kb, err := h.service.UpdateKnowledgeBase(ctx, id, req.Name, req.Description, req.Config) + kb, err := h.service.UpdateKnowledgeBase(ctx, id, req.Name, req.Description, req.Config, req.VLMConfig) if err != nil { + // A rejected vlm_config is the caller's mistake, not a server failure. + if appErr, ok := apperrors.IsAppError(err); ok { + _ = c.Error(appErr) + return + } logger.ErrorWithFields(ctx, err, nil) c.Error(apperrors.NewInternalServerError(err.Error())) return diff --git a/internal/handler/knowledgebase_vlm_update_test.go b/internal/handler/knowledgebase_vlm_update_test.go new file mode 100644 index 00000000..10802c13 --- /dev/null +++ b/internal/handler/knowledgebase_vlm_update_test.go @@ -0,0 +1,92 @@ +package handler + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/config" + "github.com/Tencent/WeKnora/internal/middleware" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type vlmUpdateKBService struct { + interfaces.KnowledgeBaseService + kb *types.KnowledgeBase + updated bool +} + +func (s *vlmUpdateKBService) GetKnowledgeBaseByID(context.Context, string) (*types.KnowledgeBase, error) { + return s.kb, nil +} + +func (s *vlmUpdateKBService) UpdateKnowledgeBase( + _ context.Context, _, _, _ string, _ *types.KnowledgeBaseConfig, _ *types.VLMConfig, +) (*types.KnowledgeBase, error) { + s.updated = true + return s.kb, nil +} + +type vlmUpdateShareStub struct { + interfaces.KBShareService + permission types.OrgMemberRole +} + +func (s *vlmUpdateShareStub) CheckTenantKBPermission( + context.Context, string, uint64, types.TenantRole, +) (types.OrgMemberRole, bool, error) { + return s.permission, true, nil +} + +// PUT /knowledge-bases/:id admits share editors through KBAccessWrite, but the +// VLM model is a KB setting: like PUT /initialization/config, only the owner +// workspace or an admin share may change it. +func TestUpdateKnowledgeBaseVLMConfigRequiresSettingsAccess(t *testing.T) { + const withVLM = `{"name":"n","vlm_config":{"enabled":true,"model_id":"vlm-1"}}` + cases := []struct { + name string + ownerTenant uint64 + permission types.OrgMemberRole + body string + wantStatus int + }{ + {"share editor with vlm_config", 2, types.OrgRoleEditor, withVLM, http.StatusForbidden}, + {"share editor without vlm_config", 2, types.OrgRoleEditor, `{"name":"n"}`, http.StatusOK}, + {"share admin with vlm_config", 2, types.OrgRoleAdmin, withVLM, http.StatusOK}, + {"owner workspace with vlm_config", 1, "", withVLM, http.StatusOK}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := &vlmUpdateKBService{kb: &types.KnowledgeBase{ID: "kb-1", TenantID: tc.ownerTenant}} + shares := &vlmUpdateShareStub{permission: tc.permission} + h := &KnowledgeBaseHandler{service: svc, kbShareService: shares} + enabled := true + r := gin.New() + r.Use(middleware.ErrorHandler(), func(c *gin.Context) { + ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(1)) + ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin) + c.Request = c.Request.WithContext(ctx) + c.Set(types.TenantIDContextKey.String(), uint64(1)) + c.Next() + }) + r.PUT("/:id", middleware.RequireKBAccess( + middleware.KBIDFromParam("id"), types.OrgRoleEditor, svc, shares, nil, + &config.Config{Tenant: &config.TenantConfig{EnableRBAC: &enabled}}, + ), h.UpdateKnowledgeBase) + + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPut, "/kb-1", strings.NewReader(tc.body)) + req.Header.Set("Content-Type", "application/json") + r.ServeHTTP(w, req) + + require.Equal(t, tc.wantStatus, w.Code, w.Body.String()) + require.Equal(t, tc.wantStatus == http.StatusOK, svc.updated) + }) + } +} diff --git a/internal/types/interfaces/knowledgebase.go b/internal/types/interfaces/knowledgebase.go index ddf5071e..d1e2d7d9 100644 --- a/internal/types/interfaces/knowledgebase.go +++ b/internal/types/interfaces/knowledgebase.go @@ -67,11 +67,12 @@ type KnowledgeBaseService interface { // - name: New knowledge base name // - description: New knowledge base description // - config: Knowledge base configuration, including chunking strategy, vectorization settings, etc. + // - vlmConfig: Optional multimodal (vision) config; nil means no change // Returns: // - Updated knowledge base object // - Possible errors such as not existing, insufficient permissions, etc. UpdateKnowledgeBase(ctx context.Context, - id string, name string, description string, config *types.KnowledgeBaseConfig, + id string, name string, description string, config *types.KnowledgeBaseConfig, vlmConfig *types.VLMConfig, ) (*types.KnowledgeBase, error) // DeleteKnowledgeBase deletes a knowledge base diff --git a/website-docs/04-api/02-api-knowledge.md b/website-docs/04-api/02-api-knowledge.md index 2327ad80..0c401428 100644 --- a/website-docs/04-api/02-api-knowledge.md +++ b/website-docs/04-api/02-api-knowledge.md @@ -101,6 +101,7 @@ curl $BASE/api/v1/knowledge-bases/kb-1 -H "Authorization: Bearer $TOKEN" | `name` | string | 是(`binding:"required"`) | 名称 | | `description` | string | 否 | 描述 | | `config` | object | 否 | 局部配置更新:`chunking_config`、`image_processing_config`、`faq_config`、`wiki_config`、`auto_tag_config`、`profile_config`、`indexing_strategy` | +| `vlm_config` | object | 否 | 多模态配置,整体替换:只取 `enabled`、`model_id`(须为 VLLM 模型)、`description_language`、`custom_instructions`(≤4000 字),未传的字段按空值处理;不想改就不要传。共享库需所有者空间或共享 admin 权限(editor 返回 403)。旧版内联字段 `model_name`/`base_url`/`api_key`/`interface_type` 不会被写入:启用托管 `model_id` 或关闭时会清空已存的旧版配置,但纯旧版库(未存 `model_id`,只存了 `model_name`/`base_url`)原样回传 GET 结果(`enabled=false` 且 `model_name`/`base_url` 与存储一致)视为不改;其余库 `enabled=true` 却缺 `model_id` 返回 400 | 响应:200 `{"success":true,"data":{KnowledgeBase}}`