refactor(knowledge): keep metadata document scoped

main
wizardchen 2026-07-28 15:50:39 +08:00 committed by lyingbug
parent 9a37f01325
commit 1320c50bde
10 changed files with 262 additions and 42 deletions

View File

@ -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 display
func (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 != "" {

View File

@ -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 &lt;One&gt;")
require.Contains(t, text, "Shanghai &amp; 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())
}

View File

@ -578,15 +578,8 @@ func (s *chunkService) syncChunkIndex(ctx context.Context, chunk *types.Chunk) e
if 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) e
continue
}
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,

View File

@ -638,13 +638,6 @@ func (s *knowledgeService) UpdateKnowledge(ctx context.Context, knowledge *types
return 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)
}

View File

@ -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
}

View File

@ -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)
}

View File

@ -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.Con
for _, 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, c
for _, 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,

View File

@ -150,6 +150,7 @@ type modelChunk struct {
docHandle string
kbHandle string
title string
metadata string
chunkType string
index int
view string
@ -195,6 +196,7 @@ func (r *sourceRegistry) modelKnowledgeOutput(mode string, rows []map[string]int
docHandle: 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 string
kbHandle string
title string
metadata string
chunks []modelChunk
order 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] = group
groups = 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 != "" {

View File

@ -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 &amp; Suzhou</metadata>")
require.Equal(t, 2, strings.Count(output, "<chunk "))
}
func TestModelOutputWebAliasExpandsToWebCitation(t *testing.T) {
registry := newSourceRegistry()
output := registry.ModelOutput(&types.ToolResult{

View File

@ -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 ""