Files
Enterprise-Knowledge-Base/internal/application/service/chat_pipline/search.go
T
wizardchen 266b9a5943 feat: Enhance chat and knowledge base functionalities with multi-KB support
- Updated agentChat API to accept optional knowledge_base_ids and agent_enabled parameters.
- Introduced getSession API to retrieve session details.
- Modified useStream to validate knowledge_base_ids for agent-chat requests and prepare POST body accordingly.
- Enhanced createKnowledgeBase API to include additional configuration options.
- Refactored chat routing to remove knowledge base ID from the chat path, allowing for dynamic knowledge base selection.
- Improved session management by preventing duplicate session entries in the menu store.
- Updated UI components for better session handling and display.
- Added context management for agent conversations to improve state persistence across sessions.
2025-11-06 21:12:26 +08:00

183 lines
5.6 KiB
Go

package chatpipline
import (
"context"
"strings"
"sync"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginSearch implements search functionality for chat pipeline
type PluginSearch struct {
knowledgeBaseService interfaces.KnowledgeBaseService
modelService interfaces.ModelService
config *config.Config
}
func NewPluginSearch(eventManager *EventManager,
knowledgeBaseService interfaces.KnowledgeBaseService,
modelService interfaces.ModelService,
config *config.Config,
) *PluginSearch {
res := &PluginSearch{
knowledgeBaseService: knowledgeBaseService,
modelService: modelService,
config: config,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginSearch) ActivationEvents() []types.EventType {
return []types.EventType{types.CHUNK_SEARCH}
}
// OnEvent handles search events in the chat pipeline
func (p *PluginSearch) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
// Get knowledge base IDs list
knowledgeBaseIDs := chatManage.KnowledgeBaseIDs
if len(knowledgeBaseIDs) == 0 && chatManage.KnowledgeBaseID != "" {
// Fall back to single knowledge base
knowledgeBaseIDs = []string{chatManage.KnowledgeBaseID}
logger.Infof(ctx, "No KnowledgeBaseIDs provided, falling back to single KB: %s", chatManage.KnowledgeBaseID)
}
if len(knowledgeBaseIDs) == 0 {
logger.Errorf(ctx, "No knowledge base IDs available for search")
return ErrSearch.WithError(nil)
}
logger.Infof(ctx, "Searching across %d knowledge base(s): %v", len(knowledgeBaseIDs), knowledgeBaseIDs)
// Prepare search parameters
searchParams := types.SearchParams{
QueryText: strings.TrimSpace(chatManage.RewriteQuery),
VectorThreshold: chatManage.VectorThreshold,
KeywordThreshold: chatManage.KeywordThreshold,
MatchCount: chatManage.EmbeddingTopK,
}
logger.Infof(ctx, "Search parameters: %v", searchParams)
// Parallel search across multiple knowledge bases
var wg sync.WaitGroup
var mu sync.Mutex
var allResults []*types.SearchResult
for _, kbID := range knowledgeBaseIDs {
wg.Add(1)
go func(knowledgeBaseID string) {
defer wg.Done()
results, err := p.knowledgeBaseService.HybridSearch(ctx, knowledgeBaseID, searchParams)
if err != nil {
logger.Errorf(ctx, "Failed to search KB %s: %v", knowledgeBaseID, err)
return
}
logger.Infof(ctx, "KB %s search results count: %d", knowledgeBaseID, len(results))
mu.Lock()
allResults = append(allResults, results...)
mu.Unlock()
}(kbID)
}
wg.Wait()
logger.Infof(ctx, "Total search results from all KBs: %d", len(allResults))
chatManage.SearchResult = allResults
// Add relevant results from chat history
historyResult := p.getSearchResultFromHistory(chatManage)
if historyResult != nil {
logger.Infof(ctx, "Add history result, result count: %d", len(historyResult))
chatManage.SearchResult = append(chatManage.SearchResult, historyResult...)
}
// Try search with processed query if different from rewrite query
if chatManage.RewriteQuery != chatManage.ProcessedQuery {
searchParams.QueryText = strings.TrimSpace(chatManage.ProcessedQuery)
logger.Infof(ctx, "Searching with processed query: %s", searchParams.QueryText)
var wg2 sync.WaitGroup
var mu2 sync.Mutex
var processedResults []*types.SearchResult
for _, kbID := range knowledgeBaseIDs {
wg2.Add(1)
go func(knowledgeBaseID string) {
defer wg2.Done()
results, err := p.knowledgeBaseService.HybridSearch(ctx, knowledgeBaseID, searchParams)
if err != nil {
logger.Errorf(ctx, "Failed to search KB %s with processed query: %v", knowledgeBaseID, err)
return
}
logger.Infof(ctx, "KB %s processed query results count: %d", knowledgeBaseID, len(results))
mu2.Lock()
processedResults = append(processedResults, results...)
mu2.Unlock()
}(kbID)
}
wg2.Wait()
logger.Infof(ctx, "Total processed query results from all KBs: %d", len(processedResults))
chatManage.SearchResult = append(chatManage.SearchResult, processedResults...)
}
// Remove duplicate results
chatManage.SearchResult = removeDuplicateResults(chatManage.SearchResult)
// Return if we have results
if len(chatManage.SearchResult) != 0 {
logger.Infof(
ctx,
"Get search results, count: %d, session_id: %s",
len(chatManage.SearchResult), chatManage.SessionID,
)
return next()
}
logger.Infof(ctx, "No search result, session_id: %s", chatManage.SessionID)
return ErrSearchNothing
}
// getSearchResultFromHistory retrieves relevant knowledge references from chat history
func (p *PluginSearch) getSearchResultFromHistory(chatManage *types.ChatManage) []*types.SearchResult {
if len(chatManage.History) == 0 {
return nil
}
// Search history in reverse chronological order
for i := len(chatManage.History) - 1; i >= 0; i-- {
if len(chatManage.History[i].KnowledgeReferences) > 0 {
// Mark all references as history matches
for _, reference := range chatManage.History[i].KnowledgeReferences {
reference.MatchType = types.MatchTypeHistory
}
return chatManage.History[i].KnowledgeReferences
}
}
return nil
}
func removeDuplicateResults(results []*types.SearchResult) []*types.SearchResult {
seen := make(map[string]bool)
var uniqueResults []*types.SearchResult
for _, result := range results {
if !seen[result.ID] {
seen[result.ID] = true
uniqueResults = append(uniqueResults, result)
}
}
return uniqueResults
}