feat: Enhance agent settings and UI components

- Updated the Input-field component to improve styling and consistency with new color scheme.
- Added model recommendation section in AgentSettings with localized content for better user guidance.
- Enhanced AgentStreamDisplay to conditionally show timeline based on event types, improving user experience.
- Updated botmsg and docInfo components for better display of web search references and document information.
- Improved fallback response handling in session management, allowing for more flexible user interactions.
- Introduced deduplication and scoring mechanisms in grep_chunks and knowledge_search tools to enhance search result relevance and diversity.
This commit is contained in:
wizardchen
2025-11-25 13:28:21 +08:00
parent 55d6bc7274
commit 9f6f5f5773
15 changed files with 1336 additions and 222 deletions
+295 -40
View File
@@ -3,6 +3,8 @@ package tools
import (
"context"
"fmt"
"math"
"sort"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
@@ -188,16 +190,52 @@ func (t *GrepChunksTool) Execute(ctx context.Context, args map[string]interface{
logger.Infof(ctx, "[Tool][GrepChunks] Found %d matching chunks", len(results))
// Apply deduplication to remove duplicate or near-duplicate chunks
deduplicatedResults := t.deduplicateChunks(ctx, results)
logger.Infof(ctx, "[Tool][GrepChunks] After deduplication: %d chunks (from %d)",
len(deduplicatedResults), len(results))
// Calculate match scores for sorting (based on match count and position)
scoredResults := t.scoreChunks(ctx, deduplicatedResults, patterns)
// Apply MMR to reduce redundancy if we have many results
finalResults := scoredResults
if len(scoredResults) > 10 {
// Use MMR when we have more than 10 results
mmrK := len(scoredResults)
if maxResults > 0 && mmrK > maxResults {
mmrK = maxResults
}
logger.Debugf(ctx, "[Tool][GrepChunks] Applying MMR: k=%d, lambda=0.7, input=%d results", mmrK, len(scoredResults))
mmrResults := t.applyMMR(ctx, scoredResults, patterns, mmrK, 0.7)
if len(mmrResults) > 0 {
finalResults = mmrResults
logger.Infof(ctx, "[Tool][GrepChunks] MMR completed: %d results selected", len(finalResults))
}
}
// Sort by match score (descending), then by chunk index
sort.Slice(finalResults, func(i, j int) bool {
if finalResults[i].MatchScore != finalResults[j].MatchScore {
return finalResults[i].MatchScore > finalResults[j].MatchScore
}
return finalResults[i].ChunkIndex < finalResults[j].ChunkIndex
})
if len(finalResults) > 20 {
finalResults = finalResults[:20]
}
// Format output
output := t.formatOutput(ctx, results, totalCount, patterns, contextLines, countOnly, showLineNumbers, kbIDs, knowledgeIDs)
output := t.formatOutput(ctx, finalResults, totalCount, patterns, contextLines, countOnly, showLineNumbers, kbIDs, knowledgeIDs)
return &types.ToolResult{
Success: true,
Output: output,
Data: map[string]interface{}{
"patterns": patterns,
"results": results,
"result_count": len(results),
"results": finalResults,
"result_count": len(finalResults),
"total_matches": totalCount,
"knowledge_base_ids": kbIDs,
"knowledge_ids": knowledgeIDs,
@@ -207,6 +245,12 @@ func (t *GrepChunksTool) Execute(ctx context.Context, args map[string]interface{
}, nil
}
type chunkWithTitle struct {
types.Chunk
Title string
MatchScore float64 // Score based on match count and position
}
// searchChunks performs the database search with pattern matching
func (t *GrepChunksTool) searchChunks(
ctx context.Context,
@@ -214,7 +258,7 @@ func (t *GrepChunksTool) searchChunks(
kbIDs []string,
knowledgeIDs []string,
maxResults int,
) ([]map[string]interface{}, int64, error) {
) ([]chunkWithTitle, int64, error) {
// Build base query
query := t.db.WithContext(ctx).Table("chunks").
Select("chunks.id, chunks.content, chunks.chunk_index, chunks.knowledge_id, chunks.knowledge_base_id, chunks.chunk_type, chunks.created_at, knowledges.title as knowledge_title").
@@ -255,7 +299,7 @@ func (t *GrepChunksTool) searchChunks(
}
// Fetch results
var results []map[string]interface{}
var results []chunkWithTitle
if err := query.Limit(maxResults).Order("chunks.created_at DESC").Find(&results).Error; err != nil {
logger.Errorf(ctx, "[Tool][GrepChunks] Failed to fetch results: %v", err)
return nil, 0, err
@@ -267,7 +311,7 @@ func (t *GrepChunksTool) searchChunks(
// formatOutput formats the search results for display (grep-style output)
func (t *GrepChunksTool) formatOutput(
ctx context.Context,
results []map[string]interface{},
results []chunkWithTitle,
totalCount int64,
patterns []string,
contextLines int,
@@ -304,19 +348,21 @@ func (t *GrepChunksTool) formatOutput(
// Group by document (like grep showing filename)
docGroups := make(map[string]struct {
title string
chunks []map[string]interface{}
title string
knowledgeBaseID string
chunks []chunkWithTitle
})
for _, result := range results {
knowledgeID := fmt.Sprintf("%v", result["knowledge_id"])
knowledgeID := fmt.Sprintf("%v", result.KnowledgeID)
title := "Untitled"
if t := result["knowledge_title"]; t != nil {
if t := result.Title; t != "" {
title = fmt.Sprintf("%v", t)
}
group := docGroups[knowledgeID]
group.title = title
group.knowledgeBaseID = result.KnowledgeBaseID
group.chunks = append(group.chunks, result)
docGroups[knowledgeID] = group
}
@@ -324,28 +370,13 @@ func (t *GrepChunksTool) formatOutput(
// Display results in grep-style format
for docID, group := range docGroups {
// Show document header (like grep showing filename)
if len(docGroups) > 1 {
output.WriteString(fmt.Sprintf("\n--- %s (knowledge_id: %s) ---\n", group.title, docID))
}
output.WriteString(fmt.Sprintf("\n--- knowledge_base_id: %s, knowledge_id: %s, title: %s ---\n",
group.knowledgeBaseID, docID, group.title))
// Show each matching chunk
for _, chunk := range group.chunks {
chunkIndex := 0
if idx, ok := chunk["chunk_index"]; ok {
switch v := idx.(type) {
case int:
chunkIndex = v
case int64:
chunkIndex = int(v)
case float64:
chunkIndex = int(v)
}
}
content := ""
if c, ok := chunk["content"]; ok && c != nil {
content = fmt.Sprintf("%v", c)
}
chunkIndex := chunk.ChunkIndex
content := chunk.Content
// Extract preview with context around match (case-insensitive)
// Try each pattern and use the first match
@@ -367,17 +398,6 @@ func (t *GrepChunksTool) formatOutput(
}
}
}
// Add guidance for next steps
output.WriteString("\n=== Next Steps ===\n")
if len(results) > 0 {
output.WriteString("- Found matching documents. Use knowledge_search with semantic queries to understand the context.\n")
output.WriteString("- Filter knowledge_search by knowledge_ids from above results for better relevance.\n")
} else {
output.WriteString("- No matches found. Try different keywords or use knowledge_search for semantic search.\n")
output.WriteString("- Consider using synonyms or related terms in your search patterns.\n")
}
return output.String()
}
@@ -477,3 +497,238 @@ func extractPreviewMultiPattern(content string, patterns []string, caseSensitive
}
return string(runes[:contextLen*2])
}
// deduplicateChunks removes duplicate or near-duplicate chunks using content signature
func (t *GrepChunksTool) deduplicateChunks(ctx context.Context, results []chunkWithTitle) []chunkWithTitle {
seen := make(map[string]bool)
contentSig := make(map[string]bool)
uniqueResults := make([]chunkWithTitle, 0)
for _, r := range results {
// Build multiple keys for deduplication
keys := []string{r.ID}
if r.ParentChunkID != "" {
keys = append(keys, "parent:"+r.ParentChunkID)
}
if r.KnowledgeID != "" {
keys = append(keys, fmt.Sprintf("kb:%s#%d", r.KnowledgeID, r.ChunkIndex))
}
// Check if any key is already seen
dup := false
for _, k := range keys {
if seen[k] {
dup = true
break
}
}
if dup {
continue
}
// Check content signature for near-duplicate content
sig := t.buildContentSignature(r.Content)
if sig != "" {
if contentSig[sig] {
continue
}
contentSig[sig] = true
}
// Mark all keys as seen
for _, k := range keys {
seen[k] = true
}
uniqueResults = append(uniqueResults, r)
}
// If we have duplicates by ID, keep the first one
seenByID := make(map[string]bool)
deduplicated := make([]chunkWithTitle, 0)
for _, r := range uniqueResults {
if !seenByID[r.ID] {
seenByID[r.ID] = true
deduplicated = append(deduplicated, r)
}
}
return deduplicated
}
// buildContentSignature creates a normalized signature for content to detect near-duplicates
func (t *GrepChunksTool) buildContentSignature(content string) string {
c := strings.ToLower(strings.TrimSpace(content))
if c == "" {
return ""
}
// Normalize whitespace
c = strings.Join(strings.Fields(c), " ")
// Use first 128 characters as signature
if len(c) > 128 {
c = c[:128]
}
return c
}
// scoreChunks calculates match scores for chunks based on pattern matches
func (t *GrepChunksTool) scoreChunks(ctx context.Context, results []chunkWithTitle, patterns []string) []chunkWithTitle {
scored := make([]chunkWithTitle, len(results))
for i := range results {
scored[i] = results[i]
scored[i].MatchScore = t.calculateMatchScore(results[i].Content, patterns)
}
return scored
}
// calculateMatchScore calculates a score based on how many patterns match and their positions
func (t *GrepChunksTool) calculateMatchScore(content string, patterns []string) float64 {
if content == "" || len(patterns) == 0 {
return 0.0
}
contentLower := strings.ToLower(content)
matchCount := 0
earliestPos := len(content)
// Count how many patterns match and find earliest position
for _, pattern := range patterns {
patternLower := strings.ToLower(pattern)
if strings.Contains(contentLower, patternLower) {
matchCount++
// Find position of first match
pos := strings.Index(contentLower, patternLower)
if pos >= 0 && pos < earliestPos {
earliestPos = pos
}
}
}
// Score: higher for more matches, slightly higher for earlier positions
// Base score: match ratio (0.0 to 1.0)
baseScore := float64(matchCount) / float64(len(patterns))
// Position bonus: earlier matches get slight boost (max 0.1)
positionBonus := 0.0
if earliestPos < len(content) {
// Normalize position to [0, 1] and apply small bonus
positionRatio := 1.0 - float64(earliestPos)/float64(len(content))
positionBonus = positionRatio * 0.1
}
return math.Min(baseScore+positionBonus, 1.0)
}
// applyMMR applies Maximal Marginal Relevance algorithm to reduce redundancy
func (t *GrepChunksTool) applyMMR(
ctx context.Context,
results []chunkWithTitle,
patterns []string,
k int,
lambda float64,
) []chunkWithTitle {
if k <= 0 || len(results) == 0 {
return nil
}
logger.Debugf(ctx, "[Tool][GrepChunks] Applying MMR: lambda=%.2f, k=%d, candidates=%d",
lambda, k, len(results))
selected := make([]chunkWithTitle, 0, k)
candidates := make([]chunkWithTitle, len(results))
copy(candidates, results)
// Pre-compute token sets for all candidates
tokenSets := make([]map[string]struct{}, len(candidates))
for i, r := range candidates {
tokenSets[i] = t.tokenizeSimple(r.Content)
}
// MMR selection loop
for len(selected) < k && len(candidates) > 0 {
bestIdx := 0
bestScore := -1.0
for i, r := range candidates {
relevance := r.MatchScore
redundancy := 0.0
// Calculate maximum redundancy with already selected results
for _, s := range selected {
selectedTokens := t.tokenizeSimple(s.Content)
redundancy = math.Max(redundancy, t.jaccard(tokenSets[i], selectedTokens))
}
// MMR score: balance relevance and diversity
mmr := lambda*relevance - (1.0-lambda)*redundancy
if mmr > bestScore {
bestScore = mmr
bestIdx = i
}
}
// Add best candidate to selected and remove from candidates
selected = append(selected, candidates[bestIdx])
candidates = append(candidates[:bestIdx], candidates[bestIdx+1:]...)
// Remove corresponding token set
tokenSets = append(tokenSets[:bestIdx], tokenSets[bestIdx+1:]...)
}
// Compute average redundancy among selected results
avgRed := 0.0
if len(selected) > 1 {
pairs := 0
for i := 0; i < len(selected); i++ {
for j := i + 1; j < len(selected); j++ {
si := t.tokenizeSimple(selected[i].Content)
sj := t.tokenizeSimple(selected[j].Content)
avgRed += t.jaccard(si, sj)
pairs++
}
}
if pairs > 0 {
avgRed /= float64(pairs)
}
}
logger.Debugf(ctx, "[Tool][GrepChunks] MMR completed: selected=%d, avg_redundancy=%.4f",
len(selected), avgRed)
return selected
}
// tokenizeSimple tokenizes text into a set of words (simple whitespace-based)
func (t *GrepChunksTool) tokenizeSimple(text string) map[string]struct{} {
text = strings.ToLower(text)
fields := strings.Fields(text)
set := make(map[string]struct{}, len(fields))
for _, f := range fields {
if len(f) > 1 {
set[f] = struct{}{}
}
}
return set
}
// jaccard calculates Jaccard similarity between two token sets
func (t *GrepChunksTool) jaccard(a, b map[string]struct{}) float64 {
if len(a) == 0 && len(b) == 0 {
return 0
}
// Calculate intersection
inter := 0
for k := range a {
if _, ok := b[k]; ok {
inter++
}
}
// Calculate union
union := len(a) + len(b) - inter
if union == 0 {
return 0
}
return float64(inter) / float64(union)
}
+498 -35
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"math"
"sort"
"strconv"
"strings"
@@ -225,6 +226,11 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
topK, vectorThreshold, keywordThreshold, kbTypeMap)
logger.Infof(ctx, "[Tool][KnowledgeSearch] Concurrent search completed: %d raw results", len(allResults))
// Normalize keyword search results to ensure fair comparison across knowledge bases
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Normalizing keyword search results...")
t.normalizeKeywordSearchResults(ctx, allResults)
logger.Infof(ctx, "[Tool][KnowledgeSearch] After keyword normalization: %d results", len(allResults))
// Filter by threshold first
filteredResults := t.filterByThreshold(allResults, vectorThreshold, keywordThreshold)
// Deduplicate before reranking to reduce processing overhead
@@ -271,6 +277,28 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
filteredResults = deduplicatedBeforeRerank
}
// Apply MMR (Maximal Marginal Relevance) to reduce redundancy and improve diversity
// Note: composite scoring is already applied inside rerankResults
if len(filteredResults) > 0 {
// Calculate k for MMR: use min(len(results), max(1, topK))
mmrK := len(filteredResults)
if topK > 0 && mmrK > topK {
mmrK = topK
}
if mmrK < 1 {
mmrK = 1
}
// Apply MMR with lambda=0.7 (balance between relevance and diversity)
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Applying MMR: k=%d, lambda=0.7, input=%d results", mmrK, len(filteredResults))
mmrResults := t.applyMMR(ctx, filteredResults, mmrK, 0.7)
if len(mmrResults) > 0 {
filteredResults = mmrResults
logger.Infof(ctx, "[Tool][KnowledgeSearch] MMR completed: %d results selected", len(filteredResults))
} else {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] MMR returned no results, using original results")
}
}
// Apply absolute minimum score filter to remove very low quality chunks
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Applying min_score filter (%.2f)...", minScore)
filteredResults = t.filterByMinScore(filteredResults, minScore)
@@ -302,7 +330,7 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
// Build output
logger.Infof(ctx, "[Tool][KnowledgeSearch] Formatting output with %d final results", len(deduplicatedResults))
result, err := t.formatOutput(ctx, deduplicatedResults, kbIDs, len(allResults), queries)
result, err := t.formatOutput(ctx, deduplicatedResults, kbIDs, queries)
if err != nil {
logger.Errorf(ctx, "[Tool][KnowledgeSearch] Failed to format output: %v", err)
return result, err
@@ -390,27 +418,39 @@ func (t *KnowledgeSearchTool) concurrentSearch(
}
// filterByThreshold filters results based on match type and threshold
// Special handling for history matches: uses lower threshold (reduced by 0.1, minimum 0.5)
func (t *KnowledgeSearchTool) filterByThreshold(
results []*searchResultWithMeta,
vectorThreshold, keywordThreshold float64,
) []*searchResultWithMeta {
filtered := make([]*searchResultWithMeta, 0)
for _, r := range results {
// Check if result meets threshold based on match type
if r.MatchType == types.MatchTypeEmbedding && r.Score >= vectorThreshold {
filtered = append(filtered, r)
} else if r.MatchType == types.MatchTypeKeywords && r.Score >= keywordThreshold {
filtered = append(filtered, r)
var threshold float64
// Special handling for history matches: use lower threshold
if r.MatchType == types.MatchTypeHistory {
// Use the lower of the two thresholds, then reduce by 0.1 (minimum 0.5)
th := vectorThreshold
if keywordThreshold < th {
th = keywordThreshold
}
threshold = math.Max(th-0.1, 0.5)
} else if r.MatchType == types.MatchTypeEmbedding {
threshold = vectorThreshold
} else if r.MatchType == types.MatchTypeKeywords {
threshold = keywordThreshold
} else {
// For other match types (graph, nearby chunk, etc.), use the lower threshold
minThreshold := vectorThreshold
if keywordThreshold < minThreshold {
minThreshold = keywordThreshold
}
if r.Score >= minThreshold {
filtered = append(filtered, r)
threshold = vectorThreshold
if keywordThreshold < threshold {
threshold = keywordThreshold
}
}
// Check if result meets threshold
if r.Score >= threshold {
filtered = append(filtered, r)
}
}
return filtered
}
@@ -444,12 +484,31 @@ func (t *KnowledgeSearchTool) rerankResults(
)
// Apply reranking only to non-FAQ results
switch {
case t.chatModel != nil:
rerankedNonFAQ, err = t.rerankWithLLM(ctx, query, nonFAQResults)
case t.rerankModel != nil:
// Try rerankModel first, fallback to chatModel if rerankModel fails or returns no results
if t.rerankModel != nil {
rerankedNonFAQ, err = t.rerankWithModel(ctx, query, nonFAQResults)
default:
// If rerankModel fails or returns no results, fallback to chatModel
if err != nil || len(rerankedNonFAQ) == 0 {
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Rerank model failed, falling back to chat model: %v", err)
} else {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Rerank model returned no results, falling back to chat model")
}
// Reset error to allow fallback
err = nil
// Try chatModel if available
if t.chatModel != nil {
rerankedNonFAQ, err = t.rerankWithLLM(ctx, query, nonFAQResults)
} else {
// No fallback available, use original results
rerankedNonFAQ = nonFAQResults
}
}
} else if t.chatModel != nil {
// No rerankModel, use chatModel directly
rerankedNonFAQ, err = t.rerankWithLLM(ctx, query, nonFAQResults)
} else {
// No reranking available, use original results
rerankedNonFAQ = nonFAQResults
}
@@ -457,6 +516,18 @@ func (t *KnowledgeSearchTool) rerankResults(
return nil, err
}
// Apply composite scoring to reranked results
// Get query intent from context if available (optional)
queryIntent := t.getQueryIntentFromContext(ctx)
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Applying composite scoring with query_intent=%s", queryIntent)
// Store base scores before composite scoring
for _, result := range rerankedNonFAQ {
baseScore := result.Score
// Apply composite score
result.Score = t.compositeScore(result, result.Score, baseScore, queryIntent)
}
// Combine FAQ results (with original order) and reranked non-FAQ results
combined := make([]*searchResultWithMeta, 0, len(results))
combined = append(combined, faqResults...)
@@ -537,8 +608,10 @@ func (t *KnowledgeSearchTool) rerankWithLLM(
// Build prompt with query and batch passages
var passagesBuilder strings.Builder
for i, result := range batch {
// Get enriched passage (content + image info)
enrichedContent := t.getEnrichedPassage(ctx, result.SearchResult)
// Truncate content if too long to save tokens
content := result.Content
content := enrichedContent
if len([]rune(content)) > maxContentLength {
runes := []rune(content)
content = string(runes[:maxContentLength]) + "..."
@@ -734,10 +807,10 @@ func (t *KnowledgeSearchTool) rerankWithModel(
query string,
results []*searchResultWithMeta,
) ([]*searchResultWithMeta, error) {
// Prepare passages for reranking
// Prepare passages for reranking (with enriched content including image info)
passages := make([]string, len(results))
for i, result := range results {
passages[i] = result.Content
passages[i] = t.getEnrichedPassage(ctx, result.SearchResult)
}
// Call rerank model
@@ -776,34 +849,94 @@ func (t *KnowledgeSearchTool) filterByMinScore(
}
// deduplicateResults removes duplicate chunks, keeping the highest score
// Uses multiple keys (ID, parent chunk ID, knowledge+index) and content signature for deduplication
func (t *KnowledgeSearchTool) deduplicateResults(results []*searchResultWithMeta) []*searchResultWithMeta {
seen := make(map[string]*searchResultWithMeta)
seen := make(map[string]bool)
contentSig := make(map[string]bool)
uniqueResults := make([]*searchResultWithMeta, 0)
for _, r := range results {
if existing, ok := seen[r.ID]; ok {
// Build multiple keys for deduplication
keys := []string{r.ID}
if r.ParentChunkID != "" {
keys = append(keys, "parent:"+r.ParentChunkID)
}
if r.KnowledgeID != "" {
keys = append(keys, fmt.Sprintf("kb:%s#%d", r.KnowledgeID, r.ChunkIndex))
}
// Check if any key is already seen
dup := false
for _, k := range keys {
if seen[k] {
dup = true
break
}
}
if dup {
continue
}
// Check content signature for near-duplicate content
sig := t.buildContentSignature(r.Content)
if sig != "" {
if contentSig[sig] {
continue
}
contentSig[sig] = true
}
// Mark all keys as seen
for _, k := range keys {
seen[k] = true
}
uniqueResults = append(uniqueResults, r)
}
// If we have duplicates by ID but different scores, keep the highest score
// This handles cases where the same chunk appears multiple times with different scores
seenByID := make(map[string]*searchResultWithMeta)
for _, r := range uniqueResults {
if existing, ok := seenByID[r.ID]; ok {
// Keep the result with higher score
if r.Score > existing.Score {
seen[r.ID] = r
seenByID[r.ID] = r
}
} else {
seen[r.ID] = r
seenByID[r.ID] = r
}
}
deduplicated := make([]*searchResultWithMeta, 0, len(seen))
for _, r := range seen {
// Convert back to slice
deduplicated := make([]*searchResultWithMeta, 0, len(seenByID))
for _, r := range seenByID {
deduplicated = append(deduplicated, r)
}
return deduplicated
}
// buildContentSignature creates a normalized signature for content to detect near-duplicates
func (t *KnowledgeSearchTool) buildContentSignature(content string) string {
c := strings.ToLower(strings.TrimSpace(content))
if c == "" {
return ""
}
// Normalize whitespace
c = strings.Join(strings.Fields(c), " ")
// Use first 128 characters as signature
if len(c) > 128 {
c = c[:128]
}
return c
}
// formatOutput formats the search results for display
func (t *KnowledgeSearchTool) formatOutput(
ctx context.Context,
results []*searchResultWithMeta,
kbsToSearch []string,
totalBeforeFilter int,
queries []string,
) (*types.ToolResult, error) {
if len(results) == 0 {
@@ -832,9 +965,6 @@ func (t *KnowledgeSearchTool) formatOutput(
// Build output header
output := "=== Search Results ===\n"
output += fmt.Sprintf("Found %d relevant results", len(results))
if totalBeforeFilter > len(results) {
output += fmt.Sprintf(" (filtered from %d)", totalBeforeFilter)
}
output += "\n\n"
// Count results by KB
@@ -1016,7 +1146,7 @@ func (t *KnowledgeSearchTool) formatOutput(
data := map[string]interface{}{
"knowledge_base_ids": kbsToSearch,
"results": formattedResults,
"count": len(results),
"count": len(formattedResults),
"kb_counts": kbCounts,
"display_type": "search_results",
}
@@ -1024,10 +1154,6 @@ func (t *KnowledgeSearchTool) formatOutput(
if len(queries) > 0 {
data["queries"] = queries
}
if totalBeforeFilter > len(results) {
data["total_before_filter"] = totalBeforeFilter
data["total_after_filter"] = len(results)
}
return &types.ToolResult{
Success: true,
@@ -1084,3 +1210,340 @@ func (t *KnowledgeSearchTool) findMissingChunkRanges(retrievedChunks map[int]boo
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
}
}
}
// getEnrichedPassage 合并Content和ImageInfo的文本内容
func (t *KnowledgeSearchTool) getEnrichedPassage(ctx context.Context, result *types.SearchResult) string {
if result.ImageInfo == "" {
return result.Content
}
// 解析ImageInfo
var imageInfos []types.ImageInfo
err := json.Unmarshal([]byte(result.ImageInfo), &imageInfos)
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to parse image info: %v", err)
return result.Content
}
if len(imageInfos) == 0 {
return result.Content
}
// 提取所有图片的描述和OCR文本
var imageTexts []string
for _, img := range imageInfos {
if img.Caption != "" {
imageTexts = append(imageTexts, fmt.Sprintf("图片描述: %s", img.Caption))
}
if img.OCRText != "" {
imageTexts = append(imageTexts, fmt.Sprintf("图片文本: %s", img.OCRText))
}
}
if len(imageTexts) == 0 {
return result.Content
}
// 组合内容和图片信息
combinedText := result.Content
if combinedText != "" {
combinedText += "\n\n"
}
combinedText += strings.Join(imageTexts, "\n")
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Enriched passage: content_len=%d, image_texts=%d",
len(result.Content), len(imageTexts))
return combinedText
}
// getQueryIntentFromContext attempts to extract query intent from context (optional)
func (t *KnowledgeSearchTool) getQueryIntentFromContext(ctx context.Context) string {
// Try to get query intent from context if available
// This is optional and may not always be present in agent tool context
// Return empty string if not available
return ""
}
// compositeScore calculates a composite score considering multiple factors
func (t *KnowledgeSearchTool) compositeScore(
result *searchResultWithMeta,
modelScore, baseScore float64,
queryIntent string,
) float64 {
// Source weight: web_search results get slightly lower weight
sourceWeight := 1.0
if strings.ToLower(result.KnowledgeSource) == "web_search" {
sourceWeight = 0.95
}
// Intent boost: adjust score based on query intent and chunk characteristics
intentBoost := 1.0
if queryIntent != "" {
switch queryIntent {
case "definition":
// Boost summary chunks for definition queries
if result.ChunkType == string(types.ChunkTypeSummary) {
intentBoost = 1.05
}
case "howto":
// Boost longer chunks for howto queries
if result.EndAt-result.StartAt > 300 {
intentBoost = 1.03
}
case "compare":
// No boost for compare queries
intentBoost = 1.0
}
}
// Position prior: slightly favor chunks earlier in the document
positionPrior := 1.0
if result.StartAt >= 0 && result.EndAt > result.StartAt {
// Calculate position ratio and apply small boost for earlier positions
positionRatio := 1.0 - float64(result.StartAt)/float64(result.EndAt+1)
positionPrior += t.clampFloat(positionRatio, -0.05, 0.05)
}
// Composite formula: weighted combination of model score, base score, and source weight
composite := 0.6*modelScore + 0.3*baseScore + 0.1*sourceWeight
composite *= intentBoost
composite *= positionPrior
// Clamp to [0, 1]
if composite < 0 {
composite = 0
}
if composite > 1 {
composite = 1
}
return composite
}
// clampFloat clamps a float value to the specified range
func (t *KnowledgeSearchTool) clampFloat(v, minV, maxV float64) float64 {
if v < minV {
return minV
}
if v > maxV {
return maxV
}
return v
}
// applyMMR applies Maximal Marginal Relevance algorithm to reduce redundancy
func (t *KnowledgeSearchTool) applyMMR(
ctx context.Context,
results []*searchResultWithMeta,
k int,
lambda float64,
) []*searchResultWithMeta {
if k <= 0 || len(results) == 0 {
return nil
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying MMR: lambda=%.2f, k=%d, candidates=%d",
lambda, k, len(results))
selected := make([]*searchResultWithMeta, 0, k)
candidates := make([]*searchResultWithMeta, len(results))
copy(candidates, results)
// Pre-compute token sets for all candidates
tokenSets := make([]map[string]struct{}, len(candidates))
for i, r := range candidates {
tokenSets[i] = t.tokenizeSimple(t.getEnrichedPassage(ctx, r.SearchResult))
}
// MMR selection loop
for len(selected) < k && len(candidates) > 0 {
bestIdx := 0
bestScore := -1.0
for i, r := range candidates {
relevance := r.Score
redundancy := 0.0
// Calculate maximum redundancy with already selected results
for _, s := range selected {
selectedTokens := t.tokenizeSimple(t.getEnrichedPassage(ctx, s.SearchResult))
redundancy = math.Max(redundancy, t.jaccard(tokenSets[i], selectedTokens))
}
// MMR score: balance relevance and diversity
mmr := lambda*relevance - (1.0-lambda)*redundancy
if mmr > bestScore {
bestScore = mmr
bestIdx = i
}
}
// Add best candidate to selected and remove from candidates
selected = append(selected, candidates[bestIdx])
candidates = append(candidates[:bestIdx], candidates[bestIdx+1:]...)
// Remove corresponding token set
tokenSets = append(tokenSets[:bestIdx], tokenSets[bestIdx+1:]...)
}
// Compute average redundancy among selected results
avgRed := 0.0
if len(selected) > 1 {
pairs := 0
for i := 0; i < len(selected); i++ {
for j := i + 1; j < len(selected); j++ {
si := t.tokenizeSimple(t.getEnrichedPassage(ctx, selected[i].SearchResult))
sj := t.tokenizeSimple(t.getEnrichedPassage(ctx, selected[j].SearchResult))
avgRed += t.jaccard(si, sj)
pairs++
}
}
if pairs > 0 {
avgRed /= float64(pairs)
}
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] MMR completed: selected=%d, avg_redundancy=%.4f",
len(selected), avgRed)
return selected
}
// tokenizeSimple tokenizes text into a set of words (simple whitespace-based)
func (t *KnowledgeSearchTool) tokenizeSimple(text string) map[string]struct{} {
text = strings.ToLower(text)
fields := strings.Fields(text)
set := make(map[string]struct{}, len(fields))
for _, f := range fields {
if len(f) > 1 {
set[f] = struct{}{}
}
}
return set
}
// jaccard calculates Jaccard similarity between two token sets
func (t *KnowledgeSearchTool) jaccard(a, b map[string]struct{}) float64 {
if len(a) == 0 && len(b) == 0 {
return 0
}
// Calculate intersection
inter := 0
for k := range a {
if _, ok := b[k]; ok {
inter++
}
}
// Calculate union
union := len(a) + len(b) - inter
if union == 0 {
return 0
}
return float64(inter) / float64(union)
}
+9 -1
View File
@@ -69,6 +69,14 @@ Each thought can build on, question, or revise previous insights as understandin
* Changes in approach
* Hypothesis generation
* Hypothesis verification
**CRITICAL - User-Friendly Thinking**: Write your thoughts in natural, user-friendly language. NEVER mention tool names (like "grep_chunks", "knowledge_search", "web_search", etc.) in your thinking process. Instead, describe your actions in plain language:
- ❌ BAD: "I'll use grep_chunks to search for keywords, then knowledge_search for semantic understanding"
- ✅ GOOD: "I'll start by searching for key terms in the knowledge base, then explore related concepts"
- ❌ BAD: "After grep_chunks returns results, I'll use knowledge_search"
- ✅ GOOD: "After finding relevant documents, I'll search for semantically related content"
Write thinking as if explaining your reasoning to a user, not documenting technical steps. Focus on WHAT you're trying to find and WHY, not HOW (which tools you'll use).
- **next_thought_needed**: True if you need more thinking, even if at what seemed like the end
- **thought_number**: Current number in sequence (can go beyond initial total if needed)
@@ -107,7 +115,7 @@ func (t *SequentialThinkingTool) Parameters() map[string]interface{} {
"properties": map[string]interface{}{
"thought": map[string]interface{}{
"type": "string",
"description": "Your current thinking step",
"description": `Your current thinking step. Write in natural, user-friendly language. NEVER mention tool names (like "grep_chunks", "knowledge_search", "web_search", etc.). Instead, describe actions in plain language (e.g., "I'll search for key terms" instead of "I'll use grep_chunks"). Focus on WHAT you're trying to find and WHY, not HOW (which tools you'll use).`,
},
"nextThoughtNeeded": map[string]interface{}{
"type": "boolean",
+43 -36
View File
@@ -24,8 +24,13 @@ type PlanStep struct {
// NewTodoWriteTool creates a new todo_write tool instance
func NewTodoWriteTool() *TodoWriteTool {
description := `Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
It also helps the user understand the progress of the task and overall progress of their requests.
description := `Use this tool to create and manage a structured task list for retrieval and research tasks. This helps you track progress, organize complex retrieval operations, and demonstrate thoroughness to the user.
**CRITICAL - Focus on Retrieval Tasks Only**:
- This tool is for tracking RETRIEVAL and RESEARCH tasks (e.g., searching knowledge bases, retrieving documents, gathering information)
- DO NOT include summary or synthesis tasks in todo_write - those are handled by the thinking tool
- Examples of appropriate tasks: "Search for X in knowledge base", "Retrieve information about Y", "Compare A and B"
- Examples of tasks to EXCLUDE: "Summarize findings", "Generate final answer", "Synthesize results" - these are for thinking tool
## When to Use This Tool
Use this tool proactively in these scenarios:
@@ -50,38 +55,36 @@ NOTE that you should not use this tool if there is only one trivial task to do.
## Examples of When to Use the Todo List
<example>
User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
Assistant: I'll help implement these features for your e-commerce site. Let me first think through the architecture and dependencies between these features to create an optimal implementation plan.
*Uses think tool to analyze the e-commerce architecture, identify dependencies between features (user auth needed for cart, catalog needed for checkout), consider database design, security requirements, and implementation order*
Assistant: After analyzing the system architecture and feature dependencies, let me create a strategic todo list that accounts for the interconnected nature of these features.
*Creates a todo list breaking down each feature into specific tasks based on the project architecture and dependencies*
Assistant: Let's start with user registration since it's foundational for the shopping cart and checkout features. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.
User: Compare WeKnora with other RAG frameworks like LangChain and LlamaIndex.
Assistant: I'll help you compare WeKnora with other RAG frameworks. Let me create a retrieval plan to gather information about each framework.
*Creates a todo list with retrieval tasks: 1) Search knowledge base for WeKnora features and architecture, 2) Use web_search to find LangChain documentation and features, 3) Use web_search to find LlamaIndex documentation and features, 4) Retrieve detailed comparison points for each framework*
*Note: Summary and synthesis will be handled by thinking tool after all retrieval tasks are completed*
Assistant: Let me start by searching the knowledge base for detailed WeKnora information.
<reasoning>
The assistant used both think and todo_write tools because:
1. First used think tool to analyze the complex e-commerce architecture and feature dependencies
2. Considered the interconnected nature of features (user auth → cart → checkout)
3. Analyzed security requirements, database design, and optimal implementation order
4. Then created a strategic todo list that accounts for these dependencies
5. This approach ensures features are implemented in the correct order with proper foundations
The assistant used todo_write tool correctly because:
1. The task requires multiple retrieval operations (searching KB for WeKnora, web search for LangChain and LlamaIndex)
2. Each retrieval task is specific and actionable
3. The todo list focuses on WHAT to retrieve, not HOW to summarize
4. Summary and synthesis will be handled separately by thinking tool after all retrieval is complete
5. This separation ensures clear task boundaries and avoids duplication
</reasoning>
</example>
<example>
User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
*Reviews component structure, render patterns, state management, and data fetching*
Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
*Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*
Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>
User: I need to research the latest developments in vector databases for RAG applications.
Assistant: I'll help you research vector databases for RAG. Let me create a retrieval plan to gather comprehensive information.
*Creates todo list with retrieval tasks: 1) Search knowledge base for vector database information, 2) Use web_search to find latest vector database technologies, 3) Retrieve information about performance comparisons, 4) Gather information about integration approaches*
*Note: After completing all retrieval tasks, thinking tool will synthesize the findings into a comprehensive answer*
Assistant: Let me start by searching the knowledge base for vector database information.
<reasoning>
The assistant used the todo list because:
1. First, the assistant examined the codebase to identify specific performance issues
2. Based on this analysis, it identified multiple optimization opportunities
3. Performance optimization is a non-trivial task requiring multiple steps
4. The todo list helps methodically track improvements across different components
5. This systematic approach ensures all performance bottlenecks are addressed
The assistant used todo_write tool correctly because:
1. The research task requires multiple retrieval operations (KB search, web search for latest info)
2. Each task focuses on retrieving specific information
3. The todo list tracks retrieval progress, not synthesis
4. Summary and analysis will be handled by thinking tool after retrieval is complete
5. This approach separates retrieval (todo_write) from synthesis (thinking tool)
</reasoning>
</example>
@@ -134,11 +137,14 @@ The assistant did not use the todo list because this is an informational request
- You couldn't find necessary files or dependencies
4. **Task Breakdown**:
- Create specific, actionable items
- Break complex tasks into smaller, manageable steps
- Use clear, descriptive task names
- Create specific, actionable RETRIEVAL tasks
- Break complex retrieval needs into smaller, manageable steps
- Use clear, descriptive task names focused on what to retrieve or research
- **DO NOT include summary/synthesis tasks** - those are handled separately by the thinking tool
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.`
**Important**: After completing all retrieval tasks in todo_write, use the thinking tool to synthesize findings and generate the final answer. The todo_write tool tracks WHAT to retrieve, while thinking tool handles HOW to synthesize and present the information.
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all retrieval requirements successfully.`
return &TodoWriteTool{
BaseTool: NewBaseTool("todo_write", description),
@@ -264,12 +270,13 @@ func generatePlanOutput(task string, steps []PlanStep) string {
output += fmt.Sprintf("**任务**: %s\n\n", task)
if len(steps) == 0 {
output += "注意:未提供具体步骤。建议创建3-7个结构化步骤以系统化研究。\n\n"
output += "建议的通用流程:\n"
output += "1. 使用 knowledge_search 进行初步信息收集\n"
output += "2. 使用 list_knowledge_chunks 获取关键信息详情\n"
output += "3. 使用 list_knowledge_chunks 扩展上下文理解\n"
output += "4. 使用 think 工具评估结果并综合答案\n"
output += "注意:未提供具体步骤。建议创建3-7个检索任务以系统化研究。\n\n"
output += "建议的检索流程(专注于检索任务,不包含总结):\n"
output += "1. 使用 grep_chunks 搜索关键词定位相关文档\n"
output += "2. 使用 knowledge_search 进行语义搜索获取相关内容\n"
output += "3. 使用 list_knowledge_chunks 获取关键文档的完整内容\n"
output += "4. 使用 web_search 获取补充信息(如需要)\n"
output += "\n注意:总结和综合由 thinking 工具处理,不要在此处添加总结任务。\n"
return output
}