diff --git a/.gitignore b/.gitignore index af5b4fa4..1423ddab 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ # 忽略所有隐藏文件和目录 .* - # 但不忽略特定隐藏文件和目录 !.env.example !.gitignore diff --git a/docs/api/knowledge-base.md b/docs/api/knowledge-base.md index 302679f9..79fc528d 100644 --- a/docs/api/knowledge-base.md +++ b/docs/api/knowledge-base.md @@ -7,7 +7,7 @@ - 知识库类型 `type` 为 `document`(文档)或 `faq`(FAQ),默认 `document`。 - JSON 中对象存储相关字段:**`storage_config`** 为序列化字段名(对应数据库列 `cos_config`,兼容旧数据)。旧客户端若仍发送或接收 `cos_config`,服务端会兼容解析;新集成请使用 **`storage_config`**。 - **`storage_provider_config`** 为新版存储提供者选择(如 `{"provider": "local"}`),与空间级存储引擎凭证配合使用;无配置时可为 `null`。 -- 嵌套配置对象:`chunking_config`、`image_processing_config`、`vlm_config`、`asr_config`、`extract_config`、`faq_config`、`question_generation_config`。其中 `extract_config`、`faq_config`、`question_generation_config` 允许为 `null`。 +- 嵌套配置对象:`chunking_config`、`image_processing_config`、`vlm_config`、`asr_config`、`extract_config`、`faq_config`、`question_generation_config`、`auto_tag_config`。其中 `extract_config`、`faq_config`、`question_generation_config`、`auto_tag_config` 允许为 `null`。 - **`vector_store_id`** 为知识库绑定的向量存储 ID(参见 [vector-store.md](./vector-store.md))。未指定(或 `null`/`""`)时使用空间级默认的环境变量存储;一旦创建即不可修改。详情接口返回时会附带 `vector_store_name` / `vector_store_source` / `vector_store_engine_type` / `vector_store_status` 四个只读元数据字段,用于前端展示。 | 方法 | 路径 | 描述 | @@ -46,6 +46,7 @@ | extract_config | object | 否 | 图谱抽取配置;`enabled=true` 时需提供 `text`/`tags`/`nodes`/`relations` | | faq_config | object | 否 | FAQ 配置(仅 FAQ 类型知识库需要) | | question_generation_config | object | 否 | 问题生成配置 | +| auto_tag_config | object | 否 | 文档自动标签配置,默认关闭;仅适用于 `document` 类型知识库 | | vector_store_id | string | 否 | 绑定的向量存储 ID。不传或为空字符串等同于 `null`(使用环境变量默认存储)。指定时必须是调用者所在空间拥有的向量存储 UUID;创建后不可修改。无效 UUID / 跨空间 / 未注册到引擎的 ID 会返回 `400` | **请求**: @@ -107,6 +108,11 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases' \ "enabled": false, "question_count": 3 }, + "auto_tag_config": { + "enabled": true, + "model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c", + "max_tags": 3 + }, "vector_store_id": "550e8400-e29b-41d4-a716-446655440000" }' ``` @@ -170,6 +176,11 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases' \ "enabled": false, "question_count": 3 }, + "auto_tag_config": { + "enabled": true, + "model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c", + "max_tags": 3 + }, "is_pinned": false, "pinned_at": null, "knowledge_count": 0, @@ -188,6 +199,18 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases' \ } ``` +### 自动标签配置 + +`auto_tag_config` 在文档解析完成后异步调用聊天模型,从知识库已有标签中选择匹配项并增量关联到文档。该过程不会创建新标签,也不会删除或覆盖人工添加的标签。 + +| 字段 | 类型 | 默认值 | 说明 | +| ---------- | ------- | ------ | ---- | +| `enabled` | boolean | `false` | 是否启用自动标签 | +| `model_id` | string | `""` | 使用的聊天模型 ID;为空时使用知识库的 `summary_model_id` | +| `max_tags` | integer | `3` | 单个文档最多自动关联的标签数,取值范围为 `1` 到 `10` | + +自动标签仅对启用该配置后新解析或重新解析的文档生效。模型调用失败不会阻塞文档解析完成,异步任务会按照任务队列策略重试。 + **`vector_store_*` 响应字段说明**: | 字段 | 类型 | 说明 | diff --git a/internal/application/repository/knowledge_tag.go b/internal/application/repository/knowledge_tag.go index 2f8799d3..66b147e8 100644 --- a/internal/application/repository/knowledge_tag.go +++ b/internal/application/repository/knowledge_tag.go @@ -80,7 +80,11 @@ func (r *knowledgeRepository) AddKnowledgeTagRelations( var knowledgeCount int64 if err := tx.Model(&types.Knowledge{}). Where("id = ? AND tenant_id = ? AND knowledge_base_id = ? AND deleted_at IS NULL", knowledgeID, tenantID, kbID). - Where("parse_status NOT IN ?", []string{types.ParseStatusCancelled, types.ParseStatusDeleting, types.ParseStatusFailed}). + Where("parse_status NOT IN ?", []string{ + types.ParseStatusCancelled, + types.ParseStatusDeleting, + types.ParseStatusFailed, + }). Count(&knowledgeCount).Error; err != nil { return err } diff --git a/internal/application/service/knowledge_auto_tag.go b/internal/application/service/knowledge_auto_tag.go index 1ab261ed..692b9593 100644 --- a/internal/application/service/knowledge_auto_tag.go +++ b/internal/application/service/knowledge_auto_tag.go @@ -23,6 +23,7 @@ const ( autoTagSpanName = "postprocess.auto_tag" ) +// KnowledgeAutoTagService classifies processed documents against existing knowledge-base tags. type KnowledgeAutoTagService struct { knowledgeRepo interfaces.KnowledgeRepository tagRepo interfaces.KnowledgeTagRepository @@ -32,6 +33,7 @@ type KnowledgeAutoTagService struct { spanTracker SpanTracker } +// NewKnowledgeAutoTagService creates the asynchronous automatic-tagging task handler. func NewKnowledgeAutoTagService( knowledgeRepo interfaces.KnowledgeRepository, tagRepo interfaces.KnowledgeTagRepository, @@ -67,6 +69,7 @@ type autoTagModelResponse struct { Matches []autoTagModelMatch `json:"matches"` } +// Handle processes one automatic-tagging task. func (s *KnowledgeAutoTagService) Handle(ctx context.Context, task *asynq.Task) error { var payload types.KnowledgeAutoTagPayload if err := json.Unmarshal(task.Payload(), &payload); err != nil { @@ -98,7 +101,9 @@ func (s *KnowledgeAutoTagService) Handle(ctx context.Context, task *asynq.Task) if knowledge == nil || knowledge.TenantID != payload.TenantID || knowledge.KnowledgeBaseID != payload.KnowledgeBaseID { return skip("knowledge_not_in_scope", nil) } - if knowledge.ParseStatus == types.ParseStatusCancelled || knowledge.ParseStatus == types.ParseStatusDeleting || knowledge.ParseStatus == types.ParseStatusFailed { + if knowledge.ParseStatus == types.ParseStatusCancelled || + knowledge.ParseStatus == types.ParseStatusDeleting || + knowledge.ParseStatus == types.ParseStatusFailed { return skip("knowledge_not_active", types.JSONMap{"parse_status": knowledge.ParseStatus}) } @@ -116,7 +121,13 @@ func (s *KnowledgeAutoTagService) Handle(ctx context.Context, task *asynq.Task) } config.Normalize() - tags, _, err := s.tagRepo.ListByKB(ctx, payload.TenantID, payload.KnowledgeBaseID, &types.Pagination{Page: 1, PageSize: 1000}, "") + tags, _, err := s.tagRepo.ListByKB( + ctx, + payload.TenantID, + payload.KnowledgeBaseID, + &types.Pagination{Page: 1, PageSize: maximumAutoTagCandidates + 1}, + "", + ) if err != nil { s.tracker().FailSpan(ctx, span, "AUTO_TAG_LIST_TAGS_FAILED", err.Error(), err) return fmt.Errorf("list auto tag candidates: %w", err) @@ -188,7 +199,13 @@ func (s *KnowledgeAutoTagService) Handle(ctx context.Context, task *asynq.Task) s.tracker().FailSpan(ctx, span, "AUTO_TAG_PERSIST_UNSUPPORTED", err.Error(), err) return err } - if err := adder.AddKnowledgeTagRelations(ctx, payload.TenantID, payload.KnowledgeBaseID, payload.KnowledgeID, added); err != nil { + if err := adder.AddKnowledgeTagRelations( + ctx, + payload.TenantID, + payload.KnowledgeBaseID, + payload.KnowledgeID, + added, + ); err != nil { s.tracker().FailSpan(ctx, span, "AUTO_TAG_PERSIST_FAILED", err.Error(), err) return fmt.Errorf("add automatic knowledge tags: %w", err) } @@ -220,7 +237,9 @@ func buildAutoTagDocumentContent(knowledge *types.Knowledge, chunks []*types.Chu } sort.SliceStable(orderedChunks, func(i, j int) bool { return orderedChunks[i].StartAt < orderedChunks[j].StartAt }) for _, chunk := range orderedChunks { - if chunk.ChunkType != types.ChunkTypeText && chunk.ChunkType != types.ChunkTypeImageOCR && chunk.ChunkType != types.ChunkTypeImageCaption { + if chunk.ChunkType != types.ChunkTypeText && + chunk.ChunkType != types.ChunkTypeImageOCR && + chunk.ChunkType != types.ChunkTypeImageCaption { continue } if text := strings.TrimSpace(chunk.Content); text != "" { @@ -230,7 +249,13 @@ func buildAutoTagDocumentContent(knowledge *types.Knowledge, chunks []*types.Chu return sampleLongContent(strings.Join(parts, "\n\n"), maximumAutoTagContentRunes) } -func classifyExistingTags(ctx context.Context, model chat.Chat, tags []*types.KnowledgeTag, content string, maxTags int) (*autoTagModelResponse, error) { +func classifyExistingTags( + ctx context.Context, + model chat.Chat, + tags []*types.KnowledgeTag, + content string, + maxTags int, +) (*autoTagModelResponse, error) { if maxTags <= 0 { maxTags = defaultAutoTagMaxTags } @@ -243,7 +268,8 @@ func classifyExistingTags(ctx context.Context, model chat.Chat, tags []*types.Kn } systemPrompt := fmt.Sprintf(`You classify one document using only the supplied existing tags. Return strict JSON only: {"matches":[{"tag_id":"candidate-id","confidence":0.0,"reason":"short reason"}]}. -Rules: never invent a tag; return an empty matches array when uncertain; confidence must be between 0 and 1; choose at most %d tags.`, maxTags) +Rules: never invent a tag; return an empty matches array when uncertain; confidence must be between 0 and 1. +Choose at most %d tags.`, maxTags) userPrompt := "Candidate tags:\n" + strings.Join(candidates, "\n") + "\n\nDocument:\n" + content thinking := false result, err := model.Chat(types.WithLLMCallMetadata(ctx, "document_auto_tag", ""), []chat.Message{ @@ -264,10 +290,18 @@ func stripJSONCodeFence(value string) string { value = strings.TrimSpace(value) if strings.HasPrefix(value, "```") { lines := strings.Split(value, "\n") - if len(lines) >= 3 && strings.HasPrefix(strings.TrimSpace(lines[0]), "```") && strings.TrimSpace(lines[len(lines)-1]) == "```" { + if len(lines) >= 3 && + strings.HasPrefix(strings.TrimSpace(lines[0]), "```") && + strings.TrimSpace(lines[len(lines)-1]) == "```" { value = strings.Join(lines[1:len(lines)-1], "\n") } } + // Be resilient to models that wrap JSON with a short explanation. + start := strings.IndexAny(value, "{[") + end := strings.LastIndexAny(value, "}]") + if start >= 0 && end >= start { + value = value[start : end+1] + } return strings.TrimSpace(value) } diff --git a/internal/application/service/knowledge_auto_tag_test.go b/internal/application/service/knowledge_auto_tag_test.go index 3b7465cb..fdb74aae 100644 --- a/internal/application/service/knowledge_auto_tag_test.go +++ b/internal/application/service/knowledge_auto_tag_test.go @@ -26,6 +26,8 @@ func (q *autoTagRecordingQueue) Enqueue(task *asynq.Task, _ ...asynq.Option) (*a func TestStripJSONCodeFence(t *testing.T) { assert.Equal(t, `{"matches":[]}`, stripJSONCodeFence("```json\n{\"matches\":[]}\n```")) assert.Equal(t, `{"matches":[]}`, stripJSONCodeFence(" {\"matches\":[]} ")) + assert.Equal(t, `{"matches":[]}`, stripJSONCodeFence("Sure, here is the JSON: {\"matches\":[]}")) + assert.Equal(t, `[1,2]`, stripJSONCodeFence("The values are [1,2], as requested.")) } func TestValidateAutoTagMatches(t *testing.T) { diff --git a/internal/application/service/knowledge_post_process.go b/internal/application/service/knowledge_post_process.go index 293ebb35..f3f28a6b 100644 --- a/internal/application/service/knowledge_post_process.go +++ b/internal/application/service/knowledge_post_process.go @@ -489,7 +489,11 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta // enqueueAutoTagTask schedules best-effort classification against the KB's // existing tags. It intentionally owns no pending-subtask slot: a model or // configuration failure must never keep document parsing in finalizing. -func (s *KnowledgePostProcessService) enqueueAutoTagTask(ctx context.Context, payload types.KnowledgePostProcessPayload, attempt int) bool { +func (s *KnowledgePostProcessService) enqueueAutoTagTask( + ctx context.Context, + payload types.KnowledgePostProcessPayload, + attempt int, +) bool { if s.taskEnqueuer == nil { return false } diff --git a/internal/database/migration_sqlite_test.go b/internal/database/migration_sqlite_test.go index 52161b0c..dcaa83e6 100644 --- a/internal/database/migration_sqlite_test.go +++ b/internal/database/migration_sqlite_test.go @@ -26,7 +26,7 @@ func TestSQLiteMigrationsIncludeAutoTagConfig(t *testing.T) { rows, err := db.Query("PRAGMA table_info(knowledge_bases)") require.NoError(t, err) - defer rows.Close() + defer func() { _ = rows.Close() }() found := false for rows.Next() { diff --git a/internal/types/knowledgebase.go b/internal/types/knowledgebase.go index c46ce8ba..f88e4b52 100644 --- a/internal/types/knowledgebase.go +++ b/internal/types/knowledgebase.go @@ -108,7 +108,7 @@ type KnowledgeBase struct { // QuestionGenerationConfig stores question generation configuration for document knowledge bases QuestionGenerationConfig *QuestionGenerationConfig `yaml:"question_generation_config" json:"question_generation_config" gorm:"column:question_generation_config;type:json"` // AutoTagConfig controls asynchronous association of existing tags after parsing. - AutoTagConfig *AutoTagConfig `yaml:"auto_tag_config" json:"auto_tag_config" gorm:"column:auto_tag_config;type:json;default:null"` + AutoTagConfig *AutoTagConfig `yaml:"auto_tag_config" json:"auto_tag_config" gorm:"type:json"` // WikiConfig stores wiki-specific configuration (only for wiki type knowledge bases) WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config" gorm:"column:wiki_config;type:json"` // IndexingStrategy controls which indexing pipelines are active for this knowledge base. @@ -174,8 +174,10 @@ type AutoTagConfig struct { MaxTags int `yaml:"max_tags,omitempty" json:"max_tags,omitempty"` } +// Value serializes the automatic-tagging configuration for database storage. func (c AutoTagConfig) Value() (driver.Value, error) { return json.Marshal(c) } +// Scan deserializes the automatic-tagging configuration from a database value. func (c *AutoTagConfig) Scan(value interface{}) error { if value == nil { return nil @@ -191,6 +193,7 @@ func (c *AutoTagConfig) Scan(value interface{}) error { return json.Unmarshal(b, c) } +// Normalize applies defaults and bounds to the automatic-tagging configuration. func (c *AutoTagConfig) Normalize() { if c == nil { return @@ -669,7 +672,9 @@ func (kb *KnowledgeBase) EnsureDefaults() { if kb.Type != KnowledgeBaseTypeFAQ { kb.FAQConfig = nil } - if kb.AutoTagConfig != nil { + if kb.Type != KnowledgeBaseTypeDocument { + kb.AutoTagConfig = nil + } else if kb.AutoTagConfig != nil { kb.AutoTagConfig.Normalize() } // Set defaults for FAQ diff --git a/internal/types/knowledgebase_auto_tag_test.go b/internal/types/knowledgebase_auto_tag_test.go index 1b1bc5ab..ea509f68 100644 --- a/internal/types/knowledgebase_auto_tag_test.go +++ b/internal/types/knowledgebase_auto_tag_test.go @@ -15,3 +15,23 @@ func TestAutoTagConfigNormalize(t *testing.T) { config.Normalize() assert.Equal(t, 10, config.MaxTags) } + +func TestEnsureDefaultsClearsAutoTagConfigForNonDocumentKnowledgeBases(t *testing.T) { + for _, kbType := range []string{KnowledgeBaseTypeFAQ, KnowledgeBaseTypeWiki} { + kb := &KnowledgeBase{ + Type: kbType, + AutoTagConfig: &AutoTagConfig{Enabled: true}, + } + kb.EnsureDefaults() + assert.Nil(t, kb.AutoTagConfig, "auto tags must only apply to document KBs (%s)", kbType) + } +} + +func TestEnsureDefaultsNormalizesAutoTagConfigForDocumentKnowledgeBases(t *testing.T) { + kb := &KnowledgeBase{ + Type: KnowledgeBaseTypeDocument, + AutoTagConfig: &AutoTagConfig{Enabled: true}, + } + kb.EnsureDefaults() + assert.Equal(t, 3, kb.AutoTagConfig.MaxTags) +}