feat: Add agent configuration and cleanup scripts for database migrations

This commit is contained in:
wizardchen
2025-11-05 23:18:44 +08:00
parent ae9d0778e9
commit 4fa3adbf3b
126 changed files with 22506 additions and 629 deletions
+456
View File
@@ -0,0 +1,456 @@
package tools
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"regexp"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"gorm.io/gorm"
)
// DatabaseQueryTool allows AI to query the database with auto-injected tenant_id for security
type DatabaseQueryTool struct {
BaseTool
db *gorm.DB
tenantID uint
}
// NewDatabaseQueryTool creates a new database query tool
func NewDatabaseQueryTool(db *gorm.DB, tenantID uint) *DatabaseQueryTool {
description := `Execute SQL queries to retrieve information from the database.
## Security Features
- Automatic tenant_id injection: All queries are automatically filtered by the logged-in user's tenant_id
- Read-only queries: Only SELECT statements are allowed
- Safe tables: Only allow queries on authorized tables
## Available Tables and Columns
### knowledge_bases
- id (VARCHAR): Knowledge base ID
- name (VARCHAR): Knowledge base name
- description (TEXT): Description
- tenant_id (INTEGER): Owner tenant ID
- embedding_model_id, summary_model_id, rerank_model_id, vlm_model_id (VARCHAR): Model IDs
- created_at, updated_at (TIMESTAMP)
### knowledges (documents)
- id (VARCHAR): Document ID
- tenant_id (INTEGER): Owner tenant ID
- knowledge_base_id (VARCHAR): Parent knowledge base ID
- type (VARCHAR): Document type
- title (VARCHAR): Document title
- description (TEXT): Description
- source (VARCHAR): Source location
- parse_status (VARCHAR): Processing status (unprocessed/processing/completed/failed)
- enable_status (VARCHAR): Enable status (enabled/disabled)
- file_name, file_type (VARCHAR): File information
- file_size, storage_size (BIGINT): Size in bytes
- created_at, updated_at, processed_at (TIMESTAMP)
### chunks
- id (VARCHAR): Chunk ID
- tenant_id (INTEGER): Owner tenant ID
- knowledge_base_id (VARCHAR): Parent knowledge base ID
- knowledge_id (VARCHAR): Parent document ID
- content (TEXT): Chunk content
- chunk_index (INTEGER): Index in document
- is_enabled (BOOLEAN): Enable status
- chunk_type (VARCHAR): Type (text/image/table)
- created_at, updated_at (TIMESTAMP)
## Usage Examples
Query knowledge base information:
{
"sql": "SELECT id, name, description FROM knowledge_bases ORDER BY created_at DESC LIMIT 10"
}
Count documents by status:
{
"sql": "SELECT parse_status, COUNT(*) as count FROM knowledges GROUP BY parse_status"
}
Find recent sessions:
{
"sql": "SELECT id, title, created_at FROM sessions ORDER BY created_at DESC LIMIT 5"
}
Get storage usage:
{
"sql": "SELECT SUM(storage_size) as total_storage FROM knowledges"
}
Join knowledge bases and documents:
{
"sql": "SELECT kb.name as kb_name, COUNT(k.id) as doc_count FROM knowledge_bases kb LEFT JOIN knowledges k ON kb.id = k.knowledge_base_id GROUP BY kb.id, kb.name"
}
## Important Notes
- DO NOT include tenant_id in WHERE clause - it's automatically added
- Only SELECT queries are allowed
- Limit results with LIMIT clause for better performance
- Use appropriate JOINs when querying across tables
- All timestamps are in UTC with time zone`
return &DatabaseQueryTool{
BaseTool: NewBaseTool("database_query", description),
db: db,
tenantID: tenantID,
}
}
// Parameters returns the JSON schema for the tool's parameters
func (t *DatabaseQueryTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"sql": map[string]interface{}{
"type": "string",
"description": "The SELECT SQL query to execute. DO NOT include tenant_id condition - it will be automatically added for security.",
},
},
"required": []string{"sql"},
}
}
// Execute executes the database query tool
func (t *DatabaseQueryTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][DatabaseQuery] Execute started")
// Extract SQL from args
sqlQuery, ok := args["sql"].(string)
if !ok || sqlQuery == "" {
logger.Errorf(ctx, "[Tool][DatabaseQuery] Missing or invalid SQL parameter")
return &types.ToolResult{
Success: false,
Error: "Missing or invalid 'sql' parameter",
}, fmt.Errorf("missing sql parameter")
}
logger.Infof(ctx, "[Tool][DatabaseQuery] Original SQL query:\n%s", sqlQuery)
logger.Infof(ctx, "[Tool][DatabaseQuery] Tenant ID: %d", t.tenantID)
// Validate and secure the SQL query
logger.Debugf(ctx, "[Tool][DatabaseQuery] Validating and securing SQL...")
securedSQL, err := t.validateAndSecureSQL(sqlQuery)
if err != nil {
logger.Errorf(ctx, "[Tool][DatabaseQuery] SQL validation failed: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("SQL validation failed: %v", err),
}, err
}
logger.Infof(ctx, "[Tool][DatabaseQuery] Secured SQL query:\n%s", securedSQL)
logger.Infof(ctx, "Executing secured SQL query - original: %s, secured: %s, tenant_id: %d",
sqlQuery, securedSQL, t.tenantID)
// Execute the query
logger.Infof(ctx, "[Tool][DatabaseQuery] Executing query against database...")
rows, err := t.db.WithContext(ctx).Raw(securedSQL).Rows()
if err != nil {
logger.Errorf(ctx, "[Tool][DatabaseQuery] Query execution failed: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Query execution failed: %v", err),
}, err
}
defer rows.Close()
logger.Debugf(ctx, "[Tool][DatabaseQuery] Query executed successfully, processing rows...")
// Get column names
columns, err := rows.Columns()
if err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to get columns: %v", err),
}, err
}
// Process results
results := make([]map[string]interface{}, 0)
for rows.Next() {
// Create a slice of interface{} to hold each column value
columnValues := make([]interface{}, len(columns))
columnPointers := make([]interface{}, len(columns))
for i := range columnValues {
columnPointers[i] = &columnValues[i]
}
// Scan the row
if err := rows.Scan(columnPointers...); err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to scan row: %v", err),
}, err
}
// Create a map for this row
rowMap := make(map[string]interface{})
for i, colName := range columns {
val := columnValues[i]
// Convert []byte to string for better readability
if b, ok := val.([]byte); ok {
rowMap[colName] = string(b)
} else {
rowMap[colName] = val
}
}
results = append(results, rowMap)
}
if err := rows.Err(); err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Error iterating rows: %v", err),
}, err
}
logger.Infof(ctx, "[Tool][DatabaseQuery] Retrieved %d rows with %d columns", len(results), len(columns))
logger.Debugf(ctx, "[Tool][DatabaseQuery] Columns: %v", columns)
// Log first few rows for debugging
if len(results) > 0 {
logger.Debugf(ctx, "[Tool][DatabaseQuery] First row sample:")
for key, value := range results[0] {
logger.Debugf(ctx, "[Tool][DatabaseQuery] %s: %v", key, value)
}
}
// Format output
logger.Debugf(ctx, "[Tool][DatabaseQuery] Formatting query results...")
output := t.formatQueryResults(columns, results, securedSQL)
logger.Infof(ctx, "[Tool][DatabaseQuery] Execute completed successfully: %d rows returned", len(results))
return &types.ToolResult{
Success: true,
Output: output,
Data: map[string]interface{}{
"columns": columns,
"rows": results,
"row_count": len(results),
"query": securedSQL,
"tenant_id": t.tenantID,
"display_type": "database_query",
},
}, nil
}
// validateAndSecureSQL validates the SQL query and injects tenant_id conditions
func (t *DatabaseQueryTool) validateAndSecureSQL(sqlQuery string) (string, error) {
// Normalize SQL: trim and convert to lowercase for analysis
normalizedSQL := strings.TrimSpace(sqlQuery)
lowerSQL := strings.ToLower(normalizedSQL)
// 1. Check if it's a SELECT statement
if !strings.HasPrefix(lowerSQL, "select") {
return "", fmt.Errorf("only SELECT queries are allowed")
}
// 2. Check for dangerous keywords
dangerousKeywords := []string{
"drop", "delete", "insert", "update", "alter", "create",
"truncate", "replace", "execute", "exec", "grant", "revoke",
}
for _, keyword := range dangerousKeywords {
// Use word boundary to avoid false positives (e.g., "description" contains "script")
pattern := fmt.Sprintf(`\b%s\b`, keyword)
matched, _ := regexp.MatchString(pattern, lowerSQL)
if matched {
return "", fmt.Errorf("dangerous keyword detected: %s", keyword)
}
}
// 3. Check for allowed tables
allowedTables := []string{
"tenants", "knowledge_bases", "knowledges", "sessions",
"messages", "chunks", "embeddings", "models",
}
// Extract table names from FROM and JOIN clauses
tablePattern := regexp.MustCompile(`(?i)\b(?:from|join)\s+([a-z_]+)(?:\s+as\s+[a-z_]+|\s+[a-z_]+)?`)
matches := tablePattern.FindAllStringSubmatch(lowerSQL, -1)
tablesInQuery := make(map[string]bool)
for _, match := range matches {
if len(match) > 1 {
tableName := strings.ToLower(match[1])
tablesInQuery[tableName] = true
}
}
// Verify all tables are allowed
for tableName := range tablesInQuery {
allowed := false
for _, allowedTable := range allowedTables {
if tableName == allowedTable {
allowed = true
break
}
}
if !allowed {
return "", fmt.Errorf("table not allowed: %s", tableName)
}
}
// 4. Inject tenant_id conditions for tables that have tenant_id
tablesWithTenantID := map[string]bool{
"tenants": true,
"knowledge_bases": true,
"knowledges": true,
"sessions": true,
"chunks": true,
}
// Build tenant_id injection
securedSQL := normalizedSQL
// Check if WHERE clause exists
wherePattern := regexp.MustCompile(`(?i)\bwhere\b`)
hasWhere := wherePattern.MatchString(securedSQL)
// Find table aliases
aliasPattern := regexp.MustCompile(`(?i)(?:from|join)\s+([a-z_]+)(?:\s+(?:as\s+)?([a-z_]+))?`)
aliasMatches := aliasPattern.FindAllStringSubmatch(lowerSQL, -1)
tableAliases := make(map[string]string) // table -> alias
for _, match := range aliasMatches {
if len(match) >= 3 && match[2] != "" {
// Has explicit alias
tableAliases[match[1]] = match[2]
} else if len(match) >= 2 {
// No alias, use table name itself
tableAliases[match[1]] = match[1]
}
}
// Build tenant_id conditions
var tenantConditions []string
for tableName := range tablesInQuery {
if tablesWithTenantID[tableName] {
alias := tableAliases[tableName]
if alias == "" {
alias = tableName
}
// Special handling for tenants table - use id instead of tenant_id
if tableName == "tenants" {
tenantConditions = append(tenantConditions, fmt.Sprintf("%s.id = %d", alias, t.tenantID))
} else {
tenantConditions = append(tenantConditions, fmt.Sprintf("%s.tenant_id = %d", alias, t.tenantID))
}
}
}
if len(tenantConditions) > 0 {
tenantFilter := strings.Join(tenantConditions, " AND ")
if hasWhere {
// Add to existing WHERE clause
securedSQL = wherePattern.ReplaceAllString(securedSQL, fmt.Sprintf("WHERE %s AND ", tenantFilter))
} else {
// Add new WHERE clause before ORDER BY, GROUP BY, LIMIT, etc.
orderByPattern := regexp.MustCompile(`(?i)\b(group\s+by|order\s+by|limit|offset|having)\b`)
if orderByPattern.MatchString(securedSQL) {
securedSQL = orderByPattern.ReplaceAllStringFunc(securedSQL, func(match string) string {
return fmt.Sprintf(" WHERE %s %s", tenantFilter, match)
})
} else {
// Add WHERE clause at the end
securedSQL = fmt.Sprintf("%s WHERE %s", securedSQL, tenantFilter)
}
}
}
return securedSQL, nil
}
// formatQueryResults formats query results into readable text
func (t *DatabaseQueryTool) formatQueryResults(columns []string, results []map[string]interface{}, query string) string {
output := "=== 查询结果 ===\n\n"
output += fmt.Sprintf("执行的SQL: %s\n\n", query)
output += fmt.Sprintf("返回 %d 行数据\n\n", len(results))
if len(results) == 0 {
output += "未找到匹配的记录。\n"
return output
}
output += "=== 数据详情 ===\n\n"
// Format each row
for i, row := range results {
output += fmt.Sprintf("--- 记录 #%d ---\n", i+1)
for _, col := range columns {
value := row[col]
// Format the value
var formattedValue string
if value == nil {
formattedValue = "<NULL>"
} else if jsonData, err := json.Marshal(value); err == nil {
// Check if it's a complex type
switch v := value.(type) {
case string:
formattedValue = v
case []byte:
formattedValue = string(v)
default:
formattedValue = string(jsonData)
}
} else {
formattedValue = fmt.Sprintf("%v", value)
}
output += fmt.Sprintf(" %s: %s\n", col, formattedValue)
}
output += "\n"
}
// Add summary statistics if applicable
if len(results) > 10 {
output += fmt.Sprintf("注意: 显示了前 %d 条记录,共 %d 条。建议使用 LIMIT 子句限制结果数量。\n", len(results), len(results))
}
return output
}
// Helper function to convert database value to proper type
func convertDatabaseValue(val interface{}) interface{} {
if val == nil {
return nil
}
switch v := val.(type) {
case []byte:
return string(v)
case sql.NullString:
if v.Valid {
return v.String
}
return nil
case sql.NullInt64:
if v.Valid {
return v.Int64
}
return nil
case sql.NullFloat64:
if v.Valid {
return v.Float64
}
return nil
case sql.NullBool:
if v.Valid {
return v.Bool
}
return nil
default:
return v
}
}
+332
View File
@@ -0,0 +1,332 @@
package tools
import (
"context"
"fmt"
"sync"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// GetDocumentInfoTool retrieves detailed information about a document/knowledge
type GetDocumentInfoTool struct {
BaseTool
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
}
// NewGetDocumentInfoTool creates a new get document info tool
func NewGetDocumentInfoTool(
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
) *GetDocumentInfoTool {
description := `Retrieve detailed metadata information about documents.
## When to Use
Use this tool when:
- Need to understand document basic information (title, type, size, etc.)
- Check if document exists and is available
- Batch query metadata for multiple documents
- Understand document processing status
Do not use when:
- Need document content (use knowledge_search)
- Need specific text chunks (search results already contain full content)
## Returned Information
- Basic info: title, description, source type
- File info: filename, type, size
- Processing status: whether processed, chunk count
- Metadata: custom tags and properties
## Notes
- Concurrent query for multiple documents provides better performance
- Returns complete document metadata, not just title
- Can check document processing status (parse_status)`
return &GetDocumentInfoTool{
BaseTool: NewBaseTool("get_document_info", description),
knowledgeService: knowledgeService,
chunkService: chunkService,
}
}
// Parameters returns the JSON schema for the tool's parameters
func (t *GetDocumentInfoTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"knowledge_ids": map[string]interface{}{
"type": "array",
"description": "Array of document/knowledge IDs, obtained from knowledge_id field in search results, supports concurrent batch queries",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 10,
},
},
"required": []string{"knowledge_ids"},
}
}
// Execute retrieves document information with concurrent processing
func (t *GetDocumentInfoTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
// Extract knowledge_ids array
knowledgeIDsRaw, ok := args["knowledge_ids"].([]interface{})
if !ok || len(knowledgeIDsRaw) == 0 {
return &types.ToolResult{
Success: false,
Error: "knowledge_ids is required and must be a non-empty array",
}, fmt.Errorf("knowledge_ids is required")
}
// Convert to string slice
var knowledgeIDs []string
for _, id := range knowledgeIDsRaw {
if idStr, ok := id.(string); ok && idStr != "" {
knowledgeIDs = append(knowledgeIDs, idStr)
}
}
if len(knowledgeIDs) == 0 {
return &types.ToolResult{
Success: false,
Error: "knowledge_ids must contain at least one valid knowledge ID",
}, fmt.Errorf("no valid knowledge IDs provided")
}
// Concurrently get info for each knowledge ID
type docInfo struct {
knowledge *types.Knowledge
chunkCount int
err error
}
var wg sync.WaitGroup
var mu sync.Mutex
results := make(map[string]*docInfo)
for _, knowledgeID := range knowledgeIDs {
wg.Add(1)
go func(id string) {
defer wg.Done()
// Get knowledge metadata
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, id)
if err != nil {
mu.Lock()
results[id] = &docInfo{
err: fmt.Errorf("无法获取文档信息: %v", err),
}
mu.Unlock()
return
}
// Get chunk count
chunks, err := t.chunkService.ListChunksByKnowledgeID(ctx, id)
chunkCount := 0
if err == nil {
chunkCount = len(chunks)
}
mu.Lock()
results[id] = &docInfo{
knowledge: knowledge,
chunkCount: chunkCount,
}
mu.Unlock()
}(knowledgeID)
}
wg.Wait()
// Collect successful results and errors
successDocs := make([]*docInfo, 0)
var errors []string
for _, knowledgeID := range knowledgeIDs {
result := results[knowledgeID]
if result.err != nil {
errors = append(errors, fmt.Sprintf("%s: %v", knowledgeID, result.err))
} else if result.knowledge != nil {
successDocs = append(successDocs, result)
}
}
if len(successDocs) == 0 {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("无法获取任何文档信息。错误: %v", errors),
}, fmt.Errorf("all document retrievals failed")
}
// Format output
output := "=== 文档信息 ===\n\n"
output += fmt.Sprintf("成功获取 %d / %d 个文档信息\n\n", len(successDocs), len(knowledgeIDs))
if len(errors) > 0 {
output += "=== 部分失败 ===\n"
for _, errMsg := range errors {
output += fmt.Sprintf(" - %s\n", errMsg)
}
output += "\n"
}
formattedDocs := make([]map[string]interface{}, 0, len(successDocs))
for i, doc := range successDocs {
k := doc.knowledge
// Get file type icon
typeIcon := getTypeIcon(k.Type, k.FileType)
output += fmt.Sprintf("【文档 #%d】 %s\n", i+1, typeIcon)
output += fmt.Sprintf(" ID: %s\n", k.ID)
output += fmt.Sprintf(" 标题: %s\n", k.Title)
if k.Description != "" {
output += fmt.Sprintf(" 描述: %s\n", k.Description)
}
output += fmt.Sprintf(" 来源: %s\n", formatSource(k.Type, k.Source))
if k.FileName != "" {
output += fmt.Sprintf(" 文件名: %s\n", k.FileName)
output += fmt.Sprintf(" 文件类型: %s\n", k.FileType)
output += fmt.Sprintf(" 文件大小: %s\n", formatFileSize(k.FileSize))
}
output += fmt.Sprintf(" 处理状态: %s\n", formatParseStatus(k.ParseStatus))
output += fmt.Sprintf(" 分块数量: %d 个\n", doc.chunkCount)
if k.Metadata != nil {
if metadata, err := k.Metadata.Map(); err == nil && len(metadata) > 0 {
output += " 元数据:\n"
for key, value := range metadata {
output += fmt.Sprintf(" - %s: %v\n", key, value)
}
}
}
output += "\n"
formattedDocs = append(formattedDocs, map[string]interface{}{
"knowledge_id": k.ID,
"title": k.Title,
"description": k.Description,
"type": k.Type,
"source": k.Source,
"file_name": k.FileName,
"file_type": k.FileType,
"file_size": k.FileSize,
"parse_status": k.ParseStatus,
"chunk_count": doc.chunkCount,
"metadata": k.GetMetadata(),
"type_icon": typeIcon,
})
}
output += "=== Usage Tips ===\n"
output += "- Use knowledge_search to search document content\n"
output += "- Use get_related_chunks to view context and related chunks\n"
output += "- Search results already contain full chunk content\n"
// Extract first document title for summary
var firstTitle string
if len(successDocs) > 0 && successDocs[0].knowledge != nil {
firstTitle = successDocs[0].knowledge.Title
}
return &types.ToolResult{
Success: true,
Output: output,
Data: map[string]interface{}{
"documents": formattedDocs,
"total_docs": len(successDocs),
"requested": len(knowledgeIDs),
"errors": errors,
"display_type": "document_info",
"title": firstTitle, // For frontend summary display
},
}, nil
}
// Helper functions
func getTypeIcon(knowledgeType, fileType string) string {
switch knowledgeType {
case "file":
switch fileType {
case "pdf", "PDF":
return "📄 PDF"
case "docx", "doc", "DOCX", "DOC":
return "📝 Word"
case "txt", "TXT":
return "📃 Text"
case "md", "MD", "markdown":
return "📋 Markdown"
case "xlsx", "xls", "XLSX", "XLS":
return "📊 Excel"
case "pptx", "ppt", "PPTX", "PPT":
return "📊 PowerPoint"
default:
return "📄 File"
}
case "url":
return "🌐 URL"
case "passage":
return "📝 Passage"
default:
return "📄 Document"
}
}
func formatSource(knowledgeType, source string) string {
switch knowledgeType {
case "file":
return "文件上传"
case "url":
return fmt.Sprintf("URL: %s", source)
case "passage":
return "文本输入"
default:
return knowledgeType
}
}
func formatFileSize(size int64) string {
if size == 0 {
return "未知"
}
const unit = 1024
if size < unit {
return fmt.Sprintf("%d B", size)
}
div, exp := int64(unit), 0
for n := size / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp])
}
func formatParseStatus(status string) string {
switch status {
case "pending":
return "⏳ 待处理"
case "processing":
return "🔄 处理中"
case "completed", "success":
return "✅ 已完成"
case "failed":
return "❌ 失败"
default:
return status
}
}
+427
View File
@@ -0,0 +1,427 @@
package tools
import (
"context"
"fmt"
"sync"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// GetRelatedChunksTool retrieves chunks related to a given chunk
type GetRelatedChunksTool struct {
BaseTool
chunkService interfaces.ChunkService
knowledgeBaseService interfaces.KnowledgeBaseService
}
// NewGetRelatedChunksTool creates a new get related chunks tool
func NewGetRelatedChunksTool(chunkService interfaces.ChunkService, knowledgeBaseService interfaces.KnowledgeBaseService) *GetRelatedChunksTool {
description := `Retrieve chunks related to specified reference chunks. Supports sequential (adjacent) and semantic (similar) relation types.
## When to Use
Use this tool when:
- Search results need additional context for full understanding
- You need to see content before/after a specific chunk
- Looking for semantically similar content across the document
- Understanding the complete narrative flow of a topic
Do not use when:
- Search results already provide sufficient complete content
- Only need a single specific chunk without context
## Parameters
chunk_ids (required): Array of reference chunk IDs (1-10)
- Obtained from search results
- Supports concurrent batch processing
- Example: ["chunk_abc", "chunk_def"]
relation_type (optional): Type of relation
- "sequential" (default): Get adjacent chunks before and after
- "semantic": Get semantically similar chunks regardless of position
limit (optional): Number of related chunks to return per reference chunk
- Default: 5
- Range: 1-10
- Sequential: retrieves limit/2 chunks before and after
- Semantic: retrieves top limit most similar chunks
## Relation Types
Sequential:
- Retrieves adjacent chunks in document order
- Useful for understanding complete narrative flow
- Ideal for scenarios requiring continuous reading
- Example: viewing complete configuration steps
Semantic:
- Finds content-similar chunks regardless of position
- Discovers related discussions throughout document
- Ideal for topic expansion and cross-referencing
- Example: finding all mentions of a specific concept
## Usage Patterns
1. Context expansion: knowledge_search -> get_related_chunks(sequential)
2. Topic exploration: knowledge_search -> get_related_chunks(semantic)
3. Deep research: knowledge_search -> get_related_chunks(both sequential and semantic)
## Notes
- Results are automatically deduplicated
- Source chunks are excluded from results
- Sequential results sorted by chunk_index
- Semantic results sorted by similarity score
- Limit value of 5 typically provides sufficient context without information overload`
return &GetRelatedChunksTool{
BaseTool: NewBaseTool("get_related_chunks", description),
chunkService: chunkService,
knowledgeBaseService: knowledgeBaseService,
}
}
// Parameters returns the JSON schema for the tool's parameters
func (t *GetRelatedChunksTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"chunk_ids": map[string]interface{}{
"type": "array",
"description": "Array of reference chunk IDs",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 10,
},
"relation_type": map[string]interface{}{
"type": "string",
"description": "Type: sequential (default) or semantic",
"enum": []string{"sequential", "semantic"},
"default": "sequential",
},
"limit": map[string]interface{}{
"type": "integer",
"description": "Number of related chunks per input chunk (default: 5)",
"default": 5,
"minimum": 1,
"maximum": 10,
},
},
"required": []string{"chunk_ids"},
}
}
// Execute executes the get related chunks tool with concurrent processing
func (t *GetRelatedChunksTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
// Extract chunk_ids array
chunkIDsRaw, ok := args["chunk_ids"].([]interface{})
if !ok || len(chunkIDsRaw) == 0 {
return &types.ToolResult{
Success: false,
Error: "chunk_ids is required and must be a non-empty array",
}, fmt.Errorf("chunk_ids is required")
}
// Convert to string slice
var chunkIDs []string
for _, id := range chunkIDsRaw {
if idStr, ok := id.(string); ok && idStr != "" {
chunkIDs = append(chunkIDs, idStr)
}
}
if len(chunkIDs) == 0 {
return &types.ToolResult{
Success: false,
Error: "chunk_ids must contain at least one valid chunk ID",
}, fmt.Errorf("no valid chunk IDs provided")
}
relationType := "sequential"
if rt, ok := args["relation_type"].(string); ok {
relationType = rt
}
limit := 5
if l, ok := args["limit"].(float64); ok {
limit = int(l)
}
if limit < 1 {
limit = 1
}
if limit > 10 {
limit = 10
}
// Concurrently get related chunks for each chunk ID
type relatedResult struct {
sourceChunk *types.Chunk
relatedChunks []*types.Chunk
err error
}
var wg sync.WaitGroup
var mu sync.Mutex
results := make(map[string]*relatedResult)
for _, chunkID := range chunkIDs {
wg.Add(1)
go func(id string) {
defer wg.Done()
// Get the original chunk first
chunk, err := t.chunkService.GetChunkByID(ctx, id)
if err != nil || chunk == nil {
mu.Lock()
results[id] = &relatedResult{err: fmt.Errorf("failed to retrieve chunk: %v", err)}
mu.Unlock()
return
}
var relatedChunks []*types.Chunk
if relationType == "sequential" {
relatedChunks, err = t.getSequentialRelatedChunks(ctx, chunk, limit)
} else if relationType == "semantic" {
relatedChunks, err = t.getSemanticRelatedChunks(ctx, chunk, limit)
}
mu.Lock()
results[id] = &relatedResult{
sourceChunk: chunk,
relatedChunks: relatedChunks,
err: err,
}
mu.Unlock()
}(chunkID)
}
wg.Wait()
// Collect and deduplicate all related chunks
seenChunks := make(map[string]*types.Chunk)
sourceChunkIDs := make(map[string]bool)
var errors []string
// Mark source chunks to exclude them from results
for _, chunkID := range chunkIDs {
sourceChunkIDs[chunkID] = true
}
for _, chunkID := range chunkIDs {
result := results[chunkID]
if result.err != nil {
errors = append(errors, fmt.Sprintf("chunk %s: %v", chunkID, result.err))
continue
}
for _, chunk := range result.relatedChunks {
// Exclude source chunks and avoid duplicates
if !sourceChunkIDs[chunk.ID] {
if _, seen := seenChunks[chunk.ID]; !seen {
seenChunks[chunk.ID] = chunk
}
}
}
}
// Convert map to slice and sort
allRelatedChunks := make([]*types.Chunk, 0, len(seenChunks))
for _, chunk := range seenChunks {
allRelatedChunks = append(allRelatedChunks, chunk)
}
// Sort chunks
if relationType == "sequential" {
// Sort by knowledge_id and chunk_index for sequential
sortChunksByPosition(allRelatedChunks)
}
// For semantic, keep the order from search results (already sorted by relevance)
if len(allRelatedChunks) == 0 {
return &types.ToolResult{
Success: true,
Output: "No related chunks found. Possible reasons:\n- Chunk is the only chunk in document\n- Semantic similarity threshold not met\n- Invalid chunk_id provided",
Data: map[string]interface{}{
"chunk_ids": chunkIDs,
"relation_type": relationType,
"count": 0,
"chunks": []interface{}{},
"errors": errors,
},
}, nil
}
// Format output
return t.formatOutput(chunkIDs, relationType, allRelatedChunks, errors)
}
// getSequentialRelatedChunks gets chunks before and after the reference chunk
func (t *GetRelatedChunksTool) getSequentialRelatedChunks(ctx context.Context, chunk *types.Chunk, limit int) ([]*types.Chunk, error) {
// Get all chunks from the same knowledge
allChunks, err := t.chunkService.ListChunksByKnowledgeID(ctx, chunk.KnowledgeID)
if err != nil {
return nil, fmt.Errorf("failed to retrieve document chunks: %v", err)
}
relatedChunks := make([]*types.Chunk, 0)
// Bidirectional window: get chunks before and after
halfLimit := limit / 2
if halfLimit < 1 {
halfLimit = 1
}
minIndex := chunk.ChunkIndex - halfLimit
maxIndex := chunk.ChunkIndex + halfLimit
for _, c := range allChunks {
// Within range and not the source chunk itself
if c.ChunkIndex >= minIndex && c.ChunkIndex <= maxIndex && c.ID != chunk.ID {
relatedChunks = append(relatedChunks, c)
}
}
return relatedChunks, nil
}
// getSemanticRelatedChunks gets semantically similar chunks using hybrid search
func (t *GetRelatedChunksTool) getSemanticRelatedChunks(ctx context.Context, chunk *types.Chunk, limit int) ([]*types.Chunk, error) {
// Use chunk content as query for semantic search
searchParams := types.SearchParams{
QueryText: chunk.Content,
MatchCount: limit + 5, // Get extra results for filtering
}
// Search in the knowledge base that contains this chunk
searchResults, err := t.knowledgeBaseService.HybridSearch(ctx, chunk.KnowledgeBaseID, searchParams)
if err != nil {
return nil, fmt.Errorf("semantic search failed: %v", err)
}
// Convert search results to chunks, excluding the source chunk
relatedChunks := make([]*types.Chunk, 0, limit)
for _, result := range searchResults {
if result.ID == chunk.ID {
continue // Skip the source chunk itself
}
// Convert SearchResult to Chunk
relatedChunk := &types.Chunk{
ID: result.ID,
KnowledgeID: result.KnowledgeID,
KnowledgeBaseID: chunk.KnowledgeBaseID,
Content: result.Content,
ChunkIndex: result.ChunkIndex,
}
relatedChunks = append(relatedChunks, relatedChunk)
if len(relatedChunks) >= limit {
break
}
}
return relatedChunks, nil
}
// sortChunksByPosition sorts chunks by knowledge_id and chunk_index
func sortChunksByPosition(chunks []*types.Chunk) {
// Simple bubble sort for small arrays
n := len(chunks)
for i := 0; i < n-1; i++ {
for j := 0; j < n-i-1; j++ {
// First sort by knowledge_id, then by chunk_index
if chunks[j].KnowledgeID > chunks[j+1].KnowledgeID ||
(chunks[j].KnowledgeID == chunks[j+1].KnowledgeID &&
chunks[j].ChunkIndex > chunks[j+1].ChunkIndex) {
chunks[j], chunks[j+1] = chunks[j+1], chunks[j]
}
}
}
}
// formatOutput formats the tool output
func (t *GetRelatedChunksTool) formatOutput(
chunkIDs []string,
relationType string,
chunks []*types.Chunk,
errors []string,
) (*types.ToolResult, error) {
relationTypeLabel := map[string]string{
"sequential": "Sequential (Adjacent)",
"semantic": "Semantic (Similar Content)",
}
output := "=== Related Chunks ===\n\n"
output += fmt.Sprintf("Reference chunks: %d\n", len(chunkIDs))
output += fmt.Sprintf("Relation type: %s\n", relationTypeLabel[relationType])
output += fmt.Sprintf("Found %d related chunks (deduplicated)\n\n", len(chunks))
if len(errors) > 0 {
output += "=== Partial Failures ===\n"
for _, errMsg := range errors {
output += fmt.Sprintf(" - %s\n", errMsg)
}
output += "\n"
}
output += "=== Content ===\n\n"
formattedChunks := make([]map[string]interface{}, 0, len(chunks))
currentKnowledge := ""
for i, c := range chunks {
// Group by knowledge document
if c.KnowledgeID != currentKnowledge {
currentKnowledge = c.KnowledgeID
if i > 0 {
output += "\n"
}
output += fmt.Sprintf("[Document: %s]\n\n", c.KnowledgeID)
}
output += fmt.Sprintf("Chunk #%d (Position: %d):\n", i+1, c.ChunkIndex+1)
output += fmt.Sprintf(" chunk_id: %s\n", c.ID)
output += fmt.Sprintf(" content: %s\n\n", c.Content)
formattedChunks = append(formattedChunks, map[string]interface{}{
"index": i + 1,
"chunk_id": c.ID,
"chunk_index": c.ChunkIndex,
"content": c.Content,
"knowledge_id": c.KnowledgeID,
})
}
output += "=== Notes ===\n"
if relationType == "sequential" {
output += "- Adjacent chunks in document order\n"
output += "- Useful for understanding complete narrative flow\n"
output += "- Sorted by position\n"
} else {
output += "- Semantically similar chunks sorted by relevance\n"
output += "- Useful for discovering related discussions\n"
output += "- Ideal for topic expansion and cross-referencing\n"
}
output += "- Source chunks excluded\n"
output += "- Results deduplicated\n"
return &types.ToolResult{
Success: true,
Output: output,
Data: map[string]interface{}{
"chunk_ids": chunkIDs,
"relation_type": relationType,
"count": len(chunks),
"chunks": formattedChunks,
"errors": errors,
"display_type": "related_chunks",
},
}, nil
}
+816
View File
@@ -0,0 +1,816 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"sort"
"sync"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// searchResultWithMeta wraps search result with metadata about which query matched it
type searchResultWithMeta struct {
*types.SearchResult
SourceQuery string
QueryType string // "vector" or "keyword"
}
// KnowledgeSearchTool searches knowledge bases with flexible query modes
type KnowledgeSearchTool struct {
BaseTool
knowledgeService interfaces.KnowledgeBaseService
tenantID uint
allowedKBs []string
rerankModel rerank.Reranker
}
// NewKnowledgeSearchTool creates a new knowledge search tool
func NewKnowledgeSearchTool(
knowledgeService interfaces.KnowledgeBaseService,
tenantID uint,
allowedKBs []string,
rerankModel rerank.Reranker,
) *KnowledgeSearchTool {
description := `Search within knowledge bases with flexible query modes. Unified tool that supports both targeted and broad searches.
## Features
- Multi-KB search: Search across multiple knowledge bases concurrently
- Flexible queries: Support vector, keyword, or hybrid search modes
- Quality filtering: Automatically filters low-quality chunks
## Usage
**Use when**:
- You know which knowledge bases to target (specify knowledge_base_ids)
- You're unsure which KB contains the info (omit knowledge_base_ids to search all allowed KBs)
- Want to search specific KBs with same query
- Need semantic (vector) or exact keyword searches
- Want to search only specific documents within KBs
**Parameters**:
- knowledge_base_ids (optional): Array of KB IDs to search (1-10). If omitted, searches all allowed KBs.
- query (optional): Single search query (for simple hybrid search)
- vector_queries (optional): Array of semantic queries for vector search (1-5 queries)
- keyword_queries (optional): Array of keyword queries for keyword search (1-5 queries)
- top_k (optional): Results per KB per query (default: 5, max: 20)
- vector_threshold (optional): Minimum score for vector results (default: 0.6, 0.0-1.0)
- keyword_threshold (optional): Minimum score for keyword results (default: 0.5, 0.0-1.0)
- knowledge_ids (optional): Array of document IDs to filter results (only return results from these documents)
- min_score (optional): Absolute minimum score to include results (default: 0.3, filters very low quality chunks)
**Search Modes**:
- Simple: Provide single query parameter (hybrid search)
- Vector only: Provide vector_queries only
- Keyword only: Provide keyword_queries only
- Hybrid: Provide both vector_queries and keyword_queries
- At least one query parameter must be provided
**Returns**: Merged and deduplicated search results from all KBs
## Examples
` + "`" + `
# Simple search in specific KBs
{
"knowledge_base_ids": ["kb1", "kb2"],
"query": "什么是向量数据库"
}
# Search all allowed KBs with vector queries
{
"vector_queries": ["什么是向量数据库", "向量数据库的定义"]
}
# Multiple query types with thresholds
{
"knowledge_base_ids": ["kb1"],
"vector_queries": ["向量数据库应用"],
"keyword_queries": ["Docker", "部署"],
"vector_threshold": 0.7,
"keyword_threshold": 0.6
}
# Search specific documents
{
"knowledge_base_ids": ["kb1"],
"query": "彗星的起源",
"knowledge_ids": ["doc1", "doc2"]
}
` + "`" + `
## Tips
- Concurrent search across multiple KBs and queries
- Results are automatically reranked to unify scores from different sources
- Reranked scores are in 0-1 range and directly comparable
- Results are merged, deduplicated and sorted by relevance
- Use vector_queries for semantic/conceptual searches
- Use keyword_queries for exact term matching
- Results below threshold are automatically filtered
- High relevance (>=0.8): directly usable
- Medium relevance (0.6-0.8): reference only
- Low relevance (<0.6): use with caution`
return &KnowledgeSearchTool{
BaseTool: NewBaseTool("knowledge_search", description),
knowledgeService: knowledgeService,
tenantID: tenantID,
allowedKBs: allowedKBs,
rerankModel: rerankModel,
}
}
// Parameters returns the JSON schema for the tool's parameters
func (t *KnowledgeSearchTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"knowledge_base_ids": map[string]interface{}{
"type": "array",
"description": "Array of knowledge base IDs to search in (optional, if omitted searches all allowed KBs)",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 10,
},
"query": map[string]interface{}{
"type": "string",
"description": "Single search query for simple hybrid search",
},
"vector_queries": map[string]interface{}{
"type": "array",
"description": "Array of semantic queries for vector search (1-5 queries)",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 5,
},
"keyword_queries": map[string]interface{}{
"type": "array",
"description": "Array of keyword queries for keyword search (1-5 queries)",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 5,
},
"top_k": map[string]interface{}{
"type": "integer",
"description": "Number of results per knowledge base per query (default: 5)",
"default": 5,
"minimum": 1,
"maximum": 20,
},
"vector_threshold": map[string]interface{}{
"type": "number",
"description": "Minimum score for vector results (default: 0.6)",
"default": 0.6,
"minimum": 0.0,
"maximum": 1.0,
},
"keyword_threshold": map[string]interface{}{
"type": "number",
"description": "Minimum score for keyword results (default: 0.5)",
"default": 0.5,
"minimum": 0.0,
"maximum": 1.0,
},
"knowledge_ids": map[string]interface{}{
"type": "array",
"description": "Optional array of document IDs to filter results (only return results from these specific documents)",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 50,
},
"min_score": map[string]interface{}{
"type": "number",
"description": "Absolute minimum score threshold for filtering very low quality results (default: 0.3)",
"default": 0.3,
"minimum": 0.0,
"maximum": 1.0,
},
},
"required": []string{},
}
}
// Execute executes the knowledge search tool with flexible query modes
func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Execute started")
// Log input arguments
argsJSON, _ := json.MarshalIndent(args, "", " ")
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Input args:\n%s", string(argsJSON))
// Determine which KBs to search
var kbIDs []string
if kbIDsRaw, ok := args["knowledge_base_ids"].([]interface{}); ok && len(kbIDsRaw) > 0 {
for _, id := range kbIDsRaw {
if idStr, ok := id.(string); ok && idStr != "" {
kbIDs = append(kbIDs, idStr)
}
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] User specified %d knowledge bases: %v", len(kbIDs), kbIDs)
}
// If no KBs specified, use allowed KBs
if len(kbIDs) == 0 {
kbIDs = t.allowedKBs
if len(kbIDs) == 0 {
logger.Errorf(ctx, "[Tool][KnowledgeSearch] No knowledge bases available")
return &types.ToolResult{
Success: false,
Error: "no knowledge bases specified and no allowed KBs configured",
}, fmt.Errorf("no knowledge bases available")
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] Using all allowed KBs (%d): %v", len(kbIDs), kbIDs)
}
// Parse query parameters
var singleQuery string
var vectorQueries, keywordQueries []string
// Parse single query
if q, ok := args["query"].(string); ok && q != "" {
singleQuery = q
}
// Parse vector_queries
if vq, ok := args["vector_queries"].([]interface{}); ok {
for _, q := range vq {
if queryStr, ok := q.(string); ok && queryStr != "" {
vectorQueries = append(vectorQueries, queryStr)
}
}
}
// Parse keyword_queries
if kq, ok := args["keyword_queries"].([]interface{}); ok {
for _, q := range kq {
if queryStr, ok := q.(string); ok && queryStr != "" {
keywordQueries = append(keywordQueries, queryStr)
}
}
}
// If single query provided, treat it as both vector and keyword query
if singleQuery != "" {
if len(vectorQueries) == 0 && len(keywordQueries) == 0 {
vectorQueries = []string{singleQuery}
keywordQueries = []string{singleQuery}
}
}
// Validate: at least one query must be provided
if len(vectorQueries) == 0 && len(keywordQueries) == 0 {
logger.Errorf(ctx, "[Tool][KnowledgeSearch] No query provided")
return &types.ToolResult{
Success: false,
Error: "at least one of query, vector_queries, or keyword_queries must be provided",
}, fmt.Errorf("no query provided")
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] Query mode: single=%v, vector_queries=%d, keyword_queries=%d",
singleQuery != "", len(vectorQueries), len(keywordQueries))
if singleQuery != "" {
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Single query: %s", singleQuery)
}
if len(vectorQueries) > 0 {
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Vector queries: %v", vectorQueries)
}
if len(keywordQueries) > 0 {
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Keyword queries: %v", keywordQueries)
}
// Parse thresholds
vectorThreshold := 0.6
if vt, ok := args["vector_threshold"].(float64); ok {
vectorThreshold = vt
}
keywordThreshold := 0.5
if kt, ok := args["keyword_threshold"].(float64); ok {
keywordThreshold = kt
}
// Parse min_score for absolute filtering
minScore := 0.3
if ms, ok := args["min_score"].(float64); ok {
minScore = ms
}
// Parse top_k
topK := 5
if topKVal, ok := args["top_k"]; ok {
switch v := topKVal.(type) {
case float64:
topK = int(v)
case int:
topK = v
}
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] Search params: top_k=%d, vector_threshold=%.2f, keyword_threshold=%.2f, min_score=%.2f",
topK, vectorThreshold, keywordThreshold, minScore)
// Extract knowledge_ids filter if provided
var knowledgeIDsFilter map[string]bool
if knowledgeIDsRaw, ok := args["knowledge_ids"].([]interface{}); ok && len(knowledgeIDsRaw) > 0 {
knowledgeIDsFilter = make(map[string]bool)
for _, id := range knowledgeIDsRaw {
if idStr, ok := id.(string); ok && idStr != "" {
knowledgeIDsFilter[idStr] = true
}
}
}
// Execute concurrent search
logger.Infof(ctx, "[Tool][KnowledgeSearch] Starting concurrent search across %d KBs", len(kbIDs))
allResults := t.concurrentSearch(ctx, vectorQueries, keywordQueries, kbIDs,
topK, vectorThreshold, keywordThreshold)
logger.Infof(ctx, "[Tool][KnowledgeSearch] Concurrent search completed: %d raw results", len(allResults))
// Filter by knowledge_ids if provided
if len(knowledgeIDsFilter) > 0 {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Filtering by %d knowledge IDs", len(knowledgeIDsFilter))
filtered := make([]*searchResultWithMeta, 0)
for _, r := range allResults {
if knowledgeIDsFilter[r.KnowledgeID] {
filtered = append(filtered, r)
}
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] After knowledge_id filter: %d results (from %d)",
len(filtered), len(allResults))
allResults = filtered
}
// Filter by threshold first
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying threshold filter...")
filteredResults := t.filterByThreshold(allResults, vectorThreshold, keywordThreshold)
logger.Infof(ctx, "[Tool][KnowledgeSearch] After threshold filter: %d results (from %d)",
len(filteredResults), len(allResults))
// Apply ReRank if model is configured
if t.rerankModel != nil && len(filteredResults) > 0 {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying rerank with model: %s, input: %d results",
t.rerankModel.GetModelName(), len(filteredResults))
rerankQuery := singleQuery
if rerankQuery == "" && len(vectorQueries) > 0 {
rerankQuery = vectorQueries[0] // Use first vector query as rerank query
} else if rerankQuery == "" && len(keywordQueries) > 0 {
rerankQuery = keywordQueries[0] // Use first keyword query as fallback
}
if rerankQuery != "" {
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Rerank query: %s", rerankQuery)
rerankedResults, err := t.rerankResults(ctx, rerankQuery, filteredResults)
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Rerank failed, using original results: %v", err)
} else {
filteredResults = rerankedResults
logger.Infof(ctx, "[Tool][KnowledgeSearch] Rerank completed successfully: %d results",
len(filteredResults))
}
}
}
// Apply absolute minimum score filter to remove very low quality chunks
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Applying min_score filter (%.2f)...", minScore)
filteredResults = t.filterByMinScore(filteredResults, minScore)
logger.Infof(ctx, "[Tool][KnowledgeSearch] After min_score filter: %d results", len(filteredResults))
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Deduplicating results...")
deduplicatedResults := t.deduplicateResults(filteredResults)
logger.Infof(ctx, "[Tool][KnowledgeSearch] After deduplication: %d results (from %d)",
len(deduplicatedResults), len(filteredResults))
// Sort results by score (descending)
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Sorting results by score...")
sort.Slice(deduplicatedResults, func(i, j int) bool {
if deduplicatedResults[i].Score != deduplicatedResults[j].Score {
return deduplicatedResults[i].Score > deduplicatedResults[j].Score
}
// If scores are equal, prefer vector matches
if deduplicatedResults[i].QueryType != deduplicatedResults[j].QueryType {
return deduplicatedResults[i].QueryType == "vector"
}
return deduplicatedResults[i].KnowledgeID < deduplicatedResults[j].KnowledgeID
})
// Log top results
if len(deduplicatedResults) > 0 {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Top 5 results by score:")
for i := 0; i < len(deduplicatedResults) && i < 5; i++ {
r := deduplicatedResults[i]
logger.Infof(ctx, "[Tool][KnowledgeSearch] #%d: score=%.3f, type=%s, kb=%s, chunk_id=%s",
i+1, r.Score, r.QueryType, r.KnowledgeID, r.ID)
}
}
// Build output
logger.Infof(ctx, "[Tool][KnowledgeSearch] Formatting output with %d final results", len(deduplicatedResults))
result, err := t.formatOutput(deduplicatedResults, vectorQueries, keywordQueries,
kbIDs, len(allResults), vectorThreshold, keywordThreshold, knowledgeIDsFilter, singleQuery)
if err != nil {
logger.Errorf(ctx, "[Tool][KnowledgeSearch] Failed to format output: %v", err)
return result, err
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] Execute completed successfully")
return result, nil
}
// concurrentSearch executes vector and keyword searches concurrently
func (t *KnowledgeSearchTool) concurrentSearch(
ctx context.Context,
vectorQueries, keywordQueries []string,
kbsToSearch []string,
topK int,
vectorThreshold, keywordThreshold float64,
) []*searchResultWithMeta {
var wg sync.WaitGroup
var mu sync.Mutex
allResults := make([]*searchResultWithMeta, 0)
// Launch vector searches
if len(vectorQueries) > 0 {
wg.Add(1)
go func() {
defer wg.Done()
results := t.searchWithQueries(ctx, vectorQueries, kbsToSearch, topK,
vectorThreshold, 1.0, "vector")
mu.Lock()
allResults = append(allResults, results...)
mu.Unlock()
}()
}
// Launch keyword searches
if len(keywordQueries) > 0 {
wg.Add(1)
go func() {
defer wg.Done()
results := t.searchWithQueries(ctx, keywordQueries, kbsToSearch, topK,
1.0, keywordThreshold, "keyword")
mu.Lock()
allResults = append(allResults, results...)
mu.Unlock()
}()
}
wg.Wait()
return allResults
}
// searchWithQueries executes multiple queries concurrently
func (t *KnowledgeSearchTool) searchWithQueries(
ctx context.Context,
queries []string,
kbsToSearch []string,
topK int,
vectorThreshold, keywordThreshold float64,
queryType string,
) []*searchResultWithMeta {
var wg sync.WaitGroup
var mu sync.Mutex
allResults := make([]*searchResultWithMeta, 0)
for _, query := range queries {
wg.Add(1)
go func(q string) {
defer wg.Done()
results := t.searchSingleQuery(ctx, q, kbsToSearch, topK,
vectorThreshold, keywordThreshold, queryType)
mu.Lock()
allResults = append(allResults, results...)
mu.Unlock()
}(query)
}
wg.Wait()
return allResults
}
// searchSingleQuery searches a single query across multiple KBs concurrently
func (t *KnowledgeSearchTool) searchSingleQuery(
ctx context.Context,
query string,
kbsToSearch []string,
topK int,
vectorThreshold, keywordThreshold float64,
queryType string,
) []*searchResultWithMeta {
var wg sync.WaitGroup
var mu sync.Mutex
results := make([]*searchResultWithMeta, 0)
searchParams := types.SearchParams{
QueryText: query,
MatchCount: topK,
VectorThreshold: vectorThreshold,
KeywordThreshold: keywordThreshold,
}
for _, kbID := range kbsToSearch {
wg.Add(1)
go func(kb string) {
defer wg.Done()
kbResults, err := t.knowledgeService.HybridSearch(ctx, kb, searchParams)
if err != nil {
// Log error but continue with other KBs
return
}
// Wrap results with metadata
mu.Lock()
for _, r := range kbResults {
results = append(results, &searchResultWithMeta{
SearchResult: r,
SourceQuery: query,
QueryType: queryType,
})
}
mu.Unlock()
}(kbID)
}
wg.Wait()
return results
}
// filterByThreshold filters results based on match type and threshold
func (t *KnowledgeSearchTool) filterByThreshold(
results []*searchResultWithMeta,
vectorThreshold, keywordThreshold float64,
) []*searchResultWithMeta {
filtered := make([]*searchResultWithMeta, 0)
for _, r := range results {
// Check if result meets threshold based on match type
if r.MatchType == types.MatchTypeEmbedding && r.Score >= vectorThreshold {
filtered = append(filtered, r)
} else if r.MatchType == types.MatchTypeKeywords && r.Score >= keywordThreshold {
filtered = append(filtered, r)
} else {
// For other match types (graph, nearby chunk, etc.), use the lower threshold
minThreshold := vectorThreshold
if keywordThreshold < minThreshold {
minThreshold = keywordThreshold
}
if r.Score >= minThreshold {
filtered = append(filtered, r)
}
}
}
return filtered
}
// rerankResults applies reranking to search results using the configured rerank model
func (t *KnowledgeSearchTool) rerankResults(
ctx context.Context,
query string,
results []*searchResultWithMeta,
) ([]*searchResultWithMeta, error) {
// Prepare passages for reranking
passages := make([]string, len(results))
for i, result := range results {
passages[i] = result.Content
}
// Call rerank model
rerankResp, err := t.rerankModel.Rerank(ctx, query, passages)
if err != nil {
return nil, fmt.Errorf("rerank call failed: %w", err)
}
// Map reranked results back with new scores
reranked := make([]*searchResultWithMeta, 0, len(rerankResp))
for _, rr := range rerankResp {
if rr.Index >= 0 && rr.Index < len(results) {
// Create new result with reranked score
newResult := *results[rr.Index]
newResult.Score = rr.RelevanceScore
reranked = append(reranked, &newResult)
}
}
logger.Infof(ctx, "Reranked %d results from %d original results", len(reranked), len(results))
return reranked, nil
}
// filterByMinScore filters results by absolute minimum score
func (t *KnowledgeSearchTool) filterByMinScore(
results []*searchResultWithMeta,
minScore float64,
) []*searchResultWithMeta {
filtered := make([]*searchResultWithMeta, 0)
for _, r := range results {
if r.Score >= minScore {
filtered = append(filtered, r)
}
}
return filtered
}
// deduplicateResults removes duplicate chunks, keeping the highest score
func (t *KnowledgeSearchTool) deduplicateResults(results []*searchResultWithMeta) []*searchResultWithMeta {
seen := make(map[string]*searchResultWithMeta)
for _, r := range results {
if existing, ok := seen[r.ID]; ok {
// Keep the result with higher score
if r.Score > existing.Score {
seen[r.ID] = r
}
} else {
seen[r.ID] = r
}
}
deduplicated := make([]*searchResultWithMeta, 0, len(seen))
for _, r := range seen {
deduplicated = append(deduplicated, r)
}
return deduplicated
}
// formatOutput formats the search results for display
func (t *KnowledgeSearchTool) formatOutput(
results []*searchResultWithMeta,
vectorQueries, keywordQueries []string,
kbsToSearch []string,
totalBeforeFilter int,
vectorThreshold, keywordThreshold float64,
knowledgeIDsFilter map[string]bool,
singleQuery string,
) (*types.ToolResult, error) {
if len(results) == 0 {
data := map[string]interface{}{
"knowledge_base_ids": kbsToSearch,
"results": []interface{}{},
"count": 0,
}
if len(knowledgeIDsFilter) > 0 {
filterList := make([]string, 0, len(knowledgeIDsFilter))
for id := range knowledgeIDsFilter {
filterList = append(filterList, id)
}
data["knowledge_ids"] = filterList
}
if singleQuery != "" {
data["query"] = singleQuery
}
return &types.ToolResult{
Success: true,
Output: fmt.Sprintf("No relevant content found in %d knowledge base(s).", len(kbsToSearch)),
Data: data,
}, nil
}
// Determine search mode
searchMode := "Hybrid (Vector + Keyword)"
if len(vectorQueries) > 0 && len(keywordQueries) == 0 {
searchMode = "Vector"
} else if len(vectorQueries) == 0 && len(keywordQueries) > 0 {
searchMode = "Keyword"
}
// Build output header
output := "=== Search Results ===\n"
output += fmt.Sprintf("Knowledge Bases: %v\n", kbsToSearch)
if len(knowledgeIDsFilter) > 0 {
filterList := make([]string, 0, len(knowledgeIDsFilter))
for id := range knowledgeIDsFilter {
filterList = append(filterList, id)
}
output += fmt.Sprintf("Document Filter: %v\n", filterList)
}
output += fmt.Sprintf("Search Mode: %s\n", searchMode)
if singleQuery != "" {
output += fmt.Sprintf("Query: %s\n", singleQuery)
} else {
if len(vectorQueries) > 0 {
output += fmt.Sprintf("Vector Queries: %v\n", vectorQueries)
output += fmt.Sprintf("Vector Threshold: %.2f\n", vectorThreshold)
}
if len(keywordQueries) > 0 {
output += fmt.Sprintf("Keyword Queries: %v\n", keywordQueries)
output += fmt.Sprintf("Keyword Threshold: %.2f\n", keywordThreshold)
}
}
output += fmt.Sprintf("Found %d relevant results (deduplicated)", len(results))
if totalBeforeFilter > len(results) {
output += fmt.Sprintf(" (filtered from %d)", totalBeforeFilter)
}
output += "\n\n"
// Count results by KB
kbCounts := make(map[string]int)
for _, r := range results {
kbCounts[r.KnowledgeID]++
}
output += "Knowledge Base Coverage:\n"
for kbID, count := range kbCounts {
output += fmt.Sprintf(" - %s: %d results\n", kbID, count)
}
output += "\n=== Detailed Results ===\n\n"
// Format individual results
formattedResults := make([]map[string]interface{}, 0, len(results))
currentKB := ""
for i, result := range results {
// Group by knowledge base
if result.KnowledgeID != currentKB {
currentKB = result.KnowledgeID
if i > 0 {
output += "\n"
}
output += fmt.Sprintf("[Source Document: %s]\n", result.KnowledgeTitle)
}
relevanceLevel := GetRelevanceLevel(result.Score)
output += fmt.Sprintf("\nResult #%d:\n", i+1)
output += fmt.Sprintf(" Relevance: %.2f (%s)\n", result.Score, relevanceLevel)
output += fmt.Sprintf(" Match Type: %s", FormatMatchType(result.MatchType))
if result.SourceQuery != "" && result.SourceQuery != singleQuery {
output += fmt.Sprintf(" (Query: \"%s\")", result.SourceQuery)
}
output += "\n"
output += fmt.Sprintf(" Content: %s\n", result.Content)
output += fmt.Sprintf(" [chunk_id: %s - full content included above]\n", result.ID)
formattedResults = append(formattedResults, map[string]interface{}{
"result_index": i + 1,
"chunk_id": result.ID,
"content": result.Content,
"score": result.Score,
"relevance_level": relevanceLevel,
"knowledge_id": result.KnowledgeID,
"knowledge_title": result.KnowledgeTitle,
"match_type": result.MatchType,
"source_query": result.SourceQuery,
"query_type": result.QueryType,
})
}
// Add usage guidance
output += "\n\n=== Usage Guidelines ===\n"
output += "- High relevance (>=0.8): directly usable for answering\n"
output += "- Medium relevance (0.6-0.8): use as supplementary reference\n"
output += "- Low relevance (<0.6): use with caution, may not be accurate\n"
if totalBeforeFilter > len(results) {
output += "- Results below threshold have been automatically filtered\n"
}
output += "- Full content is already included in search results above\n"
output += "- Results are deduplicated across knowledge bases and sorted by relevance\n"
output += "- Use get_related_chunks to expand context if needed\n"
data := map[string]interface{}{
"knowledge_base_ids": kbsToSearch,
"results": formattedResults,
"count": len(results),
"kb_counts": kbCounts,
"search_mode": searchMode,
"display_type": "search_results",
}
if len(knowledgeIDsFilter) > 0 {
filterList := make([]string, 0, len(knowledgeIDsFilter))
for id := range knowledgeIDsFilter {
filterList = append(filterList, id)
}
data["knowledge_ids"] = filterList
}
if singleQuery != "" {
data["query"] = singleQuery
}
if len(vectorQueries) > 0 {
data["vector_queries"] = vectorQueries
}
if len(keywordQueries) > 0 {
data["keyword_queries"] = keywordQueries
}
if totalBeforeFilter > len(results) {
data["total_before_filter"] = totalBeforeFilter
data["total_after_filter"] = len(results)
}
return &types.ToolResult{
Success: true,
Output: output,
Data: data,
}, nil
}
@@ -0,0 +1,423 @@
package tools
import (
"context"
"fmt"
"sort"
"sync"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// QueryKnowledgeGraphTool queries the knowledge graph for entities and relationships
type QueryKnowledgeGraphTool struct {
BaseTool
knowledgeService interfaces.KnowledgeBaseService
}
// NewQueryKnowledgeGraphTool creates a new query knowledge graph tool
func NewQueryKnowledgeGraphTool(knowledgeService interfaces.KnowledgeBaseService) *QueryKnowledgeGraphTool {
description := `查询知识图谱,探索实体关系和知识网络。
## 何时使用
**适用场景**:
- ✅ 需要了解实体之间的关系(如"Docker和Kubernetes的关系")
- ✅ 探索知识网络和概念关联
- ✅ 查找特定实体的相关信息
- ✅ 理解技术架构和系统关系
**不适用**:
- ❌ 普通文本搜索(用 knowledge_search 更合适)
- ❌ 知识库未配置图谱抽取
- ❌ 需要精确的文档内容(用 knowledge_search)
## 参数说明
**knowledge_base_ids** (required): 要查询的知识库ID数组(1-10个)
- 只有配置了图谱抽取的知识库才会有效
- 支持批量并发查询多个知识库
- 示例: ["kb_tech", "kb_arch"]
**query** (required): 查询内容
- 可以是实体名称(如"Docker")
- 可以是关系查询(如"容器编排")
- 可以是概念搜索(如"微服务架构")
## 图谱配置
知识图谱需要在知识库中预先配置:
- **实体类型**(Nodes):如"技术"、"工具"、"概念"
- **关系类型**(Relations):如"依赖"、"使用"、"包含"
如果知识库未配置图谱,工具会提示并返回普通搜索结果。
## 配合使用
1. **关系探索**: query_knowledge_graph → get_chunk_detail(查看详细内容)
2. **网络分析**: query_knowledge_graph → get_related_chunks(扩展上下文)
3. **主题研究**: knowledge_search → query_knowledge_graph(深入实体关系)
## 当前状态
⚠️ **注意**: 完整的图数据库集成正在开发中。当前版本:
- ✓ 支持图谱配置查询
- ✓ 返回图谱相关的文档片段
- ✓ 显示实体和关系配置信息
- ⏳ 完整的图查询语言(Cypher)支持开发中
- ⏳ 可视化图数据结构开发中
## Tips
- 结果会标注图谱配置状态
- 返回的Data字段包含结构化图信息供前端展示
- 跨知识库结果自动去重
- 按相关度排序`
return &QueryKnowledgeGraphTool{
BaseTool: NewBaseTool("query_knowledge_graph", description),
knowledgeService: knowledgeService,
}
}
// Parameters returns the JSON schema for the tool's parameters
func (t *QueryKnowledgeGraphTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"knowledge_base_ids": map[string]interface{}{
"type": "array",
"description": "Array of knowledge base IDs to query",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 10,
},
"query": map[string]interface{}{
"type": "string",
"description": "查询内容(实体名称或查询文本)",
},
},
"required": []string{"knowledge_base_ids", "query"},
}
}
// Execute queries the knowledge graph with concurrent KB processing
func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
// Extract knowledge_base_ids array
kbIDsRaw, ok := args["knowledge_base_ids"].([]interface{})
if !ok || len(kbIDsRaw) == 0 {
return &types.ToolResult{
Success: false,
Error: "knowledge_base_ids is required and must be a non-empty array",
}, fmt.Errorf("knowledge_base_ids is required")
}
// Convert to string slice
var kbIDs []string
for _, id := range kbIDsRaw {
if idStr, ok := id.(string); ok && idStr != "" {
kbIDs = append(kbIDs, idStr)
}
}
if len(kbIDs) == 0 {
return &types.ToolResult{
Success: false,
Error: "knowledge_base_ids must contain at least one valid KB ID",
}, fmt.Errorf("no valid KB IDs provided")
}
query, ok := args["query"].(string)
if !ok || query == "" {
return &types.ToolResult{
Success: false,
Error: "query is required",
}, fmt.Errorf("invalid query")
}
// Concurrently query all knowledge bases
type graphQueryResult struct {
kbID string
kb *types.KnowledgeBase
results []*types.SearchResult
err error
}
var wg sync.WaitGroup
var mu sync.Mutex
kbResults := make(map[string]*graphQueryResult)
searchParams := types.SearchParams{
QueryText: query,
MatchCount: 10,
}
for _, kbID := range kbIDs {
wg.Add(1)
go func(id string) {
defer wg.Done()
// Get knowledge base to check graph configuration
kb, err := t.knowledgeService.GetKnowledgeBaseByID(ctx, id)
if err != nil {
mu.Lock()
kbResults[id] = &graphQueryResult{kbID: id, err: fmt.Errorf("获取知识库失败: %v", err)}
mu.Unlock()
return
}
// Check if graph extraction is enabled
if kb.ExtractConfig == nil || (len(kb.ExtractConfig.Nodes) == 0 && len(kb.ExtractConfig.Relations) == 0) {
mu.Lock()
kbResults[id] = &graphQueryResult{kbID: id, err: fmt.Errorf("未配置知识图谱抽取")}
mu.Unlock()
return
}
// Query graph
results, err := t.knowledgeService.HybridSearch(ctx, id, searchParams)
if err != nil {
mu.Lock()
kbResults[id] = &graphQueryResult{kbID: id, kb: kb, err: fmt.Errorf("查询失败: %v", err)}
mu.Unlock()
return
}
mu.Lock()
kbResults[id] = &graphQueryResult{kbID: id, kb: kb, results: results}
mu.Unlock()
}(kbID)
}
wg.Wait()
// Collect and deduplicate results
seenChunks := make(map[string]*types.SearchResult)
var errors []string
graphConfigs := make(map[string]map[string]interface{})
kbCounts := make(map[string]int)
for _, kbID := range kbIDs {
result := kbResults[kbID]
if result.err != nil {
errors = append(errors, fmt.Sprintf("KB %s: %v", kbID, result.err))
continue
}
if result.kb != nil && result.kb.ExtractConfig != nil {
graphConfigs[kbID] = map[string]interface{}{
"nodes": result.kb.ExtractConfig.Nodes,
"relations": result.kb.ExtractConfig.Relations,
}
}
kbCounts[kbID] = len(result.results)
for _, r := range result.results {
if _, seen := seenChunks[r.ID]; !seen {
seenChunks[r.ID] = r
}
}
}
// Convert map to slice and sort by score
allResults := make([]*types.SearchResult, 0, len(seenChunks))
for _, result := range seenChunks {
allResults = append(allResults, result)
}
sort.Slice(allResults, func(i, j int) bool {
return allResults[i].Score > allResults[j].Score
})
if len(allResults) == 0 {
return &types.ToolResult{
Success: true,
Output: "未找到相关的图谱信息。",
Data: map[string]interface{}{
"knowledge_base_ids": kbIDs,
"query": query,
"results": []interface{}{},
"graph_configs": graphConfigs,
"errors": errors,
},
}, nil
}
// Format output with enhanced graph information
output := "=== 知识图谱查询 ===\n\n"
output += fmt.Sprintf("📊 查询: %s\n", query)
output += fmt.Sprintf("🎯 目标知识库: %v\n", kbIDs)
output += fmt.Sprintf("✓ 找到 %d 条相关结果(已去重)\n\n", len(allResults))
if len(errors) > 0 {
output += "=== ⚠️ 部分失败 ===\n"
for _, errMsg := range errors {
output += fmt.Sprintf(" - %s\n", errMsg)
}
output += "\n"
}
// Display graph configuration status
hasGraphConfig := false
output += "=== 📈 图谱配置状态 ===\n\n"
for kbID, config := range graphConfigs {
hasGraphConfig = true
output += fmt.Sprintf("知识库【%s】:\n", kbID)
nodes, _ := config["nodes"].([]interface{})
relations, _ := config["relations"].([]interface{})
if len(nodes) > 0 {
output += fmt.Sprintf(" ✓ 实体类型 (%d): ", len(nodes))
nodeNames := make([]string, 0, len(nodes))
for _, n := range nodes {
if nodeMap, ok := n.(map[string]interface{}); ok {
if name, ok := nodeMap["name"].(string); ok {
nodeNames = append(nodeNames, name)
}
}
}
output += fmt.Sprintf("%v\n", nodeNames)
} else {
output += " ⚠️ 未配置实体类型\n"
}
if len(relations) > 0 {
output += fmt.Sprintf(" ✓ 关系类型 (%d): ", len(relations))
relNames := make([]string, 0, len(relations))
for _, r := range relations {
if relMap, ok := r.(map[string]interface{}); ok {
if name, ok := relMap["name"].(string); ok {
relNames = append(relNames, name)
}
}
}
output += fmt.Sprintf("%v\n", relNames)
} else {
output += " ⚠️ 未配置关系类型\n"
}
output += "\n"
}
if !hasGraphConfig {
output += "⚠️ 所查询的知识库均未配置图谱抽取\n"
output += "💡 提示: 需要在知识库设置中配置实体和关系类型\n\n"
}
// Display result counts by KB
if len(kbCounts) > 0 {
output += "=== 📚 知识库覆盖 ===\n"
for kbID, count := range kbCounts {
output += fmt.Sprintf(" - %s: %d 条结果\n", kbID, count)
}
output += "\n"
}
// Display search results
output += "=== 🔍 查询结果 ===\n\n"
if !hasGraphConfig {
output += "💡 当前返回相关文档片段(知识库未配置图谱)\n\n"
} else {
output += "💡 基于图谱配置的相关内容检索\n\n"
}
formattedResults := make([]map[string]interface{}, 0, len(allResults))
currentKB := ""
for i, result := range allResults {
// Group by knowledge base
if result.KnowledgeID != currentKB {
currentKB = result.KnowledgeID
if i > 0 {
output += "\n"
}
output += fmt.Sprintf("【来源文档: %s】\n\n", result.KnowledgeTitle)
}
relevanceLevel := GetRelevanceLevel(result.Score)
output += fmt.Sprintf("结果 #%d:\n", i+1)
output += fmt.Sprintf(" 📍 相关度: %.2f (%s)\n", result.Score, relevanceLevel)
output += fmt.Sprintf(" 🔗 匹配方式: %s\n", FormatMatchType(result.MatchType))
output += fmt.Sprintf(" 📄 内容: %s\n", result.Content)
output += fmt.Sprintf(" 🆔 chunk_id: %s\n\n", result.ID)
formattedResults = append(formattedResults, map[string]interface{}{
"result_index": i + 1,
"chunk_id": result.ID,
"content": result.Content,
"score": result.Score,
"relevance_level": relevanceLevel,
"knowledge_id": result.KnowledgeID,
"knowledge_title": result.KnowledgeTitle,
"match_type": FormatMatchType(result.MatchType),
})
}
output += "=== 💡 使用提示 ===\n"
output += "- ✓ 结果已跨知识库去重并按相关度排序\n"
output += "- ✓ 使用 get_chunk_detail 获取完整内容\n"
output += "- ✓ 使用 get_related_chunks 探索上下文\n"
if !hasGraphConfig {
output += "- ⚠️ 配置图谱抽取以获得更精准的实体关系结果\n"
}
output += "- ⏳ 完整的图查询语言(Cypher)支持开发中\n"
// Build structured graph data for frontend visualization
graphData := buildGraphVisualizationData(allResults, graphConfigs)
return &types.ToolResult{
Success: true,
Output: output,
Data: map[string]interface{}{
"knowledge_base_ids": kbIDs,
"query": query,
"results": formattedResults,
"count": len(allResults),
"kb_counts": kbCounts,
"graph_configs": graphConfigs,
"graph_data": graphData,
"has_graph_config": hasGraphConfig,
"errors": errors,
"display_type": "graph_query_results",
},
}, nil
}
// buildGraphVisualizationData builds structured data for graph visualization
func buildGraphVisualizationData(results []*types.SearchResult, graphConfigs map[string]map[string]interface{}) map[string]interface{} {
// Build a simple graph structure for frontend visualization
nodes := make([]map[string]interface{}, 0)
edges := make([]map[string]interface{}, 0)
// Create nodes from results
seenEntities := make(map[string]bool)
for i, result := range results {
if !seenEntities[result.ID] {
nodes = append(nodes, map[string]interface{}{
"id": result.ID,
"label": fmt.Sprintf("Chunk %d", i+1),
"content": result.Content,
"kb_id": result.KnowledgeID,
"kb_title": result.KnowledgeTitle,
"score": result.Score,
"type": "chunk",
})
seenEntities[result.ID] = true
}
}
// TODO: Extract actual entities and relations when graph extraction is fully implemented
// For now, create placeholder structure
return map[string]interface{}{
"nodes": nodes,
"edges": edges,
"total_nodes": len(nodes),
"total_edges": len(edges),
"visualization_note": "完整的图可视化功能开发中,当前显示文档节点",
}
}
+108
View File
@@ -0,0 +1,108 @@
package tools
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
// ToolRegistry manages the registration and retrieval of tools
type ToolRegistry struct {
tools map[string]types.Tool
knowledgeBaseService interfaces.KnowledgeBaseService
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
db *gorm.DB // gorm.DB interface for database query tool
}
// NewToolRegistry creates a new tool registry
func NewToolRegistry(
knowledgeBaseService interfaces.KnowledgeBaseService,
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
db *gorm.DB, // gorm.DB for database operations
) *ToolRegistry {
return &ToolRegistry{
tools: make(map[string]types.Tool),
knowledgeBaseService: knowledgeBaseService,
knowledgeService: knowledgeService,
chunkService: chunkService,
db: db,
}
}
// RegisterTool adds a tool to the registry
func (r *ToolRegistry) RegisterTool(tool types.Tool) {
r.tools[tool.Name()] = tool
}
// GetTool retrieves a tool by name
func (r *ToolRegistry) GetTool(name string) (types.Tool, error) {
tool, exists := r.tools[name]
if !exists {
return nil, fmt.Errorf("tool not found: %s", name)
}
return tool, nil
}
// ListTools returns all registered tool names
func (r *ToolRegistry) ListTools() []string {
names := make([]string, 0, len(r.tools))
for name := range r.tools {
names = append(names, name)
}
return names
}
// GetFunctionDefinitions returns function definitions for allowed tools
// This is used for LLM function calling
func (r *ToolRegistry) GetFunctionDefinitions(allowedTools []string) []types.FunctionDefinition {
definitions := make([]types.FunctionDefinition, 0)
// If no allowed tools specified, return all tools
if len(allowedTools) == 0 {
for _, tool := range r.tools {
definitions = append(definitions, types.FunctionDefinition{
Name: tool.Name(),
Description: tool.Description(),
Parameters: tool.Parameters(),
})
}
return definitions
}
// Create a map for quick lookup
allowedMap := make(map[string]bool)
for _, name := range allowedTools {
allowedMap[name] = true
}
// Only include allowed tools
for name, tool := range r.tools {
if allowedMap[name] {
definitions = append(definitions, types.FunctionDefinition{
Name: tool.Name(),
Description: tool.Description(),
Parameters: tool.Parameters(),
})
}
}
return definitions
}
// ExecuteTool executes a tool by name with the given arguments
func (r *ToolRegistry) ExecuteTool(ctx context.Context, name string, args map[string]interface{}) (*types.ToolResult, error) {
tool, err := r.GetTool(name)
if err != nil {
return &types.ToolResult{
Success: false,
Error: err.Error(),
}, err
}
return tool.Execute(ctx, args)
}
+115
View File
@@ -0,0 +1,115 @@
package tools
import (
"context"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// ThinkingTool implements the thinking tool functionality
// This is a no-op tool inspired by code-agent and tau-bench
// It logs thoughts for transparency and better decision-making
type ThinkingTool struct {
BaseTool
}
// NewThinkingTool creates a new thinking tool instance
func NewThinkingTool() *ThinkingTool {
description := `Deep reasoning tool for systematic thinking. Use this frequently to analyze, plan, and reflect.
## Purpose
This tool helps you:
- **Analyze problems** before acting
- **Plan your approach** for complex tasks
- **Evaluate results** after tool calls
- **Reflect** on strategy and adjust
This is a no-op tool - it doesn't fetch data, but helps organize your reasoning transparently.
## When to Use
**Use frequently at key moments**:
- **Start**: Analyze the question, understand what's needed
- **Before major decisions**: Which tool to use? What query to run?
- **After tool calls**: Evaluate results, decide next step
- **Before answering**: Organize information, check completeness
## What to Think About
### At Start
- What is the user really asking?
- What information do I need?
- What's my search strategy?
### After Search Results
- Are results relevant? Complete?
- Do I need more context (get_related_chunks)?
- Should I search more or answer now?
### Before Answering
- Do I have enough information?
- Are all sources cited?
- Is the structure clear?
## Tips
- Use before important decisions
- Keep thoughts focused and actionable
- End with clear next step
- Don't overthink simple queries`
return &ThinkingTool{
BaseTool: NewBaseTool(
"thinking",
description,
),
}
}
// Parameters returns the JSON schema for the tool's parameters
func (t *ThinkingTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"thought": map[string]interface{}{
"type": "string",
"description": "Your thinking process and reasoning content",
},
},
"required": []string{"thought"},
}
}
// Execute executes the thinking tool
func (t *ThinkingTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][Thinking] Execute started")
thought, ok := args["thought"].(string)
if !ok {
thought = "Thought content not provided"
logger.Warnf(ctx, "[Tool][Thinking] No thought content provided")
}
logger.Infof(ctx, "[Tool][Thinking] Thought length: %d characters", len(thought))
logger.Debugf(ctx, "[Tool][Thinking] Thought content:\n%s", thought)
// This is a no-op tool - it just logs the thought
// The thought itself is valuable for transparency and decision-making
// Format output for better display
output := "Thought process recorded:\n\n"
output += thought
logger.Infof(ctx, "[Tool][Thinking] Execute completed")
return &types.ToolResult{
Success: true,
Output: output,
Data: map[string]interface{}{
"thought": thought,
"display_type": "thinking",
},
}, nil
}
+344
View File
@@ -0,0 +1,344 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"github.com/Tencent/WeKnora/internal/types"
)
// TodoWriteTool implements a planning tool for complex tasks
// This is an optional tool that helps organize multi-step research
type TodoWriteTool struct {
BaseTool
}
// PlanStep represents a single step in the research plan
type PlanStep struct {
ID string `json:"id"`
Description string `json:"description"`
ToolsToUse string `json:"tools_to_use"`
Status string `json:"status"` // pending, in_progress, completed, skipped
}
// NewTodoWriteTool creates a new todo_write tool instance
func NewTodoWriteTool() *TodoWriteTool {
description := `Use this tool to create a structured, actionable plan for complex research tasks. This helps you organize multi-step investigations, track progress, and ensure comprehensive coverage.
## Critical Thinking Integration
**IMPORTANT**: When working with complex research questions, you should typically use the **think tool** for deep analysis BEFORE creating your plan. This ensures:
- **Problem Analysis**: Use think tool to analyze the research question, identify key dimensions, and explore different angles
- **Strategic Planning**: Use think tool to consider what information is needed, which knowledge bases to search, and potential challenges
- **Scope Definition**: Use think tool to determine the depth and breadth of research required
The think tool helps ensure your plan is comprehensive, well-structured, and addresses all aspects of the research question effectively.
## When to Use This Tool
Use this tool proactively in these scenarios:
1. **Complex multi-dimensional questions** - Questions requiring investigation of multiple aspects or dimensions
2. **Comparison tasks** - When you need to compare multiple systems, approaches, or solutions systematically
3. **Deep research tasks** - Questions requiring exploration of multiple knowledge areas or documents
4. **Architecture analysis** - Tasks involving system design, architecture review, or technical deep-dives
5. **User requests explicit planning** - When users ask for structured analysis or step-by-step investigation
## When NOT to Use This Tool
Skip using this tool when:
1. **Simple, direct queries** - Questions with straightforward answers (e.g., "What is a vector database?")
2. **Single-step searches** - When you already know exactly what to search for
3. **Mid-execution** - Don't create plans after you've already started searching
4. **Trivial lookups** - Simple fact-finding that requires one tool call
NOTE: If the question can be answered with 1-2 simple searches, skip planning and search directly.
## Examples of When to Use
<example>
User: "如何设计一个高可用的微服务架构?需要考虑哪些方面?"
Assistant: This is a complex, multi-dimensional question. Let me first think through the key aspects and then create a structured research plan.
*Uses think tool to analyze: architecture patterns, reliability concerns, deployment strategies, monitoring needs*
Assistant: Based on my analysis, let me create a research plan covering the main dimensions.
*Creates plan with steps for:*
1. Search microservices architecture patterns and best practices
2. Investigate high availability strategies (load balancing, failover, redundancy)
3. Research service mesh and communication patterns
4. Explore monitoring and observability solutions
5. Investigate deployment and scaling strategies
*Begins executing the plan*
<reasoning>
The assistant used both think and todo_write tools because:
1. First used think tool to analyze the multi-dimensional nature of the question
2. Identified key areas: architecture, availability, communication, monitoring, deployment
3. Created a structured plan to ensure systematic coverage
4. The plan helps avoid missing critical aspects of high availability
</reasoning>
</example>
<example>
User: "对比Redis、Memcached和Hazelcast这三种缓存系统的性能、成本和适用场景"
Assistant: This is a structured comparison task. Let me think through the comparison dimensions and create a systematic research plan.
*Uses think tool to identify: performance metrics, cost factors, use case categories, comparison criteria*
Assistant: I'll create a research plan to ensure fair, comprehensive comparison across all three systems.
*Creates plan with steps:*
1. Search Redis characteristics (performance, features, use cases)
2. Search Memcached characteristics (performance, features, use cases)
3. Search Hazelcast characteristics (performance, features, use cases)
4. Search direct performance comparisons between these systems
5. Investigate cost considerations and deployment complexity
*Executes searches systematically*
<reasoning>
The assistant used todo_write because:
1. Comparison tasks benefit from structured, parallel research
2. The plan ensures each system is investigated equally
3. Structured approach prevents bias toward any particular system
4. Makes it easier to synthesize structured comparison at the end
</reasoning>
</example>
## Examples of When NOT to Use
<example>
User: "向量数据库的主要用途是什么?"
Assistant: Let me search for information about vector database use cases.
*Uses knowledge_search directly without planning*
<reasoning>
The assistant skipped todo_write because:
1. This is a simple, direct question
2. One well-crafted search will likely provide the answer
3. No need to organize multiple research steps
4. Planning would add unnecessary overhead
</reasoning>
</example>
<example>
User: "Kubernetes是什么?"
Assistant: Let me search for information about Kubernetes.
*Uses knowledge_search directly*
<reasoning>
Simple definitional question - just search directly without planning.
</reasoning>
</example>
## Standard Workflow
The recommended workflow when using this tool:
` + "```" + `
Step 1: User asks complex question
↓
Step 2: Use think tool (analyze problem, identify dimensions, consider approaches)
↓
Step 3: Use todo_write tool (create structured plan with steps, tools, priorities) [OPTIONAL]
↓
Step 4: Execute plan steps (use search tools, mark progress)
↓
Step 5: Use think tool (evaluate results, identify gaps)
↓
Step 6: Adjust plan or execute remaining steps
↓
Step 7: Synthesize comprehensive answer with citations
` + "```" + `
## Plan Structure
Your plan should include steps with:
- **ID**: Unique identifier for each step (e.g., "step1", "step2")
- **Description**: Clear description of what to investigate
- **Tools to Use**: Which tools to use (e.g., "knowledge_search", "get_related_chunks")
- **Status**: Current status (pending, in_progress, completed, skipped)
## Step Status Management
1. **Status Values**:
- **pending**: Step not yet started (default for new steps)
- **in_progress**: Currently executing this step
- **completed**: Step finished successfully with results
- **skipped**: Step determined to be unnecessary based on findings
2. **Status Management Best Practices**:
- Start with all steps as "pending"
- Mark one step as "in_progress" before executing it
- Update to "completed" immediately after finishing
- Mark as "skipped" if findings make a step unnecessary
## Parameters
- **task** (required): The complex task or question you need to create a plan for
- Be specific about what needs to be accomplished
- Include the user's actual question or research goal
- **steps** (required): Array of plan steps, each containing:
- **id**: Unique identifier (e.g., "step1", "step2")
- **description**: What to investigate or accomplish
- **tools_to_use**: Suggested tools for this step
- **status**: Current status (pending, in_progress, completed, skipped)
## Best Practices
1. **Think First**: Always use think tool before creating a plan to ensure thorough analysis
2. **Be Specific**: Each step should have a clear, actionable objective
3. **Stay Flexible**: Adjust the plan based on findings - some steps may become unnecessary
4. **Track Progress**: Update step status as you work through the plan
5. **Don't Over-plan**: 3-7 steps is usually sufficient; more suggests over-complexity
`
return &TodoWriteTool{
BaseTool: NewBaseTool("todo_write", description),
}
}
// Parameters returns the JSON schema for the tool's parameters
func (t *TodoWriteTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"task": map[string]interface{}{
"type": "string",
"description": "The complex task or question you need to create a plan for",
},
"steps": map[string]interface{}{
"type": "array",
"description": "Array of research plan steps with status tracking",
"items": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"id": map[string]interface{}{
"type": "string",
"description": "Unique identifier for this step (e.g., 'step1', 'step2')",
},
"description": map[string]interface{}{
"type": "string",
"description": "Clear description of what to investigate or accomplish in this step",
},
"tools_to_use": map[string]interface{}{
"type": "string",
"description": "Suggested tools for this step (e.g., 'knowledge_search', 'get_related_chunks')",
},
"status": map[string]interface{}{
"type": "string",
"enum": []string{"pending", "in_progress", "completed", "skipped"},
"description": "Current status: pending (not started), in_progress (executing), completed (finished), skipped (unnecessary)",
},
},
"required": []string{"id", "description", "status"},
},
},
},
"required": []string{"task", "steps"},
}
}
// Execute executes the todo_write tool
func (t *TodoWriteTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
task, ok := args["task"].(string)
if !ok {
task = "未提供任务描述"
}
// Parse plan steps
var planSteps []PlanStep
if stepsData, ok := args["steps"].([]interface{}); ok {
for _, stepData := range stepsData {
if stepMap, ok := stepData.(map[string]interface{}); ok {
step := PlanStep{
ID: getStringField(stepMap, "id"),
Description: getStringField(stepMap, "description"),
ToolsToUse: getStringField(stepMap, "tools_to_use"),
Status: getStringField(stepMap, "status"),
}
planSteps = append(planSteps, step)
}
}
}
// Generate formatted output
output := generatePlanOutput(task, planSteps)
// Prepare structured data for response
stepsJSON, _ := json.Marshal(planSteps)
return &types.ToolResult{
Success: true,
Output: output,
Data: map[string]interface{}{
"task": task,
"steps": planSteps,
"steps_json": string(stepsJSON),
"total_steps": len(planSteps),
"plan_created": true,
"display_type": "plan",
},
}, nil
}
// Helper function to safely get string field from map
func getStringField(m map[string]interface{}, key string) string {
if val, ok := m[key].(string); ok {
return val
}
return ""
}
// generatePlanOutput generates a formatted plan output
func generatePlanOutput(task string, steps []PlanStep) string {
output := "计划已创建\n\n"
output += fmt.Sprintf("**任务**: %s\n\n", task)
if len(steps) == 0 {
output += "注意:未提供具体步骤。建议创建3-7个结构化步骤以系统化研究。\n\n"
output += "建议的通用流程:\n"
output += "1. 使用 knowledge_search 进行初步信息收集\n"
output += "2. 使用 get_related_chunks 获取关键信息详情\n"
output += "3. 使用 get_related_chunks 扩展上下文理解\n"
output += "4. 使用 think 工具评估结果并综合答案\n"
return output
}
output += "**计划步骤**:\n\n"
// Display all steps in order
for i, step := range steps {
output += formatPlanStep(i+1, step)
}
output += "\n**执行指南**:\n"
output += "- 每步执行前标记为 in_progress,完成后标记为 completed\n"
output += "- 根据搜索结果灵活调整计划,可跳过不必要的步骤\n"
output += "- 在关键决策点使用 think 工具深入分析\n"
output += "- 如果某一步骤已获得足够信息,可跳过后续步骤\n\n"
output += "注意:计划是指导而非硬性要求,保持灵活应对。"
return output
}
// formatPlanStep formats a single plan step for output
func formatPlanStep(index int, step PlanStep) string {
statusEmoji := map[string]string{
"pending": "⏳",
"in_progress": "🔄",
"completed": "✅",
"skipped": "⏭️",
}
emoji, ok := statusEmoji[step.Status]
if !ok {
emoji = "⏳"
}
output := fmt.Sprintf(" %d. %s [%s] %s\n", index, emoji, step.Status, step.Description)
if step.ToolsToUse != "" {
output += fmt.Sprintf(" 工具: %s\n", step.ToolsToUse)
}
return output
}
+77
View File
@@ -0,0 +1,77 @@
package tools
import (
"fmt"
"github.com/Tencent/WeKnora/internal/types"
)
// BaseTool provides common functionality for tools
type BaseTool struct {
name string
description string
}
// NewBaseTool creates a new base tool
func NewBaseTool(name, description string) BaseTool {
return BaseTool{
name: name,
description: description,
}
}
// Name returns the tool name
func (t *BaseTool) Name() string {
return t.name
}
// Description returns the tool description
func (t *BaseTool) Description() string {
return t.description
}
// ToolExecutor is a helper interface for executing tools
type ToolExecutor interface {
types.Tool
// GetContext returns any context-specific data needed for tool execution
GetContext() map[string]interface{}
}
// Shared helper functions for tool output formatting
// GetRelevanceLevel converts a score to a human-readable relevance level
func GetRelevanceLevel(score float64) string {
switch {
case score >= 0.8:
return "高相关"
case score >= 0.6:
return "中相关"
case score >= 0.4:
return "低相关"
default:
return "弱相关"
}
}
// FormatMatchType converts MatchType to a human-readable string
func FormatMatchType(mt types.MatchType) string {
switch mt {
case types.MatchTypeEmbedding:
return "向量匹配"
case types.MatchTypeKeywords:
return "关键词匹配"
case types.MatchTypeNearByChunk:
return "相邻块匹配"
case types.MatchTypeHistory:
return "历史匹配"
case types.MatchTypeParentChunk:
return "父块匹配"
case types.MatchTypeRelationChunk:
return "关系块匹配"
case types.MatchTypeGraph:
return "图谱匹配"
default:
return fmt.Sprintf("未知类型(%d)", mt)
}
}