feat: stream answers into DingTalk AI cards
This commit is contained in:
@@ -6,8 +6,10 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/weknora"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -21,6 +23,7 @@ const (
|
||||
qaErrorReply = "抱歉,当前暂时无法完成回答,请稍后重试。"
|
||||
imageErrorReply = "图片识别暂时不可用,请稍后重试或发送文字。"
|
||||
imageQuery = "请描述并分析这张图片。"
|
||||
streamingPlaceholder = "正在处理中…"
|
||||
)
|
||||
|
||||
type TenantConfig struct {
|
||||
@@ -46,6 +49,12 @@ type QAAsker interface {
|
||||
Ask(ctx context.Context, req core.QARequest) (core.QAResult, error)
|
||||
}
|
||||
|
||||
// StreamingQAAsker asks the QA backend with streaming observer support.
|
||||
type StreamingQAAsker interface {
|
||||
QAAsker
|
||||
AskStream(ctx context.Context, req core.QARequest, observer weknora.AnswerObserver) (core.QAResult, error)
|
||||
}
|
||||
|
||||
type MarkdownSender interface {
|
||||
SendMarkdown(ctx context.Context, webhookURL, title, text string) error
|
||||
}
|
||||
@@ -60,17 +69,26 @@ type FinalCardSender interface {
|
||||
SendFinalCard(context.Context, CardRequest) (string, error)
|
||||
}
|
||||
|
||||
// StreamingCardSender supports streaming card lifecycle: start, update, and finalize.
|
||||
type StreamingCardSender interface {
|
||||
FinalCardSender
|
||||
StartCard(ctx context.Context, req CardRequest) (string, error)
|
||||
UpdateCard(ctx context.Context, id, content string, isFinalize, isError bool) error
|
||||
}
|
||||
|
||||
type HandlerOptions struct {
|
||||
ImageDownloader ImageDownloader
|
||||
CardSender FinalCardSender
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
cfg TenantConfig
|
||||
qa QAAsker
|
||||
reply MarkdownSender
|
||||
downloader ImageDownloader
|
||||
card FinalCardSender
|
||||
cfg TenantConfig
|
||||
qa QAAsker
|
||||
reply MarkdownSender
|
||||
downloader ImageDownloader
|
||||
card FinalCardSender
|
||||
now func() time.Time
|
||||
cardUpdateInterval time.Duration
|
||||
}
|
||||
|
||||
// NewHandler accepts at most one image downloader. A nil/omitted downloader
|
||||
@@ -102,7 +120,15 @@ func NewHandlerWithOptions(cfg TenantConfig, qa QAAsker, reply MarkdownSender, o
|
||||
if reply == nil {
|
||||
return nil, errors.New("dingtalk handler: markdown sender is required")
|
||||
}
|
||||
return &Handler{cfg: cfg, qa: qa, reply: reply, downloader: opts.ImageDownloader, card: opts.CardSender}, nil
|
||||
return &Handler{
|
||||
cfg: cfg,
|
||||
qa: qa,
|
||||
reply: reply,
|
||||
downloader: opts.ImageDownloader,
|
||||
card: opts.CardSender,
|
||||
now: time.Now,
|
||||
cardUpdateInterval: 750 * time.Millisecond,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) Handle(ctx context.Context, cb BotCallback) error {
|
||||
@@ -179,6 +205,27 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error {
|
||||
return h.sendReply(ctx, webhookURL, unsupportedMessageReply)
|
||||
}
|
||||
|
||||
// Check streaming capability
|
||||
streamingCard, streamingQA := h.streamingCapable()
|
||||
if streamingCard != nil && streamingQA != nil {
|
||||
return h.handleStreaming(ctx, webhookURL, req, streamingCard, streamingQA)
|
||||
}
|
||||
return h.handleNonStreaming(ctx, webhookURL, req)
|
||||
}
|
||||
|
||||
func (h *Handler) streamingCapable() (StreamingCardSender, StreamingQAAsker) {
|
||||
sc, ok := h.card.(StreamingCardSender)
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
sq, ok := h.qa.(StreamingQAAsker)
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return sc, sq
|
||||
}
|
||||
|
||||
func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req core.QARequest) error {
|
||||
result, err := h.qa.Ask(ctx, req)
|
||||
if err != nil {
|
||||
if replyErr := h.sendReply(ctx, webhookURL, qaErrorReply); replyErr != nil {
|
||||
@@ -202,6 +249,66 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error {
|
||||
return h.sendReply(ctx, webhookURL, result.Answer)
|
||||
}
|
||||
|
||||
func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req core.QARequest, streamingCard StreamingCardSender, streamingQA StreamingQAAsker) error {
|
||||
cardReq := CardRequest{
|
||||
ConversationType: req.ConversationType,
|
||||
ExternalUserID: req.ExternalUserID,
|
||||
ExternalChatID: req.ExternalChatID,
|
||||
Content: streamingPlaceholder,
|
||||
}
|
||||
outTrackID, err := streamingCard.StartCard(ctx, cardReq)
|
||||
if err != nil {
|
||||
log.Printf("DingTalk streaming card start failed, falling back to non-streaming")
|
||||
// Fallback: Ask → Markdown only (no SendFinalCard, no AskStream)
|
||||
result, askErr := h.qa.Ask(ctx, req)
|
||||
if askErr != nil {
|
||||
if replyErr := h.sendReply(ctx, webhookURL, qaErrorReply); replyErr != nil {
|
||||
return replyErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return h.sendReply(ctx, webhookURL, result.Answer)
|
||||
}
|
||||
|
||||
// Streaming observer with 750ms throttle
|
||||
var lastUpdate time.Time
|
||||
observer := func(fullContent string) {
|
||||
if strings.TrimSpace(fullContent) == "" {
|
||||
return
|
||||
}
|
||||
now := h.now()
|
||||
if lastUpdate.IsZero() || now.Sub(lastUpdate) >= h.cardUpdateInterval {
|
||||
// Advance the throttle window before I/O so a failing DingTalk API
|
||||
// cannot be hammered once per model chunk. The final update below is
|
||||
// always attempted regardless of this timestamp.
|
||||
lastUpdate = now
|
||||
if updateErr := streamingCard.UpdateCard(ctx, outTrackID, fullContent, false, false); updateErr != nil {
|
||||
log.Printf("DingTalk streaming card update failed, continuing")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result, err := streamingQA.AskStream(ctx, req, observer)
|
||||
// Final card convergence must still be attempted when the QA context was
|
||||
// canceled or timed out; otherwise the card can remain "processing"
|
||||
// forever. Keep the independent delivery window tightly bounded.
|
||||
finalCtx, cancelFinal := context.WithTimeout(context.WithoutCancel(ctx), defaultHTTPTimeout)
|
||||
defer cancelFinal()
|
||||
if err != nil || strings.TrimSpace(result.Answer) == "" {
|
||||
// Error or empty answer: converge to error card
|
||||
if updateErr := streamingCard.UpdateCard(finalCtx, outTrackID, qaErrorReply, true, true); updateErr != nil {
|
||||
return h.sendReply(finalCtx, webhookURL, qaErrorReply)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Success: finalize with answer
|
||||
if updateErr := streamingCard.UpdateCard(finalCtx, outTrackID, result.Answer, true, false); updateErr != nil {
|
||||
return h.sendReply(finalCtx, webhookURL, result.Answer)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func imageFailureStage(err error) string {
|
||||
message := strings.ToLower(err.Error())
|
||||
switch {
|
||||
|
||||
Reference in New Issue
Block a user