feat(dingtalk): enable secure multimodal image QA
This commit is contained in:
+165
-29
@@ -3,10 +3,15 @@ package im
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"os"
|
||||
"regexp"
|
||||
@@ -483,12 +488,17 @@ func buildIMQARequest(
|
||||
customAgent *types.CustomAgent,
|
||||
kbIDs []string,
|
||||
quote *QuotedMessage,
|
||||
imageURLs ...[]string,
|
||||
) *types.QARequest {
|
||||
// WebSearchEnabled: the web handler passes this per-request from the
|
||||
// frontend toggle; for IM channels the user has no per-message toggle,
|
||||
// so we derive it from the agent config (the single source of truth).
|
||||
webSearchEnabled := customAgent != nil && customAgent.Config.WebSearchEnabled
|
||||
quotedContext := formatQuotedContext(quote)
|
||||
var images []string
|
||||
if len(imageURLs) > 0 {
|
||||
images = append([]string(nil), imageURLs[0]...)
|
||||
}
|
||||
return &types.QARequest{
|
||||
Session: session,
|
||||
Query: query,
|
||||
@@ -498,9 +508,78 @@ func buildIMQARequest(
|
||||
UserMessageID: userMessageID,
|
||||
WebSearchEnabled: webSearchEnabled,
|
||||
QuotedContext: quotedContext,
|
||||
ImageURLs: images,
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
maxIMImageBytes = 10 << 20
|
||||
maxIMImageDimension = 16_384
|
||||
maxIMImagePixels = 40_000_000
|
||||
)
|
||||
|
||||
func prepareIMImageForQA(ctx context.Context, msg *IncomingMessage, downloader FileDownloader) error {
|
||||
if msg == nil || downloader == nil {
|
||||
return fmt.Errorf("image message and downloader are required")
|
||||
}
|
||||
reader, fileName, err := downloader.DownloadFile(ctx, msg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download image: %w", err)
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(reader, maxIMImageBytes+1))
|
||||
if err != nil {
|
||||
return fmt.Errorf("read image: %w", err)
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return fmt.Errorf("downloaded image is empty")
|
||||
}
|
||||
if len(data) > maxIMImageBytes {
|
||||
return fmt.Errorf("image exceeds %d MiB limit", maxIMImageBytes>>20)
|
||||
}
|
||||
contentType := strings.ToLower(http.DetectContentType(data))
|
||||
switch contentType {
|
||||
case "image/jpeg", "image/png":
|
||||
case "image/gif", "image/webp":
|
||||
return fmt.Errorf("only JPEG and PNG images are supported")
|
||||
default:
|
||||
return fmt.Errorf("unsupported image content type %q", contentType)
|
||||
}
|
||||
config, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode image metadata: %w", err)
|
||||
}
|
||||
if config.Width <= 0 || config.Height <= 0 || config.Width > maxIMImageDimension || config.Height > maxIMImageDimension || int64(config.Width)*int64(config.Height) > maxIMImagePixels {
|
||||
return fmt.Errorf("image dimensions %dx%d exceed safety limits", config.Width, config.Height)
|
||||
}
|
||||
|
||||
msg.FileName = fileName
|
||||
msg.ImageURLs = []string{"data:" + contentType + ";base64," + base64.StdEncoding.EncodeToString(data)}
|
||||
if strings.TrimSpace(msg.Content) == "" {
|
||||
msg.Content = "请识别这张图片的内容,并回答图片中的问题。"
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func imQAErrorReply(imageURLs []string) string {
|
||||
if len(imageURLs) > 0 {
|
||||
return "图片识别失败:当前模型可能不支持视觉输入,请检查智能体的图片上传开关和视觉模型配置。"
|
||||
}
|
||||
return "抱歉,处理您的问题时出现了异常,请稍后再试。"
|
||||
}
|
||||
|
||||
func allowIncrementalIMFlush(msg *IncomingMessage) bool {
|
||||
return msg == nil || len(msg.ImageURLs) == 0
|
||||
}
|
||||
|
||||
func failClosedIMImageAnswer(answer string, err error, imageURLs []string) (string, bool) {
|
||||
if err != nil && len(imageURLs) > 0 {
|
||||
return imQAErrorReply(imageURLs), true
|
||||
}
|
||||
return answer, false
|
||||
}
|
||||
|
||||
func buildIMLastRequestState(agentID string, customAgent *types.CustomAgent, kbIDs []string) *types.SessionLastRequestState {
|
||||
state := &types.SessionLastRequestState{
|
||||
AgentID: agentID,
|
||||
@@ -1232,21 +1311,17 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
||||
|
||||
logger.Infof(ctx, "[IM] HandleMessage: channel=%s platform=%s user=%s chat=%s msgtype=%s content_len=%d",
|
||||
channelID, msg.Platform, msg.UserID, msg.ChatID, msg.MessageType, len(msg.Content))
|
||||
logger.Debugf(ctx, "[IM] HandleMessage detail: msgid=%s filekey=%s filename=%s",
|
||||
msg.MessageID, msg.FileKey, msg.FileName)
|
||||
logger.Debugf(ctx, "[IM] HandleMessage detail: msgid=%s has_filekey=%t filename=%s",
|
||||
msg.MessageID, strings.TrimSpace(msg.FileKey) != "", msg.FileName)
|
||||
|
||||
// ── File/Image message shortcut ──
|
||||
// If the message is a file or image and the channel has a knowledge_base_id configured,
|
||||
// handle it separately without entering the QA pipeline.
|
||||
if (msg.MessageType == MessageTypeFile || msg.MessageType == MessageTypeImage) && channel.KnowledgeBaseID != "" {
|
||||
// Files keep the legacy knowledge-base ingestion path. Images are routed
|
||||
// below either to multimodal QA or, when vision is disabled, to this path.
|
||||
if msg.MessageType == MessageTypeFile && channel.KnowledgeBaseID != "" {
|
||||
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) {
|
||||
// Non-text files without a configured knowledge base still cannot enter QA.
|
||||
if msg.Content == "" && 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: "当前渠道未配置文件知识库,无法处理图片/文件消息。请在渠道设置中配置文件知识库后再发送,或直接用文字描述您的问题。",
|
||||
@@ -1282,6 +1357,24 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
||||
}
|
||||
}
|
||||
|
||||
if msg.MessageType == MessageTypeImage {
|
||||
if customAgent == nil || !customAgent.Config.ImageUploadEnabled {
|
||||
return adapter.SendReply(ctx, msg, &ReplyMessage{
|
||||
Content: "当前机器人未启用图片识别,请在智能体设置中开启图片上传并配置视觉模型。",
|
||||
IsFinal: true,
|
||||
})
|
||||
}
|
||||
if strings.TrimSpace(msg.FileKey) == "" {
|
||||
return adapter.SendReply(ctx, msg, &ReplyMessage{Content: "图片消息缺少有效下载凭证,请重新发送图片。", IsFinal: true})
|
||||
}
|
||||
if _, ok := adapter.(FileDownloader); !ok {
|
||||
return adapter.SendReply(ctx, msg, &ReplyMessage{Content: "当前钉钉渠道暂不支持图片下载。", IsFinal: true})
|
||||
}
|
||||
if strings.TrimSpace(msg.Content) == "" {
|
||||
msg.Content = "请识别这张图片的内容,并回答图片中的问题。"
|
||||
}
|
||||
}
|
||||
|
||||
// ── Slash-command dispatch ──
|
||||
// Commands are handled before the QA pipeline so they respond instantly.
|
||||
if cmd, args, ok := s.cmdRegistry.Parse(msg.Content); ok {
|
||||
@@ -1415,6 +1508,21 @@ func (s *Service) executeQARequest(req *qaRequest) {
|
||||
// runQA after the assistant message is created (that's when we have the
|
||||
// sessionID + messageID needed to poll StreamManager).
|
||||
|
||||
// Keep large image bytes out of the bounded queue. Download, validate and
|
||||
// encode only after this worker owns a concurrency slot.
|
||||
if req.msg.MessageType == MessageTypeImage && len(req.msg.ImageURLs) == 0 {
|
||||
downloader, ok := req.adapter.(FileDownloader)
|
||||
if !ok {
|
||||
_ = req.adapter.SendReply(ctx, req.msg, &ReplyMessage{Content: "当前钉钉渠道暂不支持图片下载。", IsFinal: true})
|
||||
return
|
||||
}
|
||||
if err := prepareIMImageForQA(ctx, req.msg, downloader); err != nil {
|
||||
logger.Warnf(ctx, "[IM] Failed to prepare image for QA: %v", err)
|
||||
_ = req.adapter.SendReply(ctx, req.msg, &ReplyMessage{Content: "图片下载或格式校验失败,请发送10MB以内的 JPG 或 PNG 图片。", IsFinal: true})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// kbIDs is left empty so the QA pipeline resolves them from the agent config.
|
||||
var kbIDs []string
|
||||
|
||||
@@ -1432,10 +1540,10 @@ func (s *Service) executeQARequest(req *qaRequest) {
|
||||
}
|
||||
|
||||
// Non-streaming fallback: collect full answer then send.
|
||||
answer, err := s.runQA(ctx, req.session, req.msg.Content, req.agent, kbIDs, req.userKey, req.msg.Quote)
|
||||
answer, err := s.runQA(ctx, req.session, req.msg.Content, req.agent, kbIDs, req.userKey, req.msg.Quote, req.msg.ImageURLs)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[IM] QA failed: %v, sending fallback reply", err)
|
||||
answer = "抱歉,处理您的问题时出现了异常,请稍后再试。"
|
||||
answer = imQAErrorReply(req.msg.ImageURLs)
|
||||
}
|
||||
|
||||
reply := &ReplyMessage{
|
||||
@@ -2132,7 +2240,7 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
|
||||
// Run QA async
|
||||
go func() {
|
||||
var err error
|
||||
req := buildIMQARequest(session, msg.Content, assistantMsg.ID, userMsg.ID, customAgent, kbIDs, msg.Quote)
|
||||
req := buildIMQARequest(session, msg.Content, assistantMsg.ID, userMsg.ID, customAgent, kbIDs, msg.Quote, msg.ImageURLs)
|
||||
if req.QuotedContext != "" {
|
||||
logger.Debugf(qaCtx, "[IM] QuotedContext set: length=%d", len(req.QuotedContext))
|
||||
}
|
||||
@@ -2158,6 +2266,9 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
|
||||
defer ticker.Stop()
|
||||
|
||||
flush := func() {
|
||||
if !allowIncrementalIMFlush(msg) {
|
||||
return
|
||||
}
|
||||
bufMu.Lock()
|
||||
parts := getStreamParts()
|
||||
agentRunning := useAgent && !agentDone
|
||||
@@ -2211,10 +2322,13 @@ loop:
|
||||
bufMu.Unlock()
|
||||
|
||||
finalDisplay := cleanIMContent(ctx, FormatIMFinalFromParts(parts), tenant, s.defaultFileSvc)
|
||||
if noVisibleContent || finalDisplay == "" {
|
||||
if replacement, override := failClosedIMImageAnswer(answer, finalErr, msg.ImageURLs); override {
|
||||
answer = replacement
|
||||
finalDisplay = replacement
|
||||
} else if noVisibleContent || finalDisplay == "" {
|
||||
fallback := "抱歉,我暂时无法回答这个问题。"
|
||||
if finalErr != nil {
|
||||
fallback = "抱歉,处理您的问题时出现了异常,请稍后再试。"
|
||||
fallback = imQAErrorReply(msg.ImageURLs)
|
||||
}
|
||||
finalDisplay = fallback
|
||||
if answer == "" {
|
||||
@@ -2222,14 +2336,7 @@ loop:
|
||||
}
|
||||
}
|
||||
|
||||
if err := streamer.FinalizeStream(ctx, msg, streamID, finalDisplay); err != nil {
|
||||
logger.Warnf(ctx, "[IM] FinalizeStream failed: %v", err)
|
||||
}
|
||||
|
||||
// End the stream
|
||||
if err := streamer.EndStream(ctx, msg, streamID); err != nil {
|
||||
logger.Warnf(ctx, "[IM] EndStream failed: %v", err)
|
||||
}
|
||||
deliveryErr := finalizeAndEndIMStream(ctx, streamer, msg, streamID, finalDisplay)
|
||||
|
||||
if answer == "" {
|
||||
answer = "抱歉,我暂时无法回答这个问题。"
|
||||
@@ -2242,28 +2349,49 @@ loop:
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[IM] Stream reply sent: platform=%s user=%s answer_len=%d", msg.Platform, msg.UserID, len(answer))
|
||||
return nil
|
||||
return deliveryErr
|
||||
}
|
||||
|
||||
func finalizeAndEndIMStream(ctx context.Context, streamer StreamSender, msg *IncomingMessage, streamID, finalDisplay string) error {
|
||||
var deliveryErr error
|
||||
if err := streamer.FinalizeStream(ctx, msg, streamID, finalDisplay); err != nil {
|
||||
logger.Warnf(ctx, "[IM] FinalizeStream failed: %v", err)
|
||||
deliveryErr = fmt.Errorf("finalize IM stream: %w", err)
|
||||
}
|
||||
|
||||
// End the stream even when finalization failed so adapter resources are released.
|
||||
if err := streamer.EndStream(ctx, msg, streamID); err != nil {
|
||||
logger.Warnf(ctx, "[IM] EndStream failed: %v", err)
|
||||
if deliveryErr == nil {
|
||||
deliveryErr = fmt.Errorf("end IM stream: %w", err)
|
||||
}
|
||||
}
|
||||
return deliveryErr
|
||||
}
|
||||
|
||||
// fallbackNonStream is used when streaming initialization fails.
|
||||
func (s *Service) fallbackNonStream(ctx context.Context, msg *IncomingMessage, session *types.Session, customAgent *types.CustomAgent, kbIDs []string, adapter Adapter, userKey string, tenant *types.Tenant) error {
|
||||
answer, err := s.runQA(ctx, session, msg.Content, customAgent, kbIDs, userKey, msg.Quote)
|
||||
answer, err := s.runQA(ctx, session, msg.Content, customAgent, kbIDs, userKey, msg.Quote, msg.ImageURLs)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[IM] QA fallback failed: %v", err)
|
||||
answer = "抱歉,处理您的问题时出现了异常,请稍后再试。"
|
||||
answer = imQAErrorReply(msg.ImageURLs)
|
||||
}
|
||||
|
||||
return adapter.SendReply(ctx, msg, &ReplyMessage{Content: formatIMOutboundAnswer(ctx, answer, tenant, s.defaultFileSvc), IsFinal: true})
|
||||
}
|
||||
|
||||
// runQA executes the WeKnora QA pipeline and returns the full answer text.
|
||||
func (s *Service) runQA(ctx context.Context, session *types.Session, query string, customAgent *types.CustomAgent, kbIDs []string, userKey string, quote *QuotedMessage) (string, error) {
|
||||
func (s *Service) runQA(ctx context.Context, session *types.Session, query string, customAgent *types.CustomAgent, kbIDs []string, userKey string, quote *QuotedMessage, imageURLs ...[]string) (string, error) {
|
||||
// Cancellable context (no hard deadline): each agent round has its own
|
||||
// LLMCallTimeout. The context can still be cancelled by /stop.
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
eventBus := event.NewEventBus()
|
||||
var images []string
|
||||
if len(imageURLs) > 0 {
|
||||
images = imageURLs[0]
|
||||
}
|
||||
|
||||
// Thread-safe answer collection
|
||||
var answerMu sync.Mutex
|
||||
@@ -2365,7 +2493,7 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
|
||||
// Run QA async
|
||||
go func() {
|
||||
var err error
|
||||
req := buildIMQARequest(session, query, assistantMsg.ID, userMsg.ID, customAgent, kbIDs, quote)
|
||||
req := buildIMQARequest(session, query, assistantMsg.ID, userMsg.ID, customAgent, kbIDs, quote, images)
|
||||
if req.QuotedContext != "" {
|
||||
logger.Debugf(ctx, "[IM] QuotedContext set: length=%d", len(req.QuotedContext))
|
||||
}
|
||||
@@ -2406,6 +2534,14 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
|
||||
qaError := qaErr
|
||||
answerMu.Unlock()
|
||||
|
||||
if replacement, override := failClosedIMImageAnswer(answer, qaError, images); override {
|
||||
assistantMsg.Content = replacement
|
||||
assistantMsg.IsCompleted = true
|
||||
if updateErr := s.messageService.UpdateMessage(ctx, assistantMsg); updateErr != nil {
|
||||
logger.Warnf(ctx, "[IM] Failed to persist image QA error: %v", updateErr)
|
||||
}
|
||||
return "", qaError
|
||||
}
|
||||
if answer == "" && qaError != nil {
|
||||
return "", qaError
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user