Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(agent): correct graph config reporting

cb2ff29cc0f4a
diff --git a/internal/agent/tools/query_knowledge_graph.go b/internal/agent/tools/query_knowledge_graph.go
index 59386669e..9760ab8d0 100644
--- a/internal/agent/tools/query_knowledge_graph.go
+++ b/internal/agent/tools/query_knowledge_graph.go
@@ -12,6 +12,11 @@ import (
"github.com/Tencent/WeKnora/internal/utils"
)
+type graphConfigSummary struct {
+ Nodes []string
+ Relations []string
+}
+
var queryKnowledgeGraphTool = BaseTool{
name: ToolQueryKnowledgeGraph,
description: `Query knowledge graph to explore entity relationships and knowledge networks.
@@ -168,7 +173,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
// Collect and deduplicate results
seenChunks := make(map[string]*types.SearchResult)
var errors []string
- graphConfigs := make(map[string]map[string]interface{})
+ graphConfigs := make(map[string]graphConfigSummary)
kbCounts := make(map[string]int)
for _, kbID := range input.KnowledgeBaseIDs {
@@ -179,10 +184,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
}
if result.kb != nil && result.kb.ExtractConfig != nil {
- graphConfigs[kbID] = map[string]interface{}{
- "nodes": result.kb.ExtractConfig.Nodes,
- "relations": result.kb.ExtractConfig.Relations,
- }
+ graphConfigs[kbID] = summarizeGraphConfig(result.kb.ExtractConfig)
}
kbCounts[kbID] = len(result.results)
@@ -211,7 +213,8 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
"knowledge_base_ids": input.KnowledgeBaseIDs,
"query": query,
"results": []interface{}{},
- "graph_configs": graphConfigs,
+ "graph_configs": graphConfigsToData(graphConfigs),
+ "graph_config": aggregateGraphConfig(graphConfigs),
"errors": errors,
},
}, nil
@@ -238,35 +241,14 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
hasGraphConfig = true
output += fmt.Sprintf("Knowledge Base [%s]:\n", kbID)
- nodes, _ := config["nodes"].([]interface{})
- relations, _ := config["relations"].([]interface{})
-
- if len(nodes) > 0 {
- output += fmt.Sprintf(" ✓ Entity Types (%d): ", len(nodes))
- nodeNames := make([]string, 0, len(nodes))
- for _, n := range nodes {
- if nodeMap, ok := n.(map[string]interface{}); ok {
- if name, ok := nodeMap["name"].(string); ok {
- nodeNames = append(nodeNames, name)
- }
- }
- }
- output += fmt.Sprintf("%v\n", nodeNames)
+ if len(config.Nodes) > 0 {
+ output += fmt.Sprintf(" ✓ Entity Types (%d): %v\n", len(config.Nodes), config.Nodes)
} else {
output += " ⚠️ No entity types configured\n"
}
- if len(relations) > 0 {
- output += fmt.Sprintf(" ✓ Relationship Types (%d): ", len(relations))
- relNames := make([]string, 0, len(relations))
- for _, r := range relations {
- if relMap, ok := r.(map[string]interface{}); ok {
- if name, ok := relMap["name"].(string); ok {
- relNames = append(relNames, name)
- }
- }
- }
- output += fmt.Sprintf("%v\n", relNames)
+ if len(config.Relations) > 0 {
+ output += fmt.Sprintf(" ✓ Relationship Types (%d): %v\n", len(config.Relations), config.Relations)
} else {
output += " ⚠️ No relationship types configured\n"
}
@@ -338,7 +320,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
output += "- ⏳ Full graph query language (Cypher) support is under development\n"
// Build structured graph data for frontend visualization
- graphData := buildGraphVisualizationData(allResults, graphConfigs)
+ graphData := buildGraphVisualizationData(allResults)
return &types.ToolResult{
Success: true,
@@ -349,7 +331,8 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
"results": formattedResults,
"count": len(allResults),
"kb_counts": kbCounts,
- "graph_configs": graphConfigs,
+ "graph_configs": graphConfigsToData(graphConfigs),
+ "graph_config": aggregateGraphConfig(graphConfigs),
"graph_data": graphData,
"has_graph_config": hasGraphConfig,
"errors": errors,
@@ -358,11 +341,102 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
}, nil
}
+func summarizeGraphConfig(config *types.ExtractConfig) graphConfigSummary {
+ if config == nil {
+ return graphConfigSummary{}
+ }
+
+ return graphConfigSummary{
+ Nodes: uniqueSortedNodeNames(config.Nodes),
+ Relations: uniqueSortedRelationNames(config.Relations),
+ }
+}
+
+func uniqueSortedNodeNames(nodes []*types.GraphNode) []string {
+ seen := make(map[string]struct{}, len(nodes))
+ names := make([]string, 0, len(nodes))
+ for _, node := range nodes {
+ if node == nil || node.Name == "" {
+ continue
+ }
+ if _, exists := seen[node.Name]; exists {
+ continue
+ }
+ seen[node.Name] = struct{}{}
+ names = append(names, node.Name)
+ }
+ sort.Strings(names)
+ return names
+}
+
+func uniqueSortedRelationNames(relations []*types.GraphRelation) []string {
+ seen := make(map[string]struct{}, len(relations))
+ names := make([]string, 0, len(relations))
+ for _, relation := range relations {
+ if relation == nil || relation.Type == "" {
+ continue
+ }
+ if _, exists := seen[relation.Type]; exists {
+ continue
+ }
+ seen[relation.Type] = struct{}{}
+ names = append(names, relation.Type)
+ }
+ sort.Strings(names)
+ return names
+}
+
+func graphConfigsToData(graphConfigs map[string]graphConfigSummary) map[string]map[string]interface{} {
+ if len(graphConfigs) == 0 {
+ return nil
+ }
+
+ data := make(map[string]map[string]interface{}, len(graphConfigs))
+ for kbID, config := range graphConfigs {
+ data[kbID] = map[string]interface{}{
+ "nodes": config.Nodes,
+ "relations": config.Relations,
+ }
+ }
+ return data
+}
+
+func aggregateGraphConfig(graphConfigs map[string]graphConfigSummary) map[string]interface{} {
+ if len(graphConfigs) == 0 {
+ return nil
+ }
+
+ merged := graphConfigSummary{}
+ for _, config := range graphConfigs {
+ merged.Nodes = append(merged.Nodes, config.Nodes...)
+ merged.Relations = append(merged.Relations, config.Relations...)
+ }
+
+ return map[string]interface{}{
+ "nodes": uniqueStrings(merged.Nodes),
+ "relations": uniqueStrings(merged.Relations),
+ }
+}
+
+func uniqueStrings(values []string) []string {
+ seen := make(map[string]struct{}, len(values))
+ result := make([]string, 0, len(values))
+ for _, value := range values {
+ if value == "" {
+ continue
+ }
+ if _, exists := seen[value]; exists {
+ continue
+ }
+ seen[value] = struct{}{}
+ result = append(result, value)
+ }
+ sort.Strings(result)
+ return result
+}
+
// buildGraphVisualizationData builds structured data for graph visualization
-func buildGraphVisualizationData(
- results []*types.SearchResult,
- graphConfigs map[string]map[string]interface{},
-) map[string]interface{} {
+func buildGraphVisualizationData(results []*types.SearchResult) map[string]interface{} {
// Build a simple graph structure for frontend visualization
nodes := make([]map[string]interface{}, 0)
edges := make([]map[string]interface{}, 0)
diff --git a/internal/agent/tools/query_knowledge_graph_test.go b/internal/agent/tools/query_knowledge_graph_test.go
new file mode 100644
index 000000000..fa8239d18
--- /dev/null
+++ b/internal/agent/tools/query_knowledge_graph_test.go
@@ -0,0 +1,144 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/hibiken/asynq"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type stubKnowledgeBaseService struct {
+ kb *types.KnowledgeBase
+ results []*types.SearchResult
+}
+
+func (s *stubKnowledgeBaseService) CreateKnowledgeBase(context.Context, *types.KnowledgeBase) (*types.KnowledgeBase, error) {
+ return nil, nil
+}
+
+func (s *stubKnowledgeBaseService) GetKnowledgeBaseByID(context.Context, string) (*types.KnowledgeBase, error) {
+ return s.kb, nil
+}
+
+func (s *stubKnowledgeBaseService) GetKnowledgeBaseByIDOnly(context.Context, string) (*types.KnowledgeBase, error) {
+ return s.kb, nil
+}
+
+func (s *stubKnowledgeBaseService) GetKnowledgeBasesByIDsOnly(context.Context, []string) ([]*types.KnowledgeBase, error) {
+ return nil, nil
+}
+
+func (s *stubKnowledgeBaseService) FillKnowledgeBaseCounts(context.Context, *types.KnowledgeBase) error {
+ return nil
+}
+
+func (s *stubKnowledgeBaseService) ListKnowledgeBases(context.Context) ([]*types.KnowledgeBase, error) {
+ return nil, nil
+}
+
+func (s *stubKnowledgeBaseService) ListKnowledgeBasesByTenantID(context.Context, uint64) ([]*types.KnowledgeBase, error) {
+ return nil, nil
+}
+
+func (s *stubKnowledgeBaseService) UpdateKnowledgeBase(
+ context.Context,
+ string,
+ string,
+ string,
+ *types.KnowledgeBaseConfig,
+) (*types.KnowledgeBase, error) {
+ return nil, nil
+}
+
+func (s *stubKnowledgeBaseService) DeleteKnowledgeBase(context.Context, string) error {
+ return nil
+}
+
+func (s *stubKnowledgeBaseService) TogglePinKnowledgeBase(context.Context, string) (*types.KnowledgeBase, error) {
+ return nil, nil
+}
+
+func (s *stubKnowledgeBaseService) HybridSearch(context.Context, string, types.SearchParams) ([]*types.SearchResult, error) {
+ return s.results, nil
+}
+
+func (s *stubKnowledgeBaseService) GetQueryEmbedding(context.Context, string, string) ([]float32, error) {
+ return nil, nil
+}
+
+func (s *stubKnowledgeBaseService) ResolveEmbeddingModelKeys(context.Context, []*types.KnowledgeBase) map[string]string {
+ return nil
+}
+
+func (s *stubKnowledgeBaseService) CopyKnowledgeBase(
+ context.Context,
+ string,
+ string,
+) (*types.KnowledgeBase, *types.KnowledgeBase, error) {
+ return nil, nil, nil
+}
+
+func (s *stubKnowledgeBaseService) GetRepository() interfaces.KnowledgeBaseRepository {
+ return nil
+}
+
+func (s *stubKnowledgeBaseService) ProcessKBDelete(context.Context, *asynq.Task) error {
+ return nil
+}
+
+func TestQueryKnowledgeGraph_ReportsConfiguredEntityAndRelationTypes(t *testing.T) {
+ tool := NewQueryKnowledgeGraphTool(&stubKnowledgeBaseService{
+ kb: &types.KnowledgeBase{
+ ID: "kb-1",
+ ExtractConfig: &types.ExtractConfig{
+ Enabled: true,
+ Nodes: []*types.GraphNode{
+ {Name: "合同"},
+ {Name: "部门"},
+ },
+ Relations: []*types.GraphRelation{
+ {Type: "属于"},
+ {Type: "管理"},
+ },
+ },
+ },
+ results: []*types.SearchResult{
+ {
+ ID: "chunk-1",
+ Content: "合同管理流程由法务部门负责。",
+ KnowledgeID: "doc-1",
+ KnowledgeTitle: "合同管理制度",
+ Score: 0.91,
+ },
+ },
+ })
+
+ args, err := json.Marshal(QueryKnowledgeGraphInput{
+ KnowledgeBaseIDs: []string{"kb-1"},
+ Query: "合同管理",
+ })
+ require.NoError(t, err)
+
+ result, err := tool.Execute(context.Background(), args)
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.True(t, result.Success)
+ t.Logf("tool output:\n%s", result.Output)
+
+ assert.Contains(t, result.Output, "Entity Types (2)")
+ assert.Contains(t, result.Output, "Relationship Types (2)")
+ assert.NotContains(t, result.Output, "No entity types configured")
+ assert.NotContains(t, result.Output, "No relationship types configured")
+ assert.Contains(t, result.Output, "合同")
+ assert.Contains(t, result.Output, "管理")
+
+ graphConfig, ok := result.Data["graph_config"].(map[string]interface{})
+ require.True(t, ok)
+ assert.ElementsMatch(t, []string{"合同", "部门"}, graphConfig["nodes"])
+ assert.ElementsMatch(t, []string{"属于", "管理"}, graphConfig["relations"])
+}