feat(dingtalk): support image questions with vision models

This commit is contained in:
姚章浩
2026-07-15 13:54:34 +08:00
parent 9645de64a1
commit 1b0b0fb8ed
7 changed files with 498 additions and 25 deletions
+92 -4
View File
@@ -3,11 +3,14 @@ package im
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"regexp"
"strings"
@@ -483,12 +486,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 +506,62 @@ func buildIMQARequest(
UserMessageID: userMessageID,
WebSearchEnabled: webSearchEnabled,
QuotedContext: quotedContext,
ImageURLs: images,
}
}
const maxIMImageBytes = 10 << 20
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", "image/gif", "image/webp":
default:
return fmt.Errorf("unsupported image content type %q", contentType)
}
msg.FileName = fileName
msg.ImageURLs = []string{"data:" + contentType + ";base64," + base64.StdEncoding.EncodeToString(data)}
referenceID := strings.TrimSpace(msg.MessageID)
if referenceID == "" {
referenceID = "unknown"
}
msg.ImageReferences = types.MessageImages{{
URL: string(msg.Platform) + "://message/" + url.PathEscape(referenceID),
Caption: fileName,
}}
if strings.TrimSpace(msg.Content) == "" {
msg.Content = "请识别这张图片的内容,并回答图片中的问题。"
}
return nil
}
func auditImageURLs(audit *imMessageAuditContext) []string {
if audit == nil {
return nil
}
return append([]string(nil), audit.imageURLs...)
}
func buildIMLastRequestState(agentID string, customAgent *types.CustomAgent, kbIDs []string) *types.SessionLastRequestState {
state := &types.SessionLastRequestState{
AgentID: agentID,
@@ -529,6 +590,8 @@ type imMessageAuditContext struct {
chatID string
threadID string
knowledgeBaseIDs types.MessageKnowledgeBaseIDs
imageReferences types.MessageImages
imageURLs []string
}
func newIMMessageAuditContext(msg *IncomingMessage, channelID string, kbIDs []string) *imMessageAuditContext {
@@ -544,6 +607,8 @@ func newIMMessageAuditContext(msg *IncomingMessage, channelID string, kbIDs []st
audit.userID = msg.UserID
audit.chatID = msg.ChatID
audit.threadID = msg.ThreadID
audit.imageReferences = append(types.MessageImages(nil), msg.ImageReferences...)
audit.imageURLs = append([]string(nil), msg.ImageURLs...)
return audit
}
@@ -571,6 +636,9 @@ func createIMUserMessagePayload(sessionID, content, requestID string, audit *imM
Channel: "im",
}
applyIMMessageAudit(message, audit)
if audit != nil {
message.Images = append(types.MessageImages(nil), audit.imageReferences...)
}
return message
}
@@ -1293,7 +1361,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
// ── 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 != "" {
if msg.MessageType == MessageTypeFile && channel.KnowledgeBaseID != "" {
return s.handleFileMessage(ctx, msg, adapter, channel)
}
@@ -1301,7 +1369,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
// 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) {
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: "当前渠道未配置文件知识库,无法处理图片/文件消息。请在渠道设置中配置文件知识库后再发送,或直接用文字描述您的问题。",
@@ -1337,6 +1405,26 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
}
}
if msg.MessageType == MessageTypeImage {
if customAgent == nil || !customAgent.Config.ImageUploadEnabled {
if channel.KnowledgeBaseID != "" {
return s.handleFileMessage(ctx, msg, adapter, channel)
}
return adapter.SendReply(ctx, msg, &ReplyMessage{
Content: "当前机器人未启用图片识别,请在智能体设置中开启图片上传并配置视觉模型。",
IsFinal: true,
})
}
downloader, ok := adapter.(FileDownloader)
if !ok {
return adapter.SendReply(ctx, msg, &ReplyMessage{Content: "当前钉钉渠道暂不支持图片下载。", IsFinal: true})
}
if err := prepareIMImageForQA(sessionCtx, msg, downloader); err != nil {
logger.Warnf(ctx, "[IM] Failed to prepare image for QA: %v", err)
return adapter.SendReply(ctx, msg, &ReplyMessage{Content: "图片下载或格式校验失败,请发送10MB以内的 JPG、PNG、GIF 或 WebP 图片。", IsFinal: true})
}
}
// ── Slash-command dispatch ──
// Commands are handled before the QA pipeline so they respond instantly.
if cmd, args, ok := s.cmdRegistry.Parse(msg.Content); ok {
@@ -2193,7 +2281,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))
}
@@ -2428,7 +2516,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, auditImageURLs(audit))
if req.QuotedContext != "" {
logger.Debugf(ctx, "[IM] QuotedContext set: length=%d", len(req.QuotedContext))
}