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