2025-11-05 15:18:44 +00:00
package tools
import (
"context"
2025-12-23 08:56:30 +00:00
"encoding/json"
2025-11-05 15:18:44 +00:00
"fmt"
"sync"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
2025-12-23 08:56:30 +00:00
"github.com/Tencent/WeKnora/internal/utils"
2025-11-05 15:18:44 +00:00
)
2025-12-23 08:56:30 +00:00
var getDocumentInfoTool = BaseTool {
name : ToolGetDocumentInfo ,
description : ` Retrieve detailed metadata information about documents .
2025-11-05 15:18:44 +00:00
# # When to Use
Use this tool when :
- Need to understand document basic information ( title , type , size , etc . )
- Check if document exists and is available
- Batch query metadata for multiple documents
- Understand document processing status
Do not use when :
- Need document content ( use knowledge_search )
- Need specific text chunks ( search results already contain full content )
# # Returned Information
- Basic info : title , description , source type
- File info : filename , type , size
- Processing status : whether processed , chunk count
- Metadata : custom tags and properties
# # Notes
- Concurrent query for multiple documents provides better performance
- Returns complete document metadata , not just title
2025-12-23 08:56:30 +00:00
- 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
2026-01-30 08:28:01 +00:00
searchTargets types . SearchTargets // Pre-computed unified search targets with KB-tenant mapping
2025-12-23 08:56:30 +00:00
}
2025-11-05 15:18:44 +00:00
2025-12-23 08:56:30 +00:00
// NewGetDocumentInfoTool creates a new get document info tool
func NewGetDocumentInfoTool (
knowledgeService interfaces . KnowledgeService ,
chunkService interfaces . ChunkService ,
2026-01-30 08:28:01 +00:00
searchTargets types . SearchTargets ,
2025-12-23 08:56:30 +00:00
) * GetDocumentInfoTool {
2025-11-05 15:18:44 +00:00
return & GetDocumentInfoTool {
2025-12-23 08:56:30 +00:00
BaseTool : getDocumentInfoTool ,
2025-11-05 15:18:44 +00:00
knowledgeService : knowledgeService ,
chunkService : chunkService ,
2026-01-30 08:28:01 +00:00
searchTargets : searchTargets ,
2025-11-05 15:18:44 +00:00
}
}
2025-12-23 08:56:30 +00:00
// Execute retrieves document information with concurrent processing
func ( t * GetDocumentInfoTool ) Execute ( ctx context . Context , args json . RawMessage ) ( * types . ToolResult , error ) {
// 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
2025-11-05 15:18:44 +00:00
}
// Extract knowledge_ids array
2025-12-23 08:56:30 +00:00
knowledgeIDs := input . KnowledgeIDs
if len ( knowledgeIDs ) == 0 {
2025-11-05 15:18:44 +00:00
return & types . ToolResult {
Success : false ,
Error : "knowledge_ids is required and must be a non-empty array" ,
} , fmt . Errorf ( "knowledge_ids is required" )
}
// Concurrently get info for each knowledge ID
type docInfo struct {
knowledge * types . Knowledge
chunkCount int
err error
}
var wg sync . WaitGroup
var mu sync . Mutex
results := make ( map [ string ] * docInfo )
2025-12-01 09:24:57 +00:00
// Concurrently get info for each knowledge ID
2025-11-05 15:18:44 +00:00
for _ , knowledgeID := range knowledgeIDs {
wg . Add ( 1 )
go func ( id string ) {
defer wg . Done ( )
2026-01-30 08:28:01 +00:00
// Get knowledge metadata without tenant filter to support shared KB
knowledge , err := t . knowledgeService . GetKnowledgeByIDOnly ( ctx , id )
2025-11-05 15:18:44 +00:00
if err != nil {
mu . Lock ( )
results [ id ] = & docInfo {
2026-03-06 11:24:23 +00:00
err : fmt . Errorf ( "failed to get document info: %v" , err ) ,
2025-11-05 15:18:44 +00:00
}
mu . Unlock ( )
return
}
2026-01-30 08:28:01 +00:00
// Verify the knowledge's KB is in searchTargets (permission check)
if ! t . searchTargets . ContainsKB ( knowledge . KnowledgeBaseID ) {
mu . Lock ( )
results [ id ] = & docInfo {
2026-03-06 11:24:23 +00:00
err : fmt . Errorf ( "knowledge base %s is not accessible" , knowledge . KnowledgeBaseID ) ,
2026-01-30 08:28:01 +00:00
}
mu . Unlock ( )
return
}
// Use knowledge's actual tenant_id for chunk query (supports cross-tenant shared KB)
2025-11-28 08:17:52 +00:00
_ , total , err := t . chunkService . GetRepository ( ) .
2026-01-30 08:28:01 +00:00
ListPagedChunksByKnowledgeID ( ctx , knowledge . TenantID , id , & types . Pagination {
2025-11-28 08:17:52 +00:00
Page : 1 ,
2026-03-18 15:49:46 +00:00
PageSize : 1 ,
2025-12-26 04:30:06 +00:00
} , [ ] types . ChunkType { "text" } , "" , "" , "" , "" , "" )
2025-11-20 12:08:24 +00:00
if err != nil {
mu . Lock ( )
results [ id ] = & docInfo {
2026-03-06 11:24:23 +00:00
err : fmt . Errorf ( "failed to get document info: %v" , err ) ,
2025-11-20 12:08:24 +00:00
}
mu . Unlock ( )
return
2025-11-05 15:18:44 +00:00
}
2025-11-20 12:08:24 +00:00
chunkCount := int ( total )
2025-11-05 15:18:44 +00:00
mu . Lock ( )
results [ id ] = & docInfo {
knowledge : knowledge ,
chunkCount : chunkCount ,
}
mu . Unlock ( )
} ( knowledgeID )
}
wg . Wait ( )
// Collect successful results and errors
successDocs := make ( [ ] * docInfo , 0 )
var errors [ ] string
for _ , knowledgeID := range knowledgeIDs {
result := results [ knowledgeID ]
if result . err != nil {
errors = append ( errors , fmt . Sprintf ( "%s: %v" , knowledgeID , result . err ) )
} else if result . knowledge != nil {
successDocs = append ( successDocs , result )
}
}
if len ( successDocs ) == 0 {
return & types . ToolResult {
Success : false ,
2026-03-06 11:24:23 +00:00
Error : fmt . Sprintf ( "Failed to retrieve any document info. Errors: %v" , errors ) ,
2025-11-05 15:18:44 +00:00
} , fmt . Errorf ( "all document retrievals failed" )
}
// Format output
2026-03-06 11:24:23 +00:00
output := "=== Document Info ===\n\n"
output += fmt . Sprintf ( "Successfully retrieved %d / %d documents\n\n" , len ( successDocs ) , len ( knowledgeIDs ) )
2025-11-05 15:18:44 +00:00
if len ( errors ) > 0 {
2026-03-06 11:24:23 +00:00
output += "=== Partial Failures ===\n"
2025-11-05 15:18:44 +00:00
for _ , errMsg := range errors {
output += fmt . Sprintf ( " - %s\n" , errMsg )
}
output += "\n"
}
formattedDocs := make ( [ ] map [ string ] interface { } , 0 , len ( successDocs ) )
for i , doc := range successDocs {
k := doc . knowledge
2026-03-06 11:24:23 +00:00
output += fmt . Sprintf ( "[Document #%d]\n" , i + 1 )
output += fmt . Sprintf ( " ID: %s\n" , k . ID )
output += fmt . Sprintf ( " Title: %s\n" , k . Title )
2025-11-05 15:18:44 +00:00
if k . Description != "" {
2026-03-06 11:24:23 +00:00
output += fmt . Sprintf ( " Description: %s\n" , k . Description )
2025-11-05 15:18:44 +00:00
}
2026-03-06 11:24:23 +00:00
output += fmt . Sprintf ( " Source: %s\n" , formatSource ( k . Type , k . Source ) )
2025-11-05 15:18:44 +00:00
if k . FileName != "" {
2026-03-06 11:24:23 +00:00
output += fmt . Sprintf ( " File Name: %s\n" , k . FileName )
output += fmt . Sprintf ( " File Type: %s\n" , k . FileType )
output += fmt . Sprintf ( " File Size: %s\n" , formatFileSize ( k . FileSize ) )
2025-11-05 15:18:44 +00:00
}
2026-03-06 11:24:23 +00:00
output += fmt . Sprintf ( " Parse Status: %s\n" , formatParseStatus ( k . ParseStatus ) )
output += fmt . Sprintf ( " Chunk Count: %d\n" , doc . chunkCount )
2025-11-05 15:18:44 +00:00
if k . Metadata != nil {
if metadata , err := k . Metadata . Map ( ) ; err == nil && len ( metadata ) > 0 {
2026-03-06 11:24:23 +00:00
output += " Metadata:\n"
2025-11-05 15:18:44 +00:00
for key , value := range metadata {
output += fmt . Sprintf ( " - %s: %v\n" , key , value )
}
}
}
output += "\n"
formattedDocs = append ( formattedDocs , map [ string ] interface { } {
2025-11-20 12:08:24 +00:00
"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 ( ) ,
2025-11-05 15:18:44 +00:00
} )
}
// Extract first document title for summary
var firstTitle string
if len ( successDocs ) > 0 && successDocs [ 0 ] . knowledge != nil {
firstTitle = successDocs [ 0 ] . knowledge . Title
}
return & types . ToolResult {
Success : true ,
Output : output ,
Data : map [ string ] interface { } {
"documents" : formattedDocs ,
"total_docs" : len ( successDocs ) ,
"requested" : len ( knowledgeIDs ) ,
"errors" : errors ,
"display_type" : "document_info" ,
"title" : firstTitle , // For frontend summary display
} ,
} , nil
}
func formatSource ( knowledgeType , source string ) string {
switch knowledgeType {
case "file" :
2026-03-06 11:24:23 +00:00
return "File Upload"
2025-11-05 15:18:44 +00:00
case "url" :
return fmt . Sprintf ( "URL: %s" , source )
case "passage" :
2026-03-06 11:24:23 +00:00
return "Text Input"
2025-11-05 15:18:44 +00:00
default :
return knowledgeType
}
}
func formatFileSize ( size int64 ) string {
if size == 0 {
2026-03-06 11:24:23 +00:00
return "Unknown"
2025-11-05 15:18:44 +00:00
}
const unit = 1024
if size < unit {
return fmt . Sprintf ( "%d B" , size )
}
div , exp := int64 ( unit ) , 0
for n := size / unit ; n >= unit ; n /= unit {
div *= unit
exp ++
}
return fmt . Sprintf ( "%.1f %cB" , float64 ( size ) / float64 ( div ) , "KMGTPE" [ exp ] )
}
func formatParseStatus ( status string ) string {
switch status {
case "pending" :
2026-03-06 11:24:23 +00:00
return "Pending"
2025-11-05 15:18:44 +00:00
case "processing" :
2026-03-06 11:24:23 +00:00
return "Processing"
2025-11-05 15:18:44 +00:00
case "completed" , "success" :
2026-03-06 11:24:23 +00:00
return "Completed"
2025-11-05 15:18:44 +00:00
case "failed" :
2026-03-06 11:24:23 +00:00
return "Failed"
2025-11-05 15:18:44 +00:00
default :
return status
}
}