feat: 添加AI问题生成功能,支持配置生成数量并在前端展示生成的问题
This commit is contained in:
@@ -60,7 +60,6 @@ func (r *chunkRepository) ListChunksByKnowledgeID(
|
||||
) ([]*types.Chunk, error) {
|
||||
var chunks []*types.Chunk
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info").
|
||||
Where("tenant_id = ? AND knowledge_id = ? and chunk_type = ?", tenantID, knowledgeID, "text").
|
||||
Order("chunk_index ASC").
|
||||
Find(&chunks).Error; err != nil {
|
||||
@@ -85,7 +84,7 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
|
||||
|
||||
baseFilter := func(db *gorm.DB) *gorm.DB {
|
||||
db = db.Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN (?) AND status in (?)",
|
||||
tenantID, knowledgeID, chunkType, []types.ChunkStatus{types.ChunkStatusIndexed, types.ChunkStatusDefault})
|
||||
tenantID, knowledgeID, chunkType, []int{int(types.ChunkStatusIndexed), int(types.ChunkStatusDefault)})
|
||||
if tagID != "" {
|
||||
db = db.Where("tag_id = ?", tagID)
|
||||
}
|
||||
@@ -106,7 +105,7 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
|
||||
// Then query the paginated data
|
||||
dataQuery := baseFilter(
|
||||
r.db.WithContext(ctx).
|
||||
Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info, metadata, tag_id"),
|
||||
Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info, metadata, tag_id, status"),
|
||||
)
|
||||
|
||||
if err := dataQuery.
|
||||
|
||||
@@ -291,7 +291,7 @@ func (g *pgRepository) VectorRetrieve(ctx context.Context,
|
||||
ORDER BY embedding::halfvec(%d) <=> $1::halfvec
|
||||
LIMIT $%d
|
||||
) AS candidates
|
||||
WHERE distance < $%d
|
||||
WHERE distance <= $%d
|
||||
ORDER BY distance ASC
|
||||
LIMIT $%d
|
||||
`, dimension, whereClause, dimension, subqueryLimitParam, thresholdParam, finalLimitParam)
|
||||
|
||||
@@ -5,34 +5,24 @@ import (
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/yanyiwu/gojieba"
|
||||
)
|
||||
|
||||
// PluginPreprocess Query preprocessing plugin
|
||||
type PluginPreprocess struct {
|
||||
config *config.Config
|
||||
jieba *gojieba.Jieba
|
||||
stopwords map[string]struct{}
|
||||
modelService interfaces.ModelService
|
||||
}
|
||||
|
||||
// Regular expressions for text cleaning
|
||||
var (
|
||||
multiSpaceRegex = regexp.MustCompile(`\s+`) // Multiple spaces
|
||||
urlRegex = regexp.MustCompile(`https?://\S+`) // URLs
|
||||
emailRegex = regexp.MustCompile(`\b[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}\b`) // Email addresses
|
||||
punctRegex = regexp.MustCompile(`[^\p{L}\p{N}\s]`) // Punctuation marks
|
||||
multiSpaceRegex = regexp.MustCompile(`\s+`) // Multiple spaces
|
||||
)
|
||||
|
||||
const maxProcessedTokens = 12
|
||||
|
||||
// NewPluginPreprocess Creates a new query preprocessing plugin
|
||||
func NewPluginPreprocess(
|
||||
eventManager *EventManager,
|
||||
@@ -40,51 +30,15 @@ func NewPluginPreprocess(
|
||||
cleaner interfaces.ResourceCleaner,
|
||||
modelService interfaces.ModelService,
|
||||
) *PluginPreprocess {
|
||||
// Use default dictionary for Jieba tokenizer
|
||||
jieba := gojieba.NewJieba()
|
||||
|
||||
// Load stopwords from built-in stopword library
|
||||
stopwords := loadStopwords()
|
||||
|
||||
res := &PluginPreprocess{
|
||||
config: config,
|
||||
jieba: jieba,
|
||||
stopwords: stopwords,
|
||||
modelService: modelService,
|
||||
}
|
||||
|
||||
// Register resource cleanup function
|
||||
if cleaner != nil {
|
||||
cleaner.RegisterWithName("JiebaPreprocessor", func() error {
|
||||
res.Close()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
eventManager.Register(res)
|
||||
return res
|
||||
}
|
||||
|
||||
// Load stopwords
|
||||
func loadStopwords() map[string]struct{} {
|
||||
// Directly use some common stopwords built into Jieba
|
||||
commonStopwords := []string{
|
||||
"的", "了", "和", "是", "在", "我", "你", "他", "她", "它",
|
||||
"这", "那", "什么", "怎么", "如何", "为什么", "哪里", "什么时候",
|
||||
"the", "is", "are", "am", "I", "you", "he", "she", "it", "this",
|
||||
"that", "what", "how", "a", "an", "and", "or", "but", "if", "of",
|
||||
"to", "in", "on", "at", "by", "for", "with", "about", "from",
|
||||
"有", "无", "好", "来", "去", "说", "看", "想", "会", "可以",
|
||||
"吗", "呢", "啊", "吧", "的话", "就是", "只是", "因为", "所以",
|
||||
}
|
||||
|
||||
result := make(map[string]struct{}, len(commonStopwords))
|
||||
for _, word := range commonStopwords {
|
||||
result[word] = struct{}{}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ActivationEvents Register activation events
|
||||
func (p *PluginPreprocess) ActivationEvents() []types.EventType {
|
||||
return []types.EventType{types.PREPROCESS_QUERY}
|
||||
@@ -107,171 +61,22 @@ func (p *PluginPreprocess) OnEvent(
|
||||
"rewrite_query": rawQuery,
|
||||
})
|
||||
|
||||
normalized := normalizeWhitespace(rawQuery)
|
||||
sanitized := strings.TrimSpace(p.cleanText(normalized))
|
||||
if sanitized == "" {
|
||||
sanitized = normalized
|
||||
}
|
||||
|
||||
var (
|
||||
processed = sanitized
|
||||
strategy = "original"
|
||||
tokenPreview string
|
||||
tokenCount int
|
||||
)
|
||||
|
||||
switch {
|
||||
case containsChineseCharacters(sanitized):
|
||||
segments := p.segmentText(sanitized)
|
||||
tokens := p.selectMeaningfulTokens(segments)
|
||||
tokenCount = len(tokens)
|
||||
if len(tokens) >= 2 {
|
||||
processed = strings.Join(tokens, " ")
|
||||
strategy = "zh_tokens"
|
||||
tokenPreview = strings.Join(tokens, ",")
|
||||
} else {
|
||||
strategy = "fallback_original"
|
||||
}
|
||||
case containsLatinLetters(sanitized):
|
||||
processed = normalizeLatinQuery(sanitized)
|
||||
if processed != sanitized {
|
||||
strategy = "latin_normalize"
|
||||
}
|
||||
default:
|
||||
strategy = "original"
|
||||
}
|
||||
|
||||
if strings.TrimSpace(processed) == "" {
|
||||
processed = rawQuery
|
||||
strategy = "fallback_original"
|
||||
}
|
||||
// Lightweight normalization: just collapse multiple spaces
|
||||
processed := multiSpaceRegex.ReplaceAllString(rawQuery, " ")
|
||||
processed = strings.TrimSpace(processed)
|
||||
|
||||
chatManage.ProcessedQuery = processed
|
||||
chatManage.QueryIntent = p.detectIntentLLM(ctx, chatManage, sanitized)
|
||||
chatManage.QueryIntent = p.detectIntentLLM(ctx, chatManage, processed)
|
||||
|
||||
pipelineInfo(ctx, "Preprocess", "output", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"processed_query": processed,
|
||||
"strategy": strategy,
|
||||
"token_count": tokenCount,
|
||||
"token_preview": tokenPreview,
|
||||
"query_intent": chatManage.QueryIntent,
|
||||
})
|
||||
|
||||
return next()
|
||||
}
|
||||
|
||||
// cleanText Basic text cleaning
|
||||
func (p *PluginPreprocess) cleanText(text string) string {
|
||||
// Remove URLs
|
||||
text = urlRegex.ReplaceAllString(text, " ")
|
||||
|
||||
// Remove email addresses
|
||||
text = emailRegex.ReplaceAllString(text, " ")
|
||||
|
||||
// Remove excessive spaces
|
||||
text = multiSpaceRegex.ReplaceAllString(text, " ")
|
||||
|
||||
// Remove punctuation marks
|
||||
text = punctRegex.ReplaceAllString(text, " ")
|
||||
|
||||
// Trim leading and trailing spaces
|
||||
text = strings.TrimSpace(text)
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
// segmentText Text tokenization
|
||||
func (p *PluginPreprocess) segmentText(text string) []string {
|
||||
// Use Jieba tokenizer for tokenization, using search engine mode
|
||||
segments := p.jieba.CutForSearch(text, true)
|
||||
return segments
|
||||
}
|
||||
|
||||
// filterStopwords Filter stopwords
|
||||
func (p *PluginPreprocess) selectMeaningfulTokens(segments []string) []string {
|
||||
var tokens []string
|
||||
seen := make(map[string]struct{})
|
||||
|
||||
for _, word := range segments {
|
||||
word = strings.TrimSpace(word)
|
||||
if word == "" {
|
||||
continue
|
||||
}
|
||||
if _, stop := p.stopwords[word]; stop {
|
||||
continue
|
||||
}
|
||||
if _, exists := seen[word]; exists {
|
||||
continue
|
||||
}
|
||||
if !isInformativeToken(word) {
|
||||
continue
|
||||
}
|
||||
|
||||
seen[word] = struct{}{}
|
||||
tokens = append(tokens, word)
|
||||
if len(tokens) >= maxProcessedTokens {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return tokens
|
||||
}
|
||||
|
||||
// isBlank Check if a string is blank
|
||||
func isInformativeToken(token string) bool {
|
||||
if token == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
runeCount := utf8.RuneCountInString(token)
|
||||
if runeCount == 1 {
|
||||
r, _ := utf8.DecodeRuneInString(token)
|
||||
if unicode.IsDigit(r) {
|
||||
return true
|
||||
}
|
||||
if r <= unicode.MaxASCII && unicode.IsLetter(r) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// containsChineseCharacters checks if a string contains Chinese characters
|
||||
func containsChineseCharacters(text string) bool {
|
||||
for _, r := range text {
|
||||
if unicode.Is(unicode.Han, r) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// containsLatinLetters checks if a string contains Latin letters
|
||||
func containsLatinLetters(text string) bool {
|
||||
for _, r := range text {
|
||||
if r <= unicode.MaxASCII && unicode.IsLetter(r) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// normalizeWhitespace normalizes whitespace in a string
|
||||
func normalizeWhitespace(text string) string {
|
||||
text = strings.TrimSpace(text)
|
||||
return multiSpaceRegex.ReplaceAllString(text, " ")
|
||||
}
|
||||
|
||||
// normalizeLatinQuery normalizes a Latin query
|
||||
func normalizeLatinQuery(text string) string {
|
||||
text = strings.ToLower(text)
|
||||
text = multiSpaceRegex.ReplaceAllString(text, " ")
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
// intentResp is a response for intent detection
|
||||
type intentResp struct {
|
||||
Intent string `json:"intent"`
|
||||
@@ -349,12 +154,8 @@ func extractJSONBody(text string) string {
|
||||
return "{}"
|
||||
}
|
||||
|
||||
// Ensure resources are properly released
|
||||
// Close Releases resources
|
||||
func (p *PluginPreprocess) Close() {
|
||||
if p.jieba != nil {
|
||||
p.jieba.Free()
|
||||
p.jieba = nil
|
||||
}
|
||||
}
|
||||
|
||||
// ShutdownHandler Returns shutdown function
|
||||
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/models/embedding"
|
||||
"github.com/Tencent/WeKnora/internal/models/utils"
|
||||
"github.com/Tencent/WeKnora/internal/tracing"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
@@ -283,14 +282,26 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
||||
enableMultimodelValue = kb.VLMConfig.Enabled
|
||||
}
|
||||
|
||||
// Check question generation config
|
||||
enableQuestionGeneration := false
|
||||
questionCount := 3 // default
|
||||
if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled {
|
||||
enableQuestionGeneration = true
|
||||
if kb.QuestionGenerationConfig.QuestionCount > 0 {
|
||||
questionCount = kb.QuestionGenerationConfig.QuestionCount
|
||||
}
|
||||
}
|
||||
|
||||
taskPayload := types.DocumentProcessPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
KnowledgeBaseID: kbID,
|
||||
FilePath: filePath,
|
||||
FileName: safeFilename,
|
||||
FileType: getFileType(safeFilename),
|
||||
EnableMultimodel: enableMultimodelValue,
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
KnowledgeBaseID: kbID,
|
||||
FilePath: filePath,
|
||||
FileName: safeFilename,
|
||||
FileType: getFileType(safeFilename),
|
||||
EnableMultimodel: enableMultimodelValue,
|
||||
EnableQuestionGeneration: enableQuestionGeneration,
|
||||
QuestionCount: questionCount,
|
||||
}
|
||||
|
||||
payloadBytes, err := json.Marshal(taskPayload)
|
||||
@@ -405,12 +416,24 @@ func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context,
|
||||
enableMultimodelValue = kb.VLMConfig.Enabled
|
||||
}
|
||||
|
||||
// Check question generation config
|
||||
enableQuestionGeneration := false
|
||||
questionCount := 3 // default
|
||||
if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled {
|
||||
enableQuestionGeneration = true
|
||||
if kb.QuestionGenerationConfig.QuestionCount > 0 {
|
||||
questionCount = kb.QuestionGenerationConfig.QuestionCount
|
||||
}
|
||||
}
|
||||
|
||||
taskPayload := types.DocumentProcessPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
KnowledgeBaseID: kbID,
|
||||
URL: url,
|
||||
EnableMultimodel: enableMultimodelValue,
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
KnowledgeBaseID: kbID,
|
||||
URL: url,
|
||||
EnableMultimodel: enableMultimodelValue,
|
||||
EnableQuestionGeneration: enableQuestionGeneration,
|
||||
QuestionCount: questionCount,
|
||||
}
|
||||
|
||||
payloadBytes, err := json.Marshal(taskPayload)
|
||||
@@ -595,12 +618,25 @@ func (s *knowledgeService) createKnowledgeFromPassageInternal(ctx context.Contex
|
||||
// Enqueue passage processing task to Asynq
|
||||
logger.Info(ctx, "Enqueuing passage processing task to Asynq")
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
|
||||
// Check question generation config
|
||||
enableQuestionGeneration := false
|
||||
questionCount := 3 // default
|
||||
if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled {
|
||||
enableQuestionGeneration = true
|
||||
if kb.QuestionGenerationConfig.QuestionCount > 0 {
|
||||
questionCount = kb.QuestionGenerationConfig.QuestionCount
|
||||
}
|
||||
}
|
||||
|
||||
taskPayload := types.DocumentProcessPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
KnowledgeBaseID: kbID,
|
||||
Passages: safePassages,
|
||||
EnableMultimodel: false, // 文本段落不支持多模态
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
KnowledgeBaseID: kbID,
|
||||
Passages: safePassages,
|
||||
EnableMultimodel: false, // 文本段落不支持多模态
|
||||
EnableQuestionGeneration: enableQuestionGeneration,
|
||||
QuestionCount: questionCount,
|
||||
}
|
||||
|
||||
payloadBytes, err := json.Marshal(taskPayload)
|
||||
@@ -917,10 +953,23 @@ func (s *knowledgeService) processDocumentFromPassage(ctx context.Context,
|
||||
s.processChunks(ctx, kb, knowledge, chunks)
|
||||
}
|
||||
|
||||
// ProcessChunksOptions contains options for processing chunks
|
||||
type ProcessChunksOptions struct {
|
||||
EnableQuestionGeneration bool
|
||||
QuestionCount int
|
||||
}
|
||||
|
||||
// processChunks processes chunks and creates embeddings for knowledge content
|
||||
func (s *knowledgeService) processChunks(ctx context.Context,
|
||||
kb *types.KnowledgeBase, knowledge *types.Knowledge, chunks []*proto.Chunk,
|
||||
opts ...ProcessChunksOptions,
|
||||
) {
|
||||
// Get options
|
||||
var options ProcessChunksOptions
|
||||
if len(opts) > 0 {
|
||||
options = opts[0]
|
||||
}
|
||||
|
||||
ctx, span := tracing.ContextWithSpan(ctx, "knowledgeService.processChunks")
|
||||
defer span.End()
|
||||
span.SetAttributes(
|
||||
@@ -969,14 +1018,6 @@ func (s *knowledgeService) processChunks(ctx context.Context,
|
||||
|
||||
logger.Infof(ctx, "Cleanup completed, starting to process new chunks")
|
||||
|
||||
// Generate document summary - 只使用文本类型的 Chunk
|
||||
chatModel, err := s.modelService.GetChatModel(ctx, kb.SummaryModelID)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Errorf("processChunks get summary model failed")
|
||||
span.RecordError(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Create chunk objects from proto chunks
|
||||
maxSeq := 0
|
||||
|
||||
@@ -1118,52 +1159,19 @@ func (s *knowledgeService) processChunks(ctx context.Context,
|
||||
}
|
||||
}
|
||||
|
||||
span.AddEvent("extract summary")
|
||||
summary, err := s.getSummary(ctx, chatModel, knowledge, textChunks)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).WithField("knowledge_id", knowledge.ID).
|
||||
WithField("error", err).Errorf("processChunks get summary failed, use first chunk as description")
|
||||
if len(textChunks) > 0 {
|
||||
knowledge.Description = textChunks[0].Content
|
||||
}
|
||||
} else {
|
||||
knowledge.Description = summary
|
||||
}
|
||||
span.SetAttributes(attribute.String("summary", knowledge.Description))
|
||||
|
||||
// 批量索引
|
||||
if strings.TrimSpace(knowledge.Description) != "" && len(textChunks) > 0 {
|
||||
sChunk := &types.Chunk{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: knowledge.TenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
KnowledgeBaseID: knowledge.KnowledgeBaseID,
|
||||
Content: fmt.Sprintf("# 文档名称\n%s\n\n# 摘要\n%s", knowledge.FileName, knowledge.Description),
|
||||
ChunkIndex: maxSeq + 3, // 使用不冲突的索引方式
|
||||
IsEnabled: true,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
StartAt: 0,
|
||||
EndAt: 0,
|
||||
ChunkType: types.ChunkTypeSummary,
|
||||
ParentChunkID: textChunks[0].ID,
|
||||
}
|
||||
logger.GetLogger(ctx).Infof("Created summary chunk for %s with index %d",
|
||||
sChunk.ParentChunkID, sChunk.ChunkIndex)
|
||||
insertChunks = append(insertChunks, sChunk)
|
||||
}
|
||||
|
||||
// Create index information for each chunk
|
||||
indexInfoList := utils.MapSlice(insertChunks, func(chunk *types.Chunk) *types.IndexInfo {
|
||||
return &types.IndexInfo{
|
||||
// Create index information for each chunk (without generated questions for now)
|
||||
indexInfoList := make([]*types.IndexInfo, 0, len(insertChunks))
|
||||
for _, chunk := range insertChunks {
|
||||
// Add original chunk content to index
|
||||
indexInfoList = append(indexInfoList, &types.IndexInfo{
|
||||
Content: chunk.Content,
|
||||
SourceID: chunk.ID,
|
||||
SourceType: types.ChunkSourceType,
|
||||
ChunkID: chunk.ID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
KnowledgeBaseID: knowledge.KnowledgeBaseID,
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Initialize retrieval engine
|
||||
|
||||
@@ -1249,6 +1257,23 @@ func (s *knowledgeService) processChunks(ctx context.Context,
|
||||
logger.GetLogger(ctx).WithField("error", err).Errorf("processChunks update knowledge failed")
|
||||
}
|
||||
|
||||
// Enqueue question generation task if enabled (async, non-blocking)
|
||||
if options.EnableQuestionGeneration && len(textChunks) > 0 {
|
||||
questionCount := options.QuestionCount
|
||||
if questionCount <= 0 {
|
||||
questionCount = 3
|
||||
}
|
||||
if questionCount > 10 {
|
||||
questionCount = 10
|
||||
}
|
||||
s.enqueueQuestionGenerationTask(ctx, knowledge.KnowledgeBaseID, knowledge.ID, questionCount)
|
||||
}
|
||||
|
||||
// Enqueue summary generation task (async, non-blocking)
|
||||
if len(textChunks) > 0 {
|
||||
s.enqueueSummaryGenerationTask(ctx, knowledge.KnowledgeBaseID, knowledge.ID)
|
||||
}
|
||||
|
||||
// Update tenant's storage usage
|
||||
tenantInfo.StorageUsed += totalStorageSize
|
||||
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, totalStorageSize); err != nil {
|
||||
@@ -1354,6 +1379,471 @@ func (s *knowledgeService) getSummary(ctx context.Context,
|
||||
return summary.Content, nil
|
||||
}
|
||||
|
||||
// enqueueQuestionGenerationTask enqueues an async task for question generation
|
||||
func (s *knowledgeService) enqueueQuestionGenerationTask(ctx context.Context,
|
||||
kbID, knowledgeID string, questionCount int,
|
||||
) {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
payload := types.QuestionGenerationPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
KnowledgeID: knowledgeID,
|
||||
QuestionCount: questionCount,
|
||||
}
|
||||
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to marshal question generation payload: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
task := asynq.NewTask(types.TypeQuestionGeneration, payloadBytes, asynq.Queue("low"), asynq.MaxRetry(3))
|
||||
info, err := s.task.Enqueue(task)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue question generation task: %v", err)
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Enqueued question generation task: %s for knowledge: %s", info.ID, knowledgeID)
|
||||
}
|
||||
|
||||
// enqueueSummaryGenerationTask enqueues an async task for summary generation
|
||||
func (s *knowledgeService) enqueueSummaryGenerationTask(ctx context.Context,
|
||||
kbID, knowledgeID string,
|
||||
) {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
payload := types.SummaryGenerationPayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
KnowledgeID: knowledgeID,
|
||||
}
|
||||
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to marshal summary generation payload: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
task := asynq.NewTask(types.TypeSummaryGeneration, payloadBytes, asynq.Queue("low"), asynq.MaxRetry(3))
|
||||
info, err := s.task.Enqueue(task)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue summary generation task: %v", err)
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Enqueued summary generation task: %s for knowledge: %s", info.ID, knowledgeID)
|
||||
}
|
||||
|
||||
// ProcessSummaryGeneration handles async summary generation task
|
||||
func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asynq.Task) error {
|
||||
var payload types.SummaryGenerationPayload
|
||||
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
|
||||
logger.Errorf(ctx, "Failed to unmarshal summary generation payload: %v", err)
|
||||
return nil // Don't retry on unmarshal error
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Processing summary generation for knowledge: %s", payload.KnowledgeID)
|
||||
|
||||
// Set tenant context
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
|
||||
|
||||
// Get knowledge base
|
||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, payload.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get knowledge base: %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get knowledge
|
||||
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get knowledge: %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get text chunks for this knowledge
|
||||
chunks, err := s.chunkService.ListChunksByKnowledgeID(ctx, payload.KnowledgeID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get chunks: %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Filter text chunks only
|
||||
textChunks := make([]*types.Chunk, 0)
|
||||
for _, chunk := range chunks {
|
||||
if chunk.ChunkType == types.ChunkTypeText {
|
||||
textChunks = append(textChunks, chunk)
|
||||
}
|
||||
}
|
||||
|
||||
if len(textChunks) == 0 {
|
||||
logger.Infof(ctx, "No text chunks found for knowledge: %s", payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sort chunks by ChunkIndex for proper ordering
|
||||
sort.Slice(textChunks, func(i, j int) bool {
|
||||
return textChunks[i].ChunkIndex < textChunks[j].ChunkIndex
|
||||
})
|
||||
|
||||
// Initialize chat model for summary
|
||||
chatModel, err := s.modelService.GetChatModel(ctx, kb.SummaryModelID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get chat model: %v", err)
|
||||
return fmt.Errorf("failed to get chat model: %w", err)
|
||||
}
|
||||
|
||||
// Generate summary
|
||||
summary, err := s.getSummary(ctx, chatModel, knowledge, textChunks)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to generate summary for knowledge %s: %v", payload.KnowledgeID, err)
|
||||
// Use first chunk content as fallback
|
||||
if len(textChunks) > 0 {
|
||||
summary = textChunks[0].Content
|
||||
if len(summary) > 500 {
|
||||
summary = summary[:500]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update knowledge description
|
||||
knowledge.Description = summary
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
logger.Errorf(ctx, "Failed to update knowledge description: %v", err)
|
||||
return fmt.Errorf("failed to update knowledge: %w", err)
|
||||
}
|
||||
|
||||
// Create summary chunk and index it
|
||||
if strings.TrimSpace(summary) != "" {
|
||||
// Get max chunk index
|
||||
maxChunkIndex := 0
|
||||
for _, chunk := range chunks {
|
||||
if chunk.ChunkIndex > maxChunkIndex {
|
||||
maxChunkIndex = chunk.ChunkIndex
|
||||
}
|
||||
}
|
||||
|
||||
summaryChunk := &types.Chunk{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: knowledge.TenantID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
KnowledgeBaseID: knowledge.KnowledgeBaseID,
|
||||
Content: fmt.Sprintf("# 文档名称\n%s\n\n# 摘要\n%s", knowledge.FileName, summary),
|
||||
ChunkIndex: maxChunkIndex + 1,
|
||||
IsEnabled: true,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
StartAt: 0,
|
||||
EndAt: 0,
|
||||
ChunkType: types.ChunkTypeSummary,
|
||||
ParentChunkID: textChunks[0].ID,
|
||||
}
|
||||
|
||||
// Save summary chunk
|
||||
if err := s.chunkService.CreateChunks(ctx, []*types.Chunk{summaryChunk}); err != nil {
|
||||
logger.Errorf(ctx, "Failed to create summary chunk: %v", err)
|
||||
return fmt.Errorf("failed to create summary chunk: %w", err)
|
||||
}
|
||||
|
||||
// Index summary chunk
|
||||
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get tenant info: %v", err)
|
||||
return fmt.Errorf("failed to get tenant info: %w", err)
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenantInfo)
|
||||
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to init retrieve engine: %v", err)
|
||||
return fmt.Errorf("failed to init retrieve engine: %w", err)
|
||||
}
|
||||
|
||||
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get embedding model: %v", err)
|
||||
return fmt.Errorf("failed to get embedding model: %w", err)
|
||||
}
|
||||
|
||||
indexInfo := []*types.IndexInfo{{
|
||||
Content: summaryChunk.Content,
|
||||
SourceID: summaryChunk.ID,
|
||||
SourceType: types.ChunkSourceType,
|
||||
ChunkID: summaryChunk.ID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
KnowledgeBaseID: knowledge.KnowledgeBaseID,
|
||||
}}
|
||||
|
||||
if err := retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfo); err != nil {
|
||||
logger.Errorf(ctx, "Failed to index summary chunk: %v", err)
|
||||
return fmt.Errorf("failed to index summary chunk: %w", err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Successfully created and indexed summary chunk for knowledge: %s", payload.KnowledgeID)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Successfully generated summary for knowledge: %s", payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProcessQuestionGeneration handles async question generation task
|
||||
func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asynq.Task) error {
|
||||
ctx, span := tracing.ContextWithSpan(ctx, "knowledgeService.ProcessQuestionGeneration")
|
||||
defer span.End()
|
||||
|
||||
var payload types.QuestionGenerationPayload
|
||||
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
|
||||
logger.Errorf(ctx, "Failed to unmarshal question generation payload: %v", err)
|
||||
return nil // Don't retry on unmarshal error
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Processing question generation for knowledge: %s", payload.KnowledgeID)
|
||||
|
||||
// Set tenant context
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
|
||||
|
||||
// Get knowledge base
|
||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, payload.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get knowledge base: %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get knowledge
|
||||
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get knowledge: %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get text chunks for this knowledge
|
||||
chunks, err := s.chunkService.ListChunksByKnowledgeID(ctx, payload.KnowledgeID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get chunks: %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Filter text chunks only
|
||||
textChunks := make([]*types.Chunk, 0)
|
||||
for _, chunk := range chunks {
|
||||
if chunk.ChunkType == types.ChunkTypeText {
|
||||
textChunks = append(textChunks, chunk)
|
||||
}
|
||||
}
|
||||
|
||||
if len(textChunks) == 0 {
|
||||
logger.Infof(ctx, "No text chunks found for knowledge: %s", payload.KnowledgeID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sort chunks by StartAt for context building
|
||||
sort.Slice(textChunks, func(i, j int) bool {
|
||||
return textChunks[i].StartAt < textChunks[j].StartAt
|
||||
})
|
||||
|
||||
// Initialize chat model
|
||||
chatModel, err := s.modelService.GetChatModel(ctx, kb.SummaryModelID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get chat model: %v", err)
|
||||
return fmt.Errorf("failed to get chat model: %w", err)
|
||||
}
|
||||
|
||||
// Initialize embedding model and retrieval engine
|
||||
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get embedding model: %v", err)
|
||||
return fmt.Errorf("failed to get embedding model: %w", err)
|
||||
}
|
||||
|
||||
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get tenant info: %v", err)
|
||||
return fmt.Errorf("failed to get tenant info: %w", err)
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenantInfo)
|
||||
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to init retrieve engine: %v", err)
|
||||
return fmt.Errorf("failed to init retrieve engine: %w", err)
|
||||
}
|
||||
|
||||
questionCount := payload.QuestionCount
|
||||
if questionCount <= 0 {
|
||||
questionCount = 3
|
||||
}
|
||||
if questionCount > 10 {
|
||||
questionCount = 10
|
||||
}
|
||||
|
||||
// Generate questions for each chunk with context
|
||||
var indexInfoList []*types.IndexInfo
|
||||
for i, chunk := range textChunks {
|
||||
// Build context from adjacent chunks
|
||||
var prevContent, nextContent string
|
||||
if i > 0 {
|
||||
prevContent = textChunks[i-1].Content
|
||||
// Limit context size
|
||||
if len(prevContent) > 500 {
|
||||
prevContent = prevContent[len(prevContent)-500:]
|
||||
}
|
||||
}
|
||||
if i < len(textChunks)-1 {
|
||||
nextContent = textChunks[i+1].Content
|
||||
// Limit context size
|
||||
if len(nextContent) > 500 {
|
||||
nextContent = nextContent[:500]
|
||||
}
|
||||
}
|
||||
|
||||
questions, err := s.generateQuestionsWithContext(ctx, chatModel, chunk.Content, prevContent, nextContent, knowledge.Title, questionCount)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to generate questions for chunk %s: %v", chunk.ID, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(questions) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Update chunk metadata
|
||||
meta := &types.DocumentChunkMetadata{
|
||||
GeneratedQuestions: questions,
|
||||
}
|
||||
if err := chunk.SetDocumentMetadata(meta); err != nil {
|
||||
logger.Warnf(ctx, "Failed to set document metadata for chunk %s: %v", chunk.ID, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Update chunk in database
|
||||
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
|
||||
logger.Warnf(ctx, "Failed to update chunk %s: %v", chunk.ID, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Create index entries for generated questions
|
||||
for j, question := range questions {
|
||||
sourceID := fmt.Sprintf("%s-q%d", chunk.ID, j)
|
||||
indexInfoList = append(indexInfoList, &types.IndexInfo{
|
||||
Content: question,
|
||||
SourceID: sourceID,
|
||||
SourceType: types.ChunkSourceType,
|
||||
ChunkID: chunk.ID,
|
||||
KnowledgeID: knowledge.ID,
|
||||
KnowledgeBaseID: knowledge.KnowledgeBaseID,
|
||||
})
|
||||
}
|
||||
logger.Debugf(ctx, "Generated %d questions for chunk %s", len(questions), chunk.ID)
|
||||
}
|
||||
|
||||
// Index generated questions
|
||||
if len(indexInfoList) > 0 {
|
||||
if err := retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfoList); err != nil {
|
||||
logger.Errorf(ctx, "Failed to index generated questions: %v", err)
|
||||
return fmt.Errorf("failed to index questions: %w", err)
|
||||
}
|
||||
logger.Infof(ctx, "Successfully indexed %d generated questions for knowledge: %s", len(indexInfoList), payload.KnowledgeID)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// generateQuestionsWithContext generates questions for a chunk with surrounding context
|
||||
func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
|
||||
chatModel chat.Chat, content, prevContent, nextContent, docName string, questionCount int,
|
||||
) ([]string, error) {
|
||||
if content == "" || questionCount <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Build prompt with context
|
||||
prompt := s.config.Conversation.GenerateQuestionsPrompt
|
||||
if prompt == "" {
|
||||
prompt = defaultQuestionGenerationPrompt
|
||||
}
|
||||
|
||||
// Build context section
|
||||
var contextSection string
|
||||
if prevContent != "" || nextContent != "" {
|
||||
contextSection = "## 上下文信息(仅供参考,帮助理解主要内容)\n"
|
||||
if prevContent != "" {
|
||||
contextSection += fmt.Sprintf("【前文】%s\n", prevContent)
|
||||
}
|
||||
if nextContent != "" {
|
||||
contextSection += fmt.Sprintf("【后文】%s\n", nextContent)
|
||||
}
|
||||
contextSection += "\n"
|
||||
}
|
||||
|
||||
// Replace placeholders
|
||||
prompt = strings.ReplaceAll(prompt, "{{.QuestionCount}}", fmt.Sprintf("%d", questionCount))
|
||||
prompt = strings.ReplaceAll(prompt, "{{.Content}}", content)
|
||||
prompt = strings.ReplaceAll(prompt, "{{.Context}}", contextSection)
|
||||
prompt = strings.ReplaceAll(prompt, "{{.DocName}}", docName)
|
||||
|
||||
thinking := false
|
||||
response, err := chatModel.Chat(ctx, []chat.Message{
|
||||
{
|
||||
Role: "user",
|
||||
Content: prompt,
|
||||
},
|
||||
}, &chat.ChatOptions{
|
||||
Temperature: 0.7,
|
||||
MaxTokens: 512,
|
||||
Thinking: &thinking,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate questions: %w", err)
|
||||
}
|
||||
|
||||
// Parse response
|
||||
lines := strings.Split(response.Content, "\n")
|
||||
questions := make([]string, 0, questionCount)
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
line = strings.TrimLeft(line, "0123456789.-*) ")
|
||||
line = strings.TrimSpace(line)
|
||||
if line != "" && len(line) > 5 {
|
||||
questions = append(questions, line)
|
||||
if len(questions) >= questionCount {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return questions, nil
|
||||
}
|
||||
|
||||
// Default prompt for question generation with context support
|
||||
const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。
|
||||
|
||||
{{.Context}}
|
||||
## 主要内容(请基于此内容生成问题)
|
||||
文档名称:{{.DocName}}
|
||||
文档内容:
|
||||
{{.Content}}
|
||||
|
||||
## 核心要求
|
||||
- 生成的问题必须与【主要内容】直接相关
|
||||
- 问题中禁止使用任何代词或指代词(如"它"、"这个"、"该文档"、"本文"、"文中"、"其"等),必须用具体名称替代
|
||||
- 问题必须是完整独立的,脱离上下文也能被理解
|
||||
- 问题应该是用户在实际场景中可能会提出的自然问题
|
||||
- 问题应该多样化,覆盖内容的不同方面
|
||||
- 每个问题应该简洁明了,长度控制在30字以内
|
||||
- 生成的问题数量为 {{.QuestionCount}} 个
|
||||
|
||||
## 问题类型建议
|
||||
- 定义类:什么是...?...是什么?
|
||||
- 原因类:为什么...?...的原因是什么?
|
||||
- 方法类:如何...?怎样...?
|
||||
- 比较类:...和...有什么区别?
|
||||
- 应用类:...可以用于什么场景?
|
||||
|
||||
## 输出格式
|
||||
直接输出问题列表,每行一个问题,不要有序号或其他前缀。`
|
||||
|
||||
// GetKnowledgeFile retrieves the physical file associated with a knowledge entry
|
||||
func (s *knowledgeService) GetKnowledgeFile(ctx context.Context, id string) (io.ReadCloser, string, error) {
|
||||
// Get knowledge record
|
||||
@@ -4051,7 +4541,10 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
}
|
||||
|
||||
// 处理chunks(这会更新状态为completed)
|
||||
s.processChunks(ctx, kb, knowledge, chunks)
|
||||
s.processChunks(ctx, kb, knowledge, chunks, ProcessChunksOptions{
|
||||
EnableQuestionGeneration: payload.EnableQuestionGeneration,
|
||||
QuestionCount: payload.QuestionCount,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user