feat: Implement FAQ functionality in Knowledge Base

- Added support for creating and managing FAQ knowledge bases, including new API endpoints for listing, upserting, updating, and deleting FAQ entries.
- Enhanced the frontend to allow users to create FAQ knowledge bases and manage FAQ entries with a dedicated interface.
- Introduced new types and configurations for FAQ handling in the backend, ensuring proper indexing and retrieval of FAQ entries.
- Updated localization files to include new strings related to FAQ management in multiple languages.
- Refactored existing components to accommodate the new FAQ features, improving user experience and functionality.
This commit is contained in:
wizardchen
2025-11-15 01:30:17 +08:00
parent 0ea5e6a2a2
commit 25fdaed8ca
37 changed files with 4778 additions and 198 deletions
+265 -5
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"slices"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/application/service/retriever"
@@ -55,6 +56,7 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
kb.CreatedAt = time.Now()
kb.TenantID = ctx.Value(types.TenantIDContextKey).(uint)
kb.UpdatedAt = time.Now()
kb.EnsureDefaults()
logger.Infof(ctx, "Creating knowledge base, ID: %s, tenant ID: %d, name: %s", kb.ID, kb.TenantID, kb.Name)
@@ -87,6 +89,8 @@ func (s *knowledgeBaseService) GetKnowledgeBaseByID(ctx context.Context, id stri
return nil, err
}
kb.EnsureDefaults()
logger.Infof(ctx, "Knowledge base retrieved successfully, ID: %s, name: %s", kb.ID, kb.Name)
return kb, nil
}
@@ -98,6 +102,10 @@ func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types
kbs, err := s.repo.ListKnowledgeBasesByTenantID(ctx, tenantID)
if err != nil {
for _, kb := range kbs {
kb.EnsureDefaults()
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
})
@@ -141,7 +149,12 @@ func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
kb.Description = description
kb.ChunkingConfig = config.ChunkingConfig
kb.ImageProcessingConfig = config.ImageProcessingConfig
// Update FAQ config if provided
if config.FAQConfig != nil {
kb.FAQConfig = config.FAQConfig
}
kb.UpdatedAt = time.Now()
kb.EnsureDefaults()
logger.Info(ctx, "Saving knowledge base update")
if err := s.repo.UpdateKnowledgeBase(ctx, kb); err != nil {
@@ -232,6 +245,7 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
logger.Errorf(ctx, "Get source knowledge base failed: %v", err)
return nil, nil, err
}
sourceKB.EnsureDefaults()
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
var targetKB *types.KnowledgeBase
if dstKB != "" {
@@ -240,9 +254,15 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
return nil, nil, err
}
} else {
var faqConfig *types.FAQConfig
if sourceKB.FAQConfig != nil {
cfg := *sourceKB.FAQConfig
faqConfig = &cfg
}
targetKB = &types.KnowledgeBase{
ID: uuid.New().String(),
Name: sourceKB.Name,
Type: sourceKB.Type,
Description: sourceKB.Description,
TenantID: tenantID,
ChunkingConfig: sourceKB.ChunkingConfig,
@@ -252,7 +272,9 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
RerankModelID: sourceKB.RerankModelID,
VLMModelID: sourceKB.VLMModelID,
StorageConfig: sourceKB.StorageConfig,
FAQConfig: faqConfig,
}
targetKB.EnsureDefaults()
if err := s.repo.CreateKnowledgeBase(ctx, targetKB); err != nil {
return nil, nil, err
}
@@ -282,7 +304,7 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
var kb *types.KnowledgeBase
// Add vector retrieval params if supported
if retrieveEngine.SupportRetriever(types.VectorRetrieverType) {
if retrieveEngine.SupportRetriever(types.VectorRetrieverType) && !params.DisableVectorMatch {
logger.Info(ctx, "Vector retrieval supported, preparing vector retrieval parameters")
kb, err = s.repo.GetKnowledgeBaseByID(ctx, id)
@@ -322,7 +344,7 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
}
// Add keyword retrieval params if supported
if retrieveEngine.SupportRetriever(types.KeywordsRetrieverType) {
if retrieveEngine.SupportRetriever(types.KeywordsRetrieverType) && !params.DisableKeywordsMatch {
logger.Info(ctx, "Keyword retrieval supported, preparing keyword retrieval parameters")
retrieveParams = append(retrieveParams, types.RetrieveParams{
Query: params.QueryText,
@@ -367,15 +389,251 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
logger.Info(ctx, "No search results found")
return nil, nil
}
// Deduplicate results by chunk ID
logger.Infof(ctx, "Result count before deduplication: %d", len(matchResults))
deduplicatedChunks := common.Deduplicate(func(r *types.IndexWithScore) string { return r.ChunkID }, matchResults...)
for _, chunk := range matchResults {
logger.Infof(ctx, "Before deduplication: Chunk: %s, Content: %s, Score: %f, MatchType: %d", chunk.ChunkID, chunk.Content, chunk.Score, chunk.MatchType)
}
// First, try standard deduplication
deduplicatedChunks := common.DeduplicateWithScore(func(r *types.IndexWithScore) string { return r.ChunkID }, matchResults...)
logger.Infof(ctx, "Result count after deduplication: %d", len(deduplicatedChunks))
for _, chunk := range deduplicatedChunks {
logger.Infof(ctx, "After deduplication: Chunk: %s, Content: %s, Score: %f, MatchType: %d", chunk.ChunkID, chunk.Content, chunk.Score, chunk.MatchType)
}
kb.EnsureDefaults()
// Check if we need iterative retrieval for FAQ with separate indexing
// Only use iterative retrieval if we don't have enough unique chunks after first deduplication
needsIterativeRetrieval := len(deduplicatedChunks) < params.MatchCount &&
kb.Type == types.KnowledgeBaseTypeFAQ &&
kb.FAQConfig != nil &&
kb.FAQConfig.QuestionIndexMode == types.FAQQuestionIndexModeSeparate
if needsIterativeRetrieval {
logger.Infof(ctx, "Not enough unique chunks (%d < %d), using iterative retrieval for FAQ with separate indexing",
len(deduplicatedChunks), params.MatchCount)
// Use iterative retrieval to get more unique chunks (with negative question filtering inside)
deduplicatedChunks = s.iterativeRetrieveWithDeduplication(ctx, retrieveEngine, retrieveParams, params.MatchCount, params.QueryText, kb.Type == types.KnowledgeBaseTypeFAQ)
} else if kb.Type == types.KnowledgeBaseTypeFAQ {
// Filter by negative questions if not using iterative retrieval
deduplicatedChunks = s.filterByNegativeQuestions(ctx, deduplicatedChunks, params.QueryText)
logger.Infof(ctx, "Result count after negative question filtering: %d", len(deduplicatedChunks))
}
// Limit to MatchCount
if len(deduplicatedChunks) > params.MatchCount {
deduplicatedChunks = deduplicatedChunks[:params.MatchCount]
}
return s.processSearchResults(ctx, deduplicatedChunks)
}
// iterativeRetrieveWithDeduplication performs iterative retrieval until enough unique chunks are found
// This is used for FAQ knowledge bases with separate indexing mode
// Negative question filtering is applied after each iteration to ensure we have enough valid chunks
func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Context,
retrieveEngine *retriever.CompositeRetrieveEngine,
retrieveParams []types.RetrieveParams,
matchCount int,
queryText string,
isFAQ bool,
) []*types.IndexWithScore {
maxIterations := 5
currentTopK := matchCount
uniqueChunks := make(map[string]*types.IndexWithScore)
for i := 0; i < maxIterations; i++ {
logger.Infof(ctx, "Iterative retrieval iteration %d, TopK: %d", i+1, currentTopK)
// Update TopK in retrieve params
updatedParams := make([]types.RetrieveParams, len(retrieveParams))
for j := range retrieveParams {
updatedParams[j] = retrieveParams[j]
updatedParams[j].TopK = currentTopK
}
// Execute retrieval
retrieveResults, err := retrieveEngine.Retrieve(ctx, updatedParams)
if err != nil {
logger.Warnf(ctx, "Iterative retrieval failed at iteration %d: %v", i+1, err)
break
}
// Collect results
iterationResults := []*types.IndexWithScore{}
for _, retrieveResult := range retrieveResults {
iterationResults = append(iterationResults, retrieveResult.Results...)
}
if len(iterationResults) == 0 {
logger.Infof(ctx, "No results found at iteration %d", i+1)
break
}
// Check if we got fewer results than requested - means no more results available
totalRetrieved := len(iterationResults)
if totalRetrieved < currentTopK {
logger.Infof(ctx, "Retrieved %d results (less than TopK %d), no more results available", totalRetrieved, currentTopK)
}
// Deduplicate and merge (keep highest score for each chunk)
// Multiple similar questions hitting the same chunk will keep the highest score
for _, result := range iterationResults {
if existing, ok := uniqueChunks[result.ChunkID]; !ok || result.Score > existing.Score {
uniqueChunks[result.ChunkID] = result
}
}
// Convert to slice for filtering
chunksSlice := make([]*types.IndexWithScore, 0, len(uniqueChunks))
for _, chunk := range uniqueChunks {
chunksSlice = append(chunksSlice, chunk)
}
// Filter by negative questions if this is a FAQ knowledge base
if isFAQ {
chunksSlice = s.filterByNegativeQuestions(ctx, chunksSlice, queryText)
// Update uniqueChunks map with filtered results
uniqueChunks = make(map[string]*types.IndexWithScore, len(chunksSlice))
for _, chunk := range chunksSlice {
uniqueChunks[chunk.ChunkID] = chunk
}
}
logger.Infof(ctx, "After iteration %d: retrieved %d results, found %d unique chunks after filtering (target: %d)",
i+1, totalRetrieved, len(uniqueChunks), matchCount)
// Early stop: Check if we have enough unique chunks after deduplication and filtering
if len(uniqueChunks) >= matchCount {
logger.Infof(ctx, "Found enough unique chunks after %d iterations", i+1)
break
}
// Early stop: If we got fewer results than TopK, there are no more results to retrieve
if totalRetrieved < currentTopK {
logger.Infof(ctx, "No more results available, stopping iteration")
break
}
// Increase TopK for next iteration
currentTopK *= 2
}
// Convert map to slice and sort by score
result := make([]*types.IndexWithScore, 0, len(uniqueChunks))
for _, chunk := range uniqueChunks {
result = append(result, chunk)
}
// Sort by score descending
slices.SortFunc(result, func(a, b *types.IndexWithScore) int {
if a.Score > b.Score {
return -1
} else if a.Score < b.Score {
return 1
}
return 0
})
logger.Infof(ctx, "Iterative retrieval completed: %d unique chunks found after filtering", len(result))
return result
}
// filterByNegativeQuestions filters out chunks that match negative questions for FAQ knowledge bases.
func (s *knowledgeBaseService) filterByNegativeQuestions(ctx context.Context,
chunks []*types.IndexWithScore,
queryText string,
) []*types.IndexWithScore {
if len(chunks) == 0 {
return chunks
}
queryTextLower := strings.ToLower(strings.TrimSpace(queryText))
if queryTextLower == "" {
return chunks
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
// Collect chunk IDs
chunkIDs := make([]string, 0, len(chunks))
for _, chunk := range chunks {
chunkIDs = append(chunkIDs, chunk.ChunkID)
}
// Batch fetch chunks to get negative questions
allChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
if err != nil {
logger.Warnf(ctx, "Failed to fetch chunks for negative question filtering: %v", err)
// If we can't fetch chunks, return original results
return chunks
}
// Build chunk map for quick lookup
chunkMap := make(map[string]*types.Chunk, len(allChunks))
for _, chunk := range allChunks {
chunkMap[chunk.ID] = chunk
}
// Filter out chunks that match negative questions
filteredChunks := make([]*types.IndexWithScore, 0, len(chunks))
for _, chunk := range chunks {
chunkData, ok := chunkMap[chunk.ChunkID]
if !ok {
// If chunk not found, keep it (shouldn't happen, but be safe)
filteredChunks = append(filteredChunks, chunk)
continue
}
// Only filter FAQ type chunks
if chunkData.ChunkType != types.ChunkTypeFAQ {
filteredChunks = append(filteredChunks, chunk)
continue
}
// Get FAQ metadata and check negative questions
meta, err := chunkData.FAQMetadata()
if err != nil || meta == nil {
// If we can't parse metadata, keep the chunk
filteredChunks = append(filteredChunks, chunk)
continue
}
// Check if query matches any negative question
if s.matchesNegativeQuestions(queryTextLower, meta.NegativeQuestions) {
logger.Debugf(ctx, "Filtered FAQ chunk %s due to negative question match", chunk.ChunkID)
continue
}
// Keep the chunk
filteredChunks = append(filteredChunks, chunk)
}
return filteredChunks
}
// matchesNegativeQuestions checks if the query text matches any negative questions.
// Returns true if the query matches any negative question, false otherwise.
func (s *knowledgeBaseService) matchesNegativeQuestions(queryTextLower string, negativeQuestions []string) bool {
if len(negativeQuestions) == 0 {
return false
}
for _, negativeQ := range negativeQuestions {
negativeQLower := strings.ToLower(strings.TrimSpace(negativeQ))
if negativeQLower == "" {
continue
}
// Check if query text is exactly the same as the negative question
if queryTextLower == negativeQLower {
return true
}
}
return false
}
// processSearchResults handles the processing of search results, optimizing database queries
func (s *knowledgeBaseService) processSearchResults(ctx context.Context,
chunks []*types.IndexWithScore,
@@ -422,6 +680,7 @@ func (s *knowledgeBaseService) processSearchResults(ctx context.Context,
})
return nil, err
}
logger.Infof(ctx, "Chunk data fetched successfully, count: %d", len(allChunks))
// Build chunk map and collect additional IDs to fetch
chunkMap := make(map[string]*types.Chunk, len(allChunks))
@@ -555,6 +814,7 @@ func (s *knowledgeBaseService) buildSearchResult(chunk *types.Chunk,
func (s *knowledgeBaseService) isValidTextChunk(chunk *types.Chunk) bool {
return slices.Contains([]types.ChunkType{
types.ChunkTypeText, types.ChunkTypeSummary,
types.ChunkTypeFAQ,
}, chunk.ChunkType)
}