feat: 支持输入框内选择知识库和文件,优化选择交互体验
This commit is contained in:
@@ -22,6 +22,7 @@ type PluginExtractEntity struct {
|
||||
modelService interfaces.ModelService // Model service for calling large language models
|
||||
template *types.PromptTemplateStructured // Template for generating prompts
|
||||
knowledgeBaseRepo interfaces.KnowledgeBaseRepository
|
||||
knowledgeRepo interfaces.KnowledgeRepository
|
||||
}
|
||||
|
||||
// NewPluginRewrite creates a new query rewriting plugin instance
|
||||
@@ -30,12 +31,14 @@ func NewPluginExtractEntity(
|
||||
eventManager *EventManager,
|
||||
modelService interfaces.ModelService,
|
||||
knowledgeBaseRepo interfaces.KnowledgeBaseRepository,
|
||||
knowledgeRepo interfaces.KnowledgeRepository,
|
||||
config *config.Config,
|
||||
) *PluginExtractEntity {
|
||||
res := &PluginExtractEntity{
|
||||
modelService: modelService,
|
||||
template: config.ExtractManager.ExtractEntity,
|
||||
knowledgeBaseRepo: knowledgeBaseRepo,
|
||||
knowledgeRepo: knowledgeRepo,
|
||||
}
|
||||
eventManager.Register(res)
|
||||
return res
|
||||
@@ -65,16 +68,68 @@ func (p *PluginExtractEntity) OnEvent(ctx context.Context,
|
||||
return next()
|
||||
}
|
||||
|
||||
kb, err := p.knowledgeBaseRepo.GetKnowledgeBaseByID(ctx, chatManage.KnowledgeBaseID)
|
||||
// Collect all knowledge base IDs to query
|
||||
kbIDSet := make(map[string]struct{})
|
||||
for _, id := range chatManage.KnowledgeBaseIDs {
|
||||
kbIDSet[id] = struct{}{}
|
||||
}
|
||||
|
||||
// If KnowledgeIDs is specified, retrieve them and collect their knowledge base IDs
|
||||
// Also build a mapping from KnowledgeID to KnowledgeBaseID
|
||||
knowledgeToKBMap := make(map[string]string)
|
||||
if len(chatManage.KnowledgeIDs) > 0 {
|
||||
knowledges, err := p.knowledgeRepo.GetKnowledgeBatch(ctx, chatManage.TenantID, chatManage.KnowledgeIDs)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to get knowledges: %v", err)
|
||||
return next()
|
||||
}
|
||||
for _, k := range knowledges {
|
||||
kbIDSet[k.KnowledgeBaseID] = struct{}{}
|
||||
knowledgeToKBMap[k.ID] = k.KnowledgeBaseID
|
||||
}
|
||||
}
|
||||
|
||||
// Convert set to slice
|
||||
allKBIDs := make([]string, 0, len(kbIDSet))
|
||||
for id := range kbIDSet {
|
||||
allKBIDs = append(allKBIDs, id)
|
||||
}
|
||||
|
||||
// Batch retrieve all knowledge bases
|
||||
kbs, err := p.knowledgeBaseRepo.GetKnowledgeBaseByIDs(ctx, allKBIDs)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to get knowledge base: %v", err)
|
||||
logger.Errorf(ctx, "failed to get knowledge bases: %v", err)
|
||||
return next()
|
||||
}
|
||||
if kb.ExtractConfig == nil {
|
||||
logger.Warnf(ctx, "failed to get extract config")
|
||||
|
||||
// Check if any knowledge base has ExtractConfig enabled and collect their IDs
|
||||
enabledKBSet := make(map[string]struct{})
|
||||
for _, kb := range kbs {
|
||||
if kb.ExtractConfig != nil && kb.ExtractConfig.Enabled {
|
||||
enabledKBSet[kb.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
if len(enabledKBSet) == 0 {
|
||||
logger.Debugf(ctx, "no knowledge base has extract config enabled")
|
||||
return next()
|
||||
}
|
||||
|
||||
// Save enabled knowledge base IDs for later use in search_entity
|
||||
enabledKBIDs := make([]string, 0, len(enabledKBSet))
|
||||
for id := range enabledKBSet {
|
||||
enabledKBIDs = append(enabledKBIDs, id)
|
||||
}
|
||||
chatManage.EntityKBIDs = enabledKBIDs
|
||||
|
||||
// Filter knowledgeToKBMap to only include files from enabled knowledge bases
|
||||
entityKnowledge := make(map[string]string)
|
||||
for knowledgeID, kbID := range knowledgeToKBMap {
|
||||
if _, ok := enabledKBSet[kbID]; ok {
|
||||
entityKnowledge[knowledgeID] = kbID
|
||||
}
|
||||
}
|
||||
chatManage.EntityKnowledge = entityKnowledge
|
||||
|
||||
template := &types.PromptTemplateStructured{
|
||||
Description: p.template.Description,
|
||||
Examples: p.template.Examples,
|
||||
|
||||
@@ -66,35 +66,54 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
return ErrGetRerankModel.WithError(err)
|
||||
}
|
||||
|
||||
// Prepare passages for reranking
|
||||
pipelineInfo(ctx, "Rerank", "build_passages", map[string]interface{}{
|
||||
"candidate_cnt": len(chatManage.SearchResult),
|
||||
})
|
||||
// Prepare passages for reranking (excluding DirectLoad results)
|
||||
var passages []string
|
||||
var candidatesToRerank []*types.SearchResult
|
||||
var directLoadResults []*types.SearchResult
|
||||
|
||||
for _, result := range chatManage.SearchResult {
|
||||
if result.MatchType == types.MatchTypeDirectLoad {
|
||||
directLoadResults = append(directLoadResults, result)
|
||||
pipelineInfo(ctx, "Rerank", "direct_load_skip", map[string]interface{}{
|
||||
"chunk_id": result.ID,
|
||||
})
|
||||
continue
|
||||
}
|
||||
// 合并Content和ImageInfo的文本内容
|
||||
passage := getEnrichedPassage(ctx, result)
|
||||
passages = append(passages, passage)
|
||||
candidatesToRerank = append(candidatesToRerank, result)
|
||||
}
|
||||
|
||||
// Single rerank call with RewriteQuery, use threshold degradation if no results
|
||||
originalThreshold := chatManage.RerankThreshold
|
||||
rerankResp := p.rerank(ctx, chatManage, rerankModel, chatManage.RewriteQuery, passages)
|
||||
pipelineInfo(ctx, "Rerank", "build_passages", map[string]interface{}{
|
||||
"total_cnt": len(chatManage.SearchResult),
|
||||
"candidate_cnt": len(candidatesToRerank),
|
||||
"direct_cnt": len(directLoadResults),
|
||||
})
|
||||
|
||||
// If no results and threshold is high enough, try with lower threshold
|
||||
if len(rerankResp) == 0 && originalThreshold > 0.3 {
|
||||
degradedThreshold := originalThreshold * 0.7
|
||||
if degradedThreshold < 0.3 {
|
||||
degradedThreshold = 0.3
|
||||
var rerankResp []rerank.RankResult
|
||||
|
||||
// Only call rerank model if there are candidates
|
||||
if len(candidatesToRerank) > 0 {
|
||||
// Single rerank call with RewriteQuery, use threshold degradation if no results
|
||||
originalThreshold := chatManage.RerankThreshold
|
||||
rerankResp = p.rerank(ctx, chatManage, rerankModel, chatManage.RewriteQuery, passages, candidatesToRerank)
|
||||
|
||||
// If no results and threshold is high enough, try with lower threshold
|
||||
if len(rerankResp) == 0 && originalThreshold > 0.3 {
|
||||
degradedThreshold := originalThreshold * 0.7
|
||||
if degradedThreshold < 0.3 {
|
||||
degradedThreshold = 0.3
|
||||
}
|
||||
pipelineInfo(ctx, "Rerank", "threshold_degrade", map[string]interface{}{
|
||||
"original": originalThreshold,
|
||||
"degraded": degradedThreshold,
|
||||
})
|
||||
chatManage.RerankThreshold = degradedThreshold
|
||||
rerankResp = p.rerank(ctx, chatManage, rerankModel, chatManage.RewriteQuery, passages, candidatesToRerank)
|
||||
// Restore original threshold
|
||||
chatManage.RerankThreshold = originalThreshold
|
||||
}
|
||||
pipelineInfo(ctx, "Rerank", "threshold_degrade", map[string]interface{}{
|
||||
"original": originalThreshold,
|
||||
"degraded": degradedThreshold,
|
||||
})
|
||||
chatManage.RerankThreshold = degradedThreshold
|
||||
rerankResp = p.rerank(ctx, chatManage, rerankModel, chatManage.RewriteQuery, passages)
|
||||
// Restore original threshold
|
||||
chatManage.RerankThreshold = originalThreshold
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "Rerank", "model_response", map[string]interface{}{
|
||||
@@ -114,9 +133,14 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
for i := range chatManage.SearchResult {
|
||||
chatManage.SearchResult[i].Metadata = ensureMetadata(chatManage.SearchResult[i].Metadata)
|
||||
}
|
||||
reranked := make([]*types.SearchResult, 0, len(rerankResp))
|
||||
reranked := make([]*types.SearchResult, 0, len(rerankResp)+len(directLoadResults))
|
||||
|
||||
// Process reranked results
|
||||
for _, rr := range rerankResp {
|
||||
sr := chatManage.SearchResult[rr.Index]
|
||||
if rr.Index >= len(candidatesToRerank) {
|
||||
continue
|
||||
}
|
||||
sr := candidatesToRerank[rr.Index]
|
||||
base := sr.Score
|
||||
sr.Metadata["base_score"] = fmt.Sprintf("%.4f", base)
|
||||
modelScore := rr.RelevanceScore
|
||||
@@ -130,6 +154,23 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
})
|
||||
reranked = append(reranked, sr)
|
||||
}
|
||||
|
||||
// Process direct load results (bypass rerank model, assume high relevance)
|
||||
for _, sr := range directLoadResults {
|
||||
base := sr.Score
|
||||
sr.Metadata["base_score"] = fmt.Sprintf("%.4f", base)
|
||||
// Assign high model score for direct load items
|
||||
modelScore := 1.0
|
||||
sr.Score = compositeScore(sr, modelScore, base)
|
||||
pipelineInfo(ctx, "Rerank", "composite_calc_direct", map[string]interface{}{
|
||||
"chunk_id": sr.ID,
|
||||
"base_score": fmt.Sprintf("%.4f", base),
|
||||
"model_score": fmt.Sprintf("%.4f", modelScore),
|
||||
"final_score": fmt.Sprintf("%.4f", sr.Score),
|
||||
"match_type": sr.MatchType,
|
||||
})
|
||||
reranked = append(reranked, sr)
|
||||
}
|
||||
final := applyMMR(ctx, reranked, chatManage, min(len(reranked), max(1, chatManage.RerankTopK)), 0.7)
|
||||
chatManage.RerankResult = final
|
||||
|
||||
@@ -160,6 +201,7 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
// rerank performs the actual reranking operation with given query and passages
|
||||
func (p *PluginRerank) rerank(ctx context.Context,
|
||||
chatManage *types.ChatManage, rerankModel rerank.Reranker, query string, passages []string,
|
||||
candidates []*types.SearchResult,
|
||||
) []rerank.RankResult {
|
||||
pipelineInfo(ctx, "Rerank", "model_call", map[string]interface{}{
|
||||
"query_variant": query,
|
||||
@@ -179,21 +221,26 @@ func (p *PluginRerank) rerank(ctx context.Context,
|
||||
"threshold": chatManage.RerankThreshold,
|
||||
})
|
||||
for i := range min(5, len(rerankResp)) {
|
||||
pipelineInfo(ctx, "Rerank", "top_score", map[string]interface{}{
|
||||
"rank": i + 1,
|
||||
"score": rerankResp[i].RelevanceScore,
|
||||
"chunk_id": chatManage.SearchResult[rerankResp[i].Index].ID,
|
||||
"match_type": chatManage.SearchResult[rerankResp[i].Index].MatchType,
|
||||
"chunk_type": chatManage.SearchResult[rerankResp[i].Index].ChunkType,
|
||||
"content": chatManage.SearchResult[rerankResp[i].Index].Content,
|
||||
})
|
||||
if rerankResp[i].Index < len(candidates) {
|
||||
pipelineInfo(ctx, "Rerank", "top_score", map[string]interface{}{
|
||||
"rank": i + 1,
|
||||
"score": rerankResp[i].RelevanceScore,
|
||||
"chunk_id": candidates[rerankResp[i].Index].ID,
|
||||
"match_type": candidates[rerankResp[i].Index].MatchType,
|
||||
"chunk_type": candidates[rerankResp[i].Index].ChunkType,
|
||||
"content": candidates[rerankResp[i].Index].Content,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Filter results based on threshold with special handling for history matches
|
||||
rankFilter := []rerank.RankResult{}
|
||||
for _, result := range rerankResp {
|
||||
if result.Index >= len(candidates) {
|
||||
continue
|
||||
}
|
||||
th := chatManage.RerankThreshold
|
||||
matchType := chatManage.SearchResult[result.Index].MatchType
|
||||
matchType := candidates[result.Index].MatchType
|
||||
if matchType == types.MatchTypeHistory {
|
||||
th = math.Max(th-0.1, 0.5) // Lower threshold for history matches
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
type PluginSearch struct {
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
config *config.Config
|
||||
webSearchService interfaces.WebSearchService
|
||||
tenantService interfaces.TenantService
|
||||
@@ -28,6 +29,7 @@ type PluginSearch struct {
|
||||
func NewPluginSearch(eventManager *EventManager,
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
chunkService interfaces.ChunkService,
|
||||
config *config.Config,
|
||||
webSearchService interfaces.WebSearchService,
|
||||
tenantService interfaces.TenantService,
|
||||
@@ -36,6 +38,7 @@ func NewPluginSearch(eventManager *EventManager,
|
||||
res := &PluginSearch{
|
||||
knowledgeBaseService: knowledgeBaseService,
|
||||
knowledgeService: knowledgeService,
|
||||
chunkService: chunkService,
|
||||
config: config,
|
||||
webSearchService: webSearchService,
|
||||
tenantService: tenantService,
|
||||
@@ -54,35 +57,25 @@ func (p *PluginSearch) ActivationEvents() []types.EventType {
|
||||
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}
|
||||
pipelineInfo(ctx, "Search", "fallback_kb", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"kb_id": chatManage.KnowledgeBaseID,
|
||||
})
|
||||
}
|
||||
|
||||
if len(knowledgeBaseIDs) == 0 {
|
||||
// Check if we have search targets
|
||||
if len(chatManage.SearchTargets) == 0 && len(chatManage.KnowledgeBaseIDs) == 0 && len(chatManage.KnowledgeIDs) == 0 {
|
||||
pipelineError(ctx, "Search", "kb_not_found", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
})
|
||||
return ErrSearch.WithError(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "Search", "input", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"rewrite_query": chatManage.RewriteQuery,
|
||||
"kb_ids": strings.Join(knowledgeBaseIDs, ","),
|
||||
"tenant_id": chatManage.TenantID,
|
||||
"web_enabled": chatManage.WebSearchEnabled,
|
||||
"session_id": chatManage.SessionID,
|
||||
"rewrite_query": chatManage.RewriteQuery,
|
||||
"search_targets": len(chatManage.SearchTargets),
|
||||
"tenant_id": chatManage.TenantID,
|
||||
"web_enabled": chatManage.WebSearchEnabled,
|
||||
})
|
||||
|
||||
// Run KB search and web search concurrently
|
||||
pipelineInfo(ctx, "Search", "plan", map[string]interface{}{
|
||||
"kb_count": len(knowledgeBaseIDs),
|
||||
"search_targets": len(chatManage.SearchTargets),
|
||||
"embedding_top_k": chatManage.EmbeddingTopK,
|
||||
"vector_threshold": chatManage.VectorThreshold,
|
||||
"keyword_threshold": chatManage.KeywordThreshold,
|
||||
@@ -92,10 +85,10 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
allResults := make([]*types.SearchResult, 0)
|
||||
|
||||
wg.Add(2)
|
||||
// Goroutine 1: Knowledge base search (rewrite + processed)
|
||||
// Goroutine 1: Knowledge base search using SearchTargets
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
kbResults := p.searchKnowledgeBases(ctx, knowledgeBaseIDs, chatManage)
|
||||
kbResults := p.searchByTargets(ctx, chatManage)
|
||||
if len(kbResults) > 0 {
|
||||
mu.Lock()
|
||||
allResults = append(allResults, kbResults...)
|
||||
@@ -141,11 +134,11 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
})
|
||||
expTopK := max(chatManage.EmbeddingTopK*2, chatManage.RerankTopK*2)
|
||||
expKwTh := chatManage.KeywordThreshold * 0.8
|
||||
// Concurrent expansion retrieval across queries and KBs
|
||||
// Concurrent expansion retrieval across queries and search targets
|
||||
expResults := make([]*types.SearchResult, 0, expTopK*len(expansions))
|
||||
var muExp sync.Mutex
|
||||
var wgExp sync.WaitGroup
|
||||
jobs := len(expansions) * len(knowledgeBaseIDs)
|
||||
jobs := len(expansions) * len(chatManage.SearchTargets)
|
||||
capSem := 16
|
||||
if jobs < capSem {
|
||||
capSem = jobs
|
||||
@@ -159,9 +152,9 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
"cap": capSem,
|
||||
})
|
||||
for _, q := range expansions {
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
for _, target := range chatManage.SearchTargets {
|
||||
wgExp.Add(1)
|
||||
go func(q string, kbID string) {
|
||||
go func(q string, t *types.SearchTarget) {
|
||||
defer wgExp.Done()
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
@@ -173,17 +166,21 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
DisableVectorMatch: true,
|
||||
DisableKeywordsMatch: false,
|
||||
}
|
||||
res, err := p.knowledgeBaseService.HybridSearch(ctx, kbID, paramsExp)
|
||||
// Apply knowledge ID filter if this is a partial KB search
|
||||
if t.Type == types.SearchTargetTypeKnowledge {
|
||||
paramsExp.KnowledgeIDs = t.KnowledgeIDs
|
||||
}
|
||||
res, err := p.knowledgeBaseService.HybridSearch(ctx, t.KnowledgeBaseID, paramsExp)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Search", "expansion_error", map[string]interface{}{
|
||||
"kb_id": kbID,
|
||||
"kb_id": t.KnowledgeBaseID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
if len(res) > 0 {
|
||||
pipelineInfo(ctx, "Search", "expansion_hits", map[string]interface{}{
|
||||
"kb_id": kbID,
|
||||
"kb_id": t.KnowledgeBaseID,
|
||||
"query": q,
|
||||
"hits": len(res),
|
||||
})
|
||||
@@ -191,7 +188,7 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
expResults = append(expResults, res...)
|
||||
muExp.Unlock()
|
||||
}
|
||||
}(q, kbID)
|
||||
}(q, target)
|
||||
}
|
||||
}
|
||||
wgExp.Wait()
|
||||
@@ -308,46 +305,89 @@ func buildContentSignature(content string) string {
|
||||
return searchutil.BuildContentSignature(content)
|
||||
}
|
||||
|
||||
// searchKnowledgeBases performs KB searches across KB IDs using RewriteQuery only
|
||||
func (p *PluginSearch) searchKnowledgeBases(
|
||||
// searchByTargets performs KB searches using pre-computed SearchTargets
|
||||
// This is the main search method that uses the unified search targets
|
||||
func (p *PluginSearch) searchByTargets(
|
||||
ctx context.Context,
|
||||
knowledgeBaseIDs []string,
|
||||
chatManage *types.ChatManage,
|
||||
) []*types.SearchResult {
|
||||
// Build params for rewrite query
|
||||
baseParams := types.SearchParams{
|
||||
QueryText: strings.TrimSpace(chatManage.RewriteQuery),
|
||||
VectorThreshold: chatManage.VectorThreshold,
|
||||
KeywordThreshold: chatManage.KeywordThreshold,
|
||||
MatchCount: chatManage.EmbeddingTopK,
|
||||
if len(chatManage.SearchTargets) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
var results []*types.SearchResult
|
||||
|
||||
// Search with rewrite query only (removed duplicate ProcessedQuery search)
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
// Search each target concurrently
|
||||
for _, target := range chatManage.SearchTargets {
|
||||
wg.Add(1)
|
||||
go func(knowledgeBaseID string) {
|
||||
go func(t *types.SearchTarget) {
|
||||
defer wg.Done()
|
||||
res, err := p.knowledgeBaseService.HybridSearch(ctx, knowledgeBaseID, baseParams)
|
||||
|
||||
// List of knowledge IDs to perform vector search on
|
||||
// Default to all IDs in the target
|
||||
searchKnowledgeIDs := t.KnowledgeIDs
|
||||
|
||||
// Try direct loading for specific knowledge targets
|
||||
if t.Type == types.SearchTargetTypeKnowledge {
|
||||
directResults, skippedIDs := p.tryDirectChunkLoading(ctx, chatManage.TenantID, t.KnowledgeIDs)
|
||||
|
||||
if len(directResults) > 0 {
|
||||
pipelineInfo(ctx, "Search", "direct_load", map[string]interface{}{
|
||||
"kb_id": t.KnowledgeBaseID,
|
||||
"loaded_count": len(directResults),
|
||||
"skipped_ids": len(skippedIDs),
|
||||
})
|
||||
mu.Lock()
|
||||
results = append(results, directResults...)
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
// If all files were loaded directly, we don't need to search anything
|
||||
if len(skippedIDs) == 0 && len(t.KnowledgeIDs) > 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Otherwise, only search the files that were skipped (too large)
|
||||
searchKnowledgeIDs = skippedIDs
|
||||
}
|
||||
|
||||
// If no IDs left to search (and we are in Knowledge mode), we are done
|
||||
if t.Type == types.SearchTargetTypeKnowledge && len(searchKnowledgeIDs) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Build params for rewrite query
|
||||
params := types.SearchParams{
|
||||
QueryText: strings.TrimSpace(chatManage.RewriteQuery),
|
||||
VectorThreshold: chatManage.VectorThreshold,
|
||||
KeywordThreshold: chatManage.KeywordThreshold,
|
||||
MatchCount: chatManage.EmbeddingTopK,
|
||||
}
|
||||
// Apply knowledge ID filter if this is a partial KB search
|
||||
if t.Type == types.SearchTargetTypeKnowledge {
|
||||
params.KnowledgeIDs = searchKnowledgeIDs
|
||||
}
|
||||
res, err := p.knowledgeBaseService.HybridSearch(ctx, t.KnowledgeBaseID, params)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Search", "kb_search_error", map[string]interface{}{
|
||||
"kb_id": knowledgeBaseID,
|
||||
"query": baseParams.QueryText,
|
||||
"error": err.Error(),
|
||||
"kb_id": t.KnowledgeBaseID,
|
||||
"target_type": t.Type,
|
||||
"query": params.QueryText,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
pipelineInfo(ctx, "Search", "kb_result", map[string]interface{}{
|
||||
"kb_id": knowledgeBaseID,
|
||||
"hit_count": len(res),
|
||||
"kb_id": t.KnowledgeBaseID,
|
||||
"target_type": t.Type,
|
||||
"hit_count": len(res),
|
||||
})
|
||||
mu.Lock()
|
||||
results = append(results, res...)
|
||||
mu.Unlock()
|
||||
}(kbID)
|
||||
}(target)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
@@ -358,6 +398,93 @@ func (p *PluginSearch) searchKnowledgeBases(
|
||||
return results
|
||||
}
|
||||
|
||||
// tryDirectChunkLoading attempts to load chunks for given knowledge IDs directly
|
||||
// Returns loaded results and a list of knowledge IDs that were skipped (e.g. due to size limits)
|
||||
func (p *PluginSearch) tryDirectChunkLoading(ctx context.Context, tenantID uint64, knowledgeIDs []string) ([]*types.SearchResult, []string) {
|
||||
if len(knowledgeIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Limit direct loading to avoid OOM or context overflow
|
||||
// 50 chunks * ~500 chars/chunk ~= 25k chars
|
||||
const maxTotalChunks = 50
|
||||
|
||||
var allChunks []*types.Chunk
|
||||
var skippedIDs []string
|
||||
loadedKnowledgeIDs := make(map[string]bool)
|
||||
|
||||
for _, kid := range knowledgeIDs {
|
||||
// Optimization: Check chunk count first if possible?
|
||||
chunks, err := p.chunkService.ListChunksByKnowledgeID(ctx, kid)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "DirectLoad: Failed to list chunks for knowledge %s: %v", kid, err)
|
||||
skippedIDs = append(skippedIDs, kid)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(allChunks)+len(chunks) > maxTotalChunks {
|
||||
logger.Infof(ctx, "DirectLoad: Skipped knowledge %s due to size limit (%d + %d > %d)",
|
||||
kid, len(allChunks), len(chunks), maxTotalChunks)
|
||||
skippedIDs = append(skippedIDs, kid)
|
||||
continue
|
||||
}
|
||||
allChunks = append(allChunks, chunks...)
|
||||
loadedKnowledgeIDs[kid] = true
|
||||
}
|
||||
|
||||
if len(allChunks) == 0 {
|
||||
return nil, skippedIDs
|
||||
}
|
||||
|
||||
// Fetch Knowledge metadata
|
||||
var uniqueKIDs []string
|
||||
for kid := range loadedKnowledgeIDs {
|
||||
uniqueKIDs = append(uniqueKIDs, kid)
|
||||
}
|
||||
|
||||
knowledgeMap := make(map[string]*types.Knowledge)
|
||||
if len(uniqueKIDs) > 0 {
|
||||
knowledges, err := p.knowledgeService.GetKnowledgeBatch(ctx, tenantID, uniqueKIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "DirectLoad: Failed to fetch knowledge batch: %v", err)
|
||||
// Continue without metadata
|
||||
} else {
|
||||
for _, k := range knowledges {
|
||||
knowledgeMap[k.ID] = k
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var results []*types.SearchResult
|
||||
for _, chunk := range allChunks {
|
||||
res := &types.SearchResult{
|
||||
ID: chunk.ID,
|
||||
Content: chunk.Content,
|
||||
Score: 1.0, // Maximum score for direct matches
|
||||
KnowledgeID: chunk.KnowledgeID,
|
||||
ChunkIndex: chunk.ChunkIndex,
|
||||
MatchType: types.MatchTypeDirectLoad,
|
||||
ChunkType: string(chunk.ChunkType),
|
||||
ParentChunkID: chunk.ParentChunkID,
|
||||
ImageInfo: chunk.ImageInfo,
|
||||
ChunkMetadata: chunk.Metadata,
|
||||
StartAt: chunk.StartAt,
|
||||
EndAt: chunk.EndAt,
|
||||
}
|
||||
|
||||
if k, ok := knowledgeMap[chunk.KnowledgeID]; ok {
|
||||
res.KnowledgeTitle = k.Title
|
||||
res.KnowledgeFilename = k.FileName
|
||||
res.KnowledgeSource = k.Source
|
||||
res.Metadata = k.GetMetadata()
|
||||
}
|
||||
|
||||
results = append(results, res)
|
||||
}
|
||||
|
||||
return results, skippedIDs
|
||||
}
|
||||
|
||||
// searchWebIfEnabled executes web search when enabled and returns converted results
|
||||
func (p *PluginSearch) searchWebIfEnabled(ctx context.Context, chatManage *types.ChatManage) []*types.SearchResult {
|
||||
if !chatManage.WebSearchEnabled || p.webSearchService == nil || p.tenantService == nil || chatManage.TenantID <= 0 {
|
||||
|
||||
@@ -47,50 +47,81 @@ func (p *PluginSearchEntity) OnEvent(ctx context.Context,
|
||||
return next()
|
||||
}
|
||||
|
||||
// Get knowledge base IDs list
|
||||
knowledgeBaseIDs := chatManage.KnowledgeBaseIDs
|
||||
if len(knowledgeBaseIDs) == 0 && chatManage.KnowledgeBaseID != "" {
|
||||
knowledgeBaseIDs = []string{chatManage.KnowledgeBaseID}
|
||||
logger.Infof(ctx, "No KnowledgeBaseIDs provided, falling back to single KB: %s", chatManage.KnowledgeBaseID)
|
||||
}
|
||||
// Use EntityKBIDs (knowledge bases with ExtractConfig enabled)
|
||||
knowledgeBaseIDs := chatManage.EntityKBIDs
|
||||
// Use EntityKnowledge (KnowledgeID -> KnowledgeBaseID mapping for graph-enabled files)
|
||||
entityKnowledge := chatManage.EntityKnowledge
|
||||
|
||||
if len(knowledgeBaseIDs) == 0 {
|
||||
logger.Warnf(ctx, "No knowledge base IDs available for entity search")
|
||||
if len(knowledgeBaseIDs) == 0 && len(entityKnowledge) == 0 {
|
||||
logger.Warnf(ctx, "No knowledge base IDs or knowledge IDs with ExtractConfig enabled for entity search")
|
||||
return next()
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Searching entities across %d knowledge base(s): %v", len(knowledgeBaseIDs), knowledgeBaseIDs)
|
||||
|
||||
// Parallel search across multiple knowledge bases
|
||||
// Parallel search across multiple knowledge bases and individual files
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
var allNodes []*types.GraphNode
|
||||
var allRelations []*types.GraphRelation
|
||||
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
wg.Add(1)
|
||||
go func(knowledgeBaseID string) {
|
||||
defer wg.Done()
|
||||
// If specific KnowledgeIDs are provided, search by individual files
|
||||
if len(entityKnowledge) > 0 {
|
||||
logger.Infof(ctx, "Searching entities across %d knowledge file(s)", len(entityKnowledge))
|
||||
for knowledgeID, kbID := range entityKnowledge {
|
||||
wg.Add(1)
|
||||
go func(knowledgeBaseID, knowledgeID string) {
|
||||
defer wg.Done()
|
||||
|
||||
graph, err := p.graphRepo.SearchNode(ctx, types.NameSpace{KnowledgeBase: knowledgeBaseID}, entity)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to search entity in KB %s: %v", knowledgeBaseID, err)
|
||||
return
|
||||
}
|
||||
graph, err := p.graphRepo.SearchNode(ctx, types.NameSpace{
|
||||
KnowledgeBase: knowledgeBaseID,
|
||||
Knowledge: knowledgeID,
|
||||
}, entity)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to search entity in Knowledge %s: %v", knowledgeID, err)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"KB %s entity search result count: %d nodes, %d relations",
|
||||
knowledgeBaseID,
|
||||
len(graph.Node),
|
||||
len(graph.Relation),
|
||||
)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Knowledge %s entity search result count: %d nodes, %d relations",
|
||||
knowledgeID,
|
||||
len(graph.Node),
|
||||
len(graph.Relation),
|
||||
)
|
||||
|
||||
mu.Lock()
|
||||
allNodes = append(allNodes, graph.Node...)
|
||||
allRelations = append(allRelations, graph.Relation...)
|
||||
mu.Unlock()
|
||||
}(kbID)
|
||||
mu.Lock()
|
||||
allNodes = append(allNodes, graph.Node...)
|
||||
allRelations = append(allRelations, graph.Relation...)
|
||||
mu.Unlock()
|
||||
}(kbID, knowledgeID)
|
||||
}
|
||||
} else {
|
||||
// Otherwise, search by knowledge base
|
||||
logger.Infof(ctx, "Searching entities across %d knowledge base(s): %v", len(knowledgeBaseIDs), knowledgeBaseIDs)
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
wg.Add(1)
|
||||
go func(knowledgeBaseID string) {
|
||||
defer wg.Done()
|
||||
|
||||
graph, err := p.graphRepo.SearchNode(ctx, types.NameSpace{KnowledgeBase: knowledgeBaseID}, entity)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to search entity in KB %s: %v", knowledgeBaseID, err)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"KB %s entity search result count: %d nodes, %d relations",
|
||||
knowledgeBaseID,
|
||||
len(graph.Node),
|
||||
len(graph.Relation),
|
||||
)
|
||||
|
||||
mu.Lock()
|
||||
allNodes = append(allNodes, graph.Node...)
|
||||
allRelations = append(allRelations, graph.Relation...)
|
||||
mu.Unlock()
|
||||
}(kbID)
|
||||
}
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
@@ -35,6 +35,7 @@ func NewPluginSearchParallel(
|
||||
eventManager *EventManager,
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
chunkService interfaces.ChunkService,
|
||||
config *config.Config,
|
||||
webSearchService interfaces.WebSearchService,
|
||||
tenantService interfaces.TenantService,
|
||||
@@ -47,6 +48,7 @@ func NewPluginSearchParallel(
|
||||
searchPlugin := &PluginSearch{
|
||||
knowledgeBaseService: knowledgeBaseService,
|
||||
knowledgeService: knowledgeService,
|
||||
chunkService: chunkService,
|
||||
config: config,
|
||||
webSearchService: webSearchService,
|
||||
tenantService: tenantService,
|
||||
|
||||
Reference in New Issue
Block a user