feat: Add DataSchema tool for retrieving schema information from CSV and Excel files

This commit is contained in:
begoniezhao
2025-12-23 16:56:30 +08:00
parent ddf5ae4e65
commit 907e9a5522
51 changed files with 2784 additions and 1307 deletions
+460
View File
@@ -0,0 +1,460 @@
package tools
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
_ "github.com/duckdb/duckdb-go/v2"
)
var dataAnalysisTool = BaseTool{
name: ToolDataAnalysis,
description: "Use this tool when the knowledge is CSV or Excel files. It loads the data into memory and executes SQL for data analysis. If the user's question requires data statistics, convert the question into SQL and execute it.",
schema: utils.GenerateSchema[DataAnalysisInput](),
}
type DataAnalysisInput struct {
KnowledgeID string `json:"knowledge_id" jsonschema:"id of the knowledge to query"`
Sql string `json:"sql" jsonschema:"SQL to be executed on knowledge"`
}
type DataAnalysisTool struct {
BaseTool
knowledgeService interfaces.KnowledgeService
db *sql.DB
sessionID string
createdTables []string // Track tables created in this session
}
func NewDataAnalysisTool(knowledgeService interfaces.KnowledgeService, db *sql.DB, sessionID string) *DataAnalysisTool {
return &DataAnalysisTool{
BaseTool: dataAnalysisTool,
knowledgeService: knowledgeService,
db: db,
sessionID: sessionID,
}
}
// recordCreatedTable records a table name for cleanup, ensuring uniqueness
// Returns true if the table was newly recorded, false if it already existed
func (t *DataAnalysisTool) recordCreatedTable(tableName string) bool {
for _, name := range t.createdTables {
if name == tableName {
return false
}
}
t.createdTables = append(t.createdTables, tableName)
return true
}
// Cleanup cleans up the session-specific schema
func (t *DataAnalysisTool) Cleanup(ctx context.Context) {
if len(t.createdTables) == 0 {
logger.Infof(ctx, "[Tool][DataAnalysis] No tables to clean up for session: %s", t.sessionID)
return
}
logger.Infof(ctx, "[Tool][DataAnalysis] Cleaning up %d tables for session: %s", len(t.createdTables), t.sessionID)
for _, tableName := range t.createdTables {
dropSQL := fmt.Sprintf("DROP TABLE IF EXISTS \"%s\"", tableName)
if _, err := t.db.ExecContext(ctx, dropSQL); err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to drop table '%s': %v", tableName, err)
// Continue to drop other tables even if one fails
continue
}
logger.Infof(ctx, "[Tool][DataAnalysis] Successfully dropped table '%s'", tableName)
}
// Clear the list after cleanup
t.createdTables = nil
}
// Execute executes the SQL query on DuckDB (only read-only queries are allowed)
func (t *DataAnalysisTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][DataAnalysis] Execute started for session: %s", t.sessionID)
var input DataAnalysisInput
if err := json.Unmarshal(args, &input); err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to parse input args: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse input args: %v", err),
}, err
}
schema, err := t.LoadFromKnowledgeID(ctx, input.KnowledgeID)
if err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to load knowledge ID '%s': %v", input.KnowledgeID, err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to load knowledge ID '%s': %v", input.KnowledgeID, err),
}, err
}
// Replace knowledge ID with table name
input.Sql = strings.ReplaceAll(input.Sql, input.KnowledgeID, schema.TableName)
// Check if this is a read-only query
normalizedSQL := strings.TrimSpace(strings.ToLower(input.Sql))
isReadOnly := strings.HasPrefix(normalizedSQL, "select") ||
strings.HasPrefix(normalizedSQL, "show") ||
strings.HasPrefix(normalizedSQL, "describe") ||
strings.HasPrefix(normalizedSQL, "explain") ||
strings.HasPrefix(normalizedSQL, "pragma")
if !isReadOnly {
// Reject modification queries
logger.Warnf(ctx, "[Tool][DataAnalysis] Modification query rejected for session %s: %s", t.sessionID, input.Sql)
return &types.ToolResult{
Success: false,
Error: "DuckDB tool only supports read-only queries (SELECT, SHOW, DESCRIBE, EXPLAIN, PRAGMA). Modification operations (INSERT, UPDATE, DELETE, CREATE, DROP, etc.) are not allowed.",
}, fmt.Errorf("modification queries are not allowed")
}
logger.Infof(ctx, "[Tool][DataAnalysis] Received SQL query for session %s: %s", t.sessionID, input.Sql)
// Execute single query and get results
results, err := t.executeSingleQuery(ctx, input.Sql)
if err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Query execution failed: %v", err),
}, err
}
queryOutput := t.formatQueryResults(results, input.Sql)
logger.Infof(ctx, "[Tool][DataAnalysis] Completed execution query, total %d rows for session %s", len(results), t.sessionID)
return &types.ToolResult{
Success: true,
Output: queryOutput,
Data: map[string]interface{}{
"rows": results,
"row_count": len(results),
"query": input.Sql,
"display_type": ToolDataAnalysis,
"session_id": t.sessionID,
},
}, nil
}
// executeSingleQuery executes a single SQL query and returns columns and results
// Parameters:
// - ctx: context for cancellation and timeout
// - sqlQuery: the SQL query to execute
// - existingColumns: existing column names to merge with (can be nil or empty)
//
// Returns:
// - []string: merged column names (existing + new columns, deduplicated)
// - []map[string]string: query results
// - error: any error that occurred during execution
func (t *DataAnalysisTool) executeSingleQuery(ctx context.Context, sqlQuery string) ([]map[string]string, error) {
rows, err := t.db.QueryContext(ctx, sqlQuery)
if err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Query execution failed: %v", err)
return nil, fmt.Errorf("query execution failed: %w", err)
}
defer rows.Close()
// Get column names
columns, err := rows.Columns()
if err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to get columns: %v", err)
return nil, fmt.Errorf("failed to get columns: %w", err)
}
// Process results
results := make([]map[string]string, 0)
for rows.Next() {
columnValues := make([]interface{}, len(columns))
columnPointers := make([]interface{}, len(columns))
for i := range columnValues {
columnPointers[i] = &columnValues[i]
}
if err := rows.Scan(columnPointers...); err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to scan row: %v", err)
return nil, fmt.Errorf("failed to scan row: %w", err)
}
rowMap := make(map[string]string)
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] = fmt.Sprintf("%v", val)
}
}
results = append(results, rowMap)
}
if err := rows.Err(); err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Error iterating rows: %v", err)
return nil, fmt.Errorf("error iterating rows: %w", err)
}
return results, nil
}
// formatQueryResults formats query results into JSONL format (one JSON object per line)
func (t *DataAnalysisTool) formatQueryResults(results []map[string]string, query string) string {
var output strings.Builder
output.WriteString("=== DuckDB 查询结果 ===\n\n")
output.WriteString(fmt.Sprintf("执行的SQL: %s\n\n", query))
output.WriteString(fmt.Sprintf("返回 %d 行数据\n\n", len(results)))
if len(results) == 0 {
output.WriteString("未找到匹配的记录。\n")
return output.String()
}
output.WriteString("=== 数据详情 ===\n\n")
if len(results) > 10 {
output.WriteString(fmt.Sprintf("显示了所有 %d 条记录。建议使用 LIMIT 子句限制结果数量以提高性能。\n\n", len(results)))
}
// Write each record as a separate JSON line
for i, record := range results {
recordBytes, _ := json.Marshal(record)
// Remove the trailing newline added by Encode
recordStr := strings.Trim(string(recordBytes), "\n")
output.WriteString(fmt.Sprintf("record %d: %s\n", i+1, recordStr))
}
return output.String()
}
// TableSchema represents the schema information of a table
type TableSchema struct {
TableName string `json:"table_name"`
Columns []ColumnInfo `json:"columns"`
RowCount int64 `json:"row_count"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
// ColumnInfo represents information about a single column
type ColumnInfo struct {
Name string `json:"name"`
Type string `json:"type"`
Nullable string `json:"nullable"`
}
// LoadFromCSV loads data from a CSV file into a DuckDB table and returns the table schema
// Parameters:
// - ctx: context for cancellation and timeout
// - filename: path to the CSV file
// - tableName: name of the table to create
//
// Returns:
// - *TableSchema: schema information of the created table
// - error: any error that occurred during the operation
func (t *DataAnalysisTool) LoadFromCSV(ctx context.Context, filename string, tableName string) (*TableSchema, error) {
logger.Infof(ctx, "[Tool][DataAnalysis] Loading CSV file '%s' into table '%s' for session %s", filename, tableName, t.sessionID)
// Record the created table for cleanup. If already exists, skip creation
if t.recordCreatedTable(tableName) {
// Create table from CSV using DuckDB's read_csv_auto function
// Table will be created in the session schema
createTableSQL := fmt.Sprintf("CREATE TABLE \"%s\" AS SELECT * FROM read_csv_auto('%s')", tableName, filename)
_, err := t.db.ExecContext(ctx, createTableSQL)
if err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to create table from CSV: %v", err)
return nil, fmt.Errorf("failed to create table from CSV: %w", err)
}
logger.Infof(ctx, "[Tool][DataAnalysis] Successfully created table '%s' from CSV file in session %s", tableName, t.sessionID)
}
// Get and return the table schema
return t.LoadFromTable(ctx, tableName)
}
// LoadFromExcel loads data from an Excel file into a DuckDB table and returns the table schema
// Parameters:
// - ctx: context for cancellation and timeout
// - filename: path to the Excel file
// - tableName: name of the table to create
//
// Returns:
// - *TableSchema: schema information of the created table
// - error: any error that occurred during the operation
//
// Note: This function requires the spatial extension to be installed in DuckDB
func (t *DataAnalysisTool) LoadFromExcel(ctx context.Context, filename string, tableName string) (*TableSchema, error) {
logger.Infof(ctx, "[Tool][DataAnalysis] Loading Excel file '%s' into table '%s' for session %s", filename, tableName, t.sessionID)
// Record the created table for cleanup. If already exists, skip creation
if t.recordCreatedTable(tableName) {
// Try to read Excel file using st_read (from spatial extension)
// If spatial extension doesn't support Excel, we'll need to convert to CSV first
createTableSQL := fmt.Sprintf("CREATE TABLE \"%s\" AS SELECT * FROM st_read('%s')", tableName, filename)
_, err := t.db.ExecContext(ctx, createTableSQL)
if err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to create table from Excel: %v", err)
return nil, fmt.Errorf("failed to create table from Excel file. Consider converting to CSV first: %w", err)
}
logger.Infof(ctx, "[Tool][DataAnalysis] Successfully created table '%s' from Excel file in session %s", tableName, t.sessionID)
}
// Get and return the table schema
return t.LoadFromTable(ctx, tableName)
}
// LoadFromKnowledge loads data from a Knowledge entity into a DuckDB table and returns the table schema
// It automatically determines the file type and calls the appropriate loading method
// Parameters:
// - ctx: context for cancellation and timeout
// - knowledge: the Knowledge entity containing file information
//
// Returns:
// - *TableSchema: schema information of the created table
// - error: any error that occurred during the operation
func (t *DataAnalysisTool) LoadFromKnowledge(ctx context.Context, knowledge *types.Knowledge) (*TableSchema, error) {
if knowledge == nil {
return nil, fmt.Errorf("knowledge cannot be nil")
}
tableName := t.TableName(knowledge)
// Normalize file type to lowercase for comparison
fileType := strings.ToLower(knowledge.FileType)
logger.Infof(ctx, "[Tool][DataAnalysis] Loading knowledge '%s' (type: %s) into table '%s' for session %s",
knowledge.ID, fileType, tableName, t.sessionID)
switch fileType {
case "csv":
return t.LoadFromCSV(ctx, knowledge.FilePath, tableName)
case "xlsx", "xls":
return t.LoadFromExcel(ctx, knowledge.FilePath, tableName)
default:
logger.Warnf(ctx, "[Tool][DataAnalysis] Unsupported file type '%s' for knowledge '%s' in session %s",
fileType, knowledge.ID, t.sessionID)
return nil, fmt.Errorf("unsupported file type: %s (supported types: csv, xlsx, xls)", fileType)
}
}
// LoadFromKnowledgeID loads data from a Knowledge ID into a DuckDB table and returns the table schema
// Parameters:
// - ctx: context for cancellation and timeout
// - knowledgeID: the ID of the Knowledge entity
//
// Returns:
// - string: the name of the created table
// - *TableSchema: schema information of the created table
// - error: any error that occurred during the operation
func (t *DataAnalysisTool) LoadFromKnowledgeID(ctx context.Context, knowledgeID string) (*TableSchema, error) {
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, knowledgeID)
if err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to get knowledge by ID '%s': %v", knowledgeID, err)
return nil, fmt.Errorf("failed to get knowledge by ID: %w", err)
}
return t.LoadFromKnowledge(ctx, knowledge)
}
// LoadFromTable retrieves the schema information of an existing table
// Parameters:
// - ctx: context for cancellation and timeout
// - tableName: name of the table to query
//
// Returns:
// - *TableSchema: schema information of the table
// - error: any error that occurred during the operation
//
// Note: This function does NOT create the table, it only retrieves schema information
func (t *DataAnalysisTool) LoadFromTable(ctx context.Context, tableName string) (*TableSchema, error) {
logger.Infof(ctx, "[Tool][DataAnalysis] Getting schema for table '%s' in session %s", tableName, t.sessionID)
// Query to get column information using PRAGMA table_info or DESCRIBE
schemaSQL := fmt.Sprintf("DESCRIBE \"%s\"", tableName)
rows, err := t.db.QueryContext(ctx, schemaSQL)
if err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to get table schema: %v", err)
return nil, fmt.Errorf("failed to get table schema: %w", err)
}
defer rows.Close()
// Parse column information
columns := make([]ColumnInfo, 0)
for rows.Next() {
var colName, colType, nullable string
var extra1, extra2, extra3 interface{} // DuckDB DESCRIBE may return additional columns
// Try to scan with different column counts
err := rows.Scan(&colName, &colType, &nullable, &extra1, &extra2, &extra3)
if err != nil {
// Try with fewer columns
err = rows.Scan(&colName, &colType, &nullable)
if err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to scan column info: %v", err)
return nil, fmt.Errorf("failed to scan column info: %w", err)
}
}
columns = append(columns, ColumnInfo{
Name: colName,
Type: colType,
Nullable: nullable,
})
}
if err := rows.Err(); err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Error iterating schema rows: %v", err)
return nil, fmt.Errorf("error iterating schema rows: %w", err)
}
// Get row count
countSQL := fmt.Sprintf("SELECT COUNT(*) FROM \"%s\"", tableName)
var rowCount int64
if err := t.db.QueryRowContext(ctx, countSQL).Scan(&rowCount); err != nil {
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to get row count: %v", err)
return nil, fmt.Errorf("failed to get row count: %w", err)
}
schema := &TableSchema{
TableName: tableName,
Columns: columns,
RowCount: rowCount,
Metadata: map[string]interface{}{
"column_count": len(columns),
"session_id": t.sessionID,
},
}
logger.Infof(ctx, "[Tool][DataAnalysis] Retrieved schema for table '%s' in session %s: %d columns, %d rows",
tableName, t.sessionID, len(columns), rowCount)
return schema, nil
}
func (t *DataAnalysisTool) TableName(knowledge *types.Knowledge) string {
return "k_" + strings.ReplaceAll(knowledge.ID, "-", "_")
}
// buildSchemaDescription builds a formatted schema description
func (t *TableSchema) Description() string {
var builder strings.Builder
builder.WriteString(fmt.Sprintf("表名: %s\n", t.TableName))
builder.WriteString(fmt.Sprintf("列数: %d\n", len(t.Columns)))
builder.WriteString(fmt.Sprintf("行数: %d\n\n", t.RowCount))
builder.WriteString("列信息:\n")
for _, col := range t.Columns {
builder.WriteString(fmt.Sprintf("- %s (%s)\n", col.Name, col.Type))
}
return builder.String()
}
+114
View File
@@ -0,0 +1,114 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
)
var dataSchemaTool = BaseTool{
name: ToolDataSchema,
description: "Use this tool to get the schema information of a CSV or Excel file loaded into DuckDB. It returns the table name, columns, and row count.",
schema: utils.GenerateSchema[DataSchemaInput](),
}
type DataSchemaInput struct {
KnowledgeID string `json:"knowledge_id" jsonschema:"id of the knowledge to query"`
}
type DataSchemaTool struct {
BaseTool
knowledgeService interfaces.KnowledgeService
chunkRepo interfaces.ChunkRepository
targetChunkTypes []types.ChunkType
}
func NewDataSchemaTool(knowledgeService interfaces.KnowledgeService, chunkRepo interfaces.ChunkRepository, targetChunkTypes ...types.ChunkType) *DataSchemaTool {
if len(targetChunkTypes) == 0 {
targetChunkTypes = []types.ChunkType{types.ChunkTypeTableSummary, types.ChunkTypeTableColumn}
}
return &DataSchemaTool{
BaseTool: dataSchemaTool,
knowledgeService: knowledgeService,
chunkRepo: chunkRepo,
targetChunkTypes: targetChunkTypes,
}
}
// Execute executes the tool logic
func (t *DataSchemaTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var input DataSchemaInput
if err := json.Unmarshal(args, &input); err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse input args: %v", err),
}, err
}
// Get knowledge to get TenantID
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, input.KnowledgeID)
if err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to get knowledge '%s': %v", input.KnowledgeID, err),
}, err
}
// Get chunks for the knowledge ID using ChunkRepository
// We only need table summary and column chunks
chunkTypes := t.targetChunkTypes
page := &types.Pagination{
Page: 1,
PageSize: 100, // Should be enough for schema chunks
}
chunks, _, err := t.chunkRepo.ListPagedChunksByKnowledgeID(
ctx,
knowledge.TenantID,
input.KnowledgeID,
page,
chunkTypes,
"", // tagID
"", // keyword
"", // searchField
"", // sortOrder
"", // knowledgeType
)
if err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to list chunks for knowledge ID '%s': %v", input.KnowledgeID, err),
}, err
}
var summaryContent, columnContent string
for _, chunk := range chunks {
if chunk.ChunkType == types.ChunkTypeTableSummary {
summaryContent = chunk.Content
} else if chunk.ChunkType == types.ChunkTypeTableColumn {
columnContent = chunk.Content
}
}
if summaryContent == "" || columnContent == "" {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("No table schema information found for knowledge ID '%s'", input.KnowledgeID),
}, fmt.Errorf("no schema info found")
}
output := fmt.Sprintf("%s\n\n%s", summaryContent, columnContent)
return &types.ToolResult{
Success: true,
Output: output,
Data: map[string]interface{}{
"summary": summaryContent,
"columns": columnContent,
},
}, nil
}
+117 -108
View File
@@ -9,92 +9,14 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
pg_query "github.com/pganalyze/pg_query_go/v6"
"gorm.io/gorm"
)
// SQLSecurityValidator provides comprehensive SQL injection protection using PostgreSQL's official parser
type SQLSecurityValidator struct {
allowedTables map[string]bool
allowedFunctions map[string]bool
tenantID uint64
}
// NewSQLSecurityValidator creates a new SQL security validator
func NewSQLSecurityValidator(tenantID uint64) *SQLSecurityValidator {
return &SQLSecurityValidator{
allowedTables: map[string]bool{
"tenants": true,
"knowledge_bases": true,
"knowledges": true,
"sessions": true,
"messages": true,
"chunks": true,
"embeddings": true,
"models": true,
},
// Whitelist of allowed SQL functions (aggregates and safe functions only)
allowedFunctions: map[string]bool{
// Aggregate functions
"count": true,
"sum": true,
"avg": true,
"min": true,
"max": true,
"array_agg": true,
"string_agg": true,
"bool_and": true,
"bool_or": true,
"json_agg": true,
"jsonb_agg": true,
"json_object_agg": true,
"jsonb_object_agg": true,
// Safe scalar functions
"coalesce": true,
"nullif": true,
"greatest": true,
"least": true,
"abs": true,
"ceil": true,
"floor": true,
"round": true,
"length": true,
"lower": true,
"upper": true,
"trim": true,
"ltrim": true,
"rtrim": true,
"substring": true,
"concat": true,
"concat_ws": true,
"replace": true,
"left": true,
"right": true,
"now": true,
"current_date": true,
"current_timestamp": true,
"date_trunc": true,
"extract": true,
"to_char": true,
"to_date": true,
"to_timestamp": true,
"date_part": true,
"age": true,
},
tenantID: tenantID,
}
}
// DatabaseQueryTool allows AI to query the database with auto-injected tenant_id for security
type DatabaseQueryTool struct {
BaseTool
db *gorm.DB
tenantID uint64
}
// NewDatabaseQueryTool creates a new database query tool
func NewDatabaseQueryTool(db *gorm.DB, tenantID uint64) *DatabaseQueryTool {
description := `Execute SQL queries to retrieve information from the database.
var databaseQueryTool = BaseTool{
name: ToolDatabaseQuery,
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
@@ -171,36 +93,123 @@ Join knowledge bases and documents:
- 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`
- All timestamps are in UTC with time zone`,
schema: utils.GenerateSchema[DatabaseQueryInput](),
}
return &DatabaseQueryTool{
BaseTool: NewBaseTool("database_query", description),
db: db,
type DatabaseQueryInput struct {
SQL string `json:"sql" jsonschema:"The SELECT SQL query to execute. DO NOT include tenant_id condition - it will be automatically added for security."`
}
// SQLSecurityValidator provides comprehensive SQL injection protection using PostgreSQL's official parser
type SQLSecurityValidator struct {
allowedTables map[string]bool
allowedFunctions map[string]bool
tenantID uint64
}
// NewSQLSecurityValidator creates a new SQL security validator
func NewSQLSecurityValidator(tenantID uint64) *SQLSecurityValidator {
return &SQLSecurityValidator{
allowedTables: map[string]bool{
"tenants": true,
"knowledge_bases": true,
"knowledges": true,
"sessions": true,
"messages": true,
"chunks": true,
"embeddings": true,
"models": true,
},
// Whitelist of allowed SQL functions (aggregates and safe functions only)
allowedFunctions: map[string]bool{
// Aggregate functions
"count": true,
"sum": true,
"avg": true,
"min": true,
"max": true,
"array_agg": true,
"string_agg": true,
"bool_and": true,
"bool_or": true,
"json_agg": true,
"jsonb_agg": true,
"json_object_agg": true,
"jsonb_object_agg": true,
// Safe scalar functions
"coalesce": true,
"nullif": true,
"greatest": true,
"least": true,
"abs": true,
"ceil": true,
"floor": true,
"round": true,
"length": true,
"lower": true,
"upper": true,
"trim": true,
"ltrim": true,
"rtrim": true,
"substring": true,
"concat": true,
"concat_ws": true,
"replace": true,
"left": true,
"right": true,
"now": true,
"current_date": true,
"current_timestamp": true,
"date_trunc": true,
"extract": true,
"to_char": true,
"to_date": true,
"to_timestamp": true,
"date_part": true,
"age": true,
},
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"},
// DatabaseQueryInput defines the input parameters for database query tool
// DatabaseQueryTool allows AI to query the database with auto-injected tenant_id for security
type DatabaseQueryTool struct {
BaseTool
db *gorm.DB
}
// NewDatabaseQueryTool creates a new database query tool
func NewDatabaseQueryTool(db *gorm.DB) *DatabaseQueryTool {
return &DatabaseQueryTool{
BaseTool: databaseQueryTool,
db: db,
}
}
// Execute executes the database query tool
func (t *DatabaseQueryTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
func (t *DatabaseQueryTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][DatabaseQuery] Execute started")
// Extract SQL from args
sqlQuery, ok := args["sql"].(string)
if !ok || sqlQuery == "" {
tenantID := uint64(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
tenantID = tid
}
// Parse args from json.RawMessage
var input DatabaseQueryInput
if err := json.Unmarshal(args, &input); err != nil {
logger.Errorf(ctx, "[Tool][DatabaseQuery] Failed to parse args: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, err
}
// Extract SQL from input
if input.SQL == "" {
logger.Errorf(ctx, "[Tool][DatabaseQuery] Missing or invalid SQL parameter")
return &types.ToolResult{
Success: false,
@@ -208,12 +217,12 @@ func (t *DatabaseQueryTool) Execute(ctx context.Context, args map[string]interfa
}, 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)
logger.Infof(ctx, "[Tool][DatabaseQuery] Original SQL query:\n%s", input.SQL)
logger.Infof(ctx, "[Tool][DatabaseQuery] Tenant ID: %d", tenantID)
// Validate and secure the SQL query
logger.Debugf(ctx, "[Tool][DatabaseQuery] Validating and securing SQL...")
securedSQL, err := t.validateAndSecureSQL(sqlQuery)
securedSQL, err := t.validateAndSecureSQL(input.SQL, tenantID)
if err != nil {
logger.Errorf(ctx, "[Tool][DatabaseQuery] SQL validation failed: %v", err)
return &types.ToolResult{
@@ -224,7 +233,7 @@ func (t *DatabaseQueryTool) Execute(ctx context.Context, args map[string]interfa
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)
input.SQL, securedSQL, tenantID)
// Execute the query
logger.Infof(ctx, "[Tool][DatabaseQuery] Executing query against database...")
@@ -312,15 +321,15 @@ func (t *DatabaseQueryTool) Execute(ctx context.Context, args map[string]interfa
"rows": results,
"row_count": len(results),
"query": securedSQL,
"tenant_id": t.tenantID,
"tenant_id": tenantID,
"display_type": "database_query",
},
}, nil
}
// validateAndSecureSQL validates the SQL query and injects tenant_id conditions
func (t *DatabaseQueryTool) validateAndSecureSQL(sqlQuery string) (string, error) {
validator := NewSQLSecurityValidator(t.tenantID)
func (t *DatabaseQueryTool) validateAndSecureSQL(sqlQuery string, tenantID uint64) (string, error) {
validator := NewSQLSecurityValidator(tenantID)
return validator.ValidateAndSecure(sqlQuery)
}
+36 -16
View File
@@ -1,5 +1,21 @@
package tools
// Tool names constants
const (
ToolThinking = "thinking"
ToolTodoWrite = "todo_write"
ToolGrepChunks = "grep_chunks"
ToolKnowledgeSearch = "knowledge_search"
ToolListKnowledgeChunks = "list_knowledge_chunks"
ToolQueryKnowledgeGraph = "query_knowledge_graph"
ToolGetDocumentInfo = "get_document_info"
ToolDatabaseQuery = "database_query"
ToolDataAnalysis = "data_analysis"
ToolDataSchema = "data_schema"
ToolWebSearch = "web_search"
ToolWebFetch = "web_fetch"
)
// AvailableTool defines a simple tool metadata used by settings APIs.
type AvailableTool struct {
Name string `json:"name"`
@@ -11,27 +27,31 @@ type AvailableTool struct {
// Keep this in sync with registered tools in this package.
func AvailableToolDefinitions() []AvailableTool {
return []AvailableTool{
{Name: "thinking", Label: "思考", Description: "动态和反思性的问题解决思考工具"},
{Name: "todo_write", Label: "制定计划", Description: "创建结构化的研究计划"},
{Name: "grep_chunks", Label: "关键词搜索", Description: "快速定位包含特定关键词的文档和分块"},
{Name: "knowledge_search", Label: "语义搜索", Description: "理解问题并查找语义相关内容"},
{Name: "list_knowledge_chunks", Label: "查看文档分块", Description: "获取文档完整分块内容"},
{Name: "query_knowledge_graph", Label: "查询知识图谱", Description: "从知识图谱中查询关系"},
{Name: "get_document_info", Label: "获取文档信息", Description: "查看文档元数据"},
{Name: "database_query", Label: "查询数据库", Description: "查询数据库中的信息"},
{Name: ToolThinking, Label: "思考", Description: "动态和反思性的问题解决思考工具"},
{Name: ToolTodoWrite, Label: "制定计划", Description: "创建结构化的研究计划"},
{Name: ToolGrepChunks, Label: "关键词搜索", Description: "快速定位包含特定关键词的文档和分块"},
{Name: ToolKnowledgeSearch, Label: "语义搜索", Description: "理解问题并查找语义相关内容"},
{Name: ToolListKnowledgeChunks, Label: "查看文档分块", Description: "获取文档完整分块内容"},
{Name: ToolQueryKnowledgeGraph, Label: "查询知识图谱", Description: "从知识图谱中查询关系"},
{Name: ToolGetDocumentInfo, Label: "获取文档信息", Description: "查看文档元数据"},
{Name: ToolDatabaseQuery, Label: "查询数据库", Description: "查询数据库中的信息"},
{Name: ToolDataAnalysis, Label: "数据分析", Description: "理解数据文件并进行数据分析"},
{Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息"},
}
}
// DefaultAllowedTools returns the default allowed tools list.
func DefaultAllowedTools() []string {
return []string{
"thinking",
"todo_write",
"knowledge_search",
"grep_chunks",
"list_knowledge_chunks",
"query_knowledge_graph",
"get_document_info",
"database_query",
ToolThinking,
ToolTodoWrite,
ToolKnowledgeSearch,
ToolGrepChunks,
ToolListKnowledgeChunks,
ToolQueryKnowledgeGraph,
ToolGetDocumentInfo,
ToolDatabaseQuery,
ToolDataAnalysis,
ToolDataSchema,
}
}
+47 -52
View File
@@ -2,28 +2,18 @@ package tools
import (
"context"
"encoding/json"
"fmt"
"sync"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
)
// GetDocumentInfoTool retrieves detailed information about a document/knowledge
type GetDocumentInfoTool struct {
BaseTool
tenantID uint64
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
}
// NewGetDocumentInfoTool creates a new get document info tool
func NewGetDocumentInfoTool(
tenantID uint64,
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
) *GetDocumentInfoTool {
description := `Retrieve detailed metadata information about documents.
var getDocumentInfoTool = BaseTool{
name: ToolGetDocumentInfo,
description: `Retrieve detailed metadata information about documents.
## When to Use
@@ -50,56 +40,61 @@ Do not use when:
- Concurrent query for multiple documents provides better performance
- Returns complete document metadata, not just title
- Can check document processing status (parse_status)`
- Can check document processing status (parse_status)`,
schema: utils.GenerateSchema[GetDocumentInfoInput](),
}
// GetDocumentInfoInput defines the input parameters for get document info tool
type GetDocumentInfoInput struct {
KnowledgeIDs []string `json:"knowledge_ids" jsonschema:"Array of document/knowledge IDs, obtained from knowledge_id field in search results, supports concurrent batch queries"`
}
// 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 {
return &GetDocumentInfoTool{
BaseTool: NewBaseTool("get_document_info", description),
tenantID: tenantID,
BaseTool: getDocumentInfoTool,
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) {
func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
tenantID := uint64(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
tenantID = tid
}
// Parse args from json.RawMessage
var input GetDocumentInfoInput
if err := json.Unmarshal(args, &input); err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, err
}
// Extract knowledge_ids array
knowledgeIDsRaw, ok := args["knowledge_ids"].([]interface{})
if !ok || len(knowledgeIDsRaw) == 0 {
knowledgeIDs := input.KnowledgeIDs
if len(knowledgeIDs) == 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)
}
}
// Check if knowledge IDs are valid
if len(knowledgeIDs) == 0 {
// Validate max 10 documents
if len(knowledgeIDs) > 10 {
return &types.ToolResult{
Success: false,
Error: "knowledge_ids must contain at least one valid knowledge ID",
@@ -124,7 +119,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args map[string]inter
defer wg.Done()
// Get knowledge metadata
knowledge, err := t.knowledgeService.GetRepository().GetKnowledgeByID(ctx, t.tenantID, id)
knowledge, err := t.knowledgeService.GetRepository().GetKnowledgeByID(ctx, tenantID, id)
if err != nil {
mu.Lock()
results[id] = &docInfo{
@@ -136,7 +131,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args map[string]inter
// Get chunk count
_, total, err := t.chunkService.GetRepository().
ListPagedChunksByKnowledgeID(ctx, t.tenantID, id, &types.Pagination{
ListPagedChunksByKnowledgeID(ctx, tenantID, id, &types.Pagination{
Page: 1,
PageSize: 1000,
}, []types.ChunkType{"text"}, "", "", "", "", "")
+74 -81
View File
@@ -2,6 +2,7 @@ package tools
import (
"context"
"encoding/json"
"fmt"
"math"
"sort"
@@ -13,19 +14,9 @@ import (
"gorm.io/gorm"
)
// GrepChunksTool performs text pattern matching in knowledge base chunks
// Similar to grep command in Unix-like systems, but operates on knowledge base content
type GrepChunksTool struct {
BaseTool
db *gorm.DB
tenantID uint64
knowledgeBaseIDs []string
knowledgeIDs []string // Specific knowledge/document IDs to search within
}
// NewGrepChunksTool creates a new grep chunks tool
func NewGrepChunksTool(db *gorm.DB, tenantID uint64, knowledgeBaseIDs []string, knowledgeIDs []string) *GrepChunksTool {
description := `Unix-style text pattern matching tool for knowledge base chunks.
var grepChunksTool = BaseTool{
name: ToolGrepChunks,
description: `Unix-style text pattern matching tool for knowledge base chunks.
Searches for text patterns in chunk content using strict literal text matching (fixed-string search). This tool performs exact keyword lookup, not semantic search.
@@ -61,76 +52,81 @@ grep_chunks scans enabled chunks across the specified knowledge bases and return
- Exact keyword presence checks
- Fast preliminary filtering before semantic search
- Situations requiring deterministic text search
`,
schema: json.RawMessage(`{
"type": "object",
"properties": {
"pattern": {
"type": "array",
"description": "REQUIRED: Text patterns to search for. Can be a single pattern or multiple patterns. Treated as literal text (fixed string matching). Results match any of the patterns (OR logic).",
"items": {
"type": "string"
},
"minItems": 1
},
"knowledge_base_ids": {
"type": "array",
"description": "Filter by knowledge base IDs. If empty, searches all allowed KBs.",
"items": {
"type": "string"
}
},
"max_results": {
"type": "integer",
"description": "Maximum number of matching chunks to return (default: 50, max: 200)",
"default": 50,
"minimum": 1,
"maximum": 200
}
},
"required": ["pattern"]
}`),
}
`
// GrepChunksInput defines the input parameters for grep chunks tool
type GrepChunksInput struct {
Pattern []string `json:"pattern" `
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
MaxResults int `json:"max_results,omitempty"`
}
// GrepChunksTool performs text pattern matching in knowledge base chunks
// Similar to grep command in Unix-like systems, but operates on knowledge base content
type GrepChunksTool struct {
BaseTool
db *gorm.DB
knowledgeBaseIDs []string
knowledgeIDs []string // Specific knowledge/document IDs to search within
}
// NewGrepChunksTool creates a new grep chunks tool
func NewGrepChunksTool(db *gorm.DB, knowledgeBaseIDs []string, knowledgeIDs []string) *GrepChunksTool {
return &GrepChunksTool{
BaseTool: NewBaseTool("grep_chunks", description),
BaseTool: grepChunksTool,
db: db,
tenantID: tenantID,
knowledgeBaseIDs: knowledgeBaseIDs,
knowledgeIDs: knowledgeIDs,
}
}
// Parameters returns the JSON schema for the tool's parameters
func (t *GrepChunksTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"pattern": map[string]interface{}{
"type": "array",
"description": "REQUIRED: Text patterns to search for. Can be a single pattern or multiple patterns. Treated as literal text (fixed string matching). Results match any of the patterns (OR logic).",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
},
"knowledge_base_ids": map[string]interface{}{
"type": "array",
"description": "Filter by knowledge base IDs. If empty, searches all allowed KBs.",
"items": map[string]interface{}{
"type": "string",
},
},
// "knowledge_ids": map[string]interface{}{
// "type": "array",
// "description": "Filter by document/knowledge IDs. If empty, searches all documents.",
// "items": map[string]interface{}{
// "type": "string",
// },
// },
"max_results": map[string]interface{}{
"type": "integer",
"description": "Maximum number of matching chunks to return (default: 50, max: 200)",
"default": 50,
"minimum": 1,
"maximum": 200,
},
},
"required": []string{"pattern"},
}
}
// Execute executes the grep chunks tool
func (t *GrepChunksTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
func (t *GrepChunksTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][GrepChunks] Execute started")
// Parse args from json.RawMessage
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
}
// Parse pattern parameter (required) - support multiple patterns
var patterns []string
if patternsRaw, ok := args["pattern"].([]interface{}); ok && len(patternsRaw) > 0 {
for _, p := range patternsRaw {
if pStr, ok := p.(string); ok && strings.TrimSpace(pStr) != "" {
patterns = append(patterns, strings.TrimSpace(pStr))
}
}
}
// Also support single string for backward compatibility
if len(patterns) == 0 {
if patternStr, ok := args["pattern"].(string); ok && strings.TrimSpace(patternStr) != "" {
patterns = append(patterns, strings.TrimSpace(patternStr))
}
}
patterns := input.Pattern
// Validate patterns
if len(patterns) == 0 {
logger.Errorf(ctx, "[Tool][GrepChunks] Missing or invalid pattern parameter")
return &types.ToolResult{
@@ -143,8 +139,8 @@ func (t *GrepChunksTool) Execute(ctx context.Context, args map[string]interface{
countOnly := false // default: show results
maxResults := 50
if mr, ok := args["max_results"].(float64); ok {
maxResults = int(mr)
if input.MaxResults > 0 {
maxResults = input.MaxResults
if maxResults < 1 {
maxResults = 1
} else if maxResults > 200 {
@@ -153,14 +149,7 @@ func (t *GrepChunksTool) Execute(ctx context.Context, args map[string]interface{
}
// Parse knowledge_base_ids filter
var kbIDs []string
if kbIDsRaw, ok := args["knowledge_base_ids"].([]interface{}); ok {
for _, id := range kbIDsRaw {
if idStr, ok := id.(string); ok && idStr != "" {
kbIDs = append(kbIDs, idStr)
}
}
}
kbIDs := input.KnowledgeBaseIDs
if len(kbIDs) == 0 {
kbIDs = t.knowledgeBaseIDs
}
@@ -273,11 +262,15 @@ func (t *GrepChunksTool) searchChunks(
kbIDs []string,
knowledgeIDs []string,
) ([]chunkWithTitle, int64, error) {
tenantID := uint64(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
tenantID = tid
}
// Build base query
query := t.db.Debug().WithContext(ctx).Table("chunks").
Select("chunks.id, chunks.content, chunks.chunk_index, chunks.knowledge_id, chunks.knowledge_base_id, chunks.chunk_type, chunks.created_at, knowledges.title as knowledge_title, COUNT(*) OVER (PARTITION BY chunks.knowledge_id) AS total_chunk_count").
Joins("LEFT JOIN knowledges ON chunks.knowledge_id = knowledges.id").
Where("chunks.tenant_id = ?", t.tenantID).
Where("chunks.tenant_id = ?", tenantID).
Where("chunks.is_enabled = ?", true).
Where("chunks.deleted_at IS NULL").
Where("knowledges.deleted_at IS NULL")
+87 -83
View File
@@ -19,40 +19,9 @@ import (
"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"
KnowledgeBaseID string // ID of the knowledge base this result came from
KnowledgeBaseType string // Type of the knowledge base (document, faq, etc.)
}
// KnowledgeSearchTool searches knowledge bases with flexible query modes
type KnowledgeSearchTool struct {
BaseTool
knowledgeBaseService interfaces.KnowledgeBaseService
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
tenantID uint64
searchTargets types.SearchTargets // Pre-computed unified search targets
rerankModel rerank.Reranker
chatModel chat.Chat // Optional chat model for LLM-based reranking
config *config.Config // Global config for fallback values
}
// NewKnowledgeSearchTool creates a new knowledge search tool
func NewKnowledgeSearchTool(
knowledgeBaseService interfaces.KnowledgeBaseService,
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
tenantID uint64,
searchTargets types.SearchTargets,
rerankModel rerank.Reranker,
chatModel chat.Chat,
cfg *config.Config,
) *KnowledgeSearchTool {
description := `Semantic/vector search tool for retrieving knowledge by meaning, intent, and conceptual relevance.
var knowledgeSearchTool = BaseTool{
name: ToolKnowledgeSearch,
description: `Semantic/vector search tool for retrieving knowledge by meaning, intent, and conceptual relevance.
This tool uses embeddings to understand the user's query and find semantically similar content across knowledge base chunks.
@@ -106,15 +75,75 @@ Avoid:
## Output
Returns chunks ranked by semantic similarity, reranked when applicable.
Results represent conceptual relevance, not literal keyword overlap.
`
Results represent conceptual relevance, not literal keyword overlap.`,
schema: json.RawMessage(`{
"type": "object",
"properties": {
"queries": {
"type": "array",
"description": "REQUIRED: 1-5 semantic questions/topics (e.g., ['What is RAG?', 'RAG benefits'])",
"items": {
"type": "string"
},
"minItems": 1,
"maxItems": 5
},
"knowledge_base_ids": {
"type": "array",
"description": "Optional: KB IDs to search",
"items": {
"type": "string"
},
"minItems": 0,
"maxItems": 10
}
},
"required": ["queries"]
}`),
}
// KnowledgeSearchInput defines the input parameters for knowledge search tool
type KnowledgeSearchInput struct {
Queries []string `json:"queries"`
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
}
// searchResultWithMeta wraps search result with metadata about which query matched it
type searchResultWithMeta struct {
*types.SearchResult
SourceQuery string
QueryType string // "vector" or "keyword"
KnowledgeBaseID string // ID of the knowledge base this result came from
KnowledgeBaseType string // Type of the knowledge base (document, faq, etc.)
}
// KnowledgeSearchTool searches knowledge bases with flexible query modes
type KnowledgeSearchTool struct {
BaseTool
knowledgeBaseService interfaces.KnowledgeBaseService
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
searchTargets types.SearchTargets // Pre-computed unified search targets
rerankModel rerank.Reranker
chatModel chat.Chat // Optional chat model for LLM-based reranking
config *config.Config // Global config for fallback values
}
// NewKnowledgeSearchTool creates a new knowledge search tool
func NewKnowledgeSearchTool(
knowledgeBaseService interfaces.KnowledgeBaseService,
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
searchTargets types.SearchTargets,
rerankModel rerank.Reranker,
chatModel chat.Chat,
cfg *config.Config,
) *KnowledgeSearchTool {
return &KnowledgeSearchTool{
BaseTool: NewBaseTool("knowledge_search", description),
BaseTool: knowledgeSearchTool,
knowledgeBaseService: knowledgeBaseService,
knowledgeService: knowledgeService,
chunkService: chunkService,
tenantID: tenantID,
searchTargets: searchTargets,
rerankModel: rerankModel,
chatModel: chatModel,
@@ -122,50 +151,28 @@ Results represent conceptual relevance, not literal keyword overlap.
}
}
// 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{}{
"queries": map[string]interface{}{
"type": "array",
"description": "REQUIRED: 1-5 semantic questions/topics (e.g., ['What is RAG?', 'RAG benefits'])",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 5,
},
"knowledge_base_ids": map[string]interface{}{
"type": "array",
"description": "Optional: KB IDs to search",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 0,
"maxItems": 10,
},
},
"required": []string{"queries"},
}
}
// Execute executes the knowledge search tool
func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
func (t *KnowledgeSearchTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Execute started")
// Parse args from json.RawMessage
var input KnowledgeSearchInput
if err := json.Unmarshal(args, &input); err != nil {
logger.Errorf(ctx, "[Tool][KnowledgeSearch] Failed to parse args: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, err
}
// Log input arguments
argsJSON, _ := json.MarshalIndent(args, "", " ")
argsJSON, _ := json.MarshalIndent(input, "", " ")
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Input args:\n%s", string(argsJSON))
// Determine which KBs to search - user can optionally filter to specific KBs
var userSpecifiedKBs []string
if kbIDsRaw, ok := args["knowledge_base_ids"].([]interface{}); ok && len(kbIDsRaw) > 0 {
for _, id := range kbIDsRaw {
if idStr, ok := id.(string); ok && idStr != "" {
userSpecifiedKBs = append(userSpecifiedKBs, idStr)
}
}
if len(input.KnowledgeBaseIDs) > 0 {
userSpecifiedKBs = input.KnowledgeBaseIDs
logger.Infof(ctx, "[Tool][KnowledgeSearch] User specified %d knowledge bases: %v", len(userSpecifiedKBs), userSpecifiedKBs)
}
@@ -199,14 +206,7 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
logger.Infof(ctx, "[Tool][KnowledgeSearch] Using %d search targets across %d KBs", len(searchTargets), len(kbIDs))
// Parse query parameter
var queries []string
if queriesRaw, ok := args["queries"].([]interface{}); ok && len(queriesRaw) > 0 {
for _, q := range queriesRaw {
if qStr, ok := q.(string); ok && qStr != "" {
queries = append(queries, qStr)
}
}
}
queries := input.Queries
// Validate: query must be provided
if len(queries) == 0 {
@@ -965,6 +965,10 @@ func (t *KnowledgeSearchTool) formatOutput(
kbsToSearch []string,
queries []string,
) (*types.ToolResult, error) {
tenantID := uint64(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
tenantID = tid
}
if len(results) == 0 {
data := map[string]interface{}{
"knowledge_base_ids": kbsToSearch,
@@ -1050,7 +1054,7 @@ func (t *KnowledgeSearchTool) formatOutput(
// Get total chunk count for this knowledge (cache it)
if _, exists := knowledgeTotalMap[result.KnowledgeID]; !exists {
_, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
t.tenantID, result.KnowledgeID,
tenantID, result.KnowledgeID,
&types.Pagination{Page: 1, PageSize: 1},
[]types.ChunkType{types.ChunkTypeText}, "", "", "", "", "",
)
+71 -63
View File
@@ -10,21 +10,9 @@ import (
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// ListKnowledgeChunksTool retrieves chunk snapshots for a specific knowledge document.
type ListKnowledgeChunksTool struct {
BaseTool
tenantID uint64
chunkService interfaces.ChunkService
knowledgeService interfaces.KnowledgeService
}
// NewListKnowledgeChunksTool creates a new tool instance.
func NewListKnowledgeChunksTool(
tenantID uint64,
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
) *ListKnowledgeChunksTool {
description := `Retrieve full chunk content for a document by knowledge_id.
var listKnowledgeChunksTool = BaseTool{
name: ToolListKnowledgeChunks,
description: `Retrieve full chunk content for a document by knowledge_id.
## Use After grep_chunks or knowledge_search:
1. grep_chunks(["keyword", "变体"]) → get knowledge_id
@@ -41,46 +29,76 @@ func NewListKnowledgeChunksTool(
- offset (optional): Start position (default 0)
## Output:
Full chunk content with chunk_id, chunk_index, and content text.`
Full chunk content with chunk_id, chunk_index, and content text.`,
schema: json.RawMessage(`{
"type": "object",
"properties": {
"knowledge_id": {
"type": "string",
"description": "Document ID to retrieve chunks from"
},
"limit": {
"type": "integer",
"description": "Chunks per page (default 20, max 100)",
"default": 20,
"minimum": 1,
"maximum": 100
},
"offset": {
"type": "integer",
"description": "Start position (default 0)",
"default": 0,
"minimum": 0
}
},
"required": ["knowledge_id", "limit", "offset"]
}`),
}
// ListKnowledgeChunksInput defines the input parameters for list knowledge chunks tool
type ListKnowledgeChunksInput struct {
KnowledgeID string `json:"knowledge_id"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
// ListKnowledgeChunksTool retrieves chunk snapshots for a specific knowledge document.
type ListKnowledgeChunksTool struct {
BaseTool
chunkService interfaces.ChunkService
knowledgeService interfaces.KnowledgeService
}
// NewListKnowledgeChunksTool creates a new tool instance.
func NewListKnowledgeChunksTool(
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
) *ListKnowledgeChunksTool {
return &ListKnowledgeChunksTool{
BaseTool: NewBaseTool("list_knowledge_chunks", description),
tenantID: tenantID,
BaseTool: listKnowledgeChunksTool,
chunkService: chunkService,
knowledgeService: knowledgeService,
}
}
// Parameters returns the JSON schema describing accepted arguments.
func (t *ListKnowledgeChunksTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"knowledge_id": map[string]interface{}{
"type": "string",
"description": "Document ID to retrieve chunks from",
},
"limit": map[string]interface{}{
"type": "integer",
"description": "Chunks per page (default 20, max 100)",
"default": 20,
"minimum": 1,
"maximum": 100,
},
"offset": map[string]interface{}{
"type": "integer",
"description": "Start position (default 0)",
"default": 0,
"minimum": 0,
},
},
"required": []string{"knowledge_id", "limit", "offset"},
}
}
// Execute performs the chunk fetch against the chunk service.
func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
knowledgeID, ok := args["knowledge_id"].(string)
func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
tenantID := uint64(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
tenantID = tid
}
// Parse args from json.RawMessage
var input ListKnowledgeChunksInput
if err := json.Unmarshal(args, &input); err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, err
}
knowledgeID := input.KnowledgeID
ok := knowledgeID != ""
if !ok || strings.TrimSpace(knowledgeID) == "" {
return &types.ToolResult{
Success: false,
@@ -90,22 +108,12 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args map[string]i
knowledgeID = strings.TrimSpace(knowledgeID)
chunkLimit := 20
offset := 0
if rawLimit, exists := args["limit"]; exists {
switch v := rawLimit.(type) {
case float64:
chunkLimit = int(v)
case int:
chunkLimit = v
}
if input.Limit > 0 {
chunkLimit = input.Limit
}
if rawOffset, exists := args["offset"]; exists {
switch v := rawOffset.(type) {
case float64:
offset = int(v)
case int:
offset = v
}
offset := 0
if input.Offset > 0 {
offset = input.Offset
}
if offset < 0 {
offset = 0
@@ -117,7 +125,7 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args map[string]i
}
chunks, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
t.tenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "", "")
tenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "", "")
if err != nil {
return &types.ToolResult{
Success: false,
+20 -9
View File
@@ -12,6 +12,8 @@ import (
"github.com/Tencent/WeKnora/internal/types"
)
type MCPInput = map[string]any
// MCPTool wraps an MCP service tool to implement the Tool interface
type MCPTool struct {
service *types.MCPService
@@ -47,22 +49,31 @@ func (t *MCPTool) Description() string {
}
// Parameters returns the JSON Schema for tool parameters
func (t *MCPTool) Parameters() map[string]interface{} {
if t.mcpTool.InputSchema != nil {
func (t *MCPTool) Parameters() json.RawMessage {
if len(t.mcpTool.InputSchema) > 0 {
return t.mcpTool.InputSchema
}
// Return a default schema if none provided
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{},
}
return json.RawMessage(`{
"type": "object",
"properties": {}
}`)
}
// Execute executes the MCP tool
func (t *MCPTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.GetLogger(ctx).Infof("Executing MCP tool: %s from service: %s", t.mcpTool.Name, t.service.Name)
// Parse args from json.RawMessage
var input MCPInput
if err := json.Unmarshal(args, &input); err != nil {
logger.Errorf(ctx, "[Tool][DatabaseQuery] Failed to parse args: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, err
}
// Get or create MCP client
client, err := t.mcpManager.GetOrCreateClient(t.service)
if err != nil {
@@ -86,7 +97,7 @@ func (t *MCPTool) Execute(ctx context.Context, args map[string]interface{}) (*ty
}
// Call the tool via MCP
result, err := client.CallTool(ctx, t.mcpTool.Name, args)
result, err := client.CallTool(ctx, t.mcpTool.Name, input)
if err != nil {
logger.GetLogger(ctx).Errorf("MCP tool call failed: %v", err)
return &types.ToolResult{
+45 -55
View File
@@ -2,23 +2,19 @@ package tools
import (
"context"
"encoding/json"
"fmt"
"sort"
"sync"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
)
// 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 := `Query knowledge graph to explore entity relationships and knowledge networks.
var queryKnowledgeGraphTool = BaseTool{
name: ToolQueryKnowledgeGraph,
description: `Query knowledge graph to explore entity relationships and knowledge networks.
## Core Function
Explores relationships between entities in knowledge bases that have graph extraction configured.
@@ -54,65 +50,59 @@ If KB is not configured with graph, tool will return regular search results.
## Notes
- Results indicate graph configuration status
- Cross-KB results are automatically deduplicated
- Results are sorted by relevance`
- Results are sorted by relevance`,
schema: utils.GenerateSchema[QueryKnowledgeGraphInput](),
}
// QueryKnowledgeGraphInput defines the input parameters for query knowledge graph tool
type QueryKnowledgeGraphInput struct {
KnowledgeBaseIDs []string `json:"knowledge_base_ids" jsonschema:"Array of knowledge base IDs to query"`
Query string `json:"query" jsonschema:"查询内容(实体名称或查询文本)"`
}
// 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 {
return &QueryKnowledgeGraphTool{
BaseTool: NewBaseTool("query_knowledge_graph", description),
BaseTool: queryKnowledgeGraphTool,
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 performs the knowledge graph query with concurrent KB processing
func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
// Parse args from json.RawMessage
var input QueryKnowledgeGraphInput
if err := json.Unmarshal(args, &input); err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, err
}
// Extract knowledge_base_ids array
kbIDsRaw, ok := args["knowledge_base_ids"].([]interface{})
if !ok || len(kbIDsRaw) == 0 {
if len(input.KnowledgeBaseIDs) == 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 {
// Validate max 10 KBs
if len(input.KnowledgeBaseIDs) > 10 {
return &types.ToolResult{
Success: false,
Error: "knowledge_base_ids must contain at least one valid KB ID",
}, fmt.Errorf("no valid KB IDs provided")
Error: "knowledge_base_ids must contain at most 10 KB IDs",
}, fmt.Errorf("too many KB IDs")
}
query, ok := args["query"].(string)
if !ok || query == "" {
query := input.Query
if query == "" {
return &types.ToolResult{
Success: false,
Error: "query is required",
@@ -136,7 +126,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args map[string]i
MatchCount: 10,
}
for _, kbID := range kbIDs {
for _, kbID := range input.KnowledgeBaseIDs {
wg.Add(1)
go func(id string) {
defer wg.Done()
@@ -181,7 +171,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args map[string]i
graphConfigs := make(map[string]map[string]interface{})
kbCounts := make(map[string]int)
for _, kbID := range kbIDs {
for _, kbID := range input.KnowledgeBaseIDs {
result := kbResults[kbID]
if result.err != nil {
errors = append(errors, fmt.Sprintf("KB %s: %v", kbID, result.err))
@@ -218,7 +208,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args map[string]i
Success: true,
Output: "未找到相关的图谱信息。",
Data: map[string]interface{}{
"knowledge_base_ids": kbIDs,
"knowledge_base_ids": input.KnowledgeBaseIDs,
"query": query,
"results": []interface{}{},
"graph_configs": graphConfigs,
@@ -230,7 +220,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args map[string]i
// Format output with enhanced graph information
output := "=== 知识图谱查询 ===\n\n"
output += fmt.Sprintf("📊 查询: %s\n", query)
output += fmt.Sprintf("🎯 目标知识库: %v\n", kbIDs)
output += fmt.Sprintf("🎯 目标知识库: %v\n", input.KnowledgeBaseIDs)
output += fmt.Sprintf("✓ 找到 %d 条相关结果(已去重)\n\n", len(allResults))
if len(errors) > 0 {
@@ -354,7 +344,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args map[string]i
Success: true,
Output: output,
Data: map[string]interface{}{
"knowledge_base_ids": kbIDs,
"knowledge_base_ids": input.KnowledgeBaseIDs,
"query": query,
"results": formattedResults,
"count": len(allResults),
+15 -16
View File
@@ -2,33 +2,22 @@ package tools
import (
"context"
"encoding/json"
"fmt"
"github.com/Tencent/WeKnora/internal/common"
"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
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
db *gorm.DB
tools map[string]types.Tool
}
// NewToolRegistry creates a new tool registry
func NewToolRegistry(
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
db *gorm.DB, // gorm.DB for database operations
) *ToolRegistry {
func NewToolRegistry() *ToolRegistry {
return &ToolRegistry{
tools: make(map[string]types.Tool),
knowledgeService: knowledgeService,
chunkService: chunkService,
db: db,
tools: make(map[string]types.Tool),
}
}
@@ -72,7 +61,7 @@ func (r *ToolRegistry) GetFunctionDefinitions() []types.FunctionDefinition {
func (r *ToolRegistry) ExecuteTool(
ctx context.Context,
name string,
args map[string]interface{},
args json.RawMessage,
) (*types.ToolResult, error) {
common.PipelineInfo(ctx, "AgentTool", "execute_start", map[string]interface{}{
"tool": name,
@@ -112,3 +101,13 @@ func (r *ToolRegistry) ExecuteTool(
return result, execErr
}
// Cleanup cleans up all registered tools that implement the Cleanup method
func (r *ToolRegistry) Cleanup(ctx context.Context) {
// Check specifically for DataAnalysisTool
if tool, exists := r.tools[ToolDataAnalysis]; exists {
if dataAnalysisTool, ok := tool.(*DataAnalysisTool); ok {
dataAnalysisTool.Cleanup(ctx)
}
}
}
+113 -164
View File
@@ -2,36 +2,16 @@ package tools
import (
"context"
"encoding/json"
"fmt"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// SequentialThinkingTool is a dynamic and reflective problem-solving tool
// This tool helps analyze problems through a flexible thinking process that can adapt and evolve
type SequentialThinkingTool struct {
BaseTool
thoughtHistory []ThoughtData
branches map[string][]ThoughtData
}
// ThoughtData represents a single thought in the sequential thinking process
type ThoughtData struct {
Thought string `json:"thought"`
ThoughtNumber int `json:"thought_number"`
TotalThoughts int `json:"total_thoughts"`
IsRevision bool `json:"is_revision,omitempty"`
RevisesThought *int `json:"revises_thought,omitempty"`
BranchFromThought *int `json:"branch_from_thought,omitempty"`
BranchID string `json:"branch_id,omitempty"`
NeedsMoreThoughts bool `json:"needs_more_thoughts,omitempty"`
NextThoughtNeeded bool `json:"next_thought_needed"`
}
// NewSequentialThinkingTool creates a new sequential thinking tool instance
func NewSequentialThinkingTool() *SequentialThinkingTool {
description := `A detailed tool for dynamic and reflective problem-solving through thoughts.
var sequentialThinkingTool = BaseTool{
name: ToolThinking,
description: `A detailed tool for dynamic and reflective problem-solving through thoughts.
This tool helps analyze problems through a flexible thinking process that can adapt and evolve.
@@ -99,72 +79,101 @@ Each thought can build on, question, or revise previous insights as understandin
8. Verify the hypothesis based on the Chain of Thought steps
9. Repeat the process until satisfied with the solution
10. Provide a single, ideally correct answer as the final output
11. Only set next_thought_needed to false when truly done and a satisfactory answer is reached`
return &SequentialThinkingTool{
BaseTool: NewBaseTool("thinking", description),
thoughtHistory: make([]ThoughtData, 0),
branches: make(map[string][]ThoughtData),
}
11. Only set next_thought_needed to false when truly done and a satisfactory answer is reached`,
schema: json.RawMessage(`{
"type": "object",
"properties": {
"thought": {
"type": "string",
"description": "Your current thinking step. Write in natural, user-friendly language. NEVER mention tool names (like \"grep_chunks\", \"knowledge_search\", \"web_search\", etc.). Instead, describe actions in plain language (e.g., \"I'll search for key terms\" instead of \"I'll use grep_chunks\"). Focus on WHAT you're trying to find and WHY, not HOW (which tools you'll use)."
},
"nextThoughtNeeded": {
"type": "boolean",
"description": "Whether another thought step is needed"
},
"thoughtNumber": {
"type": "integer",
"description": "Current thought number (numeric value, e.g., 1, 2, 3)",
"minimum": 1
},
"totalThoughts": {
"type": "integer",
"description": "Estimated total thoughts needed (numeric value, e.g., 5, 10)",
"minimum": 5
},
"isRevision": {
"type": "boolean",
"description": "Whether this revises previous thinking"
},
"revisesThought": {
"type": "integer",
"description": "Which thought is being reconsidered",
"minimum": 1
},
"branchFromThought": {
"type": "integer",
"description": "Branching point thought number",
"minimum": 1
},
"branchId": {
"type": "string",
"description": "Branch identifier"
},
"needsMoreThoughts": {
"type": "boolean",
"description": "If more thoughts are needed"
}
},
"required": ["thought", "nextThoughtNeeded", "thoughtNumber", "totalThoughts"]
}`),
}
// Parameters returns the JSON schema for the tool's parameters
func (t *SequentialThinkingTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"thought": map[string]interface{}{
"type": "string",
"description": `Your current thinking step. Write in natural, user-friendly language. NEVER mention tool names (like "grep_chunks", "knowledge_search", "web_search", etc.). Instead, describe actions in plain language (e.g., "I'll search for key terms" instead of "I'll use grep_chunks"). Focus on WHAT you're trying to find and WHY, not HOW (which tools you'll use).`,
},
"nextThoughtNeeded": map[string]interface{}{
"type": "boolean",
"description": "Whether another thought step is needed",
},
"thoughtNumber": map[string]interface{}{
"type": "integer",
"description": "Current thought number (numeric value, e.g., 1, 2, 3)",
"minimum": 1,
},
"totalThoughts": map[string]interface{}{
"type": "integer",
"description": "Estimated total thoughts needed (numeric value, e.g., 5, 10)",
"minimum": 5,
},
"isRevision": map[string]interface{}{
"type": "boolean",
"description": "Whether this revises previous thinking",
},
"revisesThought": map[string]interface{}{
"type": "integer",
"description": "Which thought is being reconsidered",
"minimum": 1,
},
"branchFromThought": map[string]interface{}{
"type": "integer",
"description": "Branching point thought number",
"minimum": 1,
},
"branchId": map[string]interface{}{
"type": "string",
"description": "Branch identifier",
},
"needsMoreThoughts": map[string]interface{}{
"type": "boolean",
"description": "If more thoughts are needed",
},
},
"required": []string{"thought", "nextThoughtNeeded", "thoughtNumber", "totalThoughts"},
// SequentialThinkingTool is a dynamic and reflective problem-solving tool
// This tool helps analyze problems through a flexible thinking process that can adapt and evolve
type SequentialThinkingTool struct {
BaseTool
thoughtHistory []SequentialThinkingInput
branches map[string][]SequentialThinkingInput
}
// SequentialThinkingInput defines the input parameters for sequential thinking tool
type SequentialThinkingInput struct {
Thought string `json:"thought"`
ThoughtNumber int `json:"thought_number"`
TotalThoughts int `json:"total_thoughts"`
IsRevision bool `json:"is_revision,omitempty"`
RevisesThought *int `json:"revises_thought,omitempty"`
BranchFromThought *int `json:"branch_from_thought,omitempty"`
BranchID string `json:"branch_id,omitempty"`
NeedsMoreThoughts bool `json:"needs_more_thoughts,omitempty"`
NextThoughtNeeded bool `json:"next_thought_needed"`
}
// NewSequentialThinkingTool creates a new sequential thinking tool instance
func NewSequentialThinkingTool() *SequentialThinkingTool {
return &SequentialThinkingTool{
BaseTool: sequentialThinkingTool,
thoughtHistory: make([]SequentialThinkingInput, 0),
branches: make(map[string][]SequentialThinkingInput),
}
}
// Execute executes the sequential thinking tool
func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
func (t *SequentialThinkingTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][SequentialThinking] Execute started")
// Parse args from json.RawMessage
var input SequentialThinkingInput
if err := json.Unmarshal(args, &input); err != nil {
logger.Errorf(ctx, "[Tool][SequentialThinking] Failed to parse args: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, err
}
// Validate and parse input
thoughtData, err := t.validateThoughtData(args)
if err != nil {
if err := t.validate(input); err != nil {
logger.Errorf(ctx, "[Tool][SequentialThinking] Validation failed: %v", err)
return &types.ToolResult{
Success: false,
@@ -173,22 +182,22 @@ func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]in
}
// Adjust totalThoughts if thoughtNumber exceeds it
if thoughtData.ThoughtNumber > thoughtData.TotalThoughts {
thoughtData.TotalThoughts = thoughtData.ThoughtNumber
if input.ThoughtNumber > input.TotalThoughts {
input.TotalThoughts = input.ThoughtNumber
}
// Add to thought history
t.thoughtHistory = append(t.thoughtHistory, thoughtData)
t.thoughtHistory = append(t.thoughtHistory, input)
// Handle branching
if thoughtData.BranchFromThought != nil && thoughtData.BranchID != "" {
if t.branches[thoughtData.BranchID] == nil {
t.branches[thoughtData.BranchID] = make([]ThoughtData, 0)
if input.BranchFromThought != nil && input.BranchID != "" {
if t.branches[input.BranchID] == nil {
t.branches[input.BranchID] = make([]SequentialThinkingInput, 0)
}
t.branches[thoughtData.BranchID] = append(t.branches[thoughtData.BranchID], thoughtData)
t.branches[input.BranchID] = append(t.branches[input.BranchID], input)
}
logger.Debugf(ctx, "[Tool][SequentialThinking] %s", thoughtData.Thought)
logger.Debugf(ctx, "[Tool][SequentialThinking] %s", input.Thought)
// Prepare response data
branchKeys := make([]string, 0, len(t.branches))
@@ -196,25 +205,25 @@ func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]in
branchKeys = append(branchKeys, k)
}
incomplete := thoughtData.NextThoughtNeeded || thoughtData.NeedsMoreThoughts ||
thoughtData.ThoughtNumber < thoughtData.TotalThoughts
incomplete := input.NextThoughtNeeded || input.NeedsMoreThoughts ||
input.ThoughtNumber < input.TotalThoughts
responseData := map[string]interface{}{
"thought_number": thoughtData.ThoughtNumber,
"total_thoughts": thoughtData.TotalThoughts,
"next_thought_needed": thoughtData.NextThoughtNeeded,
"thought_number": input.ThoughtNumber,
"total_thoughts": input.TotalThoughts,
"next_thought_needed": input.NextThoughtNeeded,
"branches": branchKeys,
"thought_history_length": len(t.thoughtHistory),
"display_type": "thinking",
"thought": thoughtData.Thought,
"thought": input.Thought,
"incomplete_steps": incomplete,
}
logger.Infof(
ctx,
"[Tool][SequentialThinking] Execute completed - Thought %d/%d",
thoughtData.ThoughtNumber,
thoughtData.TotalThoughts,
input.ThoughtNumber,
input.TotalThoughts,
)
outputMsg := "Thought process recorded"
@@ -229,82 +238,22 @@ func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]in
}, nil
}
// validateThoughtData validates and parses the input arguments
func (t *SequentialThinkingTool) validateThoughtData(input map[string]interface{}) (ThoughtData, error) {
var data ThoughtData
// validate validates the input thought data
func (t *SequentialThinkingTool) validate(data SequentialThinkingInput) error {
// Validate thought (required)
thought, ok := input["thought"].(string)
if !ok || thought == "" {
return data, fmt.Errorf("invalid thought: must be a non-empty string")
if data.Thought == "" {
return fmt.Errorf("invalid thought: must be a non-empty string")
}
data.Thought = thought
// Validate thoughtNumber (required)
thoughtNumber, ok := input["thoughtNumber"].(float64)
if !ok {
// Try int type
if num, ok := input["thoughtNumber"].(int); ok {
data.ThoughtNumber = num
} else {
return data, fmt.Errorf("invalid thoughtNumber: must be a number")
}
} else {
data.ThoughtNumber = int(thoughtNumber)
}
if data.ThoughtNumber < 1 {
return data, fmt.Errorf("invalid thoughtNumber: must be >= 1")
return fmt.Errorf("invalid thoughtNumber: must be >= 1")
}
// Validate totalThoughts (required)
totalThoughts, ok := input["totalThoughts"].(float64)
if !ok {
// Try int type
if num, ok := input["totalThoughts"].(int); ok {
data.TotalThoughts = num
} else {
return data, fmt.Errorf("invalid totalThoughts: must be a number")
}
} else {
data.TotalThoughts = int(totalThoughts)
}
if data.TotalThoughts < 1 {
return data, fmt.Errorf("invalid totalThoughts: must be >= 1")
return fmt.Errorf("invalid totalThoughts: must be >= 1")
}
// Validate nextThoughtNeeded (required)
nextThoughtNeeded, ok := input["nextThoughtNeeded"].(bool)
if !ok {
return data, fmt.Errorf("invalid nextThoughtNeeded: must be a boolean")
}
data.NextThoughtNeeded = nextThoughtNeeded
// Optional fields
if isRevision, ok := input["isRevision"].(bool); ok {
data.IsRevision = isRevision
}
if revisesThought, ok := input["revisesThought"].(float64); ok {
num := int(revisesThought)
data.RevisesThought = &num
} else if revisesThought, ok := input["revisesThought"].(int); ok {
data.RevisesThought = &revisesThought
}
if branchFromThought, ok := input["branchFromThought"].(float64); ok {
num := int(branchFromThought)
data.BranchFromThought = &num
} else if branchFromThought, ok := input["branchFromThought"].(int); ok {
data.BranchFromThought = &branchFromThought
}
if branchID, ok := input["branchId"].(string); ok {
data.BranchID = branchID
}
if needsMoreThoughts, ok := input["needsMoreThoughts"].(bool); ok {
data.NeedsMoreThoughts = needsMoreThoughts
}
return data, nil
return nil
}
+44 -83
View File
@@ -6,25 +6,12 @@ import (
"fmt"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
// 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 and manage a structured task list for retrieval and research tasks. This helps you track progress, organize complex retrieval operations, and demonstrate thoroughness to the user.
var todoWriteTool = BaseTool{
name: ToolTodoWrite,
description: `Use this tool to create and manage a structured task list for retrieval and research tasks. This helps you track progress, organize complex retrieval operations, and demonstrate thoroughness to the user.
**CRITICAL - Focus on Retrieval Tasks Only**:
- This tool is for tracking RETRIEVAL and RESEARCH tasks (e.g., searching knowledge bases, retrieving documents, gathering information)
@@ -144,82 +131,56 @@ The assistant did not use the todo list because this is an informational request
**Important**: After completing all retrieval tasks in todo_write, use the thinking tool to synthesize findings and generate the final answer. The todo_write tool tracks WHAT to retrieve, while thinking tool handles HOW to synthesize and present the information.
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all retrieval requirements successfully.`
return &TodoWriteTool{
BaseTool: NewBaseTool("todo_write", description),
}
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all retrieval requirements successfully.`,
schema: utils.GenerateSchema[TodoWriteInput](),
}
// 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": "array",
// "description": "Suggested tools for this step (e.g., ['knowledge_search', 'list_knowledge_chunks'])",
// "items": map[string]interface{}{
// "type": "string",
// },
// },
"status": map[string]interface{}{
"type": "string",
"enum": []string{"pending", "in_progress", "completed"},
"description": "Current status: pending (not started), in_progress (executing), completed (finished)",
},
},
"required": []string{"id", "description", "status"},
},
},
},
"required": []string{"task", "steps"},
// TodoWriteTool implements a planning tool for complex tasks
// This is an optional tool that helps organize multi-step research
type TodoWriteTool struct {
BaseTool
}
// TodoWriteInput defines the input parameters for todo_write tool
type TodoWriteInput struct {
Task string `json:"task" jsonschema:"The complex task or question you need to create a plan for"`
Steps []PlanStep `json:"steps" jsonschema:"Array of research plan steps with status tracking"`
}
// PlanStep represents a single step in the research plan
type PlanStep struct {
ID string `json:"id" jsonschema:"Unique identifier for this step (e.g., 'step1', 'step2')"`
Description string `json:"description" jsonschema:"Clear description of what to investigate or accomplish in this step"`
Status string `json:"status" jsonschema:"Current status: pending (not started), in_progress (executing), completed (finished)"`
}
// NewTodoWriteTool creates a new todo_write tool instance
func NewTodoWriteTool() *TodoWriteTool {
return &TodoWriteTool{
BaseTool: todoWriteTool,
}
}
// 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 = "未提供任务描述"
func (t *TodoWriteTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
// Parse args from json.RawMessage
var input TodoWriteInput
if err := json.Unmarshal(args, &input); err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, err
}
if input.Task == "" {
input.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: getStringArrayField(stepMap, "tools_to_use"),
Status: getStringField(stepMap, "status"),
}
planSteps = append(planSteps, step)
}
}
}
planSteps := input.Steps
// Generate formatted output
output := generatePlanOutput(task, planSteps)
output := generatePlanOutput(input.Task, planSteps)
// Prepare structured data for response
stepsJSON, _ := json.Marshal(planSteps)
@@ -228,7 +189,7 @@ func (t *TodoWriteTool) Execute(ctx context.Context, args map[string]interface{}
Success: true,
Output: output,
Data: map[string]interface{}{
"task": task,
"task": input.Task,
"steps": planSteps,
"steps_json": string(stepsJSON),
"total_steps": len(planSteps),
+9 -1
View File
@@ -1,6 +1,7 @@
package tools
import (
"encoding/json"
"fmt"
"github.com/Tencent/WeKnora/internal/types"
@@ -10,13 +11,15 @@ import (
type BaseTool struct {
name string
description string
schema json.RawMessage
}
// NewBaseTool creates a new base tool
func NewBaseTool(name, description string) BaseTool {
func NewBaseTool(name, description string, schema json.RawMessage) BaseTool {
return BaseTool{
name: name,
description: description,
schema: schema,
}
}
@@ -30,6 +33,11 @@ func (t *BaseTool) Description() string {
return t.description
}
// Parameters returns the tool parameters schema
func (t *BaseTool) Parameters() json.RawMessage {
return t.schema
}
// ToolExecutor is a helper interface for executing tools
type ToolExecutor interface {
types.Tool
+50 -60
View File
@@ -2,6 +2,7 @@ package tools
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
@@ -16,6 +17,7 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
const (
@@ -23,6 +25,33 @@ const (
webFetchMaxChars = 100000 // maximum number of characters to fetch
)
var webFetchTool = BaseTool{
name: ToolWebFetch,
description: `Fetch detailed web content from previously discovered URLs and analyze it with an LLM.
## Usage
- Receive one or more {url, prompt} combinations
- Fetch web page content and convert to Markdown text
- Use prompt to call small model for analysis and summary (if model is available)
- Return summary result and original content fragment
## When to Use
- **MANDATORY**: After web_search returns results, if content is truncated or incomplete, use web_fetch to get full page content
- When web_search snippet is insufficient for answering the question`,
schema: utils.GenerateSchema[WebFetchInput](),
}
// WebFetchInput defines the input parameters for web fetch tool
type WebFetchInput struct {
Items []WebFetchItem `json:"items" jsonschema:"批量抓取任务,每项包含 url 与 prompt"`
}
// WebFetchItem represents a single web fetch task
type WebFetchItem struct {
URL string `json:"url" jsonschema:"待抓取的网页 URL,需来自 web_search 结果"`
Prompt string `json:"prompt" jsonschema:"分析该网页内容时使用的提示词"`
}
// webFetchParams is the parameters for the web fetch tool
type webFetchParams struct {
URL string
@@ -45,21 +74,8 @@ type WebFetchTool struct {
// NewWebFetchTool creates a new web_fetch tool instance
func NewWebFetchTool(chatModel chat.Chat) *WebFetchTool {
description := `Fetch detailed web content from previously discovered URLs and analyze it with an LLM.
## Usage
- Receive one or more {url, prompt} combinations
- Fetch web page content and convert to Markdown text
- Use prompt to call small model for analysis and summary (if model is available)
- Return summary result and original content fragment
## When to Use
- **MANDATORY**: After web_search returns results, if content is truncated or incomplete, use web_fetch to get full page content
- When web_search snippet is insufficient for answering the question
`
return &WebFetchTool{
BaseTool: NewBaseTool("web_fetch", description),
BaseTool: webFetchTool,
client: &http.Client{
Timeout: webFetchTimeout,
},
@@ -67,41 +83,21 @@ func NewWebFetchTool(chatModel chat.Chat) *WebFetchTool {
}
}
// Parameters 返回工具参数的 JSON Schema
func (t *WebFetchTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"items": map[string]interface{}{
"type": "array",
"description": "批量抓取任务,每项包含 url 与 prompt",
"items": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"url": map[string]interface{}{
"type": "string",
"description": "待抓取的网页 URL,需来自 web_search 结果",
},
"prompt": map[string]interface{}{
"type": "string",
"description": "分析该网页内容时使用的提示词",
},
},
"required": []string{"url", "prompt"},
},
"minItems": 1,
},
},
"required": []string{"items"},
}
}
// Execute 执行 web_fetch 工具
func (t *WebFetchTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
func (t *WebFetchTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][WebFetch] Execute started")
rawItems, ok := args["items"]
if !ok {
// Parse args from json.RawMessage
var input WebFetchInput
if err := json.Unmarshal(args, &input); err != nil {
logger.Errorf(ctx, "[Tool][WebFetch] Failed to parse args: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, err
}
if len(input.Items) == 0 {
logger.Errorf(ctx, "[Tool][WebFetch] 参数缺失: items")
return &types.ToolResult{
Success: false,
@@ -109,25 +105,19 @@ func (t *WebFetchTool) Execute(ctx context.Context, args map[string]interface{})
}, nil
}
itemsSlice, ok := rawItems.([]interface{})
if !ok || len(itemsSlice) == 0 {
logger.Errorf(ctx, "[Tool][WebFetch] items 解析失败或为空: %#v", rawItems)
return &types.ToolResult{
Success: false,
Error: "'items' must be a non-empty array",
}, nil
}
results := make([]*webFetchItemResult, len(itemsSlice))
results := make([]*webFetchItemResult, len(input.Items))
var wg sync.WaitGroup
wg.Add(len(itemsSlice))
wg.Add(len(input.Items))
for idx := range itemsSlice {
for idx := range input.Items {
i := idx
itemAny := itemsSlice[i]
item := input.Items[i]
params := t.parseParams(itemAny)
params := webFetchParams{
URL: item.URL,
Prompt: item.Prompt,
}
go func(index int, p webFetchParams) {
defer wg.Done()
+61 -56
View File
@@ -2,6 +2,7 @@ package tools
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
@@ -9,29 +10,12 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
)
// WebSearchTool performs web searches and returns results
type WebSearchTool struct {
BaseTool
webSearchService interfaces.WebSearchService
knowledgeBaseService interfaces.KnowledgeBaseService
knowledgeService interfaces.KnowledgeService
sessionService interfaces.SessionService
sessionID string
maxResults int
}
// NewWebSearchTool creates a new web search tool
func NewWebSearchTool(
webSearchService interfaces.WebSearchService,
knowledgeBaseService interfaces.KnowledgeBaseService,
knowledgeService interfaces.KnowledgeService,
sessionService interfaces.SessionService,
sessionID string,
maxResults int,
) *WebSearchTool {
description := `Search the web for current information and news. This tool searches the internet to find up-to-date information that may not be in the knowledge base.
var webSearchTool = BaseTool{
name: ToolWebSearch,
description: `Search the web for current information and news. This tool searches the internet to find up-to-date information that may not be in the knowledge base.
## CRITICAL - KB First Rule
**ABSOLUTE RULE**: You MUST complete KB retrieval (grep_chunks AND knowledge_search) FIRST before using this tool.
@@ -57,10 +41,7 @@ func NewWebSearchTool(
**Parameters**:
- query (required): Search query string
**Returns**: Web search results with title, URL, snippet, and content (up to ` + fmt.Sprintf(
"%d",
maxResults,
) + ` results)
**Returns**: Web search results with title, URL, snippet, and content (up to %d results)
## Examples
@@ -83,42 +64,66 @@ func NewWebSearchTool(
- Use this tool when knowledge bases don't have the information you need
- Results include URL, title, snippet, and content snippet (may be truncated)
- **CRITICAL**: If content is truncated or you need full details, use **web_fetch** to fetch complete page content
- Maximum ` + fmt.Sprintf(
"%d",
maxResults,
) + ` results will be returned per search`
return &WebSearchTool{
BaseTool: NewBaseTool("web_search", description),
webSearchService: webSearchService,
knowledgeBaseService: knowledgeBaseService,
knowledgeService: knowledgeService,
sessionService: sessionService,
sessionID: sessionID,
maxResults: maxResults,
}
- Maximum %d results will be returned per search`,
schema: utils.GenerateSchema[WebSearchInput](),
}
// Parameters returns the JSON schema for the tool's parameters
func (t *WebSearchTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"query": map[string]interface{}{
"type": "string",
"description": "Search query string",
},
},
"required": []string{"query"},
// WebSearchInput defines the input parameters for web search tool
type WebSearchInput struct {
Query string `json:"query" jsonschema:"Search query string"`
}
// WebSearchTool performs web searches and returns results
type WebSearchTool struct {
BaseTool
webSearchService interfaces.WebSearchService
knowledgeBaseService interfaces.KnowledgeBaseService
knowledgeService interfaces.KnowledgeService
webSearchStateService interfaces.WebSearchStateService
sessionID string
maxResults int
}
// NewWebSearchTool creates a new web search tool
func NewWebSearchTool(
webSearchService interfaces.WebSearchService,
knowledgeBaseService interfaces.KnowledgeBaseService,
knowledgeService interfaces.KnowledgeService,
webSearchStateService interfaces.WebSearchStateService,
sessionID string,
maxResults int,
) *WebSearchTool {
tool := webSearchTool
tool.description = fmt.Sprintf(tool.description, maxResults, maxResults)
return &WebSearchTool{
BaseTool: tool,
webSearchService: webSearchService,
knowledgeBaseService: knowledgeBaseService,
knowledgeService: knowledgeService,
webSearchStateService: webSearchStateService,
sessionID: sessionID,
maxResults: maxResults,
}
}
// Execute executes the web search tool
func (t *WebSearchTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
func (t *WebSearchTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][WebSearch] Execute started")
// Parse args from json.RawMessage
var input WebSearchInput
if err := json.Unmarshal(args, &input); err != nil {
logger.Errorf(ctx, "[Tool][WebSearch] Failed to parse args: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, err
}
// Parse query
query, ok := args["query"].(string)
query := input.Query
ok := query != ""
if !ok || query == "" {
logger.Errorf(ctx, "[Tool][WebSearch] Query is required")
return &types.ToolResult{
@@ -178,8 +183,8 @@ func (t *WebSearchTool) Execute(ctx context.Context, args map[string]interface{}
// Apply RAG compression if configured
if len(webResults) > 0 && tenant.WebSearchConfig.CompressionMethod != "none" &&
tenant.WebSearchConfig.CompressionMethod != "" {
// Load session-scoped temp KB state from Redis using SessionService
tempKBID, seen, ids := t.sessionService.GetWebSearchTempKBState(ctx, t.sessionID)
// Load session-scoped temp KB state from Redis using WebSearchStateRepository
tempKBID, seen, ids := t.webSearchStateService.GetWebSearchTempKBState(ctx, t.sessionID)
// Build questions for RAG compression
questions := []string{strings.TrimSpace(query)}
@@ -193,8 +198,8 @@ func (t *WebSearchTool) Execute(ctx context.Context, args map[string]interface{}
logger.Warnf(ctx, "[Tool][WebSearch] RAG compression failed, using raw results: %v", err)
} else {
webResults = compressed
// Persist temp KB state back into Redis using SessionService
t.sessionService.SaveWebSearchTempKBState(ctx, t.sessionID, kbID, newSeen, newIDs)
// Persist temp KB state back into Redis using WebSearchStateRepository
t.webSearchStateService.SaveWebSearchTempKBState(ctx, t.sessionID, kbID, newSeen, newIDs)
logger.Infof(ctx, "[Tool][WebSearch] RAG compression completed, %d results", len(webResults))
}
}