🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: normalize multimodal fallback image formats (#18851)
YuTengjing0387dc58082e
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.tsindex 1785c9c32ec..53bbd515a0a 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts@@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type { ToolExecutionContext } from '../../types';const mockToolsEnv = vi.hoisted(() => ({+ MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS: ['image/png', 'image/jpeg'],MULTIMODAL_UNDERSTANDING_MODEL: undefined as string | undefined,MULTIMODAL_UNDERSTANDING_PROVIDER: undefined as string | undefined,}));@@ -14,6 +15,7 @@ const mockMessageModelQuery = vi.hoisted(() => vi.fn());const mockChat = vi.hoisted(() => vi.fn());const mockInitModelRuntimeFromDB = vi.hoisted(() => vi.fn());const mockConsumeStreamUntilDone = vi.hoisted(() => vi.fn());+const mockImageUrlToBase64 = vi.hoisted(() => vi.fn());const mockSharpOptions = vi.hoisted(() => vi.fn());const mockBuiltinModels = vi.hoisted(() => [{@@ -70,6 +72,11 @@ vi.mock('@lobechat/model-runtime', () => ({consumeStreamUntilDone: (...args: any[]) => mockConsumeStreamUntilDone(...args),}));+vi.mock('@lobechat/utils', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ imageUrlToBase64: (...args: unknown[]) => mockImageUrlToBase64(...args),+}));+vi.mock('@/business/client/model-bank/loadModels', () => ({loadModels: vi.fn().mockResolvedValue(mockBuiltinModels),}));@@ -119,6 +126,7 @@ describe('lobeAgentRuntime', () => {beforeEach(() => {vi.clearAllMocks();mockMessageModelQuery.mockResolvedValue([]);+ mockToolsEnv.MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS = ['image/png', 'image/jpeg'];mockToolsEnv.MULTIMODAL_UNDERSTANDING_MODEL = 'vision-model';mockToolsEnv.MULTIMODAL_UNDERSTANDING_PROVIDER = 'test-provider';mockChat.mockImplementation(async (_payload, options) => {@@ -128,6 +136,116 @@ describe('lobeAgentRuntime', () => {});mockInitModelRuntimeFromDB.mockResolvedValue({ chat: mockChat });mockConsumeStreamUntilDone.mockResolvedValue(undefined);+ mockImageUrlToBase64.mockResolvedValue({+ base64: VALID_PNG_BASE64,+ mimeType: 'image/png',+ });+ });++ it('should transcode unsupported images before calling the multimodal model', async () => {+ const { default: sharp } = await import('sharp');+ const avifBuffer = await sharp({+ create: {+ background: { alpha: 1, b: 0, g: 0, r: 255 },+ channels: 4,+ height: 1,+ width: 1,+ },+ })+ .avif()+ .toBuffer();+ mockImageUrlToBase64.mockResolvedValueOnce({+ base64: avifBuffer.toString('base64'),+ mimeType: 'image/avif',+ });+ const runtime = lobeAgentRuntime.factory(baseContext);+ const imageUrl = 'https://example.com/image.avif?signature=example';++ const result = await runtime.analyzeMedia({+ question: 'what is this?',+ urls: [imageUrl],+ });++ expect(result.success).toBe(true);+ expect(mockImageUrlToBase64).toHaveBeenCalledWith(imageUrl);+ const [payload] = mockChat.mock.calls[0];+ const imagePart = payload.messages[0].content.find(+ (part: { type: string }) => part.type === 'image_url',+ );+ expect(imagePart.image_url.url).toMatch(/^data:image\/png;base64,/);++ const convertedBuffer = Buffer.from(imagePart.image_url.url.split(',')[1], 'base64');+ await expect(sharp(convertedBuffer).metadata()).resolves.toMatchObject({ format: 'png' });+ });++ it('should flatten transparent images onto white when transcoding to JPEG', async () => {+ const { default: sharp } = await import('sharp');+ const transparentWebp = await sharp({+ create: {+ background: { alpha: 0, b: 0, g: 0, r: 0 },+ channels: 4,+ height: 1,+ width: 1,+ },+ })+ .webp({ lossless: true })+ .toBuffer();+ mockToolsEnv.MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS = ['image/jpeg', 'image/png'];+ mockImageUrlToBase64.mockResolvedValueOnce({+ base64: transparentWebp.toString('base64'),+ mimeType: 'image/webp',+ });+ const runtime = lobeAgentRuntime.factory(baseContext);++ const result = await runtime.analyzeMedia({+ question: 'what is this?',+ urls: ['https://example.com/transparent.webp'],+ });++ expect(result.success).toBe(true);+ const [payload] = mockChat.mock.calls[0];+ const imagePart = payload.messages[0].content.find(+ (part: { type: string }) => part.type === 'image_url',+ );+ expect(imagePart.image_url.url).toMatch(/^data:image\/jpeg;base64,/);++ const convertedBuffer = Buffer.from(imagePart.image_url.url.split(',')[1], 'base64');+ const pixel = await sharp(convertedBuffer).raw().toBuffer();+ expect([...pixel.subarray(0, 3)]).toEqual([255, 255, 255]);+ });++ it('should detect suffixless images after downloading without transcoding supported formats', async () => {+ const runtime = lobeAgentRuntime.factory(baseContext);++ const result = await runtime.analyzeMedia({+ question: 'what is this?',+ urls: ['https://example.com/image'],+ });++ expect(result.success).toBe(true);+ expect(mockImageUrlToBase64).toHaveBeenCalledWith('https://example.com/image');+ expect(mockSharpOptions).not.toHaveBeenCalled();+ const [payload] = mockChat.mock.calls[0];+ const imagePart = payload.messages[0].content.find(+ (part: { type: string }) => part.type === 'image_url',+ );+ expect(imagePart.image_url.url).toBe(VALID_PNG_DATA_URL);+ });++ it('should fail before calling the multimodal model when image preparation fails', async () => {+ mockImageUrlToBase64.mockRejectedValueOnce(new Error('download failed'));+ const runtime = lobeAgentRuntime.factory(baseContext);++ const result = await runtime.analyzeMedia({+ question: 'what is this?',+ urls: ['https://example.com/image.avif'],+ });++ expect(result).toMatchObject({+ error: { code: 'MULTIMODAL_IMAGE_PREPARATION_FAILED' },+ success: false,+ });+ expect(mockChat).not.toHaveBeenCalled();});it('should have the correct identifier', () => {@@ -249,6 +367,7 @@ describe('lobeAgentRuntime', () => {}),}),);+ expect(mockImageUrlToBase64).not.toHaveBeenCalled();});it('should pass workspaceId when initializing multimodal model runtime', async () => {@@ -346,9 +465,6 @@ describe('lobeAgentRuntime', () => {});expect(result.success).toBe(true);- expect(mockSharpOptions).toHaveBeenCalledWith(- expect.objectContaining({ failOn: 'error', limitInputPixels: 25_000_000 }),- );expect(mockMessageModelQueryByIds).not.toHaveBeenCalled();expect(mockChat).toHaveBeenCalledWith(expect.objectContaining({diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.tsindex c50de4e033f..f9fc32324cf 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts@@ -30,6 +30,7 @@ import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { FileService } from '@/server/services/file';import type { ToolExecutionContext } from '../types';+import { normalizeMultimodalImageItems } from './lobeAgentImage';import { createServerPlanRuntimeService } from './lobeAgentPlan';import type { ServerRuntimeRegistration } from './types';@@ -59,7 +60,6 @@ const buildError = (content: string, code: string): BuiltinServerRuntimeOutput =const BASE64_CONTENT_PATTERN = /^[A-Z\d+/]+={0,2}$/i;const MAX_INLINE_IMAGE_PIXELS = 25_000_000;-/*** Decode inline images before the provider boundary. Protocol and header checks* are insufficient because a PNG can retain a valid signature while its pixel@@ -91,7 +91,10 @@ const findInvalidInlineImageIndexes = async (urls: string[]) => {try {const buffer = Buffer.from(base64, 'base64');- await sharp(buffer, { failOn: 'error', limitInputPixels: MAX_INLINE_IMAGE_PIXELS }).stats();+ await sharp(buffer, {+ failOn: 'error',+ limitInputPixels: MAX_INLINE_IMAGE_PIXELS,+ }).stats();} catch {invalidIndexes.push(index + 1);}@@ -413,13 +416,31 @@ class LobeAgentExecutionRuntime {);}+ let modelItems = selectedItems;+ if (hasImages) {+ try {+ modelItems = await normalizeMultimodalImageItems(+ selectedItems,+ toolsEnv.MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS,+ );+ } catch (error) {+ console.error('Failed to prepare images for multimodal understanding:', {+ name: error instanceof Error ? error.name : 'UnknownError',+ });+ return buildError(+ 'Failed to prepare one or more images for the configured multimodal understanding model.',+ 'MULTIMODAL_IMAGE_PREPARATION_FAILED',+ );+ }+ }+let content = '';let usage: unknown;const runtime = await initModelRuntimeFromDB(this.db, this.userId, provider, this.workspaceId);const payload = {messages: [{- content: buildAnalyzeMediaContent(selectedItems, params.question),+ content: buildAnalyzeMediaContent(modelItems, params.question),role: 'user' as const,},],diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgentImage.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgentImage.tsnew file mode 100644index 00000000000..43898fc1a89--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgentImage.ts@@ -0,0 +1,97 @@+import type { MediaFileItem } from '@lobechat/builtin-tool-lobe-agent';+import { imageUrlToBase64 } from '@lobechat/utils';+import { parseDataUri } from '@lobechat/utils/uriParser';+import mime from 'mime';++const SHARP_FORMAT_BY_MIME_TYPE = {+ 'image/jpeg': 'jpeg',+ 'image/png': 'png',+ 'image/webp': 'webp',+} as const;++type MultimodalImageMimeType = keyof typeof SHARP_FORMAT_BY_MIME_TYPE;++const normalizeMimeType = (mimeType?: string | null) => {+ const normalized = mimeType?.toLowerCase();+ return normalized === 'image/jpg' ? 'image/jpeg' : normalized;+};++const getDeclaredMimeType = (uri: string) => {+ if (/^data:image\//i.test(uri)) {+ return normalizeMimeType(parseDataUri(uri).mimeType);+ }++ try {+ return normalizeMimeType(mime.getType(new URL(uri).pathname));+ } catch {+ return undefined;+ }+};++const readImage = async (uri: string) => {+ if (/^data:image\//i.test(uri)) {+ const { base64, mimeType, type } = parseDataUri(uri);+ if (type !== 'base64' || !base64) throw new TypeError('Invalid inline image data');++ return { base64, buffer: Buffer.from(base64, 'base64'), mimeType: normalizeMimeType(mimeType) };+ }++ const { base64, mimeType } = await imageUrlToBase64(uri);+ return { base64, buffer: Buffer.from(base64, 'base64'), mimeType: normalizeMimeType(mimeType) };+};++/** Transcode images, using white for alpha pixels because JPEG cannot preserve transparency. */+const transcodeImage = async (buffer: Buffer, targetMimeType: MultimodalImageMimeType) => {+ const { default: sharp } = await import('sharp');+ const image = sharp(buffer).rotate();++ if (targetMimeType === 'image/jpeg') image.flatten({ background: '#fff' });++ return image.toFormat(SHARP_FORMAT_BY_MIME_TYPE[targetMimeType]).toBuffer();+};++/** Convert only image formats that the configured visual fallback does not accept. */+export const normalizeMultimodalImageItems = async (+ items: MediaFileItem[],+ supportedFormats: MultimodalImageMimeType[],+) => {+ const supportedFormatSet = new Set(supportedFormats);+ const targetMimeType = supportedFormats[0];+ if (!targetMimeType) throw new TypeError('At least one multimodal image format is required');++ const normalizedItems: MediaFileItem[] = [];++ for (const item of items) {+ if (item.type !== 'image') {+ normalizedItems.push(item);+ continue;+ }++ const declaredMimeType = getDeclaredMimeType(item.uri);+ if (declaredMimeType && supportedFormatSet.has(declaredMimeType as MultimodalImageMimeType)) {+ normalizedItems.push(item);+ continue;+ }++ const source = await readImage(item.uri);+ if (+ !declaredMimeType &&+ source.mimeType &&+ supportedFormatSet.has(source.mimeType as MultimodalImageMimeType)+ ) {+ normalizedItems.push({+ ...item,+ uri: `data:${source.mimeType};base64,${source.base64}`,+ });+ continue;+ }++ const converted = await transcodeImage(source.buffer, targetMimeType);+ normalizedItems.push({+ ...item,+ uri: `data:${targetMimeType};base64,${converted.toString('base64')}`,+ });+ }++ return normalizedItems;+};diff --git a/docs/self-hosting/environment-variables/basic.mdx b/docs/self-hosting/environment-variables/basic.mdxindex 24dcb26e2f4..a2471bff302 100644--- a/docs/self-hosting/environment-variables/basic.mdx+++ b/docs/self-hosting/environment-variables/basic.mdx@@ -249,11 +249,19 @@ SSRF_ALLOW_IP_ADDRESS_LIST=192.168.1.100,10.0.0.50- Default: -- Example: `gemini-2.5-flash` or your local multimodal model ID+### `MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS`++- Type: Optional+- Description: Comma-separated image formats accepted by the fallback multimodal understanding model. Supported values are `jpeg`, `png`, `webp`, or their MIME types. The image format is inferred from the URL extension when available; unsupported formats are converted to the first configured format before being sent to the model. URLs without a recognizable extension are downloaded to detect their format.+- Default: `jpeg,png`+- Example: `png,jpeg,webp`+Configuration example:```bashMULTIMODAL_UNDERSTANDING_PROVIDER=googleMULTIMODAL_UNDERSTANDING_MODEL=gemini-2.5-flash+MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS=png,jpeg,webp```For migration compatibility, `VISUAL_UNDERSTANDING_PROVIDER` and `VISUAL_UNDERSTANDING_MODEL` remain supported as legacy aliases. When both old and new variables are set, `MULTIMODAL_UNDERSTANDING_*` takes precedence.diff --git a/docs/self-hosting/environment-variables/basic.zh-CN.mdx b/docs/self-hosting/environment-variables/basic.zh-CN.mdxindex f78852f95e2..aeedf198d0d 100644--- a/docs/self-hosting/environment-variables/basic.zh-CN.mdx+++ b/docs/self-hosting/environment-variables/basic.zh-CN.mdx@@ -242,11 +242,19 @@ SSRF_ALLOW_IP_ADDRESS_LIST=192.168.1.100,10.0.0.50- 默认值:-- 示例:`gemini-2.5-flash` 或你的本地多模态模型 ID+### `MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS`++- 类型:可选+- 描述:兜底多模态理解模型支持的图片格式,使用英文逗号分隔。可填写 `jpeg`、`png`、`webp` 或对应的 MIME 类型。系统优先根据 URL 后缀判断格式;不支持的格式会在发送给模型前转换为列表中的第一个格式。URL 没有可识别的后缀时,系统会下载图片后识别格式。+- 默认值:`jpeg,png`+- 示例:`png,jpeg,webp`+配置示例:```bashMULTIMODAL_UNDERSTANDING_PROVIDER=googleMULTIMODAL_UNDERSTANDING_MODEL=gemini-2.5-flash+MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS=png,jpeg,webp```为兼容迁移,旧环境变量 `VISUAL_UNDERSTANDING_PROVIDER` 和 `VISUAL_UNDERSTANDING_MODEL` 仍可继续使用。同时配置新旧变量时,`MULTIMODAL_UNDERSTANDING_*` 优先。diff --git a/packages/env/src/__tests__/tools.test.ts b/packages/env/src/__tests__/tools.test.tsindex 01b918f730d..f3f5e8fc244 100644--- a/packages/env/src/__tests__/tools.test.ts+++ b/packages/env/src/__tests__/tools.test.ts@@ -2,6 +2,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const multimodalEnvKeys = [+ 'MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS','MULTIMODAL_UNDERSTANDING_MODEL','MULTIMODAL_UNDERSTANDING_PROVIDER','VISUAL_UNDERSTANDING_MODEL',@@ -18,6 +19,26 @@ describe('getToolsConfig', () => {for (const key of multimodalEnvKeys) delete process.env[key];});+ it('should use safe default image formats for multimodal understanding', async () => {+ const { getToolsConfig } = await import('../tools');+ const config = getToolsConfig();++ expect(config.MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS).toEqual(['image/jpeg', 'image/png']);+ });++ it('should normalize configured multimodal image formats', async () => {+ process.env.MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS = ' png, image/jpeg, jpg, image/webp, PNG ';++ const { getToolsConfig } = await import('../tools');+ const config = getToolsConfig();++ expect(config.MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS).toEqual([+ 'image/png',+ 'image/jpeg',+ 'image/webp',+ ]);+ });+it('should expose legacy visual understanding variables through the multimodal config', async () => {process.env.VISUAL_UNDERSTANDING_MODEL = 'legacy-model';process.env.VISUAL_UNDERSTANDING_PROVIDER = 'legacy-provider';diff --git a/packages/env/src/tools.ts b/packages/env/src/tools.tsindex 6c3443e7536..58d2440b8b1 100644--- a/packages/env/src/tools.ts+++ b/packages/env/src/tools.ts@@ -7,6 +7,42 @@ const optionalNumberEnv = (min: number, max: number) =>z.coerce.number().int().max(max).min(min).optional(),);+const SUPPORTED_MULTIMODAL_IMAGE_FORMATS = ['image/jpeg', 'image/png', 'image/webp'] as const;+const DEFAULT_MULTIMODAL_IMAGE_FORMATS = SUPPORTED_MULTIMODAL_IMAGE_FORMATS.slice(0, 2);+const MULTIMODAL_IMAGE_FORMAT_ALIASES: Record<+ string,+ (typeof SUPPORTED_MULTIMODAL_IMAGE_FORMATS)[number]+> = {+ 'image/jpeg': 'image/jpeg',+ 'image/jpg': 'image/jpeg',+ 'image/png': 'image/png',+ 'image/webp': 'image/webp',+ 'jpeg': 'image/jpeg',+ 'jpg': 'image/jpeg',+ 'png': 'image/png',+ 'webp': 'image/webp',+};++const multimodalImageFormatsEnv = z.preprocess(+ (value) => {+ if (typeof value !== 'string') return value;++ const formats = value+ .split(',')+ .map((format) => {+ const normalizedFormat = format.trim().toLowerCase();+ return MULTIMODAL_IMAGE_FORMAT_ALIASES[normalizedFormat] ?? normalizedFormat;+ })+ .filter(Boolean);++ return formats.length > 0 ? [...new Set(formats)] : undefined;+ },+ z+ .array(z.enum(SUPPORTED_MULTIMODAL_IMAGE_FORMATS))+ .min(1)+ .default([...DEFAULT_MULTIMODAL_IMAGE_FORMATS]),+);+export const getToolsConfig = () => {/*** Keep the visual-understanding variables as migration fallbacks while@@ -23,6 +59,7 @@ export const getToolsConfig = () => {CRAWLER_RETRY: process.env.CRAWLER_RETRY,CRAWLER_IMPLS: process.env.CRAWLER_IMPLS,JINA_USE_CN_DOMAINS: process.env.JINA_USE_CN_DOMAINS,+ MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS: process.env.MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS,SEARCH_PROVIDERS: process.env.SEARCH_PROVIDERS,SEARXNG_URL: process.env.SEARXNG_URL,TOOL_NAME_MAX_LENGTH: process.env.TOOL_NAME_MAX_LENGTH,@@ -35,6 +72,7 @@ export const getToolsConfig = () => {CRAWLER_RETRY: optionalNumberEnv(0, 3),CRAWLER_IMPLS: z.string().optional(),JINA_USE_CN_DOMAINS: z.enum(['true', 'false']).optional(),+ MULTIMODAL_UNDERSTANDING_IMAGE_FORMATS: multimodalImageFormatsEnv,SEARCH_PROVIDERS: z.string().optional(),SEARXNG_URL: z.string().url().optional(),/**