feat: Enhance agent configuration and localization for web search prompts
- Updated agent configuration to support separate system prompts for web search enabled and disabled states. - Removed deprecated agent configuration parameters to streamline settings management. - Enhanced UI components in AgentSettings.vue to allow configuration of custom prompts based on web search status. - Improved localization in English, Russian, and Chinese for new prompt settings and UI elements. - Refactored related API and service logic to accommodate changes in agent configuration structure.
This commit is contained in:
@@ -14,7 +14,7 @@ func AvailableToolDefinitions() []AvailableTool {
|
||||
{Name: "thinking", Label: "思考", Description: "动态和反思性的问题解决思考工具"},
|
||||
{Name: "todo_write", Label: "制定计划", Description: "创建结构化的研究计划"},
|
||||
{Name: "knowledge_search", Label: "知识搜索", Description: "在知识库中搜索相关信息"},
|
||||
{Name: "get_related_chunks", Label: "获取相关片段", Description: "查找相关的知识片段"},
|
||||
{Name: "list_knowledge_chunks", Label: "查看知识分块", Description: "按 knowledge_id 拉取文档分块列表"},
|
||||
{Name: "query_knowledge_graph", Label: "查询知识图谱", Description: "从知识图谱中查询关系"},
|
||||
{Name: "get_document_info", Label: "获取文档信息", Description: "查看文档元数据"},
|
||||
{Name: "database_query", Label: "查询数据库", Description: "查询数据库中的信息"},
|
||||
@@ -27,7 +27,7 @@ func DefaultAllowedTools() []string {
|
||||
"thinking",
|
||||
"todo_write",
|
||||
"knowledge_search",
|
||||
"get_related_chunks",
|
||||
"list_knowledge_chunks",
|
||||
"query_knowledge_graph",
|
||||
"get_document_info",
|
||||
"database_query",
|
||||
|
||||
@@ -12,12 +12,14 @@ import (
|
||||
// GetDocumentInfoTool retrieves detailed information about a document/knowledge
|
||||
type GetDocumentInfoTool struct {
|
||||
BaseTool
|
||||
tenantID uint
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
}
|
||||
|
||||
// NewGetDocumentInfoTool creates a new get document info tool
|
||||
func NewGetDocumentInfoTool(
|
||||
tenantID uint,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
chunkService interfaces.ChunkService,
|
||||
) *GetDocumentInfoTool {
|
||||
@@ -52,6 +54,7 @@ Do not use when:
|
||||
|
||||
return &GetDocumentInfoTool{
|
||||
BaseTool: NewBaseTool("get_document_info", description),
|
||||
tenantID: tenantID,
|
||||
knowledgeService: knowledgeService,
|
||||
chunkService: chunkService,
|
||||
}
|
||||
@@ -119,7 +122,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args map[string]inter
|
||||
defer wg.Done()
|
||||
|
||||
// Get knowledge metadata
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, id)
|
||||
knowledge, err := t.knowledgeService.GetRepository().GetKnowledgeByID(ctx, t.tenantID, id)
|
||||
if err != nil {
|
||||
mu.Lock()
|
||||
results[id] = &docInfo{
|
||||
@@ -130,7 +133,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args map[string]inter
|
||||
}
|
||||
|
||||
// Get chunk count
|
||||
chunks, err := t.chunkService.ListChunksByKnowledgeID(ctx, id)
|
||||
chunks, err := t.chunkService.GetRepository().ListChunksByKnowledgeID(ctx, t.tenantID, id)
|
||||
chunkCount := 0
|
||||
if err == nil {
|
||||
chunkCount = len(chunks)
|
||||
@@ -217,24 +220,24 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args map[string]inter
|
||||
output += "\n"
|
||||
|
||||
formattedDocs = append(formattedDocs, map[string]interface{}{
|
||||
"knowledge_id": k.ID,
|
||||
"title": k.Title,
|
||||
"description": k.Description,
|
||||
"type": k.Type,
|
||||
"source": k.Source,
|
||||
"file_name": k.FileName,
|
||||
"file_type": k.FileType,
|
||||
"file_size": k.FileSize,
|
||||
"parse_status": k.ParseStatus,
|
||||
"chunk_count": doc.chunkCount,
|
||||
"metadata": k.GetMetadata(),
|
||||
"type_icon": typeIcon,
|
||||
"knowledge_id": k.ID,
|
||||
"title": k.Title,
|
||||
"description": k.Description,
|
||||
"type": k.Type,
|
||||
"source": k.Source,
|
||||
"file_name": k.FileName,
|
||||
"file_type": k.FileType,
|
||||
"file_size": k.FileSize,
|
||||
"parse_status": k.ParseStatus,
|
||||
"chunk_count_min": doc.chunkCount,
|
||||
"metadata": k.GetMetadata(),
|
||||
"type_icon": typeIcon,
|
||||
})
|
||||
}
|
||||
|
||||
output += "=== Usage Tips ===\n"
|
||||
output += "- Use knowledge_search to search document content\n"
|
||||
output += "- Use get_related_chunks to view context and related chunks\n"
|
||||
output += "- Use list_knowledge_chunks to view context and related chunks\n"
|
||||
output += "- Search results already contain full chunk content\n"
|
||||
|
||||
// Extract first document title for summary
|
||||
|
||||
@@ -1,427 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// GetRelatedChunksTool retrieves chunks related to a given chunk
|
||||
type GetRelatedChunksTool struct {
|
||||
BaseTool
|
||||
chunkService interfaces.ChunkService
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService
|
||||
}
|
||||
|
||||
// NewGetRelatedChunksTool creates a new get related chunks tool
|
||||
func NewGetRelatedChunksTool(chunkService interfaces.ChunkService, knowledgeBaseService interfaces.KnowledgeBaseService) *GetRelatedChunksTool {
|
||||
description := `Retrieve chunks related to specified reference chunks. Supports sequential (adjacent) and semantic (similar) relation types.
|
||||
|
||||
## When to Use
|
||||
|
||||
Use this tool when:
|
||||
- Search results need additional context for full understanding
|
||||
- You need to see content before/after a specific chunk
|
||||
- Looking for semantically similar content across the document
|
||||
- Understanding the complete narrative flow of a topic
|
||||
|
||||
Do not use when:
|
||||
- Search results already provide sufficient complete content
|
||||
- Only need a single specific chunk without context
|
||||
|
||||
## Parameters
|
||||
|
||||
chunk_ids (required): Array of reference chunk IDs (1-10)
|
||||
- Obtained from search results
|
||||
- Supports concurrent batch processing
|
||||
- Example: ["chunk_abc", "chunk_def"]
|
||||
|
||||
relation_type (optional): Type of relation
|
||||
- "sequential" (default): Get adjacent chunks before and after
|
||||
- "semantic": Get semantically similar chunks regardless of position
|
||||
|
||||
limit (optional): Number of related chunks to return per reference chunk
|
||||
- Default: 5
|
||||
- Range: 1-10
|
||||
- Sequential: retrieves limit/2 chunks before and after
|
||||
- Semantic: retrieves top limit most similar chunks
|
||||
|
||||
## Relation Types
|
||||
|
||||
Sequential:
|
||||
- Retrieves adjacent chunks in document order
|
||||
- Useful for understanding complete narrative flow
|
||||
- Ideal for scenarios requiring continuous reading
|
||||
- Example: viewing complete configuration steps
|
||||
|
||||
Semantic:
|
||||
- Finds content-similar chunks regardless of position
|
||||
- Discovers related discussions throughout document
|
||||
- Ideal for topic expansion and cross-referencing
|
||||
- Example: finding all mentions of a specific concept
|
||||
|
||||
## Usage Patterns
|
||||
|
||||
1. Context expansion: knowledge_search -> get_related_chunks(sequential)
|
||||
2. Topic exploration: knowledge_search -> get_related_chunks(semantic)
|
||||
3. Deep research: knowledge_search -> get_related_chunks(both sequential and semantic)
|
||||
|
||||
## Notes
|
||||
|
||||
- Results are automatically deduplicated
|
||||
- Source chunks are excluded from results
|
||||
- Sequential results sorted by chunk_index
|
||||
- Semantic results sorted by similarity score
|
||||
- Limit value of 5 typically provides sufficient context without information overload`
|
||||
|
||||
return &GetRelatedChunksTool{
|
||||
BaseTool: NewBaseTool("get_related_chunks", description),
|
||||
chunkService: chunkService,
|
||||
knowledgeBaseService: knowledgeBaseService,
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters returns the JSON schema for the tool's parameters
|
||||
func (t *GetRelatedChunksTool) Parameters() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"chunk_ids": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "Array of reference chunk IDs",
|
||||
"items": map[string]interface{}{
|
||||
"type": "string",
|
||||
},
|
||||
"minItems": 1,
|
||||
"maxItems": 10,
|
||||
},
|
||||
"relation_type": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "Type: sequential (default) or semantic",
|
||||
"enum": []string{"sequential", "semantic"},
|
||||
"default": "sequential",
|
||||
},
|
||||
"limit": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Number of related chunks per input chunk (default: 5)",
|
||||
"default": 5,
|
||||
"minimum": 1,
|
||||
"maximum": 10,
|
||||
},
|
||||
},
|
||||
"required": []string{"chunk_ids"},
|
||||
}
|
||||
}
|
||||
|
||||
// Execute executes the get related chunks tool with concurrent processing
|
||||
func (t *GetRelatedChunksTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
// Extract chunk_ids array
|
||||
chunkIDsRaw, ok := args["chunk_ids"].([]interface{})
|
||||
if !ok || len(chunkIDsRaw) == 0 {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "chunk_ids is required and must be a non-empty array",
|
||||
}, fmt.Errorf("chunk_ids is required")
|
||||
}
|
||||
|
||||
// Convert to string slice
|
||||
var chunkIDs []string
|
||||
for _, id := range chunkIDsRaw {
|
||||
if idStr, ok := id.(string); ok && idStr != "" {
|
||||
chunkIDs = append(chunkIDs, idStr)
|
||||
}
|
||||
}
|
||||
|
||||
if len(chunkIDs) == 0 {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "chunk_ids must contain at least one valid chunk ID",
|
||||
}, fmt.Errorf("no valid chunk IDs provided")
|
||||
}
|
||||
|
||||
relationType := "sequential"
|
||||
if rt, ok := args["relation_type"].(string); ok {
|
||||
relationType = rt
|
||||
}
|
||||
|
||||
limit := 5
|
||||
if l, ok := args["limit"].(float64); ok {
|
||||
limit = int(l)
|
||||
}
|
||||
if limit < 1 {
|
||||
limit = 1
|
||||
}
|
||||
if limit > 10 {
|
||||
limit = 10
|
||||
}
|
||||
|
||||
// Concurrently get related chunks for each chunk ID
|
||||
type relatedResult struct {
|
||||
sourceChunk *types.Chunk
|
||||
relatedChunks []*types.Chunk
|
||||
err error
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
results := make(map[string]*relatedResult)
|
||||
|
||||
for _, chunkID := range chunkIDs {
|
||||
wg.Add(1)
|
||||
go func(id string) {
|
||||
defer wg.Done()
|
||||
|
||||
// Get the original chunk first
|
||||
chunk, err := t.chunkService.GetChunkByID(ctx, id)
|
||||
if err != nil || chunk == nil {
|
||||
mu.Lock()
|
||||
results[id] = &relatedResult{err: fmt.Errorf("failed to retrieve chunk: %v", err)}
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
var relatedChunks []*types.Chunk
|
||||
|
||||
if relationType == "sequential" {
|
||||
relatedChunks, err = t.getSequentialRelatedChunks(ctx, chunk, limit)
|
||||
} else if relationType == "semantic" {
|
||||
relatedChunks, err = t.getSemanticRelatedChunks(ctx, chunk, limit)
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
results[id] = &relatedResult{
|
||||
sourceChunk: chunk,
|
||||
relatedChunks: relatedChunks,
|
||||
err: err,
|
||||
}
|
||||
mu.Unlock()
|
||||
}(chunkID)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// Collect and deduplicate all related chunks
|
||||
seenChunks := make(map[string]*types.Chunk)
|
||||
sourceChunkIDs := make(map[string]bool)
|
||||
var errors []string
|
||||
|
||||
// Mark source chunks to exclude them from results
|
||||
for _, chunkID := range chunkIDs {
|
||||
sourceChunkIDs[chunkID] = true
|
||||
}
|
||||
|
||||
for _, chunkID := range chunkIDs {
|
||||
result := results[chunkID]
|
||||
if result.err != nil {
|
||||
errors = append(errors, fmt.Sprintf("chunk %s: %v", chunkID, result.err))
|
||||
continue
|
||||
}
|
||||
|
||||
for _, chunk := range result.relatedChunks {
|
||||
// Exclude source chunks and avoid duplicates
|
||||
if !sourceChunkIDs[chunk.ID] {
|
||||
if _, seen := seenChunks[chunk.ID]; !seen {
|
||||
seenChunks[chunk.ID] = chunk
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert map to slice and sort
|
||||
allRelatedChunks := make([]*types.Chunk, 0, len(seenChunks))
|
||||
for _, chunk := range seenChunks {
|
||||
allRelatedChunks = append(allRelatedChunks, chunk)
|
||||
}
|
||||
|
||||
// Sort chunks
|
||||
if relationType == "sequential" {
|
||||
// Sort by knowledge_id and chunk_index for sequential
|
||||
sortChunksByPosition(allRelatedChunks)
|
||||
}
|
||||
// For semantic, keep the order from search results (already sorted by relevance)
|
||||
|
||||
if len(allRelatedChunks) == 0 {
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: "No related chunks found. Possible reasons:\n- Chunk is the only chunk in document\n- Semantic similarity threshold not met\n- Invalid chunk_id provided",
|
||||
Data: map[string]interface{}{
|
||||
"chunk_ids": chunkIDs,
|
||||
"relation_type": relationType,
|
||||
"count": 0,
|
||||
"chunks": []interface{}{},
|
||||
"errors": errors,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Format output
|
||||
return t.formatOutput(chunkIDs, relationType, allRelatedChunks, errors)
|
||||
}
|
||||
|
||||
// getSequentialRelatedChunks gets chunks before and after the reference chunk
|
||||
func (t *GetRelatedChunksTool) getSequentialRelatedChunks(ctx context.Context, chunk *types.Chunk, limit int) ([]*types.Chunk, error) {
|
||||
// Get all chunks from the same knowledge
|
||||
allChunks, err := t.chunkService.ListChunksByKnowledgeID(ctx, chunk.KnowledgeID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to retrieve document chunks: %v", err)
|
||||
}
|
||||
|
||||
relatedChunks := make([]*types.Chunk, 0)
|
||||
|
||||
// Bidirectional window: get chunks before and after
|
||||
halfLimit := limit / 2
|
||||
if halfLimit < 1 {
|
||||
halfLimit = 1
|
||||
}
|
||||
|
||||
minIndex := chunk.ChunkIndex - halfLimit
|
||||
maxIndex := chunk.ChunkIndex + halfLimit
|
||||
|
||||
for _, c := range allChunks {
|
||||
// Within range and not the source chunk itself
|
||||
if c.ChunkIndex >= minIndex && c.ChunkIndex <= maxIndex && c.ID != chunk.ID {
|
||||
relatedChunks = append(relatedChunks, c)
|
||||
}
|
||||
}
|
||||
|
||||
return relatedChunks, nil
|
||||
}
|
||||
|
||||
// getSemanticRelatedChunks gets semantically similar chunks using hybrid search
|
||||
func (t *GetRelatedChunksTool) getSemanticRelatedChunks(ctx context.Context, chunk *types.Chunk, limit int) ([]*types.Chunk, error) {
|
||||
// Use chunk content as query for semantic search
|
||||
searchParams := types.SearchParams{
|
||||
QueryText: chunk.Content,
|
||||
MatchCount: limit + 5, // Get extra results for filtering
|
||||
}
|
||||
|
||||
// Search in the knowledge base that contains this chunk
|
||||
searchResults, err := t.knowledgeBaseService.HybridSearch(ctx, chunk.KnowledgeBaseID, searchParams)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("semantic search failed: %v", err)
|
||||
}
|
||||
|
||||
// Convert search results to chunks, excluding the source chunk
|
||||
relatedChunks := make([]*types.Chunk, 0, limit)
|
||||
for _, result := range searchResults {
|
||||
if result.ID == chunk.ID {
|
||||
continue // Skip the source chunk itself
|
||||
}
|
||||
|
||||
// Convert SearchResult to Chunk
|
||||
relatedChunk := &types.Chunk{
|
||||
ID: result.ID,
|
||||
KnowledgeID: result.KnowledgeID,
|
||||
KnowledgeBaseID: chunk.KnowledgeBaseID,
|
||||
Content: result.Content,
|
||||
ChunkIndex: result.ChunkIndex,
|
||||
}
|
||||
|
||||
relatedChunks = append(relatedChunks, relatedChunk)
|
||||
|
||||
if len(relatedChunks) >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return relatedChunks, nil
|
||||
}
|
||||
|
||||
// sortChunksByPosition sorts chunks by knowledge_id and chunk_index
|
||||
func sortChunksByPosition(chunks []*types.Chunk) {
|
||||
// Simple bubble sort for small arrays
|
||||
n := len(chunks)
|
||||
for i := 0; i < n-1; i++ {
|
||||
for j := 0; j < n-i-1; j++ {
|
||||
// First sort by knowledge_id, then by chunk_index
|
||||
if chunks[j].KnowledgeID > chunks[j+1].KnowledgeID ||
|
||||
(chunks[j].KnowledgeID == chunks[j+1].KnowledgeID &&
|
||||
chunks[j].ChunkIndex > chunks[j+1].ChunkIndex) {
|
||||
chunks[j], chunks[j+1] = chunks[j+1], chunks[j]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// formatOutput formats the tool output
|
||||
func (t *GetRelatedChunksTool) formatOutput(
|
||||
chunkIDs []string,
|
||||
relationType string,
|
||||
chunks []*types.Chunk,
|
||||
errors []string,
|
||||
) (*types.ToolResult, error) {
|
||||
relationTypeLabel := map[string]string{
|
||||
"sequential": "Sequential (Adjacent)",
|
||||
"semantic": "Semantic (Similar Content)",
|
||||
}
|
||||
|
||||
output := "=== Related Chunks ===\n\n"
|
||||
output += fmt.Sprintf("Reference chunks: %d\n", len(chunkIDs))
|
||||
output += fmt.Sprintf("Relation type: %s\n", relationTypeLabel[relationType])
|
||||
output += fmt.Sprintf("Found %d related chunks (deduplicated)\n\n", len(chunks))
|
||||
|
||||
if len(errors) > 0 {
|
||||
output += "=== Partial Failures ===\n"
|
||||
for _, errMsg := range errors {
|
||||
output += fmt.Sprintf(" - %s\n", errMsg)
|
||||
}
|
||||
output += "\n"
|
||||
}
|
||||
|
||||
output += "=== Content ===\n\n"
|
||||
|
||||
formattedChunks := make([]map[string]interface{}, 0, len(chunks))
|
||||
currentKnowledge := ""
|
||||
|
||||
for i, c := range chunks {
|
||||
// Group by knowledge document
|
||||
if c.KnowledgeID != currentKnowledge {
|
||||
currentKnowledge = c.KnowledgeID
|
||||
if i > 0 {
|
||||
output += "\n"
|
||||
}
|
||||
output += fmt.Sprintf("[Document: %s]\n\n", c.KnowledgeID)
|
||||
}
|
||||
|
||||
output += fmt.Sprintf("Chunk #%d (Position: %d):\n", i+1, c.ChunkIndex+1)
|
||||
output += fmt.Sprintf(" chunk_id: %s\n", c.ID)
|
||||
output += fmt.Sprintf(" content: %s\n\n", c.Content)
|
||||
|
||||
formattedChunks = append(formattedChunks, map[string]interface{}{
|
||||
"index": i + 1,
|
||||
"chunk_id": c.ID,
|
||||
"chunk_index": c.ChunkIndex,
|
||||
"content": c.Content,
|
||||
"knowledge_id": c.KnowledgeID,
|
||||
})
|
||||
}
|
||||
|
||||
output += "=== Notes ===\n"
|
||||
if relationType == "sequential" {
|
||||
output += "- Adjacent chunks in document order\n"
|
||||
output += "- Useful for understanding complete narrative flow\n"
|
||||
output += "- Sorted by position\n"
|
||||
} else {
|
||||
output += "- Semantically similar chunks sorted by relevance\n"
|
||||
output += "- Useful for discovering related discussions\n"
|
||||
output += "- Ideal for topic expansion and cross-referencing\n"
|
||||
}
|
||||
output += "- Source chunks excluded\n"
|
||||
output += "- Results deduplicated\n"
|
||||
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: output,
|
||||
Data: map[string]interface{}{
|
||||
"chunk_ids": chunkIDs,
|
||||
"relation_type": relationType,
|
||||
"count": len(chunks),
|
||||
"chunks": formattedChunks,
|
||||
"errors": errors,
|
||||
"display_type": "related_chunks",
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/models/rerank"
|
||||
@@ -28,48 +29,39 @@ type searchResultWithMeta struct {
|
||||
// KnowledgeSearchTool searches knowledge bases with flexible query modes
|
||||
type KnowledgeSearchTool struct {
|
||||
BaseTool
|
||||
knowledgeService interfaces.KnowledgeBaseService
|
||||
chunkService interfaces.ChunkService
|
||||
tenantID uint
|
||||
allowedKBs []string
|
||||
rerankModel rerank.Reranker
|
||||
chatModel chat.Chat // Optional chat model for LLM-based reranking
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService
|
||||
chunkService interfaces.ChunkService
|
||||
tenantID uint
|
||||
allowedKBs []string
|
||||
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(
|
||||
knowledgeService interfaces.KnowledgeBaseService,
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService,
|
||||
chunkService interfaces.ChunkService,
|
||||
tenantID uint,
|
||||
allowedKBs []string,
|
||||
rerankModel rerank.Reranker,
|
||||
chatModel chat.Chat,
|
||||
cfg *config.Config,
|
||||
) *KnowledgeSearchTool {
|
||||
description := `Search within knowledge bases with flexible query modes. Unified tool that supports both targeted and broad searches.
|
||||
description := `Search within knowledge bases. Unified tool that supports both targeted and broad searches.
|
||||
|
||||
## Features
|
||||
- Multi-KB search: Search across multiple knowledge bases concurrently
|
||||
- Flexible queries: Support vector, keyword, or hybrid search modes
|
||||
- Quality filtering: Automatically filters low-quality chunks
|
||||
|
||||
## Usage
|
||||
|
||||
**Use when**:
|
||||
- You know which knowledge bases to target (specify knowledge_base_ids)
|
||||
- You're unsure which KB contains the info (omit knowledge_base_ids to search all allowed KBs)
|
||||
- Want to search specific KBs with same query
|
||||
- Need semantic (vector) or exact keyword searches
|
||||
- Want to search only specific documents within KBs
|
||||
- Want to search with multiple queries to get comprehensive results
|
||||
- Want to filter results from specific documents (use knowledge_ids)
|
||||
|
||||
|
||||
**Search Modes**:
|
||||
- Simple: Provide single query parameter (hybrid search)
|
||||
- Vector only: Provide vector_queries only
|
||||
- Keyword only: Provide keyword_queries only
|
||||
- Hybrid: Provide both vector_queries and keyword_queries
|
||||
- At least one query parameter must be provided
|
||||
|
||||
**Returns**: Merged and deduplicated search results from all KBs
|
||||
**Returns**: Merged and deduplicated search results from KBs
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -77,48 +69,37 @@ func NewKnowledgeSearchTool(
|
||||
# Simple search in specific KBs
|
||||
{
|
||||
"knowledge_base_ids": ["kb1", "kb2"],
|
||||
"query": "什么是向量数据库"
|
||||
"queries": ["什么是向量数据库"]
|
||||
}
|
||||
|
||||
# Search all allowed KBs with vector queries
|
||||
# Search all allowed KBs with multiple queries
|
||||
{
|
||||
"vector_queries": ["什么是向量数据库", "向量数据库的定义"]
|
||||
}
|
||||
|
||||
# Multiple query types with thresholds
|
||||
{
|
||||
"knowledge_base_ids": ["kb1"],
|
||||
"vector_queries": ["向量数据库应用"],
|
||||
"keyword_queries": ["Docker", "部署"],
|
||||
"vector_threshold": 0.7,
|
||||
"keyword_threshold": 0.6
|
||||
"queries": ["什么是向量数据库", "向量数据库的应用场景"]
|
||||
}
|
||||
|
||||
# Search specific documents
|
||||
{
|
||||
"knowledge_base_ids": ["kb1"],
|
||||
"query": "彗星的起源",
|
||||
"queries": ["彗星的起源"],
|
||||
"knowledge_ids": ["doc1", "doc2"]
|
||||
}
|
||||
` + "`" + `
|
||||
|
||||
## Tips
|
||||
|
||||
- Concurrent search across multiple KBs and queries
|
||||
- Concurrent search across multiple KBs
|
||||
- Results are automatically reranked to unify scores from different sources
|
||||
- Reranked scores are in 0-1 range and directly comparable
|
||||
- Results are merged, deduplicated and sorted by relevance
|
||||
- Use vector_queries for semantic/conceptual searches
|
||||
- Use keyword_queries for exact term matching`
|
||||
- Results are merged, deduplicated and sorted by relevance`
|
||||
|
||||
return &KnowledgeSearchTool{
|
||||
BaseTool: NewBaseTool("knowledge_search", description),
|
||||
knowledgeService: knowledgeService,
|
||||
chunkService: chunkService,
|
||||
tenantID: tenantID,
|
||||
allowedKBs: allowedKBs,
|
||||
rerankModel: rerankModel,
|
||||
chatModel: chatModel,
|
||||
BaseTool: NewBaseTool("knowledge_search", description),
|
||||
knowledgeBaseService: knowledgeBaseService,
|
||||
chunkService: chunkService,
|
||||
tenantID: tenantID,
|
||||
allowedKBs: allowedKBs,
|
||||
rerankModel: rerankModel,
|
||||
chatModel: chatModel,
|
||||
config: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,80 +108,39 @@ func (t *KnowledgeSearchTool) Parameters() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"queries": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "Array of search queries",
|
||||
"items": map[string]interface{}{
|
||||
"type": "string",
|
||||
},
|
||||
"minItems": 1,
|
||||
"maxItems": 5,
|
||||
},
|
||||
"knowledge_base_ids": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "Array of knowledge base IDs to search in (optional, if omitted searches all allowed KBs)",
|
||||
"items": map[string]interface{}{
|
||||
"type": "string",
|
||||
},
|
||||
"minItems": 1,
|
||||
"minItems": 0,
|
||||
"maxItems": 10,
|
||||
},
|
||||
"query": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "Single search query for simple hybrid search",
|
||||
},
|
||||
"vector_queries": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "Array of semantic queries for vector search (1-5 queries)",
|
||||
"items": map[string]interface{}{
|
||||
"type": "string",
|
||||
},
|
||||
"minItems": 1,
|
||||
"maxItems": 5,
|
||||
},
|
||||
"keyword_queries": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "Array of keyword queries for keyword search (1-5 queries)",
|
||||
"items": map[string]interface{}{
|
||||
"type": "string",
|
||||
},
|
||||
"minItems": 1,
|
||||
"maxItems": 5,
|
||||
},
|
||||
"top_k": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Number of results per knowledge base per query (default: 5)",
|
||||
"default": 5,
|
||||
"minimum": 1,
|
||||
"maximum": 20,
|
||||
},
|
||||
"vector_threshold": map[string]interface{}{
|
||||
"type": "number",
|
||||
"description": "Minimum score for vector results (default: 0.6)",
|
||||
"default": 0.6,
|
||||
"minimum": 0.0,
|
||||
"maximum": 1.0,
|
||||
},
|
||||
"keyword_threshold": map[string]interface{}{
|
||||
"type": "number",
|
||||
"description": "Minimum score for keyword results (default: 0.5)",
|
||||
"default": 0.5,
|
||||
"minimum": 0.0,
|
||||
"maximum": 1.0,
|
||||
},
|
||||
"knowledge_ids": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "Optional array of document IDs to filter results (only return results from these specific documents)",
|
||||
"items": map[string]interface{}{
|
||||
"type": "string",
|
||||
},
|
||||
"minItems": 1,
|
||||
"minItems": 0,
|
||||
"maxItems": 50,
|
||||
},
|
||||
"min_score": map[string]interface{}{
|
||||
"type": "number",
|
||||
"description": "Absolute minimum score threshold for filtering very low quality results (default: 0.3)",
|
||||
"default": 0.3,
|
||||
"minimum": 0.0,
|
||||
"maximum": 1.0,
|
||||
},
|
||||
},
|
||||
"required": []string{},
|
||||
"required": []string{"queries"},
|
||||
}
|
||||
}
|
||||
|
||||
// Execute executes the knowledge search tool with flexible query modes
|
||||
// Execute executes the knowledge search tool
|
||||
func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Execute started")
|
||||
|
||||
@@ -232,90 +172,74 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Using all allowed KBs (%d): %v", len(kbIDs), kbIDs)
|
||||
}
|
||||
|
||||
// Parse query parameters
|
||||
var singleQuery string
|
||||
var vectorQueries, keywordQueries []string
|
||||
|
||||
// Parse single query
|
||||
if q, ok := args["query"].(string); ok && q != "" {
|
||||
singleQuery = q
|
||||
}
|
||||
|
||||
// Parse vector_queries
|
||||
if vq, ok := args["vector_queries"].([]interface{}); ok {
|
||||
for _, q := range vq {
|
||||
if queryStr, ok := q.(string); ok && queryStr != "" {
|
||||
vectorQueries = append(vectorQueries, queryStr)
|
||||
// Parse 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse keyword_queries
|
||||
if kq, ok := args["keyword_queries"].([]interface{}); ok {
|
||||
for _, q := range kq {
|
||||
if queryStr, ok := q.(string); ok && queryStr != "" {
|
||||
keywordQueries = append(keywordQueries, queryStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If single query provided, treat it as both vector and keyword query
|
||||
if singleQuery != "" {
|
||||
if len(vectorQueries) == 0 && len(keywordQueries) == 0 {
|
||||
vectorQueries = []string{singleQuery}
|
||||
keywordQueries = []string{singleQuery}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate: at least one query must be provided
|
||||
if len(vectorQueries) == 0 && len(keywordQueries) == 0 {
|
||||
logger.Errorf(ctx, "[Tool][KnowledgeSearch] No query provided")
|
||||
// Validate: query must be provided
|
||||
if len(queries) == 0 {
|
||||
logger.Errorf(ctx, "[Tool][KnowledgeSearch] No queries provided")
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "at least one of query, vector_queries, or keyword_queries must be provided",
|
||||
}, fmt.Errorf("no query provided")
|
||||
Error: "queries parameter is required",
|
||||
}, fmt.Errorf("no queries provided")
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Query mode: single=%v, vector_queries=%d, keyword_queries=%d",
|
||||
singleQuery != "", len(vectorQueries), len(keywordQueries))
|
||||
if singleQuery != "" {
|
||||
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Single query: %s", singleQuery)
|
||||
}
|
||||
if len(vectorQueries) > 0 {
|
||||
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Vector queries: %v", vectorQueries)
|
||||
}
|
||||
if len(keywordQueries) > 0 {
|
||||
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Keyword queries: %v", keywordQueries)
|
||||
}
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Queries: %v", queries)
|
||||
|
||||
// Parse thresholds
|
||||
vectorThreshold := 0.6
|
||||
if vt, ok := args["vector_threshold"].(float64); ok {
|
||||
vectorThreshold = vt
|
||||
}
|
||||
// Get search parameters from tenant conversation config, fallback to global config
|
||||
var topK int
|
||||
var vectorThreshold, keywordThreshold, minScore float64
|
||||
|
||||
keywordThreshold := 0.5
|
||||
if kt, ok := args["keyword_threshold"].(float64); ok {
|
||||
keywordThreshold = kt
|
||||
}
|
||||
|
||||
// Parse min_score for absolute filtering
|
||||
minScore := 0.3
|
||||
if ms, ok := args["min_score"].(float64); ok {
|
||||
minScore = ms
|
||||
}
|
||||
|
||||
// Parse top_k
|
||||
topK := 5
|
||||
if topKVal, ok := args["top_k"]; ok {
|
||||
switch v := topKVal.(type) {
|
||||
case float64:
|
||||
topK = int(v)
|
||||
case int:
|
||||
topK = v
|
||||
// Try to get from tenant conversation config
|
||||
if tenantVal := ctx.Value(types.TenantInfoContextKey); tenantVal != nil {
|
||||
if tenant, ok := tenantVal.(*types.Tenant); ok && tenant != nil && tenant.ConversationConfig != nil {
|
||||
cc := tenant.ConversationConfig
|
||||
if cc.EmbeddingTopK > 0 {
|
||||
topK = cc.EmbeddingTopK
|
||||
}
|
||||
if cc.VectorThreshold > 0 {
|
||||
vectorThreshold = cc.VectorThreshold
|
||||
}
|
||||
if cc.KeywordThreshold > 0 {
|
||||
keywordThreshold = cc.KeywordThreshold
|
||||
}
|
||||
// minScore is not in ConversationConfig, use default or config
|
||||
minScore = 0.3
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to global config if not set
|
||||
if topK == 0 && t.config != nil {
|
||||
topK = t.config.Conversation.EmbeddingTopK
|
||||
}
|
||||
if vectorThreshold == 0 && t.config != nil {
|
||||
vectorThreshold = t.config.Conversation.VectorThreshold
|
||||
}
|
||||
if keywordThreshold == 0 && t.config != nil {
|
||||
keywordThreshold = t.config.Conversation.KeywordThreshold
|
||||
}
|
||||
|
||||
// Final fallback to hardcoded defaults if config is not available
|
||||
if topK == 0 {
|
||||
topK = 5
|
||||
}
|
||||
if vectorThreshold == 0 {
|
||||
vectorThreshold = 0.6
|
||||
}
|
||||
if keywordThreshold == 0 {
|
||||
keywordThreshold = 0.5
|
||||
}
|
||||
if minScore == 0 {
|
||||
minScore = 0.3
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Search params: top_k=%d, vector_threshold=%.2f, keyword_threshold=%.2f, min_score=%.2f",
|
||||
topK, vectorThreshold, keywordThreshold, minScore)
|
||||
|
||||
@@ -330,11 +254,11 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
|
||||
}
|
||||
}
|
||||
|
||||
// Execute concurrent search
|
||||
// Execute concurrent search (hybrid search handles both vector and keyword)
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Starting concurrent search across %d KBs", len(kbIDs))
|
||||
kbTypeMap := t.getKnowledgeBaseTypes(ctx, kbIDs)
|
||||
|
||||
allResults := t.concurrentSearch(ctx, vectorQueries, keywordQueries, kbIDs,
|
||||
allResults := t.concurrentSearch(ctx, queries, kbIDs,
|
||||
topK, vectorThreshold, keywordThreshold, kbTypeMap)
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Concurrent search completed: %d raw results", len(allResults))
|
||||
|
||||
@@ -353,55 +277,54 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
|
||||
}
|
||||
|
||||
// Filter by threshold first
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying threshold filter...")
|
||||
filteredResults := t.filterByThreshold(allResults, vectorThreshold, keywordThreshold)
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] After threshold filter: %d results (from %d)",
|
||||
len(filteredResults), len(allResults))
|
||||
|
||||
// Deduplicate before reranking to reduce processing overhead
|
||||
deduplicatedBeforeRerank := t.deduplicateResults(filteredResults)
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] After deduplication before rerank: %d results (from %d)",
|
||||
len(deduplicatedBeforeRerank), len(filteredResults))
|
||||
|
||||
// Apply ReRank if model is configured
|
||||
// Prefer chatModel (LLM-based reranking) over rerankModel if both are available
|
||||
if t.chatModel != nil && len(filteredResults) > 0 {
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying LLM-based rerank with model: %s, input: %d results",
|
||||
t.chatModel.GetModelName(), len(filteredResults))
|
||||
rerankQuery := singleQuery
|
||||
if rerankQuery == "" && len(vectorQueries) > 0 {
|
||||
rerankQuery = vectorQueries[0] // Use first vector query as rerank query
|
||||
} else if rerankQuery == "" && len(keywordQueries) > 0 {
|
||||
rerankQuery = keywordQueries[0] // Use first keyword query as fallback
|
||||
// Use first query for reranking (or combine all queries if needed)
|
||||
rerankQuery := ""
|
||||
if len(queries) > 0 {
|
||||
rerankQuery = queries[0]
|
||||
if len(queries) > 1 {
|
||||
// Combine multiple queries for reranking
|
||||
rerankQuery = strings.Join(queries, " ")
|
||||
}
|
||||
}
|
||||
|
||||
if rerankQuery != "" {
|
||||
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Rerank query: %s", rerankQuery)
|
||||
rerankedResults, err := t.rerankResults(ctx, rerankQuery, filteredResults)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] LLM rerank failed, using original results: %v", err)
|
||||
} else {
|
||||
filteredResults = rerankedResults
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] LLM rerank completed successfully: %d results",
|
||||
len(filteredResults))
|
||||
}
|
||||
if t.chatModel != nil && len(deduplicatedBeforeRerank) > 0 && rerankQuery != "" {
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying LLM-based rerank with model: %s, input: %d results, queries: %v",
|
||||
t.chatModel.GetModelName(), len(deduplicatedBeforeRerank), queries)
|
||||
rerankedResults, err := t.rerankResults(ctx, rerankQuery, deduplicatedBeforeRerank)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] LLM rerank failed, using original results: %v", err)
|
||||
filteredResults = deduplicatedBeforeRerank
|
||||
} else {
|
||||
filteredResults = rerankedResults
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] LLM rerank completed successfully: %d results",
|
||||
len(filteredResults))
|
||||
}
|
||||
} else if t.rerankModel != nil && len(filteredResults) > 0 {
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying rerank with model: %s, input: %d results",
|
||||
t.rerankModel.GetModelName(), len(filteredResults))
|
||||
rerankQuery := singleQuery
|
||||
if rerankQuery == "" && len(vectorQueries) > 0 {
|
||||
rerankQuery = vectorQueries[0] // Use first vector query as rerank query
|
||||
} else if rerankQuery == "" && len(keywordQueries) > 0 {
|
||||
rerankQuery = keywordQueries[0] // Use first keyword query as fallback
|
||||
}
|
||||
|
||||
if rerankQuery != "" {
|
||||
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Rerank query: %s", rerankQuery)
|
||||
rerankedResults, err := t.rerankResults(ctx, rerankQuery, filteredResults)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Rerank failed, using original results: %v", err)
|
||||
} else {
|
||||
filteredResults = rerankedResults
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Rerank completed successfully: %d results",
|
||||
len(filteredResults))
|
||||
}
|
||||
} else if t.rerankModel != nil && len(deduplicatedBeforeRerank) > 0 && rerankQuery != "" {
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying rerank with model: %s, input: %d results, queries: %v",
|
||||
t.rerankModel.GetModelName(), len(deduplicatedBeforeRerank), queries)
|
||||
rerankedResults, err := t.rerankResults(ctx, rerankQuery, deduplicatedBeforeRerank)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Rerank failed, using original results: %v", err)
|
||||
filteredResults = deduplicatedBeforeRerank
|
||||
} else {
|
||||
filteredResults = rerankedResults
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Rerank completed successfully: %d results",
|
||||
len(filteredResults))
|
||||
}
|
||||
} else {
|
||||
// No reranking, use deduplicated results
|
||||
filteredResults = deduplicatedBeforeRerank
|
||||
}
|
||||
|
||||
// Apply absolute minimum score filter to remove very low quality chunks
|
||||
@@ -409,44 +332,37 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
|
||||
filteredResults = t.filterByMinScore(filteredResults, minScore)
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] After min_score filter: %d results", len(filteredResults))
|
||||
|
||||
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Deduplicating results...")
|
||||
// Final deduplication after rerank (in case rerank changed scores/order but duplicates remain)
|
||||
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Final deduplication after rerank...")
|
||||
deduplicatedResults := t.deduplicateResults(filteredResults)
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] After deduplication: %d results (from %d)",
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] After final deduplication: %d results (from %d)",
|
||||
len(deduplicatedResults), len(filteredResults))
|
||||
|
||||
// Sort results by score (descending)
|
||||
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Sorting results by score...")
|
||||
sort.Slice(deduplicatedResults, func(i, j int) bool {
|
||||
if deduplicatedResults[i].Score != deduplicatedResults[j].Score {
|
||||
return deduplicatedResults[i].Score > deduplicatedResults[j].Score
|
||||
}
|
||||
// If scores are equal, prefer vector matches
|
||||
if deduplicatedResults[i].QueryType != deduplicatedResults[j].QueryType {
|
||||
return deduplicatedResults[i].QueryType == "vector"
|
||||
}
|
||||
// If scores are equal, sort by knowledge ID for consistency
|
||||
return deduplicatedResults[i].KnowledgeID < deduplicatedResults[j].KnowledgeID
|
||||
})
|
||||
|
||||
// Log top results
|
||||
if len(deduplicatedResults) > 0 {
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Top 5 results by score:")
|
||||
for i := 0; i < len(deduplicatedResults) && i < 5; i++ {
|
||||
r := deduplicatedResults[i]
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] #%d: score=%.3f, type=%s, kb=%s, chunk_id=%s",
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch][Top %d] score=%.3f, type=%s, kb=%s, chunk_id=%s",
|
||||
i+1, r.Score, r.QueryType, r.KnowledgeID, r.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// Build output
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Formatting output with %d final results", len(deduplicatedResults))
|
||||
result, err := t.formatOutput(ctx, deduplicatedResults, vectorQueries, keywordQueries,
|
||||
kbIDs, len(allResults), vectorThreshold, keywordThreshold, knowledgeIDsFilter, singleQuery)
|
||||
result, err := t.formatOutput(ctx, deduplicatedResults, kbIDs, len(allResults), knowledgeIDsFilter, queries)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][KnowledgeSearch] Failed to format output: %v", err)
|
||||
return result, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Execute completed successfully")
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -462,7 +378,7 @@ func (t *KnowledgeSearchTool) getKnowledgeBaseTypes(ctx context.Context, kbIDs [
|
||||
continue
|
||||
}
|
||||
|
||||
kb, err := t.knowledgeService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
kb, err := t.knowledgeBaseService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to fetch knowledge base %s info: %v", kbID, err)
|
||||
continue
|
||||
@@ -474,57 +390,13 @@ func (t *KnowledgeSearchTool) getKnowledgeBaseTypes(ctx context.Context, kbIDs [
|
||||
return kbTypeMap
|
||||
}
|
||||
|
||||
// concurrentSearch executes vector and keyword searches concurrently
|
||||
// concurrentSearch executes hybrid search across multiple KBs concurrently
|
||||
func (t *KnowledgeSearchTool) concurrentSearch(
|
||||
ctx context.Context,
|
||||
vectorQueries, keywordQueries []string,
|
||||
kbsToSearch []string,
|
||||
topK int,
|
||||
vectorThreshold, keywordThreshold float64,
|
||||
kbTypeMap map[string]string,
|
||||
) []*searchResultWithMeta {
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
allResults := make([]*searchResultWithMeta, 0)
|
||||
|
||||
// Launch vector searches
|
||||
if len(vectorQueries) > 0 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
results := t.searchWithQueries(ctx, vectorQueries, kbsToSearch, topK,
|
||||
vectorThreshold, 1.0, "vector", kbTypeMap)
|
||||
mu.Lock()
|
||||
allResults = append(allResults, results...)
|
||||
mu.Unlock()
|
||||
}()
|
||||
}
|
||||
|
||||
// Launch keyword searches
|
||||
if len(keywordQueries) > 0 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
results := t.searchWithQueries(ctx, keywordQueries, kbsToSearch, topK,
|
||||
1.0, keywordThreshold, "keyword", kbTypeMap)
|
||||
mu.Lock()
|
||||
allResults = append(allResults, results...)
|
||||
mu.Unlock()
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
return allResults
|
||||
}
|
||||
|
||||
// searchWithQueries executes multiple queries concurrently
|
||||
func (t *KnowledgeSearchTool) searchWithQueries(
|
||||
ctx context.Context,
|
||||
queries []string,
|
||||
kbsToSearch []string,
|
||||
topK int,
|
||||
vectorThreshold, keywordThreshold float64,
|
||||
queryType string,
|
||||
kbTypeMap map[string]string,
|
||||
) []*searchResultWithMeta {
|
||||
var wg sync.WaitGroup
|
||||
@@ -532,72 +404,46 @@ func (t *KnowledgeSearchTool) searchWithQueries(
|
||||
allResults := make([]*searchResultWithMeta, 0)
|
||||
|
||||
for _, query := range queries {
|
||||
wg.Add(1)
|
||||
go func(q string) {
|
||||
defer wg.Done()
|
||||
results := t.searchSingleQuery(ctx, q, kbsToSearch, topK,
|
||||
vectorThreshold, keywordThreshold, queryType, kbTypeMap)
|
||||
mu.Lock()
|
||||
allResults = append(allResults, results...)
|
||||
mu.Unlock()
|
||||
}(query)
|
||||
}
|
||||
// Capture query in local variable to avoid closure issues
|
||||
q := query
|
||||
for _, kbID := range kbsToSearch {
|
||||
// Capture kbID in local variable to avoid closure issues
|
||||
kb := kbID
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
searchParams := types.SearchParams{
|
||||
QueryText: q,
|
||||
MatchCount: topK,
|
||||
VectorThreshold: vectorThreshold,
|
||||
KeywordThreshold: keywordThreshold,
|
||||
}
|
||||
kbResults, err := t.knowledgeBaseService.HybridSearch(ctx, kb, searchParams)
|
||||
if err != nil {
|
||||
// Log error but continue with other KBs
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to search knowledge base %s: %v", kb, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Wrap results with metadata
|
||||
mu.Lock()
|
||||
for _, r := range kbResults {
|
||||
allResults = append(allResults, &searchResultWithMeta{
|
||||
SearchResult: r,
|
||||
SourceQuery: q,
|
||||
QueryType: "hybrid", // Hybrid search combines both vector and keyword
|
||||
KnowledgeBaseID: kb,
|
||||
KnowledgeBaseType: kbTypeMap[kb],
|
||||
})
|
||||
}
|
||||
mu.Unlock()
|
||||
}()
|
||||
}
|
||||
}
|
||||
wg.Wait()
|
||||
return allResults
|
||||
}
|
||||
|
||||
// searchSingleQuery searches a single query across multiple KBs concurrently
|
||||
func (t *KnowledgeSearchTool) searchSingleQuery(
|
||||
ctx context.Context,
|
||||
query string,
|
||||
kbsToSearch []string,
|
||||
topK int,
|
||||
vectorThreshold, keywordThreshold float64,
|
||||
queryType string,
|
||||
kbTypeMap map[string]string,
|
||||
) []*searchResultWithMeta {
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
results := make([]*searchResultWithMeta, 0)
|
||||
|
||||
searchParams := types.SearchParams{
|
||||
QueryText: query,
|
||||
MatchCount: topK,
|
||||
VectorThreshold: vectorThreshold,
|
||||
KeywordThreshold: keywordThreshold,
|
||||
}
|
||||
|
||||
for _, kbID := range kbsToSearch {
|
||||
wg.Add(1)
|
||||
go func(kb string) {
|
||||
defer wg.Done()
|
||||
|
||||
kbResults, err := t.knowledgeService.HybridSearch(ctx, kb, searchParams)
|
||||
if err != nil {
|
||||
// Log error but continue with other KBs
|
||||
return
|
||||
}
|
||||
|
||||
// Wrap results with metadata
|
||||
mu.Lock()
|
||||
for _, r := range kbResults {
|
||||
results = append(results, &searchResultWithMeta{
|
||||
SearchResult: r,
|
||||
SourceQuery: query,
|
||||
QueryType: queryType,
|
||||
KnowledgeBaseID: kb,
|
||||
KnowledgeBaseType: kbTypeMap[kb],
|
||||
})
|
||||
}
|
||||
mu.Unlock()
|
||||
}(kbID)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
return results
|
||||
}
|
||||
|
||||
// filterByThreshold filters results based on match type and threshold
|
||||
func (t *KnowledgeSearchTool) filterByThreshold(
|
||||
results []*searchResultWithMeta,
|
||||
@@ -1011,12 +857,10 @@ func (t *KnowledgeSearchTool) deduplicateResults(results []*searchResultWithMeta
|
||||
func (t *KnowledgeSearchTool) formatOutput(
|
||||
ctx context.Context,
|
||||
results []*searchResultWithMeta,
|
||||
vectorQueries, keywordQueries []string,
|
||||
kbsToSearch []string,
|
||||
totalBeforeFilter int,
|
||||
vectorThreshold, keywordThreshold float64,
|
||||
knowledgeIDsFilter map[string]bool,
|
||||
singleQuery string,
|
||||
queries []string,
|
||||
) (*types.ToolResult, error) {
|
||||
if len(results) == 0 {
|
||||
data := map[string]interface{}{
|
||||
@@ -1031,8 +875,8 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
}
|
||||
data["knowledge_ids"] = filterList
|
||||
}
|
||||
if singleQuery != "" {
|
||||
data["query"] = singleQuery
|
||||
if len(queries) > 0 {
|
||||
data["queries"] = queries
|
||||
}
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
@@ -1041,14 +885,6 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Determine search mode
|
||||
searchMode := "Hybrid (Vector + Keyword)"
|
||||
if len(vectorQueries) > 0 && len(keywordQueries) == 0 {
|
||||
searchMode = "Vector"
|
||||
} else if len(vectorQueries) == 0 && len(keywordQueries) > 0 {
|
||||
searchMode = "Keyword"
|
||||
}
|
||||
|
||||
// Build output header
|
||||
output := "=== Search Results ===\n"
|
||||
output += fmt.Sprintf("Knowledge Bases: %v\n", kbsToSearch)
|
||||
@@ -1059,22 +895,13 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
}
|
||||
output += fmt.Sprintf("Document Filter: %v\n", filterList)
|
||||
}
|
||||
output += fmt.Sprintf("Search Mode: %s\n", searchMode)
|
||||
|
||||
if singleQuery != "" {
|
||||
output += fmt.Sprintf("Query: %s\n", singleQuery)
|
||||
} else {
|
||||
if len(vectorQueries) > 0 {
|
||||
output += fmt.Sprintf("Vector Queries: %v\n", vectorQueries)
|
||||
output += fmt.Sprintf("Vector Threshold: %.2f\n", vectorThreshold)
|
||||
}
|
||||
if len(keywordQueries) > 0 {
|
||||
output += fmt.Sprintf("Keyword Queries: %v\n", keywordQueries)
|
||||
output += fmt.Sprintf("Keyword Threshold: %.2f\n", keywordThreshold)
|
||||
}
|
||||
if len(queries) == 1 {
|
||||
output += fmt.Sprintf("Query: %s\n", queries[0])
|
||||
} else if len(queries) > 1 {
|
||||
output += fmt.Sprintf("Queries (%d): %v\n", len(queries), queries)
|
||||
}
|
||||
|
||||
output += fmt.Sprintf("Found %d relevant results (deduplicated)", len(results))
|
||||
output += fmt.Sprintf("Found %d relevant results", len(results))
|
||||
if totalBeforeFilter > len(results) {
|
||||
output += fmt.Sprintf(" (filtered from %d)", totalBeforeFilter)
|
||||
}
|
||||
@@ -1118,16 +945,9 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
output += fmt.Sprintf("[Source Document: %s]\n", result.KnowledgeTitle)
|
||||
}
|
||||
|
||||
relevanceLevel := GetRelevanceLevel(result.Score)
|
||||
// relevanceLevel := GetRelevanceLevel(result.Score)
|
||||
output += fmt.Sprintf("\nResult #%d:\n", i+1)
|
||||
output += fmt.Sprintf(" Relevance: %.2f (%s)\n", result.Score, relevanceLevel)
|
||||
output += fmt.Sprintf(" Match Type: %s", FormatMatchType(result.MatchType))
|
||||
if result.SourceQuery != "" && result.SourceQuery != singleQuery {
|
||||
output += fmt.Sprintf(" (Query: \"%s\")", result.SourceQuery)
|
||||
}
|
||||
output += "\n"
|
||||
output += fmt.Sprintf(" Content: %s\n", result.Content)
|
||||
output += fmt.Sprintf(" [chunk_id: %s - full content included above]\n", result.ID)
|
||||
output += fmt.Sprintf(" [chunk_id: %s][chunk_index: %d]\nContent: %s\n", result.ID, result.ChunkIndex, result.Content)
|
||||
|
||||
if faqMeta != nil {
|
||||
if faqMeta.StandardQuestion != "" {
|
||||
@@ -1139,17 +959,17 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
if len(faqMeta.Answers) > 0 {
|
||||
output += " FAQ Answers:\n"
|
||||
for _, ans := range faqMeta.Answers {
|
||||
output += fmt.Sprintf(" - %s\n", ans)
|
||||
output += fmt.Sprintf(" Answer Choice %d: %s\n", i+1, ans)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
formattedResults = append(formattedResults, map[string]interface{}{
|
||||
"result_index": i + 1,
|
||||
"chunk_id": result.ID,
|
||||
"content": result.Content,
|
||||
"score": result.Score,
|
||||
"relevance_level": relevanceLevel,
|
||||
"result_index": i + 1,
|
||||
"chunk_id": result.ID,
|
||||
"content": result.Content,
|
||||
// "score": result.Score,
|
||||
// "relevance_level": relevanceLevel,
|
||||
"knowledge_id": result.KnowledgeID,
|
||||
"knowledge_title": result.KnowledgeTitle,
|
||||
"match_type": result.MatchType,
|
||||
@@ -1182,14 +1002,13 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
// }
|
||||
// output += "- Full content is already included in search results above\n"
|
||||
// output += "- Results are deduplicated across knowledge bases and sorted by relevance\n"
|
||||
// output += "- Use get_related_chunks to expand context if needed\n"
|
||||
// output += "- Use list_knowledge_chunks to expand context if needed\n"
|
||||
|
||||
data := map[string]interface{}{
|
||||
"knowledge_base_ids": kbsToSearch,
|
||||
"results": formattedResults,
|
||||
"count": len(results),
|
||||
"kb_counts": kbCounts,
|
||||
"search_mode": searchMode,
|
||||
"display_type": "search_results",
|
||||
}
|
||||
if len(knowledgeIDsFilter) > 0 {
|
||||
@@ -1199,14 +1018,8 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
}
|
||||
data["knowledge_ids"] = filterList
|
||||
}
|
||||
if singleQuery != "" {
|
||||
data["query"] = singleQuery
|
||||
}
|
||||
if len(vectorQueries) > 0 {
|
||||
data["vector_queries"] = vectorQueries
|
||||
}
|
||||
if len(keywordQueries) > 0 {
|
||||
data["keyword_queries"] = keywordQueries
|
||||
if len(queries) > 0 {
|
||||
data["queries"] = queries
|
||||
}
|
||||
if totalBeforeFilter > len(results) {
|
||||
data["total_before_filter"] = totalBeforeFilter
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// ListKnowledgeChunksTool retrieves chunk snapshots for a specific knowledge document.
|
||||
type ListKnowledgeChunksTool struct {
|
||||
BaseTool
|
||||
tenantID uint
|
||||
chunkService interfaces.ChunkService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
}
|
||||
|
||||
// NewListKnowledgeChunksTool creates a new tool instance.
|
||||
func NewListKnowledgeChunksTool(
|
||||
tenantID uint,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
chunkService interfaces.ChunkService,
|
||||
) *ListKnowledgeChunksTool {
|
||||
description := `Retrieve paged chunks for a document (knowledge) by knowledge_id.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Need deterministic chunk previews for a known document
|
||||
- Want to quickly confirm how many chunks a document contains
|
||||
- Require surrounding context around a chunk_index returned by search results
|
||||
- Need content snippets without running an additional search query
|
||||
|
||||
Avoid when:
|
||||
- You don't know the knowledge_id (use knowledge_search first)
|
||||
|
||||
## Parameters
|
||||
|
||||
- knowledge_id (required): Target document/knowledge ID
|
||||
- limit (optional): Number of chunks to fetch (default 20, max 100).
|
||||
- offset (optional): Offset to start fetching chunks from (default 0).`
|
||||
|
||||
return &ListKnowledgeChunksTool{
|
||||
BaseTool: NewBaseTool("list_knowledge_chunks", description),
|
||||
tenantID: tenantID,
|
||||
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": "Knowledge/document ID to inspect",
|
||||
},
|
||||
"limit": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Number of chunks to fetch (default 20, max 100)",
|
||||
"default": 20,
|
||||
"minimum": 1,
|
||||
"maximum": 100,
|
||||
},
|
||||
"offset": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Offset to start fetching chunks from (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)
|
||||
if !ok || strings.TrimSpace(knowledgeID) == "" {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "knowledge_id is required",
|
||||
}, fmt.Errorf("knowledge_id is required")
|
||||
}
|
||||
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 rawOffset, exists := args["offset"]; exists {
|
||||
switch v := rawOffset.(type) {
|
||||
case float64:
|
||||
offset = int(v)
|
||||
case int:
|
||||
offset = v
|
||||
}
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
|
||||
pagination := &types.Pagination{
|
||||
Page: offset/chunkLimit + 1,
|
||||
PageSize: chunkLimit,
|
||||
}
|
||||
|
||||
chunks, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
|
||||
t.tenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText}, "")
|
||||
if err != nil {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("failed to list chunks: %v", err),
|
||||
}, err
|
||||
}
|
||||
if chunks == nil {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "chunk query returned no data",
|
||||
}, fmt.Errorf("chunk query returned no data")
|
||||
}
|
||||
|
||||
totalChunks := total
|
||||
fetched := len(chunks)
|
||||
|
||||
knowledgeTitle := t.lookupKnowledgeTitle(ctx, knowledgeID)
|
||||
|
||||
output := t.buildOutput(knowledgeID, knowledgeTitle, totalChunks, fetched, chunkLimit, chunks)
|
||||
|
||||
formattedChunks := make([]map[string]interface{}, 0, len(chunks))
|
||||
for idx, c := range chunks {
|
||||
formattedChunks = append(formattedChunks, map[string]interface{}{
|
||||
"seq": idx + 1,
|
||||
"chunk_id": c.ID,
|
||||
"chunk_index": c.ChunkIndex,
|
||||
"content": c.Content,
|
||||
"chunk_type": c.ChunkType,
|
||||
"knowledge_id": c.KnowledgeID,
|
||||
"knowledge_base": c.KnowledgeBaseID,
|
||||
"start_at": c.StartAt,
|
||||
"end_at": c.EndAt,
|
||||
"parent_chunk_id": c.ParentChunkID,
|
||||
})
|
||||
}
|
||||
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: output,
|
||||
Data: map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
"knowledge_title": knowledgeTitle,
|
||||
"total_chunks": totalChunks,
|
||||
"fetched_chunks": fetched,
|
||||
"page": pagination.Page,
|
||||
"page_size": pagination.PageSize,
|
||||
"chunks": formattedChunks,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *ListKnowledgeChunksTool) lookupKnowledgeTitle(ctx context.Context, knowledgeID string) string {
|
||||
if t.knowledgeService == nil {
|
||||
return ""
|
||||
}
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, knowledgeID)
|
||||
if err != nil || knowledge == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(knowledge.Title)
|
||||
}
|
||||
|
||||
func (t *ListKnowledgeChunksTool) buildOutput(
|
||||
knowledgeID string,
|
||||
knowledgeTitle string,
|
||||
total int64,
|
||||
fetched int,
|
||||
chunkLimit int,
|
||||
chunks []*types.Chunk,
|
||||
) string {
|
||||
builder := &strings.Builder{}
|
||||
builder.WriteString("=== 知识文档分块 ===\n\n")
|
||||
|
||||
if knowledgeTitle != "" {
|
||||
builder.WriteString(fmt.Sprintf("文档: %s (%s)\n", knowledgeTitle, knowledgeID))
|
||||
} else {
|
||||
builder.WriteString(fmt.Sprintf("文档 ID: %s\n", knowledgeID))
|
||||
}
|
||||
builder.WriteString(fmt.Sprintf("总分块数: %d\n", total))
|
||||
builder.WriteString(fmt.Sprintf("本次拉取: %d 条(offset=%d)\n\n", fetched, chunkLimit))
|
||||
|
||||
if fetched == 0 {
|
||||
builder.WriteString("未找到任何分块,请确认文档是否已完成解析。\n")
|
||||
if total > 0 {
|
||||
builder.WriteString("文档存在但当前页数据为空,请检查分页参数。\n")
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
builder.WriteString("=== 分块内容预览 ===\n\n")
|
||||
for idx, c := range chunks {
|
||||
builder.WriteString(fmt.Sprintf("Chunk #%d (Index %d)\n", idx+1, c.ChunkIndex+1))
|
||||
builder.WriteString(fmt.Sprintf(" chunk_id: %s\n", c.ID))
|
||||
builder.WriteString(fmt.Sprintf(" 类型: %s\n", c.ChunkType))
|
||||
builder.WriteString(fmt.Sprintf(" 内容: %s\n\n", summarizeContent(c.Content)))
|
||||
}
|
||||
|
||||
if int64(fetched) < total {
|
||||
builder.WriteString("提示:文档仍有更多分块,可调整 offset 或多次调用以获取全部内容。\n")
|
||||
}
|
||||
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func summarizeContent(content string) string {
|
||||
cleaned := strings.TrimSpace(content)
|
||||
if cleaned == "" {
|
||||
return "(空内容)"
|
||||
}
|
||||
|
||||
return strings.TrimSpace(string(cleaned))
|
||||
}
|
||||
@@ -56,7 +56,7 @@ func NewQueryKnowledgeGraphTool(knowledgeService interfaces.KnowledgeBaseService
|
||||
## 配合使用
|
||||
|
||||
1. **关系探索**: query_knowledge_graph → get_chunk_detail(查看详细内容)
|
||||
2. **网络分析**: query_knowledge_graph → get_related_chunks(扩展上下文)
|
||||
2. **网络分析**: query_knowledge_graph → list_knowledge_chunks(扩展上下文)
|
||||
3. **主题研究**: knowledge_search → query_knowledge_graph(深入实体关系)
|
||||
|
||||
## 当前状态
|
||||
@@ -360,7 +360,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args map[string]i
|
||||
output += "=== 💡 使用提示 ===\n"
|
||||
output += "- ✓ 结果已跨知识库去重并按相关度排序\n"
|
||||
output += "- ✓ 使用 get_chunk_detail 获取完整内容\n"
|
||||
output += "- ✓ 使用 get_related_chunks 探索上下文\n"
|
||||
output += "- ✓ 使用 list_knowledge_chunks 探索上下文\n"
|
||||
if !hasGraphConfig {
|
||||
output += "- ⚠️ 配置图谱抽取以获得更精准的实体关系结果\n"
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
@@ -11,26 +12,23 @@ import (
|
||||
|
||||
// ToolRegistry manages the registration and retrieval of tools
|
||||
type ToolRegistry struct {
|
||||
tools map[string]types.Tool
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
db *gorm.DB // gorm.DB interface for database query tool
|
||||
tools map[string]types.Tool
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewToolRegistry creates a new tool registry
|
||||
func NewToolRegistry(
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
chunkService interfaces.ChunkService,
|
||||
db *gorm.DB, // gorm.DB for database operations
|
||||
) *ToolRegistry {
|
||||
return &ToolRegistry{
|
||||
tools: make(map[string]types.Tool),
|
||||
knowledgeBaseService: knowledgeBaseService,
|
||||
knowledgeService: knowledgeService,
|
||||
chunkService: chunkService,
|
||||
db: db,
|
||||
tools: make(map[string]types.Tool),
|
||||
knowledgeService: knowledgeService,
|
||||
chunkService: chunkService,
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,13 +70,41 @@ func (r *ToolRegistry) GetFunctionDefinitions() []types.FunctionDefinition {
|
||||
|
||||
// ExecuteTool executes a tool by name with the given arguments
|
||||
func (r *ToolRegistry) ExecuteTool(ctx context.Context, name string, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
common.PipelineInfo(ctx, "AgentTool", "execute_start", map[string]interface{}{
|
||||
"tool": name,
|
||||
"args": args,
|
||||
})
|
||||
tool, err := r.GetTool(name)
|
||||
if err != nil {
|
||||
common.PipelineError(ctx, "AgentTool", "execute_failed", map[string]interface{}{
|
||||
"tool": name,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
}, err
|
||||
}
|
||||
|
||||
return tool.Execute(ctx, args)
|
||||
result, execErr := tool.Execute(ctx, args)
|
||||
fields := map[string]interface{}{
|
||||
"tool": name,
|
||||
"args": args,
|
||||
}
|
||||
if result != nil {
|
||||
fields["success"] = result.Success
|
||||
if result.Error != "" {
|
||||
fields["error"] = result.Error
|
||||
}
|
||||
}
|
||||
if execErr != nil {
|
||||
fields["error"] = execErr.Error()
|
||||
common.PipelineError(ctx, "AgentTool", "execute_done", fields)
|
||||
} else if result != nil && !result.Success {
|
||||
common.PipelineWarn(ctx, "AgentTool", "execute_done", fields)
|
||||
} else {
|
||||
common.PipelineInfo(ctx, "AgentTool", "execute_done", fields)
|
||||
}
|
||||
|
||||
return result, execErr
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ func (t *SequentialThinkingTool) Parameters() map[string]interface{} {
|
||||
"totalThoughts": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Estimated total thoughts needed (numeric value, e.g., 5, 10)",
|
||||
"minimum": 1,
|
||||
"minimum": 5,
|
||||
},
|
||||
"isRevision": map[string]interface{}{
|
||||
"type": "boolean",
|
||||
@@ -188,6 +188,8 @@ func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]in
|
||||
branchKeys = append(branchKeys, k)
|
||||
}
|
||||
|
||||
incomplete := thoughtData.NextThoughtNeeded || thoughtData.NeedsMoreThoughts || thoughtData.ThoughtNumber < thoughtData.TotalThoughts
|
||||
|
||||
responseData := map[string]interface{}{
|
||||
"thought_number": thoughtData.ThoughtNumber,
|
||||
"total_thoughts": thoughtData.TotalThoughts,
|
||||
@@ -196,13 +198,19 @@ func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]in
|
||||
"thought_history_length": len(t.thoughtHistory),
|
||||
"display_type": "thinking",
|
||||
"thought": thoughtData.Thought,
|
||||
"incomplete_steps": incomplete,
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][SequentialThinking] Execute completed - Thought %d/%d", thoughtData.ThoughtNumber, thoughtData.TotalThoughts)
|
||||
|
||||
outputMsg := "Thought process recorded"
|
||||
if incomplete {
|
||||
outputMsg = "Thought process recorded - unfinished steps remain, continue exploring and calling tools"
|
||||
}
|
||||
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: "Thought process recorded",
|
||||
Output: outputMsg,
|
||||
Data: responseData,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ func (t *TodoWriteTool) Parameters() map[string]interface{} {
|
||||
},
|
||||
"tools_to_use": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "Suggested tools for this step (e.g., ['knowledge_search', 'get_related_chunks'])",
|
||||
"description": "Suggested tools for this step (e.g., ['knowledge_search', 'list_knowledge_chunks'])",
|
||||
"items": map[string]interface{}{
|
||||
"type": "string",
|
||||
},
|
||||
@@ -268,8 +268,8 @@ func generatePlanOutput(task string, steps []PlanStep) string {
|
||||
output += "注意:未提供具体步骤。建议创建3-7个结构化步骤以系统化研究。\n\n"
|
||||
output += "建议的通用流程:\n"
|
||||
output += "1. 使用 knowledge_search 进行初步信息收集\n"
|
||||
output += "2. 使用 get_related_chunks 获取关键信息详情\n"
|
||||
output += "3. 使用 get_related_chunks 扩展上下文理解\n"
|
||||
output += "2. 使用 list_knowledge_chunks 获取关键信息详情\n"
|
||||
output += "3. 使用 list_knowledge_chunks 扩展上下文理解\n"
|
||||
output += "4. 使用 think 工具评估结果并综合答案\n"
|
||||
return output
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user