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
@@ -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 }),
)
}