WeKnora/internal/agent/tools/query_knowledge_graph_trunc...

133 lines
6.1 KiB
Go
Raw Normal View History

fix(agent): 图谱查询的三处截断必须可见,模型不再把子图当全集 (#3885) query_knowledge_graph 有三处静默上限:返回关系 30 条、每个知识库抓取的 证据 chunk 10 条、送进图谱存储的实体词 8 个。命中上限后既不计数也不提示, 输出还按截断后的长度报告 "Found N relations",读起来就是"该实体的关系就 这么多"。模型据此把被砍过的子图当作实体的完整邻域作答,漏答或得出与图谱 事实不符的结论,且没有任何信号提示它应当收窄实体。同一仓库的图谱存储层 (neo4j/repository.go 的 graphSearchMaxRows 告警)已经把"截断必须可见" 写成明确要求,工具层没有遵守。 改动: - 关系去重后继续计数,Data 增加 relations_total / relations_omitted; - 证据 chunk 边取边计数,Data 增加 graph_chunks_total / graph_chunks_omitted (未接 chunk 仓库、抓取失败都不计入,避免把错误报成截断); - 被上限丢弃的查询词计数进入 Data(query_terms_total / query_terms_omitted); - 命中上限时 Output 追加 "=== ⚠️ Truncated ===" 段并给出收窄建议,主行改为 "Found 30 of 42 relations";未命中上限不输出任何内容,沉默只表示没有丢弃; - modelcontext 的 <retrieval> 视图补 <graph_truncated .../>:模型在有 chunk 行时读的是重建视图,标记只写 Output 到不了模型。 上限数值、去重语义与检索行为不变,只让截断可见。 Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 15:59:50 +00:00
package tools
import (
"context"
"encoding/json"
"fmt"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// graphToolOverEveryCap builds a tool whose graph answer overflows both caps:
// graphQueryMaxRelations+12 distinct relations on one hub entity, and
// graphQueryMaxChunks+4 chunks referenced by it.
func graphToolOverEveryCap() *QueryKnowledgeGraphTool {
relations := make([]*types.GraphRelation, 0, graphQueryMaxRelations+13)
for i := 0; i < graphQueryMaxRelations+12; i++ {
relations = append(relations, &types.GraphRelation{
Node1: "Docker", Node2: fmt.Sprintf("Service%02d", i), Type: "depends_on",
})
}
// A repeat of a relation already in the list must not inflate the total.
relations = append(relations, &types.GraphRelation{Node1: "Docker", Node2: "Service00", Type: "depends_on"})
chunks := make(map[string]*types.Chunk, graphQueryMaxChunks+4)
chunkIDs := make([]string, 0, graphQueryMaxChunks+4)
for i := 0; i < graphQueryMaxChunks+4; i++ {
id := fmt.Sprintf("c-%02d", i)
chunkIDs = append(chunkIDs, id)
chunks[id] = &types.Chunk{
ID: id, KnowledgeBaseID: "kb-1", KnowledgeID: "doc", Content: "Docker evidence", IsEnabled: true,
}
}
graphRepo := &stubGraphRepo{graph: &types.GraphData{
Node: []*types.GraphNode{{Name: "Docker", Chunks: chunkIDs}},
Relation: relations,
}}
return NewQueryKnowledgeGraphTool(&stubKnowledgeBaseService{
kb: &types.KnowledgeBase{ID: "kb-1", ExtractConfig: &types.ExtractConfig{
Enabled: true, Nodes: []*types.GraphNode{{Name: "技术"}},
}},
}).WithGraph(graphRepo, &stubGraphChunkRepo{chunks: chunks})
}
// A hub entity has far more relations than the tool returns. The cut has to be
// stated, in the tool output and in Data: read without a marker, the returned
// subgraph is the entity's whole neighbourhood to the model, which then answers
// "X is not related to Y" from a list that never held Y.
func TestQueryKnowledgeGraph_MarksCappedRelationsAndChunks(t *testing.T) {
tool := graphToolOverEveryCap()
args, err := json.Marshal(QueryKnowledgeGraphInput{KnowledgeBaseIDs: []string{"kb-1"}, Query: "Docker"})
require.NoError(t, err)
result, err := tool.Execute(context.Background(), args)
require.NoError(t, err)
t.Logf("tool output:\n%s", result.Output)
assert.Contains(t, result.Output, fmt.Sprintf("✓ Found %d of %d relations", graphQueryMaxRelations,
graphQueryMaxRelations+12), "the headline count must not read as the total")
assert.Contains(t, result.Output, "=== ⚠️ Truncated ===")
assert.Contains(t, result.Output, fmt.Sprintf("Relations: %d of %d shown", graphQueryMaxRelations,
graphQueryMaxRelations+12))
assert.Contains(t, result.Output, fmt.Sprintf("Graph evidence chunks: %d of %d fetched", graphQueryMaxChunks,
graphQueryMaxChunks+4))
relations, ok := result.Data["relations"].([]map[string]interface{})
require.True(t, ok)
assert.Len(t, relations, graphQueryMaxRelations)
assert.Equal(t, graphQueryMaxRelations+12, result.Data["relations_total"])
assert.Equal(t, 12, result.Data["relations_omitted"])
assert.Equal(t, graphQueryMaxChunks+4, result.Data["graph_chunks_total"])
assert.Equal(t, 4, result.Data["graph_chunks_omitted"])
}
// A long query names more entity candidates than the tool looks up. The words
// that were left out have to be stated: an entity named by one of them is never
// matched, and "no relevant graph information" would otherwise read as "this
// entity has no relations".
func TestQueryKnowledgeGraph_MarksCappedQueryTerms(t *testing.T) {
graphRepo := &stubGraphRepo{graph: &types.GraphData{}}
tool := NewQueryKnowledgeGraphTool(&stubKnowledgeBaseService{
kb: &types.KnowledgeBase{ID: "kb-1", ExtractConfig: &types.ExtractConfig{
Enabled: true, Nodes: []*types.GraphNode{{Name: "技术"}},
}},
}).WithGraph(graphRepo, &stubGraphChunkRepo{chunks: map[string]*types.Chunk{}})
query := "docker kubernetes scheduler container image registry cluster pod node volume secret ingress"
args, err := json.Marshal(QueryKnowledgeGraphInput{KnowledgeBaseIDs: []string{"kb-1"}, Query: query})
require.NoError(t, err)
result, err := tool.Execute(context.Background(), args)
require.NoError(t, err)
t.Logf("tool output:\n%s", result.Output)
// The 12 words plus the query itself are candidates; the cap keeps 8.
assert.Equal(t, 13, result.Data["query_terms_total"])
assert.Equal(t, 5, result.Data["query_terms_omitted"])
assert.Contains(t, result.Output, "No relevant graph information found.")
assert.Contains(t, result.Output, "Entity terms: 8 of 13 query words")
}
// Silence has to mean "nothing was dropped": a result under every cap carries
// no truncation marker and no total, so a marker always means a subset.
func TestQueryKnowledgeGraph_NoTruncationMarkerWhenNothingDropped(t *testing.T) {
graphRepo := &stubGraphRepo{graph: &types.GraphData{
Node: []*types.GraphNode{{Name: "Docker", Chunks: []string{"c-1"}}},
Relation: []*types.GraphRelation{{Node1: "Kubernetes", Node2: "Docker", Type: "orchestrates"}},
}}
chunkRepo := &stubGraphChunkRepo{chunks: map[string]*types.Chunk{
"c-1": {ID: "c-1", KnowledgeBaseID: "kb-1", KnowledgeID: "doc", Content: "Docker", IsEnabled: true},
}}
tool := NewQueryKnowledgeGraphTool(&stubKnowledgeBaseService{
kb: &types.KnowledgeBase{ID: "kb-1", ExtractConfig: &types.ExtractConfig{
Enabled: true, Nodes: []*types.GraphNode{{Name: "技术"}},
}},
}).WithGraph(graphRepo, chunkRepo)
args, err := json.Marshal(QueryKnowledgeGraphInput{KnowledgeBaseIDs: []string{"kb-1"}, Query: "Docker"})
require.NoError(t, err)
result, err := tool.Execute(context.Background(), args)
require.NoError(t, err)
assert.NotContains(t, result.Output, "Truncated")
assert.NotContains(t, result.Output, " of 1 relations")
_, hasRelationsTotal := result.Data["relations_total"]
assert.False(t, hasRelationsTotal, "an uncapped result must not claim a relation total")
_, hasChunksTotal := result.Data["graph_chunks_total"]
assert.False(t, hasChunksTotal, "an uncapped result must not claim a chunk total")
_, hasTermsTotal := result.Data["query_terms_total"]
assert.False(t, hasTermsTotal, "an uncapped result must not claim a term total")
}