feat(dingtalk): enable secure multimodal image QA

This commit is contained in:
姚章浩
2026-07-16 00:17:16 +08:00
parent 4022040e98
commit c9c4f0aaa5
59 changed files with 3279 additions and 429 deletions
@@ -79,8 +79,10 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
pipelineInfo(ctx, "Stream", "model_call", map[string]interface{}{
"chat_model": chatManage.ChatModelID,
})
responseChan, err := chatModel.ChatStream(ctx, chatMessages, opt)
streamCtx, streamCancel := context.WithCancel(ctx)
responseChan, err := chatModel.ChatStream(streamCtx, chatMessages, opt)
if err != nil {
streamCancel()
pipelineError(ctx, "Stream", "model_call", map[string]interface{}{
"chat_model": chatManage.ChatModelID,
"error": err.Error(),
@@ -88,6 +90,7 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
return ErrModelCall.WithError(err)
}
if responseChan == nil {
streamCancel()
pipelineError(ctx, "Stream", "model_call", map[string]interface{}{
"chat_model": chatManage.ChatModelID,
"error": "nil_channel",
@@ -105,6 +108,7 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
// The goroutine monitors ctx.Done() to avoid leaking when the context is cancelled
// and the upstream channel is not closed promptly.
go func() {
defer streamCancel()
thinkingID := fmt.Sprintf("%s-thinking", uuid.New().String()[:8])
answerID := fmt.Sprintf("%s-answer", uuid.New().String()[:8])
thinkingOpen := false
@@ -145,19 +149,20 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
if response.ResponseType == types.ResponseTypeError {
pipelineError(ctx, "Stream", "stream_error", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": response.Content,
"error": "chat completion stream failed",
})
eventBus.Emit(ctx, types.Event{
ID: fmt.Sprintf("%s-error", uuid.New().String()[:8]),
Type: types.EventType(event.EventError),
SessionID: chatManage.SessionID,
Data: event.ErrorData{
Error: response.Content,
Error: "chat completion stream failed",
Stage: "chat_completion_stream",
SessionID: chatManage.SessionID,
},
})
continue
closeThinking()
return
}
if response.ResponseType == types.ResponseTypeThinking {
@@ -190,6 +195,9 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
Done: response.Done,
},
})
if response.Done {
return
}
}
}
}
@@ -91,7 +91,14 @@ func (p *PluginQueryUnderstand) OnEvent(ctx context.Context,
}
// --- Select the appropriate model ---
rewriteModel, useImages := p.selectModel(ctx, chatManage, hasImages)
rewriteModel, useImages, selectErr := p.selectModel(ctx, chatManage, hasImages)
if selectErr != nil {
pipelineError(ctx, "QueryUnderstand", "get_visual_model", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": selectErr.Error(),
})
return &PluginError{Err: selectErr, Description: "Visual model is unavailable", ErrorType: "image_understanding_failed"}
}
if rewriteModel == nil {
pipelineError(ctx, "QueryUnderstand", "get_model", map[string]interface{}{
"session_id": chatManage.SessionID,
@@ -127,11 +134,18 @@ func (p *PluginQueryUnderstand) OnEvent(ctx context.Context,
"session_id": chatManage.SessionID,
"error": err.Error(),
})
if hasImages {
return &PluginError{Err: err, Description: "Visual model request failed", ErrorType: "image_understanding_failed"}
}
return next()
}
// --- Parse structured output ---
p.parseOutput(chatManage, response.Content)
if hasImages && !chatManage.ChatModelSupportsVision && strings.TrimSpace(chatManage.ImageDescription) == "" {
err := fmt.Errorf("visual model returned no image description")
return &PluginError{Err: err, Description: "Visual model returned no usable image description", ErrorType: "image_understanding_failed"}
}
// Persist image description asynchronously — this DB write does not affect
// the current pipeline result, so it can run in the background.
@@ -222,33 +236,43 @@ func (p *PluginQueryUnderstand) loadHistory(ctx context.Context, chatManage *typ
}
// selectModel picks the model for query understanding. When images are present
// it prefers a vision-capable model. Returns (model, useImages).
func (p *PluginQueryUnderstand) selectModel(ctx context.Context, chatManage *types.ChatManage, hasImages bool) (chat.Chat, bool) {
// it requires a vision-capable model and never falls back to text-only processing.
func (p *PluginQueryUnderstand) selectModel(ctx context.Context, chatManage *types.ChatManage, hasImages bool) (chat.Chat, bool, error) {
if hasImages {
var lastErr error
if chatManage.ChatModelSupportsVision {
m, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
if err == nil {
return m, true
if err == nil && chat.SupportsImageInput(m) {
return m, true, nil
}
pipelineWarn(ctx, "QueryUnderstand", "vision_model_fallback", map[string]interface{}{
if err == nil {
err = fmt.Errorf("configured Chat transport does not support image input")
}
lastErr = err
pipelineWarn(ctx, "QueryUnderstand", "vision_model_unavailable", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
}
if chatManage.VLMModelID != "" {
m, err := p.modelService.GetChatModel(ctx, chatManage.VLMModelID)
if err == nil {
return m, true
if err == nil && chat.SupportsImageInput(m) {
return m, true, nil
}
pipelineWarn(ctx, "QueryUnderstand", "vlm_model_fallback", map[string]interface{}{
if err == nil {
err = fmt.Errorf("configured VLM transport does not support image input")
}
lastErr = err
pipelineWarn(ctx, "QueryUnderstand", "vlm_model_unavailable", map[string]interface{}{
"session_id": chatManage.SessionID,
"vlm_model_id": chatManage.VLMModelID,
"error": err.Error(),
})
}
pipelineWarn(ctx, "QueryUnderstand", "no_vision_model", map[string]interface{}{
"session_id": chatManage.SessionID,
})
if lastErr != nil {
return nil, false, fmt.Errorf("no usable visual model: %w", lastErr)
}
return nil, false, fmt.Errorf("no visual model is configured")
}
textModelID := chatManage.ChatModelID
@@ -266,7 +290,7 @@ func (p *PluginQueryUnderstand) selectModel(ctx context.Context, chatManage *typ
"error": err.Error(),
})
if fallback, fbErr := p.modelService.GetChatModel(ctx, chatManage.ChatModelID); fbErr == nil {
return fallback, false
return fallback, false, nil
}
}
pipelineError(ctx, "QueryUnderstand", "get_model", map[string]interface{}{
@@ -274,9 +298,9 @@ func (p *PluginQueryUnderstand) selectModel(ctx context.Context, chatManage *typ
"chat_model_id": textModelID,
"error": err.Error(),
})
return nil, false
return nil, false, nil
}
return m, false
return m, false, nil
}
// buildPrompts constructs system and user prompts with placeholder replacement.
@@ -0,0 +1,54 @@
package chatpipeline
import (
"context"
"testing"
modelchat "github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type visionModelStub struct{}
func (visionModelStub) Chat(context.Context, []modelchat.Message, *modelchat.ChatOptions) (*types.ChatResponse, error) {
return nil, nil
}
func (visionModelStub) ChatStream(context.Context, []modelchat.Message, *modelchat.ChatOptions) (<-chan types.StreamResponse, error) {
return nil, nil
}
func (visionModelStub) GetModelName() string { return "test-vlm" }
func (visionModelStub) GetModelID() string { return "test-vlm" }
func (visionModelStub) SupportsImageInput() bool { return true }
type modelServiceStub struct {
interfaces.ModelService
model modelchat.Chat
}
func (s modelServiceStub) GetChatModel(context.Context, string) (modelchat.Chat, error) {
return s.model, nil
}
func TestSelectModelFailsClosedWhenImageHasNoVisualModel(t *testing.T) {
plugin := &PluginQueryUnderstand{}
manage := &types.ChatManage{PipelineRequest: types.PipelineRequest{ChatModelSupportsVision: false}}
model, useImages, err := plugin.selectModel(context.Background(), manage, true)
if err == nil || model != nil || useImages {
t.Fatalf("selectModel = model %v useImages %v err %v; want fail closed", model, useImages, err)
}
}
func TestSelectModelUsesVLMWhenChatTransportIsNotVisual(t *testing.T) {
vlm := visionModelStub{}
plugin := &PluginQueryUnderstand{modelService: modelServiceStub{model: vlm}}
manage := &types.ChatManage{PipelineRequest: types.PipelineRequest{
ChatModelSupportsVision: false,
VLMModelID: "document-parser-vlm",
}}
model, useImages, err := plugin.selectModel(context.Background(), manage, true)
if err != nil || model == nil || !useImages {
t.Fatalf("selectModel = model %v useImages %v err %v; want visual VLM fallback", model, useImages, err)
}
}