feat(llm): introduce request-local source reference aliases

Replace raw chunk/document/KB IDs in LLM context with short cN/dN/bN/wN
aliases, decode tool arguments on the way in, and expand compact <ref/>
citations to the public <kb>/<web> format before user-facing output.
This commit is contained in:
wizardchen
2026-07-16 21:23:20 +08:00
committed by lyingbug
parent 79e8f3d894
commit 014164ae44
33 changed files with 1962 additions and 149 deletions
+10 -19
View File
@@ -117,27 +117,18 @@ func LoadAgentHistory(
}
// buildUserHistoryMessage converts a stored user message into the chat.Message
// form that should appear in LLM history. It prefers RenderedContent (which
// already contains any retrieval-context augmentation from prior turns) and
// falls back to Content. When the user uploaded images, the captions extracted
// during ingestion are appended so subsequent turns retain a textual reference
// to those images even after the binary payload is gone.
// form that should appear in LLM history. It deliberately ignores
// RenderedContent: that field is a snapshot of the old prompt and retrieval
// context format, which must not be mixed into the current request protocol.
// Image captions and attachments are reconstructed from their canonical DB
// columns so useful user-provided context is retained without stale RAG data.
func buildUserHistoryMessage(m *types.Message) chat.Message {
content := m.RenderedContent
if content == "" {
content = m.Content
content := m.Content
if captions := extractImageCaptionsFromMessage(m.Images); captions != "" {
content += "\n\n[用户上传图片内容]\n" + captions
}
// Only append fallbacks when RenderedContent is absent — when present, it
// already carries the augmented version persisted by the original turn.
// Agent-mode turns do not persist RenderedContent (scope envelopes are
// injected only for the current LLM call, not replayed from history).
if m.RenderedContent == "" {
if captions := extractImageCaptionsFromMessage(m.Images); captions != "" {
content += "\n\n[用户上传图片内容]\n" + captions
}
if len(m.Attachments) > 0 {
content += m.Attachments.BuildPrompt()
}
if len(m.Attachments) > 0 {
content += m.Attachments.BuildPrompt()
}
return chat.Message{Role: "user", Content: content}
}
@@ -11,12 +11,9 @@ import (
"github.com/stretchr/testify/require"
)
// TestBuildUserHistoryMessage_PrefersRenderedContent verifies the user side of
// history rebuild: RenderedContent (the RAG-augmented version) wins over the
// raw Content, and image captions are appended only when there's no rendered
// override (the rendered version already carries any retrieval context that
// would have included the caption upstream).
func TestBuildUserHistoryMessage_PrefersRenderedContent(t *testing.T) {
// TestBuildUserHistoryMessage_IgnoresLegacyRenderedContent verifies that old
// prompt/context snapshots never re-enter the current model context.
func TestBuildUserHistoryMessage_IgnoresLegacyRenderedContent(t *testing.T) {
msg := &types.Message{
Role: "user",
Content: "what about the chart?",
@@ -27,7 +24,8 @@ func TestBuildUserHistoryMessage_PrefersRenderedContent(t *testing.T) {
}
got := buildUserHistoryMessage(msg)
assert.Equal(t, "user", got.Role)
assert.Equal(t, "what about the chart? [augmented]", got.Content)
assert.Equal(t, "what about the chart?\n\n[用户上传图片内容]\na bar chart", got.Content)
assert.NotContains(t, got.Content, "[augmented]")
}
func TestBuildUserHistoryMessage_FallsBackToContentWithCaptions(t *testing.T) {
@@ -69,10 +67,10 @@ func TestBuildUserHistoryMessage_AppendsAttachmentsWhenNoRenderedContent(t *test
assert.Contains(t, got.Content, "hello world")
}
// TestBuildUserHistoryMessage_RenderedContentSkipsAttachmentReplay ensures the
// KnowledgeQA path (where RenderedContent already includes the attachment
// prompt persisted by the pipeline) does not double-inject attachments.
func TestBuildUserHistoryMessage_RenderedContentSkipsAttachmentReplay(t *testing.T) {
// TestBuildUserHistoryMessage_RenderedContentRebuildsAttachment verifies that
// canonical attachment data is retained while the legacy rendered snapshot is
// discarded.
func TestBuildUserHistoryMessage_RenderedContentRebuildsAttachment(t *testing.T) {
msg := &types.Message{
Role: "user",
Content: "summarize this",
@@ -82,8 +80,9 @@ func TestBuildUserHistoryMessage_RenderedContentSkipsAttachmentReplay(t *testing
},
}
got := buildUserHistoryMessage(msg)
assert.Equal(t, "summarize this [with retrieval context already included]", got.Content)
assert.NotContains(t, got.Content, "<attachment")
assert.Contains(t, got.Content, "summarize this")
assert.NotContains(t, got.Content, "[with retrieval context already included]")
assert.Contains(t, got.Content, "<attachment")
}
// TestBuildAssistantHistoryMessages_NaturalFinishEmitsSingleAnswer covers the
@@ -51,8 +51,9 @@ func (p *PluginChatCompletion) OnEvent(
pipelineInfo(ctx, "Completion", "messages_ready", map[string]interface{}{
"message_count": len(chatManage.History) + 2,
})
chatMessages := prepareMessagesWithHistory(chatManage)
chatMessages, sourceRefs := prepareMessagesWithReferences(ctx, chatManage)
resourceRefs := llmresource.NewRegistry()
chatMessages = sourceRefs.EncodeMessages(chatMessages)
chatMessages = resourceRefs.EncodeMessages(chatMessages)
// Call the chat model to generate response
@@ -68,6 +69,7 @@ func (p *PluginChatCompletion) OnEvent(
return ErrModelCall.WithError(err)
}
resourceRefs.DecodeResponse(chatResponse)
sourceRefs.ExpandResponse(chatResponse)
if orphans := resourceRefs.OrphanAliases(chatResponse.Content); len(orphans) > 0 {
pipelineWarn(ctx, "Completion", "orphan_resource_aliases", map[string]interface{}{
"session_id": chatManage.SessionID,
@@ -6,6 +6,7 @@ import (
"fmt"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/llmreference"
"github.com/Tencent/WeKnora/internal/llmresource"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -55,8 +56,9 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
// Prepare base messages without history
chatMessages := prepareMessagesWithHistory(chatManage)
chatMessages, sourceRefs := prepareMessagesWithReferences(ctx, chatManage)
resourceRefs := llmresource.NewRegistry()
chatMessages = sourceRefs.EncodeMessages(chatMessages)
chatMessages = resourceRefs.EncodeMessages(chatMessages)
pipelineInfo(ctx, "Stream", "messages_ready", map[string]interface{}{
"message_count": len(chatMessages),
@@ -110,6 +112,8 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
go func() {
answerDecoder := llmresource.NewStreamDecoder(resourceRefs)
thinkingDecoder := llmresource.NewStreamDecoder(resourceRefs)
answerRefExpander := llmreference.NewStreamExpander(sourceRefs)
thinkingRefExpander := llmreference.NewStreamExpander(sourceRefs)
thinkingID := fmt.Sprintf("%s-thinking", uuid.New().String()[:8])
answerID := fmt.Sprintf("%s-answer", uuid.New().String()[:8])
thinkingOpen := false
@@ -135,20 +139,22 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
// reference in flight at teardown is silently dropped (and never
// persisted, since the assistant message is saved from these events).
flushDecoders := func() {
if tail := thinkingDecoder.Flush(); tail != "" {
thinkingTail := thinkingRefExpander.Feed(thinkingDecoder.Flush()) + thinkingRefExpander.Flush()
if thinkingTail != "" {
_ = eventBus.Emit(ctx, types.Event{
ID: thinkingID,
Type: types.EventType(event.EventAgentThought),
SessionID: chatManage.SessionID,
Data: event.AgentThoughtData{Content: tail},
Data: event.AgentThoughtData{Content: thinkingTail},
})
}
if tail := answerDecoder.Flush(); tail != "" {
answerTail := answerRefExpander.Feed(answerDecoder.Flush()) + answerRefExpander.Flush()
if answerTail != "" {
_ = eventBus.Emit(ctx, types.Event{
ID: answerID,
Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{Content: tail},
Data: event.AgentFinalAnswerData{Content: answerTail},
})
}
}
@@ -192,7 +198,7 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
}
if response.ResponseType == types.ResponseTypeThinking {
response.Content = thinkingDecoder.Feed(response.Content)
response.Content = thinkingRefExpander.Feed(thinkingDecoder.Feed(response.Content))
if response.Content != "" {
thinkingOpen = true
eventBus.Emit(ctx, types.Event{
@@ -212,7 +218,7 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
}
if response.ResponseType == types.ResponseTypeAnswer {
response.Content = answerDecoder.Feed(response.Content)
response.Content = answerRefExpander.Feed(answerDecoder.Feed(response.Content))
closeThinking()
eventBus.Emit(ctx, types.Event{
ID: answerID,
@@ -145,25 +145,18 @@ func loadAndProcessHistory(
h = &types.History{}
}
if message.Role == "user" {
if message.RenderedContent != "" {
h.Query = message.RenderedContent
} else {
h.Query = message.Content
}
// RenderedContent is a snapshot of the prompt/context format used by
// the original turn. Replaying it would mix legacy <context id="…">
// envelopes and old citation instructions into the current protocol.
// Historical references are carried separately in KnowledgeReferences
// and can be re-merged into this turn's freshly rendered context.
h.Query = message.Content
h.CreateAt = message.CreatedAt
// When RenderedContent is absent (e.g. the pure-chat, non-RAG path
// and the search-nothing fallback path never persist it), replay the
// previous turn's image captions and attachment content from the
// stored message so the model retains a textual reference to them.
// When RenderedContent is present it already carries this
// augmentation, so we must not double-append.
if message.RenderedContent == "" {
if desc := extractImageCaptions(message.Images); desc != "" {
h.Query += "\n\n[用户上传图片内容]\n" + desc
}
if len(message.Attachments) > 0 {
h.Query += message.Attachments.BuildPrompt()
}
if desc := extractImageCaptions(message.Images); desc != "" {
h.Query += "\n\n[用户上传图片内容]\n" + desc
}
if len(message.Attachments) > 0 {
h.Query += message.Attachments.BuildPrompt()
}
} else {
h.Answer = regThinkTags.ReplaceAllString(message.Content, "")
@@ -0,0 +1,135 @@
package chatpipeline
import (
"context"
"strings"
"github.com/Tencent/WeKnora/internal/llmreference"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
)
// prepareMessagesWithReferences replaces the pipeline's positional context IDs
// with request-local chunk references in the copy sent to the model. Persisted
// rendered_content and the public citation contract remain unchanged.
func prepareMessagesWithReferences(
ctx context.Context,
chatManage *types.ChatManage,
) ([]chat.Message, *llmreference.Registry) {
refs := llmreference.NewRegistry()
if chatManage == nil {
return nil, refs
}
messages := prepareMessagesWithHistory(chatManage)
if len(messages) > 0 {
messages[0].Content = strings.TrimRight(messages[0].Content, " \t\r\n") + llmreference.ProtocolPrompt
}
if len(chatManage.MergeResult) == 0 || len(messages) == 0 {
return messages, refs
}
ordered := orderedPipelineReferences(chatManage)
knowledgeResults := make([]*types.SearchResult, 0, len(ordered))
knowledgeRows := make([]map[string]interface{}, 0, len(ordered))
webRows := make([]map[string]interface{}, 0)
for _, result := range ordered {
if result == nil {
continue
}
if isPipelineWebReference(result) {
webRows = append(webRows, map[string]interface{}{
"url": result.ID,
"title": firstPipelineTitle(result),
"snippet": result.Content,
"published_at": result.Metadata["published_at"],
})
continue
}
knowledgeResults = append(knowledgeResults, result)
knowledgeRows = append(knowledgeRows, map[string]interface{}{
"chunk_id": result.ID,
"knowledge_id": result.KnowledgeID,
"knowledge_base_id": result.KnowledgeBaseID,
"knowledge_title": firstPipelineTitle(result),
"chunk_index": result.ChunkIndex,
"chunk_type": result.ChunkType,
"content": getEnrichedPassageForChat(ctx, result),
})
}
refs.RegisterSearchResults(knowledgeResults)
var contextParts []string
if len(knowledgeRows) > 0 {
contextParts = append(contextParts, refs.ModelOutput(&types.ToolResult{
Success: true,
Data: map[string]interface{}{
"display_type": "search_results",
"results": knowledgeRows,
},
}))
}
if len(webRows) > 0 {
contextParts = append(contextParts, refs.ModelOutput(&types.ToolResult{
Success: true,
Data: map[string]interface{}{
"display_type": "web_search_results",
"results": webRows,
},
}))
}
modelContexts := strings.Join(contextParts, "\n")
if strings.TrimSpace(modelContexts) == "" {
return messages, refs
}
last := len(messages) - 1
replaced := false
for _, index := range []int{0, last} {
if chatManage.RenderedContexts != "" && strings.Contains(messages[index].Content, chatManage.RenderedContexts) {
messages[index].Content = strings.ReplaceAll(messages[index].Content, chatManage.RenderedContexts, modelContexts)
replaced = true
}
}
if !replaced {
messages[last].Content = modelContexts + "\n\n" + messages[last].Content
}
return messages, refs
}
func isPipelineWebReference(result *types.SearchResult) bool {
if result == nil {
return false
}
return strings.EqualFold(result.ChunkType, string(types.ChunkTypeWebSearch)) ||
strings.EqualFold(result.KnowledgeSource, "web_search")
}
func orderedPipelineReferences(chatManage *types.ChatManage) []*types.SearchResult {
if chatManage == nil {
return nil
}
if !chatManage.FAQPriorityEnabled {
return chatManage.MergeResult
}
ordered := make([]*types.SearchResult, 0, len(chatManage.MergeResult))
for _, result := range chatManage.MergeResult {
if result != nil && result.ChunkType == string(types.ChunkTypeFAQ) {
ordered = append(ordered, result)
}
}
for _, result := range chatManage.MergeResult {
if result != nil && result.ChunkType != string(types.ChunkTypeFAQ) {
ordered = append(ordered, result)
}
}
return ordered
}
func firstPipelineTitle(result *types.SearchResult) string {
if result == nil {
return ""
}
if result.KnowledgeTitle != "" {
return result.KnowledgeTitle
}
return result.KnowledgeFilename
}
@@ -0,0 +1,116 @@
package chatpipeline
import (
"context"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
func TestPrepareMessagesWithReferencesUsesChunkCentricContext(t *testing.T) {
rendered := `<context id="1">first content</context><context id="2">second content</context>`
manage := &types.ChatManage{
PipelineRequest: types.PipelineRequest{
Query: "question",
SummaryConfig: types.SummaryConfig{
Prompt: "system",
},
},
PipelineState: types.PipelineState{
RenderedContexts: rendered,
UserContent: "References:\n" + rendered + "\nQuestion: question",
MergeResult: []*types.SearchResult{
{ID: "chunk-1", KnowledgeID: "doc-1", KnowledgeBaseID: "kb-1", KnowledgeTitle: "Doc", ChunkIndex: 1, Content: "first content"},
{ID: "chunk-2", KnowledgeID: "doc-1", KnowledgeBaseID: "kb-1", KnowledgeTitle: "Doc", ChunkIndex: 2, Content: "second content"},
},
},
}
messages, refs := prepareMessagesWithReferences(context.Background(), manage)
require.Len(t, messages, 2)
require.Contains(t, messages[0].Content, "Source reference protocol")
require.Contains(t, messages[1].Content, `<document id="d1" kb="b1" title="Doc">`)
require.Contains(t, messages[1].Content, `<chunk id="c1" index="1" view="full">`)
require.Contains(t, messages[1].Content, `<chunk id="c2" index="2" view="full">`)
require.False(t, strings.Contains(messages[1].Content, "chunk-1"))
require.Equal(t,
`<kb doc="Doc" chunk_id="chunk-1" kb_id="kb-1" />`,
refs.ExpandText(`<ref id="c1"/>`),
)
}
func TestPrepareMessagesWithReferencesReplacesSystemPromptContextAndHistoryCitations(t *testing.T) {
rendered := `<context id="1">first content</context>`
manage := &types.ChatManage{
PipelineRequest: types.PipelineRequest{
Query: "question",
SummaryConfig: types.SummaryConfig{
Prompt: `System references: {{contexts}}`,
},
},
PipelineState: types.PipelineState{
RenderedContexts: rendered,
UserContent: "Question: question",
History: []*types.History{{
Query: "previous",
Answer: `Previous <kb doc="Old" chunk_id="old-chunk" kb_id="old-kb" />`,
}},
MergeResult: []*types.SearchResult{{
ID: "current-chunk", KnowledgeID: "current-doc", KnowledgeBaseID: "current-kb", KnowledgeTitle: "Current", Content: "first content",
}},
},
}
messages, refs := prepareMessagesWithReferences(context.Background(), manage)
messages = refs.EncodeMessages(messages)
require.NotContains(t, messages[0].Content, rendered)
require.Contains(t, messages[0].Content, `<chunk id="c1"`)
require.Contains(t, messages[2].Content, `<ref id="c2"/>`)
require.NotContains(t, messages[2].Content, "old-chunk")
}
func TestPrepareMessagesWithReferencesKeepsWebSeparateFromChunks(t *testing.T) {
manage := &types.ChatManage{
PipelineRequest: types.PipelineRequest{Query: "question", SummaryConfig: types.SummaryConfig{Prompt: "system"}},
PipelineState: types.PipelineState{
UserContent: "question",
MergeResult: []*types.SearchResult{{
ID: "https://example.com/page",
KnowledgeTitle: "Example",
Content: "web content",
ChunkType: string(types.ChunkTypeWebSearch),
KnowledgeSource: "web_search",
}},
},
}
messages, refs := prepareMessagesWithReferences(context.Background(), manage)
require.Contains(t, messages[1].Content, `<retrieval type="web" mode="search">`)
require.Contains(t, messages[1].Content, `<page id="w1" title="Example">`)
require.NotContains(t, messages[1].Content, `<chunk id="c1"`)
require.Equal(t,
`<web url="https://example.com/page" title="Example" />`,
refs.ExpandText(`<ref id="w1"/>`),
)
}
func TestPrepareMessagesWithReferencesCompactsHistoryWithoutCurrentRetrieval(t *testing.T) {
manage := &types.ChatManage{
PipelineRequest: types.PipelineRequest{Query: "follow-up", SummaryConfig: types.SummaryConfig{Prompt: "system"}},
PipelineState: types.PipelineState{
UserContent: "follow-up",
History: []*types.History{{
Query: "previous",
Answer: `Previous <web url="https://example.com/old" title="Old" />`,
}},
},
}
messages, refs := prepareMessagesWithReferences(context.Background(), manage)
messages = refs.EncodeMessages(messages)
require.Contains(t, messages[0].Content, "Source reference protocol")
require.Contains(t, messages[2].Content, `<ref id="w1"/>`)
require.NotContains(t, messages[2].Content, "https://example.com/old")
}
@@ -79,3 +79,20 @@ func TestBuildFallbackMessages_AttachesImagesToUserTurn(t *testing.T) {
withVision := buildFallbackMessages(cm, "fallback")
assert.Equal(t, cm.Images, withVision[len(withVision)-1].Images)
}
func TestPrepareFallbackMessagesMigratesHistoricalCitations(t *testing.T) {
cm := &types.ChatManage{}
cm.Query = "follow-up"
cm.History = []*types.History{{
Query: "previous",
Answer: `Previous <kb doc="Legacy" chunk_id="legacy-chunk" kb_id="legacy-kb" />`,
}}
messages, refs := prepareFallbackMessages(cm, "legacy fallback prompt")
require.Contains(t, messages[0].Content, "Source reference protocol")
require.Equal(t, `Previous <ref id="c1"/>`, messages[2].Content)
require.Equal(t,
`<kb doc="Legacy" chunk_id="legacy-chunk" kb_id="legacy-kb" />`,
refs.ExpandText(`<ref id="c1"/>`),
)
}
@@ -10,6 +10,7 @@ import (
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/llmreference"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
@@ -971,7 +972,8 @@ func (s *sessionService) handleModelFallback(ctx context.Context, chatManage *ty
}
// Start streaming response
responseChan, err := chatModel.ChatStream(ctx, buildFallbackMessages(chatManage, promptContent), opt)
fallbackMessages, sourceRefs := prepareFallbackMessages(chatManage, promptContent)
responseChan, err := chatModel.ChatStream(ctx, fallbackMessages, opt)
if err != nil {
logger.Errorf(ctx, "Failed to start streaming fallback response: %v, falling back to fixed response", err)
s.handleFixedFallback(ctx, chatManage)
@@ -985,7 +987,21 @@ func (s *sessionService) handleModelFallback(ctx context.Context, chatManage *ty
}
// Start goroutine to consume stream and emit events
go s.consumeFallbackStream(ctx, chatManage, responseChan)
go s.consumeFallbackStream(ctx, chatManage, responseChan, sourceRefs)
}
func prepareFallbackMessages(
chatManage *types.ChatManage,
promptContent string,
) ([]chat.Message, *llmreference.Registry) {
messages := buildFallbackMessages(chatManage, promptContent)
refs := llmreference.NewRegistry()
if len(messages) > 0 && messages[0].Role == "system" {
messages[0].Content = strings.TrimRight(messages[0].Content, " \t\r\n") + llmreference.ProtocolPrompt
} else {
messages = append([]chat.Message{{Role: "system", Content: strings.TrimSpace(llmreference.ProtocolPrompt)}}, messages...)
}
return refs.EncodeMessages(messages), refs
}
func buildFallbackMessages(chatManage *types.ChatManage, promptContent string) []chat.Message {
@@ -1118,15 +1134,21 @@ func (s *sessionService) consumeFallbackStream(
ctx context.Context,
chatManage *types.ChatManage,
responseChan <-chan types.StreamResponse,
sourceRefs *llmreference.Registry,
) {
fallbackID := generateEventID("fallback")
eventBus := chatManage.EventBus
var finalContent string
streamCompleted := false
refExpander := llmreference.NewStreamExpander(sourceRefs)
for response := range responseChan {
// Emit event for each answer chunk
if response.ResponseType == types.ResponseTypeAnswer {
response.Content = refExpander.Feed(response.Content)
if response.Done {
response.Content += refExpander.Flush()
}
finalContent += response.Content
if err := eventBus.Emit(ctx, types.Event{
ID: fallbackID,