feat: add DingTalk picture agent QA
This commit is contained in:
@@ -4,37 +4,30 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
||||
)
|
||||
|
||||
const (
|
||||
// msgTypeText is the DingTalk robot callback message type for text.
|
||||
msgTypeText = "text"
|
||||
// conversationTypeDirect is a 1:1 (direct) conversation callback.
|
||||
msgTypeText = "text"
|
||||
msgTypePicture = "picture"
|
||||
conversationTypeDirect = "1"
|
||||
// conversationTypeGroup is a group conversation callback.
|
||||
conversationTypeGroup = "2"
|
||||
conversationTypeGroup = "2"
|
||||
replyTitle = "DobotAI"
|
||||
|
||||
// replyTitle is the markdown title used for session webhook replies.
|
||||
replyTitle = "DobotAI"
|
||||
|
||||
// unsupportedMessageReply is sent for non-text messages.
|
||||
unsupportedMessageReply = "当前版本暂仅支持文字消息。"
|
||||
// qaErrorReply is sent when the QA backend fails. It must never leak
|
||||
// internal error details to end users.
|
||||
qaErrorReply = "抱歉,当前暂时无法完成回答,请稍后重试。"
|
||||
qaErrorReply = "抱歉,当前暂时无法完成回答,请稍后重试。"
|
||||
imageErrorReply = "图片识别暂时不可用,请稍后重试或发送文字。"
|
||||
imageQuery = "请描述并分析这张图片。"
|
||||
)
|
||||
|
||||
// TenantConfig identifies the tenant + channel this handler serves.
|
||||
type TenantConfig struct {
|
||||
TenantKey string
|
||||
Channel string
|
||||
}
|
||||
|
||||
// BotCallback is the decoded DingTalk robot callback payload for the
|
||||
// fields the text ingress path needs.
|
||||
type BotCallback struct {
|
||||
ConversationType string
|
||||
ConversationID string
|
||||
@@ -46,28 +39,31 @@ type BotCallback struct {
|
||||
IsInAtList bool
|
||||
SessionWebhook string
|
||||
Text string
|
||||
DownloadCode string
|
||||
}
|
||||
|
||||
// QAAsker answers questions (implemented by the QA service).
|
||||
type QAAsker interface {
|
||||
Ask(ctx context.Context, req core.QARequest) (core.QAResult, error)
|
||||
}
|
||||
|
||||
// MarkdownSender sends a markdown reply to a session webhook
|
||||
// (implemented by WebhookSender).
|
||||
type MarkdownSender interface {
|
||||
SendMarkdown(ctx context.Context, webhookURL, title, text string) error
|
||||
}
|
||||
|
||||
// Handler processes DingTalk robot callbacks synchronously.
|
||||
type Handler struct {
|
||||
cfg TenantConfig
|
||||
qa QAAsker
|
||||
reply MarkdownSender
|
||||
type ImageDownloader interface {
|
||||
Download(ctx context.Context, downloadCode string) (core.ImageInput, error)
|
||||
}
|
||||
|
||||
// NewHandler validates its dependencies and returns a Handler.
|
||||
func NewHandler(cfg TenantConfig, qa QAAsker, reply MarkdownSender) (*Handler, error) {
|
||||
type Handler struct {
|
||||
cfg TenantConfig
|
||||
qa QAAsker
|
||||
reply MarkdownSender
|
||||
downloader ImageDownloader
|
||||
}
|
||||
|
||||
// NewHandler accepts at most one image downloader. A nil/omitted downloader
|
||||
// keeps text ingress available while picture messages fail closed.
|
||||
func NewHandler(cfg TenantConfig, qa QAAsker, reply MarkdownSender, downloaders ...ImageDownloader) (*Handler, error) {
|
||||
if strings.TrimSpace(cfg.TenantKey) == "" {
|
||||
return nil, errors.New("dingtalk handler: tenant key is required")
|
||||
}
|
||||
@@ -80,78 +76,113 @@ func NewHandler(cfg TenantConfig, qa QAAsker, reply MarkdownSender) (*Handler, e
|
||||
if reply == nil {
|
||||
return nil, errors.New("dingtalk handler: markdown sender is required")
|
||||
}
|
||||
return &Handler{cfg: cfg, qa: qa, reply: reply}, nil
|
||||
if len(downloaders) > 1 {
|
||||
return nil, errors.New("dingtalk handler: at most one image downloader is allowed")
|
||||
}
|
||||
var downloader ImageDownloader
|
||||
if len(downloaders) == 1 {
|
||||
downloader = downloaders[0]
|
||||
}
|
||||
return &Handler{cfg: cfg, qa: qa, reply: reply, downloader: downloader}, nil
|
||||
}
|
||||
|
||||
// Handle processes a single bot callback synchronously and returns nil
|
||||
// once any required reply has been sent (or the message was silently
|
||||
// ignored). No goroutines are spawned.
|
||||
func (h *Handler) Handle(ctx context.Context, cb BotCallback) error {
|
||||
// Group messages that do not @ the bot are silently ignored.
|
||||
// Admission comes first: a group message without @ must have zero side effects.
|
||||
if cb.ConversationType == conversationTypeGroup && !cb.IsInAtList {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Non-text messages never reach QA; reply with the unsupported notice.
|
||||
if cb.Msgtype != msgTypeText {
|
||||
if strings.TrimSpace(cb.SessionWebhook) == "" {
|
||||
return errors.New("dingtalk handler: sessionWebhook is required to reply")
|
||||
}
|
||||
return h.reply.SendMarkdown(ctx, cb.SessionWebhook, replyTitle, unsupportedMessageReply)
|
||||
// Validate the only reply destination before downloading media or spending a
|
||||
// model call. Webhook errors never include its query string.
|
||||
webhookURL := strings.TrimSpace(cb.SessionWebhook)
|
||||
if webhookURL == "" {
|
||||
return errors.New("dingtalk handler: sessionWebhook is required to reply")
|
||||
}
|
||||
|
||||
query := strings.TrimSpace(cb.Text)
|
||||
if query == "" {
|
||||
return errors.New("dingtalk handler: text message content is empty")
|
||||
if err := ValidateWebhookURL(webhookURL); err != nil {
|
||||
return fmt.Errorf("dingtalk handler: invalid sessionWebhook: %w", err)
|
||||
}
|
||||
if cb.MsgID == "" {
|
||||
if strings.TrimSpace(cb.MsgID) == "" {
|
||||
return errors.New("dingtalk handler: msgId is required")
|
||||
}
|
||||
|
||||
externalUserID := cb.SenderStaffID
|
||||
externalUserID := strings.TrimSpace(cb.SenderStaffID)
|
||||
if externalUserID == "" {
|
||||
externalUserID = cb.SenderID
|
||||
externalUserID = strings.TrimSpace(cb.SenderID)
|
||||
}
|
||||
if externalUserID == "" {
|
||||
return errors.New("dingtalk handler: sender staffId/senderId is required")
|
||||
}
|
||||
|
||||
// The session webhook is the only reply channel; fail fast before
|
||||
// calling QA so a missing webhook never wastes a model call.
|
||||
if strings.TrimSpace(cb.SessionWebhook) == "" {
|
||||
return errors.New("dingtalk handler: sessionWebhook is required to reply")
|
||||
}
|
||||
|
||||
req := core.QARequest{
|
||||
TenantKey: h.cfg.TenantKey,
|
||||
Channel: h.cfg.Channel,
|
||||
ExternalUserID: externalUserID,
|
||||
ExternalMessageID: cb.MsgID,
|
||||
ExternalMessageID: strings.TrimSpace(cb.MsgID),
|
||||
SenderName: cb.SenderNick,
|
||||
Query: query,
|
||||
}
|
||||
switch cb.ConversationType {
|
||||
case conversationTypeGroup:
|
||||
if cb.ConversationID == "" {
|
||||
if strings.TrimSpace(cb.ConversationID) == "" {
|
||||
return errors.New("dingtalk handler: conversationId is required for group messages")
|
||||
}
|
||||
req.ConversationType = core.ConversationGroup
|
||||
req.ExternalChatID = cb.ConversationID
|
||||
req.ExternalChatID = strings.TrimSpace(cb.ConversationID)
|
||||
default:
|
||||
req.ConversationType = core.ConversationDirect
|
||||
}
|
||||
|
||||
switch strings.ToLower(strings.TrimSpace(cb.Msgtype)) {
|
||||
case msgTypeText:
|
||||
req.Query = strings.TrimSpace(cb.Text)
|
||||
if req.Query == "" {
|
||||
return errors.New("dingtalk handler: text message content is empty")
|
||||
}
|
||||
case msgTypePicture:
|
||||
if strings.TrimSpace(cb.DownloadCode) == "" {
|
||||
log.Printf("DingTalk image preparation failed: stage=missing_download_code")
|
||||
return h.sendReply(ctx, webhookURL, imageErrorReply)
|
||||
}
|
||||
if h.downloader == nil {
|
||||
log.Printf("DingTalk image preparation failed: stage=downloader_unavailable")
|
||||
return h.sendReply(ctx, webhookURL, imageErrorReply)
|
||||
}
|
||||
image, err := h.downloader.Download(ctx, strings.TrimSpace(cb.DownloadCode))
|
||||
if err != nil {
|
||||
log.Printf("DingTalk image preparation failed: stage=%s", imageFailureStage(err))
|
||||
return h.sendReply(ctx, webhookURL, imageErrorReply)
|
||||
}
|
||||
req.Query = imageQuery
|
||||
req.Images = []core.ImageInput{image}
|
||||
default:
|
||||
return h.sendReply(ctx, webhookURL, unsupportedMessageReply)
|
||||
}
|
||||
|
||||
result, err := h.qa.Ask(ctx, req)
|
||||
if err != nil {
|
||||
// Never leak internal error details to the user. If the friendly
|
||||
// reply cannot be delivered, surface that failure instead.
|
||||
if replyErr := h.sendReply(ctx, cb.SessionWebhook, qaErrorReply); replyErr != nil {
|
||||
if replyErr := h.sendReply(ctx, webhookURL, qaErrorReply); replyErr != nil {
|
||||
return replyErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return h.sendReply(ctx, webhookURL, result.Answer)
|
||||
}
|
||||
|
||||
return h.sendReply(ctx, cb.SessionWebhook, result.Answer)
|
||||
func imageFailureStage(err error) string {
|
||||
message := strings.ToLower(err.Error())
|
||||
switch {
|
||||
case strings.Contains(message, "oauth"):
|
||||
return "oauth"
|
||||
case strings.Contains(message, "api"):
|
||||
return "file_api"
|
||||
case strings.Contains(message, "unsafe") || strings.Contains(message, "destination"):
|
||||
return "unsafe_url"
|
||||
case strings.Contains(message, "format") || strings.Contains(message, "image data") || strings.Contains(message, "dimensions") || strings.Contains(message, "size limit"):
|
||||
return "image_validation"
|
||||
case strings.Contains(message, "request") || strings.Contains(message, "http") || strings.Contains(message, "read"):
|
||||
return "image_fetch"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) sendReply(ctx context.Context, webhookURL, text string) error {
|
||||
|
||||
Reference in New Issue
Block a user