Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(agent): 图谱查询的三处截断必须可见,模型不再把子图当全集 (#3885)
linus-liu-web9490035f1517
diff --git a/internal/agent/tools/query_knowledge_graph.go b/internal/agent/tools/query_knowledge_graph.goindex 04e6af565..1a7e809a3 100644--- a/internal/agent/tools/query_knowledge_graph.go+++ b/internal/agent/tools/query_knowledge_graph.go@@ -67,15 +67,80 @@ const (graphQueryMaxRelations = 30)-// graphSearchTerms turns the query into entity-name terms. The graph store-// matches node names by case-sensitive substring, so the whole query only-// matches when it is itself an entity name; its words catch the entities a-// question mentions ("Docker 和 Kubernetes 的关系" → Docker, Kubernetes).-// Words keep their case: lowercased terms never matched "Docker".-func graphSearchTerms(query string) []string {+// graphTruncation records what the caps above left out, per source. The zero+// value means nothing was dropped. A capped result must say so: a relation+// list read without a marker is the entity's whole neighbourhood to the model,+// and it then answers "X is not related to Y" from a list that never held Y.+type graphTruncation struct {+ relationsShown int+ relationsTotal int+ chunksFetched int+ chunksTotal int+ termsMatched int+ termsTotal int+}++// truncated reports whether any cap fired.+func (tr graphTruncation) truncated() bool {+ return tr.relationsTotal > tr.relationsShown || tr.chunksTotal > tr.chunksFetched ||+ tr.termsTotal > tr.termsMatched+}++// statement renders the block the model reads when a cap fired, and nothing+// otherwise: silence has to mean "nothing was dropped".+func (tr graphTruncation) statement() string {+ if !tr.truncated() {+ return ""+ }+ var b strings.Builder+ b.WriteString("=== ⚠️ Truncated ===\n")+ if tr.relationsTotal > tr.relationsShown {+ fmt.Fprintf(&b, " - Relations: %d of %d shown (cap %d per query). These entities have more relations "++ "than the ones listed below; query a single entity by name to see its neighbourhood.\n",+ tr.relationsShown, tr.relationsTotal, graphQueryMaxRelations)+ }+ if tr.chunksTotal > tr.chunksFetched {+ fmt.Fprintf(&b, " - Graph evidence chunks: %d of %d fetched (cap %d per knowledge base). Some of these "++ "entities' source chunks are not part of this result.\n",+ tr.chunksFetched, tr.chunksTotal, graphQueryMaxChunks)+ }+ if tr.termsTotal > tr.termsMatched {+ fmt.Fprintf(&b, " - Entity terms: %d of %d query words were matched against entity names (cap %d). A word "++ "left out can hide an entity, so name the entity you mean in query.\n",+ tr.termsMatched, tr.termsTotal, graphQueryMaxTerms)+ }+ b.WriteString("\n")+ return b.String()+}++// addToData records the cap counts under the tool's Data, and only when a cap+// fired: an absent key means nothing was dropped. The model reads a view+// rebuilt from these keys, so the marker has to travel here too.+func (tr graphTruncation) addToData(data map[string]interface{}) {+ if tr.relationsTotal > tr.relationsShown {+ data["relations_total"] = tr.relationsTotal+ data["relations_omitted"] = tr.relationsTotal - tr.relationsShown+ }+ if tr.chunksTotal > tr.chunksFetched {+ data["graph_chunks_total"] = tr.chunksTotal+ data["graph_chunks_omitted"] = tr.chunksTotal - tr.chunksFetched+ }+ if tr.termsTotal > tr.termsMatched {+ data["query_terms_total"] = tr.termsTotal+ data["query_terms_omitted"] = tr.termsTotal - tr.termsMatched+ }+}++// graphSearchTerms turns the query into entity-name terms, and reports how many+// candidate words the cap dropped. The graph store matches node names by+// case-sensitive substring, so the whole query only matches when it is itself+// an entity name; its words catch the entities a question mentions ("Docker 和+// Kubernetes 的关系" → Docker, Kubernetes). Words keep their case: lowercased+// terms never matched "Docker".+func graphSearchTerms(query string) (terms []string, dropped int) {query = strings.TrimSpace(query)if query == "" {- return nil+ return nil, 0}seen := map[string]bool{query: true}var tokens []string@@ -93,14 +158,17 @@ func graphSearchTerms(query string) []string {}return tokens[i] < tokens[j]})- terms := []string{query}+ terms = []string{query}for _, token := range tokens {if len(terms) >= graphQueryMaxTerms {- break+ // Dropped, not merely deferred: an entity named by one of these+ // words is never looked up, so the count travels with the result.+ dropped+++ continue}terms = append(terms, token)}- return terms+ return terms, dropped}// WithKnowledgeScope enables document/tag-level result filtering for Agent@@ -173,19 +241,21 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess// Concurrently query all knowledge basestype graphQueryResult struct {- kbID string- kb *types.KnowledgeBase- graphResults []*types.SearchResult // chunks the matched entities come from- textResults []*types.SearchResult- relations []*types.GraphRelation- warnings []string // failures of one source while the other returned results- err error+ kbID string+ kb *types.KnowledgeBase+ graphResults []*types.SearchResult // chunks the matched entities come from+ textResults []*types.SearchResult+ relations []*types.GraphRelation+ chunksFetched int // evidence chunks fetched, before scope filtering+ chunksTotal int // evidence chunks the matched entities reference+ warnings []string // failures of one source while the other returned results+ err error}var wg sync.WaitGroupvar mu sync.MutexkbResults := make(map[string]*graphQueryResult)- terms := graphSearchTerms(query)+ terms, termsDropped := graphSearchTerms(query)searchParams := types.SearchParams{QueryText: query,@@ -219,10 +289,12 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess}var errs []string- graphResults, graph, err := t.queryGraph(ctx, id, terms)+ lookup, err := t.queryGraph(ctx, id, terms)if err != nil {errs = append(errs, fmt.Sprintf("graph query failed: %v", err))}+ graphResults, graph := lookup.chunks, lookup.graph+ res.chunksFetched, res.chunksTotal = lookup.chunksFetched, lookup.chunksTotalvar relations []*types.GraphRelationif graph != nil {relations = graph.Relation@@ -274,6 +346,8 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMessvar graphHits, textHits []*types.SearchResultvar relations []*types.GraphRelationseenRelations := make(map[string]bool)+ relationsTotal := 0+ chunksFetched, chunksTotal := 0, 0for _, kbID := range input.KnowledgeBaseIDs {result := kbResults[kbID]@@ -290,6 +364,8 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess}kbCounts[kbID] = len(result.graphResults) + len(result.textResults)+ chunksFetched += result.chunksFetched+ chunksTotal += result.chunksTotalfor _, r := range result.graphResults {if !seenChunks[r.ID] {seenChunks[r.ID] = true@@ -304,12 +380,28 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess}for _, rel := range result.relations {key := rel.Node1 + "\x00" + rel.Type + "\x00" + rel.Node2- if !seenRelations[key] && len(relations) < graphQueryMaxRelations {- seenRelations[key] = true- relations = append(relations, rel)+ if seenRelations[key] {+ continue+ }+ seenRelations[key] = true+ relationsTotal+++ if len(relations) >= graphQueryMaxRelations {+ // Counted but not returned: the cap stays visible through+ // graphTruncation, or this subgraph reads as the whole+ // neighbourhood of every entity it mentions.+ continue}+ relations = append(relations, rel)}}+ truncation := graphTruncation{+ relationsShown: len(relations),+ relationsTotal: relationsTotal,+ chunksFetched: chunksFetched,+ chunksTotal: chunksTotal,+ termsMatched: len(terms),+ termsTotal: len(terms) + termsDropped,+ }sort.SliceStable(textHits, func(i, j int) bool {return textHits[i].Score > textHits[j].Score@@ -329,19 +421,26 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMessif len(errs) > 0 {output += " Some knowledge bases could not be queried: " + strings.Join(errs, "; ") + "."}+ // "Found nothing" is also what a dropped entity term looks like, so a+ // cap that fired has to be stated on this path too.+ if truncation.truncated() {+ output += "\n\n" + truncation.statement()+ }+ data := map[string]interface{}{+ "knowledge_base_ids": input.KnowledgeBaseIDs,+ "query": query,+ "results": []interface{}{},+ "relations": relationData,+ "graph_configs": graphConfigsToData(graphConfigs),+ "graph_config": aggregateGraphConfig(graphConfigs),+ "errors": errs,+ "display_type": "graph_query_results",+ }+ truncation.addToData(data)return &types.ToolResult{Success: true,Output: output,- Data: map[string]interface{}{- "knowledge_base_ids": input.KnowledgeBaseIDs,- "query": query,- "results": []interface{}{},- "relations": relationData,- "graph_configs": graphConfigsToData(graphConfigs),- "graph_config": aggregateGraphConfig(graphConfigs),- "errors": errs,- "display_type": "graph_query_results",- },+ Data: data,}, nil}@@ -349,8 +448,13 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMessoutput := "=== Knowledge Graph Query ===\n\n"output += fmt.Sprintf("📊 Query: %s\n", query)output += fmt.Sprintf("🎯 Target Knowledge Bases: %v\n", input.KnowledgeBaseIDs)- output += fmt.Sprintf("✓ Found %d relations and %d relevant chunks (deduplicated)\n\n",- len(relations), len(allResults))+ if truncation.relationsTotal > truncation.relationsShown {+ output += fmt.Sprintf("✓ Found %d of %d relations and %d relevant chunks (deduplicated)\n\n",+ len(relations), truncation.relationsTotal, len(allResults))+ } else {+ output += fmt.Sprintf("✓ Found %d relations and %d relevant chunks (deduplicated)\n\n",+ len(relations), len(allResults))+ }if len(errs) > 0 {output += "=== ⚠️ Partial Failures ===\n"@@ -360,6 +464,8 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMessoutput += "\n"}+ output += truncation.statement()+if len(relations) > 0 {output += "=== 🔗 Relations ===\n"for _, rel := range relations {@@ -444,61 +550,90 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess// Build structured graph data for frontend visualizationgraphData := buildGraphVisualizationData(allResults, relations)+ data := map[string]interface{}{+ "knowledge_base_ids": input.KnowledgeBaseIDs,+ "query": query,+ "results": formattedResults,+ "relations": relationData,+ "count": len(allResults),+ "kb_counts": kbCounts,+ "graph_configs": graphConfigsToData(graphConfigs),+ "graph_config": aggregateGraphConfig(graphConfigs),+ "graph_data": graphData,+ "has_graph_config": hasGraphConfig,+ "errors": errs,+ "display_type": "graph_query_results",+ }+ truncation.addToData(data)+return &types.ToolResult{Success: true,Output: output,- Data: map[string]interface{}{- "knowledge_base_ids": input.KnowledgeBaseIDs,- "query": query,- "results": formattedResults,- "relations": relationData,- "count": len(allResults),- "kb_counts": kbCounts,- "graph_configs": graphConfigsToData(graphConfigs),- "graph_config": aggregateGraphConfig(graphConfigs),- "graph_data": graphData,- "has_graph_config": hasGraphConfig,- "errors": errs,- "display_type": "graph_query_results",- },+ Data: data,}, nil}+// graphLookup is one knowledge base's graph lookup: the matched graph, the+// evidence chunks fetched for it, and how many distinct chunks the matched+// entities reference in total. The two counts travel back with the chunks so a+// fetch that stopped at graphQueryMaxChunks can be reported as such.+type graphLookup struct {+ graph *types.GraphData+ chunks []*types.SearchResult+ chunksFetched int+ chunksTotal int+}+// queryGraph looks the query's entity terms up in kbID's graph and returns// the chunks the matched entities were extracted from, plus the matched graph// (entities and relations). With no graph store wired, or none configured// (the store answers nil), it returns nothing.func (t *QueryKnowledgeGraphTool) queryGraph(ctx context.Context, kbID string, terms []string,-) ([]*types.SearchResult, *types.GraphData, error) {+) (graphLookup, error) {if t.graphRepo == nil || len(terms) == 0 {- return nil, nil, nil+ return graphLookup{}, nil}graph, err := t.graphRepo.SearchNode(ctx, types.NameSpace{KnowledgeBase: kbID}, terms)- if err != nil || graph == nil {- return nil, nil, err+ if err != nil {+ return graphLookup{}, err+ }+ if graph == nil {+ return graphLookup{}, nil+ }+ // Without a chunk store nothing is fetched at all, and none of it was+ // dropped by the cap: leaving the counts at zero keeps that apart from a+ // capped fetch, which must be reported.+ lookup := graphLookup{graph: graph}+ if t.chunkRepo == nil {+ return lookup, nil}chunkIDs := make([]string, 0, graphQueryMaxChunks)- seen := make(map[string]bool)+ referenced := make(map[string]bool)for _, node := range graph.Node {for _, id := range node.Chunks {- if len(chunkIDs) >= graphQueryMaxChunks {- break+ if id == "" || referenced[id] {+ continue}- if id != "" && !seen[id] {- seen[id] = true+ referenced[id] = true+ // Past the cap a chunk is counted, not fetched: the counts are+ // what tells the caller the evidence is a subset.+ if len(chunkIDs) < graphQueryMaxChunks {chunkIDs = append(chunkIDs, id)}}}- if len(chunkIDs) == 0 || t.chunkRepo == nil {- return nil, graph, nil+ lookup.chunksFetched, lookup.chunksTotal = len(chunkIDs), len(referenced)+ if len(chunkIDs) == 0 {+ return lookup, nil}// The graph namespace is the knowledge base, which the caller already// authorized; a chunk ID is only trusted when its row belongs to it.chunks, err := t.chunkRepo.ListChunksByIDOnly(ctx, chunkIDs)if err != nil {- return nil, graph, err+ // A failed fetch is an error, not a capped fetch: dropping the counts+ // keeps it from being reported as truncation.+ return graphLookup{graph: graph}, err}byID := make(map[string]*types.Chunk, len(chunks))knowledgeIDs := make([]string, 0, len(chunks))@@ -510,7 +645,7 @@ func (t *QueryKnowledgeGraphTool) queryGraph(}titles, err := t.knowledgeTitles(ctx, knowledgeIDs)if err != nil {- return nil, graph, err+ return graphLookup{graph: graph}, err}results := make([]*types.SearchResult, 0, len(byID))for _, id := range chunkIDs {@@ -535,7 +670,8 @@ func (t *QueryKnowledgeGraphTool) queryGraph(MatchType: types.MatchTypeGraph,})}- return results, graph, nil+ lookup.chunks = results+ return lookup, nil}// knowledgeTitles returns the titles of the knowledge IDs that still exist.diff --git a/internal/agent/tools/query_knowledge_graph_truncation_test.go b/internal/agent/tools/query_knowledge_graph_truncation_test.gonew file mode 100644index 000000000..25f95dabe--- /dev/null+++ b/internal/agent/tools/query_knowledge_graph_truncation_test.go@@ -0,0 +1,132 @@+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")+}diff --git a/internal/modelcontext/graph_truncation_test.go b/internal/modelcontext/graph_truncation_test.gonew file mode 100644index 000000000..64f175c97--- /dev/null+++ b/internal/modelcontext/graph_truncation_test.go@@ -0,0 +1,76 @@+package modelcontext++import (+ "fmt"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/require"+)++// graphQueryResultData builds the Data of a graph query answer whose relation+// list stopped at the tool's cap, as the tool reports it.+func graphQueryResultData(relations []map[string]interface{}, totals map[string]interface{}) map[string]interface{} {+ data := map[string]interface{}{+ "display_type": "graph_query_results",+ "results": []map[string]interface{}{{+ "chunk_id": "graph-chunk-real",+ "chunk_index": 4,+ "knowledge_id": "graph-doc-real",+ "knowledge_base_id": "graph-kb-real",+ "knowledge_title": "Graph Source",+ "content": "A relates to B.",+ }},+ "relations": relations,+ }+ for key, value := range totals {+ data[key] = value+ }+ return data+}++// The model reads a view rebuilt from Data, never the tool's Output, so a+// capped relation list has to carry its marker into that view: without it the+// model treats the returned subgraph as the entity's whole neighbourhood.+func TestModelOutputMarksCappedGraphRelations(t *testing.T) {+ registry := newSourceRegistry()+ relations := make([]map[string]interface{}, 0, 30)+ for i := 0; i < 30; i++ {+ relations = append(relations, map[string]interface{}{+ "source": "Docker", "type": "depends_on", "target": fmt.Sprintf("Service%02d", i),+ })+ }+ output := registry.ModelOutput(&types.ToolResult{+ Success: true,+ Output: "=== Knowledge Graph Query ===\n\n✓ Found 30 of 42 relations and 1 relevant chunks (deduplicated)\n",+ Data: graphQueryResultData(relations, map[string]interface{}{+ "relations_total": 42,+ "relations_omitted": 12,+ "graph_chunks_total": 14,+ "graph_chunks_omitted": 4,+ "query_terms_total": 13,+ "query_terms_omitted": 5,+ }),+ })+ t.Logf("model view:\n%s", output)++ require.Contains(t, output, `<graph_truncated relations_shown="30" relations_total="42" `++ `chunks_fetched="10" chunks_total="14" terms_shown="8" terms_total="13">`)+ require.Contains(t, output, "not the complete picture")+ require.Contains(t, output, `<relation source="Docker" type="depends_on" target="Service00" />`)+}++// An answer under every cap must stay clean: the marker only means a subset+// when it appears.+func TestModelOutputOmitsGraphTruncationMarkerWhenComplete(t *testing.T) {+ registry := newSourceRegistry()+ output := registry.ModelOutput(&types.ToolResult{+ Success: true,+ Data: graphQueryResultData([]map[string]interface{}{+ {"source": "Kubernetes", "type": "orchestrates", "target": "Docker"},+ }, nil),+ })++ require.Contains(t, output, `<relation source="Kubernetes" type="orchestrates" target="Docker" />`)+ require.NotContains(t, output, "graph_truncated")+}diff --git a/internal/modelcontext/model_output.go b/internal/modelcontext/model_output.goindex 6e0a20264..7c512a214 100644--- a/internal/modelcontext/model_output.go+++ b/internal/modelcontext/model_output.go@@ -308,13 +308,17 @@ func matchAddsToContent(match, content string) bool {return excerpt != "" && !strings.Contains(content, excerpt)}-// annotateGraphResult adds the graph relations and any per-knowledge-base-// failures to a graph query's chunk view. Both lived only in Output, which-// the model never sees once there are chunk rows to render.+// annotateGraphResult adds the graph relations, any per-knowledge-base+// failures, and any cap the graph tool hit to a graph query's chunk view. The+// first two lived only in Output, which the model never sees once there are+// chunk rows to render; the same goes for a truncated relation list, which+// without a marker reads as the entity's whole neighbourhood.func annotateGraphResult(output string, data map[string]interface{}) string {relations := mapsValue(data["relations"])failures := stringSliceValue(data["errors"])- if (len(relations) == 0 && len(failures) == 0) || !strings.HasSuffix(output, "</retrieval>") {+ truncation := graphTruncationNote(data, len(relations))+ if (len(relations) == 0 && len(failures) == 0 && truncation == "") ||+ !strings.HasSuffix(output, "</retrieval>") {return output}var b strings.Builder@@ -326,9 +330,50 @@ func annotateGraphResult(output string, data map[string]interface{}) string {for _, failure := range failures {fmt.Fprintf(&b, " <error>%s</error>\n", escapeText(failure))}+ b.WriteString(truncation)return strings.TrimSuffix(output, "</retrieval>") + b.String() + "</retrieval>"}+// graphTruncationNote states inside the model's view the caps the graph query+// tool hit. shownRelations is how many relations that view carries; the tool+// reports the totals under relations_total / graph_chunks_total /+// query_terms_total. It returns "" when nothing was dropped, so a complete+// result stays clean.+func graphTruncationNote(data map[string]interface{}, shownRelations int) string {+ totalRelations := intValue(data, "relations_total")+ totalChunks := intValue(data, "graph_chunks_total")+ fetchedChunks := totalChunks - intValue(data, "graph_chunks_omitted")+ totalTerms := intValue(data, "query_terms_total")+ if totalRelations <= shownRelations && totalChunks <= fetchedChunks && totalTerms <= 0 {+ return ""+ }+ var b strings.Builder+ b.WriteString(" <graph_truncated")+ if totalRelations > shownRelations {+ fmt.Fprintf(&b, " relations_shown=\"%d\" relations_total=\"%d\"", shownRelations, totalRelations)+ }+ if totalChunks > fetchedChunks {+ fmt.Fprintf(&b, " chunks_fetched=\"%d\" chunks_total=\"%d\"", fetchedChunks, totalChunks)+ }+ if totalTerms > 0 {+ fmt.Fprintf(&b, " terms_shown=\"%d\" terms_total=\"%d\"",+ totalTerms-intValue(data, "query_terms_omitted"), totalTerms)+ }+ b.WriteString(">This graph query stopped at a result cap, so it is not the complete picture: ")+ if totalRelations > shownRelations {+ b.WriteString("the relations listed are a subset of these entities' relations, ")+ }+ if totalChunks > fetchedChunks {+ b.WriteString("some of their source chunks are missing, ")+ }+ if totalTerms > 0 {+ b.WriteString("and some words of the query were never matched against entity names, ")+ }+ b.WriteString("so a relation may be absent only because it was dropped. Narrow the query to a single entity " ++ "name before concluding that a relation does not exist.</graph_truncated>\n")+ return b.String()+}+// annotateSearchNotes tells the model what a search result does not show:// how many lower-ranked results were left out to fit the tool output budget// (so it narrows the query or lowers the limit instead of concluding nothing