feat(client): enhance knowledge file upload with process configuration support
- Updated the `CreateKnowledgeFromFile` function to accept an optional `processConfig` parameter for per-upload parse configuration overrides. - Introduced the `KnowledgeProcessOverrides` type to define various parsing settings, including parser engine rules and chunking configurations. - Modified the API client and related components to handle the new process configuration, improving flexibility in knowledge file uploads. - Updated documentation and API specifications to reflect the new `process_config` parameter in the upload process. - Added a new `UploadConfirmHost` component to facilitate user confirmation for uploads, integrating with the updated upload logic. - Enhanced user experience by providing detailed configuration options during the upload process.
This commit is contained in:
@@ -839,6 +839,7 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource
|
||||
item.FileName, // customFileName — must include extension for file-type validation
|
||||
tagID, // auto-tag from data source
|
||||
channel,
|
||||
nil,
|
||||
)
|
||||
return isUpdate, err
|
||||
}
|
||||
@@ -855,6 +856,7 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource
|
||||
item.Title,
|
||||
tagID, // auto-tag from data source
|
||||
channel,
|
||||
nil,
|
||||
)
|
||||
return isUpdate, err
|
||||
}
|
||||
|
||||
@@ -290,10 +290,22 @@ func (s *ChunkExtractService) Handle(ctx context.Context, t *asynq.Task) error {
|
||||
handleErr = err
|
||||
return err
|
||||
}
|
||||
if kb.ExtractConfig == nil {
|
||||
logger.Warnf(ctx, "failed to get extract config")
|
||||
graphOut["skipped"] = "no_extract_config"
|
||||
return err
|
||||
|
||||
var processOverrides *types.KnowledgeProcessOverrides
|
||||
knowledgeID := p.KnowledgeID
|
||||
if knowledgeID == "" {
|
||||
knowledgeID = chunk.KnowledgeID
|
||||
}
|
||||
if knowledgeID != "" && s.knowledgeRepo != nil {
|
||||
if k, kerr := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, knowledgeID); kerr == nil && k != nil {
|
||||
processOverrides, _ = k.ProcessOverrides()
|
||||
}
|
||||
}
|
||||
extractCfg := ResolveProcessConfig(kb, processOverrides).ExtractConfig
|
||||
if !extractCfg.Enabled {
|
||||
logger.Warnf(ctx, "extract config not enabled")
|
||||
graphOut["skipped"] = "extract_disabled"
|
||||
return nil
|
||||
}
|
||||
|
||||
chatModel, err := s.modelService.GetChatModel(ctx, p.ModelID)
|
||||
@@ -305,12 +317,12 @@ func (s *ChunkExtractService) Handle(ctx context.Context, t *asynq.Task) error {
|
||||
|
||||
template := &types.PromptTemplateStructured{
|
||||
Description: s.template.Description,
|
||||
Tags: kb.ExtractConfig.Tags,
|
||||
Tags: extractCfg.Tags,
|
||||
Examples: []types.GraphData{
|
||||
{
|
||||
Text: kb.ExtractConfig.Text,
|
||||
Node: kb.ExtractConfig.Nodes,
|
||||
Relation: kb.ExtractConfig.Relations,
|
||||
Text: extractCfg.Text,
|
||||
Node: extractCfg.Nodes,
|
||||
Relation: extractCfg.Relations,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -201,7 +201,7 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
|
||||
}
|
||||
}()
|
||||
|
||||
vlmModel, err := s.resolveVLM(ctx, payload.KnowledgeBaseID)
|
||||
vlmModel, vlmCfg, err := s.resolveVLM(ctx, payload.KnowledgeBaseID, payload.KnowledgeID)
|
||||
if err != nil {
|
||||
handleErr = fmt.Errorf("resolve VLM: %w", err)
|
||||
return handleErr
|
||||
@@ -210,12 +210,10 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
|
||||
// legacy inline-config path) so the trace shows WHICH model handled
|
||||
// this image. Without this, debugging "VLM is slow" requires a
|
||||
// separate hop to the KB config.
|
||||
if kb, kbErr := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID); kbErr == nil && kb != nil {
|
||||
if id := strings.TrimSpace(kb.VLMConfig.ModelID); id != "" {
|
||||
imgOut["vlm_model_id"] = id
|
||||
} else {
|
||||
imgOut["vlm_model_id"] = "legacy_inline"
|
||||
}
|
||||
if id := strings.TrimSpace(vlmCfg.ModelID); id != "" {
|
||||
imgOut["vlm_model_id"] = id
|
||||
} else {
|
||||
imgOut["vlm_model_id"] = "legacy_inline"
|
||||
}
|
||||
|
||||
// Read image bytes. A provider:// URL must be resolved via FileService —
|
||||
@@ -456,27 +454,36 @@ func (s *ImageMultimodalService) indexChunks(ctx context.Context, payload types.
|
||||
|
||||
// resolveVLM creates a vlm.VLM instance for the given knowledge base,
|
||||
// supporting both new-style (ModelID) and legacy (inline BaseURL) configs.
|
||||
func (s *ImageMultimodalService) resolveVLM(ctx context.Context, kbID string) (vlm.VLM, error) {
|
||||
// Per-upload process_overrides on the knowledge entry take precedence over KB defaults.
|
||||
func (s *ImageMultimodalService) resolveVLM(ctx context.Context, kbID, knowledgeID string) (vlm.VLM, types.VLMConfig, error) {
|
||||
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get knowledge base %s: %w", kbID, err)
|
||||
return nil, types.VLMConfig{}, fmt.Errorf("get knowledge base %s: %w", kbID, err)
|
||||
}
|
||||
if kb == nil {
|
||||
return nil, fmt.Errorf("knowledge base %s not found", kbID)
|
||||
return nil, types.VLMConfig{}, fmt.Errorf("knowledge base %s not found", kbID)
|
||||
}
|
||||
|
||||
vlmCfg := kb.VLMConfig
|
||||
var processOverrides *types.KnowledgeProcessOverrides
|
||||
if knowledgeID != "" && s.knowledgeRepo != nil {
|
||||
if k, kerr := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, knowledgeID); kerr == nil && k != nil {
|
||||
processOverrides, _ = k.ProcessOverrides()
|
||||
}
|
||||
}
|
||||
vlmCfg := ResolveProcessConfig(kb, processOverrides).VLMConfig
|
||||
if !vlmCfg.IsEnabled() {
|
||||
return nil, fmt.Errorf("VLM is not enabled for knowledge base %s", kbID)
|
||||
return nil, types.VLMConfig{}, fmt.Errorf("VLM is not enabled for knowledge base %s", kbID)
|
||||
}
|
||||
|
||||
// New-style: resolve model through ModelService
|
||||
if vlmCfg.ModelID != "" {
|
||||
return s.modelService.GetVLMModel(ctx, vlmCfg.ModelID)
|
||||
model, err := s.modelService.GetVLMModel(ctx, vlmCfg.ModelID)
|
||||
return model, vlmCfg, err
|
||||
}
|
||||
|
||||
// Legacy: create VLM from inline config
|
||||
return vlm.NewVLMFromLegacyConfig(vlmCfg, s.ollamaService)
|
||||
model, err := vlm.NewVLMFromLegacyConfig(vlmCfg, s.ollamaService)
|
||||
return model, vlmCfg, err
|
||||
}
|
||||
|
||||
// resolveFileServiceForPayload resolves tenant/KB scoped file service for reading provider:// URLs.
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
// CreateKnowledgeFromFile creates a knowledge entry from an uploaded file
|
||||
func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
||||
kbID string, file *multipart.FileHeader, metadata map[string]string, enableMultimodel *bool, customFileName string, tagID string, channel string,
|
||||
processOverrides *types.KnowledgeProcessOverrides,
|
||||
) (*types.Knowledge, error) {
|
||||
logger.Info(ctx, "Start creating knowledge from file")
|
||||
|
||||
@@ -60,62 +61,6 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 检查多模态配置完整性 - 只在图片文件时校验
|
||||
if !IsImageType(getFileType(fileName)) {
|
||||
logger.Info(ctx, "Non-image file with multimodal enabled, skipping COS/VLM validation")
|
||||
} else {
|
||||
// 解析有效 provider:优先 KB 级别(新字段 > 旧字段),其次租户默认
|
||||
provider := kb.GetStorageProvider()
|
||||
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if provider == "" && tenant != nil && tenant.StorageEngineConfig != nil {
|
||||
provider = strings.ToLower(strings.TrimSpace(tenant.StorageEngineConfig.DefaultProvider))
|
||||
}
|
||||
|
||||
// 根据 provider 校验租户级存储引擎配置
|
||||
switch provider {
|
||||
case "cos":
|
||||
if tenant == nil || tenant.StorageEngineConfig == nil || tenant.StorageEngineConfig.COS == nil ||
|
||||
tenant.StorageEngineConfig.COS.SecretID == "" || tenant.StorageEngineConfig.COS.SecretKey == "" ||
|
||||
tenant.StorageEngineConfig.COS.Region == "" || tenant.StorageEngineConfig.COS.BucketName == "" {
|
||||
logger.Error(ctx, "COS configuration incomplete for image multimodal processing")
|
||||
return nil, werrors.NewBadRequestError("上传图片文件需要完整的对象存储配置信息, 请前往知识库存储设置或系统设置页面进行补全")
|
||||
}
|
||||
case "minio":
|
||||
ok := false
|
||||
if tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.MinIO != nil {
|
||||
m := tenant.StorageEngineConfig.MinIO
|
||||
if m.Mode == "remote" {
|
||||
ok = m.Endpoint != "" && m.AccessKeyID != "" && m.SecretAccessKey != "" && m.BucketName != ""
|
||||
} else {
|
||||
ok = os.Getenv("MINIO_ENDPOINT") != "" && os.Getenv("MINIO_ACCESS_KEY_ID") != "" &&
|
||||
os.Getenv("MINIO_SECRET_ACCESS_KEY") != "" &&
|
||||
(m.BucketName != "" || os.Getenv("MINIO_BUCKET_NAME") != "")
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
logger.Error(ctx, "MinIO configuration incomplete for image multimodal processing")
|
||||
return nil, werrors.NewBadRequestError("上传图片文件需要完整的对象存储配置信息, 请前往知识库存储设置或系统设置页面进行补全")
|
||||
}
|
||||
}
|
||||
|
||||
// 检查VLM配置
|
||||
if !kb.VLMConfig.Enabled || kb.VLMConfig.ModelID == "" {
|
||||
logger.Error(ctx, "VLM model is not configured")
|
||||
return nil, werrors.NewBadRequestError("上传图片文件需要设置VLM模型")
|
||||
}
|
||||
|
||||
logger.Info(ctx, "Image multimodal configuration validation passed")
|
||||
}
|
||||
|
||||
// 检查音频ASR配置完整性 - 只在音频文件时校验
|
||||
if IsAudioType(getFileType(fileName)) {
|
||||
if !kb.ASRConfig.IsASREnabled() {
|
||||
logger.Error(ctx, "ASR model is not configured")
|
||||
return nil, werrors.NewBadRequestError("上传音频文件需要设置ASR语音识别模型")
|
||||
}
|
||||
logger.Info(ctx, "Audio ASR configuration validation passed")
|
||||
}
|
||||
|
||||
// Validate file type
|
||||
logger.Infof(ctx, "Checking file type: %s", fileName)
|
||||
if !isValidFileType(fileName) {
|
||||
@@ -179,6 +124,64 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
||||
return nil, werrors.NewValidationError("文件名包含非法字符")
|
||||
}
|
||||
|
||||
eff := ResolveProcessConfig(kb, processOverrides)
|
||||
if enableMultimodel != nil && (processOverrides == nil || processOverrides.EnableMultimodel == nil) {
|
||||
eff.EnableMultimodel = *enableMultimodel
|
||||
}
|
||||
|
||||
if processOverrides != nil {
|
||||
if err := ValidateProcessOverrides(ctx, kb, processOverrides, []string{getFileType(safeFilename)}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
// 检查多模态配置完整性 - 只在图片文件时校验
|
||||
if IsImageType(getFileType(safeFilename)) {
|
||||
provider := kb.GetStorageProvider()
|
||||
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if provider == "" && tenant != nil && tenant.StorageEngineConfig != nil {
|
||||
provider = strings.ToLower(strings.TrimSpace(tenant.StorageEngineConfig.DefaultProvider))
|
||||
}
|
||||
|
||||
switch provider {
|
||||
case "cos":
|
||||
if tenant == nil || tenant.StorageEngineConfig == nil || tenant.StorageEngineConfig.COS == nil ||
|
||||
tenant.StorageEngineConfig.COS.SecretID == "" || tenant.StorageEngineConfig.COS.SecretKey == "" ||
|
||||
tenant.StorageEngineConfig.COS.Region == "" || tenant.StorageEngineConfig.COS.BucketName == "" {
|
||||
logger.Error(ctx, "COS configuration incomplete for image multimodal processing")
|
||||
return nil, werrors.NewBadRequestError("上传图片文件需要完整的对象存储配置信息, 请前往知识库存储设置或系统设置页面进行补全")
|
||||
}
|
||||
case "minio":
|
||||
ok := false
|
||||
if tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.MinIO != nil {
|
||||
m := tenant.StorageEngineConfig.MinIO
|
||||
if m.Mode == "remote" {
|
||||
ok = m.Endpoint != "" && m.AccessKeyID != "" && m.SecretAccessKey != "" && m.BucketName != ""
|
||||
} else {
|
||||
ok = os.Getenv("MINIO_ENDPOINT") != "" && os.Getenv("MINIO_ACCESS_KEY_ID") != "" &&
|
||||
os.Getenv("MINIO_SECRET_ACCESS_KEY") != "" &&
|
||||
(m.BucketName != "" || os.Getenv("MINIO_BUCKET_NAME") != "")
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
logger.Error(ctx, "MinIO configuration incomplete for image multimodal processing")
|
||||
return nil, werrors.NewBadRequestError("上传图片文件需要完整的对象存储配置信息, 请前往知识库存储设置或系统设置页面进行补全")
|
||||
}
|
||||
}
|
||||
|
||||
if !kb.VLMConfig.Enabled || kb.VLMConfig.ModelID == "" {
|
||||
logger.Error(ctx, "VLM model is not configured")
|
||||
return nil, werrors.NewBadRequestError("上传图片文件需要设置VLM模型")
|
||||
}
|
||||
}
|
||||
|
||||
if IsAudioType(getFileType(safeFilename)) {
|
||||
if !kb.ASRConfig.IsASREnabled() {
|
||||
logger.Error(ctx, "ASR model is not configured")
|
||||
return nil, werrors.NewBadRequestError("上传音频文件需要设置ASR语音识别模型")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare knowledge record
|
||||
logger.Info(ctx, "Preparing knowledge record")
|
||||
knowledge := &types.Knowledge{
|
||||
@@ -201,6 +204,13 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
||||
Metadata: metadataJSON,
|
||||
}
|
||||
|
||||
if processOverrides != nil {
|
||||
if err := knowledge.SetProcessOverrides(processOverrides); err != nil {
|
||||
logger.Errorf(ctx, "Failed to set process overrides: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Save the file to storage (use KB-level storage engine if configured)
|
||||
logger.Infof(ctx, "Saving file, knowledge ID: %s", knowledge.ID)
|
||||
fileSvc := s.resolveFileService(ctx, kb)
|
||||
@@ -223,21 +233,12 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
||||
|
||||
// Enqueue document processing task to Asynq
|
||||
logger.Info(ctx, "Enqueuing document processing task to Asynq")
|
||||
enableMultimodelValue := false
|
||||
if enableMultimodel != nil {
|
||||
enableMultimodelValue = *enableMultimodel
|
||||
} else {
|
||||
enableMultimodelValue = kb.IsMultimodalEnabled()
|
||||
}
|
||||
enableMultimodelValue := eff.EnableMultimodel
|
||||
|
||||
// Check question generation config
|
||||
enableQuestionGeneration := false
|
||||
questionCount := 3 // default
|
||||
if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled {
|
||||
enableQuestionGeneration = true
|
||||
if kb.QuestionGenerationConfig.QuestionCount > 0 {
|
||||
questionCount = kb.QuestionGenerationConfig.QuestionCount
|
||||
}
|
||||
enableQuestionGeneration := eff.QuestionGenerationConfig.Enabled
|
||||
questionCount := eff.QuestionGenerationConfig.QuestionCount
|
||||
if questionCount <= 0 {
|
||||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
@@ -307,13 +308,16 @@ func isFileURL(rawURL, fileName, fileType string) bool {
|
||||
|
||||
func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context,
|
||||
kbID string, rawURL string, fileName string, fileType string, enableMultimodel *bool, title string, tagID string, channel string,
|
||||
processOverrides *types.KnowledgeProcessOverrides,
|
||||
) (*types.Knowledge, error) {
|
||||
logger.Info(ctx, "Start creating knowledge from URL")
|
||||
logger.Infof(ctx, "Knowledge base ID: %s, URL: %s", kbID, rawURL)
|
||||
|
||||
// Route to file_url logic when the URL points to a downloadable file
|
||||
if isFileURL(rawURL, fileName, fileType) {
|
||||
return s.createKnowledgeFromFileURL(ctx, kbID, rawURL, fileName, fileType, enableMultimodel, title, tagID, channel)
|
||||
return s.createKnowledgeFromFileURL(
|
||||
ctx, kbID, rawURL, fileName, fileType, enableMultimodel, title, tagID, channel, processOverrides,
|
||||
)
|
||||
}
|
||||
|
||||
url := rawURL
|
||||
@@ -397,6 +401,11 @@ func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context,
|
||||
|
||||
// Save knowledge record
|
||||
logger.Infof(ctx, "Saving knowledge record to database, ID: %s", knowledge.ID)
|
||||
eff, err := ApplyKnowledgeProcessOverrides(ctx, kb, knowledge, processOverrides, []string{"html"}, enableMultimodel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.repo.CreateKnowledge(ctx, knowledge); err != nil {
|
||||
logger.Errorf(ctx, "Failed to create knowledge record: %v", err)
|
||||
return nil, err
|
||||
@@ -404,21 +413,11 @@ func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context,
|
||||
|
||||
// Enqueue URL processing task to Asynq
|
||||
logger.Info(ctx, "Enqueuing URL processing task to Asynq")
|
||||
enableMultimodelValue := false
|
||||
if enableMultimodel != nil {
|
||||
enableMultimodelValue = *enableMultimodel
|
||||
} else {
|
||||
enableMultimodelValue = kb.IsMultimodalEnabled()
|
||||
}
|
||||
|
||||
// Check question generation config
|
||||
enableQuestionGeneration := false
|
||||
questionCount := 3 // default
|
||||
if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled {
|
||||
enableQuestionGeneration = true
|
||||
if kb.QuestionGenerationConfig.QuestionCount > 0 {
|
||||
questionCount = kb.QuestionGenerationConfig.QuestionCount
|
||||
}
|
||||
enableMultimodelValue := eff.EnableMultimodel
|
||||
enableQuestionGeneration := eff.QuestionGenerationConfig.Enabled
|
||||
questionCount := eff.QuestionGenerationConfig.QuestionCount
|
||||
if questionCount <= 0 {
|
||||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
@@ -515,6 +514,7 @@ func (s *knowledgeService) createKnowledgeFromFileURL(
|
||||
title string,
|
||||
tagID string,
|
||||
channel string,
|
||||
processOverrides *types.KnowledgeProcessOverrides,
|
||||
) (*types.Knowledge, error) {
|
||||
logger.Info(ctx, "Start creating knowledge from file URL")
|
||||
logger.Infof(ctx, "Knowledge base ID: %s, file URL: %s", kbID, fileURL)
|
||||
@@ -624,26 +624,32 @@ func (s *knowledgeService) createKnowledgeFromFileURL(
|
||||
knowledge.Title = displayName
|
||||
}
|
||||
|
||||
resolvedFileType := fileType
|
||||
if resolvedFileType == "" && fileName != "" {
|
||||
resolvedFileType = getFileType(fileName)
|
||||
}
|
||||
if resolvedFileType == "" {
|
||||
resolvedFileType = getFileType(extractFileNameFromURL(fileURL))
|
||||
}
|
||||
|
||||
eff, err := ApplyKnowledgeProcessOverrides(
|
||||
ctx, kb, knowledge, processOverrides, []string{resolvedFileType}, enableMultimodel,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.repo.CreateKnowledge(ctx, knowledge); err != nil {
|
||||
logger.Errorf(ctx, "Failed to create knowledge record: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Build async task payload
|
||||
enableMultimodelValue := false
|
||||
if enableMultimodel != nil {
|
||||
enableMultimodelValue = *enableMultimodel
|
||||
} else {
|
||||
enableMultimodelValue = kb.IsMultimodalEnabled()
|
||||
}
|
||||
|
||||
enableQuestionGeneration := false
|
||||
questionCount := 3
|
||||
if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled {
|
||||
enableQuestionGeneration = true
|
||||
if kb.QuestionGenerationConfig.QuestionCount > 0 {
|
||||
questionCount = kb.QuestionGenerationConfig.QuestionCount
|
||||
}
|
||||
enableMultimodelValue := eff.EnableMultimodel
|
||||
enableQuestionGeneration := eff.QuestionGenerationConfig.Enabled
|
||||
questionCount := eff.QuestionGenerationConfig.QuestionCount
|
||||
if questionCount <= 0 {
|
||||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
@@ -775,6 +781,12 @@ func (s *knowledgeService) CreateKnowledgeFromManual(ctx context.Context,
|
||||
knowledge.ParseStatus = "pending"
|
||||
}
|
||||
|
||||
if status == types.ManualKnowledgeStatusPublish {
|
||||
if _, err := ApplyKnowledgeProcessOverrides(ctx, kb, knowledge, payload.ProcessConfig, nil, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.repo.CreateKnowledge(ctx, knowledge); err != nil {
|
||||
logger.Errorf(ctx, "Failed to create manual knowledge record: %v", err)
|
||||
return nil, err
|
||||
@@ -998,6 +1010,10 @@ func (s *knowledgeService) UpdateManualKnowledge(ctx context.Context,
|
||||
existing.Description = ""
|
||||
existing.ProcessedAt = nil
|
||||
|
||||
if _, err := ApplyKnowledgeProcessOverrides(ctx, kb, existing, payload.ProcessConfig, nil, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.repo.UpdateKnowledge(ctx, existing); err != nil {
|
||||
logger.Errorf(ctx, "Failed to persist manual knowledge before indexing: %v", err)
|
||||
return nil, err
|
||||
@@ -1101,26 +1117,27 @@ func (s *knowledgeService) triggerManualProcessing(ctx context.Context,
|
||||
}
|
||||
}
|
||||
|
||||
processOverrides, _ := knowledge.ProcessOverrides()
|
||||
eff := ResolveProcessConfig(kb, processOverrides)
|
||||
|
||||
// Manual content is markdown - chunk directly with Go chunker
|
||||
chunkCfg := buildSplitterConfig(kb)
|
||||
chunkCfg := buildSplitterConfigFromChunking(eff.ChunkingConfig)
|
||||
|
||||
var parsed []types.ParsedChunk
|
||||
opts := ProcessChunksOptions{
|
||||
// When the KB has VLM enabled and we resolved remote images, pass them
|
||||
// through so processChunks will enqueue image:multimodal tasks (OCR + caption).
|
||||
EnableMultimodel: kb.IsMultimodalEnabled() && len(resolvedImages) > 0,
|
||||
EnableMultimodel: eff.EnableMultimodel && len(resolvedImages) > 0,
|
||||
StoredImages: resolvedImages,
|
||||
}
|
||||
if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled {
|
||||
if eff.QuestionGenerationConfig.Enabled {
|
||||
opts.EnableQuestionGeneration = true
|
||||
opts.QuestionCount = kb.QuestionGenerationConfig.QuestionCount
|
||||
opts.QuestionCount = eff.QuestionGenerationConfig.QuestionCount
|
||||
if opts.QuestionCount <= 0 {
|
||||
opts.QuestionCount = 3
|
||||
}
|
||||
}
|
||||
|
||||
if kb.ChunkingConfig.EnableParentChild {
|
||||
parentCfg, childCfg := buildParentChildConfigs(kb.ChunkingConfig, chunkCfg)
|
||||
if eff.ChunkingConfig.EnableParentChild {
|
||||
parentCfg, childCfg := buildParentChildConfigs(eff.ChunkingConfig, chunkCfg)
|
||||
pcResult := chunker.SplitParentChild(clean, parentCfg, childCfg)
|
||||
parsed = make([]types.ParsedChunk, len(pcResult.Children))
|
||||
for i, c := range pcResult.Children {
|
||||
|
||||
@@ -138,6 +138,7 @@ func TestCreateKnowledgeFromFileDoesNotPersistWhenStorageSaveFails(t *testing.T)
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
nil,
|
||||
)
|
||||
|
||||
require.Error(t, err)
|
||||
@@ -168,6 +169,7 @@ func TestCreateKnowledgeFromFilePersistsStoredFilePathOnCreate(t *testing.T) {
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
nil,
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
@@ -201,6 +203,7 @@ func TestCreateKnowledgeFromFileDeletesStoredFileWhenCreateFails(t *testing.T) {
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
nil,
|
||||
)
|
||||
|
||||
require.EqualError(t, err, "database unavailable")
|
||||
@@ -211,6 +214,52 @@ func TestCreateKnowledgeFromFileDeletesStoredFileWhenCreateFails(t *testing.T) {
|
||||
require.Equal(t, "stored/"+fileSvc.savedWithKnowledgeID, fileSvc.deletedPath)
|
||||
}
|
||||
|
||||
func TestCreateKnowledgeFromFile_PersistsProcessOverrides(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
repo := &createKnowledgeFileRepoStub{}
|
||||
fileSvc := &createKnowledgeFileServiceStub{}
|
||||
task := &createKnowledgeTaskEnqueuerStub{}
|
||||
svc := &knowledgeService{
|
||||
repo: repo,
|
||||
kbService: &createKnowledgeFileKBServiceStub{kb: &types.KnowledgeBase{ID: "kb-1"}},
|
||||
fileSvc: fileSvc,
|
||||
task: task,
|
||||
}
|
||||
|
||||
chunkSize := 512
|
||||
overrides := &types.KnowledgeProcessOverrides{
|
||||
ChunkingConfig: &types.ChunkingConfig{ChunkSize: chunkSize},
|
||||
}
|
||||
|
||||
knowledge, err := svc.CreateKnowledgeFromFile(
|
||||
newCreateKnowledgeFileContext(),
|
||||
"kb-1",
|
||||
newMultipartFileHeader(t, "doc.txt", "hello"),
|
||||
map[string]string{"source": "test"},
|
||||
nil,
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
overrides,
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, knowledge)
|
||||
require.Equal(t, 1, repo.createCalls)
|
||||
require.NotNil(t, repo.createdKnowledge)
|
||||
|
||||
parsed, err := repo.createdKnowledge.ProcessOverrides()
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, parsed)
|
||||
require.NotNil(t, parsed.ChunkingConfig)
|
||||
require.Equal(t, chunkSize, parsed.ChunkingConfig.ChunkSize)
|
||||
|
||||
metadataMap, err := repo.createdKnowledge.Metadata.Map()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "test", metadataMap["source"])
|
||||
}
|
||||
|
||||
func newCreateKnowledgeFileContext() context.Context {
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
|
||||
ctx = context.WithValue(ctx, types.TenantInfoContextKey, &types.Tenant{})
|
||||
|
||||
@@ -124,6 +124,9 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
||||
return fmt.Errorf("get knowledge base %s: %w", payload.KnowledgeBaseID, err)
|
||||
}
|
||||
|
||||
processOverrides, _ := knowledge.ProcessOverrides()
|
||||
eff := ResolveProcessConfig(kb, processOverrides)
|
||||
|
||||
// 2. Fetch all chunks
|
||||
chunks, err := s.chunkService.ListChunksByKnowledgeID(ctx, payload.KnowledgeID)
|
||||
if err != nil {
|
||||
@@ -155,7 +158,7 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
||||
// drains is bounded by the housekeeping finalizing sweep.
|
||||
willSpawnSummary := len(textChunks) > 0
|
||||
willSpawnQuestion := willSpawnSummary && kb.NeedsEmbeddingModel() &&
|
||||
kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled
|
||||
eff.QuestionGenerationConfig.Enabled
|
||||
willSpawnWiki := kb.IndexingStrategy.WikiEnabled && len(textChunks) > 0
|
||||
|
||||
// Question generation now fans out one subtask per plain text chunk
|
||||
@@ -184,7 +187,7 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
||||
questionBatchCount := (len(questionChunks) + questionGenChunkBatchSize - 1) / questionGenChunkBatchSize
|
||||
|
||||
graphChunkCount := 0
|
||||
if kb.IsGraphEnabled() {
|
||||
if eff.GraphEnabled {
|
||||
graphChunkCount = len(textChunks)
|
||||
}
|
||||
expectedSubtasks := 0
|
||||
@@ -302,7 +305,7 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
||||
"chunk_count": len(questionChunks),
|
||||
})
|
||||
}
|
||||
enqueuedQuestionCount = s.enqueueQuestionGenerationTasks(ctx, payload, kb, attempt, questionChunks)
|
||||
enqueuedQuestionCount = s.enqueueQuestionGenerationTasks(ctx, payload, eff.QuestionGenerationConfig, attempt, questionChunks)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -466,18 +469,18 @@ const postprocessQuestionGroupSpanName = "postprocess.question"
|
||||
func (s *KnowledgePostProcessService) enqueueQuestionGenerationTasks(
|
||||
ctx context.Context,
|
||||
payload types.KnowledgePostProcessPayload,
|
||||
kb *types.KnowledgeBase,
|
||||
qg types.QuestionGenerationConfig,
|
||||
attempt int,
|
||||
questionChunks []*types.Chunk,
|
||||
) int {
|
||||
if s.taskEnqueuer == nil || len(questionChunks) == 0 {
|
||||
return 0
|
||||
}
|
||||
if kb.QuestionGenerationConfig == nil || !kb.QuestionGenerationConfig.Enabled {
|
||||
if !qg.Enabled {
|
||||
return 0
|
||||
}
|
||||
|
||||
questionCount := kb.QuestionGenerationConfig.QuestionCount
|
||||
questionCount := qg.QuestionCount
|
||||
if questionCount <= 0 {
|
||||
questionCount = 3
|
||||
}
|
||||
|
||||
@@ -201,13 +201,17 @@ func finalizeIndexedKnowledgeState(
|
||||
// identical whether callers come through this path or invoke the chunker
|
||||
// directly with a zero-value config.
|
||||
func buildSplitterConfig(kb *types.KnowledgeBase) chunker.SplitterConfig {
|
||||
return buildSplitterConfigFromChunking(kb.ChunkingConfig)
|
||||
}
|
||||
|
||||
func buildSplitterConfigFromChunking(cc types.ChunkingConfig) chunker.SplitterConfig {
|
||||
chunkCfg := chunker.SplitterConfig{
|
||||
ChunkSize: kb.ChunkingConfig.ChunkSize,
|
||||
ChunkOverlap: kb.ChunkingConfig.ChunkOverlap,
|
||||
Separators: kb.ChunkingConfig.Separators,
|
||||
Strategy: kb.ChunkingConfig.Strategy,
|
||||
TokenLimit: kb.ChunkingConfig.TokenLimit,
|
||||
Languages: kb.ChunkingConfig.Languages,
|
||||
ChunkSize: cc.ChunkSize,
|
||||
ChunkOverlap: cc.ChunkOverlap,
|
||||
Separators: cc.Separators,
|
||||
Strategy: cc.Strategy,
|
||||
TokenLimit: cc.TokenLimit,
|
||||
Languages: cc.Languages,
|
||||
}
|
||||
if chunkCfg.ChunkSize <= 0 {
|
||||
chunkCfg.ChunkSize = chunker.DefaultChunkSize
|
||||
@@ -1973,6 +1977,9 @@ func (s *knowledgeService) ReparseKnowledge(ctx context.Context, knowledgeID str
|
||||
return nil, err
|
||||
}
|
||||
|
||||
processOverrides, _ := existing.ProcessOverrides()
|
||||
reparseEff := ResolveProcessConfig(kb, processOverrides)
|
||||
|
||||
// Keep wiki's pending queue consistent across both manual and non-manual
|
||||
// paths. The destructive work (swapping old wiki contributions for new)
|
||||
// happens asynchronously inside mapOneDocument — see its oldPageSlugs
|
||||
@@ -2060,17 +2067,11 @@ func (s *knowledgeService) ReparseKnowledge(ctx context.Context, knowledgeID str
|
||||
if existing.FilePath != "" {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
|
||||
// Determine multimodal setting
|
||||
enableMultimodel := kb.IsMultimodalEnabled()
|
||||
|
||||
// Check question generation config
|
||||
enableQuestionGeneration := false
|
||||
questionCount := 3 // default
|
||||
if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled {
|
||||
enableQuestionGeneration = true
|
||||
if kb.QuestionGenerationConfig.QuestionCount > 0 {
|
||||
questionCount = kb.QuestionGenerationConfig.QuestionCount
|
||||
}
|
||||
enableMultimodel := reparseEff.EnableMultimodel
|
||||
enableQuestionGeneration := reparseEff.QuestionGenerationConfig.Enabled
|
||||
questionCount := reparseEff.QuestionGenerationConfig.QuestionCount
|
||||
if questionCount <= 0 {
|
||||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
@@ -2119,16 +2120,11 @@ func (s *knowledgeService) ReparseKnowledge(ctx context.Context, knowledgeID str
|
||||
if existing.Type == "file_url" && existing.Source != "" {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
|
||||
enableMultimodel := kb.IsMultimodalEnabled()
|
||||
|
||||
// Check question generation config
|
||||
enableQuestionGeneration := false
|
||||
questionCount := 3
|
||||
if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled {
|
||||
enableQuestionGeneration = true
|
||||
if kb.QuestionGenerationConfig.QuestionCount > 0 {
|
||||
questionCount = kb.QuestionGenerationConfig.QuestionCount
|
||||
}
|
||||
enableMultimodel := reparseEff.EnableMultimodel
|
||||
enableQuestionGeneration := reparseEff.QuestionGenerationConfig.Enabled
|
||||
questionCount := reparseEff.QuestionGenerationConfig.QuestionCount
|
||||
if questionCount <= 0 {
|
||||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
@@ -2172,16 +2168,11 @@ func (s *knowledgeService) ReparseKnowledge(ctx context.Context, knowledgeID str
|
||||
if existing.Type == "url" && existing.Source != "" {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
|
||||
enableMultimodel := kb.IsMultimodalEnabled()
|
||||
|
||||
// Check question generation config
|
||||
enableQuestionGeneration := false
|
||||
questionCount := 3
|
||||
if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled {
|
||||
enableQuestionGeneration = true
|
||||
if kb.QuestionGenerationConfig.QuestionCount > 0 {
|
||||
questionCount = kb.QuestionGenerationConfig.QuestionCount
|
||||
}
|
||||
enableMultimodel := reparseEff.EnableMultimodel
|
||||
enableQuestionGeneration := reparseEff.QuestionGenerationConfig.Enabled
|
||||
questionCount := reparseEff.QuestionGenerationConfig.QuestionCount
|
||||
if questionCount <= 0 {
|
||||
questionCount = 3
|
||||
}
|
||||
|
||||
lang, _ := types.LanguageFromContext(ctx)
|
||||
@@ -2734,6 +2725,9 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
return nil
|
||||
}
|
||||
|
||||
processOverrides, _ := knowledge.ProcessOverrides()
|
||||
eff := ResolveProcessConfig(kb, processOverrides)
|
||||
|
||||
// Re-check abort status right before flipping to "processing" — closes
|
||||
// the race where the user cancels between the entry guard above and
|
||||
// this write (otherwise the worker would overwrite cancelled→processing
|
||||
@@ -2775,7 +2769,7 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
}
|
||||
|
||||
// 检查音频ASR配置(仅对文件导入)
|
||||
if payload.FilePath != "" && IsAudioType(payload.FileType) && !kb.ASRConfig.IsASREnabled() {
|
||||
if payload.FilePath != "" && IsAudioType(payload.FileType) && !eff.ASRConfig.IsASREnabled() {
|
||||
logger.GetLogger(ctx).WithField("knowledge_id", knowledge.ID).
|
||||
Errorf("processDocument audio without ASR model configured")
|
||||
knowledge.ParseStatus = "failed"
|
||||
@@ -2857,7 +2851,7 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
payload.FilePath = filePath
|
||||
payload.FileName = resolvedFileName
|
||||
payload.FileType = resolvedFileType
|
||||
convertResult, err = s.convert(ctx, payload, kb, knowledge, isLastRetry)
|
||||
convertResult, err = s.convert(ctx, payload, kb, knowledge, eff, isLastRetry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -2866,7 +2860,7 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
}
|
||||
} else if payload.URL != "" {
|
||||
// URL import
|
||||
convertResult, err = s.convert(ctx, payload, kb, knowledge, isLastRetry)
|
||||
convertResult, err = s.convert(ctx, payload, kb, knowledge, eff, isLastRetry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -2910,7 +2904,7 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
return nil
|
||||
} else {
|
||||
// File import
|
||||
convertResult, err = s.convert(ctx, payload, kb, knowledge, isLastRetry)
|
||||
convertResult, err = s.convert(ctx, payload, kb, knowledge, eff, isLastRetry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -2921,7 +2915,7 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
|
||||
// Step 1.5: ASR transcription for audio files
|
||||
if convertResult != nil && convertResult.IsAudio && len(convertResult.AudioData) > 0 {
|
||||
if !kb.ASRConfig.IsASREnabled() {
|
||||
if !eff.ASRConfig.IsASREnabled() {
|
||||
logger.Error(ctx, "Audio file detected but ASR is not configured")
|
||||
knowledge.ParseStatus = "failed"
|
||||
knowledge.ErrorMessage = "ASR model is not configured for audio transcription"
|
||||
@@ -2933,7 +2927,7 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
logger.Infof(ctx, "[ASR] Starting audio transcription for knowledge %s, audio size=%d bytes",
|
||||
knowledge.ID, len(convertResult.AudioData))
|
||||
|
||||
asrModel, err := s.modelService.GetASRModel(ctx, kb.ASRConfig.ModelID)
|
||||
asrModel, err := s.modelService.GetASRModel(ctx, eff.ASRConfig.ModelID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[ASR] Failed to get ASR model: %v", err)
|
||||
knowledge.ParseStatus = "failed"
|
||||
@@ -3003,7 +2997,7 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
}
|
||||
|
||||
// Step 3: Split into chunks using Go chunker
|
||||
chunkCfg := buildSplitterConfig(kb)
|
||||
chunkCfg := buildSplitterConfigFromChunking(eff.ChunkingConfig)
|
||||
|
||||
processOpts := ProcessChunksOptions{
|
||||
EnableQuestionGeneration: payload.EnableQuestionGeneration,
|
||||
@@ -3016,8 +3010,8 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
processOpts.Metadata = convertResult.Metadata
|
||||
}
|
||||
|
||||
if kb.ChunkingConfig.EnableParentChild {
|
||||
parentCfg, childCfg := buildParentChildConfigs(kb.ChunkingConfig, chunkCfg)
|
||||
if eff.ChunkingConfig.EnableParentChild {
|
||||
parentCfg, childCfg := buildParentChildConfigs(eff.ChunkingConfig, chunkCfg)
|
||||
pcResult := chunker.SplitParentChild(convertResult.MarkdownContent, parentCfg, childCfg)
|
||||
chunks = make([]types.ParsedChunk, len(pcResult.Children))
|
||||
for i, c := range pcResult.Children {
|
||||
@@ -3064,6 +3058,7 @@ func (s *knowledgeService) convert(
|
||||
payload types.DocumentProcessPayload,
|
||||
kb *types.KnowledgeBase,
|
||||
knowledge *types.Knowledge,
|
||||
eff types.EffectiveProcessConfig,
|
||||
isLastRetry bool,
|
||||
) (*types.ReadResult, error) {
|
||||
// Stage tracking: docreader. Mark the stage as running here so the
|
||||
@@ -3097,13 +3092,13 @@ func (s *knowledgeService) convert(
|
||||
}
|
||||
}
|
||||
|
||||
parserEngine := kb.ChunkingConfig.ResolveParserEngine(fileType)
|
||||
parserEngine := eff.ChunkingConfig.ResolveParserEngine(fileType)
|
||||
if isURL {
|
||||
parserEngine = kb.ChunkingConfig.ResolveParserEngine("url")
|
||||
parserEngine = eff.ChunkingConfig.ResolveParserEngine("url")
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[convert] kb=%s fileType=%s isURL=%v engine=%q rules=%+v",
|
||||
kb.ID, fileType, isURL, parserEngine, kb.ChunkingConfig.ParserEngineRules)
|
||||
kb.ID, fileType, isURL, parserEngine, eff.ChunkingConfig.ParserEngineRules)
|
||||
|
||||
var reader interfaces.DocReader = s.resolveDocReader(ctx, parserEngine, fileType, isURL, overrides)
|
||||
if reader == nil {
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
werrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ResolveProcessConfig merges KB defaults with per-upload overrides for the parse pipeline.
|
||||
func ResolveProcessConfig(kb *types.KnowledgeBase, overrides *types.KnowledgeProcessOverrides) types.EffectiveProcessConfig {
|
||||
eff := types.EffectiveProcessConfig{
|
||||
ChunkingConfig: kb.ChunkingConfig,
|
||||
EnableMultimodel: kb.IsMultimodalEnabled(),
|
||||
VLMConfig: kb.VLMConfig,
|
||||
ASRConfig: kb.ASRConfig,
|
||||
QuestionGenerationConfig: defaultQuestionGenerationConfig(kb),
|
||||
GraphEnabled: kb.IsGraphEnabled(),
|
||||
ExtractConfig: derefExtractConfig(kb.ExtractConfig),
|
||||
}
|
||||
if overrides == nil {
|
||||
return eff
|
||||
}
|
||||
|
||||
if overrides.ChunkingConfig != nil {
|
||||
eff.ChunkingConfig = mergeChunkingConfig(eff.ChunkingConfig, overrides.ChunkingConfig)
|
||||
}
|
||||
if len(overrides.ParserEngineRules) > 0 {
|
||||
eff.ChunkingConfig.ParserEngineRules = overrides.ParserEngineRules
|
||||
}
|
||||
if overrides.EnableMultimodel != nil {
|
||||
eff.EnableMultimodel = *overrides.EnableMultimodel
|
||||
}
|
||||
if overrides.VLMConfig != nil {
|
||||
eff.VLMConfig = *overrides.VLMConfig
|
||||
}
|
||||
if overrides.ASRConfig != nil {
|
||||
eff.ASRConfig = *overrides.ASRConfig
|
||||
}
|
||||
if overrides.QuestionGenerationConfig != nil {
|
||||
eff.QuestionGenerationConfig = *overrides.QuestionGenerationConfig
|
||||
}
|
||||
if overrides.GraphEnabled != nil {
|
||||
eff.GraphEnabled = *overrides.GraphEnabled
|
||||
}
|
||||
if overrides.ExtractConfig != nil {
|
||||
eff.ExtractConfig = mergeExtractConfig(eff.ExtractConfig, overrides.ExtractConfig)
|
||||
}
|
||||
|
||||
return eff
|
||||
}
|
||||
|
||||
// ValidateProcessOverrides validates batch overrides against file types in the upload.
|
||||
func ValidateProcessOverrides(
|
||||
ctx context.Context,
|
||||
kb *types.KnowledgeBase,
|
||||
overrides *types.KnowledgeProcessOverrides,
|
||||
fileTypes []string,
|
||||
) error {
|
||||
if overrides == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
hasImage := false
|
||||
hasAudio := false
|
||||
for _, ft := range fileTypes {
|
||||
if IsImageType(ft) {
|
||||
hasImage = true
|
||||
}
|
||||
if IsAudioType(ft) {
|
||||
hasAudio = true
|
||||
}
|
||||
}
|
||||
|
||||
eff := ResolveProcessConfig(kb, overrides)
|
||||
|
||||
if hasImage {
|
||||
if err := validateImageMultimodalConfig(ctx, kb); err != nil {
|
||||
return err
|
||||
}
|
||||
if !eff.VLMConfig.IsEnabled() {
|
||||
return werrors.NewBadRequestError("上传图片文件需要设置VLM模型")
|
||||
}
|
||||
}
|
||||
|
||||
if hasAudio && !eff.ASRConfig.IsASREnabled() {
|
||||
return werrors.NewBadRequestError("上传音频文件需要设置ASR语音识别模型")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplyKnowledgeProcessOverrides validates optional overrides, persists them on the
|
||||
// knowledge record, and returns the effective config for task enqueue.
|
||||
func ApplyKnowledgeProcessOverrides(
|
||||
ctx context.Context,
|
||||
kb *types.KnowledgeBase,
|
||||
knowledge *types.Knowledge,
|
||||
processOverrides *types.KnowledgeProcessOverrides,
|
||||
fileTypes []string,
|
||||
enableMultimodel *bool,
|
||||
) (types.EffectiveProcessConfig, error) {
|
||||
eff := ResolveProcessConfig(kb, processOverrides)
|
||||
if enableMultimodel != nil && (processOverrides == nil || processOverrides.EnableMultimodel == nil) {
|
||||
eff.EnableMultimodel = *enableMultimodel
|
||||
}
|
||||
if processOverrides == nil {
|
||||
return eff, nil
|
||||
}
|
||||
if err := ValidateProcessOverrides(ctx, kb, processOverrides, fileTypes); err != nil {
|
||||
return eff, err
|
||||
}
|
||||
if err := knowledge.SetProcessOverrides(processOverrides); err != nil {
|
||||
return eff, err
|
||||
}
|
||||
return eff, nil
|
||||
}
|
||||
|
||||
func defaultQuestionGenerationConfig(kb *types.KnowledgeBase) types.QuestionGenerationConfig {
|
||||
if kb == nil || kb.QuestionGenerationConfig == nil {
|
||||
return types.QuestionGenerationConfig{}
|
||||
}
|
||||
return *kb.QuestionGenerationConfig
|
||||
}
|
||||
|
||||
func derefExtractConfig(cfg *types.ExtractConfig) types.ExtractConfig {
|
||||
if cfg == nil {
|
||||
return types.ExtractConfig{}
|
||||
}
|
||||
return *cfg
|
||||
}
|
||||
|
||||
func mergeChunkingConfig(base types.ChunkingConfig, override *types.ChunkingConfig) types.ChunkingConfig {
|
||||
if override == nil {
|
||||
return base
|
||||
}
|
||||
result := base
|
||||
if override.ChunkSize != 0 {
|
||||
result.ChunkSize = override.ChunkSize
|
||||
}
|
||||
if override.ChunkOverlap != 0 {
|
||||
result.ChunkOverlap = override.ChunkOverlap
|
||||
}
|
||||
if len(override.Separators) > 0 {
|
||||
result.Separators = override.Separators
|
||||
}
|
||||
if override.EnableMultimodal {
|
||||
result.EnableMultimodal = override.EnableMultimodal
|
||||
}
|
||||
if len(override.ParserEngineRules) > 0 {
|
||||
result.ParserEngineRules = override.ParserEngineRules
|
||||
}
|
||||
if override.EnableParentChild {
|
||||
result.EnableParentChild = override.EnableParentChild
|
||||
}
|
||||
if override.ParentChunkSize != 0 {
|
||||
result.ParentChunkSize = override.ParentChunkSize
|
||||
}
|
||||
if override.ChildChunkSize != 0 {
|
||||
result.ChildChunkSize = override.ChildChunkSize
|
||||
}
|
||||
if override.Strategy != "" {
|
||||
result.Strategy = override.Strategy
|
||||
}
|
||||
if override.TokenLimit != 0 {
|
||||
result.TokenLimit = override.TokenLimit
|
||||
}
|
||||
if len(override.Languages) > 0 {
|
||||
result.Languages = override.Languages
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func mergeExtractConfig(base types.ExtractConfig, override *types.ExtractConfig) types.ExtractConfig {
|
||||
if override == nil {
|
||||
return base
|
||||
}
|
||||
result := base
|
||||
if override.Enabled {
|
||||
result.Enabled = true
|
||||
}
|
||||
if override.Text != "" {
|
||||
result.Text = override.Text
|
||||
}
|
||||
if len(override.Tags) > 0 {
|
||||
result.Tags = override.Tags
|
||||
}
|
||||
if len(override.Nodes) > 0 {
|
||||
result.Nodes = override.Nodes
|
||||
}
|
||||
if len(override.Relations) > 0 {
|
||||
result.Relations = override.Relations
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func validateImageMultimodalConfig(ctx context.Context, kb *types.KnowledgeBase) error {
|
||||
provider := kb.GetStorageProvider()
|
||||
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if provider == "" && tenant != nil && tenant.StorageEngineConfig != nil {
|
||||
provider = strings.ToLower(strings.TrimSpace(tenant.StorageEngineConfig.DefaultProvider))
|
||||
}
|
||||
|
||||
switch provider {
|
||||
case "cos":
|
||||
if tenant == nil || tenant.StorageEngineConfig == nil || tenant.StorageEngineConfig.COS == nil ||
|
||||
tenant.StorageEngineConfig.COS.SecretID == "" || tenant.StorageEngineConfig.COS.SecretKey == "" ||
|
||||
tenant.StorageEngineConfig.COS.Region == "" || tenant.StorageEngineConfig.COS.BucketName == "" {
|
||||
return werrors.NewBadRequestError("上传图片文件需要完整的对象存储配置信息, 请前往知识库存储设置或系统设置页面进行补全")
|
||||
}
|
||||
case "minio":
|
||||
ok := false
|
||||
if tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.MinIO != nil {
|
||||
m := tenant.StorageEngineConfig.MinIO
|
||||
if m.Mode == "remote" {
|
||||
ok = m.Endpoint != "" && m.AccessKeyID != "" && m.SecretAccessKey != "" && m.BucketName != ""
|
||||
} else {
|
||||
ok = os.Getenv("MINIO_ENDPOINT") != "" && os.Getenv("MINIO_ACCESS_KEY_ID") != "" &&
|
||||
os.Getenv("MINIO_SECRET_ACCESS_KEY") != "" &&
|
||||
(m.BucketName != "" || os.Getenv("MINIO_BUCKET_NAME") != "")
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
return werrors.NewBadRequestError("上传图片文件需要完整的对象存储配置信息, 请前往知识库存储设置或系统设置页面进行补全")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
werrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func processConfigBoolPtr(v bool) *bool {
|
||||
return &v
|
||||
}
|
||||
|
||||
func testKBWithGraphEnabled(enabled bool) *types.KnowledgeBase {
|
||||
return &types.KnowledgeBase{
|
||||
IndexingStrategy: types.IndexingStrategy{GraphEnabled: enabled},
|
||||
ExtractConfig: &types.ExtractConfig{Enabled: enabled},
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveProcessConfig_OverridesChunkSize(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{
|
||||
ChunkingConfig: types.ChunkingConfig{ChunkSize: 512, ChunkOverlap: 50},
|
||||
}
|
||||
overrides := &types.KnowledgeProcessOverrides{
|
||||
ChunkingConfig: &types.ChunkingConfig{ChunkSize: 2048},
|
||||
}
|
||||
eff := ResolveProcessConfig(kb, overrides)
|
||||
require.Equal(t, 2048, eff.ChunkingConfig.ChunkSize)
|
||||
require.Equal(t, 50, eff.ChunkingConfig.ChunkOverlap)
|
||||
}
|
||||
|
||||
func TestResolveProcessConfig_GraphDisabled(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := testKBWithGraphEnabled(true)
|
||||
overrides := &types.KnowledgeProcessOverrides{GraphEnabled: processConfigBoolPtr(false)}
|
||||
eff := ResolveProcessConfig(kb, overrides)
|
||||
require.False(t, eff.GraphEnabled)
|
||||
}
|
||||
|
||||
func TestResolveProcessConfig_NilOverridesUsesKBDefaults(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{
|
||||
ChunkingConfig: types.ChunkingConfig{ChunkSize: 512, ChunkOverlap: 50},
|
||||
VLMConfig: types.VLMConfig{Enabled: true, ModelID: "vlm-1"},
|
||||
ASRConfig: types.ASRConfig{Enabled: true, ModelID: "asr-1"},
|
||||
QuestionGenerationConfig: &types.QuestionGenerationConfig{
|
||||
Enabled: true,
|
||||
QuestionCount: 3,
|
||||
},
|
||||
IndexingStrategy: types.IndexingStrategy{GraphEnabled: true},
|
||||
ExtractConfig: &types.ExtractConfig{Enabled: true, Tags: []string{"tag-a"}},
|
||||
}
|
||||
kb.ChunkingConfig.EnableMultimodal = true
|
||||
|
||||
eff := ResolveProcessConfig(kb, nil)
|
||||
|
||||
require.Equal(t, 512, eff.ChunkingConfig.ChunkSize)
|
||||
require.Equal(t, 50, eff.ChunkingConfig.ChunkOverlap)
|
||||
require.True(t, eff.EnableMultimodel)
|
||||
require.Equal(t, "vlm-1", eff.VLMConfig.ModelID)
|
||||
require.Equal(t, "asr-1", eff.ASRConfig.ModelID)
|
||||
require.True(t, eff.QuestionGenerationConfig.Enabled)
|
||||
require.Equal(t, 3, eff.QuestionGenerationConfig.QuestionCount)
|
||||
require.True(t, eff.GraphEnabled)
|
||||
require.True(t, eff.ExtractConfig.Enabled)
|
||||
require.Equal(t, []string{"tag-a"}, eff.ExtractConfig.Tags)
|
||||
}
|
||||
|
||||
func TestBuildSplitterConfigFromChunking_UsesEffectiveChunkingConfig(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{
|
||||
ChunkingConfig: types.ChunkingConfig{ChunkSize: 512, ChunkOverlap: 50, Strategy: "token"},
|
||||
}
|
||||
overrides := &types.KnowledgeProcessOverrides{
|
||||
ChunkingConfig: &types.ChunkingConfig{ChunkSize: 1500, ChunkOverlap: 120, Strategy: "character"},
|
||||
}
|
||||
eff := ResolveProcessConfig(kb, overrides)
|
||||
cfg := buildSplitterConfigFromChunking(eff.ChunkingConfig)
|
||||
|
||||
require.Equal(t, 1500, cfg.ChunkSize)
|
||||
require.Equal(t, 120, cfg.ChunkOverlap)
|
||||
require.Equal(t, "character", cfg.Strategy)
|
||||
}
|
||||
|
||||
func TestEffectiveChunkingConfig_ResolveParserEngineFromOverrides(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{
|
||||
ChunkingConfig: types.ChunkingConfig{
|
||||
ParserEngineRules: []types.ParserEngineRule{
|
||||
{FileTypes: []string{"pdf"}, Engine: "builtin"},
|
||||
},
|
||||
},
|
||||
}
|
||||
overrides := &types.KnowledgeProcessOverrides{
|
||||
ParserEngineRules: []types.ParserEngineRule{
|
||||
{FileTypes: []string{"pdf"}, Engine: "mineru"},
|
||||
},
|
||||
}
|
||||
eff := ResolveProcessConfig(kb, overrides)
|
||||
require.Equal(t, "mineru", eff.ChunkingConfig.ResolveParserEngine("pdf"))
|
||||
}
|
||||
|
||||
func TestResolveProcessConfig_ParserEngineRulesReplaced(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{
|
||||
ChunkingConfig: types.ChunkingConfig{
|
||||
ParserEngineRules: []types.ParserEngineRule{
|
||||
{FileTypes: []string{"pdf"}, Engine: "builtin"},
|
||||
},
|
||||
},
|
||||
}
|
||||
overrides := &types.KnowledgeProcessOverrides{
|
||||
ParserEngineRules: []types.ParserEngineRule{
|
||||
{FileTypes: []string{"docx"}, Engine: "custom"},
|
||||
},
|
||||
}
|
||||
eff := ResolveProcessConfig(kb, overrides)
|
||||
require.Len(t, eff.ChunkingConfig.ParserEngineRules, 1)
|
||||
require.Equal(t, []string{"docx"}, eff.ChunkingConfig.ParserEngineRules[0].FileTypes)
|
||||
require.Equal(t, "custom", eff.ChunkingConfig.ParserEngineRules[0].Engine)
|
||||
}
|
||||
|
||||
func TestResolveProcessConfig_EnableMultimodelOverride(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{
|
||||
VLMConfig: types.VLMConfig{Enabled: true, ModelID: "vlm-1"},
|
||||
}
|
||||
overrides := &types.KnowledgeProcessOverrides{
|
||||
EnableMultimodel: processConfigBoolPtr(false),
|
||||
}
|
||||
eff := ResolveProcessConfig(kb, overrides)
|
||||
require.False(t, eff.EnableMultimodel)
|
||||
}
|
||||
|
||||
func TestResolveProcessConfig_ExtractConfigFieldMerge(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{
|
||||
ExtractConfig: &types.ExtractConfig{
|
||||
Enabled: true,
|
||||
Text: "base text",
|
||||
Tags: []string{"base-tag"},
|
||||
},
|
||||
}
|
||||
overrides := &types.KnowledgeProcessOverrides{
|
||||
ExtractConfig: &types.ExtractConfig{
|
||||
Tags: []string{"override-tag"},
|
||||
},
|
||||
}
|
||||
eff := ResolveProcessConfig(kb, overrides)
|
||||
require.True(t, eff.ExtractConfig.Enabled)
|
||||
require.Equal(t, "base text", eff.ExtractConfig.Text)
|
||||
require.Equal(t, []string{"override-tag"}, eff.ExtractConfig.Tags)
|
||||
}
|
||||
|
||||
func TestValidateProcessOverrides_NilOverrides(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := ValidateProcessOverrides(context.Background(), &types.KnowledgeBase{}, nil, []string{"png"})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestValidateProcessOverrides_ImageRequiresVLM(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{
|
||||
VLMConfig: types.VLMConfig{Enabled: false},
|
||||
}
|
||||
err := ValidateProcessOverrides(context.Background(), kb, &types.KnowledgeProcessOverrides{}, []string{"png"})
|
||||
require.Error(t, err)
|
||||
var badReq *werrors.AppError
|
||||
require.ErrorAs(t, err, &badReq)
|
||||
}
|
||||
|
||||
func TestValidateProcessOverrides_ImageWithEffectiveVLM(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{
|
||||
VLMConfig: types.VLMConfig{Enabled: false},
|
||||
}
|
||||
overrides := &types.KnowledgeProcessOverrides{
|
||||
VLMConfig: &types.VLMConfig{Enabled: true, ModelID: "vlm-1"},
|
||||
}
|
||||
err := ValidateProcessOverrides(context.Background(), kb, overrides, []string{"jpg"})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestValidateProcessOverrides_AudioRequiresASR(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{
|
||||
ASRConfig: types.ASRConfig{Enabled: false},
|
||||
}
|
||||
err := ValidateProcessOverrides(context.Background(), kb, &types.KnowledgeProcessOverrides{}, []string{"mp3"})
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestValidateProcessOverrides_AudioWithEffectiveASR(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{
|
||||
ASRConfig: types.ASRConfig{Enabled: false},
|
||||
}
|
||||
overrides := &types.KnowledgeProcessOverrides{
|
||||
ASRConfig: &types.ASRConfig{Enabled: true, ModelID: "asr-1"},
|
||||
}
|
||||
err := ValidateProcessOverrides(context.Background(), kb, overrides, []string{"wav"})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestValidateProcessOverrides_NonMediaFileTypes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
kb := &types.KnowledgeBase{}
|
||||
err := ValidateProcessOverrides(context.Background(), kb, &types.KnowledgeProcessOverrides{}, []string{"pdf", "txt"})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestValidateProcessOverrides_COSIncompleteForImage(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.WithValue(context.Background(), types.TenantInfoContextKey, &types.Tenant{
|
||||
StorageEngineConfig: &types.StorageEngineConfig{
|
||||
COS: &types.COSEngineConfig{SecretID: "id"},
|
||||
},
|
||||
})
|
||||
kb := &types.KnowledgeBase{
|
||||
VLMConfig: types.VLMConfig{Enabled: true, ModelID: "vlm-1"},
|
||||
}
|
||||
kb.SetStorageProvider("cos")
|
||||
|
||||
err := ValidateProcessOverrides(ctx, kb, &types.KnowledgeProcessOverrides{}, []string{"png"})
|
||||
require.Error(t, err)
|
||||
}
|
||||
Reference in New Issue
Block a user