feat(dingtalk): enable secure multimodal image QA
This commit is contained in:
@@ -3,7 +3,7 @@ package chat
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -13,27 +13,33 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
ollamaapi "github.com/ollama/ollama/api"
|
||||
)
|
||||
|
||||
// OllamaChat 实现了基于 Ollama 的聊天
|
||||
type OllamaChat struct {
|
||||
modelName string
|
||||
modelID string
|
||||
ollamaService *ollama.OllamaService
|
||||
modelName string
|
||||
modelID string
|
||||
supportsVision bool
|
||||
ollamaService *ollama.OllamaService
|
||||
}
|
||||
|
||||
func (c *OllamaChat) SupportsImageInput() bool { return c.supportsVision }
|
||||
|
||||
// NewOllamaChat 创建 Ollama 聊天实例
|
||||
func NewOllamaChat(config *ChatConfig, ollamaService *ollama.OllamaService) (*OllamaChat, error) {
|
||||
return &OllamaChat{
|
||||
modelName: config.ModelName,
|
||||
modelID: config.ModelID,
|
||||
ollamaService: ollamaService,
|
||||
modelName: config.ModelName,
|
||||
modelID: config.ModelID,
|
||||
supportsVision: config.SupportsVision,
|
||||
ollamaService: ollamaService,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// convertMessages 转换消息格式为Ollama API格式
|
||||
func (c *OllamaChat) convertMessages(messages []Message) []ollamaapi.Message {
|
||||
// convertMessages converts messages and fails closed if any declared image
|
||||
// cannot be resolved. Silently dropping one image would change the user's input.
|
||||
func (c *OllamaChat) convertMessages(messages []Message) ([]ollamaapi.Message, error) {
|
||||
ollamaMessages := make([]ollamaapi.Message, 0, len(messages))
|
||||
for _, msg := range messages {
|
||||
msgOllama := ollamaapi.Message{
|
||||
@@ -46,47 +52,69 @@ func (c *OllamaChat) convertMessages(messages []Message) []ollamaapi.Message {
|
||||
}
|
||||
if len(msg.Images) > 0 && msg.Role == "user" {
|
||||
for _, imgURL := range msg.Images {
|
||||
if imgData := resolveImageForOllama(imgURL); imgData != nil {
|
||||
msgOllama.Images = append(msgOllama.Images, imgData)
|
||||
imgData, err := resolveImageForOllama(imgURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msgOllama.Images = append(msgOllama.Images, imgData)
|
||||
}
|
||||
}
|
||||
ollamaMessages = append(ollamaMessages, msgOllama)
|
||||
}
|
||||
return ollamaMessages
|
||||
return ollamaMessages, nil
|
||||
}
|
||||
|
||||
// resolveImageForOllama resolves an image URL into raw bytes for Ollama.
|
||||
// Handles local serving paths (/files/...), data URIs, and remote HTTP URLs.
|
||||
func resolveImageForOllama(imageURL string) ollamaapi.ImageData {
|
||||
func resolveImageForOllama(imageURL string) (ollamaapi.ImageData, error) {
|
||||
if data := resolveImageURLForOllama(imageURL); data != nil {
|
||||
return data
|
||||
return data, nil
|
||||
}
|
||||
if strings.HasPrefix(imageURL, "http://") || strings.HasPrefix(imageURL, "https://") {
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
if err := secutils.ValidateURLForSSRF(imageURL); err != nil {
|
||||
return nil, errors.New("ollama image URL is not allowed")
|
||||
}
|
||||
client := &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: secutils.SSRFSafeDialContext,
|
||||
},
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
resp, err := client.Get(imageURL)
|
||||
if err != nil {
|
||||
return nil
|
||||
return nil, errors.New("ollama image download failed")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 20*1024*1024))
|
||||
if err != nil {
|
||||
return nil
|
||||
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||
return nil, errors.New("ollama image download failed")
|
||||
}
|
||||
return data
|
||||
const maxOllamaImageBytes = 20 * 1024 * 1024
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, maxOllamaImageBytes+1))
|
||||
if err != nil {
|
||||
return nil, errors.New("ollama image download failed")
|
||||
}
|
||||
if len(data) == 0 || len(data) > maxOllamaImageBytes {
|
||||
return nil, errors.New("ollama image payload is invalid")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
return nil
|
||||
return nil, errors.New("ollama image payload is invalid")
|
||||
}
|
||||
|
||||
// buildChatRequest 构建聊天请求参数
|
||||
func (c *OllamaChat) buildChatRequest(messages []Message, opts *ChatOptions, isStream bool) *ollamaapi.ChatRequest {
|
||||
func (c *OllamaChat) buildChatRequest(messages []Message, opts *ChatOptions, isStream bool) (*ollamaapi.ChatRequest, error) {
|
||||
// 设置流式标志
|
||||
streamFlag := isStream
|
||||
|
||||
// 构建请求参数
|
||||
convertedMessages, err := c.convertMessages(messages)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chatReq := &ollamaapi.ChatRequest{
|
||||
Model: c.modelName,
|
||||
Messages: c.convertMessages(messages),
|
||||
Messages: convertedMessages,
|
||||
Stream: &streamFlag,
|
||||
Options: make(map[string]interface{}),
|
||||
}
|
||||
@@ -113,7 +141,7 @@ func (c *OllamaChat) buildChatRequest(messages []Message, opts *ChatOptions, isS
|
||||
}
|
||||
}
|
||||
|
||||
return chatReq
|
||||
return chatReq, nil
|
||||
}
|
||||
|
||||
// Chat 进行非流式聊天
|
||||
@@ -124,7 +152,10 @@ func (c *OllamaChat) Chat(ctx context.Context, messages []Message, opts *ChatOpt
|
||||
}
|
||||
|
||||
// 构建请求参数
|
||||
chatReq := c.buildChatRequest(messages, opts, false)
|
||||
chatReq, err := c.buildChatRequest(messages, opts, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 记录请求日志
|
||||
logger.GetLogger(ctx).Infof("发送聊天请求到模型 %s", c.modelName)
|
||||
@@ -134,7 +165,7 @@ func (c *OllamaChat) Chat(ctx context.Context, messages []Message, opts *ChatOpt
|
||||
var promptTokens, completionTokens int
|
||||
|
||||
// 使用 Ollama 客户端发送请求
|
||||
err := c.ollamaService.Chat(ctx, chatReq, func(resp ollamaapi.ChatResponse) error {
|
||||
err = c.ollamaService.Chat(ctx, chatReq, func(resp ollamaapi.ChatResponse) error {
|
||||
responseContent = resp.Message.Content
|
||||
// 当 Content 为空但 Thinking 有内容时(如推理模型未正确配置 thinking 参数),使用 Thinking 作为兜底
|
||||
if responseContent == "" && resp.Message.Thinking != "" {
|
||||
@@ -151,7 +182,7 @@ func (c *OllamaChat) Chat(ctx context.Context, messages []Message, opts *ChatOpt
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("聊天请求失败: %w", err)
|
||||
return nil, errors.New("ollama chat failed")
|
||||
}
|
||||
|
||||
usage := types.TokenUsage{
|
||||
@@ -180,7 +211,10 @@ func (c *OllamaChat) ChatStream(
|
||||
}
|
||||
|
||||
// 构建请求参数
|
||||
chatReq := c.buildChatRequest(messages, opts, true)
|
||||
chatReq, err := c.buildChatRequest(messages, opts, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 记录请求日志
|
||||
logger.GetLogger(ctx).Infof("发送流式聊天请求到模型 %s", c.modelName)
|
||||
@@ -193,6 +227,8 @@ func (c *OllamaChat) ChatStream(
|
||||
defer close(streamChan)
|
||||
|
||||
var thinking thinkingEmitter
|
||||
var terminalUsage *types.TokenUsage
|
||||
providerDone := false
|
||||
err := c.ollamaService.Chat(ctx, chatReq, func(resp ollamaapi.ChatResponse) error {
|
||||
// 发送思考内容(支持 Qwen3、DeepSeek 等推理模型)
|
||||
if resp.Message.Thinking != "" {
|
||||
@@ -247,32 +283,32 @@ func (c *OllamaChat) ChatStream(
|
||||
}
|
||||
|
||||
if resp.Done {
|
||||
var usage *types.TokenUsage
|
||||
providerDone = true
|
||||
if resp.PromptEvalCount > 0 || resp.EvalCount > 0 {
|
||||
usage = &types.TokenUsage{
|
||||
terminalUsage = &types.TokenUsage{
|
||||
PromptTokens: resp.PromptEvalCount,
|
||||
CompletionTokens: resp.EvalCount,
|
||||
TotalTokens: resp.PromptEvalCount + resp.EvalCount,
|
||||
}
|
||||
}
|
||||
logUsage(ctx, c.modelName, usage)
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
Usage: usage,
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("流式聊天请求失败: %v", err)
|
||||
// 发送错误响应
|
||||
if err != nil || !providerDone {
|
||||
logger.GetLogger(ctx).Error("流式聊天请求失败")
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeError,
|
||||
Content: err.Error(),
|
||||
Content: "ollama stream failed",
|
||||
Done: true,
|
||||
}
|
||||
return
|
||||
}
|
||||
logUsage(ctx, c.modelName, terminalUsage)
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
Usage: terminalUsage,
|
||||
}
|
||||
}()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user