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
refactor(knowledge): keep metadata document scoped
wizardchen1320c50bde50
diff --git a/internal/agent/tools/knowledge_search.go b/internal/agent/tools/knowledge_search.goindex 78b3620a5..9870c72b8 100644--- a/internal/agent/tools/knowledge_search.go+++ b/internal/agent/tools/knowledge_search.go@@ -1103,6 +1103,39 @@ func (t *KnowledgeSearchTool) buildContentSignature(content string) string {return searchutil.BuildContentSignature(content)}+// writeKnowledgeMetadataHeader emits document-scoped metadata once per+// knowledge item. Chunk entries keep only chunk-specific content so repeated+// results from the same document do not waste model context.+func writeKnowledgeMetadataHeader(ob *strings.Builder, results []*searchResultWithMeta) {+ seen := make(map[string]struct{}, len(results))+ hasMetadata := false+ var documents strings.Builder+ for _, result := range results {+ if result == nil || result.SearchResult == nil || result.KnowledgeID == "" || result.KnowledgeCustomMetadata == "" {+ continue+ }+ if _, ok := seen[result.KnowledgeID]; ok {+ continue+ }+ seen[result.KnowledgeID] = struct{}{}+ hasMetadata = true+ documents.WriteString(fmt.Sprintf(+ "<document knowledge_id=\"%s\" knowledge_base_id=\"%s\" title=\"%s\">\n",+ xmlEscape(result.KnowledgeID),+ xmlEscape(result.KnowledgeBaseID),+ xmlEscape(result.KnowledgeTitle),+ ))+ documents.WriteString(fmt.Sprintf("<metadata>%s</metadata>\n", xmlEscape(result.KnowledgeCustomMetadata)))+ documents.WriteString("</document>\n")+ }+ if !hasMetadata {+ return+ }+ ob.WriteString("<documents>\n")+ ob.WriteString(documents.String())+ ob.WriteString("</documents>\n")+}+// formatOutput formats the search results for displayfunc (t *KnowledgeSearchTool) formatOutput(ctx context.Context,@@ -1148,6 +1181,7 @@ func (t *KnowledgeSearchTool) formatOutput(for _, q := range queries {ob.WriteString(fmt.Sprintf("<query>%s</query>\n", xmlEscape(q)))}+ writeKnowledgeMetadataHeader(&ob, results)formattedResults := make([]map[string]interface{}, 0, len(results))@@ -1274,9 +1308,6 @@ func (t *KnowledgeSearchTool) formatOutput(if snippet != "" {ob.WriteString(fmt.Sprintf("<match_snippet>%s</match_snippet>\n", xmlEscape(snippet)))}- if result.KnowledgeCustomMetadata != "" {- ob.WriteString(fmt.Sprintf("<metadata>%s</metadata>\n", xmlEscape(result.KnowledgeCustomMetadata)))- }ob.WriteString(fmt.Sprintf("<content>%s</content>\n", result.Content))if result.ImageInfo != "" {diff --git a/internal/agent/tools/knowledge_search_metadata_test.go b/internal/agent/tools/knowledge_search_metadata_test.gonew file mode 100644index 000000000..5b5ccc1d9--- /dev/null+++ b/internal/agent/tools/knowledge_search_metadata_test.go@@ -0,0 +1,62 @@+package tools++import (+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/require"+)++func TestWriteKnowledgeMetadataHeaderDeduplicatesByKnowledge(t *testing.T) {+ t.Parallel()+ results := []*searchResultWithMeta{+ {+ SearchResult: &types.SearchResult{+ KnowledgeID: "knowledge-1", KnowledgeTitle: "Document <One>",+ KnowledgeCustomMetadata: "region: Shanghai & Suzhou",+ },+ KnowledgeBaseID: "kb-1",+ },+ {+ SearchResult: &types.SearchResult{+ KnowledgeID: "knowledge-1", KnowledgeTitle: "Document <One>",+ KnowledgeCustomMetadata: "region: Shanghai & Suzhou",+ },+ KnowledgeBaseID: "kb-1",+ },+ {+ SearchResult: &types.SearchResult{+ KnowledgeID: "knowledge-2", KnowledgeTitle: "Document Two",+ },+ KnowledgeBaseID: "kb-1",+ },+ {+ SearchResult: &types.SearchResult{+ KnowledgeID: "knowledge-3", KnowledgeTitle: "Document Three",+ KnowledgeCustomMetadata: "owner: Alice",+ },+ KnowledgeBaseID: "kb-2",+ },+ }++ var output strings.Builder+ writeKnowledgeMetadataHeader(&output, results)+ text := output.String()++ require.Equal(t, 1, strings.Count(text, `knowledge_id="knowledge-1"`))+ require.Equal(t, 1, strings.Count(text, `knowledge_id="knowledge-3"`))+ require.NotContains(t, text, `knowledge_id="knowledge-2"`)+ require.Equal(t, 2, strings.Count(text, "<metadata>"))+ require.Contains(t, text, "Document <One>")+ require.Contains(t, text, "Shanghai & Suzhou")+}++func TestWriteKnowledgeMetadataHeaderOmitsEmptySection(t *testing.T) {+ t.Parallel()+ var output strings.Builder+ writeKnowledgeMetadataHeader(&output, []*searchResultWithMeta{{+ SearchResult: &types.SearchResult{KnowledgeID: "knowledge-1"},+ }})+ require.Empty(t, output.String())+}diff --git a/internal/application/service/chunk.go b/internal/application/service/chunk.goindex eb8a2f9fb..bea696715 100644--- a/internal/application/service/chunk.go+++ b/internal/application/service/chunk.go@@ -578,15 +578,8 @@ func (s *chunkService) syncChunkIndex(ctx context.Context, chunk *types.Chunk) eif err != nil {return err}- prefix := ""- if knowledge.Title != "" {- prefix = strings.TrimSpace(knowledge.Title) + "\n"- }- if metadata := knowledge.CustomMetadataText(); metadata != "" {- prefix += "Metadata:\n" + metadata + "\n"- }items := []*types.IndexInfo{{- Content: prefix + chunk.EmbeddingContent(), SourceID: chunk.ID,+ Content: buildKnowledgeIndexContent(knowledge, chunk.EmbeddingContent()), SourceID: chunk.ID,SourceType: types.ChunkSourceType, ChunkID: chunk.ID,KnowledgeID: chunk.KnowledgeID, KnowledgeBaseID: chunk.KnowledgeBaseID,KnowledgeType: kb.Type, IsEnabled: true,@@ -601,7 +594,7 @@ func (s *chunkService) syncChunkIndex(ctx context.Context, chunk *types.Chunk) econtinue}items = append(items, &types.IndexInfo{- Content: prefix + question.Question, SourceID: types.GeneratedQuestionSourceID(chunk.ID, question.ID),+ Content: buildKnowledgeIndexContent(knowledge, question.Question), SourceID: types.GeneratedQuestionSourceID(chunk.ID, question.ID),SourceType: types.ChunkSourceType, ChunkID: chunk.ID,KnowledgeID: chunk.KnowledgeID, KnowledgeBaseID: chunk.KnowledgeBaseID,KnowledgeType: kb.Type, IsEnabled: true,diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.goindex 4567b081b..fe671d391 100644--- a/internal/application/service/knowledge.go+++ b/internal/application/service/knowledge.go@@ -638,13 +638,6 @@ func (s *knowledgeService) UpdateKnowledge(ctx context.Context, knowledge *typesreturn err}if metadataChanged {- chunks, err := s.chunkRepo.ListChunksByKnowledgeID(ctx, record.TenantID, record.ID)- if err != nil {- return fmt.Errorf("list chunks for metadata reindex: %w", err)- }- if err := s.updateChunkVector(ctx, record.KnowledgeBaseID, chunks); err != nil {- return fmt.Errorf("metadata saved but reindex failed: %w", err)- }if record.SummaryStatus == types.SummaryStatusCompleted {_ = s.repo.UpdateKnowledgeColumn(ctx, record.ID, "summary_status", types.SummaryStatusPending)}diff --git a/internal/application/service/knowledge_index_content.go b/internal/application/service/knowledge_index_content.gonew file mode 100644index 000000000..1b0796452--- /dev/null+++ b/internal/application/service/knowledge_index_content.go@@ -0,0 +1,21 @@+package service++import (+ "strings"++ "github.com/Tencent/WeKnora/internal/types"+)++// buildKnowledgeIndexContent adds only the document title to searchable text.+// Custom metadata stays document-scoped: it is supplied once to the answer+// model and summary model, rather than repeated in every chunk embedding.+func buildKnowledgeIndexContent(knowledge *types.Knowledge, content string) string {+ if knowledge == nil {+ return content+ }+ title := strings.TrimSpace(knowledge.Title)+ if title == "" {+ return content+ }+ return title + "\n" + content+}diff --git a/internal/application/service/knowledge_index_content_test.go b/internal/application/service/knowledge_index_content_test.gonew file mode 100644index 000000000..e9d462726--- /dev/null+++ b/internal/application/service/knowledge_index_content_test.go@@ -0,0 +1,95 @@+package service++import (+ "context"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/stretchr/testify/require"+)++func TestBuildKnowledgeIndexContentExcludesCustomMetadata(t *testing.T) {+ t.Parallel()+ knowledge := &types.Knowledge{+ Title: " WeKnora Handbook ",+ CustomMetadata: types.JSON(`{"region":"Shanghai","department":"R&D"}`),+ }++ content := buildKnowledgeIndexContent(knowledge, "Chunk body")++ require.Equal(t, "WeKnora Handbook\nChunk body", content)+ require.NotContains(t, content, "Shanghai")+ require.NotContains(t, content, "department")+}++func TestBuildKnowledgeIndexContentWithoutTitleReturnsContent(t *testing.T) {+ t.Parallel()+ require.Equal(t, "Chunk body", buildKnowledgeIndexContent(&types.Knowledge{+ CustomMetadata: types.JSON(`{"region":"Shanghai"}`),+ }, "Chunk body"))+ require.Equal(t, "Chunk body", buildKnowledgeIndexContent(nil, "Chunk body"))+}++type metadataUpdateKnowledgeRepo struct {+ interfaces.KnowledgeRepository+ knowledge *types.Knowledge+ summaryStatusUpdate interface{}+}++func (r *metadataUpdateKnowledgeRepo) GetKnowledgeByID(+ _ context.Context, _ uint64, _ string,+) (*types.Knowledge, error) {+ clone := *r.knowledge+ return &clone, nil+}++func (r *metadataUpdateKnowledgeRepo) UpdateKnowledge(_ context.Context, knowledge *types.Knowledge) error {+ clone := *knowledge+ r.knowledge = &clone+ return nil+}++func (r *metadataUpdateKnowledgeRepo) UpdateKnowledgeColumn(+ _ context.Context, _ string, column string, value interface{},+) error {+ if column == "summary_status" {+ r.summaryStatusUpdate = value+ }+ return nil+}++type metadataUpdateChunkRepo struct {+ interfaces.ChunkRepository+ listCalls int+}++func (r *metadataUpdateChunkRepo) ListChunksByKnowledgeID(+ _ context.Context, _ uint64, _ string,+) ([]*types.Chunk, error) {+ r.listCalls+++ return nil, nil+}++func TestUpdateKnowledgeMetadataDoesNotReindexChunks(t *testing.T) {+ t.Parallel()+ repo := &metadataUpdateKnowledgeRepo{knowledge: &types.Knowledge{+ ID: "knowledge-1",+ TenantID: 7,+ SummaryStatus: types.SummaryStatusCompleted,+ CustomMetadata: types.JSON(`{"region":"Beijing"}`),+ }}+ chunkRepo := &metadataUpdateChunkRepo{}+ service := &knowledgeService{repo: repo, chunkRepo: chunkRepo}+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))++ err := service.UpdateKnowledge(ctx, &types.Knowledge{+ ID: "knowledge-1",+ CustomMetadata: types.JSON(`{"region":"Shanghai"}`),+ })++ require.NoError(t, err)+ require.JSONEq(t, `{"region":"Shanghai"}`, string(repo.knowledge.CustomMetadata))+ require.Zero(t, chunkRepo.listCalls)+ require.Equal(t, types.SummaryStatusPending, repo.summaryStatusUpdate)+}diff --git a/internal/application/service/knowledge_process.go b/internal/application/service/knowledge_process.goindex d41a10151..c59a6c944 100644--- a/internal/application/service/knowledge_process.go+++ b/internal/application/service/knowledge_process.go@@ -529,18 +529,12 @@ func (s *knowledgeService) processChunks(ctx context.Context,// Prepend the document title to improve semantic alignment between// question-style queries and statement-style chunk content.indexInfoList := make([]*types.IndexInfo, 0, len(textChunks))- titlePrefix := ""- if t := strings.TrimSpace(knowledge.Title); t != "" {- titlePrefix = t + "\n"- }- if metadata := knowledge.CustomMetadataText(); metadata != "" {- titlePrefix += "Metadata:\n" + metadata + "\n"- }for _, chunk := range textChunks {// chunk.EmbeddingContent prepends ContextHeader (heading breadcrumb)// when the chunker populated it during Tier-1 splitting; falls back- // to plain Content otherwise. Title prefix sits outermost.- indexContent := titlePrefix + chunk.EmbeddingContent()+ // to plain Content otherwise. The document title sits outermost;+ // custom metadata remains document-scoped model context.+ indexContent := buildKnowledgeIndexContent(knowledge, chunk.EmbeddingContent())indexInfoList = append(indexInfoList, &types.IndexInfo{Content: indexContent,SourceID: chunk.ID,@@ -1602,7 +1596,7 @@ func (s *knowledgeService) processQuestionGenerationForKnowledge(ctx context.Confor _, gq := range generatedQuestions {sourceID := types.GeneratedQuestionSourceID(chunk.ID, gq.ID)indexInfoList = append(indexInfoList, &types.IndexInfo{- Content: gq.Question,+ Content: buildKnowledgeIndexContent(knowledge, gq.Question),SourceID: sourceID,SourceType: types.ChunkSourceType,ChunkID: chunk.ID,@@ -1929,7 +1923,7 @@ func (s *knowledgeService) processQuestionGenerationForChunks(ctx context.Contex}for _, gq := range generatedQuestions {indexInfoList = append(indexInfoList, &types.IndexInfo{- Content: gq.Question,+ Content: buildKnowledgeIndexContent(knowledge, gq.Question),SourceID: types.GeneratedQuestionSourceID(chunk.ID, gq.ID),SourceType: types.ChunkSourceType,ChunkID: chunk.ID,@@ -2663,15 +2657,8 @@ func (s *knowledgeService) updateChunkVector(ctx context.Context, kbID string, c}knowledgeCache[chunk.KnowledgeID] = knowledge}- prefix := ""- if title := strings.TrimSpace(knowledge.Title); title != "" {- prefix = title + "\n"- }- if metadata := knowledge.CustomMetadataText(); metadata != "" {- prefix += "Metadata:\n" + metadata + "\n"- }indexInfo = append(indexInfo, &types.IndexInfo{- Content: prefix + chunk.EmbeddingContent(),+ Content: buildKnowledgeIndexContent(knowledge, chunk.EmbeddingContent()),SourceID: chunk.ID,SourceType: types.ChunkSourceType,ChunkID: chunk.ID,@@ -2688,7 +2675,7 @@ func (s *knowledgeService) updateChunkVector(ctx context.Context, kbID string, cfor _, q := range meta.GeneratedQuestions {if strings.TrimSpace(q.Question) != "" {indexInfo = append(indexInfo, &types.IndexInfo{- Content: prefix + q.Question, SourceID: types.GeneratedQuestionSourceID(chunk.ID, q.ID),+ Content: buildKnowledgeIndexContent(knowledge, q.Question), SourceID: types.GeneratedQuestionSourceID(chunk.ID, q.ID),SourceType: types.ChunkSourceType, ChunkID: chunk.ID,KnowledgeID: chunk.KnowledgeID, KnowledgeBaseID: chunk.KnowledgeBaseID,KnowledgeType: sourceKB.Type, IsEnabled: true,diff --git a/internal/modelcontext/model_output.go b/internal/modelcontext/model_output.goindex d06510971..ca01792f0 100644--- a/internal/modelcontext/model_output.go+++ b/internal/modelcontext/model_output.go@@ -150,6 +150,7 @@ type modelChunk struct {docHandle stringkbHandle stringtitle string+ metadata stringchunkType stringindex intview string@@ -195,6 +196,7 @@ func (r *sourceRegistry) modelKnowledgeOutput(mode string, rows []map[string]intdocHandle: r.RegisterDocument(knowledgeID),kbHandle: r.RegisterKnowledgeBase(kbID),title: title,+ metadata: stringValue(row, "knowledge_metadata"),chunkType: chunkType,index: chunkIndex,view: viewForRow(row, mode),@@ -255,6 +257,7 @@ func renderKnowledgeChunks(mode string, chunks []modelChunk) string {handle stringkbHandle stringtitle string+ metadata stringchunks []modelChunkorder int}@@ -267,9 +270,14 @@ func renderKnowledgeChunks(mode string, chunks []modelChunk) string {}group := groupsByKey[key]if group == nil {- group = &docGroup{handle: chunk.docHandle, kbHandle: chunk.kbHandle, title: chunk.title, order: chunk.inputOrder}+ group = &docGroup{+ handle: chunk.docHandle, kbHandle: chunk.kbHandle, title: chunk.title,+ metadata: chunk.metadata, order: chunk.inputOrder,+ }groupsByKey[key] = groupgroups = append(groups, group)+ } else if group.metadata == "" {+ group.metadata = chunk.metadata}group.chunks = append(group.chunks, chunk)}@@ -289,6 +297,9 @@ func renderKnowledgeChunks(mode string, chunks []modelChunk) string {fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(group.title))}b.WriteString(">\n")+ if group.metadata != "" {+ fmt.Fprintf(&b, " <metadata>%s</metadata>\n", escapeText(group.metadata))+ }for _, chunk := range group.chunks {fmt.Fprintf(&b, " <chunk id=\"%s\" index=\"%d\" view=\"%s\"", chunk.handle, chunk.index, chunk.view)if chunk.chunkType != "" {diff --git a/internal/modelcontext/sources_test.go b/internal/modelcontext/sources_test.goindex f55d87f0a..afb207cf0 100644--- a/internal/modelcontext/sources_test.go+++ b/internal/modelcontext/sources_test.go@@ -234,6 +234,32 @@ func TestModelOutputGroupsChunksAndReusesAliasAcrossTools(t *testing.T) {require.False(t, strings.Contains(second, "c2"))}+func TestModelOutputRendersKnowledgeMetadataOncePerDocument(t *testing.T) {+ registry := newSourceRegistry()+ output := registry.ModelOutput(&types.ToolResult{+ Success: true,+ Data: map[string]interface{}{+ "display_type": "search_results",+ "results": []map[string]interface{}{+ {+ "chunk_id": "chunk-1", "chunk_index": 1, "content": "first",+ "knowledge_id": "document-1", "knowledge_base_id": "kb-1", "knowledge_title": "Doc",+ "knowledge_metadata": "region: Shanghai & Suzhou",+ },+ {+ "chunk_id": "chunk-2", "chunk_index": 2, "content": "second",+ "knowledge_id": "document-1", "knowledge_base_id": "kb-1", "knowledge_title": "Doc",+ "knowledge_metadata": "region: Shanghai & Suzhou",+ },+ },+ },+ })++ require.Equal(t, 1, strings.Count(output, "<metadata>"))+ require.Contains(t, output, "<metadata>region: Shanghai & Suzhou</metadata>")+ require.Equal(t, 2, strings.Count(output, "<chunk "))+}+func TestModelOutputWebAliasExpandsToWebCitation(t *testing.T) {registry := newSourceRegistry()output := registry.ModelOutput(&types.ToolResult{diff --git a/internal/types/knowledge.go b/internal/types/knowledge.goindex b5676d661..80ad38a30 100644--- a/internal/types/knowledge.go+++ b/internal/types/knowledge.go@@ -175,8 +175,9 @@ type Knowledge struct {KnowledgeBaseName string `json:"knowledge_base_name" gorm:"-"`}-// CustomMetadataText returns stable human-readable metadata for retrieval and-// model context. Internal ingestion metadata is intentionally excluded.+// CustomMetadataText returns stable human-readable metadata for summaries and+// document-scoped model context. Internal ingestion metadata is intentionally+// excluded.func (k *Knowledge) CustomMetadataText() string {if k == nil || len(k.CustomMetadata) == 0 {return ""