2025-11-05 15:18:44 +00:00
package tools
import (
"context"
"encoding/json"
"fmt"
2025-11-25 05:28:21 +00:00
"math"
2025-11-05 15:18:44 +00:00
"sort"
2025-11-12 17:22:08 +00:00
"strconv"
"strings"
2025-11-05 15:18:44 +00:00
"sync"
2025-11-19 11:27:25 +00:00
"github.com/Tencent/WeKnora/internal/config"
2025-11-05 15:18:44 +00:00
"github.com/Tencent/WeKnora/internal/logger"
2025-11-12 17:22:08 +00:00
"github.com/Tencent/WeKnora/internal/models/chat"
2025-11-05 15:18:44 +00:00
"github.com/Tencent/WeKnora/internal/models/rerank"
2025-12-01 10:27:12 +00:00
"github.com/Tencent/WeKnora/internal/searchutil"
2025-11-05 15:18:44 +00:00
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
2025-12-23 08:56:30 +00:00
var knowledgeSearchTool = BaseTool {
name : ToolKnowledgeSearch ,
description : ` Semantic / vector search tool for retrieving knowledge by meaning , intent , and conceptual relevance .
2025-11-05 15:18:44 +00:00
2025-11-27 06:19:57 +00:00
This tool uses embeddings to understand the user ' s query and find semantically similar content across knowledge base chunks .
2025-11-05 15:18:44 +00:00
2025-11-27 06:19:57 +00:00
# # Purpose
Designed for high - level understanding tasks , such as :
- conceptual explanations
- topic overviews
- reasoning - based information needs
- contextual or intent - driven retrieval
- queries that cannot be answered with literal keyword matching
2025-11-05 15:18:44 +00:00
2025-11-27 06:19:57 +00:00
The tool searches by MEANING rather than exact text . It identifies chunks that are conceptually relevant even when the wording differs .
2025-11-05 15:18:44 +00:00
2025-11-27 06:19:57 +00:00
# # What the Tool Does NOT Do
- Does NOT perform exact keyword matching
- Does NOT search for specific named entities
- Should NOT be used for literal lookup tasks
- Should NOT receive long raw text or user messages as queries
- Should NOT be used to locate specific strings or error codes
2025-11-05 15:18:44 +00:00
2025-11-27 06:19:57 +00:00
For literal / keyword / entity search , another tool should be used .
# # Required Input Behavior
"queries" must contain * * 1 – 5 short , well - formed semantic questions or conceptual statements * * that clearly express the meaning the model is trying to retrieve .
Each query should represent a * * concept , idea , topic , explanation , or intent * * , such as :
- abstract topics
- definitions
- mechanisms
- best practices
- comparisons
- how / why questions
Avoid :
- keyword lists
- raw text from user messages
- full paragraphs
- unprocessed input
# # Examples of valid query shapes ( not content ) :
- "What is the main idea of..."
- "How does X work in general?"
- "Explain the purpose of..."
- "What are the key principles behind..."
- "Overview of ..."
2025-11-05 15:18:44 +00:00
2025-11-23 09:32:50 +00:00
# # Parameters
2025-11-27 06:19:57 +00:00
- queries ( required ) : 1 – 5 semantic questions or conceptual statements .
These should reflect the meaning or topic you want embeddings to capture .
- knowledge_base_ids ( optional ) : limit the search scope .
2025-11-05 15:18:44 +00:00
2025-11-23 09:32:50 +00:00
# # Output
2025-11-27 06:19:57 +00:00
Returns chunks ranked by semantic similarity , reranked when applicable .
2026-07-16 13:46:52 +00:00
Each chunk has a short cN source ID and belongs to a dN document ID . Results represent conceptual relevance , not literal keyword overlap . Use dN for document - level follow - up tool calls . ` ,
2025-12-23 08:56:30 +00:00
schema : json . RawMessage ( ` {
"type" : "object" ,
"properties" : {
"queries" : {
"type" : "array" ,
"description" : "REQUIRED: 1-5 semantic questions/topics (e.g., ['What is RAG?', 'RAG benefits'])" ,
"items" : {
"type" : "string"
} ,
"minItems" : 1 ,
"maxItems" : 5
} ,
"knowledge_base_ids" : {
"type" : "array" ,
2026-07-16 13:23:20 +00:00
"description" : "Optional: bound knowledge-base IDs (the short bN values shown in runtime context)" ,
2025-12-23 08:56:30 +00:00
"items" : {
"type" : "string"
} ,
"minItems" : 0 ,
"maxItems" : 10
}
} ,
"required" : [ "queries" ]
} ` ) ,
}
// KnowledgeSearchInput defines the input parameters for knowledge search tool
type KnowledgeSearchInput struct {
Queries [ ] string ` json:"queries" `
KnowledgeBaseIDs [ ] string ` json:"knowledge_base_ids,omitempty" `
}
// searchResultWithMeta wraps search result with metadata about which query matched it
type searchResultWithMeta struct {
* types . SearchResult
SourceQuery string
QueryType string // "vector" or "keyword"
KnowledgeBaseID string // ID of the knowledge base this result came from
KnowledgeBaseType string // Type of the knowledge base (document, faq, etc.)
}
2026-04-21 11:19:57 +00:00
// KnowledgeSearchTool searches knowledge bases with flexible query modes.
// seenChunks lets repeated calls in the same session surface previously-
// returned chunks in a compact form (mirroring wiki_search's de-duping UX)
// so the LLM doesn't burn tokens re-reading identical content.
2025-12-23 08:56:30 +00:00
type KnowledgeSearchTool struct {
BaseTool
knowledgeBaseService interfaces . KnowledgeBaseService
knowledgeService interfaces . KnowledgeService
chunkService interfaces . ChunkService
searchTargets types . SearchTargets // Pre-computed unified search targets
rerankModel rerank . Reranker
chatModel chat . Chat // Optional chat model for LLM-based reranking
config * config . Config // Global config for fallback values
2026-04-21 11:19:57 +00:00
seenMu sync . Mutex
seenChunks map [ string ] bool
2025-12-23 08:56:30 +00:00
}
2025-11-05 15:18:44 +00:00
2025-12-23 08:56:30 +00:00
// NewKnowledgeSearchTool creates a new knowledge search tool
func NewKnowledgeSearchTool (
knowledgeBaseService interfaces . KnowledgeBaseService ,
knowledgeService interfaces . KnowledgeService ,
chunkService interfaces . ChunkService ,
searchTargets types . SearchTargets ,
rerankModel rerank . Reranker ,
chatModel chat . Chat ,
cfg * config . Config ,
) * KnowledgeSearchTool {
2025-11-05 15:18:44 +00:00
return & KnowledgeSearchTool {
2025-12-23 08:56:30 +00:00
BaseTool : knowledgeSearchTool ,
2025-11-19 11:27:25 +00:00
knowledgeBaseService : knowledgeBaseService ,
2025-12-19 14:17:56 +00:00
knowledgeService : knowledgeService ,
2025-11-19 11:27:25 +00:00
chunkService : chunkService ,
2025-12-19 14:17:56 +00:00
searchTargets : searchTargets ,
2025-11-19 11:27:25 +00:00
rerankModel : rerankModel ,
chatModel : chatModel ,
config : cfg ,
2026-04-21 11:19:57 +00:00
seenChunks : make ( map [ string ] bool ) ,
2025-11-05 15:18:44 +00:00
}
}
2025-11-19 11:27:25 +00:00
// Execute executes the knowledge search tool
2025-12-23 08:56:30 +00:00
func ( t * KnowledgeSearchTool ) Execute ( ctx context . Context , args json . RawMessage ) ( * types . ToolResult , error ) {
2025-11-05 15:18:44 +00:00
logger . Infof ( ctx , "[Tool][KnowledgeSearch] Execute started" )
2025-12-23 08:56:30 +00:00
// Parse args from json.RawMessage
var input KnowledgeSearchInput
if err := json . Unmarshal ( args , & input ) ; err != nil {
logger . Errorf ( ctx , "[Tool][KnowledgeSearch] Failed to parse args: %v" , err )
return & types . ToolResult {
Success : false ,
Error : fmt . Sprintf ( "Failed to parse args: %v" , err ) ,
} , err
}
2025-11-05 15:18:44 +00:00
// Log input arguments
2025-12-23 08:56:30 +00:00
argsJSON , _ := json . MarshalIndent ( input , "" , " " )
2025-11-05 15:18:44 +00:00
logger . Debugf ( ctx , "[Tool][KnowledgeSearch] Input args:\n%s" , string ( argsJSON ) )
2025-12-19 14:17:56 +00:00
// Determine which KBs to search - user can optionally filter to specific KBs
var userSpecifiedKBs [ ] string
2025-12-23 08:56:30 +00:00
if len ( input . KnowledgeBaseIDs ) > 0 {
userSpecifiedKBs = input . KnowledgeBaseIDs
2026-07-26 16:59:38 +00:00
if err := validateKnowledgeBaseIDsInSearchTargets ( t . searchTargets , userSpecifiedKBs ) ; err != nil {
return & types . ToolResult { Success : false , Error : err . Error ( ) } , err
}
2025-12-19 14:17:56 +00:00
logger . Infof ( ctx , "[Tool][KnowledgeSearch] User specified %d knowledge bases: %v" , len ( userSpecifiedKBs ) , userSpecifiedKBs )
}
// Use pre-computed search targets, optionally filtered by user-specified KBs
searchTargets := t . searchTargets
if len ( userSpecifiedKBs ) > 0 {
// Filter search targets to only include user-specified KBs
userKBSet := make ( map [ string ] bool )
for _ , kbID := range userSpecifiedKBs {
userKBSet [ kbID ] = true
}
var filteredTargets types . SearchTargets
for _ , target := range t . searchTargets {
2026-07-26 16:59:38 +00:00
if target == nil {
continue
}
2025-12-19 14:17:56 +00:00
if userKBSet [ target . KnowledgeBaseID ] {
filteredTargets = append ( filteredTargets , target )
}
2025-11-05 15:18:44 +00:00
}
2025-12-19 14:17:56 +00:00
searchTargets = filteredTargets
2025-11-05 15:18:44 +00:00
}
2025-12-19 14:17:56 +00:00
// Validate search targets
if len ( searchTargets ) == 0 {
logger . Errorf ( ctx , "[Tool][KnowledgeSearch] No search targets available" )
return & types . ToolResult {
Success : false ,
Error : "no knowledge bases specified and no search targets configured" ,
} , fmt . Errorf ( "no search targets available" )
}
kbIDs := searchTargets . GetAllKnowledgeBaseIDs ( )
logger . Infof ( ctx , "[Tool][KnowledgeSearch] Using %d search targets across %d KBs" , len ( searchTargets ) , len ( kbIDs ) )
2025-11-19 11:27:25 +00:00
// Parse query parameter
2025-12-23 08:56:30 +00:00
queries := input . Queries
2025-11-05 15:18:44 +00:00
2025-11-19 11:27:25 +00:00
// Validate: query must be provided
if len ( queries ) == 0 {
logger . Errorf ( ctx , "[Tool][KnowledgeSearch] No queries provided" )
return & types . ToolResult {
Success : false ,
Error : "queries parameter is required" ,
} , fmt . Errorf ( "no queries provided" )
2025-11-05 15:18:44 +00:00
}
2025-11-19 11:27:25 +00:00
logger . Infof ( ctx , "[Tool][KnowledgeSearch] Queries: %v" , queries )
2025-11-05 15:18:44 +00:00
refactor(api): drop deprecated tenant ConversationConfig field and KV write path
The Tenant.ConversationConfig field was marked deprecated when
CustomAgent (builtin-quick-answer) replaced the per-tenant defaults
path, but the JSONB column, GET/PUT KV handlers, write helpers and
read fall-throughs all stayed wired. This had two concrete failure
modes:
- Input-field.vue silently PUT-ed per-user model picks back into
/tenants/kv/conversation-config, which requires Admin+ — Viewers
and Contributors got a 403 every time they switched chat models.
- The same write also overwrote the tenant-shared default for every
other user, turning a per-user UX into a per-tenant footgun.
Remove the field, the struct, the validate helper, the PUT case and
the two dead Summary helpers in session/helpers.go. KnowledgeSearch
loses its tenant-conversation fallback (one chunk-tool reader); the
global config + hardcoded defaults still cover it. session_agent_qa
already required agents to declare their own rerank_model_id, so no
behaviour change there.
Frontend follows:
- Input-field.vue: per-user 'last selected chat model' moves to
localStorage, no API call.
- AgentEditorModal: defaults for builtin-quick-answer creation now
come from prompt-templates (system/context/rewrite/fallback) and
retrieval-config (top_k / threshold), the two endpoints that
actually own those settings now.
- AgentSettings.vue: orphan settings page with no router/import
referencing it; deleted.
- api/system: getConversationConfig / updateConversationConfig and
the ConversationConfig interface go away.
Net: 137 insertions, 2761 deletions.
2026-05-15 04:14:53 +00:00
// Search parameters: fall back to global config, then to hardcoded defaults.
// We used to read tenant.ConversationConfig here as the first source of
// truth, but that field was removed when the chat pipeline moved to
// CustomAgent — tenant-level KV settings now live on the agent itself.
2025-11-19 11:27:25 +00:00
var topK int
var vectorThreshold , keywordThreshold , minScore float64
// Fallback to global config if not set
if topK == 0 && t . config != nil {
topK = t . config . Conversation . EmbeddingTopK
2025-11-05 15:18:44 +00:00
}
2025-11-19 11:27:25 +00:00
if vectorThreshold == 0 && t . config != nil {
vectorThreshold = t . config . Conversation . VectorThreshold
2025-11-05 15:18:44 +00:00
}
2025-11-19 11:27:25 +00:00
if keywordThreshold == 0 && t . config != nil {
keywordThreshold = t . config . Conversation . KeywordThreshold
2025-11-05 15:18:44 +00:00
}
2025-11-19 11:27:25 +00:00
// Final fallback to hardcoded defaults if config is not available
if topK == 0 {
topK = 5
2025-11-05 15:18:44 +00:00
}
2025-11-19 11:27:25 +00:00
if vectorThreshold == 0 {
vectorThreshold = 0.6
2025-11-05 15:18:44 +00:00
}
2025-11-19 11:27:25 +00:00
if keywordThreshold == 0 {
keywordThreshold = 0.5
2025-11-05 15:18:44 +00:00
}
2025-11-19 11:27:25 +00:00
if minScore == 0 {
minScore = 0.3
2025-11-05 15:18:44 +00:00
}
2025-11-28 08:17:52 +00:00
logger . Infof (
ctx ,
"[Tool][KnowledgeSearch] Search params: top_k=%d, vector_threshold=%.2f, keyword_threshold=%.2f, min_score=%.2f" ,
topK ,
vectorThreshold ,
keywordThreshold ,
minScore ,
)
2025-11-05 15:18:44 +00:00
2025-12-19 14:17:56 +00:00
// Execute concurrent search using pre-computed search targets
logger . Infof ( ctx , "[Tool][KnowledgeSearch] Starting concurrent search with %d search targets" ,
len ( searchTargets ) )
2025-11-17 07:33:43 +00:00
kbTypeMap := t . getKnowledgeBaseTypes ( ctx , kbIDs )
2025-12-19 14:17:56 +00:00
allResults := t . concurrentSearchByTargets ( ctx , queries , searchTargets ,
2025-11-17 07:33:43 +00:00
topK , vectorThreshold , keywordThreshold , kbTypeMap )
2025-11-05 15:18:44 +00:00
logger . Infof ( ctx , "[Tool][KnowledgeSearch] Concurrent search completed: %d raw results" , len ( allResults ) )
2025-12-03 09:45:21 +00:00
// Note: HybridSearch now uses RRF (Reciprocal Rank Fusion) which produces normalized scores
// RRF scores are in range [0, ~0.033] (max when rank=1 on both sides: 2/(60+1))
// Threshold filtering is already done inside HybridSearch before RRF, so we skip it here
2025-11-25 05:28:21 +00:00
2025-11-19 11:27:25 +00:00
// Deduplicate before reranking to reduce processing overhead
2025-12-03 09:45:21 +00:00
deduplicatedBeforeRerank := t . deduplicateResults ( allResults )
2025-11-19 11:27:25 +00:00
2025-11-05 15:18:44 +00:00
// Apply ReRank if model is configured
2026-04-28 12:15:52 +00:00
// Prefer rerankModel; fall back to chatModel (LLM-based reranking) if unavailable
2025-11-19 11:27:25 +00:00
// Use first query for reranking (or combine all queries if needed)
rerankQuery := ""
if len ( queries ) > 0 {
rerankQuery = queries [ 0 ]
if len ( queries ) > 1 {
// Combine multiple queries for reranking
rerankQuery = strings . Join ( queries , " " )
2025-11-12 17:22:08 +00:00
}
2025-11-19 11:27:25 +00:00
}
2025-11-12 17:22:08 +00:00
2025-12-03 09:45:21 +00:00
// Variable to hold results through reranking and MMR stages
var filteredResults [ ] * searchResultWithMeta
2026-04-28 12:15:52 +00:00
if ( t . rerankModel != nil || t . chatModel != nil ) && len ( deduplicatedBeforeRerank ) > 0 && rerankQuery != "" {
2026-06-15 16:49:34 +00:00
logger . Infof ( ctx , "[Tool][KnowledgeSearch] Applying rerank, input: %d results, threshold: %.2f, queries: %v" ,
len ( deduplicatedBeforeRerank ) , t . rerankThreshold ( ) , queries )
2025-11-19 11:27:25 +00:00
rerankedResults , err := t . rerankResults ( ctx , rerankQuery , deduplicatedBeforeRerank )
if err != nil {
logger . Warnf ( ctx , "[Tool][KnowledgeSearch] Rerank failed, using original results: %v" , err )
filteredResults = deduplicatedBeforeRerank
} else {
filteredResults = rerankedResults
logger . Infof ( ctx , "[Tool][KnowledgeSearch] Rerank completed successfully: %d results" ,
len ( filteredResults ) )
2025-11-05 15:18:44 +00:00
}
2025-11-19 11:27:25 +00:00
} else {
2026-04-28 12:15:52 +00:00
// No reranking model available, use deduplicated results
2025-11-19 11:27:25 +00:00
filteredResults = deduplicatedBeforeRerank
2025-11-05 15:18:44 +00:00
}
2025-11-25 05:28:21 +00:00
// 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)
2025-11-28 08:17:52 +00:00
logger . Debugf (
ctx ,
"[Tool][KnowledgeSearch] Applying MMR: k=%d, lambda=0.7, input=%d results" ,
mmrK ,
len ( filteredResults ) ,
)
2025-11-25 05:28:21 +00:00
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" )
}
}
2025-12-03 09:45:21 +00:00
// Note: minScore filter is skipped because HybridSearch now uses RRF scores
// RRF scores are in range [0, ~0.033], not [0, 1], so old thresholds don't apply
// Threshold filtering is already done inside HybridSearch before RRF fusion
2025-11-05 15:18:44 +00:00
2025-11-19 11:27:25 +00:00
// Final deduplication after rerank (in case rerank changed scores/order but duplicates remain)
logger . Debugf ( ctx , "[Tool][KnowledgeSearch] Final deduplication after rerank..." )
2025-11-05 15:18:44 +00:00
deduplicatedResults := t . deduplicateResults ( filteredResults )
2025-11-19 11:27:25 +00:00
logger . Infof ( ctx , "[Tool][KnowledgeSearch] After final deduplication: %d results (from %d)" ,
2025-11-05 15:18:44 +00:00
len ( deduplicatedResults ) , len ( filteredResults ) )
// Sort results by score (descending)
sort . Slice ( deduplicatedResults , func ( i , j int ) bool {
if deduplicatedResults [ i ] . Score != deduplicatedResults [ j ] . Score {
return deduplicatedResults [ i ] . Score > deduplicatedResults [ j ] . Score
}
2025-11-19 11:27:25 +00:00
// If scores are equal, sort by knowledge ID for consistency
2025-11-05 15:18:44 +00:00
return deduplicatedResults [ i ] . KnowledgeID < deduplicatedResults [ j ] . KnowledgeID
} )
2026-06-15 16:49:34 +00:00
// Log all ranked results (including lower ranks for rerank debugging)
2025-11-05 15:18:44 +00:00
if len ( deduplicatedResults ) > 0 {
2026-06-15 16:49:34 +00:00
total := len ( deduplicatedResults )
for i , r := range deduplicatedResults {
logger . Infof ( ctx , "[Tool][KnowledgeSearch][Rank %d/%d] score=%.3f, type=%s, kb=%s, chunk_id=%s" ,
i + 1 , total , r . Score , r . QueryType , r . KnowledgeID , r . ID )
2025-11-05 15:18:44 +00:00
}
}
2026-04-16 15:25:25 +00:00
// Enrich image info for search results (lazy-loaded from child image chunks)
if t . chunkService != nil && len ( deduplicatedResults ) > 0 {
byTenant := make ( map [ uint64 ] [ ] * types . SearchResult )
for _ , r := range deduplicatedResults {
tid := t . searchTargets . GetTenantIDForKB ( r . KnowledgeBaseID )
if tid == 0 {
continue
}
byTenant [ tid ] = append ( byTenant [ tid ] , r . SearchResult )
}
for tid , batch := range byTenant {
searchutil . EnrichSearchResultsImageInfo ( ctx , t . chunkService . GetRepository ( ) , tid , batch )
}
}
2025-11-05 15:18:44 +00:00
// Build output
logger . Infof ( ctx , "[Tool][KnowledgeSearch] Formatting output with %d final results" , len ( deduplicatedResults ) )
2025-11-25 05:28:21 +00:00
result , err := t . formatOutput ( ctx , deduplicatedResults , kbIDs , queries )
2025-11-05 15:18:44 +00:00
if err != nil {
logger . Errorf ( ctx , "[Tool][KnowledgeSearch] Failed to format output: %v" , err )
return result , err
}
2025-11-23 09:32:50 +00:00
logger . Infof ( ctx , "[Tool][KnowledgeSearch] Output: %s" , result . Output )
2025-11-05 15:18:44 +00:00
return result , nil
}
2025-11-17 07:33:43 +00:00
// getKnowledgeBaseTypes fetches knowledge base types for the given IDs
func ( t * KnowledgeSearchTool ) getKnowledgeBaseTypes ( ctx context . Context , kbIDs [ ] string ) map [ string ] string {
kbTypeMap := make ( map [ string ] string , len ( kbIDs ) )
for _ , kbID := range kbIDs {
if kbID == "" {
continue
}
if _ , exists := kbTypeMap [ kbID ] ; exists {
continue
}
2025-11-19 11:27:25 +00:00
kb , err := t . knowledgeBaseService . GetKnowledgeBaseByID ( ctx , kbID )
2025-11-17 07:33:43 +00:00
if err != nil {
logger . Warnf ( ctx , "[Tool][KnowledgeSearch] Failed to fetch knowledge base %s info: %v" , kbID , err )
continue
}
kbTypeMap [ kbID ] = kb . Type
}
return kbTypeMap
}
2026-03-13 12:33:47 +00:00
// concurrentSearchByTargets executes hybrid search using pre-computed search targets.
2026-03-13 12:54:25 +00:00
// Targets sharing the same underlying embedding model (identified by model name + endpoint)
// are grouped so the query embedding is computed once per (model, query) pair, and all
// full-KB targets in a group are combined into a single retrieval call.
2025-12-19 14:17:56 +00:00
func ( t * KnowledgeSearchTool ) concurrentSearchByTargets (
2025-11-05 15:18:44 +00:00
ctx context . Context ,
queries [ ] string ,
2025-12-19 14:17:56 +00:00
searchTargets types . SearchTargets ,
2025-11-05 15:18:44 +00:00
topK int ,
vectorThreshold , keywordThreshold float64 ,
2025-11-17 07:33:43 +00:00
kbTypeMap map [ string ] string ,
2025-11-05 15:18:44 +00:00
) [ ] * searchResultWithMeta {
2026-03-13 12:33:47 +00:00
// Batch-fetch KB records for embedding model grouping
kbIDs := searchTargets . GetAllKnowledgeBaseIDs ( )
2026-03-13 12:54:25 +00:00
var kbList [ ] * types . KnowledgeBase
2026-03-13 12:33:47 +00:00
if kbs , err := t . knowledgeBaseService . GetKnowledgeBasesByIDsOnly ( ctx , kbIDs ) ; err == nil {
2026-03-13 12:54:25 +00:00
kbList = kbs
2026-03-13 12:33:47 +00:00
}
2026-04-22 13:17:12 +00:00
// Filter out non-searchable KBs (wiki-only / graph-only). knowledge_search
// can only serve KBs with vector or keyword indexing; feeding a wiki-only
// KB into HybridSearch causes spurious "model ID cannot be empty" errors
// because such KBs have no EmbeddingModelID configured. Such scopes
// should be queried via wiki_search / graph tools instead.
//
// KBs that we couldn't fetch from the repo (not in kbList) are kept so
// the downstream HybridSearch path can still surface the real error.
searchableKBs := make ( map [ string ] bool , len ( kbList ) )
knownKBs := make ( map [ string ] bool , len ( kbList ) )
for _ , kb := range kbList {
if kb == nil {
continue
}
knownKBs [ kb . ID ] = true
if kb . IsVectorEnabled ( ) || kb . IsKeywordEnabled ( ) {
searchableKBs [ kb . ID ] = true
}
}
filteredTargets := make ( types . SearchTargets , 0 , len ( searchTargets ) )
for _ , st := range searchTargets {
2026-07-26 16:59:38 +00:00
if st == nil || st . KnowledgeBaseID == "" {
continue
}
2026-04-22 13:17:12 +00:00
if searchableKBs [ st . KnowledgeBaseID ] {
filteredTargets = append ( filteredTargets , st )
continue
}
if knownKBs [ st . KnowledgeBaseID ] {
logger . Infof ( ctx , "[Tool][KnowledgeSearch] Skipping non-searchable KB %s (no vector/keyword index, likely wiki/graph-only)" , st . KnowledgeBaseID )
continue
}
// KB record unavailable; keep so downstream can surface real errors.
filteredTargets = append ( filteredTargets , st )
}
if len ( filteredTargets ) == 0 {
logger . Infof ( ctx , "[Tool][KnowledgeSearch] No searchable KBs in scope (all wiki/graph-only); skipping retrieval" )
return nil
}
searchTargets = filteredTargets
2026-03-13 12:54:25 +00:00
// Resolve actual model identities (name + endpoint) for cross-tenant grouping
modelKeyMap := t . knowledgeBaseService . ResolveEmbeddingModelKeys ( ctx , kbList )
groups := make ( map [ string ] [ ] * types . SearchTarget )
2026-03-13 12:33:47 +00:00
for _ , st := range searchTargets {
2026-07-26 16:59:38 +00:00
if st == nil || st . KnowledgeBaseID == "" {
continue
}
2026-03-13 12:54:25 +00:00
key := modelKeyMap [ st . KnowledgeBaseID ]
2026-03-13 12:33:47 +00:00
groups [ key ] = append ( groups [ key ] , st )
}
2025-11-05 15:18:44 +00:00
var wg sync . WaitGroup
var mu sync . Mutex
allResults := make ( [ ] * searchResultWithMeta , 0 )
for _ , query := range queries {
2025-11-19 11:27:25 +00:00
q := query
2026-03-13 12:54:25 +00:00
for modelKey , targets := range groups {
2025-11-19 11:27:25 +00:00
wg . Add ( 1 )
2026-03-13 12:54:25 +00:00
go func ( q string , modelKey string , targets [ ] * types . SearchTarget ) {
2025-11-19 11:27:25 +00:00
defer wg . Done ( )
2025-12-19 14:17:56 +00:00
2026-03-13 12:33:47 +00:00
// Compute embedding once for this (model, query) pair
var queryEmbedding [ ] float32
2026-03-13 12:54:25 +00:00
if modelKey != "" {
2026-03-13 12:33:47 +00:00
emb , err := t . knowledgeBaseService . GetQueryEmbedding ( ctx , targets [ 0 ] . KnowledgeBaseID , q )
if err != nil {
2026-03-13 12:54:25 +00:00
logger . Warnf ( ctx , "[Tool][KnowledgeSearch] Failed to pre-compute embedding for model %s: %v" , modelKey , err )
2026-03-13 12:33:47 +00:00
} else {
queryEmbedding = emb
}
2025-11-19 11:27:25 +00:00
}
2025-12-19 14:17:56 +00:00
2026-03-13 12:33:47 +00:00
// Separate full-KB targets (combinable) from specific-knowledge targets
var fullKBIDs [ ] string
var knowledgeTargets [ ] * types . SearchTarget
for _ , st := range targets {
2026-06-29 08:01:58 +00:00
if st . Type == types . SearchTargetTypeKnowledgeBase && len ( st . TagIDs ) == 0 {
2026-03-13 12:33:47 +00:00
fullKBIDs = append ( fullKBIDs , st . KnowledgeBaseID )
} else {
knowledgeTargets = append ( knowledgeTargets , st )
}
2025-12-19 14:17:56 +00:00
}
2026-03-13 12:33:47 +00:00
var innerWg sync . WaitGroup
// Combined retrieval for all full-KB targets in this group
if len ( fullKBIDs ) > 0 {
innerWg . Add ( 1 )
go func ( ) {
defer innerWg . Done ( )
searchParams := types . SearchParams {
QueryText : q ,
QueryEmbedding : queryEmbedding ,
KnowledgeBaseIDs : fullKBIDs ,
MatchCount : topK ,
VectorThreshold : vectorThreshold ,
KeywordThreshold : keywordThreshold ,
}
kbResults , err := t . knowledgeBaseService . HybridSearch ( ctx , fullKBIDs [ 0 ] , searchParams )
if err != nil {
logger . Warnf ( ctx , "[Tool][KnowledgeSearch] Combined search failed for KBs %v: %v" , fullKBIDs , err )
return
}
mu . Lock ( )
for _ , r := range kbResults {
allResults = append ( allResults , & searchResultWithMeta {
SearchResult : r ,
SourceQuery : q ,
QueryType : "hybrid" ,
KnowledgeBaseID : r . KnowledgeBaseID ,
KnowledgeBaseType : kbTypeMap [ r . KnowledgeBaseID ] ,
} )
}
mu . Unlock ( )
} ( )
2025-11-19 11:27:25 +00:00
}
2025-11-05 15:18:44 +00:00
2026-03-13 12:33:47 +00:00
// Individual retrieval for specific-knowledge targets
for _ , target := range knowledgeTargets {
st := target
innerWg . Add ( 1 )
go func ( ) {
defer innerWg . Done ( )
2026-07-17 02:16:58 +00:00
stVectorThreshold , stKeywordThreshold := st . RecallThresholds (
vectorThreshold ,
keywordThreshold ,
)
2026-03-13 12:33:47 +00:00
searchParams := types . SearchParams {
QueryText : q ,
QueryEmbedding : queryEmbedding ,
MatchCount : topK ,
2026-07-17 02:16:58 +00:00
VectorThreshold : stVectorThreshold ,
KeywordThreshold : stKeywordThreshold ,
2026-03-13 12:33:47 +00:00
KnowledgeIDs : st . KnowledgeIDs ,
2026-06-29 08:01:58 +00:00
TagIDs : st . TagIDs ,
2026-07-17 02:16:58 +00:00
ScopeTagIDs : st . ScopeTagIDs ,
2026-03-13 12:33:47 +00:00
}
kbResults , err := t . knowledgeBaseService . HybridSearch ( ctx , st . KnowledgeBaseID , searchParams )
if err != nil {
logger . Warnf ( ctx , "[Tool][KnowledgeSearch] Failed to search KB %s: %v" , st . KnowledgeBaseID , err )
return
}
mu . Lock ( )
for _ , r := range kbResults {
allResults = append ( allResults , & searchResultWithMeta {
SearchResult : r ,
SourceQuery : q ,
QueryType : "hybrid" ,
KnowledgeBaseID : r . KnowledgeBaseID ,
KnowledgeBaseType : kbTypeMap [ r . KnowledgeBaseID ] ,
} )
}
mu . Unlock ( )
} ( )
2025-11-19 11:27:25 +00:00
}
2026-03-13 12:33:47 +00:00
innerWg . Wait ( )
2026-03-13 12:54:25 +00:00
} ( q , modelKey , targets )
2025-11-19 11:27:25 +00:00
}
2025-11-05 15:18:44 +00:00
}
wg . Wait ( )
2025-11-19 11:27:25 +00:00
return allResults
2025-11-05 15:18:44 +00:00
}
2026-06-15 16:49:34 +00:00
// rerankResults applies reranking to all search results (including FAQ entries)
// using the rerank model or LLM fallback, then filters by threshold and applies
// composite scoring so MMR/sorting uses a single score scale.
2025-11-05 15:18:44 +00:00
func ( t * KnowledgeSearchTool ) rerankResults (
ctx context . Context ,
query string ,
results [ ] * searchResultWithMeta ,
2025-11-12 17:22:08 +00:00
) ( [ ] * searchResultWithMeta , error ) {
2026-06-15 16:49:34 +00:00
if len ( results ) == 0 {
2025-11-17 07:33:43 +00:00
return results , nil
}
var (
2026-06-15 16:49:34 +00:00
reranked [ ] * searchResultWithMeta
err error
2025-11-17 07:33:43 +00:00
)
2025-11-25 05:28:21 +00:00
if t . rerankModel != nil {
2026-06-15 16:49:34 +00:00
reranked , err = t . rerankWithModel ( ctx , query , results )
if err != nil || len ( reranked ) == 0 {
2025-11-25 05:28:21 +00:00
if err != nil {
logger . Warnf ( ctx , "[Tool][KnowledgeSearch] Rerank model failed, falling back to chat model: %v" , err )
} else {
2026-06-15 16:49:34 +00:00
logger . Warnf ( ctx , "[Tool][KnowledgeSearch] Rerank model returned no results above threshold, falling back to chat model" )
2025-11-25 05:28:21 +00:00
}
err = nil
if t . chatModel != nil {
2026-06-15 16:49:34 +00:00
reranked , err = t . rerankWithLLM ( ctx , query , results )
} else if len ( reranked ) == 0 {
reranked = results
2025-11-25 05:28:21 +00:00
}
}
} else if t . chatModel != nil {
2026-06-15 16:49:34 +00:00
reranked , err = t . rerankWithLLM ( ctx , query , results )
2025-11-25 05:28:21 +00:00
} else {
2026-06-15 16:49:34 +00:00
return results , nil
2025-11-12 17:22:08 +00:00
}
2025-11-17 07:33:43 +00:00
if err != nil {
return nil , err
2025-11-12 17:22:08 +00:00
}
2026-06-15 16:49:34 +00:00
logger . Debugf ( ctx , "[Tool][KnowledgeSearch] Rerank produced %d results after threshold filter" , len ( reranked ) )
return reranked , nil
2025-11-17 07:33:43 +00:00
}
func ( t * KnowledgeSearchTool ) getFAQMetadata (
ctx context . Context ,
chunkID string ,
cache map [ string ] * types . FAQChunkMetadata ,
) ( * types . FAQChunkMetadata , error ) {
if chunkID == "" || t . chunkService == nil {
return nil , nil
}
if meta , ok := cache [ chunkID ] ; ok {
return meta , nil
}
chunk , err := t . chunkService . GetChunkByID ( ctx , chunkID )
if err != nil {
cache [ chunkID ] = nil
return nil , err
}
if chunk == nil {
cache [ chunkID ] = nil
return nil , nil
}
meta , err := chunk . FAQMetadata ( )
if err != nil {
cache [ chunkID ] = nil
return nil , err
}
cache [ chunkID ] = meta
return meta , nil
2025-11-12 17:22:08 +00:00
}
// rerankWithLLM uses LLM prompt to score and rerank search results
2025-11-14 17:30:17 +00:00
// Uses batch processing to handle large result sets efficiently
2025-11-12 17:22:08 +00:00
func ( t * KnowledgeSearchTool ) rerankWithLLM (
ctx context . Context ,
query string ,
results [ ] * searchResultWithMeta ,
) ( [ ] * searchResultWithMeta , error ) {
logger . Infof ( ctx , "[Tool][KnowledgeSearch] Using LLM for reranking %d results" , len ( results ) )
2025-11-14 17:30:17 +00:00
if len ( results ) == 0 {
return results , nil
2025-11-12 17:22:08 +00:00
}
2025-11-14 17:30:17 +00:00
// Batch size: process 15 results at a time to balance quality and token usage
// This prevents token overflow and improves processing efficiency
const batchSize = 15
const maxContentLength = 800 // Maximum characters per passage to avoid excessive tokens
// Process in batches
allScores := make ( [ ] float64 , len ( results ) )
for batchStart := 0 ; batchStart < len ( results ) ; batchStart += batchSize {
batchEnd := batchStart + batchSize
if batchEnd > len ( results ) {
batchEnd = len ( results )
}
batch := results [ batchStart : batchEnd ]
logger . Debugf ( ctx , "[Tool][KnowledgeSearch] Processing rerank batch %d-%d of %d results" ,
batchStart + 1 , batchEnd , len ( results ) )
// Build prompt with query and batch passages
var passagesBuilder strings . Builder
for i , result := range batch {
2025-11-25 05:28:21 +00:00
// Get enriched passage (content + image info)
enrichedContent := t . getEnrichedPassage ( ctx , result . SearchResult )
2025-11-14 17:30:17 +00:00
// Truncate content if too long to save tokens
2025-11-25 05:28:21 +00:00
content := enrichedContent
2025-11-14 17:30:17 +00:00
if len ( [ ] rune ( content ) ) > maxContentLength {
runes := [ ] rune ( content )
content = string ( runes [ : maxContentLength ] ) + "..."
}
// Use clear separators to distinguish each passage
if i > 0 {
passagesBuilder . WriteString ( "\n" )
}
passagesBuilder . WriteString ( "─────────────────────────────────────────────────────────────\n" )
passagesBuilder . WriteString ( fmt . Sprintf ( "Passage %d:\n" , i + 1 ) )
passagesBuilder . WriteString ( "─────────────────────────────────────────────────────────────\n" )
passagesBuilder . WriteString ( content + "\n" )
}
// Optimized prompt focused on retrieval matching and reranking
2025-11-28 08:17:52 +00:00
prompt := fmt . Sprintf (
` You are a search result reranking expert . Your task is to evaluate how well each retrieved passage matches the user ' s search query and information need .
2025-11-12 17:22:08 +00:00
2025-11-14 17:30:17 +00:00
User Query : % s
2025-11-12 17:22:08 +00:00
2025-11-14 17:30:17 +00:00
Your task : Rerank these search results by evaluating their retrieval relevance - how well each passage answers or relates to the query .
2025-11-12 17:22:08 +00:00
2025-11-14 17:30:17 +00:00
Scoring Criteria ( 0.0 to 1.0 ) :
- 1.0 ( 0.9 - 1.0 ) : Directly answers the query , contains key information needed , highly relevant
- 0.8 ( 0.7 - 0.8 ) : Strongly related , provides substantial relevant information
- 0.6 ( 0.5 - 0.6 ) : Moderately related , contains some relevant information but may be incomplete
- 0.4 ( 0.3 - 0.4 ) : Weakly related , minimal relevance to the query
- 0.2 ( 0.1 - 0.2 ) : Barely related , mostly irrelevant
- 0.0 ( 0.0 ) : Completely irrelevant , no relation to the query
Evaluation Factors :
1. Query - Answer Match : Does the passage directly address what the user is asking ?
2. Information Completeness : Does it provide sufficient information to answer the query ?
3. Semantic Relevance : Does the content semantically relate to the query intent ?
4. Key Term Coverage : Does it cover important terms / concepts from the query ?
5. Information Accuracy : Is the information accurate and trustworthy ?
Retrieved Passages :
2025-11-12 17:22:08 +00:00
% s
2025-11-14 17:30:17 +00:00
IMPORTANT : Return exactly % d scores , one per line , in this exact format :
2025-11-12 17:22:08 +00:00
Passage 1 : X . XX
Passage 2 : X . XX
2025-11-14 17:30:17 +00:00
Passage 3 : X . XX
2025-11-12 17:22:08 +00:00
...
2025-11-14 17:30:17 +00:00
Passage % d : X . XX
2025-11-12 17:22:08 +00:00
2025-11-28 08:17:52 +00:00
Output only the scores , no explanations or additional text . ` ,
query ,
passagesBuilder . String ( ) ,
len ( batch ) ,
len ( batch ) ,
)
2025-11-12 17:22:08 +00:00
2025-11-14 17:30:17 +00:00
messages := [ ] chat . Message {
{
Role : "system" ,
Content : "You are a professional search result reranking expert specializing in information retrieval. You evaluate how well retrieved passages match user queries in search scenarios. Focus on retrieval relevance: whether the passage answers the query, provides needed information, and matches the user's information need. Always respond with scores only, no explanations." ,
} ,
{
Role : "user" ,
Content : prompt ,
} ,
}
2025-11-12 17:22:08 +00:00
2025-11-14 17:30:17 +00:00
// Calculate appropriate max tokens based on batch size
// Each score line is ~15 tokens, add buffer for safety
maxTokens := len ( batch ) * 20 + 100
2026-07-23 10:00:35 +00:00
modelCtx := types . WithLLMCallMetadata ( ctx , "knowledge_search_rerank" , "" )
response , err := t . chatModel . Chat ( modelCtx , messages , & chat . ChatOptions {
2025-11-14 17:30:17 +00:00
Temperature : 0.1 , // Low temperature for consistent scoring
MaxTokens : maxTokens ,
} )
if err != nil {
logger . Warnf ( ctx , "[Tool][KnowledgeSearch] LLM rerank batch %d-%d failed: %v, using original scores" ,
batchStart + 1 , batchEnd , err )
// Use original scores for this batch on error
for i := batchStart ; i < batchEnd ; i ++ {
allScores [ i ] = results [ i ] . Score
}
continue
}
logger . Infof ( ctx , "[Tool][KnowledgeSearch] LLM rerank batch %d-%d response: %s" ,
batchStart + 1 , batchEnd , response . Content )
// Parse scores from response
batchScores , err := t . parseScoresFromResponse ( response . Content , len ( batch ) )
if err != nil {
2025-11-28 08:17:52 +00:00
logger . Warnf (
ctx ,
"[Tool][KnowledgeSearch] Failed to parse LLM scores for batch %d-%d: %v, using original scores" ,
batchStart + 1 ,
batchEnd ,
err ,
)
2025-11-14 17:30:17 +00:00
// Use original scores for this batch on parsing error
for i := batchStart ; i < batchEnd ; i ++ {
allScores [ i ] = results [ i ] . Score
}
continue
}
// Store scores for this batch
for i , score := range batchScores {
if batchStart + i < len ( allScores ) {
allScores [ batchStart + i ] = score
}
}
2025-11-12 17:22:08 +00:00
}
2026-06-15 16:49:34 +00:00
// Create rerank rank results and apply the same threshold + composite path as the model.
rankResults := make ( [ ] rerank . RankResult , 0 , len ( results ) )
for i , score := range allScores {
if i >= len ( results ) {
break
2025-11-12 17:22:08 +00:00
}
2026-06-15 16:49:34 +00:00
rankResults = append ( rankResults , rerank . RankResult {
Index : i ,
RelevanceScore : score ,
} )
2025-11-12 17:22:08 +00:00
}
2026-06-15 16:49:34 +00:00
sort . Slice ( rankResults , func ( i , j int ) bool {
return rankResults [ i ] . RelevanceScore > rankResults [ j ] . RelevanceScore
2025-11-12 17:22:08 +00:00
} )
2026-07-17 02:16:58 +00:00
ranked := t . applyModelRerankScores (
results ,
rankResults ,
t . rerankThreshold ( ) ,
t . searchTargets . HasRecallThresholdOverride ( ) ,
)
2026-06-15 16:49:34 +00:00
logger . Infof ( ctx , "[Tool][KnowledgeSearch] LLM reranked %d/%d results above threshold %.2f" ,
len ( ranked ) , len ( results ) , t . rerankThreshold ( ) )
return ranked , nil
2025-11-12 17:22:08 +00:00
}
// parseScoresFromResponse parses scores from LLM response text
func ( t * KnowledgeSearchTool ) parseScoresFromResponse ( responseText string , expectedCount int ) ( [ ] float64 , error ) {
lines := strings . Split ( strings . TrimSpace ( responseText ) , "\n" )
scores := make ( [ ] float64 , 0 , expectedCount )
for _ , line := range lines {
line = strings . TrimSpace ( line )
if line == "" {
continue
}
// Try to extract score from various formats:
// "Passage 1: 0.85"
// "1: 0.85"
// "0.85"
// etc.
parts := strings . Split ( line , ":" )
var scoreStr string
if len ( parts ) >= 2 {
scoreStr = strings . TrimSpace ( parts [ len ( parts ) - 1 ] )
} else {
scoreStr = strings . TrimSpace ( line )
}
// Remove any non-numeric characters except decimal point
scoreStr = strings . TrimFunc ( scoreStr , func ( r rune ) bool {
return ( r < '0' || r > '9' ) && r != '.'
} )
if scoreStr == "" {
continue
}
score , err := strconv . ParseFloat ( scoreStr , 64 )
if err != nil {
continue // Skip invalid scores
}
// Clamp score to [0.0, 1.0]
if score < 0.0 {
score = 0.0
}
if score > 1.0 {
score = 1.0
}
scores = append ( scores , score )
}
if len ( scores ) == 0 {
return nil , fmt . Errorf ( "no valid scores found in response" )
}
// If we got fewer scores than expected, pad with last score or 0.5
for len ( scores ) < expectedCount {
if len ( scores ) > 0 {
scores = append ( scores , scores [ len ( scores ) - 1 ] )
} else {
scores = append ( scores , 0.5 )
}
}
// Truncate if we got more scores than expected
if len ( scores ) > expectedCount {
scores = scores [ : expectedCount ]
}
return scores , nil
}
2026-06-15 16:49:34 +00:00
// rerankWithModel uses the rerank model for reranking.
2025-11-12 17:22:08 +00:00
func ( t * KnowledgeSearchTool ) rerankWithModel (
ctx context . Context ,
query string ,
results [ ] * searchResultWithMeta ,
2025-11-05 15:18:44 +00:00
) ( [ ] * searchResultWithMeta , error ) {
passages := make ( [ ] string , len ( results ) )
for i , result := range results {
2025-11-25 05:28:21 +00:00
passages [ i ] = t . getEnrichedPassage ( ctx , result . SearchResult )
2025-11-05 15:18:44 +00:00
}
rerankResp , err := t . rerankModel . Rerank ( ctx , query , passages )
if err != nil {
return nil , fmt . Errorf ( "rerank call failed: %w" , err )
}
2026-07-17 02:16:58 +00:00
ranked := t . applyModelRerankScores (
results ,
rerankResp ,
t . rerankThreshold ( ) ,
t . searchTargets . HasRecallThresholdOverride ( ) ,
)
2025-11-28 08:17:52 +00:00
logger . Infof (
ctx ,
2026-06-15 16:49:34 +00:00
"[Tool][KnowledgeSearch] Reranked %d/%d results above threshold %.2f" ,
len ( ranked ) ,
2025-11-28 08:17:52 +00:00
len ( results ) ,
2026-06-15 16:49:34 +00:00
t . rerankThreshold ( ) ,
2025-11-28 08:17:52 +00:00
)
2026-06-15 16:49:34 +00:00
return ranked , nil
}
func ( t * KnowledgeSearchTool ) rerankThreshold ( ) float64 {
if t . config != nil && t . config . Conversation != nil && t . config . Conversation . RerankThreshold > 0 {
return t . config . Conversation . RerankThreshold
}
return 0.3
}
const agentRerankFallbackMinScore = 0.15
2026-07-17 02:16:58 +00:00
func filterRerankRankResults (
rankResults [ ] rerank . RankResult ,
threshold float64 ,
preserveTop bool ,
) [ ] rerank . RankResult {
2026-06-15 16:49:34 +00:00
if len ( rankResults ) == 0 {
return nil
}
filtered := make ( [ ] rerank . RankResult , 0 , len ( rankResults ) )
for _ , r := range rankResults {
if r . RelevanceScore >= threshold {
filtered = append ( filtered , r )
}
}
if len ( filtered ) == 0 {
top := rankResults [ 0 ]
for _ , r := range rankResults [ 1 : ] {
if r . RelevanceScore > top . RelevanceScore {
top = r
}
}
2026-07-17 02:16:58 +00:00
if preserveTop || top . RelevanceScore >= agentRerankFallbackMinScore {
2026-06-15 16:49:34 +00:00
return [ ] rerank . RankResult { top }
}
}
return filtered
}
func ( t * KnowledgeSearchTool ) applyModelRerankScores (
originals [ ] * searchResultWithMeta ,
rankResults [ ] rerank . RankResult ,
threshold float64 ,
2026-07-17 02:16:58 +00:00
preserveTop bool ,
2026-06-15 16:49:34 +00:00
) [ ] * searchResultWithMeta {
2026-07-17 02:16:58 +00:00
filtered := filterRerankRankResults ( rankResults , threshold , preserveTop )
2026-06-15 16:49:34 +00:00
out := make ( [ ] * searchResultWithMeta , 0 , len ( filtered ) )
for _ , rr := range filtered {
if rr . Index < 0 || rr . Index >= len ( originals ) {
continue
}
newResult := * originals [ rr . Index ]
baseScore := newResult . Score
modelScore := rr . RelevanceScore
newResult . Score = t . compositeScore ( & newResult , modelScore , baseScore )
out = append ( out , & newResult )
}
sort . Slice ( out , func ( i , j int ) bool {
return out [ i ] . Score > out [ j ] . Score
} )
return out
2025-11-05 15:18:44 +00:00
}
// deduplicateResults removes duplicate chunks, keeping the highest score
2025-11-25 05:28:21 +00:00
// Uses multiple keys (ID, parent chunk ID, knowledge+index) and content signature for deduplication
2025-11-05 15:18:44 +00:00
func ( t * KnowledgeSearchTool ) deduplicateResults ( results [ ] * searchResultWithMeta ) [ ] * searchResultWithMeta {
2025-11-25 05:28:21 +00:00
seen := make ( map [ string ] bool )
contentSig := make ( map [ string ] bool )
uniqueResults := make ( [ ] * searchResultWithMeta , 0 )
2025-11-05 15:18:44 +00:00
for _ , r := range results {
2025-11-25 05:28:21 +00:00
// 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 {
2025-11-05 15:18:44 +00:00
// Keep the result with higher score
if r . Score > existing . Score {
2025-11-25 05:28:21 +00:00
seenByID [ r . ID ] = r
2025-11-05 15:18:44 +00:00
}
} else {
2025-11-25 05:28:21 +00:00
seenByID [ r . ID ] = r
2025-11-05 15:18:44 +00:00
}
}
2025-11-25 05:28:21 +00:00
// Convert back to slice
deduplicated := make ( [ ] * searchResultWithMeta , 0 , len ( seenByID ) )
for _ , r := range seenByID {
2025-11-05 15:18:44 +00:00
deduplicated = append ( deduplicated , r )
}
return deduplicated
}
2025-11-25 05:28:21 +00:00
// buildContentSignature creates a normalized signature for content to detect near-duplicates
func ( t * KnowledgeSearchTool ) buildContentSignature ( content string ) string {
2025-12-03 09:45:21 +00:00
return searchutil . BuildContentSignature ( content )
2025-11-25 05:28:21 +00:00
}
2026-07-28 07:50:39 +00:00
// writeKnowledgeMetadataHeader emits document-scoped metadata once per
// knowledge item. Chunk entries keep only chunk-specific content so repeated
// results from the same document do not waste model context.
func writeKnowledgeMetadataHeader ( ob * strings . Builder , results [ ] * searchResultWithMeta ) {
seen := make ( map [ string ] struct { } , len ( results ) )
hasMetadata := false
var documents strings . Builder
for _ , result := range results {
if result == nil || result . SearchResult == nil || result . KnowledgeID == "" || result . KnowledgeCustomMetadata == "" {
continue
}
if _ , ok := seen [ result . KnowledgeID ] ; ok {
continue
}
seen [ result . KnowledgeID ] = struct { } { }
hasMetadata = true
documents . WriteString ( fmt . Sprintf (
"<document knowledge_id=\"%s\" knowledge_base_id=\"%s\" title=\"%s\">\n" ,
xmlEscape ( result . KnowledgeID ) ,
xmlEscape ( result . KnowledgeBaseID ) ,
xmlEscape ( result . KnowledgeTitle ) ,
) )
documents . WriteString ( fmt . Sprintf ( "<metadata>%s</metadata>\n" , xmlEscape ( result . KnowledgeCustomMetadata ) ) )
documents . WriteString ( "</document>\n" )
}
if ! hasMetadata {
return
}
ob . WriteString ( "<documents>\n" )
ob . WriteString ( documents . String ( ) )
ob . WriteString ( "</documents>\n" )
}
2025-11-05 15:18:44 +00:00
// formatOutput formats the search results for display
func ( t * KnowledgeSearchTool ) formatOutput (
2025-11-17 07:33:43 +00:00
ctx context . Context ,
2025-11-05 15:18:44 +00:00
results [ ] * searchResultWithMeta ,
kbsToSearch [ ] string ,
2025-11-19 11:27:25 +00:00
queries [ ] string ,
2025-11-05 15:18:44 +00:00
) ( * types . ToolResult , error ) {
if len ( results ) == 0 {
data := map [ string ] interface { } {
"knowledge_base_ids" : kbsToSearch ,
"results" : [ ] interface { } { } ,
"count" : 0 ,
}
2025-11-19 11:27:25 +00:00
if len ( queries ) > 0 {
data [ "queries" ] = queries
2025-11-05 15:18:44 +00:00
}
2025-11-23 09:32:50 +00:00
output := fmt . Sprintf ( "No relevant content found in %d knowledge base(s).\n\n" , len ( kbsToSearch ) )
output += "=== ⚠️ CRITICAL - Next Steps ===\n"
output += "- ❌ DO NOT use training data or general knowledge to answer\n"
output += "- ✅ If web_search is enabled: You MUST use web_search to find information\n"
output += "- ✅ If web_search is disabled: State 'I couldn't find relevant information in the knowledge base'\n"
output += "- NEVER fabricate or infer answers - ONLY use retrieved content\n"
2025-11-05 15:18:44 +00:00
return & types . ToolResult {
Success : true ,
2025-11-23 09:32:50 +00:00
Output : output ,
2025-11-05 15:18:44 +00:00
Data : data ,
} , nil
}
// Count results by KB
kbCounts := make ( map [ string ] int )
for _ , r := range results {
2026-07-26 16:59:38 +00:00
kbCounts [ r . KnowledgeBaseID ] ++
2025-11-05 15:18:44 +00:00
}
2026-04-21 11:19:57 +00:00
// Format individual results as XML. Tag names are kept in sync with
// wiki_search (`<search_results>`, per-entry element, `<query>`) so that
// agents and downstream consumers see a single consistent shape across
// all retrieval tools.
2026-04-16 15:25:25 +00:00
var ob strings . Builder
ob . WriteString ( fmt . Sprintf ( "<search_results count=\"%d\">\n" , len ( results ) ) )
2026-04-21 11:19:57 +00:00
for _ , q := range queries {
ob . WriteString ( fmt . Sprintf ( "<query>%s</query>\n" , xmlEscape ( q ) ) )
}
2026-07-28 07:50:39 +00:00
writeKnowledgeMetadataHeader ( & ob , results )
2025-11-05 15:18:44 +00:00
formattedResults := make ( [ ] map [ string ] interface { } , 0 , len ( results ) )
2026-07-29 06:33:44 +00:00
enabled := true
2025-11-05 15:18:44 +00:00
2025-11-17 07:33:43 +00:00
faqMetadataCache := make ( map [ string ] * types . FAQChunkMetadata )
2026-04-16 15:25:25 +00:00
knowledgeChunkMap := make ( map [ string ] map [ int ] bool )
knowledgeTotalMap := make ( map [ string ] int64 )
knowledgeTitleMap := make ( map [ string ] string )
2025-11-23 09:32:50 +00:00
2025-11-05 15:18:44 +00:00
for i , result := range results {
2025-11-17 07:33:43 +00:00
var faqMeta * types . FAQChunkMetadata
if result . KnowledgeBaseType == types . KnowledgeBaseTypeFAQ {
meta , err := t . getFAQMetadata ( ctx , result . ID , faqMetadataCache )
if err != nil {
2026-04-16 15:25:25 +00:00
logger . Warnf ( ctx , "[Tool][KnowledgeSearch] Failed to load FAQ metadata for chunk %s: %v" , result . ID , err )
2025-11-17 07:33:43 +00:00
} else {
faqMeta = meta
}
}
2025-11-23 09:32:50 +00:00
if knowledgeChunkMap [ result . KnowledgeID ] == nil {
knowledgeChunkMap [ result . KnowledgeID ] = make ( map [ int ] bool )
}
knowledgeChunkMap [ result . KnowledgeID ] [ result . ChunkIndex ] = true
knowledgeTitleMap [ result . KnowledgeID ] = result . KnowledgeTitle
2026-04-16 15:25:25 +00:00
// Cache total chunk count per knowledge
if _ , exists := knowledgeTotalMap [ result . KnowledgeID ] ; ! exists {
effectiveTenantID := t . searchTargets . GetTenantIDForKB ( result . KnowledgeBaseID )
if effectiveTenantID == 0 {
logger . Warnf ( ctx , "[Tool][KnowledgeSearch] KB %s not found in searchTargets, skipping chunk count" , result . KnowledgeBaseID )
knowledgeTotalMap [ result . KnowledgeID ] = 0
} else {
2026-04-22 13:17:12 +00:00
// Use the same chunk-type filter as list_knowledge_chunks so the
// total reported here matches what list_knowledge_chunks can page
// over. Mismatched filters previously let LLMs compute offsets
// against an inflated/deflated total and page past the end.
2026-04-16 15:25:25 +00:00
_ , total , err := t . chunkService . GetRepository ( ) . ListPagedChunksByKnowledgeID ( ctx ,
effectiveTenantID , result . KnowledgeID ,
& types . Pagination { Page : 1 , PageSize : 1 } ,
2026-07-23 02:27:35 +00:00
[ ] types . ChunkType { types . ChunkTypeText , types . ChunkTypeFAQ } , nil , "" , "" , "" , "" ,
2026-07-29 06:33:44 +00:00
& enabled ,
2026-04-16 15:25:25 +00:00
)
if err != nil {
logger . Warnf ( ctx , "[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v" , result . KnowledgeID , err )
2025-11-23 09:32:50 +00:00
knowledgeTotalMap [ result . KnowledgeID ] = 0
} else {
2026-04-16 15:25:25 +00:00
knowledgeTotalMap [ result . KnowledgeID ] = total
2025-11-23 09:32:50 +00:00
}
}
2025-11-05 15:18:44 +00:00
}
2026-04-21 11:19:57 +00:00
t . seenMu . Lock ( )
seen := t . seenChunks [ result . ID ]
t . seenChunks [ result . ID ] = true
t . seenMu . Unlock ( )
2026-06-04 12:17:43 +00:00
isFAQ := faqMeta != nil
2026-04-21 11:19:57 +00:00
if seen {
// Compact rendering for chunks we already returned in a previous
// knowledge_search call during this session. The model has the
// content in context already, so re-emitting it only burns tokens.
2026-06-04 12:17:43 +00:00
if isFAQ {
ob . WriteString ( fmt . Sprintf (
"<faq rank=\"%d\" faq_id=\"%s\" index=\"%d\" knowledge_base_id=\"%s\" knowledge_title=\"%s\" score=\"%.3f\" source_query=\"%s\" already_seen=\"true\">\n" ,
i + 1 ,
xmlEscape ( result . ID ) ,
result . ChunkIndex ,
xmlEscape ( result . KnowledgeBaseID ) ,
xmlEscape ( result . KnowledgeTitle ) ,
result . Score ,
xmlEscape ( result . SourceQuery ) ,
) )
} else {
ob . WriteString ( fmt . Sprintf (
"<chunk rank=\"%d\" chunk_id=\"%s\" chunk_index=\"%d\" knowledge_id=\"%s\" knowledge_base_id=\"%s\" knowledge_title=\"%s\" score=\"%.3f\" source_query=\"%s\" already_seen=\"true\">\n" ,
i + 1 ,
xmlEscape ( result . ID ) ,
result . ChunkIndex ,
xmlEscape ( result . KnowledgeID ) ,
xmlEscape ( result . KnowledgeBaseID ) ,
xmlEscape ( result . KnowledgeTitle ) ,
result . Score ,
xmlEscape ( result . SourceQuery ) ,
) )
}
2026-04-21 11:19:57 +00:00
ob . WriteString ( "<note>(content omitted, already returned in a previous knowledge_search call this session)</note>\n" )
2026-06-04 12:17:43 +00:00
if isFAQ {
ob . WriteString ( "</faq>\n" )
} else {
ob . WriteString ( "</chunk>\n" )
}
2026-04-21 11:19:57 +00:00
} else {
2026-06-04 12:17:43 +00:00
if isFAQ {
ob . WriteString ( fmt . Sprintf (
"<faq rank=\"%d\" faq_id=\"%s\" index=\"%d\" knowledge_base_id=\"%s\" knowledge_title=\"%s\" score=\"%.3f\" source_query=\"%s\">\n" ,
i + 1 ,
xmlEscape ( result . ID ) ,
result . ChunkIndex ,
xmlEscape ( result . KnowledgeBaseID ) ,
xmlEscape ( result . KnowledgeTitle ) ,
result . Score ,
xmlEscape ( result . SourceQuery ) ,
) )
} else {
ob . WriteString ( fmt . Sprintf (
"<chunk rank=\"%d\" chunk_id=\"%s\" chunk_index=\"%d\" knowledge_id=\"%s\" knowledge_base_id=\"%s\" knowledge_title=\"%s\" score=\"%.3f\" source_query=\"%s\">\n" ,
i + 1 ,
xmlEscape ( result . ID ) ,
result . ChunkIndex ,
xmlEscape ( result . KnowledgeID ) ,
xmlEscape ( result . KnowledgeBaseID ) ,
xmlEscape ( result . KnowledgeTitle ) ,
result . Score ,
xmlEscape ( result . SourceQuery ) ,
) )
}
snippet := ""
if faqMeta != nil {
snippet = faqMatchSnippetFromQueries ( faqMeta , queries )
}
if snippet == "" {
snippet = extractSnippetForQueries ( result . Content , queries )
}
if snippet != "" {
2026-04-21 11:19:57 +00:00
ob . WriteString ( fmt . Sprintf ( "<match_snippet>%s</match_snippet>\n" , xmlEscape ( snippet ) ) )
}
ob . WriteString ( fmt . Sprintf ( "<content>%s</content>\n" , result . Content ) )
if result . ImageInfo != "" {
var imageInfos [ ] types . ImageInfo
if err := json . Unmarshal ( [ ] byte ( result . ImageInfo ) , & imageInfos ) ; err == nil && len ( imageInfos ) > 0 {
for _ , img := range imageInfos {
2026-07-15 09:30:16 +00:00
if imageMarkdown := searchutil . BuildImageInfoMarkdownWithURL ( img . URL , & img ) ; imageMarkdown != "" {
ob . WriteString ( imageMarkdown )
ob . WriteString ( "\n" )
2026-04-21 11:19:57 +00:00
}
2025-12-16 03:31:41 +00:00
}
}
}
2026-06-04 12:17:43 +00:00
if isFAQ {
writeFAQFieldsXML ( & ob , faqMeta )
2026-04-21 11:19:57 +00:00
ob . WriteString ( "</faq>\n" )
2026-06-04 12:17:43 +00:00
} else {
ob . WriteString ( "</chunk>\n" )
2025-11-17 07:33:43 +00:00
}
2026-04-21 11:19:57 +00:00
}
2026-04-16 15:25:25 +00:00
2025-11-05 15:18:44 +00:00
formattedResults = append ( formattedResults , map [ string ] interface { } {
2026-04-16 15:25:25 +00:00
"result_index" : i + 1 ,
"content" : result . Content ,
2025-11-17 07:33:43 +00:00
"knowledge_id" : result . KnowledgeID ,
2026-07-07 12:21:28 +00:00
"knowledge_base_id" : result . KnowledgeBaseID ,
2025-11-17 07:33:43 +00:00
"knowledge_title" : result . KnowledgeTitle ,
2026-07-28 03:39:20 +00:00
"knowledge_metadata" : result . KnowledgeCustomMetadata ,
2025-11-17 07:33:43 +00:00
"match_type" : result . MatchType ,
"source_query" : result . SourceQuery ,
"query_type" : result . QueryType ,
"knowledge_base_type" : result . KnowledgeBaseType ,
2025-11-05 15:18:44 +00:00
} )
2025-11-17 07:33:43 +00:00
last := formattedResults [ len ( formattedResults ) - 1 ]
2025-12-16 03:31:41 +00:00
if result . ImageInfo != "" {
var imageInfos [ ] types . ImageInfo
if err := json . Unmarshal ( [ ] byte ( result . ImageInfo ) , & imageInfos ) ; err == nil && len ( imageInfos ) > 0 {
imageList := make ( [ ] map [ string ] string , 0 , len ( imageInfos ) )
for _ , img := range imageInfos {
imgData := make ( map [ string ] string )
if img . URL != "" {
imgData [ "url" ] = img . URL
}
if img . Caption != "" {
imgData [ "caption" ] = img . Caption
}
if img . OCRText != "" {
imgData [ "ocr_text" ] = img . OCRText
}
if len ( imgData ) > 0 {
imageList = append ( imageList , imgData )
}
}
if len ( imageList ) > 0 {
last [ "images" ] = imageList
}
}
}
2025-11-17 07:33:43 +00:00
if faqMeta != nil {
2026-06-04 12:17:43 +00:00
last [ "faq_id" ] = result . ID
last [ "index" ] = result . ChunkIndex
2025-11-17 07:33:43 +00:00
if faqMeta . StandardQuestion != "" {
last [ "faq_standard_question" ] = faqMeta . StandardQuestion
}
2026-06-04 12:17:43 +00:00
appendSimilarQuestionsToChunkData ( last , faqMeta . SimilarQuestions )
2025-11-17 07:33:43 +00:00
if len ( faqMeta . Answers ) > 0 {
last [ "faq_answers" ] = faqMeta . Answers
}
2026-06-04 12:17:43 +00:00
} else {
last [ "chunk_id" ] = result . ID
last [ "chunk_index" ] = result . ChunkIndex
2025-11-17 07:33:43 +00:00
}
2025-11-05 15:18:44 +00:00
}
2026-04-16 15:25:25 +00:00
// Retrieval statistics
ob . WriteString ( "<retrieval_statistics>\n" )
2025-11-23 09:32:50 +00:00
for knowledgeID , retrievedChunks := range knowledgeChunkMap {
totalChunks := knowledgeTotalMap [ knowledgeID ]
retrievedCount := len ( retrievedChunks )
title := knowledgeTitleMap [ knowledgeID ]
if totalChunks > 0 {
remaining := totalChunks - int64 ( retrievedCount )
2026-04-16 15:25:25 +00:00
percentage := float64 ( retrievedCount ) / float64 ( totalChunks ) * 100
ob . WriteString ( fmt . Sprintf ( "<document_stat knowledge_id=\"%s\" title=\"%s\" total_chunks=\"%d\" retrieved=\"%d\" remaining=\"%d\" coverage=\"%.1f%%\" />\n" ,
2026-04-21 11:19:57 +00:00
xmlEscape ( knowledgeID ) , xmlEscape ( title ) , totalChunks , retrievedCount , remaining , percentage ) )
2025-11-23 09:32:50 +00:00
}
}
2026-04-16 15:25:25 +00:00
ob . WriteString ( "</retrieval_statistics>\n" )
ob . WriteString ( "</search_results>" )
2025-11-23 09:32:50 +00:00
2026-04-16 15:25:25 +00:00
output := ob . String ( )
2025-11-05 15:18:44 +00:00
data := map [ string ] interface { } {
"knowledge_base_ids" : kbsToSearch ,
"results" : formattedResults ,
2025-11-25 05:28:21 +00:00
"count" : len ( formattedResults ) ,
2025-11-05 15:18:44 +00:00
"kb_counts" : kbCounts ,
"display_type" : "search_results" ,
}
2025-11-23 09:32:50 +00:00
2025-11-19 11:27:25 +00:00
if len ( queries ) > 0 {
data [ "queries" ] = queries
2025-11-05 15:18:44 +00:00
}
return & types . ToolResult {
Success : true ,
Output : output ,
Data : data ,
} , nil
}
2025-11-23 09:32:50 +00:00
// chunkRange represents a continuous range of chunk indices
type chunkRange struct {
start int
end int
}
2025-11-25 05:28:21 +00:00
// 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 != "" {
2026-03-06 11:24:23 +00:00
imageTexts = append ( imageTexts , fmt . Sprintf ( "Image Caption: %s" , img . Caption ) )
2025-11-25 05:28:21 +00:00
}
if img . OCRText != "" {
2026-03-06 11:24:23 +00:00
imageTexts = append ( imageTexts , fmt . Sprintf ( "Image Text: %s" , img . OCRText ) )
2025-11-25 05:28:21 +00:00
}
}
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
}
// compositeScore calculates a composite score considering multiple factors
func ( t * KnowledgeSearchTool ) compositeScore (
result * searchResultWithMeta ,
modelScore , baseScore float64 ,
) float64 {
// Source weight: web_search results get slightly lower weight
sourceWeight := 1.0
if strings . ToLower ( result . KnowledgeSource ) == "web_search" {
sourceWeight = 0.95
}
// 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 *= 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 {
2025-12-03 09:45:21 +00:00
return searchutil . ClampFloat ( v , minV , maxV )
2025-11-25 05:28:21 +00:00
}
// 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 { } {
2025-12-03 09:45:21 +00:00
return searchutil . TokenizeSimple ( text )
2025-11-25 05:28:21 +00:00
}
2026-04-21 11:19:57 +00:00
// extractSnippetForQueries tries to produce a short contextual snippet around
// the first occurrence of any token extracted from the provided queries.
// When no token matches (common for fully paraphrased semantic queries) it
// falls back to the leading 160 runes of content so callers always get
// something to scan. The snippet is single-lined and bounded in length to
// keep the rendered XML compact.
func extractSnippetForQueries ( content string , queries [ ] string ) string {
content = strings . TrimSpace ( content )
if content == "" {
return ""
}
2026-06-04 12:17:43 +00:00
tokens := searchQueryTokens ( queries )
2026-04-21 11:19:57 +00:00
lowered := strings . ToLower ( content )
earliest := - 1
earliestEnd := - 1
for _ , tok := range tokens {
idx := strings . Index ( lowered , tok )
if idx < 0 {
continue
}
end := idx + len ( tok )
if earliest < 0 || idx < earliest {
earliest = idx
earliestEnd = end
}
}
if earliest < 0 {
runes := [ ] rune ( content )
2026-06-04 12:17:43 +00:00
if len ( runes ) > snippetContextRunes * 2 {
return strings . TrimSpace ( string ( runes [ : snippetContextRunes * 2 ] ) ) + " ..."
2026-04-21 11:19:57 +00:00
}
return content
}
matchStr := content [ earliest : earliestEnd ]
before := content [ : earliest ]
after := content [ earliestEnd : ]
beforeRunes := [ ] rune ( before )
2026-06-04 12:17:43 +00:00
if len ( beforeRunes ) > snippetContextRunes {
beforeRunes = beforeRunes [ len ( beforeRunes ) - snippetContextRunes : ]
2026-04-21 11:19:57 +00:00
}
afterRunes := [ ] rune ( after )
2026-06-04 12:17:43 +00:00
if len ( afterRunes ) > snippetContextRunes {
afterRunes = afterRunes [ : snippetContextRunes ]
2026-04-21 11:19:57 +00:00
}
snippet := string ( beforeRunes ) + matchStr + string ( afterRunes )
snippet = strings . ReplaceAll ( snippet , "\n" , " " )
for strings . Contains ( snippet , " " ) {
snippet = strings . ReplaceAll ( snippet , " " , " " )
}
return "... " + strings . TrimSpace ( snippet ) + " ..."
}
2025-11-25 05:28:21 +00:00
// jaccard calculates Jaccard similarity between two token sets
func ( t * KnowledgeSearchTool ) jaccard ( a , b map [ string ] struct { } ) float64 {
2025-12-03 09:45:21 +00:00
return searchutil . Jaccard ( a , b )
2025-11-25 05:28:21 +00:00
}