From b66552749d6af17b41c66f1f79cf31f617606977 Mon Sep 17 00:00:00 2001 From: nullkey Date: Wed, 1 Apr 2026 22:43:36 +0800 Subject: [PATCH] fix(im): anti-hallucination for non-text quotes and unprocessable media messages - Replace content placeholders with LLM instructions for non-text quotes (NonTextType field) - Intercept image/file messages on channels without KB config - Wrap text quotes in XML tags with escape sanitization - Add nil safety to isQuoteFromBot, move debug logging to callers with real ctx - Improve reply copy to guide users toward channel KB configuration --- internal/im/adapter.go | 7 +++- internal/im/service.go | 59 ++++++++++++++++++++++----- internal/im/service_quote_test.go | 27 +++++++++--- internal/im/wecom/longconn.go | 4 +- internal/im/wecom/quote.go | 37 ++++++++--------- internal/im/wecom/quote_test.go | 68 +++++++++++++++++++++++++------ 6 files changed, 151 insertions(+), 51 deletions(-) diff --git a/internal/im/adapter.go b/internal/im/adapter.go index a82b61d4..e35eb6e8 100644 --- a/internal/im/adapter.go +++ b/internal/im/adapter.go @@ -83,12 +83,17 @@ type IncomingMessage struct { type QuotedMessage struct { // MessageID is the platform message ID of the quoted message. MessageID string - // Content is the text content (or placeholder like "[图片]" for non-text). + // Content is the text content. Empty for non-text message types. Content string // SenderID is the platform user ID of the quoted message's author. SenderID string // IsBotMessage indicates whether the quoted message was from the bot. IsBotMessage bool + // NonTextType records the original message type when the quoted message + // has no extractable text (e.g. "image", "file", "video"). + // Empty when Content is populated. Used to generate LLM instructions + // instead of content placeholders that cause hallucination. + NonTextType string } // ChatType represents the IM chat type. diff --git a/internal/im/service.go b/internal/im/service.go index 96accd60..3c693df0 100644 --- a/internal/im/service.go +++ b/internal/im/service.go @@ -162,10 +162,31 @@ func makeUserKey(channelID, userID, chatID, threadID string) string { return fmt.Sprintf("%s:%s:%s", channelID, userID, chatID) } +// nonTextTypeLabel maps a message type to a Chinese label for LLM instructions. +var nonTextTypeLabel = map[string]string{ + "image": "图片", + "file": "文件", + "video": "视频", + "voice": "语音", +} + // formatQuotedContext formats a QuotedMessage into a labeled string for LLM context. -// Returns empty string if quote is nil or has no content. +// Returns empty string if quote is nil. +// For non-text quotes, generates an instruction telling the LLM to acknowledge +// the unprocessable content instead of a placeholder that causes hallucination. func formatQuotedContext(quote *QuotedMessage) string { - if quote == nil || quote.Content == "" { + if quote == nil { + return "" + } + // Non-text quote: generate instruction, not content placeholder. + if quote.NonTextType != "" { + label := nonTextTypeLabel[quote.NonTextType] + if label == "" { + label = "该类型的" + } + return "用户引用了一条" + label + "消息,但你无法查看该内容。请直接告知用户你目前无法处理" + label + "消息,建议用户用文字描述问题。不要猜测该消息的内容。" + } + if quote.Content == "" { return "" } content := quote.Content @@ -173,11 +194,13 @@ func formatQuotedContext(quote *QuotedMessage) string { if len(runes) > maxQuoteContentLength { content = string(runes[:maxQuoteContentLength]) + "..." } - label := "[被引用的消息]" + // Prevent quoted content from escaping the XML tag boundary. + content = strings.ReplaceAll(content, "", "") + label := "以下是用户引用的一条历史消息,仅作为上下文参考:" if quote.IsBotMessage { - label = "[引用的机器人回复]" + label = "以下是用户引用的你(机器人)之前的回复,仅作为上下文参考:" } - return label + "\n" + content + return label + "\n\n" + content + "\n" } func buildIMQARequest( @@ -194,11 +217,6 @@ func buildIMQARequest( // so we derive it from the agent config (the single source of truth). webSearchEnabled := customAgent != nil && customAgent.Config.WebSearchEnabled quotedContext := formatQuotedContext(quote) - if quotedContext != "" { - // Note: using context.Background() because buildIMQARequest is a pure function without ctx. - // This debug log won't carry trace/span IDs — acceptable for a debug-level log. - logger.Debugf(context.Background(), "[IM] QuotedContext set: length=%d", len(quotedContext)) - } return &types.QARequest{ Session: session, Query: query, @@ -827,6 +845,21 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann return s.handleFileMessage(ctx, msg, adapter, channel) } + // ── Non-text message without text content ── + // If the message is an image/file/video but has no text content, the QA pipeline + // cannot do anything useful (no vision support in IM yet). Sending an empty query + // to KB retrieval would return irrelevant results and cause hallucination. + if msg.Content == "" && (msg.MessageType == MessageTypeImage || msg.MessageType == MessageTypeFile) { + logger.Infof(ctx, "[IM] Skipping QA for non-text message without content: type=%s", msg.MessageType) + if err := adapter.SendReply(ctx, msg, &ReplyMessage{ + Content: "当前渠道未配置文件知识库,无法处理图片/文件消息。请在渠道设置中配置文件知识库后再发送,或直接用文字描述您的问题。", + IsFinal: true, + }); err != nil { + logger.Warnf(ctx, "[IM] Failed to send non-text hint reply: %v", err) + } + return nil + } + // 1. Get tenant tenant, err := s.tenantService.GetTenantByID(ctx, tenantID) if err != nil { @@ -1589,6 +1622,9 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage, go func() { var err error req := buildIMQARequest(session, msg.Content, assistantMsg.ID, userMsg.ID, customAgent, kbIDs, msg.Quote) + if req.QuotedContext != "" { + logger.Debugf(qaCtx, "[IM] QuotedContext set: length=%d", len(req.QuotedContext)) + } if useAgent { err = s.sessionService.AgentQA(qaCtx, req, eventBus) } else { @@ -1779,6 +1815,9 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin go func() { var err error req := buildIMQARequest(session, query, assistantMsg.ID, userMsg.ID, customAgent, kbIDs, quote) + if req.QuotedContext != "" { + logger.Debugf(ctx, "[IM] QuotedContext set: length=%d", len(req.QuotedContext)) + } if useAgent { err = s.sessionService.AgentQA(ctx, req, eventBus) } else { diff --git a/internal/im/service_quote_test.go b/internal/im/service_quote_test.go index 67269156..bacb7551 100644 --- a/internal/im/service_quote_test.go +++ b/internal/im/service_quote_test.go @@ -18,19 +18,34 @@ func TestFormatQuotedContext(t *testing.T) { want: "", }, { - name: "empty content", + name: "empty content no NonTextType", quote: &QuotedMessage{Content: ""}, want: "", }, + { + name: "non-text image quote generates instruction", + quote: &QuotedMessage{NonTextType: "image"}, + want: "用户引用了一条图片消息,但你无法查看该内容。请直接告知用户你目前无法处理图片消息,建议用户用文字描述问题。不要猜测该消息的内容。", + }, + { + name: "non-text file quote generates instruction", + quote: &QuotedMessage{NonTextType: "file"}, + want: "用户引用了一条文件消息,但你无法查看该内容。请直接告知用户你目前无法处理文件消息,建议用户用文字描述问题。不要猜测该消息的内容。", + }, + { + name: "non-text unknown type uses fallback label", + quote: &QuotedMessage{NonTextType: "location"}, + want: "用户引用了一条该类型的消息,但你无法查看该内容。请直接告知用户你目前无法处理该类型的消息,建议用户用文字描述问题。不要猜测该消息的内容。", + }, { name: "bot message", quote: &QuotedMessage{Content: "bot reply text", IsBotMessage: true}, - want: "[引用的机器人回复]\nbot reply text", + want: "以下是用户引用的你(机器人)之前的回复,仅作为上下文参考:\n\nbot reply text\n", }, { name: "user message", quote: &QuotedMessage{Content: "user message text", IsBotMessage: false}, - want: "[被引用的消息]\nuser message text", + want: "以下是用户引用的一条历史消息,仅作为上下文参考:\n\nuser message text\n", }, { name: "truncation at 500 runes", @@ -38,7 +53,7 @@ func TestFormatQuotedContext(t *testing.T) { Content: string(make([]rune, 600)), IsBotMessage: false, }, - want: "[被引用的消息]\n" + string(make([]rune, 500)) + "...", + want: "以下是用户引用的一条历史消息,仅作为上下文参考:\n\n" + string(make([]rune, 500)) + "...\n", }, } @@ -74,7 +89,7 @@ func TestBuildIMQARequest_QuotedContext(t *testing.T) { if req.Query != "follow up" { t.Errorf("Query = %q, want %q", req.Query, "follow up") } - want := "[引用的机器人回复]\nbot reply" + want := "以下是用户引用的你(机器人)之前的回复,仅作为上下文参考:\n\nbot reply\n" if req.QuotedContext != want { t.Errorf("QuotedContext = %q, want %q", req.QuotedContext, want) } @@ -83,7 +98,7 @@ func TestBuildIMQARequest_QuotedContext(t *testing.T) { t.Run("user quote sets QuotedContext with user label", func(t *testing.T) { quote := &QuotedMessage{Content: "user msg", IsBotMessage: false} req := buildIMQARequest(session, "question", "a1", "u1", nil, nil, quote) - want := "[被引用的消息]\nuser msg" + want := "以下是用户引用的一条历史消息,仅作为上下文参考:\n\nuser msg\n" if req.QuotedContext != want { t.Errorf("QuotedContext = %q, want %q", req.QuotedContext, want) } diff --git a/internal/im/wecom/longconn.go b/internal/im/wecom/longconn.go index d6734895..c8bda37e 100644 --- a/internal/im/wecom/longconn.go +++ b/internal/im/wecom/longconn.go @@ -573,8 +573,8 @@ func (c *LongConnClient) handleCallback(ctx context.Context, frame wsFrame) { if incoming != nil && msg.Quote != nil { incoming.Quote = buildQuotedMessage(msg.Quote, msg.AiBotID) if incoming.Quote != nil { - logger.Infof(ctx, "[WeCom] Quote detected: msgid=%s sender=%s is_bot=%v content_len=%d", - msg.Quote.MsgID, msg.Quote.From.UserID, incoming.Quote.IsBotMessage, len(incoming.Quote.Content)) + logger.Infof(ctx, "[WeCom] Quote detected: msgid=%s sender=%s is_bot=%v content_len=%d non_text_type=%s", + msg.Quote.MsgID, msg.Quote.From.UserID, incoming.Quote.IsBotMessage, len(incoming.Quote.Content), incoming.Quote.NonTextType) // Debug: log raw IDs for bot identity verification during initial rollout logger.Debugf(ctx, "[WeCom] Quote identity debug: quote.from.userid=%q quote.aibotid=%q msg.aibotid=%q", msg.Quote.From.UserID, msg.Quote.AiBotID, msg.AiBotID) diff --git a/internal/im/wecom/quote.go b/internal/im/wecom/quote.go index a8a27ac5..03f9687f 100644 --- a/internal/im/wecom/quote.go +++ b/internal/im/wecom/quote.go @@ -7,7 +7,9 @@ import ( ) // extractQuoteContent extracts text content from a quoted botMessage. -// For non-text message types, returns a descriptive placeholder. +// Only returns actual textual content. Non-text types (image, file, video, etc.) +// return empty string so that buildQuotedMessage discards them — injecting +// "cannot see image" placeholders causes LLM hallucination from conversation history. func extractQuoteContent(quote *botMessage) string { if quote == nil { return "" @@ -16,34 +18,28 @@ func extractQuoteContent(quote *botMessage) string { case "text": return quote.Text.Content case "voice": - if quote.Voice.Content != "" { - return quote.Voice.Content - } - return "[语音消息]" + return quote.Voice.Content // STT result; empty if recognition failed case "mixed": + // Only keep text parts; skip images/other non-text items entirely. var parts []string for _, item := range quote.Mixed.MsgItem { if item.MsgType == "text" && item.Text.Content != "" { parts = append(parts, item.Text.Content) - } else if item.MsgType == "image" { - parts = append(parts, "[图片]") } } return strings.Join(parts, "\n") - case "image": - return "[图片]" - case "file": - return "[文件]" - case "video": - return "[视频]" default: - return "[消息]" + // image, file, video, unknown — no textual content available, discard. + return "" } } // isQuoteFromBot determines whether a quoted message was sent by the bot. // Uses two comparison strategies since WeCom's field mapping is undocumented. func isQuoteFromBot(quote *botMessage, aiBotID string) bool { + if quote == nil { + return false + } if quote.From.UserID != "" && aiBotID != "" && quote.From.UserID == aiBotID { return true } @@ -54,19 +50,22 @@ func isQuoteFromBot(quote *botMessage, aiBotID string) bool { } // buildQuotedMessage constructs a QuotedMessage from a botMessage quote. -// Returns nil if the quote is nil or has no extractable content. +// Returns nil only if quote itself is nil. +// For non-text quotes (image, file, video), Content is empty and NonTextType +// is set so downstream can generate an LLM instruction instead of a placeholder. func buildQuotedMessage(quote *botMessage, aiBotID string) *im.QuotedMessage { if quote == nil { return nil } content := extractQuoteContent(quote) - if content == "" { - return nil - } - return &im.QuotedMessage{ + result := &im.QuotedMessage{ MessageID: quote.MsgID, Content: content, SenderID: quote.From.UserID, IsBotMessage: isQuoteFromBot(quote, aiBotID), } + if content == "" { + result.NonTextType = quote.MsgType + } + return result } diff --git a/internal/im/wecom/quote_test.go b/internal/im/wecom/quote_test.go index 742bb6a5..ce58031c 100644 --- a/internal/im/wecom/quote_test.go +++ b/internal/im/wecom/quote_test.go @@ -28,30 +28,30 @@ func TestExtractQuoteContent(t *testing.T) { { name: "voice without STT content", msg: &botMessage{MsgType: "voice"}, - want: "[语音消息]", + want: "", }, { - name: "image", + name: "image returns empty (discarded to prevent hallucination)", msg: &botMessage{MsgType: "image"}, - want: "[图片]", + want: "", }, { - name: "file", + name: "file returns empty", msg: &botMessage{MsgType: "file"}, - want: "[文件]", + want: "", }, { - name: "video", + name: "video returns empty", msg: &botMessage{MsgType: "video"}, - want: "[视频]", + want: "", }, { - name: "unknown type", + name: "unknown type returns empty", msg: &botMessage{MsgType: "location"}, - want: "[消息]", + want: "", }, { - name: "mixed text and image", + name: "mixed text and image keeps only text", msg: &botMessage{ MsgType: "mixed", Mixed: struct{ MsgItem []botMixedItem `json:"msg_item"` }{ @@ -62,10 +62,10 @@ func TestExtractQuoteContent(t *testing.T) { }, }, }, - want: "part1\n[图片]\npart2", + want: "part1\npart2", }, { - name: "mixed with only images", + name: "mixed with only images returns empty", msg: &botMessage{ MsgType: "mixed", Mixed: struct{ MsgItem []botMixedItem `json:"msg_item"` }{ @@ -74,7 +74,7 @@ func TestExtractQuoteContent(t *testing.T) { }, }, }, - want: "[图片]", + want: "", }, } @@ -95,6 +95,12 @@ func TestIsQuoteFromBot(t *testing.T) { aiBotID string want bool }{ + { + name: "nil quote", + quote: nil, + aiBotID: "bot123", + want: false, + }, { name: "matching from.userid", quote: &botMessage{From: struct{ UserID string `json:"userid"` }{UserID: "bot123"}, AiBotID: ""}, @@ -162,6 +168,42 @@ func TestBuildQuotedMessage(t *testing.T) { if !got.IsBotMessage { t.Error("IsBotMessage = false, want true") } + if got.NonTextType != "" { + t.Errorf("NonTextType = %q, want empty for text quote", got.NonTextType) + } + }) + + t.Run("image quote sets NonTextType", func(t *testing.T) { + msg := &botMessage{ + MsgID: "msg-img", + MsgType: "image", + From: struct{ UserID string `json:"userid"` }{UserID: "user456"}, + } + got := buildQuotedMessage(msg, "bot1") + if got == nil { + t.Fatal("expected non-nil for image quote") + } + if got.Content != "" { + t.Errorf("Content = %q, want empty", got.Content) + } + if got.NonTextType != "image" { + t.Errorf("NonTextType = %q, want %q", got.NonTextType, "image") + } + }) + + t.Run("video quote sets NonTextType", func(t *testing.T) { + msg := &botMessage{ + MsgID: "msg-vid", + MsgType: "video", + From: struct{ UserID string `json:"userid"` }{UserID: "user456"}, + } + got := buildQuotedMessage(msg, "bot1") + if got == nil { + t.Fatal("expected non-nil for video quote") + } + if got.NonTextType != "video" { + t.Errorf("NonTextType = %q, want %q", got.NonTextType, "video") + } }) t.Run("user quote is not bot", func(t *testing.T) {