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 <quoted_message> 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
This commit is contained in:
nullkey
2026-04-01 22:43:36 +08:00
committed by lyingbug
parent dc5046ad2a
commit b66552749d
6 changed files with 151 additions and 51 deletions
+6 -1
View File
@@ -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.
+49 -10
View File
@@ -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, "</quoted_message>", "")
label := "以下是用户引用的一条历史消息,仅作为上下文参考:"
if quote.IsBotMessage {
label = "[引用的机器人回复]"
label = "以下是用户引用的你(机器人)之前的回复,仅作为上下文参考:"
}
return label + "\n" + content
return label + "\n<quoted_message>\n" + content + "\n</quoted_message>"
}
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 {
+21 -6
View File
@@ -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<quoted_message>\nbot reply text\n</quoted_message>",
},
{
name: "user message",
quote: &QuotedMessage{Content: "user message text", IsBotMessage: false},
want: "[被引用的消息]\nuser message text",
want: "以下是用户引用的一条历史消息,仅作为上下文参考:\n<quoted_message>\nuser message text\n</quoted_message>",
},
{
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<quoted_message>\n" + string(make([]rune, 500)) + "...\n</quoted_message>",
},
}
@@ -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<quoted_message>\nbot reply\n</quoted_message>"
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<quoted_message>\nuser msg\n</quoted_message>"
if req.QuotedContext != want {
t.Errorf("QuotedContext = %q, want %q", req.QuotedContext, want)
}
+2 -2
View File
@@ -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)
+18 -19
View File
@@ -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
}
+55 -13
View File
@@ -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) {