Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

Fix: Go chat pipeline sends image blocks to text-only models (Zhipu GLM error 1210) (#18580)

euvre6a0fe78560c0
diff --git a/internal/service/chat_pipeline.go b/internal/service/chat_pipeline.go
index aa266133d2..19d81c6b63 100644
--- a/internal/service/chat_pipeline.go
+++ b/internal/service/chat_pipeline.go
@@ -316,10 +316,12 @@ func (s *ChatPipelineService) AsyncChat(
// Parse file attachments from the last message.
// Split text-file URLs (joined with "\n\n") and image URLs.
- // Chat model: images → imageAttachments (multimodal conversion).
- // Image2text model: images → imageFiles (raw URLs).
+ // Vision (image2text) model: images → imageFiles for the multimodal
+ // conversion below. Text-only chat model: images are dropped —
+ // sending image content blocks makes such providers reject the
+ // request (e.g. Zhipu GLM error 1210: messages.content.type only
+ // allows 'text').
var textAttachmentsList []string
- var imageAttachments []string
var imageFiles []string
// Joined text attachments (appended to system prompt).
var attachments string
@@ -332,15 +334,20 @@ func (s *ChatPipelineService) AsyncChat(
modelType = mt
}
}
- if modelType == "chat" {
- textAttachmentsList, imageAttachments = splitFileAttachments(ctx, userID, files, false)
- } else {
+ if modelType == "image2text" {
textAttachmentsList, imageFiles = splitFileAttachments(ctx, userID, files, true)
+ } else {
+ var droppedImages []string
+ textAttachmentsList, droppedImages = splitFileAttachments(ctx, userID, files, false)
+ if len(droppedImages) > 0 {
+ common.Warn("AsyncChat: dropping image attachments for text-only chat model",
+ zap.String("llm_id", chat.LLMID),
+ zap.Int("dropped_images", len(droppedImages)))
+ }
}
attachments = strings.Join(textAttachmentsList, "\n\n")
common.Debug("Resolved attachments",
zap.Strings("text_attachments_list", textAttachmentsList),
- zap.Strings("image_attachments", imageAttachments),
zap.Strings("image_files", imageFiles),
zap.String("attachments", attachments))
}
@@ -932,16 +939,15 @@ func (s *ChatPipelineService) AsyncChat(
zap.Int("used_token_count", usedTokenCount),
zap.Int("msg_count", len(llmMessages)))
- // Multimodal conversion
- allImages := make([]string, 0, len(imageAttachments)+len(imageFiles))
- allImages = append(allImages, imageAttachments...)
- allImages = append(allImages, imageFiles...)
- if len(llmMessages) >= 2 && len(allImages) > 0 {
+ // Multimodal conversion. imageFiles is only populated for
+ // vision-capable (image2text) models; text-only chat models never
+ // reach this with images.
+ if len(llmMessages) >= 2 && len(imageFiles) > 0 {
lastIdx := len(llmMessages) - 1
if role, _ := llmMessages[lastIdx]["role"].(string); role == "user" {
if converted, err := common.ConvertLastUserMsgToMultimodal(
llmMessages[lastIdx],
- allImages,
+ imageFiles,
factoryName,
); err == nil {
llmMessages[lastIdx] = converted
@@ -1335,7 +1341,11 @@ func (s *ChatPipelineService) AsyncChatSolo(
factoryName = factoryFromLLMID(chat.LLMID)
}
- // 2. Process file attachments (chat → data URIs, image2text → raw URLs).
+ // 2. Process file attachments. Only vision-capable (image2text)
+ // models receive image content; text-only chat models reject image
+ // blocks at the provider (e.g. Zhipu GLM error 1210:
+ // messages.content.type only allows 'text'), so their image
+ // attachments are dropped here.
attachmentsStr := ""
var imageFiles []string
modelType := "chat"
@@ -1351,7 +1361,8 @@ func (s *ChatPipelineService) AsyncChatSolo(
if isImage2Text {
imageFiles = s.extractRawImageURLs(files)
} else {
- imageFiles = s.extractImageFiles(ctx, userID, files)
+ common.Debug("AsyncChatSolo: dropping image attachments for text-only chat model",
+ zap.String("llm_id", chat.LLMID))
}
}
}
@@ -1605,43 +1616,6 @@ func (s *ChatPipelineService) AsyncChatSolo(
return out, nil
}
-// extractImageFiles extracts data-URI image attachments from the files list.
-// Mirrors Python split_file_attachments raw mode.
-func (s *ChatPipelineService) extractImageFiles(ctx context.Context, userID string, files interface{}) []string {
- // ── File-dict mode ──
- if fileDicts, ok := parseFileDicts(files); ok {
- // Only used for GetFileContents (read-only); nil DocRemover means
- // this FileService MUST NOT be used for DeleteFiles.
- fileSvc := file.NewFileService(CheckFileTeamPermission, nil)
- // Use raw=false to get base64 data URIs for images.
- _, images, err := fileSvc.GetFileContents(ctx, userID, fileDicts, false)
- if err != nil {
- common.Warn("GetFileContents failed in extractImageFiles",
- zap.Error(err))
- return nil
- }
- return images
- }
-
- // ── String fallback ──
- var images []string
- switch v := files.(type) {
- case []string:
- for _, f := range v {
- if strings.HasPrefix(f, "data:") {
- images = append(images, f)
- }
- }
- case []interface{}:
- for _, f := range v {
- if s, ok := f.(string); ok && strings.HasPrefix(s, "data:") {
- images = append(images, s)
- }
- }
- }
- return images
-}
-
// extractRawImageURLs extracts image references as raw URLs/data-URIs from
// the string-mode files list, WITHOUT fetching blobs and WITHOUT filtering
// to data: prefixes. Used for image2text models that expect URLs in the
@@ -1862,36 +1836,44 @@ func tokenizeText(text string) string {
}
// getLLMModelConfig resolves the LLM model configuration for the chat.
-// Mirrors Python's three-branch resolver at dialog_service.py:552-561:
+// Mirrors Python's three-branch resolver at dialog_service.py:552-561,
+// extended so the tenant-default branch also probes vision capability:
//
// if chat.llm_id:
// if "image2text" in get_model_type_by_name(...): → IMAGE2TEXT
// else: → CHAT
-// else: → tenant default CHAT
+// else: → tenant default
+// (IMAGE2TEXT when the default model is vision-capable, else CHAT)
//
-// The returned `cfg` map's "model_type" field carries the chosen type
-// so downstream code (e.g. the multimodal-conversion guard in AsyncChat
-// at async_chat.go:632) can skip chat-only logic for image2text dialogs.
+// The returned `cfg` map's "model_type" field carries the chosen type.
+// Downstream code gates image attachments on it: only image2text
+// (vision-capable) models receive image content blocks; text-only chat
+// models reject them at the provider (e.g. Zhipu GLM error 1210:
+// messages.content.type only allows 'text').
func (s *ChatPipelineService) getLLMModelConfig(ctx context.Context, chat *entity.Chat) (map[string]interface{}, string, string, string, error) {
if chat.LLMID == "" {
// Branch 3: no explicit LLM → tenant default chat model.
- return s.buildLLMModelConfig(
+ cfg, modelName, factoryName, baseURL, err := s.buildLLMModelConfig(
s.ModelProviderSvc.GetTenantDefaultModelByType(ctx, chat.TenantID, entity.ModelTypeChat),
)
+ if err != nil {
+ return nil, "", "", "", err
+ }
+ // Probe the default model's enrolled types so a vision-capable
+ // default dispatches as image2text (same rule as the explicit-LLM
+ // branches below).
+ if ref, refErr := s.ModelProviderSvc.GetTenantDefaultModelRef(ctx, chat.TenantID, entity.ModelTypeChat); refErr == nil {
+ cfg["model_type"] = s.resolveChatModelType(ctx, chat.TenantID, ref)
+ }
+ return cfg, modelName, factoryName, baseURL, nil
}
// Branches 1/2: explicit LLM. Probe model types and pick IMAGE2TEXT
// when the LLM is registered as such, otherwise CHAT.
+ modelTypeStr := s.resolveChatModelType(ctx, chat.TenantID, chat.LLMID)
modelType := entity.ModelTypeChat
- modelTypeStr := "chat"
- if modelTypes, mtErr := s.ModelProviderSvc.ResolveModelType(ctx, chat.TenantID, chat.LLMID); mtErr == nil {
- for _, mt := range modelTypes {
- if mt == entity.ModelTypeImage2Text {
- modelType = entity.ModelTypeImage2Text
- modelTypeStr = "image2text"
- break
- }
- }
+ if modelTypeStr == "image2text" {
+ modelType = entity.ModelTypeImage2Text
}
cfg, modelName, factoryName, baseURL, err := s.buildLLMModelConfig(
s.ModelProviderSvc.ResolveModelConfig(ctx, chat.TenantID, modelType, chat.LLMID),
@@ -1903,6 +1885,26 @@ func (s *ChatPipelineService) getLLMModelConfig(ctx context.Context, chat *entit
return cfg, modelName, factoryName, baseURL, nil
}
+// resolveChatModelType probes the enrolled model types for llmRef and
+// returns "image2text" when the model is vision-capable (enrolled with an
+// image2text / "vision" type), "chat" otherwise. Probe failures are
+// conservative: they yield "chat", which drops image attachments instead
+// of risking a provider-side rejection.
+func (s *ChatPipelineService) resolveChatModelType(ctx context.Context, tenantID, llmRef string) string {
+ modelTypes, err := s.ModelProviderSvc.ResolveModelType(ctx, tenantID, llmRef)
+ if err != nil {
+ return "chat"
+ }
+ for _, mt := range modelTypes {
+ // ModelType is a bitmask: a model enrolled as chat+image2text
+ // reports a combined value, so test membership, not equality.
+ if mt.Has(entity.ModelTypeImage2Text) {
+ return "image2text"
+ }
+ }
+ return "chat"
+}
+
// buildLLMModelConfig collapses the (driver, modelName, apiConfig,
// _, err) tuple from a model-provider lookup into the dict-shaped
// config the rest of async_chat.go consumes. Default "model_type" is
diff --git a/internal/service/chat_pipeline_vision_test.go b/internal/service/chat_pipeline_vision_test.go
new file mode 100644
index 0000000000..c7bcb8d5e6
--- /dev/null
+++ b/internal/service/chat_pipeline_vision_test.go
@@ -0,0 +1,168 @@
+package service
+
+import (
+ "testing"
+
+ "github.com/glebarez/sqlite"
+ "gorm.io/gorm"
+
+ "ragflow/internal/dao"
+ "ragflow/internal/entity"
+)
+
+// setupChatPipelineVisionTestDB seeds an in-memory model-provider scope with
+// a ZHIPU-AI provider, a default instance, and enrolled models:
+//
+// glm-4-flash — chat only (text-only: rejects image content with error 1210)
+// glm-4v — chat + image2text, one tenant_model row per type
+// glm-4.6v-Flash — combined chat|image2text bitmask in a single row
+//
+// Enrollment rows are what getLLMModelConfig probes to decide whether image
+// attachments may be sent.
+func setupChatPipelineVisionTestDB(t *testing.T) *gorm.DB {
+ t.Helper()
+
+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{TranslateError: true})
+ if err != nil {
+ t.Fatalf("failed to open sqlite: %v", err)
+ }
+ if err := db.AutoMigrate(
+ &entity.Tenant{},
+ &entity.UserTenant{},
+ &entity.TenantModelProvider{},
+ &entity.TenantModelInstance{},
+ &entity.TenantModel{},
+ ); err != nil {
+ t.Fatalf("failed to migrate model tables: %v", err)
+ }
+
+ orig := dao.DB
+ dao.DB = db
+ t.Cleanup(func() { dao.DB = orig })
+
+ activeStatus := "1"
+ rows := []interface{}{
+ &entity.UserTenant{ID: "user-tenant-1", UserID: "user-1", TenantID: "tenant-1", Role: "owner", InvitedBy: "user-1", Status: &activeStatus},
+ &entity.TenantModelProvider{ID: "provider-zhipu", TenantID: "tenant-1", ProviderName: "ZHIPU-AI"},
+ &entity.TenantModelInstance{ID: "instance-zhipu", ProviderID: "provider-zhipu", InstanceName: "default", APIKey: "sk-test", Status: "active", Extra: "{}"},
+ &entity.TenantModel{ID: "model-flash-chat", ProviderID: "provider-zhipu", InstanceID: "instance-zhipu", ModelName: "glm-4-flash", ModelType: int(entity.ModelTypeChat), Status: "active"},
+ &entity.TenantModel{ID: "model-4v-chat", ProviderID: "provider-zhipu", InstanceID: "instance-zhipu", ModelName: "glm-4v", ModelType: int(entity.ModelTypeChat), Status: "active"},
+ &entity.TenantModel{ID: "model-4v-i2t", ProviderID: "provider-zhipu", InstanceID: "instance-zhipu", ModelName: "glm-4v", ModelType: int(entity.ModelTypeImage2Text), Status: "active"},
+ // Combined chat+image2text enrollment (bitmask), as produced for
+ // catalog entries with model_types ["chat", "vision"] (e.g. glm-4.6v-Flash).
+ &entity.TenantModel{ID: "model-46v-combined", ProviderID: "provider-zhipu", InstanceID: "instance-zhipu", ModelName: "glm-4.6v-Flash", ModelType: int(entity.ModelTypeChat | entity.ModelTypeImage2Text), Status: "active"},
+ }
+ for _, row := range rows {
+ if err := db.Create(row).Error; err != nil {
+ t.Fatalf("failed to seed %T: %v", row, err)
+ }
+ }
+ return db
+}
+
+func seedChatPipelineVisionTenant(t *testing.T, db *gorm.DB, defaultLLMID string) {
+ t.Helper()
+ status := string(entity.StatusValid)
+ if err := db.Create(&entity.Tenant{
+ ID: "tenant-1",
+ LLMID: defaultLLMID,
+ Status: &status,
+ }).Error; err != nil {
+ t.Fatalf("failed to create tenant: %v", err)
+ }
+}
+
+// A text-only chat model (glm-4-flash, enrolled as chat only) must resolve
+// to model_type "chat" so the pipeline drops image attachments instead of
+// sending image content blocks the provider rejects (Zhipu error 1210).
+func TestGetLLMModelConfig_TextOnlyModelResolvesChat(t *testing.T) {
+ db := setupChatPipelineVisionTestDB(t)
+ seedChatPipelineVisionTenant(t, db, "glm-4-flash@ZHIPU-AI")
+
+ svc := NewChatPipelineService()
+ cfg, _, _, _, err := svc.getLLMModelConfig(t.Context(), &entity.Chat{
+ TenantID: "tenant-1",
+ LLMID: "glm-4-flash@ZHIPU-AI",
+ })
+ if err != nil {
+ t.Fatalf("getLLMModelConfig() error = %v", err)
+ }
+ if got := cfg["model_type"]; got != "chat" {
+ t.Fatalf("model_type = %v, want chat for text-only model", got)
+ }
+}
+
+// A vision-capable model (glm-4v, enrolled as chat + image2text) must
+// resolve to model_type "image2text" so image attachments still reach it.
+func TestGetLLMModelConfig_VisionModelResolvesImage2Text(t *testing.T) {
+ db := setupChatPipelineVisionTestDB(t)
+ seedChatPipelineVisionTenant(t, db, "glm-4v@ZHIPU-AI")
+
+ svc := NewChatPipelineService()
+ cfg, _, _, _, err := svc.getLLMModelConfig(t.Context(), &entity.Chat{
+ TenantID: "tenant-1",
+ LLMID: "glm-4v@ZHIPU-AI",
+ })
+ if err != nil {
+ t.Fatalf("getLLMModelConfig() error = %v", err)
+ }
+ if got := cfg["model_type"]; got != "image2text" {
+ t.Fatalf("model_type = %v, want image2text for vision-capable model", got)
+ }
+}
+
+// A model enrolled as combined chat+image2text (bitmask 1|8, e.g.
+// glm-4.6v-Flash from a ["chat", "vision"] catalog entry) must still resolve
+// to "image2text" so its image inputs are kept, not silently dropped.
+func TestGetLLMModelConfig_CombinedChatAndImage2TextResolvesImage2Text(t *testing.T) {
+ db := setupChatPipelineVisionTestDB(t)
+ seedChatPipelineVisionTenant(t, db, "glm-4.6v-Flash@ZHIPU-AI")
+
+ svc := NewChatPipelineService()
+ cfg, _, _, _, err := svc.getLLMModelConfig(t.Context(), &entity.Chat{
+ TenantID: "tenant-1",
+ LLMID: "glm-4.6v-Flash@ZHIPU-AI",
+ })
+ if err != nil {
+ t.Fatalf("getLLMModelConfig() error = %v", err)
+ }
+ if got := cfg["model_type"]; got != "image2text" {
+ t.Fatalf("model_type = %v, want image2text for combined chat+image2text model", got)
+ }
+}
+
+// Branch 3 (no explicit dialog LLM): a text-only tenant default resolves to
+// "chat" so image attachments are dropped rather than rejected upstream.
+func TestGetLLMModelConfig_TenantDefaultTextOnlyResolvesChat(t *testing.T) {
+ db := setupChatPipelineVisionTestDB(t)
+ seedChatPipelineVisionTenant(t, db, "glm-4-flash@ZHIPU-AI")
+
+ svc := NewChatPipelineService()
+ cfg, _, _, _, err := svc.getLLMModelConfig(t.Context(), &entity.Chat{
+ TenantID: "tenant-1",
+ })
+ if err != nil {
+ t.Fatalf("getLLMModelConfig() error = %v", err)
+ }
+ if got := cfg["model_type"]; got != "chat" {
+ t.Fatalf("model_type = %v, want chat for text-only tenant default", got)
+ }
+}
+
+// Branch 3 (no explicit dialog LLM): a vision-capable tenant default must
+// still dispatch as image2text, otherwise its image inputs would be lost.
+func TestGetLLMModelConfig_TenantDefaultVisionResolvesImage2Text(t *testing.T) {
+ db := setupChatPipelineVisionTestDB(t)
+ seedChatPipelineVisionTenant(t, db, "glm-4v@ZHIPU-AI")
+
+ svc := NewChatPipelineService()
+ cfg, _, _, _, err := svc.getLLMModelConfig(t.Context(), &entity.Chat{
+ TenantID: "tenant-1",
+ })
+ if err != nil {
+ t.Fatalf("getLLMModelConfig() error = %v", err)
+ }
+ if got := cfg["model_type"]; got != "image2text" {
+ t.Fatalf("model_type = %v, want image2text for vision-capable tenant default", got)
+ }
+}