feat: implement image upload and multimodal support

- Added functionality for image uploads in chat, allowing users to attach images for multimodal Q&A.
- Enhanced the input field to handle image selection via drag-and-drop and paste, with validation for file types and sizes.
- Updated the backend to process images alongside text queries, including support for image analysis.
- Introduced new UI components for image previews and management, improving user interaction with uploaded content.
- Added localization strings for image upload features and error messages, enhancing accessibility for users in multiple languages.

These changes significantly improve the chat experience by enabling users to incorporate images into their queries, facilitating richer interactions and responses.
This commit is contained in:
wizardchen
2026-03-11 17:17:32 +08:00
parent 8de1cfb6b5
commit 991bd29a14
42 changed files with 1554 additions and 226 deletions
+1
View File
@@ -46,6 +46,7 @@ type Message struct {
Name string `json:"name,omitempty"` // Function/tool name (for tool role)
ToolCallID string `json:"tool_call_id,omitempty"` // Tool call ID (for tool role)
ToolCalls []ToolCall `json:"tool_calls,omitempty"` // Tool calls (for assistant role)
Images []string `json:"images,omitempty"` // Image URLs for multimodal (only for current user message)
}
// ToolCall represents a tool call in a message
+82
View File
@@ -0,0 +1,82 @@
package chat
import (
"encoding/base64"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
)
// resolveImageURLForLLM converts stored image paths to a format that LLM APIs can consume.
// - data: URIs and http(s):// URLs are returned as-is.
// - local:// paths are read from disk and converted to base64 data URIs.
func resolveImageURLForLLM(imageURL string) string {
if strings.HasPrefix(imageURL, "data:") || strings.HasPrefix(imageURL, "http://") || strings.HasPrefix(imageURL, "https://") {
return imageURL
}
if strings.HasPrefix(imageURL, "local://") {
data := readLocalStorageBytes(imageURL)
if data != nil {
mime := http.DetectContentType(data)
return fmt.Sprintf("data:%s;base64,%s", mime, base64.StdEncoding.EncodeToString(data))
}
}
return imageURL
}
// resolveImageURLForOllama converts stored image paths to raw bytes for the Ollama API.
func resolveImageURLForOllama(imageURL string) []byte {
if strings.HasPrefix(imageURL, "data:") {
idx := strings.Index(imageURL, ";base64,")
if idx < 0 {
return nil
}
decoded, err := base64.StdEncoding.DecodeString(imageURL[idx+8:])
if err != nil {
return nil
}
return decoded
}
if strings.HasPrefix(imageURL, "local://") {
return readLocalStorageBytes(imageURL)
}
return nil
}
// readLocalStorageBytes resolves a local:// storage path to disk bytes.
func readLocalStorageBytes(storagePath string) []byte {
relPath := strings.TrimPrefix(storagePath, "local://")
baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR")
if baseDir == "" {
baseDir = "/data/files"
}
localPath := filepath.Join(baseDir, filepath.FromSlash(relPath))
data, err := os.ReadFile(localPath)
if err != nil {
return nil
}
return data
}
// isMultimodalNotSupportedError checks if an error indicates the model does not
// support multimodal/image input.
func isMultimodalNotSupportedError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
return (strings.Contains(msg, "multimodal") || strings.Contains(msg, "image") || strings.Contains(msg, "vision")) &&
(strings.Contains(msg, "not support") || strings.Contains(msg, "unsupported") || strings.Contains(msg, "400"))
}
// stripImagesFromMessages returns a copy of messages with all image data removed.
func stripImagesFromMessages(messages []Message) []Message {
cleaned := make([]Message, len(messages))
for i, msg := range messages {
cleaned[i] = msg
cleaned[i].Images = nil
}
return cleaned
}
+33
View File
@@ -4,7 +4,11 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
@@ -40,11 +44,40 @@ func (c *OllamaChat) convertMessages(messages []Message) []ollamaapi.Message {
if msg.Role == "tool" {
msgOllama.ToolName = msg.Name
}
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)
}
}
}
ollamaMessages = append(ollamaMessages, msgOllama)
}
return ollamaMessages
}
// 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 {
if data := resolveImageURLForOllama(imageURL); data != nil {
return data
}
if strings.HasPrefix(imageURL, "http://") || strings.HasPrefix(imageURL, "https://") {
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Get(imageURL)
if err != nil {
return nil
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, 20*1024*1024))
if err != nil {
return nil
}
return data
}
return nil
}
// buildChatRequest 构建聊天请求参数
func (c *OllamaChat) buildChatRequest(messages []Message, opts *ChatOptions, isStream bool) *ollamaapi.ChatRequest {
// 设置流式标志
+37 -5
View File
@@ -12,6 +12,7 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/provider"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/sashabaranov/go-openai"
)
@@ -75,7 +76,22 @@ func (c *RemoteAPIChat) ConvertMessages(messages []Message) []openai.ChatComplet
Role: msg.Role,
}
if msg.Content != "" {
if len(msg.Images) > 0 && msg.Role == "user" {
parts := []openai.ChatMessagePart{
{Type: openai.ChatMessagePartTypeText, Text: msg.Content},
}
for _, imgURL := range msg.Images {
resolved := resolveImageURLForLLM(imgURL)
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: resolved,
Detail: openai.ImageURLDetailAuto,
},
})
}
openaiMsg.MultiContent = parts
} else if msg.Content != "" {
openaiMsg.Content = msg.Content
}
@@ -180,7 +196,7 @@ func (c *RemoteAPIChat) BuildChatCompletionRequest(messages []Message, opts *Cha
// logRequest 记录请求日志
func (c *RemoteAPIChat) logRequest(ctx context.Context, req any, isStream bool) {
if jsonData, err := json.MarshalIndent(req, "", " "); err == nil {
logger.Infof(ctx, "[LLM Request] model=%s, stream=%v, request:\n%s", c.modelName, isStream, string(jsonData))
logger.Infof(ctx, "[LLM Request] model=%s, stream=%v, request:\n%s", c.modelName, isStream, secutils.CompactImageDataURLForLog(string(jsonData)))
}
}
@@ -208,7 +224,15 @@ func (c *RemoteAPIChat) Chat(ctx context.Context, messages []Message, opts *Chat
resp, err := c.client.CreateChatCompletion(ctx, req)
if err != nil {
return nil, fmt.Errorf("create chat completion: %w", err)
if isMultimodalNotSupportedError(err) {
logger.Warnf(ctx, "[LLM Request] Model %s does not support multimodal, retrying without images", c.modelName)
cleaned := stripImagesFromMessages(messages)
req = c.BuildChatCompletionRequest(cleaned, opts, false)
resp, err = c.client.CreateChatCompletion(ctx, req)
}
if err != nil {
return nil, fmt.Errorf("create chat completion: %w", err)
}
}
return c.parseCompletionResponse(&resp)
@@ -344,8 +368,16 @@ func (c *RemoteAPIChat) ChatStream(ctx context.Context, messages []Message, opts
stream, err := c.client.CreateChatCompletionStream(ctx, req)
if err != nil {
close(streamChan)
return nil, fmt.Errorf("create chat completion stream: %w", err)
if isMultimodalNotSupportedError(err) {
logger.Warnf(ctx, "[LLM Stream] Model %s does not support multimodal, retrying without images", c.modelName)
cleaned := stripImagesFromMessages(messages)
req = c.BuildChatCompletionRequest(cleaned, opts, true)
stream, err = c.client.CreateChatCompletionStream(ctx, req)
}
if err != nil {
close(streamChan)
return nil, fmt.Errorf("create chat completion stream: %w", err)
}
}
go c.processStream(ctx, stream, streamChan)
+3 -3
View File
@@ -13,9 +13,9 @@ import (
)
const (
defaultTimeout = 30 * time.Second
defaultMaxToks = 5000
defaultTemp = float32(0.1)
defaultTimeout = 90 * time.Second
defaultMaxToks = 5000
defaultTemp = float32(0.1)
)
// RemoteAPIVLM implements VLM via an OpenAI-compatible chat completions API.