Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat: 增加自动添加标签的功能
lkx9426ee147009
diff --git a/.gitignore b/.gitignoreindex 1423ddab1..af5b4fa47 100644--- a/.gitignore+++ b/.gitignore@@ -1,5 +1,6 @@# 忽略所有隐藏文件和目录.*+# 但不忽略特定隐藏文件和目录!.env.example!.gitignorediff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.tsindex 7eecec519..6afb698a1 100644--- a/frontend/src/api/knowledge-base/index.ts+++ b/frontend/src/api/knowledge-base/index.ts@@ -87,6 +87,7 @@ export function createKnowledgeBase(data: {chunking_config?: any;embedding_model_id?: string;summary_model_id?: string;+ auto_tag_config?: { enabled: boolean; model_id?: string; max_tags?: number };// Opt-in binding to a specific tenant-owned VectorStore. Omit (or// send undefined / empty string) to fall back to the env-configured// store. Immutable after creation — UpdateKnowledgeBase intentionally@@ -149,6 +150,7 @@ export function updateKnowledgeBase(id: string, data: {content_instructions?: string;extraction_instructions?: string;};+ auto_tag_config?: { enabled: boolean; model_id?: string; max_tags?: number };indexing_strategy?: {vector_enabled: boolean;keyword_enabled: boolean;diff --git a/frontend/src/components/ModelSelector.vue b/frontend/src/components/ModelSelector.vueindex 402713d09..b4d600bcb 100644--- a/frontend/src/components/ModelSelector.vue+++ b/frontend/src/components/ModelSelector.vue@@ -7,6 +7,7 @@:disabled="disabled":loading="loading":status="status"+ :clearable="clearable"filterablestyle="width: 100%;">@@ -53,6 +54,7 @@ interface Props {disabled?: booleanplaceholder?: stringstatus?: 'default' | 'success' | 'warning' | 'error'+ clearable?: boolean// 可选:外部传入的所有模型列表,如果提供则不调用APIallModels?: ModelConfig[]}@@ -61,6 +63,7 @@ const props = withDefaults(defineProps<Props>(), {disabled: false,placeholder: '',status: 'default',+ clearable: false,})const emit = defineEmits<{@@ -119,13 +122,13 @@ const loadModels = async () => {}// 处理模型选择变化-const handleModelChange = (value: string) => {+const handleModelChange = (value?: string) => {// 如果选择的是添加模型选项,触发添加事件而不更新选中值if (value === '__add_model__') {emit('add-model')return}- emit('update:selectedModelId', value)+ emit('update:selectedModelId', value || '')}// 暴露刷新方法给父组件diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex d28822f68..c174f83d7 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -2590,6 +2590,15 @@ export default {instructionsDescription: 'Specify audience, scenario, and wording while the system retains the stable output format',instructionsPlaceholder: 'For example: generate natural customer-support questions and avoid exam-style wording…'},+ autoTag: {+ label: 'Automatic Tagging',+ description: 'After parsing, select suitable tags from the existing knowledge-base tags. Tags are never created or deleted, but one extra model call is required.',+ modelLabel: 'Classification Model',+ modelDescription: 'Leave empty to reuse the knowledge-base summary model.',+ modelPlaceholder: 'Select a classification model',+ maxTagsLabel: 'Maximum tags per document',+ maxTagsDescription: 'Automatically associate 1-10 existing tags per document.'+ },tableMetadataInstructions: {label: 'Table Metadata Instructions',description: 'Add business context and field semantics to CSV/Excel summaries for better retrieval',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 4f7b4cfef..3702e80bd 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -3311,6 +3311,15 @@ export default {instructionsLabel: '질문 생성 지침',instructionsDescription: '안정적인 출력 형식을 유지하면서 대상, 상황 및 표현 방식을 지정합니다',instructionsPlaceholder: '예: 시험 문제 형식을 피하고 자연스러운 고객 지원 질문을 생성…'+ },+ autoTag: {+ label: '자동 태그 연결',+ description: '문서 파싱 후 현재 지식베이스의 기존 태그 중 적합한 태그를 연결합니다. 태그를 생성하거나 삭제하지 않으며 모델 호출이 한 번 추가됩니다.',+ modelLabel: '분류 모델',+ modelDescription: '비워 두면 지식베이스 요약 모델을 사용합니다.',+ modelPlaceholder: '분류 모델 선택',+ maxTagsLabel: '문서당 최대 태그 수',+ maxTagsDescription: '문서마다 기존 태그 1-10개를 자동 연결합니다.'}},asr: {diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex dbb4af1ac..584b76209 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -3311,6 +3311,15 @@ export default {instructionsLabel: 'Инструкции генерации вопросов',instructionsDescription: 'Задайте аудиторию, сценарий и формулировки, сохраняя стабильный формат вывода',instructionsPlaceholder: 'Например: естественные вопросы службы поддержки без экзаменационного стиля…'+ },+ autoTag: {+ label: 'Автоматические теги',+ description: 'После разбора документа выбираются подходящие существующие теги базы знаний. Теги не создаются и не удаляются, но выполняется дополнительный вызов модели.',+ modelLabel: 'Модель классификации',+ modelDescription: 'Если не выбрана, используется модель резюмирования базы знаний.',+ modelPlaceholder: 'Выберите модель классификации',+ maxTagsLabel: 'Максимум тегов на документ',+ maxTagsDescription: 'Автоматически связывать от 1 до 10 существующих тегов.'}},asr: {diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 06eb7a75c..2c10e1dc9 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -3311,6 +3311,15 @@ export default {instructionsLabel: '问题生成要求',instructionsDescription: '指定问题面向的人群、场景和表达方式,系统仍维护稳定输出格式',instructionsPlaceholder: '例如:生成客服用户常问的自然语言问题,避免考试题式表达…'+ },+ autoTag: {+ label: '自动关联标签',+ description: '文档解析完成后,从当前知识库已有标签中选择合适标签自动关联。不会创建或删除标签,并会增加一次模型调用。',+ modelLabel: '分类模型',+ modelDescription: '留空时使用知识库摘要模型。',+ modelPlaceholder: '请选择分类模型',+ maxTagsLabel: '单篇文档最多标签数',+ maxTagsDescription: '每篇文档最多自动关联 1-10 个已有标签。'}},asr: {diff --git a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vueindex 372e181ab..6c4b378a5 100644--- a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue+++ b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue@@ -406,10 +406,12 @@ref="advancedSettingsRef"v-if="formData":question-generation="formData.questionGenerationConfig"+ :auto-tag="formData.autoTagConfig":rag-enabled="formData.indexingStrategy?.vectorEnabled || formData.indexingStrategy?.keywordEnabled":all-models="allModels":table-metadata-instructions="formData.chunkingConfig.tableMetadataInstructions"@update:question-generation="handleQuestionGenerationUpdate"+ @update:auto-tag="(value) => { if (formData) formData.autoTagConfig = value }"@update:table-metadata-instructions="(value: string) => { if (formData) formData.chunkingConfig.tableMetadataInstructions = value }"/></div>@@ -792,6 +794,11 @@ const initFormData = (type: 'document' | 'faq' = 'document') => {questionCount: 3,customInstructions: ''},+ autoTagConfig: {+ enabled: false,+ modelId: '',+ maxTags: 3+ },wikiConfig: {synthesisModelId: '',maxPagesPerIngest: 0,@@ -912,6 +919,11 @@ const loadKBData = async (kbIdOverride?: string) => {questionCount: kb.question_generation_config?.question_count || 3,customInstructions: kb.question_generation_config?.custom_instructions || ''},+ autoTagConfig: {+ enabled: kb.auto_tag_config?.enabled || false,+ modelId: kb.auto_tag_config?.model_id || '',+ maxTags: kb.auto_tag_config?.max_tags || 3+ },wikiConfig: {synthesisModelId: kb.wiki_config?.synthesis_model_id || '',maxPagesPerIngest: kb.wiki_config?.max_pages_per_ingest || 0,@@ -1266,6 +1278,12 @@ const buildSubmitData = () => {}}+ data.auto_tag_config = {+ enabled: formData.value.autoTagConfig?.enabled || false,+ model_id: formData.value.autoTagConfig?.modelId || '',+ max_tags: formData.value.autoTagConfig?.maxTags || 3+ }+if (formData.value.type === 'faq') {data.faq_config = {index_mode: formData.value.faqConfig?.indexMode || 'question_only',@@ -1390,6 +1408,7 @@ const doSubmit = async () => {}}if (formData.value.type !== 'faq') {+ updateConfig.auto_tag_config = data.auto_tag_configupdateConfig.indexing_strategy = {vector_enabled: formData.value.indexingStrategy?.vectorEnabled ?? true,keyword_enabled: formData.value.indexingStrategy?.keywordEnabled ?? true,diff --git a/frontend/src/views/knowledge/settings/KBAdvancedSettings.vue b/frontend/src/views/knowledge/settings/KBAdvancedSettings.vueindex 1b487d3ec..5648f8f45 100644--- a/frontend/src/views/knowledge/settings/KBAdvancedSettings.vue+++ b/frontend/src/views/knowledge/settings/KBAdvancedSettings.vue@@ -59,6 +59,52 @@</div></template>+ <div class="setting-row">+ <div class="setting-info">+ <label>{{ $t('knowledgeEditor.advanced.autoTag.label') }}</label>+ <p class="desc">{{ $t('knowledgeEditor.advanced.autoTag.description') }}</p>+ </div>+ <div class="setting-control">+ <t-switch v-model="localAutoTag.enabled" size="medium" @change="emitAutoTag" />+ </div>+ </div>++ <div v-if="localAutoTag.enabled" class="subsection">+ <div class="setting-row setting-row-vertical">+ <div class="setting-info">+ <label>{{ $t('knowledgeEditor.advanced.autoTag.modelLabel') }}</label>+ <p class="desc">{{ $t('knowledgeEditor.advanced.autoTag.modelDescription') }}</p>+ </div>+ <div class="setting-control">+ <ModelSelector+ model-type="KnowledgeQA"+ :selected-model-id="localAutoTag.modelId"+ :all-models="allModels"+ clearable+ :placeholder="$t('knowledgeEditor.advanced.autoTag.modelPlaceholder')"+ @update:selected-model-id="(value: string) => { localAutoTag.modelId = value; emitAutoTag() }"+ />+ </div>+ </div>+ <div class="setting-row">+ <div class="setting-info">+ <label>{{ $t('knowledgeEditor.advanced.autoTag.maxTagsLabel') }}</label>+ <p class="desc">{{ $t('knowledgeEditor.advanced.autoTag.maxTagsDescription') }}</p>+ </div>+ <div class="setting-control">+ <t-input-number+ v-model="localAutoTag.maxTags"+ :min="1"+ :max="10"+ :step="1"+ theme="normal"+ style="width: 120px;"+ @change="emitAutoTag"+ />+ </div>+ </div>+ </div>+<div class="setting-row setting-row-vertical"><div class="setting-info"><label>{{ $t('knowledgeEditor.advanced.tableMetadataInstructions.label') }}</label>@@ -81,6 +127,7 @@<script setup lang="ts">import { ref, watch } from 'vue'+import ModelSelector from '@/components/ModelSelector.vue'interface QuestionGenerationConfig {enabled: boolean@@ -88,8 +135,15 @@ interface QuestionGenerationConfig {customInstructions?: string}+interface AutoTagConfig {+ enabled: boolean+ modelId: string+ maxTags: number+}+interface Props {questionGeneration?: QuestionGenerationConfig+ autoTag?: AutoTagConfigragEnabled?: booleanallModels?: any[]embedded?: boolean@@ -102,6 +156,7 @@ const props = withDefaults(defineProps<Props>(), {const emit = defineEmits<{'update:questionGeneration': [value: QuestionGenerationConfig]+ 'update:autoTag': [value: AutoTagConfig]'update:tableMetadataInstructions': [value: string]}>()@@ -111,12 +166,26 @@ const localQuestionGeneration = ref<QuestionGenerationConfig>(: { enabled: false, questionCount: 3, customInstructions: '' })+const localAutoTag = ref<AutoTagConfig>(+ props.autoTag ? { ...props.autoTag } : { enabled: false, modelId: '', maxTags: 3 }+)+watch(() => props.questionGeneration, (newVal) => {if (newVal) {localQuestionGeneration.value = { customInstructions: '', ...newVal }}}, { deep: true })+watch(() => props.autoTag, (newVal) => {+ if (newVal) localAutoTag.value = { ...newVal }+}, { deep: true })++const emitAutoTag = () => {+ if (!localAutoTag.value.maxTags) localAutoTag.value.maxTags = 3+ localAutoTag.value.maxTags = Math.min(10, Math.max(1, Math.trunc(localAutoTag.value.maxTags)))+ emit('update:autoTag', { ...localAutoTag.value })+}+const handleQuestionGenerationToggle = () => {if (!localQuestionGeneration.value.enabled) {localQuestionGeneration.value.questionCount = 3diff --git a/internal/application/repository/knowledge_tag.go b/internal/application/repository/knowledge_tag.goindex d903b31bc..2f8799d31 100644--- a/internal/application/repository/knowledge_tag.go+++ b/internal/application/repository/knowledge_tag.go@@ -2,10 +2,12 @@ package repositoryimport ("context"+ "fmt""time""github.com/Tencent/WeKnora/internal/types""gorm.io/gorm"+ "gorm.io/gorm/clause")// SetKnowledgeTags replaces all tags for a single knowledge entry.@@ -49,6 +51,66 @@ func (r *knowledgeRepository) SetKnowledgeTags(})}+// AddKnowledgeTagRelations incrementally adds validated relations and never+// removes existing manual tags. The composite primary key plus DO NOTHING+// makes retries and duplicate deliveries idempotent.+func (r *knowledgeRepository) AddKnowledgeTagRelations(+ ctx context.Context,+ tenantID uint64,+ kbID, knowledgeID string,+ tagIDs []string,+) error {+ seen := make(map[string]struct{}, len(tagIDs))+ unique := make([]string, 0, len(tagIDs))+ for _, id := range tagIDs {+ if id == "" {+ continue+ }+ if _, ok := seen[id]; ok {+ continue+ }+ seen[id] = struct{}{}+ unique = append(unique, id)+ }+ if len(unique) == 0 {+ return nil+ }++ return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {+ 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}).+ Count(&knowledgeCount).Error; err != nil {+ return err+ }+ if knowledgeCount != 1 {+ return fmt.Errorf("knowledge %s does not belong to tenant %d and knowledge base %s", knowledgeID, tenantID, kbID)+ }++ var tagCount int64+ if err := tx.Model(&types.KnowledgeTag{}).+ Where("tenant_id = ? AND knowledge_base_id = ? AND id IN ?", tenantID, kbID, unique).+ Count(&tagCount).Error; err != nil {+ return err+ }+ if tagCount != int64(len(unique)) {+ return fmt.Errorf("one or more tags do not belong to tenant %d and knowledge base %s", tenantID, kbID)+ }++ now := time.Now()+ relations := make([]types.KnowledgeTagRelation, 0, len(unique))+ for _, tagID := range unique {+ relations = append(relations, types.KnowledgeTagRelation{+ KnowledgeID: knowledgeID,+ TagID: tagID,+ CreatedAt: now,+ })+ }+ return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&relations).Error+ })+}+// GetKnowledgeTags returns tags for multiple knowledge IDs.// The result is a map from knowledge ID to its tag list.func (r *knowledgeRepository) GetKnowledgeTags(diff --git a/internal/application/repository/knowledge_tag_test.go b/internal/application/repository/knowledge_tag_test.goindex 2c31f493e..aea5a7453 100644--- a/internal/application/repository/knowledge_tag_test.go+++ b/internal/application/repository/knowledge_tag_test.go@@ -98,6 +98,47 @@ func TestSetKnowledgeTags_DedupesAndReplaces(t *testing.T) {assert.Equal(t, int64(0), count)}+func TestAddKnowledgeTagRelations_IsIncrementalIdempotentAndScoped(t *testing.T) {+ db := setupKnowledgeTagTestDB(t)+ repo := &knowledgeRepository{db: db}+ kbID, knowledgeID, tagA, tagB := seedKnowledgeTagFixture(t, db)+ ctx := context.Background()++ require.NoError(t, repo.SetKnowledgeTags(ctx, knowledgeID, []string{tagA}))+ require.NoError(t, repo.AddKnowledgeTagRelations(ctx, 1, kbID, knowledgeID, []string{tagA, tagB, tagB}))+ require.NoError(t, repo.AddKnowledgeTagRelations(ctx, 1, kbID, knowledgeID, []string{tagB}))++ var relations []types.KnowledgeTagRelation+ require.NoError(t, db.Where("knowledge_id = ?", knowledgeID).Find(&relations).Error)+ assert.Len(t, relations, 2)++ otherKBTag := uuid.New().String()+ require.NoError(t, db.Exec(`+ INSERT INTO knowledge_tags (id, seq_id, tenant_id, knowledge_base_id, name)+ VALUES (?, 3, 1, ?, 'other')+ `, otherKBTag, uuid.New().String()).Error)+ err := repo.AddKnowledgeTagRelations(ctx, 1, kbID, knowledgeID, []string{otherKBTag})+ require.Error(t, err)+}++func TestAddKnowledgeTagRelations_RejectsCancelledKnowledge(t *testing.T) {+ db := setupKnowledgeTagTestDB(t)+ repo := &knowledgeRepository{db: db}+ kbID, knowledgeID, _, tagB := seedKnowledgeTagFixture(t, db)+ require.NoError(t, db.Model(&types.Knowledge{}).+ Where("id = ?", knowledgeID).+ Update("parse_status", types.ParseStatusCancelled).Error)++ err := repo.AddKnowledgeTagRelations(context.Background(), 1, kbID, knowledgeID, []string{tagB})+ require.Error(t, err)++ var count int64+ require.NoError(t, db.Model(&types.KnowledgeTagRelation{}).+ Where("knowledge_id = ?", knowledgeID).+ Count(&count).Error)+ assert.Zero(t, count)+}+func TestGetKnowledgeTags_ReturnsTagDetails(t *testing.T) {db := setupKnowledgeTagTestDB(t)repo := &knowledgeRepository{db: db}diff --git a/internal/application/repository/knowledgebase_sqlite_test.go b/internal/application/repository/knowledgebase_sqlite_test.goindex 64af88cb9..c6fdc87fe 100644--- a/internal/application/repository/knowledgebase_sqlite_test.go+++ b/internal/application/repository/knowledgebase_sqlite_test.go@@ -32,6 +32,7 @@ CREATE TABLE IF NOT EXISTS knowledge_bases (extract_config TEXT NULL DEFAULT NULL,faq_config TEXT,question_generation_config TEXT NULL,+ auto_tag_config TEXT NULL,is_temporary BOOLEAN NOT NULL DEFAULT 0,is_pinned INTEGER NOT NULL DEFAULT 0,pinned_at DATETIME NULL,diff --git a/internal/application/service/knowledge_auto_tag.go b/internal/application/service/knowledge_auto_tag.gonew file mode 100644index 000000000..1ab261ed6--- /dev/null+++ b/internal/application/service/knowledge_auto_tag.go@@ -0,0 +1,305 @@+package service++import (+ "context"+ "encoding/json"+ "fmt"+ "sort"+ "strings"++ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/models/chat"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/hibiken/asynq"+)++const (+ defaultAutoTagMaxTags = 3+ maximumAutoTagMaxTags = 10+ maximumAutoTagCandidates = 100+ maximumAutoTagContentRunes = 16000+ minimumAutoTagConfidence = 0.75+ autoTagSpanName = "postprocess.auto_tag"+)++type KnowledgeAutoTagService struct {+ knowledgeRepo interfaces.KnowledgeRepository+ tagRepo interfaces.KnowledgeTagRepository+ kbService interfaces.KnowledgeBaseService+ chunkService interfaces.ChunkService+ modelService interfaces.ModelService+ spanTracker SpanTracker+}++func NewKnowledgeAutoTagService(+ knowledgeRepo interfaces.KnowledgeRepository,+ tagRepo interfaces.KnowledgeTagRepository,+ kbService interfaces.KnowledgeBaseService,+ chunkService interfaces.ChunkService,+ modelService interfaces.ModelService,+ spanTracker SpanTracker,+) interfaces.TaskHandler {+ return &KnowledgeAutoTagService{+ knowledgeRepo: knowledgeRepo,+ tagRepo: tagRepo,+ kbService: kbService,+ chunkService: chunkService,+ modelService: modelService,+ spanTracker: spanTracker,+ }+}++func (s *KnowledgeAutoTagService) tracker() SpanTracker {+ if s.spanTracker == nil {+ return noopSpanTracker{}+ }+ return s.spanTracker+}++type autoTagModelMatch struct {+ TagID string `json:"tag_id"`+ Confidence float64 `json:"confidence"`+ Reason string `json:"reason,omitempty"`+}++type autoTagModelResponse struct {+ Matches []autoTagModelMatch `json:"matches"`+}++func (s *KnowledgeAutoTagService) Handle(ctx context.Context, task *asynq.Task) error {+ var payload types.KnowledgeAutoTagPayload+ if err := json.Unmarshal(task.Payload(), &payload); err != nil {+ return fmt.Errorf("unmarshal knowledge auto tag payload: %w", err)+ }+ ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)+ if payload.Language != "" {+ ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)+ }++ parent := s.tracker().LookupStage(ctx, payload.KnowledgeID, payload.Attempt, types.StagePostProcess)+ span := s.tracker().BeginSubSpan(ctx, parent, autoTagSpanName, types.SpanKindSubSpan, types.JSONMap{+ "knowledge_base_id": payload.KnowledgeBaseID,+ })+ skip := func(reason string, extra types.JSONMap) error {+ if extra == nil {+ extra = types.JSONMap{}+ }+ extra["skipped"] = reason+ s.tracker().EndSpan(ctx, span, extra)+ return nil+ }++ knowledge, err := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, payload.KnowledgeID)+ if err != nil {+ s.tracker().FailSpan(ctx, span, "AUTO_TAG_KNOWLEDGE_LOAD_FAILED", err.Error(), err)+ return fmt.Errorf("get knowledge for auto tag: %w", err)+ }+ 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 {+ return skip("knowledge_not_active", types.JSONMap{"parse_status": knowledge.ParseStatus})+ }++ kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)+ if err != nil {+ s.tracker().FailSpan(ctx, span, "AUTO_TAG_KB_LOAD_FAILED", err.Error(), err)+ return fmt.Errorf("get knowledge base for auto tag: %w", err)+ }+ if kb == nil || kb.TenantID != payload.TenantID || kb.Type != types.KnowledgeBaseTypeDocument {+ return skip("knowledge_base_not_eligible", nil)+ }+ config := kb.AutoTagConfig+ if config == nil || !config.Enabled {+ return skip("auto_tag_disabled", nil)+ }+ config.Normalize()++ tags, _, err := s.tagRepo.ListByKB(ctx, payload.TenantID, payload.KnowledgeBaseID, &types.Pagination{Page: 1, PageSize: 1000}, "")+ 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)+ }+ if len(tags) == 0 {+ return skip("no_candidate_tags", nil)+ }+ if len(tags) > maximumAutoTagCandidates {+ return skip("too_many_candidate_tags", types.JSONMap{"candidate_tag_count": len(tags)})+ }++ modelID := strings.TrimSpace(config.ModelID)+ if modelID == "" {+ modelID = strings.TrimSpace(kb.SummaryModelID)+ }+ if modelID == "" {+ return skip("model_not_configured", nil)+ }++ chunks, err := s.chunkService.ListChunksByKnowledgeID(ctx, payload.KnowledgeID)+ if err != nil {+ s.tracker().FailSpan(ctx, span, "AUTO_TAG_LIST_CHUNKS_FAILED", err.Error(), err)+ return fmt.Errorf("list chunks for auto tag: %w", err)+ }+ content := buildAutoTagDocumentContent(knowledge, chunks)+ if strings.TrimSpace(content) == "" {+ return skip("no_text_chunks", nil)+ }++ chatModel, err := s.modelService.GetChatModel(ctx, modelID)+ if err != nil {+ s.tracker().FailSpan(ctx, span, "AUTO_TAG_MODEL_LOAD_FAILED", err.Error(), err)+ return fmt.Errorf("get auto tag model: %w", err)+ }+ response, err := classifyExistingTags(ctx, chatModel, tags, content, config.MaxTags)+ if err != nil {+ s.tracker().FailSpan(ctx, span, "AUTO_TAG_MODEL_CALL_FAILED", err.Error(), err)+ return err+ }++ validIDs := validateAutoTagMatches(tags, response.Matches, config.MaxTags)+ if len(validIDs) == 0 {+ return skip("no_matching_tags", types.JSONMap{"candidate_tag_count": len(tags), "model_id": modelID})+ }++ existing, err := s.knowledgeRepo.GetKnowledgeTags(ctx, []string{payload.KnowledgeID})+ if err != nil {+ s.tracker().FailSpan(ctx, span, "AUTO_TAG_LOAD_EXISTING_FAILED", err.Error(), err)+ return fmt.Errorf("get existing knowledge tags: %w", err)+ }+ existingIDs := make(map[string]struct{}, len(existing[payload.KnowledgeID]))+ for _, tag := range existing[payload.KnowledgeID] {+ existingIDs[tag.ID] = struct{}{}+ }+ added := make([]string, 0, len(validIDs))+ for _, id := range validIDs {+ if _, ok := existingIDs[id]; !ok {+ added = append(added, id)+ }+ }+ if len(added) == 0 {+ return skip("all_matches_already_attached", types.JSONMap{"matched_tag_count": len(validIDs)})+ }+ adder, ok := s.knowledgeRepo.(interface {+ AddKnowledgeTagRelations(context.Context, uint64, string, string, []string) error+ })+ if !ok {+ err := fmt.Errorf("knowledge repository does not support incremental tag relations")+ 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 {+ s.tracker().FailSpan(ctx, span, "AUTO_TAG_PERSIST_FAILED", err.Error(), err)+ return fmt.Errorf("add automatic knowledge tags: %w", err)+ }++ logger.Infof(ctx, "[KnowledgeAutoTag] Added %d tag(s) to knowledge %s", len(added), payload.KnowledgeID)+ s.tracker().EndSpan(ctx, span, types.JSONMap{+ "candidate_tag_count": len(tags),+ "matched_tag_count": len(validIDs),+ "added_tag_count": len(added),+ "added_tag_ids": added,+ "model_id": modelID,+ })+ return nil+}++func buildAutoTagDocumentContent(knowledge *types.Knowledge, chunks []*types.Chunk) string {+ parts := make([]string, 0, len(chunks)+2)+ if name := strings.TrimSpace(knowledge.FileName); name != "" {+ parts = append(parts, "Document name: "+name)+ }+ if summary := strings.TrimSpace(knowledge.Description); summary != "" {+ parts = append(parts, "Existing summary: "+summary)+ }+ orderedChunks := make([]*types.Chunk, 0, len(chunks))+ for _, chunk := range chunks {+ if chunk != nil {+ orderedChunks = append(orderedChunks, chunk)+ }+ }+ 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 {+ continue+ }+ if text := strings.TrimSpace(chunk.Content); text != "" {+ parts = append(parts, text)+ }+ }+ 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) {+ if maxTags <= 0 {+ maxTags = defaultAutoTagMaxTags+ }+ if maxTags > maximumAutoTagMaxTags {+ maxTags = maximumAutoTagMaxTags+ }+ candidates := make([]string, 0, len(tags))+ for _, tag := range tags {+ candidates = append(candidates, fmt.Sprintf("- id=%s name=%q", tag.ID, tag.Name))+ }+ 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)+ 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{+ {Role: "system", Content: systemPrompt},+ {Role: "user", Content: userPrompt},+ }, &chat.ChatOptions{Temperature: 0.1, MaxTokens: 1024, Thinking: &thinking})+ if err != nil {+ return nil, fmt.Errorf("classify automatic tags: %w", err)+ }+ var parsed autoTagModelResponse+ if err := json.Unmarshal([]byte(stripJSONCodeFence(result.Content)), &parsed); err != nil {+ return nil, fmt.Errorf("parse automatic tag response: %w", err)+ }+ return &parsed, nil+}++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]) == "```" {+ value = strings.Join(lines[1:len(lines)-1], "\n")+ }+ }+ return strings.TrimSpace(value)+}++func validateAutoTagMatches(tags []*types.KnowledgeTag, matches []autoTagModelMatch, maxTags int) []string {+ if maxTags <= 0 {+ maxTags = defaultAutoTagMaxTags+ }+ if maxTags > maximumAutoTagMaxTags {+ maxTags = maximumAutoTagMaxTags+ }+ allowed := make(map[string]struct{}, len(tags))+ for _, tag := range tags {+ allowed[tag.ID] = struct{}{}+ }+ sort.SliceStable(matches, func(i, j int) bool { return matches[i].Confidence > matches[j].Confidence })+ seen := make(map[string]struct{}, len(matches))+ result := make([]string, 0, maxTags)+ for _, match := range matches {+ if match.Confidence < minimumAutoTagConfidence {+ continue+ }+ if _, ok := allowed[match.TagID]; !ok {+ continue+ }+ if _, ok := seen[match.TagID]; ok {+ continue+ }+ seen[match.TagID] = struct{}{}+ result = append(result, match.TagID)+ if len(result) == maxTags {+ break+ }+ }+ return result+}diff --git a/internal/application/service/knowledge_auto_tag_test.go b/internal/application/service/knowledge_auto_tag_test.gonew file mode 100644index 000000000..3b7465cbf--- /dev/null+++ b/internal/application/service/knowledge_auto_tag_test.go@@ -0,0 +1,73 @@+package service++import (+ "context"+ "encoding/json"+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/hibiken/asynq"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++type autoTagRecordingQueue struct {+ interfaces.TaskEnqueuer+ task *asynq.Task+}++func (q *autoTagRecordingQueue) Enqueue(task *asynq.Task, _ ...asynq.Option) (*asynq.TaskInfo, error) {+ q.task = task+ return &asynq.TaskInfo{ID: "auto-tag", Type: task.Type()}, nil+}++func TestStripJSONCodeFence(t *testing.T) {+ assert.Equal(t, `{"matches":[]}`, stripJSONCodeFence("```json\n{\"matches\":[]}\n```"))+ assert.Equal(t, `{"matches":[]}`, stripJSONCodeFence(" {\"matches\":[]} "))+}++func TestValidateAutoTagMatches(t *testing.T) {+ tags := []*types.KnowledgeTag{{ID: "a"}, {ID: "b"}, {ID: "c"}}+ matches := []autoTagModelMatch{+ {TagID: "unknown", Confidence: 1},+ {TagID: "a", Confidence: 0.70},+ {TagID: "b", Confidence: 0.90},+ {TagID: "b", Confidence: 0.95},+ {TagID: "c", Confidence: 0.80},+ }+ assert.Equal(t, []string{"b", "c"}, validateAutoTagMatches(tags, matches, 2))+}++func TestBuildAutoTagDocumentContentSamplesAndFilters(t *testing.T) {+ knowledge := &types.Knowledge{FileName: "policy.pdf", Description: "HR policy"}+ large := strings.Repeat("x", maximumAutoTagContentRunes+1000)+ chunks := []*types.Chunk{+ nil,+ {ChunkType: types.ChunkTypeText, Content: large, StartAt: 2},+ {ChunkType: types.ChunkTypeText, Content: "first", StartAt: 1},+ }+ content := buildAutoTagDocumentContent(knowledge, chunks)+ require.NotEmpty(t, content)+ assert.Contains(t, content, "Document name: policy.pdf")+ assert.Contains(t, content, "Existing summary: HR policy")+ assert.LessOrEqual(t, len([]rune(content)), maximumAutoTagContentRunes)+}++func TestEnqueueAutoTagTaskCarriesScopeWithoutOwningFinalizingSlot(t *testing.T) {+ queue := &autoTagRecordingQueue{}+ service := &KnowledgePostProcessService{taskEnqueuer: queue}+ ok := service.enqueueAutoTagTask(context.Background(), types.KnowledgePostProcessPayload{+ TenantID: 7, KnowledgeBaseID: "kb", KnowledgeID: "doc", Language: "zh-CN",+ }, 4)+ require.True(t, ok)+ require.NotNil(t, queue.task)+ assert.Equal(t, types.TypeKnowledgeAutoTag, queue.task.Type())+ var payload types.KnowledgeAutoTagPayload+ require.NoError(t, json.Unmarshal(queue.task.Payload(), &payload))+ assert.Equal(t, uint64(7), payload.TenantID)+ assert.Equal(t, "kb", payload.KnowledgeBaseID)+ assert.Equal(t, "doc", payload.KnowledgeID)+ assert.Equal(t, 4, payload.Attempt)+}diff --git a/internal/application/service/knowledge_post_process.go b/internal/application/service/knowledge_post_process.goindex e08a7514f..293ebb35b 100644--- a/internal/application/service/knowledge_post_process.go+++ b/internal/application/service/knowledge_post_process.go@@ -177,6 +177,9 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.TawillSpawnQuestion := willSpawnSummary && kb.NeedsEmbeddingModel() &&eff.QuestionGenerationConfig.EnabledwillSpawnWiki := kb.IndexingStrategy.WikiEnabled && len(textChunks) > 0+ willSpawnAutoTag := kb.Type == types.KnowledgeBaseTypeDocument &&+ kb.AutoTagConfig != nil && kb.AutoTagConfig.Enabled && len(textChunks) > 0+ enqueuedAutoTag := false// Question generation now fans out one subtask per plain text chunk// (mirroring the graph-extract per-chunk pattern) so each chunk's LLM@@ -336,6 +339,13 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta}}+ // Queue best-effort automatic tagging only after the processing row has+ // successfully handed off to finalizing. This avoids model calls from a+ // duplicate post-process delivery that observes an already terminal row.+ if willSpawnAutoTag {+ enqueuedAutoTag = s.enqueueAutoTagTask(ctx, payload, attempt)+ }+// 4. Spawn Summary and Question TasksenqueuedSummary := falseenqueuedQuestionCount := 0@@ -460,6 +470,7 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta"wiki_slot_owned": wikiSlotOwned,"enqueued_graph": enqueuedGraphCount > 0,"enqueued_graph_count": enqueuedGraphCount,+ "enqueued_auto_tag": enqueuedAutoTag,}s.tracker().EndSpan(ctx, postSpan, postOutput)if wikiSlotOwned && wikiEnqueueErr != nil {@@ -475,6 +486,36 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Tareturn nil}+// 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 {+ if s.taskEnqueuer == nil {+ return false+ }+ taskPayload := types.KnowledgeAutoTagPayload{+ TenantID: payload.TenantID,+ KnowledgeBaseID: payload.KnowledgeBaseID,+ KnowledgeID: payload.KnowledgeID,+ Language: payload.Language,+ Attempt: attempt,+ }+ langfuse.InjectTracing(ctx, &taskPayload)+ payloadBytes, err := json.Marshal(taskPayload)+ if err != nil {+ logger.Warnf(ctx, "[KnowledgePostProcess] Failed to marshal auto tag payload: %v", err)+ return false+ }+ task := asynq.NewTask(types.TypeKnowledgeAutoTag, payloadBytes,+ asynq.Queue(types.QueueSummary), asynq.MaxRetry(2), asynq.Timeout(2*time.Minute))+ if _, err := s.taskEnqueuer.Enqueue(task); err != nil {+ logger.Warnf(ctx, "[KnowledgePostProcess] Failed to enqueue automatic tagging for %s: %v", payload.KnowledgeID, err)+ return false+ }+ logger.Infof(ctx, "[KnowledgePostProcess] Enqueued automatic tagging for %s", payload.KnowledgeID)+ return true+}+// enqueueSummaryGenerationTask enqueues the summary task. Returns true only// when a task was actually placed on the queue, so the caller can release the// seeded pending-subtask slot when enqueue is skipped or fails.diff --git a/internal/application/service/knowledgebase.go b/internal/application/service/knowledgebase.goindex 9f6b0169a..f3799a175 100644--- a/internal/application/service/knowledgebase.go+++ b/internal/application/service/knowledgebase.go@@ -529,6 +529,10 @@ func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,if config.WikiConfig != nil {kb.WikiConfig = config.WikiConfig}+ if config.AutoTagConfig != nil {+ config.AutoTagConfig.Normalize()+ kb.AutoTagConfig = config.AutoTagConfig+ }// Update indexing strategy — syncs to ExtractConfig for backward compatif config.IndexingStrategy != nil {if !config.IndexingStrategy.HasAnyIndexing() {diff --git a/internal/application/service/vectorstore_test.go b/internal/application/service/vectorstore_test.goindex 42605ee5b..7a9fd2c1e 100644--- a/internal/application/service/vectorstore_test.go+++ b/internal/application/service/vectorstore_test.go@@ -838,6 +838,7 @@ CREATE TABLE IF NOT EXISTS knowledge_bases (extract_config TEXT NULL DEFAULT NULL,faq_config TEXT,question_generation_config TEXT NULL,+ auto_tag_config TEXT NULL,is_temporary BOOLEAN NOT NULL DEFAULT 0,is_pinned INTEGER NOT NULL DEFAULT 0,pinned_at DATETIME NULL,diff --git a/internal/container/container.go b/internal/container/container.goindex a5fe47f9f..8ddb0412c 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -209,6 +209,7 @@ func BuildContainer(container *dig.Container) *dig.Container {must(container.Provide(service.NewDataTableSummaryService, dig.Name("dataTableSummary")))must(container.Provide(service.NewImageMultimodalService, dig.Name("imageMultimodal")))must(container.Provide(service.NewKnowledgePostProcessService, dig.Name("knowledgePostProcess")))+ must(container.Provide(service.NewKnowledgeAutoTagService, dig.Name("knowledgeAutoTag")))must(container.Provide(service.NewMessageService))must(container.Provide(service.NewMessageSuggestionService))diff --git a/internal/database/migration_sqlite_test.go b/internal/database/migration_sqlite_test.gonew file mode 100644index 000000000..52161b0cd--- /dev/null+++ b/internal/database/migration_sqlite_test.go@@ -0,0 +1,44 @@+package database++import (+ "database/sql"+ "os"+ "path/filepath"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestSQLiteMigrationsIncludeAutoTagConfig(t *testing.T) {+ repoRoot, err := filepath.Abs(filepath.Join("..", ".."))+ require.NoError(t, err)+ previousDir, err := os.Getwd()+ require.NoError(t, err)+ require.NoError(t, os.Chdir(repoRoot))+ t.Cleanup(func() { _ = os.Chdir(previousDir) })++ dbPath := filepath.Join(t.TempDir(), "migration.db")+ require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))++ db, err := sql.Open("sqlite3", dbPath)+ require.NoError(t, err)+ t.Cleanup(func() { _ = db.Close() })++ rows, err := db.Query("PRAGMA table_info(knowledge_bases)")+ require.NoError(t, err)+ defer rows.Close()++ found := false+ for rows.Next() {+ var cid int+ var name, columnType string+ var notNull, primaryKey int+ var defaultValue any+ require.NoError(t, rows.Scan(&cid, &name, &columnType, ¬Null, &defaultValue, &primaryKey))+ if name == "auto_tag_config" {+ found = true+ }+ }+ require.NoError(t, rows.Err())+ require.True(t, found, "SQLite migrations must create knowledge_bases.auto_tag_config")+}diff --git a/internal/router/sync_task.go b/internal/router/sync_task.goindex c31650032..e1dc80221 100644--- a/internal/router/sync_task.go+++ b/internal/router/sync_task.go@@ -127,6 +127,7 @@ type SyncTaskParams struct {DataTableSummary interfaces.TaskHandler `name:"dataTableSummary"`ImageMultimodal interfaces.TaskHandler `name:"imageMultimodal"`KnowledgePostProcess interfaces.TaskHandler `name:"knowledgePostProcess"`+ KnowledgeAutoTag interfaces.TaskHandler `name:"knowledgeAutoTag"`WikiIngest interfaces.TaskHandler `name:"wikiIngest"`TemporaryDocument interfaces.TemporaryDocumentService}@@ -150,6 +151,7 @@ func RegisterSyncHandlers(params SyncTaskParams) {params.Executor.RegisterHandler(types.TypeKBDelete, params.KnowledgeBaseService.ProcessKBDelete)params.Executor.RegisterHandler(types.TypeImageMultimodal, params.ImageMultimodal.Handle)params.Executor.RegisterHandler(types.TypeKnowledgePostProcess, params.KnowledgePostProcess.Handle)+ params.Executor.RegisterHandler(types.TypeKnowledgeAutoTag, params.KnowledgeAutoTag.Handle)params.Executor.RegisterHandler(types.TypeDataSourceSync, params.DataSourceService.ProcessSync)params.Executor.RegisterHandler(types.TypeWikiIngest, params.WikiIngest.Handle)params.Executor.RegisterHandler(types.TypeWikiFinalize, params.WikiIngest.Handle)diff --git a/internal/router/task.go b/internal/router/task.goindex 3097fa2ab..1302438e7 100644--- a/internal/router/task.go+++ b/internal/router/task.go@@ -42,6 +42,7 @@ type AsynqTaskParams struct {DataTableSummary interfaces.TaskHandler `name:"dataTableSummary"`ImageMultimodal interfaces.TaskHandler `name:"imageMultimodal"`KnowledgePostProcess interfaces.TaskHandler `name:"knowledgePostProcess"`+ KnowledgeAutoTag interfaces.TaskHandler `name:"knowledgeAutoTag"`WikiIngest interfaces.TaskHandler `name:"wikiIngest"`TemporaryDocument interfaces.TemporaryDocumentServiceDeadLetterRepo interfaces.TaskDeadLetterRepository@@ -300,6 +301,7 @@ func RunAsynqServer(params AsynqTaskParams) *asynq.ServeMux {// Register knowledge post process handlermux.HandleFunc(types.TypeKnowledgePostProcess, params.KnowledgePostProcess.Handle)+ mux.HandleFunc(types.TypeKnowledgeAutoTag, params.KnowledgeAutoTag.Handle)// Register data source sync handlermux.HandleFunc(types.TypeDataSourceSync, params.DataSourceService.ProcessSync)diff --git a/internal/types/knowledgebase.go b/internal/types/knowledgebase.goindex 6ca36ac38..c46ce8ba8 100644--- a/internal/types/knowledgebase.go+++ b/internal/types/knowledgebase.go@@ -107,6 +107,8 @@ type KnowledgeBase struct {FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config" gorm:"column:faq_config;type:json"`// QuestionGenerationConfig stores question generation configuration for document knowledge basesQuestionGenerationConfig *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"`// 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.@@ -156,11 +158,51 @@ type KnowledgeBaseConfig struct {FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config"`// Wiki configuration (only for wiki-enabled knowledge bases)WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config"`+ // AutoTagConfig controls optional automatic association of existing KB tags.+ AutoTagConfig *AutoTagConfig `yaml:"auto_tag_config" json:"auto_tag_config"`// IndexingStrategy controls which indexing pipelines are active.// nil means "no change" when updating (preserves existing strategy).IndexingStrategy *IndexingStrategy `yaml:"indexing_strategy" json:"indexing_strategy"`}+// AutoTagConfig controls asynchronous document auto-tagging. It is deliberately+// opt-in so upgrading an existing deployment does not add model calls or alter+// document tags unexpectedly.+type AutoTagConfig struct {+ Enabled bool `yaml:"enabled" json:"enabled"`+ ModelID string `yaml:"model_id,omitempty" json:"model_id,omitempty"`+ MaxTags int `yaml:"max_tags,omitempty" json:"max_tags,omitempty"`+}++func (c AutoTagConfig) Value() (driver.Value, error) { return json.Marshal(c) }++func (c *AutoTagConfig) Scan(value interface{}) error {+ if value == nil {+ return nil+ }+ b, ok := value.([]byte)+ if !ok {+ if s, ok := value.(string); ok {+ b = []byte(s)+ } else {+ return nil+ }+ }+ return json.Unmarshal(b, c)+}++func (c *AutoTagConfig) Normalize() {+ if c == nil {+ return+ }+ if c.MaxTags <= 0 {+ c.MaxTags = 3+ }+ if c.MaxTags > 10 {+ c.MaxTags = 10+ }+}+// ParserEngineRule maps a set of file types to a specific parser engine.type ParserEngineRule struct {FileTypes []string `yaml:"file_types" json:"file_types"`@@ -627,6 +669,9 @@ func (kb *KnowledgeBase) EnsureDefaults() {if kb.Type != KnowledgeBaseTypeFAQ {kb.FAQConfig = nil}+ if kb.AutoTagConfig != nil {+ kb.AutoTagConfig.Normalize()+ }// Set defaults for FAQif kb.Type == KnowledgeBaseTypeFAQ {if kb.FAQConfig == nil {diff --git a/internal/types/knowledgebase_auto_tag_test.go b/internal/types/knowledgebase_auto_tag_test.gonew file mode 100644index 000000000..1b1bc5ab6--- /dev/null+++ b/internal/types/knowledgebase_auto_tag_test.go@@ -0,0 +1,17 @@+package types++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++func TestAutoTagConfigNormalize(t *testing.T) {+ config := &AutoTagConfig{Enabled: true}+ config.Normalize()+ assert.Equal(t, 3, config.MaxTags)++ config.MaxTags = 99+ config.Normalize()+ assert.Equal(t, 10, config.MaxTags)+}diff --git a/internal/types/task.go b/internal/types/task.goindex 9f16b2e72..a58561ee8 100644--- a/internal/types/task.go+++ b/internal/types/task.go@@ -69,7 +69,7 @@ var queueDefinitions = []QueueDefinition{TypeKnowledgePostProcess,}},{Name: QueueSummary, Pool: WorkerPoolEnrichment, Weight: 2, SharedWeight: 2, TaskTypes: []string{- TypeSummaryGeneration, TypeDataTableSummary,+ TypeSummaryGeneration, TypeDataTableSummary, TypeKnowledgeAutoTag,}},{Name: QueueMultimodal, Pool: WorkerPoolEnrichment, Weight: 1, SharedWeight: 1, TaskTypes: []string{TypeImageMultimodal}},{Name: QueueGraph, Pool: WorkerPoolEnrichment, Weight: 1, SharedWeight: 1, TaskTypes: []string{TypeChunkExtract}},@@ -241,6 +241,7 @@ const (TypeDataTableSummary = "datatable:summary" // 表格摘要任务TypeImageMultimodal = "image:multimodal" // 图片多模态处理任务(OCR + VLM Caption)TypeKnowledgePostProcess = "knowledge:post_process" // 知识后处理任务(统一调度)+ TypeKnowledgeAutoTag = "knowledge:auto_tag" // 文档自动关联知识库已有标签TypeManualProcess = "manual:process" // 手工知识更新任务(cleanup + 重新索引)TypeDataSourceSync = "datasource:sync" // 数据源同步任务TypeWikiIngest = "wiki:ingest" // Wiki 页面同步任务@@ -498,6 +499,17 @@ type KnowledgePostProcessPayload struct {Attempt int `json:"attempt,omitempty"`}+// KnowledgeAutoTagPayload identifies a document whose parsed content should be+// classified against the latest set of existing tags in its knowledge base.+type KnowledgeAutoTagPayload struct {+ TracingContext+ TenantID uint64 `json:"tenant_id"`+ KnowledgeID string `json:"knowledge_id"`+ KnowledgeBaseID string `json:"knowledge_base_id"`+ Language string `json:"language,omitempty"`+ Attempt int `json:"attempt,omitempty"`+}+// KBCloneTaskStatus represents the status of a knowledge base clone tasktype KBCloneTaskStatus stringdiff --git a/internal/types/task_queue_test.go b/internal/types/task_queue_test.goindex 4b24f397d..d2d946b1e 100644--- a/internal/types/task_queue_test.go+++ b/internal/types/task_queue_test.go@@ -83,7 +83,7 @@ func TestEveryAsynqTaskTypeHasADeclaredQueue(t *testing.T) {TypeQuestionGeneration, TypeSummaryGeneration, TypeKBClone,TypeIndexDelete, TypeKBDelete, TypeKnowledgeListDelete,TypeKnowledgeListReparse, TypeKnowledgeMove, TypeDataTableSummary,- TypeImageMultimodal, TypeKnowledgePostProcess, TypeManualProcess,+ TypeImageMultimodal, TypeKnowledgePostProcess, TypeKnowledgeAutoTag, TypeManualProcess,TypeDataSourceSync, TypeWikiIngest, TypeWikiFinalize, TypeTemporaryDocumentProcess,}for _, taskType := range taskTypes {@@ -93,6 +93,19 @@ func TestEveryAsynqTaskTypeHasADeclaredQueue(t *testing.T) {}}+func TestKnowledgeAutoTagUsesEnrichmentPool(t *testing.T) {+ queue, ok := QueueForTaskType(TypeKnowledgeAutoTag)+ if !ok || queue != QueueSummary {+ t.Fatalf("automatic tagging must use %q, got %q", QueueSummary, queue)+ }+ if QueueWeightsForPool(WorkerPoolPostProcess)[queue] != 0 {+ t.Fatalf("automatic tagging must not consume post-process orchestration capacity")+ }+ if QueueWeightsForPool(WorkerPoolEnrichment)[queue] <= 0 {+ t.Fatalf("automatic tagging queue must be consumed by the enrichment pool")+ }+}+func TestDefaultWorkerPoolConcurrencyIsExplicitBudget(t *testing.T) {allocation := DefaultWorkerPoolConcurrency()if allocation.UpstreamTotal() != DefaultUpstreamWorkerConcurrency {diff --git a/migrations/mysql/00-init-db.sql b/migrations/mysql/00-init-db.sqlindex a4c7aec60..4f88a46cd 100644--- a/migrations/mysql/00-init-db.sql+++ b/migrations/mysql/00-init-db.sql@@ -52,6 +52,7 @@ CREATE TABLE knowledge_bases (cos_config JSON NOT NULL,vlm_config JSON NOT NULL,extract_config JSON NULL,+ auto_tag_config JSON NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,deleted_at TIMESTAMP NULL DEFAULT NULLdiff --git a/migrations/paradedb/00-init-db.sql b/migrations/paradedb/00-init-db.sqlindex 738022496..49416bdf6 100644--- a/migrations/paradedb/00-init-db.sql+++ b/migrations/paradedb/00-init-db.sql@@ -64,6 +64,7 @@ CREATE TABLE IF NOT EXISTS knowledge_bases (cos_config JSONB NOT NULL DEFAULT '{}',vlm_config JSONB NOT NULL DEFAULT '{}',extract_config JSONB NULL DEFAULT NULL,+ auto_tag_config JSONB NULL,created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,deleted_at TIMESTAMP WITH TIME ZONEdiff --git a/migrations/sqlite/000003_knowledge_base_auto_tag_config.down.sql b/migrations/sqlite/000003_knowledge_base_auto_tag_config.down.sqlnew file mode 100644index 000000000..7e5bca01d--- /dev/null+++ b/migrations/sqlite/000003_knowledge_base_auto_tag_config.down.sql@@ -0,0 +1 @@+ALTER TABLE knowledge_bases DROP COLUMN auto_tag_config;diff --git a/migrations/sqlite/000003_knowledge_base_auto_tag_config.up.sql b/migrations/sqlite/000003_knowledge_base_auto_tag_config.up.sqlnew file mode 100644index 000000000..091f82221--- /dev/null+++ b/migrations/sqlite/000003_knowledge_base_auto_tag_config.up.sql@@ -0,0 +1 @@+ALTER TABLE knowledge_bases ADD COLUMN auto_tag_config TEXT;diff --git a/migrations/versioned/000080_knowledge_base_auto_tag_config.down.sql b/migrations/versioned/000080_knowledge_base_auto_tag_config.down.sqlnew file mode 100644index 000000000..795ccb812--- /dev/null+++ b/migrations/versioned/000080_knowledge_base_auto_tag_config.down.sql@@ -0,0 +1 @@+ALTER TABLE knowledge_bases DROP COLUMN IF EXISTS auto_tag_config;diff --git a/migrations/versioned/000080_knowledge_base_auto_tag_config.up.sql b/migrations/versioned/000080_knowledge_base_auto_tag_config.up.sqlnew file mode 100644index 000000000..10e7f4155--- /dev/null+++ b/migrations/versioned/000080_knowledge_base_auto_tag_config.up.sql@@ -0,0 +1,2 @@+-- Migration 000080: opt-in automatic association of existing knowledge-base tags.+ALTER TABLE knowledge_bases ADD COLUMN IF NOT EXISTS auto_tag_config JSONB;