feat: 增加自动添加标签的功能
parent
d7a620d278
commit
9426ee1470
|
|
@ -1,5 +1,6 @@
|
|||
# 忽略所有隐藏文件和目录
|
||||
.*
|
||||
|
||||
# 但不忽略特定隐藏文件和目录
|
||||
!.env.example
|
||||
!.gitignore
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
:disabled="disabled"
|
||||
:loading="loading"
|
||||
:status="status"
|
||||
:clearable="clearable"
|
||||
filterable
|
||||
style="width: 100%;"
|
||||
>
|
||||
|
|
@ -53,6 +54,7 @@ interface Props {
|
|||
disabled?: boolean
|
||||
placeholder?: string
|
||||
status?: 'default' | 'success' | 'warning' | 'error'
|
||||
clearable?: boolean
|
||||
// 可选:外部传入的所有模型列表,如果提供则不调用API
|
||||
allModels?: 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 || '')
|
||||
}
|
||||
|
||||
// 暴露刷新方法给父组件
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -3311,6 +3311,15 @@ export default {
|
|||
instructionsLabel: '질문 생성 지침',
|
||||
instructionsDescription: '안정적인 출력 형식을 유지하면서 대상, 상황 및 표현 방식을 지정합니다',
|
||||
instructionsPlaceholder: '예: 시험 문제 형식을 피하고 자연스러운 고객 지원 질문을 생성…'
|
||||
},
|
||||
autoTag: {
|
||||
label: '자동 태그 연결',
|
||||
description: '문서 파싱 후 현재 지식베이스의 기존 태그 중 적합한 태그를 연결합니다. 태그를 생성하거나 삭제하지 않으며 모델 호출이 한 번 추가됩니다.',
|
||||
modelLabel: '분류 모델',
|
||||
modelDescription: '비워 두면 지식베이스 요약 모델을 사용합니다.',
|
||||
modelPlaceholder: '분류 모델 선택',
|
||||
maxTagsLabel: '문서당 최대 태그 수',
|
||||
maxTagsDescription: '문서마다 기존 태그 1-10개를 자동 연결합니다.'
|
||||
}
|
||||
},
|
||||
asr: {
|
||||
|
|
|
|||
|
|
@ -3311,6 +3311,15 @@ export default {
|
|||
instructionsLabel: 'Инструкции генерации вопросов',
|
||||
instructionsDescription: 'Задайте аудиторию, сценарий и формулировки, сохраняя стабильный формат вывода',
|
||||
instructionsPlaceholder: 'Например: естественные вопросы службы поддержки без экзаменационного стиля…'
|
||||
},
|
||||
autoTag: {
|
||||
label: 'Автоматические теги',
|
||||
description: 'После разбора документа выбираются подходящие существующие теги базы знаний. Теги не создаются и не удаляются, но выполняется дополнительный вызов модели.',
|
||||
modelLabel: 'Модель классификации',
|
||||
modelDescription: 'Если не выбрана, используется модель резюмирования базы знаний.',
|
||||
modelPlaceholder: 'Выберите модель классификации',
|
||||
maxTagsLabel: 'Максимум тегов на документ',
|
||||
maxTagsDescription: 'Автоматически связывать от 1 до 10 существующих тегов.'
|
||||
}
|
||||
},
|
||||
asr: {
|
||||
|
|
|
|||
|
|
@ -3311,6 +3311,15 @@ export default {
|
|||
instructionsLabel: '问题生成要求',
|
||||
instructionsDescription: '指定问题面向的人群、场景和表达方式,系统仍维护稳定输出格式',
|
||||
instructionsPlaceholder: '例如:生成客服用户常问的自然语言问题,避免考试题式表达…'
|
||||
},
|
||||
autoTag: {
|
||||
label: '自动关联标签',
|
||||
description: '文档解析完成后,从当前知识库已有标签中选择合适标签自动关联。不会创建或删除标签,并会增加一次模型调用。',
|
||||
modelLabel: '分类模型',
|
||||
modelDescription: '留空时使用知识库摘要模型。',
|
||||
modelPlaceholder: '请选择分类模型',
|
||||
maxTagsLabel: '单篇文档最多标签数',
|
||||
maxTagsDescription: '每篇文档最多自动关联 1-10 个已有标签。'
|
||||
}
|
||||
},
|
||||
asr: {
|
||||
|
|
|
|||
|
|
@ -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_config
|
||||
updateConfig.indexing_strategy = {
|
||||
vector_enabled: formData.value.indexingStrategy?.vectorEnabled ?? true,
|
||||
keyword_enabled: formData.value.indexingStrategy?.keywordEnabled ?? true,
|
||||
|
|
|
|||
|
|
@ -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?: AutoTagConfig
|
||||
ragEnabled?: boolean
|
||||
allModels?: 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 = 3
|
||||
|
|
|
|||
|
|
@ -2,10 +2,12 @@ package repository
|
|||
|
||||
import (
|
||||
"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(
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
|
|
@ -177,6 +177,9 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
|||
willSpawnQuestion := willSpawnSummary && kb.NeedsEmbeddingModel() &&
|
||||
eff.QuestionGenerationConfig.Enabled
|
||||
willSpawnWiki := 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 Tasks
|
||||
enqueuedSummary := false
|
||||
enqueuedQuestionCount := 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.Ta
|
|||
return 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.
|
||||
|
|
|
|||
|
|
@ -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 compat
|
||||
if config.IndexingStrategy != nil {
|
||||
if !config.IndexingStrategy.HasAnyIndexing() {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
}
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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.TemporaryDocumentService
|
||||
DeadLetterRepo interfaces.TaskDeadLetterRepository
|
||||
|
|
@ -300,6 +301,7 @@ func RunAsynqServer(params AsynqTaskParams) *asynq.ServeMux {
|
|||
|
||||
// Register knowledge post process handler
|
||||
mux.HandleFunc(types.TypeKnowledgePostProcess, params.KnowledgePostProcess.Handle)
|
||||
mux.HandleFunc(types.TypeKnowledgeAutoTag, params.KnowledgeAutoTag.Handle)
|
||||
|
||||
// Register data source sync handler
|
||||
mux.HandleFunc(types.TypeDataSourceSync, params.DataSourceService.ProcessSync)
|
||||
|
|
|
|||
|
|
@ -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 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"`
|
||||
// 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 FAQ
|
||||
if kb.Type == KnowledgeBaseTypeFAQ {
|
||||
if kb.FAQConfig == nil {
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
@ -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 task
|
||||
type KBCloneTaskStatus string
|
||||
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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 NULL
|
||||
|
|
|
|||
|
|
@ -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 ZONE
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
ALTER TABLE knowledge_bases DROP COLUMN auto_tag_config;
|
||||
|
|
@ -0,0 +1 @@
|
|||
ALTER TABLE knowledge_bases ADD COLUMN auto_tag_config TEXT;
|
||||
|
|
@ -0,0 +1 @@
|
|||
ALTER TABLE knowledge_bases DROP COLUMN IF EXISTS auto_tag_config;
|
||||
|
|
@ -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;
|
||||
Loading…
Reference in New Issue