refactor: Introduce searchutil package for web search result conversion and keyword score normalization

- Migrate web search result conversion logic to a new searchutil package to avoid code duplication and improve maintainability.
- Implement robust keyword score normalization using percentile bounds in the searchutil package, enhancing score handling across different contexts.
- Update relevant functions in the application to utilize the new searchutil methods, streamlining the codebase.
This commit is contained in:
wizardchen
2025-12-01 18:27:12 +08:00
parent 3e31fdeefd
commit 85b1c4bc49
6 changed files with 293 additions and 408 deletions
+34 -149
View File
@@ -14,6 +14,7 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
@@ -1213,161 +1214,45 @@ type chunkRange struct {
end int
}
// findMissingChunkRanges finds all continuous ranges of missing chunks
// retrievedChunks is a set of retrieved chunk indices
// totalChunks is the total number of chunks
func (t *KnowledgeSearchTool) findMissingChunkRanges(retrievedChunks map[int]bool, totalChunks int) []chunkRange {
if totalChunks <= 0 {
return nil
}
var ranges []chunkRange
currentStart := -1
// Iterate through all possible chunk indices (0 to totalChunks-1)
for i := 0; i < totalChunks; i++ {
if !retrievedChunks[i] {
// This chunk is missing
if currentStart == -1 {
// Start of a new missing range
currentStart = i
}
} else {
// This chunk is retrieved
if currentStart != -1 {
// End of a missing range
ranges = append(ranges, chunkRange{
start: currentStart,
end: i - 1,
})
currentStart = -1
}
}
}
// Handle case where missing chunks extend to the end
if currentStart != -1 {
ranges = append(ranges, chunkRange{
start: currentStart,
end: totalChunks - 1,
})
}
return ranges
}
// normalizeKeywordSearchResults normalizes keyword search result scores into [0,1] globally across all knowledge bases
// Improvements:
// 1. Uses robust normalization with percentile-based bounds to handle outliers
// 2. Handles edge cases: single result, no variance, negative scores
// 3. Global normalization ensures fair comparison across different knowledge bases
func (t *KnowledgeSearchTool) normalizeKeywordSearchResults(ctx context.Context, results []*searchResultWithMeta) {
// Filter keyword match results
keywordResults := make([]*searchResultWithMeta, 0)
for _, result := range results {
if result.MatchType == types.MatchTypeKeywords {
keywordResults = append(keywordResults, result)
}
}
if len(keywordResults) == 0 {
return
}
// Single result: set to 1.0
if len(keywordResults) == 1 {
keywordResults[0].Score = 1.0
return
}
// Find min and max scores globally
minS := keywordResults[0].Score
maxS := keywordResults[0].Score
for _, r := range keywordResults {
if r.Score < minS {
minS = r.Score
}
if r.Score > maxS {
maxS = r.Score
}
}
// No variance: all scores are the same
if maxS <= minS {
for _, r := range keywordResults {
r.Score = 1.0
}
logger.Infof(
ctx,
"[Tool][KnowledgeSearch] Keyword scores have no variance, all set to 1.0: count=%d, score=%.3f",
len(keywordResults),
minS,
)
return
}
// Robust normalization: use percentile-based bounds to reduce outlier impact
// For small groups, use min/max; for larger groups, use 5th and 95th percentiles
normalizeMin := minS
normalizeMax := maxS
if len(keywordResults) >= 10 {
// For larger groups, use percentile-based bounds to handle outliers
// Sort scores to find percentiles
scores := make([]float64, len(keywordResults))
for i, r := range keywordResults {
scores[i] = r.Score
}
sort.Float64s(scores)
// Use 5th and 95th percentiles to reduce outlier impact
p5Idx := len(scores) * 5 / 100
p95Idx := len(scores) * 95 / 100
if p5Idx < len(scores) {
normalizeMin = scores[p5Idx]
}
if p95Idx < len(scores) {
normalizeMax = scores[p95Idx]
}
}
// Normalize scores with bounds checking
rangeSize := normalizeMax - normalizeMin
if rangeSize > 0 {
for _, r := range keywordResults {
// Clamp to [normalizeMin, normalizeMax] before normalization
clampedScore := r.Score
if clampedScore < normalizeMin {
clampedScore = normalizeMin
} else if clampedScore > normalizeMax {
clampedScore = normalizeMax
}
// Normalize to [0, 1]
ns := (clampedScore - normalizeMin) / rangeSize
if ns < 0 {
ns = 0
} else if ns > 1 {
ns = 1
}
r.Score = ns
}
logger.Infof(
ctx,
"[Tool][KnowledgeSearch] Normalized keyword scores: count=%d, raw_min=%.3f, raw_max=%.3f, normalize_min=%.3f, normalize_max=%.3f",
len(keywordResults),
minS,
maxS,
normalizeMin,
normalizeMax,
)
} else {
// Fallback: all scores are the same after percentile filtering
for _, r := range keywordResults {
r.Score = 1.0
}
}
searchutil.NormalizeKeywordScores[*searchResultWithMeta](
results,
func(r *searchResultWithMeta) bool {
return r.MatchType == types.MatchTypeKeywords
},
func(r *searchResultWithMeta) float64 {
return r.Score
},
func(r *searchResultWithMeta, score float64) {
r.Score = score
},
searchutil.KeywordScoreCallbacks{
OnNoVariance: func(count int, score float64) {
logger.Infof(
ctx,
"[Tool][KnowledgeSearch] Keyword scores have no variance, all set to 1.0: count=%d, score=%.3f",
count,
score,
)
},
OnNormalized: func(count int, rawMin, rawMax, normalizeMin, normalizeMax float64) {
logger.Infof(
ctx,
"[Tool][KnowledgeSearch] Normalized keyword scores: count=%d, raw_min=%.3f, raw_max=%.3f, normalize_min=%.3f, normalize_max=%.3f",
count,
rawMin,
rawMax,
normalizeMin,
normalizeMax,
)
},
},
)
}
// getEnrichedPassage 合并Content和ImageInfo的文本内容
@@ -4,13 +4,12 @@ import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
@@ -434,81 +433,13 @@ func (p *PluginSearch) searchWebIfEnabled(ctx context.Context, chatManage *types
// Persist temp KB state back into Redis using SessionService
p.sessionService.SaveWebSearchTempKBState(ctx, chatManage.SessionID, kbID, newSeen, newIDs)
}
res := convertWebSearchResults(webResults)
res := searchutil.ConvertWebSearchResults(webResults)
pipelineInfo(ctx, "Search", "web_hits", map[string]interface{}{
"hit_count": len(res),
})
return res
}
// convertWebSearchResults converts WebSearchResult to SearchResult
// This is a duplicate of the function in service/web_search.go to avoid circular imports
func convertWebSearchResults(webResults []*types.WebSearchResult) []*types.SearchResult {
results := make([]*types.SearchResult, 0, len(webResults))
for i, webResult := range webResults {
// Use URL as ChunkID for web search results
chunkID := webResult.URL
if chunkID == "" {
chunkID = fmt.Sprintf("web_search_%d", i)
}
// Combine title and snippet as content
content := webResult.Title
if webResult.Snippet != "" {
if content != "" {
content += "\n\n" + webResult.Snippet
} else {
content = webResult.Snippet
}
}
if webResult.Content != "" {
if content != "" {
content += "\n\n" + webResult.Content
} else {
content = webResult.Content
}
}
// Set a default score for web search results (0.6, indicating medium relevance)
score := 0.6
result := &types.SearchResult{
ID: chunkID,
Content: content,
KnowledgeID: "", // Web search results don't have knowledge ID
ChunkIndex: 0,
KnowledgeTitle: webResult.Title,
StartAt: 0,
EndAt: runeLen(content),
Seq: 1,
Score: score,
MatchType: types.MatchTypeWebSearch,
SubChunkID: []string{},
Metadata: map[string]string{
"url": webResult.URL,
"source": webResult.Source,
"title": webResult.Title,
"snippet": webResult.Snippet,
},
ChunkType: string(types.ChunkTypeWebSearch),
ParentChunkID: "",
ImageInfo: "",
KnowledgeFilename: "",
KnowledgeSource: "web_search",
}
// Add published date to metadata if available
if webResult.PublishedAt != nil {
result.Metadata["published_at"] = webResult.PublishedAt.Format(time.RFC3339)
}
results = append(results, result)
}
return results
}
// expandQueries generates paraphrases and synonyms using chat model to improve keyword recall
func (p *PluginSearch) expandQueries(ctx context.Context, chatManage *types.ChatManage) []string {
if p.modelService == nil || chatManage.ChatModelID == "" {
@@ -595,106 +526,33 @@ func extractJSONBlock(text string) string {
// 2. Handles edge cases: single result, no variance, negative scores
// 3. Global normalization ensures fair comparison across different knowledge bases
func normalizeKeywordSearchResults(ctx context.Context, results []*types.SearchResult) {
// Filter keyword match results
keywordResults := make([]*types.SearchResult, 0)
for _, result := range results {
if result.MatchType == types.MatchTypeKeywords {
keywordResults = append(keywordResults, result)
}
}
if len(keywordResults) == 0 {
return
}
// Single result: set to 1.0
if len(keywordResults) == 1 {
keywordResults[0].Score = 1.0
return
}
// Find min and max scores globally
minS := keywordResults[0].Score
maxS := keywordResults[0].Score
for _, r := range keywordResults {
if r.Score < minS {
minS = r.Score
}
if r.Score > maxS {
maxS = r.Score
}
}
// No variance: all scores are the same
if maxS <= minS {
for _, r := range keywordResults {
r.Score = 1.0
}
pipelineInfo(ctx, "Search", "keyword_scores_no_variance", map[string]interface{}{
"count": len(keywordResults),
"score": minS,
})
return
}
// Robust normalization: use percentile-based bounds to reduce outlier impact
// For small groups, use min/max; for larger groups, use 5th and 95th percentiles
normalizeMin := minS
normalizeMax := maxS
if len(keywordResults) >= 10 {
// For larger groups, use percentile-based bounds to handle outliers
// Sort scores to find percentiles
scores := make([]float64, len(keywordResults))
for i, r := range keywordResults {
scores[i] = r.Score
}
sort.Float64s(scores)
// Use 5th and 95th percentiles to reduce outlier impact
p5Idx := len(scores) * 5 / 100
p95Idx := len(scores) * 95 / 100
if p5Idx < len(scores) {
normalizeMin = scores[p5Idx]
}
if p95Idx < len(scores) {
normalizeMax = scores[p95Idx]
}
}
// Normalize scores with bounds checking
rangeSize := normalizeMax - normalizeMin
if rangeSize > 0 {
for _, r := range keywordResults {
// Clamp to [normalizeMin, normalizeMax] before normalization
clampedScore := r.Score
if clampedScore < normalizeMin {
clampedScore = normalizeMin
} else if clampedScore > normalizeMax {
clampedScore = normalizeMax
}
// Normalize to [0, 1]
ns := (clampedScore - normalizeMin) / rangeSize
if ns < 0 {
ns = 0
} else if ns > 1 {
ns = 1
}
r.Score = ns
}
pipelineInfo(ctx, "Search", "normalize_keyword_scores", map[string]interface{}{
"count": len(keywordResults),
"raw_min": minS,
"raw_max": maxS,
"normalize_min": normalizeMin,
"normalize_max": normalizeMax,
})
} else {
// Fallback: all scores are the same after percentile filtering
for _, r := range keywordResults {
r.Score = 1.0
}
}
searchutil.NormalizeKeywordScores[*types.SearchResult](
results,
func(r *types.SearchResult) bool {
return r.MatchType == types.MatchTypeKeywords
},
func(r *types.SearchResult) float64 {
return r.Score
},
func(r *types.SearchResult, score float64) {
r.Score = score
},
searchutil.KeywordScoreCallbacks{
OnNoVariance: func(count int, score float64) {
pipelineInfo(ctx, "Search", "keyword_scores_no_variance", map[string]interface{}{
"count": count,
"score": score,
})
},
OnNormalized: func(count int, rawMin, rawMax, normalizeMin, normalizeMax float64) {
pipelineInfo(ctx, "Search", "normalize_keyword_scores", map[string]interface{}{
"count": count,
"raw_min": rawMin,
"raw_max": rawMax,
"normalize_min": normalizeMin,
"normalize_max": normalizeMax,
})
},
},
)
}
+5 -66
View File
@@ -10,6 +10,7 @@ import (
"github.com/Tencent/WeKnora/internal/application/service/web_search"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
@@ -372,70 +373,8 @@ func (s *WebSearchService) matchesBlacklistRule(url, rule string) bool {
// ConvertWebSearchResults converts WebSearchResult to SearchResult
func ConvertWebSearchResults(webResults []*types.WebSearchResult) []*types.SearchResult {
results := make([]*types.SearchResult, 0, len(webResults))
for i, webResult := range webResults {
if webResult == nil {
continue
}
// Use URL as ChunkID for web search results
chunkID := webResult.URL
if chunkID == "" {
chunkID = fmt.Sprintf("web_search_%d", i)
}
// Combine title and snippet as content
content := webResult.Title
if webResult.Snippet != "" {
if content != "" {
content += "\n\n" + webResult.Snippet
} else {
content = webResult.Snippet
}
}
if webResult.Content != "" {
if content != "" {
content += "\n\n" + webResult.Content
} else {
content = webResult.Content
}
}
// Set a default score for web search results (0.6, indicating medium relevance)
score := 0.6
result := &types.SearchResult{
ID: chunkID,
Content: content,
KnowledgeID: "", // Web search results don't have knowledge ID
ChunkIndex: 0,
KnowledgeTitle: webResult.Title,
StartAt: 0,
EndAt: len(content),
Seq: i,
Score: score,
MatchType: types.MatchTypeWebSearch,
SubChunkID: []string{},
Metadata: map[string]string{
"url": webResult.URL,
"source": webResult.Source,
"title": webResult.Title,
"snippet": webResult.Snippet,
},
ChunkType: "web_search",
ParentChunkID: "",
ImageInfo: "",
KnowledgeFilename: "",
KnowledgeSource: "web_search",
}
// Add published date to metadata if available
if webResult.PublishedAt != nil {
result.Metadata["published_at"] = webResult.PublishedAt.Format(time.RFC3339)
}
results = append(results, result)
}
return results
return searchutil.ConvertWebSearchResults(
webResults,
searchutil.WithSeqFunc(func(idx int) int { return idx }),
)
}
+17 -20
View File
@@ -84,22 +84,8 @@ func (m *MCPManager) GetOrCreateClient(service *types.MCPService) (MCPClient, er
return nil, fmt.Errorf("failed to connect to MCP service: %w", err)
}
// Initialize needs a timeout to prevent hanging, but the connection context should remain alive
// Use a timeout context only for the initialization request
initTimeout := 30 * time.Second
if service.AdvancedConfig != nil && service.AdvancedConfig.Timeout > 0 {
initTimeout = time.Duration(service.AdvancedConfig.Timeout) * time.Second
if initTimeout > 60*time.Second {
initTimeout = 60 * time.Second
}
}
initCtx, initCancel := context.WithTimeout(m.ctx, initTimeout)
defer initCancel() // Safe to cancel after init - it's a one-time operation
if _, err := client.Initialize(initCtx); err != nil {
client.Disconnect()
return nil, fmt.Errorf("failed to initialize MCP client: %w", err)
if err := m.initializeClient(service, client, "failed to initialize MCP client"); err != nil {
return nil, err
}
// Store client (only for non-stdio transports)
@@ -127,7 +113,16 @@ func (m *MCPManager) createStdioClient(service *types.MCPService) (MCPClient, er
return nil, fmt.Errorf("failed to connect to stdio MCP service: %w", err)
}
// Initialize needs a timeout to prevent hanging
if err := m.initializeClient(service, client, "failed to initialize stdio MCP client"); err != nil {
return nil, err
}
logger.GetLogger(m.ctx).Infof("MCP stdio client created and initialized for service: %s", service.Name)
return client, nil
}
// initializeClient handles the shared initialization flow with timeout enforcement.
func (m *MCPManager) initializeClient(service *types.MCPService, client MCPClient, errPrefix string) error {
initTimeout := 30 * time.Second
if service.AdvancedConfig != nil && service.AdvancedConfig.Timeout > 0 {
initTimeout = time.Duration(service.AdvancedConfig.Timeout) * time.Second
@@ -141,11 +136,13 @@ func (m *MCPManager) createStdioClient(service *types.MCPService) (MCPClient, er
if _, err := client.Initialize(initCtx); err != nil {
client.Disconnect()
return nil, fmt.Errorf("failed to initialize stdio MCP client: %w", err)
if errPrefix == "" {
errPrefix = "failed to initialize MCP client"
}
return fmt.Errorf("%s: %w", errPrefix, err)
}
logger.GetLogger(m.ctx).Infof("MCP stdio client created and initialized for service: %s", service.Name)
return client, nil
return nil
}
// GetClient gets an existing client
+97
View File
@@ -0,0 +1,97 @@
package searchutil
import (
"fmt"
"time"
"unicode/utf8"
"github.com/Tencent/WeKnora/internal/types"
)
// ConvertWebResultOption configures ConvertWebSearchResults behavior.
type ConvertWebResultOption func(*convertWebResultOptions)
type convertWebResultOptions struct {
seqFunc func(idx int) int
}
// WithSeqFunc overrides the default sequence assignment for converted results.
func WithSeqFunc(f func(idx int) int) ConvertWebResultOption {
return func(opts *convertWebResultOptions) {
opts.seqFunc = f
}
}
// ConvertWebSearchResults converts []*types.WebSearchResult into []*types.SearchResult.
func ConvertWebSearchResults(
webResults []*types.WebSearchResult,
opts ...ConvertWebResultOption,
) []*types.SearchResult {
options := convertWebResultOptions{
seqFunc: func(int) int { return 1 },
}
for _, opt := range opts {
opt(&options)
}
results := make([]*types.SearchResult, 0, len(webResults))
for i, webResult := range webResults {
if webResult == nil {
continue
}
chunkID := webResult.URL
if chunkID == "" {
chunkID = fmt.Sprintf("web_search_%d", i)
}
content := webResult.Title
appendContent := func(text string) {
if text == "" {
return
}
if content != "" {
content += "\n\n" + text
} else {
content = text
}
}
appendContent(webResult.Snippet)
appendContent(webResult.Content)
result := &types.SearchResult{
ID: chunkID,
Content: content,
KnowledgeID: "",
ChunkIndex: 0,
KnowledgeTitle: webResult.Title,
StartAt: 0,
EndAt: utf8.RuneCountInString(content),
Seq: options.seqFunc(i),
Score: 0.6,
MatchType: types.MatchTypeWebSearch,
SubChunkID: []string{},
Metadata: map[string]string{
"url": webResult.URL,
"source": webResult.Source,
"title": webResult.Title,
"snippet": webResult.Snippet,
},
ChunkType: string(types.ChunkTypeWebSearch),
ParentChunkID: "",
ImageInfo: "",
KnowledgeFilename: "",
KnowledgeSource: "web_search",
}
if webResult.PublishedAt != nil {
result.Metadata["published_at"] = webResult.PublishedAt.Format(time.RFC3339)
}
results = append(results, result)
}
return results
}
+109
View File
@@ -0,0 +1,109 @@
package searchutil
import "sort"
// KeywordScoreCallbacks allows callers to hook into normalization telemetry.
type KeywordScoreCallbacks struct {
OnNoVariance func(count int, score float64)
OnNormalized func(count int, rawMin, rawMax, normalizeMin, normalizeMax float64)
}
// NormalizeKeywordScores normalizes keyword match scores in-place using robust percentile bounds.
func NormalizeKeywordScores[T any](
results []T,
isKeyword func(T) bool,
getScore func(T) float64,
setScore func(T, float64),
callbacks KeywordScoreCallbacks,
) {
keywordResults := make([]T, 0, len(results))
for _, result := range results {
if isKeyword(result) {
keywordResults = append(keywordResults, result)
}
}
if len(keywordResults) == 0 {
return
}
if len(keywordResults) == 1 {
setScore(keywordResults[0], 1.0)
return
}
minS := getScore(keywordResults[0])
maxS := minS
for _, r := range keywordResults[1:] {
score := getScore(r)
if score < minS {
minS = score
}
if score > maxS {
maxS = score
}
}
if maxS <= minS {
for _, r := range keywordResults {
setScore(r, 1.0)
}
if callbacks.OnNoVariance != nil {
callbacks.OnNoVariance(len(keywordResults), minS)
}
return
}
normalizeMin := minS
normalizeMax := maxS
if len(keywordResults) >= 10 {
scores := make([]float64, len(keywordResults))
for i, r := range keywordResults {
scores[i] = getScore(r)
}
sort.Float64s(scores)
p5Idx := len(scores) * 5 / 100
p95Idx := len(scores) * 95 / 100
if p5Idx < len(scores) {
normalizeMin = scores[p5Idx]
}
if p95Idx < len(scores) {
normalizeMax = scores[p95Idx]
}
}
rangeSize := normalizeMax - normalizeMin
if rangeSize > 0 {
for _, r := range keywordResults {
clamped := getScore(r)
if clamped < normalizeMin {
clamped = normalizeMin
} else if clamped > normalizeMax {
clamped = normalizeMax
}
ns := (clamped - normalizeMin) / rangeSize
if ns < 0 {
ns = 0
} else if ns > 1 {
ns = 1
}
setScore(r, ns)
}
if callbacks.OnNormalized != nil {
callbacks.OnNormalized(
len(keywordResults),
minS,
maxS,
normalizeMin,
normalizeMax,
)
}
return
}
// Fallback when percentile filtering collapses the range.
for _, r := range keywordResults {
setScore(r, 1.0)
}
}