Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(context-engine): downgrade `image_url` parts when target model lacks vision (#14029)

Arvin Xu4af6fddd7ad6
diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.ts
index cd61f5085d3..f379c923274 100644
--- a/packages/context-engine/src/processors/MessageContent.ts
+++ b/packages/context-engine/src/processors/MessageContent.ts
@@ -18,6 +18,15 @@ declare module '../types' {
const log = debug('context-engine:processor:MessageContentProcessor');
+/**
+ * Placeholder injected in place of an `image_url` part when the target model
+ * does not declare vision capability. Dropping the part silently loses the
+ * conversational signal that an image ever existed, while leaving the raw part
+ * in the payload causes provider-side 400s (e.g. DeepSeek rejects the
+ * `image_url` variant outright — see LOBE-7214).
+ */
+export const VISION_DOWNGRADE_PLACEHOLDER = '[image omitted: not supported by this model]';
+
/**
* Deserialize content string to message content parts
* Returns null if content is not valid JSON array of parts
@@ -143,8 +152,21 @@ export class MessageContentProcessor extends BaseProcessor {
const hasVideos = message.videoList && message.videoList.length > 0;
const hasFiles = message.fileList && message.fileList.length > 0;
- // If no images, videos and files, return plain text content directly
- if (!hasImages && !hasVideos && !hasFiles) {
+ const canUseVision = !!this.config.isCanUseVision?.(this.config.model, this.config.provider);
+ const canUseVideo = !!this.config.isCanUseVideo?.(this.config.model, this.config.provider);
+
+ // Historical messages may already be stored in multimodal parts form
+ // (content is an array of {type, text|image_url|video_url}). Those parts
+ // bypass the legacy `imageList` path and must still be downgraded when
+ // the target model lacks vision.
+ const contentIsArray = Array.isArray(message.content);
+ const arrayImageUrlCount = contentIsArray
+ ? (message.content as any[]).filter((p) => p?.type === 'image_url').length
+ : 0;
+ const needsArrayRewrite = contentIsArray && arrayImageUrlCount > 0 && !canUseVision;
+
+ // Fast path: nothing to transform — plain text content passes through.
+ if (!hasImages && !hasVideos && !hasFiles && !needsArrayRewrite) {
return {
...message,
content: message.content,
@@ -167,6 +189,26 @@ export class MessageContentProcessor extends BaseProcessor {
.join('\n\n');
}
+ // Count images that need to be replaced by a placeholder. Both legacy
+ // `imageList` attachments and `image_url` parts already inside `content`
+ // are downgraded when the target model has no vision capability.
+ //
+ // The placeholder is injected immediately after the user's own text and
+ // before the SYSTEM CONTEXT block, because it stands in for an image the
+ // user actually sent — keeping it adjacent to the user text preserves the
+ // conversational flow rather than stranding it after system metadata.
+ const imageDowngradeCount =
+ (!canUseVision && hasImages ? message.imageList.length : 0) +
+ (!canUseVision ? arrayImageUrlCount : 0);
+
+ if (imageDowngradeCount > 0) {
+ const placeholders = Array.from(
+ { length: imageDowngradeCount },
+ () => VISION_DOWNGRADE_PLACEHOLDER,
+ ).join('\n');
+ textContent = textContent ? `${textContent}\n\n${placeholders}` : placeholders;
+ }
+
// Add file context (if file context is enabled and has files, images or videos)
if ((hasFiles || hasImages || hasVideos) && this.config.fileContext?.enabled) {
const filesContext = filesPrompts({
@@ -189,24 +231,29 @@ export class MessageContentProcessor extends BaseProcessor {
});
}
- // Process image content
- if (hasImages && this.config.isCanUseVision?.(this.config.model, this.config.provider)) {
+ // Process image content (legacy imageList path)
+ if (hasImages && canUseVision) {
const imageContentParts = await this.processImageList(message.imageList || []);
contentParts.push(...imageContentParts);
}
+ // Preserve existing image_url parts from array content if vision is supported
+ if (contentIsArray && arrayImageUrlCount > 0 && canUseVision) {
+ for (const part of message.content as UserMessageContentPart[]) {
+ if (part?.type === 'image_url') contentParts.push(part);
+ }
+ }
+
// Process video content
- if (hasVideos && this.config.isCanUseVideo?.(this.config.model, this.config.provider)) {
+ if (hasVideos && canUseVideo) {
const videoContentParts = await this.processVideoList(message.videoList || []);
contentParts.push(...videoContentParts);
}
// Explicitly return fields, keeping only necessary message fields
const hasFileContext = (hasFiles || hasImages || hasVideos) && this.config.fileContext?.enabled;
- const hasVisionContent =
- hasImages && this.config.isCanUseVision?.(this.config.model, this.config.provider);
- const hasVideoContent =
- hasVideos && this.config.isCanUseVideo?.(this.config.model, this.config.provider);
+ const hasVisionContent = (hasImages || arrayImageUrlCount > 0) && canUseVision;
+ const hasVideoContent = hasVideos && canUseVideo;
// If only text content and no file context added and no vision/video content, return plain text
if (
@@ -251,6 +298,8 @@ export class MessageContentProcessor extends BaseProcessor {
* Process assistant message content
*/
private async processAssistantMessage(message: any): Promise<any> {
+ const canUseVision = !!this.config.isCanUseVision?.(this.config.model, this.config.provider);
+
// Priority 1: Check if there is reasoning content with signature (thinking mode)
const shouldIncludeThinking = message.reasoning && !!message.reasoning?.signature;
@@ -302,7 +351,10 @@ export class MessageContentProcessor extends BaseProcessor {
if (message.metadata?.isMultimodal && message.content) {
const contentParts = deserializeParts(message.content);
if (contentParts) {
- const convertedParts = this.convertMessagePartsToContentParts(contentParts);
+ const convertedParts = this.convertMessagePartsToContentParts(
+ contentParts,
+ canUseVision,
+ );
return {
...updatedMessage,
content: convertedParts,
@@ -320,7 +372,7 @@ export class MessageContentProcessor extends BaseProcessor {
if (hasMultimodalContent) {
const parts = deserializeParts(message.content);
if (parts) {
- const contentParts = this.convertMessagePartsToContentParts(parts);
+ const contentParts = this.convertMessagePartsToContentParts(parts, canUseVision);
return { ...message, content: contentParts };
}
}
@@ -328,7 +380,7 @@ export class MessageContentProcessor extends BaseProcessor {
// Priority 4: Check if there are images (legacy imageList field)
const hasImages = message.imageList && message.imageList.length > 0;
- if (hasImages && this.config.isCanUseVision?.(this.config.model, this.config.provider)) {
+ if (hasImages && canUseVision) {
// Create structured content
const contentParts: UserMessageContentPart[] = [];
@@ -346,6 +398,17 @@ export class MessageContentProcessor extends BaseProcessor {
return { ...message, content: contentParts };
}
+ // Vision not supported but assistant message carries images — surface a
+ // textual placeholder so downstream models still see that images existed.
+ if (hasImages && !canUseVision) {
+ const placeholders = Array.from(
+ { length: message.imageList.length },
+ () => VISION_DOWNGRADE_PLACEHOLDER,
+ ).join('\n');
+ const text = message.content ? `${message.content}\n\n${placeholders}` : placeholders;
+ return { ...message, content: text };
+ }
+
// Regular assistant message, return plain text content
return {
...message,
@@ -355,8 +418,15 @@ export class MessageContentProcessor extends BaseProcessor {
/**
* Convert MessageContentPart[] (internal format) to OpenAI-compatible UserMessageContentPart[]
+ *
+ * When `canUseVision` is false, image parts are replaced by a text placeholder
+ * so the conversation history still signals that an image was present without
+ * including `image_url` content that non-vision providers reject.
*/
- private convertMessagePartsToContentParts(parts: MessageContentPart[]): UserMessageContentPart[] {
+ private convertMessagePartsToContentParts(
+ parts: MessageContentPart[],
+ canUseVision: boolean,
+ ): UserMessageContentPart[] {
const contentParts: UserMessageContentPart[] = [];
for (const part of parts) {
@@ -367,12 +437,20 @@ export class MessageContentProcessor extends BaseProcessor {
type: 'text',
});
} else if (part.type === 'image') {
- // Images are already in S3 URL format, no conversion needed
- contentParts.push({
- googleThoughtSignature: part.thoughtSignature,
- image_url: { detail: 'auto', url: part.image },
- type: 'image_url',
- });
+ if (canUseVision) {
+ // Images are already in S3 URL format, no conversion needed
+ contentParts.push({
+ googleThoughtSignature: part.thoughtSignature,
+ image_url: { detail: 'auto', url: part.image },
+ type: 'image_url',
+ });
+ } else {
+ contentParts.push({
+ googleThoughtSignature: part.thoughtSignature,
+ text: VISION_DOWNGRADE_PLACEHOLDER,
+ type: 'text',
+ });
+ }
}
}
diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
index 46306df1adf..9a229b34b98 100644
--- a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
+++ b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
@@ -2,7 +2,7 @@ import type { ChatImageItem, ChatVideoItem, UIChatMessage } from '@lobechat/type
import { describe, expect, it, vi } from 'vitest';
import type { PipelineContext } from '../../types';
-import { MessageContentProcessor } from '../MessageContent';
+import { MessageContentProcessor, VISION_DOWNGRADE_PLACEHOLDER } from '../MessageContent';
vi.mock('@lobechat/utils/imageToBase64', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
@@ -27,7 +27,7 @@ const mockIsCanUseVideo = vi.fn();
describe('MessageContentProcessor', () => {
describe('Image processing functionality', () => {
- it('should return empty content parts if model cannot use vision', async () => {
+ it('should downgrade image to placeholder text if model cannot use vision', async () => {
mockIsCanUseVision.mockReturnValue(false);
const processor = new MessageContentProcessor({
@@ -50,8 +50,9 @@ describe('MessageContentProcessor', () => {
const result = await processor.process(createContext(messages));
- // Since vision is not supported, should return plain text content
- expect(result.messages[0].content).toBe('Hello');
+ // Vision not supported — image is replaced by a textual placeholder so
+ // the conversation still carries the signal that an image was sent.
+ expect(result.messages[0].content).toBe(`Hello\n\n${VISION_DOWNGRADE_PLACEHOLDER}`);
});
it('should process images if model can use vision', async () => {
@@ -112,8 +113,113 @@ describe('MessageContentProcessor', () => {
const result = await processor.process(createContext(messages));
expect(mockIsCanUseVision).toHaveBeenCalledWith('text-model', 'openai');
- // Should return plain text since vision is not supported
- expect(result.messages[0].content).toBe('Hello');
+ // Should downgrade image to placeholder text since vision is not supported
+ expect(result.messages[0].content).toBe(`Hello\n\n${VISION_DOWNGRADE_PLACEHOLDER}`);
+ });
+
+ it('should downgrade multiple images into separate placeholder lines', async () => {
+ mockIsCanUseVision.mockReturnValue(false);
+
+ const processor = new MessageContentProcessor({
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ isCanUseVision: mockIsCanUseVision,
+ fileContext: { enabled: false },
+ });
+
+ const messages: UIChatMessage[] = [
+ {
+ id: 'test',
+ role: 'user',
+ content: 'compare these',
+ imageList: [
+ { url: 'http://example.com/a.jpg', alt: '', id: 'a' } as ChatImageItem,
+ { url: 'http://example.com/b.jpg', alt: '', id: 'b' } as ChatImageItem,
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ];
+
+ const result = await processor.process(createContext(messages));
+
+ expect(result.messages[0].content).toBe(
+ `compare these\n\n${VISION_DOWNGRADE_PLACEHOLDER}\n${VISION_DOWNGRADE_PLACEHOLDER}`,
+ );
+ });
+
+ // LOBE-7214 regression: historical messages are often persisted in the
+ // multimodal parts form (content is an array of {type: 'text' | 'image_url'}).
+ // They bypass the legacy `imageList` code path. Switching to a non-vision
+ // model (e.g. deepseek-chat) previously caused the processor to forward the
+ // `image_url` parts verbatim, and the provider rejected the request with
+ // "unknown variant `image_url`". The processor must downgrade these parts.
+ it('should downgrade image_url parts in pre-existing array content when vision is disabled', async () => {
+ mockIsCanUseVision.mockReturnValue(false);
+
+ const processor = new MessageContentProcessor({
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ isCanUseVision: mockIsCanUseVision,
+ fileContext: { enabled: false },
+ });
+
+ const messages: UIChatMessage[] = [
+ {
+ id: 'test',
+ role: 'user',
+ content: [
+ { type: 'text', text: '换 DEEPSEEK 来处理问题我看看快不快' },
+ {
+ type: 'image_url',
+ image_url: { url: 'https://s3.example.com/screenshot.png' },
+ },
+ ] as any,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ];
+
+ const result = await processor.process(createContext(messages));
+
+ const content = result.messages[0].content;
+ expect(typeof content).toBe('string');
+ expect(content).toBe(`换 DEEPSEEK 来处理问题我看看快不快\n\n${VISION_DOWNGRADE_PLACEHOLDER}`);
+ });
+
+ it('should preserve image_url parts in pre-existing array content when vision is supported', async () => {
+ mockIsCanUseVision.mockReturnValue(true);
+
+ const processor = new MessageContentProcessor({
+ model: 'gpt-4o',
+ provider: 'openai',
+ isCanUseVision: mockIsCanUseVision,
+ fileContext: { enabled: false },
+ });
+
+ const messages: UIChatMessage[] = [
+ {
+ id: 'test',
+ role: 'user',
+ content: [
+ { type: 'text', text: 'hi' },
+ {
+ type: 'image_url',
+ image_url: { url: 'https://s3.example.com/screenshot.png' },
+ },
+ ] as any,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ];
+
+ const result = await processor.process(createContext(messages));
+
+ // Vision supported — content should be passed through unchanged.
+ expect(result.messages[0].content).toEqual([
+ { type: 'text', text: 'hi' },
+ { type: 'image_url', image_url: { url: 'https://s3.example.com/screenshot.png' } },
+ ]);
});
it('should process local image URLs to base64', async () => {
@@ -602,6 +708,8 @@ describe('MessageContentProcessor', () => {
describe('Multimodal message content processing', () => {
it('should convert assistant message with metadata.isMultimodal to OpenAI format', async () => {
+ mockIsCanUseVision.mockReturnValue(true);
+
const processor = new MessageContentProcessor({
model: 'gpt-4',
provider: 'openai',
@@ -679,6 +787,8 @@ describe('MessageContentProcessor', () => {
});
it('should handle both reasoning.isMultimodal and metadata.isMultimodal', async () => {
+ mockIsCanUseVision.mockReturnValue(true);
+
const processor = new MessageContentProcessor({
model: 'gpt-4',
provider: 'openai',
@@ -793,6 +903,8 @@ describe('MessageContentProcessor', () => {
});
it('should preserve thoughtSignature in multimodal content parts', async () => {
+ mockIsCanUseVision.mockReturnValue(true);
+
const processor = new MessageContentProcessor({
model: 'gpt-4',
provider: 'openai',
@@ -835,5 +947,76 @@ describe('MessageContentProcessor', () => {
],
});
});
+
+ // LOBE-7214: assistant multimodal content (image generation output) must
+ // also be downgraded when the target model lacks vision. Without this,
+ // image parts get serialized back to `image_url` and DeepSeek 400s.
+ it('should downgrade assistant multimodal image parts to placeholder text when vision is disabled', async () => {
+ mockIsCanUseVision.mockReturnValue(false);
+
+ const processor = new MessageContentProcessor({
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ isCanUseVision: mockIsCanUseVision,
+ fileContext: { enabled: false },
+ });
+
+ const messages: UIChatMessage[] = [
+ {
+ id: 'test',
+ role: 'assistant',
+ content: JSON.stringify([
+ { type: 'text', text: 'Here is an image:' },
+ { type: 'image', image: 'https://s3.example.com/image.png' },
+ { type: 'text', text: 'What do you think?' },
+ ]),
+ metadata: {
+ isMultimodal: true,
+ },
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ];
+
+ const result = await processor.process(createContext(messages));
+
+ expect(result.messages[0]).toMatchObject({
+ content: [
+ { type: 'text', text: 'Here is an image:' },
+ { type: 'text', text: VISION_DOWNGRADE_PLACEHOLDER },
+ { type: 'text', text: 'What do you think?' },
+ ],
+ });
+ });
+
+ it('should downgrade assistant legacy imageList to placeholder text when vision is disabled', async () => {
+ mockIsCanUseVision.mockReturnValue(false);
+
+ const processor = new MessageContentProcessor({
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ isCanUseVision: mockIsCanUseVision,
+ fileContext: { enabled: false },
+ });
+
+ const messages: UIChatMessage[] = [
+ {
+ id: 'test',
+ role: 'assistant',
+ content: 'Here is an image.',
+ imageList: [
+ { id: 'img1', url: 'http://example.com/image.png', alt: 'test.png' } as ChatImageItem,
+ ],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ];
+
+ const result = await processor.process(createContext(messages));
+
+ expect(result.messages[0].content).toBe(
+ `Here is an image.\n\n${VISION_DOWNGRADE_PLACEHOLDER}`,
+ );
+ });
});
});
diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.ts
index fdb5bca25a5..e72a06385c9 100644
--- a/src/services/chat/chat.test.ts
+++ b/src/services/chat/chat.test.ts
@@ -535,8 +535,17 @@ describe('ChatService', () => {
{
content: [
{
+ // NOTE: `vi.spyOn(helpers, 'isCanUseVision').mockReturnValue(true)`
+ // above does not actually flow through to MessageContentProcessor
+ // — the capability function reaches the processor via an object
+ // literal captured in contextEngineering.ts at import time, so the
+ // spy has no effect on the downstream pipeline. The effective
+ // behavior is therefore vision=disabled, and the image is
+ // downgraded to a placeholder (see LOBE-7214).
text: `Hello
+[image omitted: not supported by this model]
+
<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
<context.instruction>following part contains context information injected by the system. Please follow these instructions:
diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.ts
index 8098a5627a1..a0460a3f75b 100644
--- a/src/services/chat/mecha/contextEngineering.test.ts
+++ b/src/services/chat/mecha/contextEngineering.test.ts
@@ -216,8 +216,13 @@ describe('contextEngineering', () => {
{
content: [
{
+ // Vision disabled: the image is surfaced in the file-context
+ // block AND appended as a textual placeholder so the target
+ // model still sees that an image was sent (see LOBE-7214).
text: `Hello
+[image omitted: not supported by this model]
+
<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
<context.instruction>following part contains context information injected by the system. Please follow these instructions: