2025-11-23 09:32:50 +00:00
package tools
import (
"context"
2025-12-23 08:56:30 +00:00
"encoding/json"
2025-11-23 09:32:50 +00:00
"fmt"
2025-11-25 05:28:21 +00:00
"math"
2026-04-21 11:19:57 +00:00
"regexp"
2025-11-25 05:28:21 +00:00
"sort"
2025-11-23 09:32:50 +00:00
"strings"
2026-04-21 11:19:57 +00:00
"sync"
2025-11-23 09:32:50 +00:00
"github.com/Tencent/WeKnora/internal/logger"
2025-12-03 09:45:21 +00:00
"github.com/Tencent/WeKnora/internal/searchutil"
2025-11-23 09:32:50 +00:00
"github.com/Tencent/WeKnora/internal/types"
"gorm.io/gorm"
)
2025-12-23 08:56:30 +00:00
var grepChunksTool = BaseTool {
name : ToolGrepChunks ,
2026-05-20 11:32:37 +00:00
description : ` Search knowledge base chunk content with a single POSIX regular expression, applied directly in the database (PostgreSQL ~* / MySQL/SQLite REGEXP, case-insensitive). Behaves like ` + "`grep -E -i`" + ` .
Pack multiple concepts into ONE regex using ` + " ` | ` " + ` alternation — do not call this tool repeatedly for synonyms .
2026-07-16 13:23:20 +00:00
Returns matching chunks with a short cN chunk source ID , a parent dN document ID , and a < match > snippet around the first match .
2026-04-21 11:19:57 +00:00
Examples :
2026-05-20 11:32:37 +00:00
- Alternation ( RECOMMENDED ) : "stardust|skyvault|psionic" ( matches any of the words )
- Multiple terms in order : "psionic.*engine" ( matches both words in order )
2026-04-21 11:19:57 +00:00
- Word boundary / anchor : "\\brag\\b" or "^chapter\\s+\\d+"
- Plain text : "engine" ( matches literal substring anywhere in chunk content )
IMPORTANT — JSON escaping : every backslash in a regex MUST be written as \ \ inside the JSON tool arguments ( e . g . to search for literal "C++" write "C\\+\\+" , NOT "C\+\+" ; for "\d+" write "\\d+" ) . Plain "\+" / "\d" etc . are invalid JSON escapes and will fail to parse .
2026-06-04 12:17:43 +00:00
Use this to locate candidate chunks by exact identifiers , error codes , product names , or recurring terms .
# # Deep read after grep :
2026-07-16 13:23:20 +00:00
- * * FAQ hit * * ( chunk type faq ) : call list_knowledge_chunks with * * faq_id = cN * * from the grep result ( NOT the parent dN document ID ) .
- * * Document hit * * : call list_knowledge_chunks with * * knowledge_id = dN * * , or get_document_info with * * knowledge_ids = [ dN ] * * . ` ,
2025-12-23 08:56:30 +00:00
schema : json . RawMessage ( ` {
"type" : "object" ,
"properties" : {
2026-05-20 11:32:37 +00:00
"query" : {
"type" : "string" ,
"description" : "A single POSIX regex applied directly to chunk content (case-insensitive). Combine multiple concepts with \"|\" alternation in ONE regex (e.g. \"stardust|skyvault|psionic\") — do not split into multiple calls." ,
"minLength" : 1
2025-12-23 08:56:30 +00:00
}
} ,
2026-05-20 11:32:37 +00:00
"required" : [ "query" ]
2025-12-23 08:56:30 +00:00
} ` ) ,
}
2026-04-21 11:19:57 +00:00
// GrepChunksInput defines the input parameters for grep chunks tool.
2026-05-20 11:32:37 +00:00
// The canonical parameter is a single `query` string (a regex with optional
// `|` alternation), matching real `grep -E` semantics. Legacy array forms
// (`queries`, `patterns`) and the singular `pattern` alias remain accepted
// so older model outputs or external callers don't break silently — they
// are joined together into a single alternation regex before execution.
2025-12-23 08:56:30 +00:00
type GrepChunksInput struct {
2026-05-20 11:32:37 +00:00
Query string ` json:"query,omitempty" `
2025-12-23 08:56:30 +00:00
}
2025-11-23 09:32:50 +00:00
2026-04-21 11:19:57 +00:00
// GrepChunksTool performs regex pattern matching across knowledge base chunks.
// PostgreSQL: uses the case-insensitive POSIX operator ~*.
// MySQL/SQLite: falls back to REGEXP.
//
// The tool tracks previously-returned chunk IDs per-instance (one instance per
// agent session) so that a subsequent search hitting the same chunk can be
// rendered compactly with an `already_seen="true"` marker instead of replaying
// the snippet, mirroring the UX of wiki_search.
2025-12-23 08:56:30 +00:00
type GrepChunksTool struct {
BaseTool
2026-01-30 08:28:01 +00:00
db * gorm . DB
2026-04-21 11:19:57 +00:00
searchTargets types . SearchTargets
2026-05-20 11:32:37 +00:00
mu sync . Mutex
seenChunks map [ string ] bool
2025-12-23 08:56:30 +00:00
}
2025-11-23 09:32:50 +00:00
2025-12-23 08:56:30 +00:00
// NewGrepChunksTool creates a new grep chunks tool
2026-01-30 08:28:01 +00:00
func NewGrepChunksTool ( db * gorm . DB , searchTargets types . SearchTargets ) * GrepChunksTool {
2025-11-23 09:32:50 +00:00
return & GrepChunksTool {
2026-01-30 08:28:01 +00:00
BaseTool : grepChunksTool ,
db : db ,
searchTargets : searchTargets ,
2026-04-21 11:19:57 +00:00
seenChunks : make ( map [ string ] bool ) ,
2025-11-23 09:32:50 +00:00
}
}
// Execute executes the grep chunks tool
2025-12-23 08:56:30 +00:00
func ( t * GrepChunksTool ) Execute ( ctx context . Context , args json . RawMessage ) ( * types . ToolResult , error ) {
2025-11-23 09:32:50 +00:00
logger . Infof ( ctx , "[Tool][GrepChunks] Execute started" )
2025-12-23 08:56:30 +00:00
var input GrepChunksInput
if err := json . Unmarshal ( args , & input ) ; err != nil {
logger . Errorf ( ctx , "[Tool][GrepChunks] Failed to parse args: %v" , err )
return & types . ToolResult {
Success : false ,
Error : fmt . Sprintf ( "Failed to parse args: %v" , err ) ,
} , err
2025-11-23 09:32:50 +00:00
}
2025-12-23 08:56:30 +00:00
2026-05-20 11:32:37 +00:00
// Resolve the canonical single-string `query`, falling back to legacy
// aliases. Legacy array inputs are joined with `|` so they degrade into
// a single alternation regex — preserving the previous "match ANY"
// semantics without requiring multiple DB scans.
query := strings . TrimSpace ( input . Query )
2025-12-23 08:56:30 +00:00
2026-05-20 11:32:37 +00:00
if query == "" {
logger . Errorf ( ctx , "[Tool][GrepChunks] Missing or empty query parameter" )
2025-11-23 09:32:50 +00:00
return & types . ToolResult {
Success : false ,
2026-05-20 11:32:37 +00:00
Error : "query parameter is required and must be a non-empty regex string" ,
} , fmt . Errorf ( "missing query parameter" )
2025-11-23 09:32:50 +00:00
}
2026-05-20 11:32:37 +00:00
// Compile with (?i) prefix for case-insensitive Go-side matching.
2026-04-21 11:19:57 +00:00
// Compilation also validates the regex syntax before we send it to the DB.
2026-05-20 11:32:37 +00:00
re , err := regexp . Compile ( "(?i)" + query )
if err != nil {
logger . Errorf ( ctx , "[Tool][GrepChunks] Invalid regex %q: %v" , query , err )
return & types . ToolResult {
Success : false ,
Error : fmt . Sprintf ( "invalid regex query %q: %v" , query , err ) ,
} , err
2026-04-21 11:19:57 +00:00
}
2026-05-20 11:32:37 +00:00
queries := [ ] string { query }
compiled := [ ] * regexp . Regexp { re }
2026-04-21 11:19:57 +00:00
2026-05-20 11:32:37 +00:00
// Result count is controlled by the backend, not the caller — keep it
// bounded so the LLM context stays small regardless of regex breadth.
const limit = 30
2025-11-23 09:32:50 +00:00
2026-01-30 08:28:01 +00:00
kbTenantMap := t . searchTargets . GetKBTenantMap ( )
2026-06-29 10:21:17 +00:00
fullKBIDs , knowledgeIDs , tagTargets := t . resolveGrepScope ( )
2026-06-29 08:54:08 +00:00
kbIDsForMeta := fullKBIDs
if len ( kbIDsForMeta ) == 0 {
kbIDsForMeta = t . searchTargets . GetAllKnowledgeBaseIDs ( )
2026-01-30 08:28:01 +00:00
}
2026-06-29 10:21:17 +00:00
logger . Infof ( ctx , "[Tool][GrepChunks] Queries: %v, Limit: %d, fullKBs: %d, knowledgeIDs: %d, tagScopes: %d" ,
queries , limit , len ( fullKBIDs ) , len ( knowledgeIDs ) , len ( tagTargets ) )
2026-01-30 08:28:01 +00:00
2026-06-29 10:21:17 +00:00
results , err := t . searchChunks ( ctx , queries , fullKBIDs , knowledgeIDs , tagTargets , kbTenantMap )
2025-11-23 09:32:50 +00:00
if err != nil {
logger . Errorf ( ctx , "[Tool][GrepChunks] Search failed: %v" , err )
return & types . ToolResult {
Success : false ,
Error : fmt . Sprintf ( "Search failed: %v" , err ) ,
} , err
}
logger . Infof ( ctx , "[Tool][GrepChunks] Found %d matching chunks" , len ( results ) )
2025-11-25 05:28:21 +00:00
deduplicatedResults := t . deduplicateChunks ( ctx , results )
logger . Infof ( ctx , "[Tool][GrepChunks] After deduplication: %d chunks (from %d)" ,
len ( deduplicatedResults ) , len ( results ) )
2026-04-21 11:19:57 +00:00
// Score chunks using compiled regex (counts + earliest-position boost).
scoredResults := t . scoreChunks ( ctx , deduplicatedResults , compiled )
2025-11-25 05:28:21 +00:00
finalResults := scoredResults
if len ( scoredResults ) > 10 {
mmrK := len ( scoredResults )
2026-04-21 11:19:57 +00:00
if limit > 0 && mmrK > limit {
mmrK = limit
}
logger . Debugf ( ctx , "[Tool][GrepChunks] Applying MMR: k=%d, lambda=0.7, input=%d results" ,
mmrK , len ( scoredResults ) )
mmrResults := t . applyMMR ( ctx , scoredResults , mmrK , 0.7 )
2025-11-25 05:28:21 +00:00
if len ( mmrResults ) > 0 {
finalResults = mmrResults
logger . Infof ( ctx , "[Tool][GrepChunks] MMR completed: %d results selected" , len ( finalResults ) )
}
}
sort . Slice ( finalResults , func ( i , j int ) bool {
2026-06-03 12:51:03 +00:00
// Title matches rank above everything else (see chunkWithTitle.TitleMatch).
if finalResults [ i ] . TitleMatch != finalResults [ j ] . TitleMatch {
return finalResults [ i ] . TitleMatch
}
2025-11-27 09:56:53 +00:00
if finalResults [ i ] . MatchedPatterns != finalResults [ j ] . MatchedPatterns {
return finalResults [ i ] . MatchedPatterns > finalResults [ j ] . MatchedPatterns
}
2025-11-25 05:28:21 +00:00
if finalResults [ i ] . MatchScore != finalResults [ j ] . MatchScore {
return finalResults [ i ] . MatchScore > finalResults [ j ] . MatchScore
}
return finalResults [ i ] . ChunkIndex < finalResults [ j ] . ChunkIndex
} )
2026-04-21 11:19:57 +00:00
if len ( finalResults ) > limit {
finalResults = finalResults [ : limit ]
}
2025-11-27 09:56:53 +00:00
2026-06-15 16:49:38 +00:00
// chunk_results: per-chunk hits for UI detail (grouped by knowledge_id on the
// frontend). knowledge_results: pre-aggregated per document for summaries;
// document_count is the full distinct-document total even when the knowledge
// list is truncated for payload size.
2026-06-04 12:17:43 +00:00
chunkResults := buildGrepChunkResults ( finalResults , compiled )
2026-04-21 11:19:57 +00:00
aggregatedResults := t . aggregateByKnowledge ( finalResults , queries , compiled )
2026-06-15 16:49:38 +00:00
documentCount := len ( aggregatedResults )
knowledgeResultsForUI := aggregatedResults
const maxKnowledgeRows = 20
if len ( knowledgeResultsForUI ) > maxKnowledgeRows {
knowledgeResultsForUI = knowledgeResultsForUI [ : maxKnowledgeRows ]
2025-11-25 05:28:21 +00:00
}
2026-04-21 11:19:57 +00:00
output := t . formatOutput ( ctx , finalResults , queries , compiled )
2025-11-23 09:32:50 +00:00
return & types . ToolResult {
Success : true ,
Output : output ,
Data : map [ string ] interface { } {
2026-05-20 11:32:37 +00:00
"query" : query ,
"queries" : queries , // legacy alias for older frontends
"patterns" : queries , // legacy alias for older frontends
2026-06-04 12:17:43 +00:00
"chunk_results" : chunkResults ,
2026-06-15 16:49:38 +00:00
"knowledge_results" : knowledgeResultsForUI ,
2026-06-04 12:17:43 +00:00
"result_count" : len ( chunkResults ) ,
2026-06-15 16:49:38 +00:00
"document_count" : documentCount ,
2026-04-21 11:19:57 +00:00
"total_matches" : len ( finalResults ) ,
2026-06-29 08:54:08 +00:00
"knowledge_base_ids" : kbIDsForMeta ,
2026-04-21 11:19:57 +00:00
"limit" : limit ,
"max_results" : limit , // legacy alias
2025-11-23 09:32:50 +00:00
"display_type" : "grep_results" ,
} ,
} , nil
}
2025-11-25 05:28:21 +00:00
type chunkWithTitle struct {
types . Chunk
2025-11-28 08:17:52 +00:00
KnowledgeTitle string ` json:"knowledge_title" gorm:"column:knowledge_title" `
2026-04-21 11:19:57 +00:00
MatchScore float64 ` json:"match_score" gorm:"column:match_score" `
MatchedPatterns int ` json:"matched_patterns" `
2026-06-03 12:51:03 +00:00
// TitleMatch is true when the query regex matches the owning knowledge's
// TITLE (not just chunk body). A doc literally titled "图片素材" is the most
// on-topic hit for the query "图片素材", yet its body may mention the term far
// less than long FAQ docs that repeat it — so title hits are floated to the
// very top of both the per-chunk and per-knowledge ordering.
TitleMatch bool ` json:"title_match" `
TotalChunkCount int ` json:"total_chunk_count" gorm:"column:total_chunk_count" `
2025-11-25 05:28:21 +00:00
}
2026-04-21 11:19:57 +00:00
// regexOperatorForDialect returns the SQL operator used to apply a POSIX
// regular expression to a text column for the current dialect.
// PostgreSQL ~* is case-insensitive by default; MySQL/SQLite REGEXP relies on
// collation / driver extensions.
func ( t * GrepChunksTool ) regexOperatorForDialect ( ) string {
switch t . db . Dialector . Name ( ) {
case "postgres" :
return "~*"
default :
// MySQL, SQLite (with the go-sqlite3 REGEXP extension), or anything else
// that understands the REGEXP keyword.
return "REGEXP"
}
}
2026-06-29 10:21:17 +00:00
// resolveGrepScope splits search targets into full-KB, specific-knowledge, and
// tag-constrained KB scopes. Tag scopes stay as tag IDs so the chunk query can
// use the knowledge_tag_relations index instead of expanding a large tag into a
// huge knowledge_id IN list.
func ( t * GrepChunksTool ) resolveGrepScope ( ) ( fullKBIDs , knowledgeIDs [ ] string , tagTargets [ ] * types . SearchTarget ) {
2026-06-29 08:54:08 +00:00
seenKB := make ( map [ string ] bool )
seenKnowledge := make ( map [ string ] bool )
2026-06-29 10:21:17 +00:00
seenTagScope := make ( map [ string ] bool )
2026-06-29 08:54:08 +00:00
for _ , target := range t . searchTargets {
if target == nil || target . KnowledgeBaseID == "" {
continue
}
2026-07-27 02:54:47 +00:00
// A target that carries a resolved document whitelist is already the
// intersection of its mention and any tag scope, so it must be grepped
// by knowledge ID. Falling back to the tag branch would widen the
// search to every document carrying the tag.
targetKnowledgeIDs , targetTagIDs := searchTargetScope ( target )
2026-06-29 08:54:08 +00:00
switch {
2026-07-27 02:54:47 +00:00
case len ( targetTagIDs ) > 0 :
2026-06-29 08:54:08 +00:00
tenantID := target . TenantID
if tenantID == 0 {
tenantID = t . searchTargets . GetTenantIDForKB ( target . KnowledgeBaseID )
}
2026-07-27 02:54:47 +00:00
tagIDs := targetTagIDs
2026-06-29 10:21:17 +00:00
if len ( tagIDs ) == 0 || tenantID == 0 {
continue
2026-06-29 08:54:08 +00:00
}
2026-06-29 10:21:17 +00:00
scopeKey := fmt . Sprintf ( "%s:%d:%s" , target . KnowledgeBaseID , tenantID , strings . Join ( tagIDs , "\x00" ) )
if seenTagScope [ scopeKey ] {
continue
2026-06-29 08:54:08 +00:00
}
2026-06-29 10:21:17 +00:00
seenTagScope [ scopeKey ] = true
tagTargets = append ( tagTargets , & types . SearchTarget {
Type : types . SearchTargetTypeKnowledgeBase ,
KnowledgeBaseID : target . KnowledgeBaseID ,
TenantID : tenantID ,
TagIDs : tagIDs ,
} )
2026-07-27 02:54:47 +00:00
case len ( targetKnowledgeIDs ) > 0 :
for _ , kid := range targetKnowledgeIDs {
if ! seenKnowledge [ kid ] {
2026-07-26 16:59:38 +00:00
seenKnowledge [ kid ] = true
knowledgeIDs = append ( knowledgeIDs , kid )
}
}
2026-06-29 08:54:08 +00:00
default :
if ! seenKB [ target . KnowledgeBaseID ] {
seenKB [ target . KnowledgeBaseID ] = true
fullKBIDs = append ( fullKBIDs , target . KnowledgeBaseID )
}
}
}
2026-06-29 10:21:17 +00:00
return fullKBIDs , knowledgeIDs , tagTargets
2026-06-29 08:54:08 +00:00
}
2026-06-29 10:21:17 +00:00
func dedupNonEmptyStrings ( values [ ] string ) [ ] string {
seen := make ( map [ string ] bool , len ( values ) )
out := make ( [ ] string , 0 , len ( values ) )
for _ , value := range values {
if value == "" || seen [ value ] {
continue
}
seen [ value ] = true
out = append ( out , value )
2026-06-29 08:54:08 +00:00
}
2026-06-29 10:21:17 +00:00
return out
2026-06-29 08:54:08 +00:00
}
2026-06-29 09:17:38 +00:00
// scopeClause builds the SQL predicate restricting chunks to the active scope.
2026-06-29 10:21:17 +00:00
// Specific knowledge IDs, tag-constrained KB scopes, and full-KB (kb, tenant)
// pairs are OR'd together so a turn that mentions @KB + @tag + @file searches
2026-06-29 09:17:38 +00:00
// every requested scope. Returns ("", nil) when no usable scope exists.
2026-06-29 10:21:17 +00:00
func scopeClause (
kbIDs , knowledgeIDs [ ] string ,
tagTargets [ ] * types . SearchTarget ,
kbTenantMap map [ string ] uint64 ,
) ( string , [ ] interface { } ) {
2026-06-29 09:17:38 +00:00
var clauses [ ] string
var args [ ] interface { }
if len ( knowledgeIDs ) > 0 {
clauses = append ( clauses , "chunks.knowledge_id IN ?" )
args = append ( args , knowledgeIDs )
}
2026-06-29 10:21:17 +00:00
for _ , target := range tagTargets {
if target == nil || target . KnowledgeBaseID == "" || len ( target . TagIDs ) == 0 {
continue
}
tenantID := target . TenantID
if tenantID == 0 {
tenantID = kbTenantMap [ target . KnowledgeBaseID ]
}
if tenantID == 0 {
continue
}
clauses = append ( clauses ,
"(chunks.knowledge_base_id = ? AND chunks.tenant_id = ? AND EXISTS (" +
"SELECT 1 FROM knowledge_tag_relations ktr " +
"WHERE ktr.knowledge_id = chunks.knowledge_id AND ktr.tag_id IN ?" +
"))" )
args = append ( args , target . KnowledgeBaseID , tenantID , target . TagIDs )
}
2026-06-29 09:17:38 +00:00
for _ , kbID := range kbIDs {
tenantID := kbTenantMap [ kbID ]
if tenantID == 0 {
continue
}
clauses = append ( clauses , "(chunks.knowledge_base_id = ? AND chunks.tenant_id = ?)" )
args = append ( args , kbID , tenantID )
}
if len ( clauses ) == 0 {
return "" , nil
}
return "(" + strings . Join ( clauses , " OR " ) + ")" , args
}
2026-04-21 11:19:57 +00:00
// searchChunks performs the database search using regex queries.
2025-11-23 09:32:50 +00:00
func ( t * GrepChunksTool ) searchChunks (
ctx context . Context ,
2026-04-21 11:19:57 +00:00
queries [ ] string ,
2025-11-23 09:32:50 +00:00
kbIDs [ ] string ,
2025-12-19 14:17:56 +00:00
knowledgeIDs [ ] string ,
2026-06-29 10:21:17 +00:00
tagTargets [ ] * types . SearchTarget ,
2026-01-30 08:28:01 +00:00
kbTenantMap map [ string ] uint64 ,
2026-04-21 11:19:57 +00:00
) ( [ ] chunkWithTitle , error ) {
2026-06-29 10:21:17 +00:00
if len ( kbIDs ) == 0 && len ( knowledgeIDs ) == 0 && len ( tagTargets ) == 0 {
logger . Warnf ( ctx , "[Tool][GrepChunks] No kbIDs, knowledgeIDs, or tag scopes specified, returning empty results" )
2026-04-21 11:19:57 +00:00
return nil , nil
2025-12-23 08:56:30 +00:00
}
2026-01-30 08:28:01 +00:00
2026-04-21 11:19:57 +00:00
regexOp := t . regexOperatorForDialect ( )
2026-03-18 15:49:46 +00:00
2026-04-21 11:19:57 +00:00
query := t . db . WithContext ( ctx ) . Table ( "chunks" ) .
2026-03-18 15:49:46 +00:00
Select ( "chunks.id, chunks.content, chunks.chunk_index, chunks.knowledge_id, " +
2026-06-04 06:21:50 +00:00
"chunks.knowledge_base_id, chunks.chunk_type, chunks.metadata, chunks.created_at, " +
2026-03-24 14:35:29 +00:00
"knowledges.title as knowledge_title" ) .
2026-03-18 15:49:46 +00:00
Joins ( "JOIN knowledges ON chunks.knowledge_id = knowledges.id" ) .
2025-11-23 09:32:50 +00:00
Where ( "chunks.is_enabled = ?" , true ) .
Where ( "chunks.deleted_at IS NULL" ) .
Where ( "knowledges.deleted_at IS NULL" )
2026-06-29 10:21:17 +00:00
// Combine specific knowledge IDs, tag scopes, and full-KB scopes with OR so
// that mixing @KB with @tag/@file searches BOTH, mirroring knowledge_search's
// concurrent fan-out instead of dropping one side.
scopeSQL , scopeArgs := scopeClause ( kbIDs , knowledgeIDs , tagTargets , kbTenantMap )
2026-06-29 09:17:38 +00:00
if scopeSQL == "" {
logger . Warnf ( ctx , "[Tool][GrepChunks] No valid scope (kb-tenant pairs / knowledge IDs)" )
return nil , nil
2025-11-23 09:32:50 +00:00
}
2026-06-29 10:21:17 +00:00
logger . Infof ( ctx , "[Tool][GrepChunks] Scope: %d knowledge IDs, %d tag scopes, %d KBs" ,
len ( knowledgeIDs ) , len ( tagTargets ) , len ( kbIDs ) )
2026-06-29 09:17:38 +00:00
query = query . Where ( scopeSQL , scopeArgs ... )
2025-11-23 09:32:50 +00:00
2026-04-21 11:19:57 +00:00
// For MySQL/SQLite REGEXP case-insensitivity we rely on the column's default
// collation (utf8mb4_general_ci etc.) OR the driver's REGEXP implementation,
// which mirrors what wiki_search already ships in this codebase.
var regexConditions [ ] string
var regexArgs [ ] interface { }
for _ , q := range queries {
2026-06-03 12:51:03 +00:00
// Match the regex against either the chunk body OR the owning
// knowledge's title, so a doc whose title matches (e.g. titled
// "图片素材") surfaces even when its body rarely repeats the term.
regexConditions = append ( regexConditions ,
fmt . Sprintf ( "(chunks.content %s ? OR knowledges.title %s ?)" , regexOp , regexOp ) )
regexArgs = append ( regexArgs , q , q )
2025-11-23 09:32:50 +00:00
}
2026-04-21 11:19:57 +00:00
query = query . Where ( "(" + strings . Join ( regexConditions , " OR " ) + ")" , regexArgs ... )
2025-11-23 09:32:50 +00:00
2026-03-18 15:49:46 +00:00
const maxFetchLimit = 500
2025-11-23 09:32:50 +00:00
2025-11-25 05:28:21 +00:00
var results [ ] chunkWithTitle
2026-03-18 15:49:46 +00:00
if err := query . Order ( "chunks.created_at DESC" ) . Limit ( maxFetchLimit ) . Find ( & results ) . Error ; err != nil {
2025-11-23 09:32:50 +00:00
logger . Errorf ( ctx , "[Tool][GrepChunks] Failed to fetch results: %v" , err )
2026-04-21 11:19:57 +00:00
return nil , err
2025-11-23 09:32:50 +00:00
}
2026-03-24 14:35:29 +00:00
if len ( results ) > 0 {
knowledgeIDSet := make ( map [ string ] struct { } )
for _ , r := range results {
if r . KnowledgeID != "" {
knowledgeIDSet [ r . KnowledgeID ] = struct { } { }
}
}
uniqueKnowledgeIDs := make ( [ ] string , 0 , len ( knowledgeIDSet ) )
for kid := range knowledgeIDSet {
uniqueKnowledgeIDs = append ( uniqueKnowledgeIDs , kid )
}
type countRow struct {
KnowledgeID string ` gorm:"column:knowledge_id" `
Count int ` gorm:"column:cnt" `
}
var counts [ ] countRow
if err := t . db . WithContext ( ctx ) . Table ( "chunks" ) .
Select ( "knowledge_id, COUNT(*) AS cnt" ) .
Where ( "knowledge_id IN ?" , uniqueKnowledgeIDs ) .
Where ( "is_enabled = ?" , true ) .
Where ( "deleted_at IS NULL" ) .
Group ( "knowledge_id" ) .
Find ( & counts ) . Error ; err != nil {
logger . Warnf ( ctx , "[Tool][GrepChunks] Failed to fetch chunk counts, skipping: %v" , err )
} else {
countMap := make ( map [ string ] int , len ( counts ) )
for _ , c := range counts {
countMap [ c . KnowledgeID ] = c . Count
}
for i := range results {
results [ i ] . TotalChunkCount = countMap [ results [ i ] . KnowledgeID ]
}
}
}
2026-04-21 11:19:57 +00:00
return results , nil
2025-11-23 09:32:50 +00:00
}
2026-04-21 11:19:57 +00:00
// formatOutput emits per-chunk XML with <match_snippet> and <query_hit>
// elements, mirroring the wiki_search output shape. Chunks that were already
// surfaced by a previous call to this tool in the same session are rendered
// compactly with `already_seen="true"` so the LLM doesn't waste context
// re-reading the same snippet.
2025-11-23 09:32:50 +00:00
func ( t * GrepChunksTool ) formatOutput (
ctx context . Context ,
2026-04-21 11:19:57 +00:00
results [ ] chunkWithTitle ,
queries [ ] string ,
compiled [ ] * regexp . Regexp ,
2025-11-23 09:32:50 +00:00
) string {
2026-04-16 15:25:25 +00:00
var b strings . Builder
2025-11-23 09:32:50 +00:00
2026-04-21 11:19:57 +00:00
b . WriteString ( fmt . Sprintf ( "<grep_results chunk_count=\"%d\">\n" , len ( results ) ) )
for _ , q := range queries {
b . WriteString ( fmt . Sprintf ( "<query>%s</query>\n" , xmlEscape ( q ) ) )
2025-11-23 09:32:50 +00:00
}
if len ( results ) == 0 {
2026-04-16 15:25:25 +00:00
b . WriteString ( "</grep_results>" )
return b . String ( )
2025-11-23 09:32:50 +00:00
}
2026-04-21 11:19:57 +00:00
for _ , r := range results {
counts := countRegexHits ( r . Content , compiled , queries )
2026-06-04 12:17:43 +00:00
snippet := extractChunkMatchSnippet ( & r . Chunk , compiled )
2026-04-21 11:19:57 +00:00
2026-06-04 12:17:43 +00:00
extraAttr := ""
2026-06-04 06:21:50 +00:00
if q := faqStandardQuestion ( & r . Chunk ) ; q != "" {
2026-06-04 12:17:43 +00:00
extraAttr = fmt . Sprintf ( " faq_question=\"%s\"" , xmlEscape ( q ) )
2026-06-04 06:21:50 +00:00
}
2026-06-04 12:17:43 +00:00
isFAQ := r . ChunkType == types . ChunkTypeFAQ
2026-06-04 06:21:50 +00:00
2026-04-21 11:19:57 +00:00
t . mu . Lock ( )
seen := t . seenChunks [ r . ID ]
t . seenChunks [ r . ID ] = true
t . mu . Unlock ( )
2026-06-04 12:17:43 +00:00
if isFAQ {
if seen {
fmt . Fprintf ( & b ,
"<faq faq_id=\"%s\" knowledge_title=\"%s\"%s index=\"%d\" score=\"%.3f\" already_seen=\"true\">\n" ,
xmlEscape ( r . ID ) , xmlEscape ( r . KnowledgeTitle ) ,
extraAttr , r . ChunkIndex , r . MatchScore )
} else {
fmt . Fprintf ( & b ,
"<faq faq_id=\"%s\" knowledge_title=\"%s\"%s index=\"%d\" score=\"%.3f\">\n" ,
xmlEscape ( r . ID ) , xmlEscape ( r . KnowledgeTitle ) ,
extraAttr , r . ChunkIndex , r . MatchScore )
2026-04-16 15:25:25 +00:00
}
2026-06-04 12:17:43 +00:00
} else if seen {
fmt . Fprintf ( & b ,
"<chunk chunk_id=\"%s\" knowledge_id=\"%s\" knowledge_title=\"%s\"%s chunk_index=\"%d\" score=\"%.3f\" already_seen=\"true\">\n" ,
xmlEscape ( r . ID ) , xmlEscape ( r . KnowledgeID ) , xmlEscape ( r . KnowledgeTitle ) ,
extraAttr , r . ChunkIndex , r . MatchScore )
} else {
fmt . Fprintf ( & b ,
"<chunk chunk_id=\"%s\" knowledge_id=\"%s\" knowledge_title=\"%s\"%s chunk_index=\"%d\" score=\"%.3f\">\n" ,
xmlEscape ( r . ID ) , xmlEscape ( r . KnowledgeID ) , xmlEscape ( r . KnowledgeTitle ) ,
extraAttr , r . ChunkIndex , r . MatchScore )
2025-11-23 09:32:50 +00:00
}
2026-04-21 11:19:57 +00:00
for _ , q := range queries {
if c := counts [ q ] ; c > 0 {
b . WriteString ( fmt . Sprintf ( "<query_hit query=\"%s\" count=\"%d\" />\n" ,
xmlEscape ( q ) , c ) )
}
}
2026-06-04 12:17:43 +00:00
if seen {
b . WriteString ( "<note>(snippet omitted, already returned in a previous grep_chunks call this session)</note>\n" )
} else if snippet != "" {
2026-04-21 11:19:57 +00:00
b . WriteString ( fmt . Sprintf ( "<match_snippet>%s</match_snippet>\n" , xmlEscape ( snippet ) ) )
}
2026-06-04 12:17:43 +00:00
if isFAQ {
b . WriteString ( "</faq>\n" )
} else {
b . WriteString ( "</chunk>\n" )
}
2025-11-23 09:32:50 +00:00
}
2026-04-16 15:25:25 +00:00
b . WriteString ( "</grep_results>" )
2026-04-21 11:19:57 +00:00
_ = ctx
2026-04-16 15:25:25 +00:00
return b . String ( )
2025-11-23 09:32:50 +00:00
}
2025-11-27 09:56:53 +00:00
type knowledgeAggregation struct {
2026-06-04 06:21:50 +00:00
KnowledgeID string ` json:"knowledge_id" `
KnowledgeBaseID string ` json:"knowledge_base_id" `
KnowledgeTitle string ` json:"knowledge_title" `
// FAQQuestion is the standard question of the first matched FAQ entry in
// this knowledge. FAQ entries share the owning knowledge's title, so the
// frontend uses this to give the row a distinct, human-readable label.
FAQQuestion string ` json:"faq_question,omitempty" `
2026-06-03 12:51:03 +00:00
TitleMatch bool ` json:"title_match" `
2025-11-27 09:56:53 +00:00
ChunkHitCount int ` json:"chunk_hit_count" `
2025-11-28 07:32:51 +00:00
TotalChunkCount int ` json:"total_chunk_count" `
2025-11-27 09:56:53 +00:00
PatternCounts map [ string ] int ` json:"pattern_counts" `
TotalPatternHits int ` json:"total_pattern_hits" `
DistinctPatterns int ` json:"distinct_patterns" `
2026-06-03 13:43:11 +00:00
MatchSnippet string ` json:"match_snippet,omitempty" `
2025-11-27 09:56:53 +00:00
}
2025-11-23 09:32:50 +00:00
2026-04-21 11:19:57 +00:00
func ( t * GrepChunksTool ) aggregateByKnowledge (
results [ ] chunkWithTitle ,
queries [ ] string ,
compiled [ ] * regexp . Regexp ,
) [ ] knowledgeAggregation {
2025-11-27 09:56:53 +00:00
if len ( results ) == 0 {
return nil
2025-11-23 09:32:50 +00:00
}
2026-04-21 11:19:57 +00:00
queryKeys := make ( [ ] string , 0 , len ( queries ) )
for _ , q := range queries {
if strings . TrimSpace ( q ) == "" {
2025-11-27 09:56:53 +00:00
continue
2025-11-23 09:32:50 +00:00
}
2026-04-21 11:19:57 +00:00
queryKeys = append ( queryKeys , q )
2025-11-23 09:32:50 +00:00
}
2025-11-27 09:56:53 +00:00
aggregated := make ( map [ string ] * knowledgeAggregation )
for _ , chunk := range results {
knowledgeID := chunk . KnowledgeID
if knowledgeID == "" {
knowledgeID = fmt . Sprintf ( "chunk-%s" , chunk . ID )
}
2025-11-23 09:32:50 +00:00
2025-11-27 09:56:53 +00:00
if _ , ok := aggregated [ knowledgeID ] ; ! ok {
title := chunk . KnowledgeTitle
if strings . TrimSpace ( title ) == "" {
title = "Untitled"
}
aggregated [ knowledgeID ] = & knowledgeAggregation {
KnowledgeID : knowledgeID ,
KnowledgeBaseID : chunk . KnowledgeBaseID ,
KnowledgeTitle : title ,
2025-11-28 07:32:51 +00:00
TotalChunkCount : chunk . TotalChunkCount ,
2026-04-21 11:19:57 +00:00
PatternCounts : make ( map [ string ] int , len ( queryKeys ) ) ,
2025-11-27 09:56:53 +00:00
}
2026-04-21 11:19:57 +00:00
for _ , qKey := range queryKeys {
aggregated [ knowledgeID ] . PatternCounts [ qKey ] = 0
2025-11-27 09:56:53 +00:00
}
2025-11-23 09:32:50 +00:00
}
2025-11-27 09:56:53 +00:00
entry := aggregated [ knowledgeID ]
entry . ChunkHitCount ++
2026-06-03 12:51:03 +00:00
if chunk . TitleMatch {
entry . TitleMatch = true
}
2026-06-04 06:21:50 +00:00
if entry . FAQQuestion == "" {
if q := faqStandardQuestion ( & chunk . Chunk ) ; q != "" {
entry . FAQQuestion = q
}
}
2026-06-03 13:43:11 +00:00
if entry . MatchSnippet == "" {
2026-06-04 12:17:43 +00:00
if snippet := extractChunkMatchSnippet ( & chunk . Chunk , compiled ) ; snippet != "" {
2026-06-03 13:43:11 +00:00
entry . MatchSnippet = snippet
}
}
2025-11-23 09:32:50 +00:00
2026-04-21 11:19:57 +00:00
occurrences := countRegexHits ( chunk . Content , compiled , queryKeys )
for _ , q := range queryKeys {
count := occurrences [ q ]
2025-11-27 09:56:53 +00:00
if count == 0 {
continue
}
2026-04-21 11:19:57 +00:00
entry . PatternCounts [ q ] += count
2025-11-27 09:56:53 +00:00
entry . TotalPatternHits += count
}
2025-11-23 09:32:50 +00:00
}
2025-11-27 09:56:53 +00:00
resultSlice := make ( [ ] knowledgeAggregation , 0 , len ( aggregated ) )
for _ , entry := range aggregated {
distinct := 0
for _ , count := range entry . PatternCounts {
if count > 0 {
distinct ++
}
}
entry . DistinctPatterns = distinct
resultSlice = append ( resultSlice , * entry )
2025-11-23 09:32:50 +00:00
}
2025-11-27 09:56:53 +00:00
sort . Slice ( resultSlice , func ( i , j int ) bool {
2026-06-03 12:51:03 +00:00
// A knowledge whose TITLE matches the query is the most on-topic hit
// and always ranks first, regardless of body keyword frequency.
if resultSlice [ i ] . TitleMatch != resultSlice [ j ] . TitleMatch {
return resultSlice [ i ] . TitleMatch
}
2025-11-27 09:56:53 +00:00
if resultSlice [ i ] . DistinctPatterns != resultSlice [ j ] . DistinctPatterns {
return resultSlice [ i ] . DistinctPatterns > resultSlice [ j ] . DistinctPatterns
}
if resultSlice [ i ] . TotalPatternHits != resultSlice [ j ] . TotalPatternHits {
return resultSlice [ i ] . TotalPatternHits > resultSlice [ j ] . TotalPatternHits
}
if resultSlice [ i ] . ChunkHitCount != resultSlice [ j ] . ChunkHitCount {
return resultSlice [ i ] . ChunkHitCount > resultSlice [ j ] . ChunkHitCount
}
return resultSlice [ i ] . KnowledgeTitle < resultSlice [ j ] . KnowledgeTitle
} )
return resultSlice
2025-11-23 09:32:50 +00:00
}
2026-06-04 12:17:43 +00:00
type grepChunkResult struct {
ChunkID string ` json:"chunk_id,omitempty" `
FAQID string ` json:"faq_id,omitempty" `
KnowledgeID string ` json:"knowledge_id" `
KnowledgeBaseID string ` json:"knowledge_base_id" `
KnowledgeTitle string ` json:"knowledge_title" `
ChunkType string ` json:"chunk_type" `
Index int ` json:"index,omitempty" `
ChunkIndex int ` json:"chunk_index,omitempty" `
FAQQuestion string ` json:"faq_question,omitempty" `
TitleMatch bool ` json:"title_match,omitempty" `
MatchSnippet string ` json:"match_snippet,omitempty" `
Score float64 ` json:"score" `
}
func buildGrepChunkResults ( results [ ] chunkWithTitle , compiled [ ] * regexp . Regexp ) [ ] grepChunkResult {
if len ( results ) == 0 {
return nil
}
out := make ( [ ] grepChunkResult , 0 , len ( results ) )
for _ , r := range results {
item := grepChunkResult {
KnowledgeID : r . KnowledgeID ,
KnowledgeBaseID : r . KnowledgeBaseID ,
KnowledgeTitle : r . KnowledgeTitle ,
ChunkType : string ( r . ChunkType ) ,
TitleMatch : r . TitleMatch ,
MatchSnippet : extractChunkMatchSnippet ( & r . Chunk , compiled ) ,
Score : r . MatchScore ,
}
if r . ChunkType == types . ChunkTypeFAQ {
item . FAQID = r . ID
item . Index = r . ChunkIndex
item . FAQQuestion = faqStandardQuestion ( & r . Chunk )
} else {
item . ChunkID = r . ID
item . ChunkIndex = r . ChunkIndex
}
out = append ( out , item )
}
return out
}
2026-06-03 12:51:03 +00:00
// regexMatchesAny reports whether text matches at least one of the compiled
// patterns. Used to flag title hits without counting occurrences.
func regexMatchesAny ( text string , compiled [ ] * regexp . Regexp ) bool {
if text == "" || len ( compiled ) == 0 {
return false
}
for _ , re := range compiled {
if re != nil && re . MatchString ( text ) {
return true
}
}
return false
}
2026-04-21 11:19:57 +00:00
// countRegexHits returns the total number of matches per (compiled) pattern
// within content, keyed by the original (uncompiled) pattern string.
func countRegexHits ( content string , compiled [ ] * regexp . Regexp , patterns [ ] string ) map [ string ] int {
2025-11-27 09:56:53 +00:00
counts := make ( map [ string ] int , len ( patterns ) )
2026-04-21 11:19:57 +00:00
if content == "" || len ( compiled ) == 0 {
2025-11-27 09:56:53 +00:00
return counts
2025-11-23 09:32:50 +00:00
}
2026-04-21 11:19:57 +00:00
for i , re := range compiled {
if re == nil {
2025-11-27 09:56:53 +00:00
continue
2025-11-23 09:32:50 +00:00
}
2026-04-21 11:19:57 +00:00
matches := re . FindAllStringIndex ( content , - 1 )
counts [ patterns [ i ] ] = len ( matches )
2025-11-23 09:32:50 +00:00
}
2025-11-27 09:56:53 +00:00
return counts
}
2025-11-23 09:32:50 +00:00
2026-06-04 12:17:43 +00:00
// extractChunkMatchSnippet returns a preview for tool output. FAQ chunks only
// surface the matched question plus answers from metadata (answers are not
// stored in chunk content for question_only index mode). Other chunk types
// use regex context around the first body match.
func extractChunkMatchSnippet ( chunk * types . Chunk , compiled [ ] * regexp . Regexp ) string {
if chunk != nil && chunk . ChunkType == types . ChunkTypeFAQ {
if s := faqMatchSnippet ( chunk , compiled ) ; s != "" {
return s
}
}
if chunk == nil {
return ""
}
return extractSnippetRegex ( chunk . Content , compiled )
}
2026-04-21 11:19:57 +00:00
// extractSnippetRegex returns a short context snippet around the earliest
// regex match across any of the provided compiled patterns. Result is
// compressed to a single line and bounded in length on both sides of the
// match to keep the XML output concise.
func extractSnippetRegex ( content string , compiled [ ] * regexp . Regexp ) string {
if content == "" || len ( compiled ) == 0 {
return ""
2025-11-23 09:32:50 +00:00
}
2026-04-21 11:19:57 +00:00
earliest := - 1
earliestEnd := - 1
for _ , re := range compiled {
if re == nil {
continue
}
loc := re . FindStringIndex ( content )
if loc == nil {
continue
}
if earliest < 0 || loc [ 0 ] < earliest {
earliest = loc [ 0 ]
earliestEnd = loc [ 1 ]
2025-11-27 09:56:53 +00:00
}
2025-11-23 09:32:50 +00:00
}
2026-04-21 11:19:57 +00:00
if earliest < 0 {
return ""
}
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
}
matchRunes := [ ] rune ( matchStr )
2026-06-04 12:17:43 +00:00
if len ( matchRunes ) > snippetMaxMatchRunes {
matchRunes = append ( matchRunes [ : snippetMaxMatchRunes ] , [ ] rune ( "..." ) ... )
2026-04-21 11:19:57 +00:00
}
snippet := string ( beforeRunes ) + string ( matchRunes ) + string ( afterRunes )
snippet = strings . ReplaceAll ( snippet , "\n" , " " )
for strings . Contains ( snippet , " " ) {
snippet = strings . ReplaceAll ( snippet , " " , " " )
}
2026-06-04 12:17:43 +00:00
snippet = strings . TrimSpace ( snippet )
if len ( [ ] rune ( snippet ) ) > snippetMaxTotalRunes {
snippet = string ( [ ] rune ( snippet ) [ : snippetMaxTotalRunes ] ) + "..."
}
return "... " + snippet + " ..."
2026-04-21 11:19:57 +00:00
}
// xmlEscape replaces characters that would break simple XML attribute /
// element values. It is intentionally minimal because the rendered output is
// consumed by the LLM (forgiving parser) rather than a strict XML processor.
func xmlEscape ( s string ) string {
replacer := strings . NewReplacer (
"&" , "&" ,
"<" , "<" ,
">" , ">" ,
"\"" , """ ,
"'" , "'" ,
)
return replacer . Replace ( s )
2025-11-23 09:32:50 +00:00
}
2025-11-25 05:28:21 +00:00
// 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 {
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 ) )
}
dup := false
for _ , k := range keys {
if seen [ k ] {
dup = true
break
}
}
if dup {
continue
}
sig := t . buildContentSignature ( r . Content )
if sig != "" {
if contentSig [ sig ] {
continue
}
contentSig [ sig ] = true
}
for _ , k := range keys {
seen [ k ] = true
}
uniqueResults = append ( uniqueResults , r )
}
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 )
}
}
2026-04-21 11:19:57 +00:00
_ = ctx
2025-11-25 05:28:21 +00:00
return deduplicated
}
// buildContentSignature creates a normalized signature for content to detect near-duplicates
func ( t * GrepChunksTool ) 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-04-21 11:19:57 +00:00
// scoreChunks calculates match scores for chunks based on regex matches.
2025-11-28 08:17:52 +00:00
func ( t * GrepChunksTool ) scoreChunks (
ctx context . Context ,
results [ ] chunkWithTitle ,
2026-04-21 11:19:57 +00:00
compiled [ ] * regexp . Regexp ,
2025-11-28 08:17:52 +00:00
) [ ] chunkWithTitle {
2025-11-25 05:28:21 +00:00
scored := make ( [ ] chunkWithTitle , len ( results ) )
for i := range results {
scored [ i ] = results [ i ]
2026-04-21 11:19:57 +00:00
score , patternCount := t . calculateMatchScore ( results [ i ] . Content , compiled )
2026-06-03 12:51:03 +00:00
// Title-aware boost: when the owning knowledge's TITLE matches the
// query, treat the chunk as highly relevant regardless of how often
// the body repeats the term. The boost keeps such chunks alive through
// MMR selection; TitleMatch is the primary sort key downstream so they
// also land at the very top of the final ordering.
if regexMatchesAny ( results [ i ] . KnowledgeTitle , compiled ) {
scored [ i ] . TitleMatch = true
score = math . Min ( score + 0.5 , 1.0 )
if patternCount == 0 {
// Title-only recall (body never matched the regex) still counts
// as one matched pattern so it isn't sorted below true zeros.
patternCount = 1
}
}
2025-11-27 09:56:53 +00:00
scored [ i ] . MatchScore = score
scored [ i ] . MatchedPatterns = patternCount
2025-11-25 05:28:21 +00:00
}
2026-04-21 11:19:57 +00:00
_ = ctx
2025-11-25 05:28:21 +00:00
return scored
}
2026-04-21 11:19:57 +00:00
// calculateMatchScore counts how many regex patterns match the content and
// applies a small boost for earlier match positions.
func ( t * GrepChunksTool ) calculateMatchScore ( content string , compiled [ ] * regexp . Regexp ) ( float64 , int ) {
if content == "" || len ( compiled ) == 0 {
2025-11-27 09:56:53 +00:00
return 0.0 , 0
2025-11-25 05:28:21 +00:00
}
matchCount := 0
earliestPos := len ( content )
2026-04-21 11:19:57 +00:00
for _ , re := range compiled {
if re == nil {
continue
}
loc := re . FindStringIndex ( content )
if loc == nil {
continue
}
matchCount ++
if loc [ 0 ] < earliestPos {
earliestPos = loc [ 0 ]
2025-11-25 05:28:21 +00:00
}
}
2026-04-21 11:19:57 +00:00
if matchCount == 0 {
return 0.0 , 0
}
baseScore := float64 ( matchCount ) / float64 ( len ( compiled ) )
2025-11-25 05:28:21 +00:00
positionBonus := 0.0
if earliestPos < len ( content ) {
positionRatio := 1.0 - float64 ( earliestPos ) / float64 ( len ( content ) )
positionBonus = positionRatio * 0.1
}
2025-11-27 09:56:53 +00:00
return math . Min ( baseScore + positionBonus , 1.0 ) , matchCount
2025-11-25 05:28:21 +00:00
}
// applyMMR applies Maximal Marginal Relevance algorithm to reduce redundancy
func ( t * GrepChunksTool ) applyMMR (
ctx context . Context ,
results [ ] chunkWithTitle ,
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 )
2026-04-21 11:19:57 +00:00
selectedTokenSets := make ( [ ] map [ string ] struct { } , 0 , k )
2026-02-06 02:48:00 +00:00
2025-11-25 05:28:21 +00:00
candidates := make ( [ ] chunkWithTitle , len ( results ) )
copy ( candidates , results )
tokenSets := make ( [ ] map [ string ] struct { } , len ( candidates ) )
for i , r := range candidates {
tokenSets [ i ] = t . tokenizeSimple ( r . Content )
}
for len ( selected ) < k && len ( candidates ) > 0 {
bestIdx := 0
bestScore := - 1.0
for i , r := range candidates {
relevance := r . MatchScore
redundancy := 0.0
2026-02-06 02:48:00 +00:00
for _ , selectedTS := range selectedTokenSets {
redundancy = math . Max ( redundancy , t . jaccard ( tokenSets [ i ] , selectedTS ) )
2025-11-25 05:28:21 +00:00
}
mmr := lambda * relevance - ( 1.0 - lambda ) * redundancy
if mmr > bestScore {
bestScore = mmr
bestIdx = i
}
}
selected = append ( selected , candidates [ bestIdx ] )
2026-02-06 02:48:00 +00:00
selectedTokenSets = append ( selectedTokenSets , tokenSets [ bestIdx ] )
2026-02-06 02:49:05 +00:00
last := len ( candidates ) - 1
candidates [ bestIdx ] = candidates [ last ]
tokenSets [ bestIdx ] = tokenSets [ last ]
candidates = candidates [ : last ]
tokenSets = tokenSets [ : last ]
2025-11-25 05:28:21 +00:00
}
return selected
}
// tokenizeSimple tokenizes text into a set of words (simple whitespace-based)
func ( t * GrepChunksTool ) 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
}
// jaccard calculates Jaccard similarity between two token sets
func ( t * GrepChunksTool ) 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
}