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(model-runtime): keep inlined images within the request size budget (#21597)

YuTengjing26e1f52d9e42
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index 908a2d60861..82a37ace59c 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -101,6 +101,7 @@ import RemoteFileUploadService, {
} from '@/services/remoteFileUploadSrv';
import { createLogger } from '@/utils/logger';
import { netFetch } from '@/utils/net-fetch';
+import { shrinkImageForUpload } from '@/utils/shrinkImageForUpload';
import { ControllerModule, IpcMethod } from './index';
@@ -511,11 +512,16 @@ export default class LocalFileCtr extends ControllerModule {
return formatUploadFailure(describeUploadFailure(error));
},
upload: async (filePath) => {
- const record = await this.app
- .getService(RemoteFileUploadService)
- .uploadLocalFile(filePath);
- if (!record?.url) logger.warn('Image upload returned no record:', { filePath });
- return record;
+ const prepared = await shrinkImageForUpload(filePath, imageMimeType);
+ try {
+ const record = await this.app
+ .getService(RemoteFileUploadService)
+ .uploadLocalFile(prepared.filePath);
+ if (!record?.url) logger.warn('Image upload returned no record:', { filePath });
+ return record;
+ } finally {
+ await prepared.cleanup();
+ }
},
});
}
diff --git a/apps/desktop/src/main/utils/__tests__/shrinkImageForUpload.test.ts b/apps/desktop/src/main/utils/__tests__/shrinkImageForUpload.test.ts
new file mode 100644
index 00000000000..6b96bcf6aca
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/shrinkImageForUpload.test.ts
@@ -0,0 +1,104 @@
+import { existsSync } from 'node:fs';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ MAX_UPLOAD_IMAGE_BYTES,
+ readJpegOrientation,
+ shrinkImageForUpload,
+} from '../shrinkImageForUpload';
+
+const { createFromBuffer } = vi.hoisted(() => ({ createFromBuffer: vi.fn() }));
+vi.mock('electron', () => ({ nativeImage: { createFromBuffer } }));
+
+/** A nativeImage stand-in whose encoded size shrinks with the resize edge. */
+const fakeImage = (width: number, height: number) => ({
+ getSize: () => ({ height, width }),
+ resize: vi.fn((size: { height?: number; width?: number }) => {
+ const edge = size.width ?? size.height ?? 0;
+ const encoded = Buffer.alloc(edge * 1000);
+ return { toJPEG: vi.fn(() => encoded), toPNG: vi.fn(() => encoded) };
+ }),
+});
+
+/** Minimal JPEG with an EXIF APP1 segment carrying `orientation` (big-endian TIFF). */
+const jpegWithOrientation = (orientation: number) => {
+ const tiff = Buffer.alloc(26);
+ tiff.write('MM', 0, 'latin1');
+ tiff.writeUInt16BE(42, 2);
+ tiff.writeUInt32BE(8, 4);
+ tiff.writeUInt16BE(1, 8);
+ tiff.writeUInt16BE(0x01_12, 10);
+ tiff.writeUInt16BE(3, 12);
+ tiff.writeUInt32BE(1, 14);
+ tiff.writeUInt16BE(orientation, 18);
+ const exif = Buffer.concat([Buffer.from('Exif\0\0', 'latin1'), tiff]);
+ const header = Buffer.alloc(4);
+ header.writeUInt16BE(0xff_e1, 0);
+ header.writeUInt16BE(exif.length + 2, 2);
+ return Buffer.concat([Buffer.from([0xff, 0xd8]), header, exif, Buffer.from([0xff, 0xda])]);
+};
+
+describe('readJpegOrientation', () => {
+ it('reads the EXIF orientation tag', () => {
+ expect(readJpegOrientation(jpegWithOrientation(6))).toBe(6);
+ });
+
+ it('defaults to 1 without EXIF', () => {
+ expect(readJpegOrientation(Buffer.from([0xff, 0xd8, 0xff, 0xda]))).toBe(1);
+ });
+});
+
+describe('shrinkImageForUpload', () => {
+ let dir: string;
+
+ beforeEach(async () => {
+ createFromBuffer.mockReset();
+ dir = await mkdtemp(path.join(tmpdir(), 'shrink-image-test-'));
+ });
+
+ afterEach(async () => {
+ await rm(dir, { force: true, recursive: true });
+ });
+
+ it('writes a smaller copy with the same file name and removes it on cleanup', async () => {
+ const filePath = path.join(dir, 'screenshot.png');
+ await writeFile(filePath, Buffer.alloc(9 * 1024 * 1024));
+ const image = fakeImage(4000, 2000);
+ createFromBuffer.mockReturnValue(image);
+
+ const prepared = await shrinkImageForUpload(filePath, 'image/png');
+
+ expect(prepared.filePath).not.toBe(filePath);
+ expect(path.basename(prepared.filePath)).toBe('screenshot.png');
+ expect(image.resize).toHaveBeenCalledWith({ quality: 'best', width: 1920 });
+ expect((await readFile(prepared.filePath)).length).toBeLessThanOrEqual(MAX_UPLOAD_IMAGE_BYTES);
+
+ await prepared.cleanup();
+ expect(existsSync(prepared.filePath)).toBe(false);
+ });
+
+ it('uploads images already within the limits as is', async () => {
+ const filePath = path.join(dir, 'small.png');
+ await writeFile(filePath, Buffer.alloc(1024));
+ createFromBuffer.mockReturnValue(fakeImage(800, 600));
+
+ expect((await shrinkImageForUpload(filePath, 'image/png')).filePath).toBe(filePath);
+ });
+
+ it('leaves rotated JPEGs to the server, which applies EXIF orientation', async () => {
+ const filePath = path.join(dir, 'photo.jpg');
+ await writeFile(filePath, jpegWithOrientation(6));
+
+ expect((await shrinkImageForUpload(filePath, 'image/jpeg')).filePath).toBe(filePath);
+ expect(createFromBuffer).not.toHaveBeenCalled();
+ });
+
+ it('skips formats nativeImage does not re-encode', async () => {
+ const filePath = path.join(dir, 'anim.gif');
+ expect((await shrinkImageForUpload(filePath, 'image/gif')).filePath).toBe(filePath);
+ });
+});
diff --git a/apps/desktop/src/main/utils/shrinkImageForUpload.ts b/apps/desktop/src/main/utils/shrinkImageForUpload.ts
new file mode 100644
index 00000000000..ea30ff8d667
--- /dev/null
+++ b/apps/desktop/src/main/utils/shrinkImageForUpload.ts
@@ -0,0 +1,101 @@
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { nativeImage } from 'electron';
+
+/** Same limits as chat uploads (`packages/utils/src/compressImage.ts`). */
+export const MAX_UPLOAD_IMAGE_EDGE = 1920;
+export const MAX_UPLOAD_IMAGE_BYTES = 3 * 1024 * 1024;
+
+const JPEG_QUALITY = 85;
+
+export interface PreparedImageUpload {
+ /** Removes the temporary copy, if one was written. */
+ cleanup: () => Promise<void>;
+ filePath: string;
+}
+
+/**
+ * EXIF orientation of a JPEG, or 1 when absent. nativeImage decodes without
+ * applying it, so re-encoding a rotated photo would bake in the wrong rotation.
+ */
+export const readJpegOrientation = (buffer: Buffer): number => {
+ if (buffer.readUInt16BE(0) !== 0xff_d8) return 1;
+ let offset = 2;
+ while (offset + 4 <= buffer.length) {
+ const marker = buffer.readUInt16BE(offset);
+ const length = buffer.readUInt16BE(offset + 2);
+ if (marker === 0xff_e1 && buffer.toString('latin1', offset + 4, offset + 10) === 'Exif\0\0') {
+ const tiff = offset + 10;
+ const little = buffer.toString('latin1', tiff, tiff + 2) === 'II';
+ const u16 = (at: number) => (little ? buffer.readUInt16LE(at) : buffer.readUInt16BE(at));
+ const u32 = (at: number) => (little ? buffer.readUInt32LE(at) : buffer.readUInt32BE(at));
+ const ifd = tiff + u32(tiff + 4);
+ const entries = u16(ifd);
+ for (let i = 0; i < entries; i++) {
+ const entry = ifd + 2 + i * 12;
+ if (u16(entry) === 0x01_12) return u16(entry + 8);
+ }
+ return 1;
+ }
+ // Start of scan: image data follows, no more metadata segments.
+ if (marker === 0xff_da) return 1;
+ offset += 2 + length;
+ }
+ return 1;
+};
+
+const keepOriginal = (filePath: string): PreparedImageUpload => ({
+ cleanup: async () => {},
+ filePath,
+});
+
+/**
+ * Shrinks a PNG or JPEG that `readFile` is about to upload to the chat upload
+ * limits, so a large local screenshot does not travel as a multi-megabyte
+ * original on every later model request. Writes the result to a temporary file
+ * with the same name; any other image, or one already within the limits, is
+ * uploaded as is.
+ */
+export const shrinkImageForUpload = async (
+ filePath: string,
+ mimeType: string,
+): Promise<PreparedImageUpload> => {
+ if (mimeType !== 'image/png' && mimeType !== 'image/jpeg') return keepOriginal(filePath);
+
+ try {
+ const source = await readFile(filePath);
+ if (mimeType === 'image/jpeg' && readJpegOrientation(source) !== 1) {
+ return keepOriginal(filePath);
+ }
+
+ const image = nativeImage.createFromBuffer(source);
+ const { width, height } = image.getSize();
+ if (!width || !height) return keepOriginal(filePath);
+
+ const longEdge = Math.max(width, height);
+ if (longEdge <= MAX_UPLOAD_IMAGE_EDGE && source.length <= MAX_UPLOAD_IMAGE_BYTES) {
+ return keepOriginal(filePath);
+ }
+
+ let edge = Math.min(longEdge, MAX_UPLOAD_IMAGE_EDGE);
+ let output: Buffer;
+ do {
+ const resized = image.resize(
+ width >= height ? { quality: 'best', width: edge } : { height: edge, quality: 'best' },
+ );
+ output = mimeType === 'image/jpeg' ? resized.toJPEG(JPEG_QUALITY) : resized.toPNG();
+ edge = Math.round(edge * 0.8);
+ } while (output.length > MAX_UPLOAD_IMAGE_BYTES && edge > 100);
+
+ if (output.length >= source.length) return keepOriginal(filePath);
+
+ const dir = await mkdtemp(path.join(tmpdir(), 'lobehub-read-image-'));
+ const target = path.join(dir, path.basename(filePath));
+ await writeFile(target, output);
+ return { cleanup: () => rm(dir, { force: true, recursive: true }), filePath: target };
+ } catch {
+ return keepOriginal(filePath);
+ }
+};
diff --git a/apps/server/src/modules/ModelRuntime/index.ts b/apps/server/src/modules/ModelRuntime/index.ts
index 9640f90359c..1037de21780 100644
--- a/apps/server/src/modules/ModelRuntime/index.ts
+++ b/apps/server/src/modules/ModelRuntime/index.ts
@@ -7,6 +7,7 @@ import {
mergeModelRuntimeHooks,
ModelRuntime,
type ModelRuntimeHooks,
+ setInlineImageNormalizer,
} from '@lobechat/model-runtime';
import { isResponsesAPIModel } from '@lobechat/model-runtime/providers/openai/modelId';
import { LobeVertexAI } from '@lobechat/model-runtime/vertexai';
@@ -40,6 +41,10 @@ import { ensureFreshOAuthToken } from '@/server/services/oauthDeviceFlow/refresh
import { KeyVaultsGateKeeper } from '../KeyVaultsEncrypt';
import apiKeyManager from './apiKeyManager';
+import { sharpInlineImageNormalizer } from './inlineImageNormalizer';
+
+// Server requests can re-encode oversized images instead of dropping them.
+setInlineImageNormalizer(sharpInlineImageNormalizer);
export * from './trace';
export type { ServerDefaultHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
diff --git a/apps/server/src/modules/ModelRuntime/inlineImageNormalizer.test.ts b/apps/server/src/modules/ModelRuntime/inlineImageNormalizer.test.ts
new file mode 100644
index 00000000000..4f2d401c278
--- /dev/null
+++ b/apps/server/src/modules/ModelRuntime/inlineImageNormalizer.test.ts
@@ -0,0 +1,63 @@
+import sharp from 'sharp';
+import { describe, expect, it } from 'vitest';
+
+import { sharpInlineImageNormalizer } from './inlineImageNormalizer';
+
+const MB = 1024 * 1024;
+const LIMITS = { maxBase64Bytes: 5 * MB, maxLongEdge: 2000 };
+
+const solidPng = async (width: number, height: number) =>
+ (
+ await sharp({
+ create: { background: '#3366ff', channels: 3, height, width },
+ })
+ .png()
+ .toBuffer()
+ ).toString('base64');
+
+/** Random pixels barely compress, so the PNG is far over the byte cap. */
+const noisePng = async (width: number, height: number) => {
+ const pixels = Buffer.alloc(width * height * 3);
+ // Seeded xorshift keeps the fixture identical across runs.
+ let state = 0x9e3779b9;
+ for (let i = 0; i < pixels.length; i++) {
+ state ^= state << 13;
+ state ^= state >>> 17;
+ state ^= state << 5;
+ pixels[i] = state & 0xff;
+ }
+ return (
+ await sharp(pixels, { raw: { channels: 3, height, width } })
+ .png()
+ .toBuffer()
+ ).toString('base64');
+};
+
+describe('sharpInlineImageNormalizer', () => {
+ it('returns images within the limits untouched', async () => {
+ const image = { base64: await solidPng(800, 600), mimeType: 'image/png' };
+ expect(await sharpInlineImageNormalizer(image, LIMITS)).toBe(image);
+ });
+
+ it('scales an oversized image to the long-edge cap and keeps its format', async () => {
+ const result = await sharpInlineImageNormalizer(
+ { base64: await solidPng(3000, 1500), mimeType: 'image/png' },
+ LIMITS,
+ );
+ const metadata = await sharp(Buffer.from(result.base64, 'base64')).metadata();
+ expect(result.mimeType).toBe('image/png');
+ expect([metadata.width, metadata.height]).toEqual([2000, 1000]);
+ });
+
+ it('re-encodes to WebP under the byte cap, deterministically', async () => {
+ const image = { base64: await noisePng(1800, 1800), mimeType: 'image/png' };
+ expect(image.base64.length).toBeGreaterThan(5 * MB);
+
+ const first = await sharpInlineImageNormalizer(image, LIMITS);
+ const second = await sharpInlineImageNormalizer(image, LIMITS);
+
+ expect(first.mimeType).toBe('image/webp');
+ expect(first.base64.length).toBeLessThanOrEqual(5 * MB);
+ expect(second.base64).toBe(first.base64);
+ });
+});
diff --git a/apps/server/src/modules/ModelRuntime/inlineImageNormalizer.ts b/apps/server/src/modules/ModelRuntime/inlineImageNormalizer.ts
new file mode 100644
index 00000000000..12b40e63ed9
--- /dev/null
+++ b/apps/server/src/modules/ModelRuntime/inlineImageNormalizer.ts
@@ -0,0 +1,58 @@
+import type { InlineImageNormalizer } from '@lobechat/model-runtime';
+
+const OUTPUT_FORMATS = {
+ 'image/jpeg': 'jpeg',
+ 'image/png': 'png',
+ 'image/webp': 'webp',
+} as const;
+
+/**
+ * WebP fallbacks for an image that still exceeds the byte cap after resizing,
+ * largest and best first. Fixed steps keep the output deterministic, so the same
+ * source always yields the same bytes and the cached prompt prefix stays valid.
+ */
+const SHRINK_LADDER: Array<[scale: number, quality: number]> = [
+ [1, 85],
+ [1, 70],
+ [0.75, 70],
+ [0.5, 65],
+ [0.35, 60],
+];
+
+/**
+ * Resizes images the context builders inline as base64 so they fit the provider's
+ * dimension and per-image size limits. Images already within the limits are
+ * returned untouched, so their request bytes are the same as before.
+ *
+ * sharp is imported lazily to keep the native dependency out of module graphs
+ * that never inline an oversized image.
+ */
+export const sharpInlineImageNormalizer: InlineImageNormalizer = async (image, limits) => {
+ const source = Buffer.from(image.base64, 'base64');
+ const { default: sharp } = await import('sharp');
+ const { width = 0, height = 0 } = await sharp(source).metadata();
+ if (!width || !height) return image;
+
+ const longEdge = Math.max(width, height);
+ if (longEdge <= limits.maxLongEdge && image.base64.length <= limits.maxBase64Bytes) return image;
+
+ const fitEdge = Math.min(longEdge, limits.maxLongEdge);
+ const encode = (edge: number, format: 'jpeg' | 'png' | 'webp', quality?: number) =>
+ sharp(source)
+ .rotate()
+ .resize(edge, edge, { fit: 'inside', withoutEnlargement: true })
+ .toFormat(format, quality ? { quality } : undefined)
+ .toBuffer();
+
+ const format = OUTPUT_FORMATS[image.mimeType as keyof typeof OUTPUT_FORMATS] ?? 'png';
+ let result = await encode(fitEdge, format);
+ let mimeType = `image/${format}`;
+
+ for (const [scale, quality] of SHRINK_LADDER) {
+ if (Math.ceil(result.length / 3) * 4 <= limits.maxBase64Bytes) break;
+ result = await encode(Math.round(fitEdge * scale), 'webp', quality);
+ mimeType = 'image/webp';
+ }
+
+ return { base64: result.toString('base64'), mimeType };
+};
diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.ts b/packages/model-runtime/src/core/contextBuilders/anthropic.ts
index 15a15dd2565..7cbb3c1263c 100644
--- a/packages/model-runtime/src/core/contextBuilders/anthropic.ts
+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.ts
@@ -1,11 +1,12 @@
import type Anthropic from '@anthropic-ai/sdk';
-import { imageUrlToBase64 } from '../../utils/imageToBase64';
-import { resolveImageMimeTypeFromBase64 } from '../../utils/imageMimeType';
import type OpenAI from 'openai';
import type { OpenAIChatMessage, UserMessageContentPart } from '../../types';
import { normalizeAnthropicToolSchema } from '../../utils/anthropicToolSchema';
+import { resolveImageMimeTypeFromBase64 } from '../../utils/imageMimeType';
+import { imageUrlToBase64 } from '../../utils/imageToBase64';
import { parseDataUri } from '../../utils/uriParser';
+import { type InlineImageBudgetOptions, inlineImagesWithinBudget } from './inlineImageBudget';
const ANTHROPIC_SUPPORTED_IMAGE_TYPES = new Set([
'image/jpeg',
@@ -330,9 +331,15 @@ export const buildAnthropicMessage = async (
};
export const buildAnthropicMessages = async (
- oaiMessages: OpenAIChatMessage[],
- options: { enabledContextCaching?: boolean } = {},
+ inputMessages: OpenAIChatMessage[],
+ options: {
+ enabledContextCaching?: boolean;
+ /** Overrides for the inline image budget, e.g. a provider's lower body limit. */
+ imageBudget?: Partial<InlineImageBudgetOptions>;
+ } = {},
): Promise<Anthropic.Messages.MessageParam[]> => {
+ // Every image is inlined as base64, so keep the request under the body limit first.
+ const oaiMessages = await inlineImagesWithinBudget(inputMessages, options.imageBudget);
const messages: Anthropic.Messages.MessageParam[] = [];
// === Two-pass strategy to guarantee tool_use / tool_result pairing ===
diff --git a/packages/model-runtime/src/core/contextBuilders/inlineImageBudget.test.ts b/packages/model-runtime/src/core/contextBuilders/inlineImageBudget.test.ts
new file mode 100644
index 00000000000..10f5f0db669
--- /dev/null
+++ b/packages/model-runtime/src/core/contextBuilders/inlineImageBudget.test.ts
@@ -0,0 +1,231 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { OpenAIChatMessage, UserMessageContentPart } from '../../types';
+import { imageUrlToBase64 } from '../../utils/imageToBase64';
+import { buildAnthropicMessages } from './anthropic';
+import {
+ clearInlineImageCache,
+ type ImageSlot,
+ inlineImagesWithinBudget,
+ OMITTED_IMAGE_PLACEHOLDER,
+ OVERSIZED_IMAGE_PLACEHOLDER,
+ planImageOmissions,
+ setInlineImageNormalizer,
+} from './inlineImageBudget';
+
+vi.mock('../../utils/imageToBase64', async (importOriginal) => ({
+ ...((await importOriginal()) as object),
+ imageUrlToBase64: vi.fn(),
+}));
+
+const MB = 1024 * 1024;
+const BUDGET = { lowWatermark: 0.6, maxTotalBase64Bytes: 20 * MB };
+
+/** One image per message, all in user messages, `mb` megabytes each. */
+const userSlots = (sizesMb: number[]): ImageSlot[] =>
+ sizesMb.map((mb, index) => ({ bytes: mb * MB, messageIndex: index, userAnchorIndex: index }));
+
+const dataUri = (char: string, length: number) => `data:image/png;base64,${char.repeat(length)}`;
+
+const imagePart = (url: string): UserMessageContentPart => ({
+ image_url: { url },
+ type: 'image_url',
+});
+
+describe('planImageOmissions', () => {
+ it('keeps everything under the budget', () => {
+ expect(planImageOmissions(userSlots([5, 5, 5]), BUDGET).size).toBe(0);
+ });
+
+ it('omits the oldest images down to the low watermark once over budget', () => {
+ // 5 Γ— 5MB: crossing 20MB at the fifth image omits the oldest until ≀ 12MB.
+ const omitted = planImageOmissions(userSlots([5, 5, 5, 5, 5]), BUDGET);
+ expect([...omitted]).toEqual([0, 1, 2]);
+ });
+
+ it('never omits images in the newest message or its latest user message', () => {
+ const slots: ImageSlot[] = [
+ { bytes: 1 * MB, messageIndex: 0, userAnchorIndex: 0 },
+ // The user's attachments, followed by tool results in the same turn.
+ { bytes: 8 * MB, messageIndex: 2, userAnchorIndex: 2 },
+ { bytes: 8 * MB, messageIndex: 4, userAnchorIndex: 2 },
+ { bytes: 8 * MB, messageIndex: 6, userAnchorIndex: 2 },
+ ];
+ const omitted = planImageOmissions(slots, BUDGET);
+ expect(omitted.has(1)).toBe(false);
+ expect(omitted.has(3)).toBe(false);
+ expect([...omitted].sort()).toEqual([0, 2]);
+ });
+
+ it('trims an over-budget message once a text-only follow-up arrives', () => {
+ // Six 4MB attachments in one message stay protected while it is the newest turn.
+ const slots: ImageSlot[] = Array.from({ length: 6 }, () => ({
+ bytes: 4 * MB,
+ messageIndex: 0,
+ userAnchorIndex: 0,
+ }));
+ expect(planImageOmissions(slots, BUDGET, [0]).size).toBe(0);
+ // The next user message carries no images but still trims down to the watermark.
+ expect([...planImageOmissions(slots, BUDGET, [0, 2])]).toEqual([0, 1, 2]);
+ });
+
+ it('is prefix-stable and rewrites the history only a few times as images accumulate', () => {
+ const all = userSlots(Array.from({ length: 60 }, () => 1));
+ let previous = new Set<number>();
+ let rewrites = 0;
+
+ for (let turn = 1; turn <= all.length; turn++) {
+ const omitted = planImageOmissions(all.slice(0, turn), BUDGET);
+ // Appending a message never restores an omitted image.
+ for (const index of previous) expect(omitted.has(index)).toBe(true);
+ if (omitted.size !== previous.size) rewrites++;
+ previous = omitted;
+ }
+
+ // 1MB per turn against a 20MB budget cut to 12MB: one rewrite per 8MB of new
+ // images (turns 21, 29, 37, 45, 53), not one per turn after crossing the budget.
+ expect(rewrites).toBe(5);
+ });
+});
+
+describe('inlineImagesWithinBudget', () => {
+ beforeEach(() => {
+ clearInlineImageCache();
+ vi.mocked(imageUrlToBase64).mockReset();
+ });
+
+ afterEach(() => {
+ setInlineImageNormalizer(undefined);
+ });
+
+ it('returns the input untouched when there are no images', async () => {
+ const messages: OpenAIChatMessage[] = [{ content: 'hi', role: 'user' }];
+ expect(await inlineImagesWithinBudget(messages)).toBe(messages);
+ });
+
+ it('replaces the oldest images with a fixed placeholder without mutating the input', async () => {
+ const messages: OpenAIChatMessage[] = ['a', 'b', 'c'].map((char) => ({
+ content: [{ text: 'look', type: 'text' }, imagePart(dataUri(char, 1000))],
+ role: 'user',
+ }));
+ const snapshot = structuredClone(messages);
+
+ const result = await inlineImagesWithinBudget(messages, { maxTotalBase64Bytes: 2500 });
+
+ expect(messages).toEqual(snapshot);
+ expect(result[0].content).toEqual([
+ { text: 'look', type: 'text' },
+ { text: OMITTED_IMAGE_PLACEHOLDER, type: 'text' },
+ ]);
+ expect(result[1].content).toEqual([
+ { text: 'look', type: 'text' },
+ { text: OMITTED_IMAGE_PLACEHOLDER, type: 'text' },
+ ]);
+ expect(result[2].content).toEqual(messages[2].content);
+ });
+
+ it('produces identical output for identical input', async () => {
+ const messages: OpenAIChatMessage[] = ['a', 'b', 'c', 'd'].map((char) => ({
+ content: [imagePart(dataUri(char, 1000))],
+ role: 'user',
+ }));
+ const first = await inlineImagesWithinBudget(messages, { maxTotalBase64Bytes: 2500 });
+ const second = await inlineImagesWithinBudget(messages, { maxTotalBase64Bytes: 2500 });
+ expect(JSON.stringify(second)).toBe(JSON.stringify(first));
+ });
+
+ it('budgets tool-result images from remote URLs and reuses the download', async () => {
+ vi.mocked(imageUrlToBase64).mockImplementation(async (url) => ({
+ base64: url.slice(-1).repeat(1000),
+ mimeType: 'image/png',
+ }));
+ const messages: OpenAIChatMessage[] = [
+ { content: 'read the files', role: 'user' },
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: ['a', 'b', 'c'].map((char) => ({
+ function: { arguments: '{}', name: 'readFile' },
+ id: `call_${char}`,
+ type: 'function' as const,
+ })),
+ },
+ ...['a', 'b', 'c'].map((char): OpenAIChatMessage => ({
+ content: [imagePart(`https://example.com/${char}`)],
+ role: 'tool',
+ tool_call_id: `call_${char}`,
+ })),
+ ];
+
+ const result = await inlineImagesWithinBudget(messages, { maxTotalBase64Bytes: 2500 });
+ await inlineImagesWithinBudget(messages, { maxTotalBase64Bytes: 2500 });
+
+ expect(imageUrlToBase64).toHaveBeenCalledTimes(3);
+ expect(result[2].content).toEqual([{ text: OMITTED_IMAGE_PLACEHOLDER, type: 'text' }]);
+ expect(result[3].content).toEqual([{ text: OMITTED_IMAGE_PLACEHOLDER, type: 'text' }]);
+ expect(result[4].content).toEqual([imagePart(`data:image/png;base64,${'c'.repeat(1000)}`)]);
+ });
+
+ it('leaves orphan tool results untouched for the plain-text fallback', async () => {
+ const messages: OpenAIChatMessage[] = [
+ { content: 'hi', role: 'user' },
+ { content: [imagePart('https://example.com/orphan')], role: 'tool', tool_call_id: 'gone' },
+ ];
+
+ expect(await inlineImagesWithinBudget(messages)).toBe(messages);
+ expect(imageUrlToBase64).not.toHaveBeenCalled();
+ });
+
+ it('applies the registered normalizer and omits images it cannot shrink enough', async () => {
+ const normalizer = vi.fn(async (image: { base64: string; mimeType: string }) =>
+ image.base64.startsWith('big') ? image : { base64: 'small', mimeType: 'image/webp' },
+ );
+ setInlineImageNormalizer(normalizer);
+ const messages: OpenAIChatMessage[] = [
+ { content: [imagePart(dataUri('x', 50))], role: 'user' },
+ { content: [imagePart(`data:image/png;base64,big${'y'.repeat(100)}`)], role: 'user' },
+ ];
+
+ const result = await inlineImagesWithinBudget(messages, { maxImageBase64Bytes: 60 });
+
+ expect(normalizer).toHaveBeenCalledWith(
+ { base64: 'x'.repeat(50), mimeType: 'image/png' },
+ { maxBase64Bytes: 60, maxLongEdge: 2000 },
+ );
+ expect(result[0].content).toEqual([imagePart('data:image/webp;base64,small')]);
+ expect(result[1].content).toEqual([{ text: OVERSIZED_IMAGE_PLACEHOLDER, type: 'text' }]);
+ });
+});
+
+describe('buildAnthropicMessages image budget', () => {
+ beforeEach(() => {
+ clearInlineImageCache();
+ });
+
+ it('keeps an image-heavy conversation under the request budget', async () => {
+ // Seven 4MB screenshots: 28MB of base64 would exceed the 20MB default budget.
+ const messages: OpenAIChatMessage[] = Array.from({ length: 7 }, (_, index) => ({
+ content: [
+ { text: `screenshot ${index}`, type: 'text' },
+ imagePart(dataUri(String.fromCharCode(97 + index), 4 * MB)),
+ ],
+ role: 'user',
+ }));
+
+ const result = await buildAnthropicMessages(messages);
+ const imageBytes = result
+ .flatMap((message) => (Array.isArray(message.content) ? message.content : []))
+ .reduce(
+ (total, block) =>
+ total +
+ (block.type === 'image' && block.source.type === 'base64' ? block.source.data.length : 0),
+ 0,
+ );
+
+ expect(imageBytes).toBeLessThanOrEqual(20 * MB);
+ expect(result[0].content).toEqual([
+ { text: 'screenshot 0', type: 'text' },
+ { text: OMITTED_IMAGE_PLACEHOLDER, type: 'text' },
+ ]);
+ });
+});
diff --git a/packages/model-runtime/src/core/contextBuilders/inlineImageBudget.ts b/packages/model-runtime/src/core/contextBuilders/inlineImageBudget.ts
new file mode 100644
index 00000000000..68adcc0b1fe
--- /dev/null
+++ b/packages/model-runtime/src/core/contextBuilders/inlineImageBudget.ts
@@ -0,0 +1,322 @@
+import type { OpenAIChatMessage, UserMessageContentPart } from '../../types';
+import { imageUrlToBase64 } from '../../utils/imageToBase64';
+import { DownloadCache } from '../../utils/referenceImageCache';
+
+/**
+ * Request-size budget for images that a context builder inlines as base64.
+ *
+ * Anthropic-format providers cannot take image URLs, so every image in the
+ * conversation is downloaded and re-sent as base64 on every request. A topic
+ * that accumulates large images (screenshots, desktop `readFile` results)
+ * eventually exceeds the provider's request body limit and every later send
+ * fails with HTTP 413 β€” Anthropic rejects bodies over 32MB, DeepSeek's
+ * Anthropic endpoint around 40–48MB, Bedrock lower still. See LOBE-15186.
+ *
+ * This pre-pass keeps the inlined image bytes under a budget by replacing the
+ * oldest images with a fixed text placeholder. Prompt caching constrains how:
+ *
+ * - The plan is a deterministic replay over the conversation in order, so the
+ * same messages always yield the same omissions, and appending messages can
+ * only omit more older images, never restore one (prefix stability).
+ * - Omissions cut down to a low watermark rather than just under the budget.
+ * Each omission rewrites the cached prefix once; the headroom means the next
+ * rewrite waits until that much new image data has accumulated, instead of
+ * recurring on every later request.
+ * - Images of the current turn are trimmed only after every earlier image, and
+ * the newest message and the latest user message never are, so the model
+ * always sees what it just asked for.
+ *
+ * Token accounting is unaffected: context-window counters and compaction
+ * triggers already ignore image payloads, and this pass runs after them on a
+ * copy of the messages.
+ */
+
+const MB = 1024 * 1024;
+
+export interface InlineImage {
+ base64: string;
+ mimeType: string;
+}
+
+export interface InlineImageLimits {
+ /** Largest allowed base64 length for one image. */
+ maxBase64Bytes: number;
+ /** Longest allowed edge in pixels. */
+ maxLongEdge: number;
+}
+
+/**
+ * Re-encodes an image to fit `limits`. Must be deterministic and must return the
+ * input unchanged when it already fits, so requests stay byte-identical across
+ * turns. Returning an image that still exceeds `maxBase64Bytes` omits it.
+ */
+export type InlineImageNormalizer = (
+ image: InlineImage,
+ limits: InlineImageLimits,
+) => Promise<InlineImage>;
+
+export interface InlineImageBudgetOptions {
+ /** Fraction of the budget an omission cuts down to. */
+ lowWatermark: number;
+ /** Largest base64 length for one image. Anthropic rejects images over 5MB of base64. */
+ maxImageBase64Bytes: number;
+ /** Longest image edge. Anthropic rejects requests with more than 20 images over 2000px. */
+ maxLongEdge: number;
+ /** Total base64 length of all inlined images. */
+ maxTotalBase64Bytes: number;
+}
+
+export const DEFAULT_INLINE_IMAGE_BUDGET: InlineImageBudgetOptions = {
+ lowWatermark: 0.6,
+ maxImageBase64Bytes: 5 * MB,
+ // A fixed cap instead of resizing only once a request crosses 20 images: crossing
+ // the threshold would otherwise re-encode every earlier image and rewrite the
+ // whole cached prefix. Claude downsamples larger images anyway (1568px, 2576px
+ // on high-resolution models).
+ maxLongEdge: 2000,
+ // Leaves room for text and tool definitions under Anthropic's 32MB body limit.
+ maxTotalBase64Bytes: 20 * MB,
+};
+
+/** Fixed text so a trimmed request stays byte-identical across turns. */
+export const OMITTED_IMAGE_PLACEHOLDER =
+ '[Image omitted: an earlier image was removed to keep the request within the size limit]';
+
+export const OVERSIZED_IMAGE_PLACEHOLDER =
+ '[Image omitted: the image is too large to send to the model]';
+
+let normalizer: InlineImageNormalizer | undefined;
+
+/**
+ * Registers the image re-encoder. The server installs a sharp-based one; the
+ * browser runtime has none, so images there are only budgeted, not resized.
+ */
+export const setInlineImageNormalizer = (next: InlineImageNormalizer | undefined) => {
+ normalizer = next;
+};
+
+/**
+ * Normalized downloads, reused across the steps of one agent operation, which
+ * resend the same images within seconds or minutes.
+ */
+const inlineImageCache = new DownloadCache({
+ maxEntryBytes: 10 * MB,
+ maxTotalBytes: 96 * MB,
+ ttlMs: 5 * 60 * 1000,
+});
+
+/** Test helper. */
+export const clearInlineImageCache = () => {
+ inlineImageCache.clear();
+};
+
+export interface ImageSlot {
+ /** Base64 length the image adds to the request. */
+ bytes: number;
+ /** Index of the message holding the image. */
+ messageIndex: number;
+ /** Index of the latest user message at or before `messageIndex`, or -1. */
+ userAnchorIndex: number;
+}
+
+/**
+ * Replays the conversation in order and returns the slot indices to omit.
+ *
+ * After each message's images are added, and at each user message, if the kept
+ * total exceeds the budget, the oldest kept images are omitted until the total
+ * drops to the low watermark, so earlier turns go before earlier tool images of
+ * the current turn. Images in that message and in its latest user message are
+ * never omitted. Checking at text-only user messages too lets a follow-up trim
+ * an earlier message whose own images exceeded the budget while it was protected.
+ * Decisions depend only on messages up to the one being processed.
+ */
+export const planImageOmissions = (
+ slots: ImageSlot[],
+ options: Pick<InlineImageBudgetOptions, 'lowWatermark' | 'maxTotalBase64Bytes'>,
+ /** Indices of user messages, in order; each is a checkpoint even without images. */
+ userMessageIndices: number[] = [],
+): Set<number> => {
+ const omitted = new Set<number>();
+ const kept: number[] = [];
+ let keptBytes = 0;
+ const target = options.maxTotalBase64Bytes * options.lowWatermark;
+
+ const trim = (messageIndex: number, userAnchorIndex: number) => {
+ if (keptBytes <= options.maxTotalBase64Bytes) return;
+ // Oldest first, so earlier turns go before earlier tool images of this turn.
+ for (let k = 0; k < kept.length && keptBytes > target;) {
+ const slot = slots[kept[k]];
+ if (slot.messageIndex === messageIndex || slot.messageIndex === userAnchorIndex) {
+ k++;
+ continue;
+ }
+ keptBytes -= slot.bytes;
+ omitted.add(kept[k]);
+ kept.splice(k, 1);
+ }
+ };
+
+ let start = 0;
+ let user = 0;
+ while (start < slots.length || user < userMessageIndices.length) {
+ const nextSlotMessage = start < slots.length ? slots[start].messageIndex : Infinity;
+ const nextUserMessage = user < userMessageIndices.length ? userMessageIndices[user] : Infinity;
+
+ if (nextUserMessage < nextSlotMessage) {
+ trim(nextUserMessage, nextUserMessage);
+ user++;
+ continue;
+ }
+ if (nextUserMessage === nextSlotMessage) user++;
+
+ const { messageIndex, userAnchorIndex } = slots[start];
+ let end = start;
+ for (; end < slots.length && slots[end].messageIndex === messageIndex; end++) {
+ kept.push(end);
+ keptBytes += slots[end].bytes;
+ }
+ trim(messageIndex, userAnchorIndex);
+ start = end;
+ }
+
+ return omitted;
+};
+
+const isRemoteUrl = (url: string) => /^https?:\/\//i.test(url);
+
+const BASE64_MARKER = ';base64,';
+
+/** indexOf instead of a regex: data URIs can be tens of megabytes. */
+const splitBase64DataUri = (url: string): InlineImage | undefined => {
+ if (!url.startsWith('data:')) return;
+ const markerIndex = url.indexOf(BASE64_MARKER);
+ if (markerIndex <= 5) return;
+ const base64 = url.slice(markerIndex + BASE64_MARKER.length);
+ if (!base64) return;
+ return { base64, mimeType: url.slice(5, markerIndex) };
+};
+
+const normalize = async (image: InlineImage, options: InlineImageBudgetOptions) => {
+ if (!normalizer) return image;
+ try {
+ return await normalizer(image, {
+ maxBase64Bytes: options.maxImageBase64Bytes,
+ maxLongEdge: options.maxLongEdge,
+ });
+ } catch (error) {
+ console.error('Error normalizing inline image:', error);
+ return image;
+ }
+};
+
+const resolveImage = async (
+ url: string,
+ options: InlineImageBudgetOptions,
+): Promise<InlineImage | undefined> => {
+ const dataUri = splitBase64DataUri(url);
+ if (dataUri) return normalize(dataUri, options);
+
+ // Leave anything else to the block builder, which reports invalid URLs.
+ if (!isRemoteUrl(url)) return undefined;
+
+ const load = async () => normalize(await imageUrlToBase64(url), options);
+
+ return inlineImageCache.get(
+ `inline:${options.maxLongEdge}:${options.maxImageBase64Bytes}:${url}`,
+ load,
+ (value) => value.base64.length,
+ );
+};
+
+interface ImageRef {
+ messageIndex: number;
+ partIndex: number;
+}
+
+/**
+ * Inlines every image as a data URI and replaces those outside the budget with
+ * text placeholders. Returns new message objects; the input is not mutated.
+ */
+export const inlineImagesWithinBudget = async (
+ messages: OpenAIChatMessage[],
+ overrides: Partial<InlineImageBudgetOptions> = {},
+): Promise<OpenAIChatMessage[]> => {
+ const options = { ...DEFAULT_INLINE_IMAGE_BUDGET, ...overrides };
+
+ // Orphan tool results degrade to plain text in the builders, so leave their URLs alone.
+ const toolCallIds = new Set(
+ messages.flatMap((message) => message.tool_calls?.map((call) => call.id) ?? []),
+ );
+
+ const refs: ImageRef[] = [];
+ const anchors: number[] = [];
+ const userMessageIndices: number[] = [];
+ let userAnchorIndex = -1;
+ messages.forEach((message, messageIndex) => {
+ if (message.role === 'user') {
+ userAnchorIndex = messageIndex;
+ userMessageIndices.push(messageIndex);
+ }
+ if (
+ message.role === 'tool' &&
+ (!message.tool_call_id || !toolCallIds.has(message.tool_call_id))
+ )
+ return;
+ if (!Array.isArray(message.content)) return;
+ message.content.forEach((part, partIndex) => {
+ if (part.type !== 'image_url') return;
+ refs.push({ messageIndex, partIndex });
+ anchors.push(userAnchorIndex);
+ });
+ });
+
+ if (refs.length === 0) return messages;
+
+ const images = await Promise.all(
+ refs.map(({ messageIndex, partIndex }) => {
+ const part = (messages[messageIndex].content as UserMessageContentPart[])[partIndex];
+ return resolveImage((part as { image_url: { url: string } }).image_url.url, options);
+ }),
+ );
+
+ const oversized = new Set<number>();
+ const slots: ImageSlot[] = refs.map(({ messageIndex }, index) => {
+ const bytes = images[index]?.base64.length ?? 0;
+ if (bytes > options.maxImageBase64Bytes) oversized.add(index);
+ return {
+ bytes: oversized.has(index) ? 0 : bytes,
+ messageIndex,
+ userAnchorIndex: anchors[index],
+ };
+ });
+ const omitted = planImageOmissions(slots, options, userMessageIndices);
+
+ const replacements = new Map<number, Map<number, UserMessageContentPart>>();
+ refs.forEach(({ messageIndex, partIndex }, index) => {
+ const image = images[index];
+ let part: UserMessageContentPart | undefined;
+ if (oversized.has(index)) part = { text: OVERSIZED_IMAGE_PLACEHOLDER, type: 'text' };
+ else if (omitted.has(index)) part = { text: OMITTED_IMAGE_PLACEHOLDER, type: 'text' };
+ else if (image) {
+ part = {
+ image_url: { url: `data:${image.mimeType};base64,${image.base64}` },
+ type: 'image_url',
+ };
+ }
+ if (!part) return;
+ const parts = replacements.get(messageIndex) ?? new Map();
+ parts.set(partIndex, part);
+ replacements.set(messageIndex, parts);
+ });
+
+ return messages.map((message, messageIndex) => {
+ const parts = replacements.get(messageIndex);
+ if (!parts) return message;
+ return {
+ ...message,
+ content: (message.content as UserMessageContentPart[]).map(
+ (part, partIndex) => parts.get(partIndex) ?? part,
+ ),
+ };
+ });
+};
diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.ts
index c372451466e..c70a0db567b 100644
--- a/packages/model-runtime/src/index.ts
+++ b/packages/model-runtime/src/index.ts
@@ -1,4 +1,8 @@
export * from './core/BaseAI';
+export {
+ type InlineImageNormalizer,
+ setInlineImageNormalizer,
+} from './core/contextBuilders/inlineImageBudget';
export { pruneReasoningPayload } from './core/contextBuilders/openai';
export { mergeModelRuntimeHooks } from './core/mergeHooks';
export type { ModelRuntimeHooks } from './core/ModelRuntime';
diff --git a/packages/model-runtime/src/providers/bedrock/index.ts b/packages/model-runtime/src/providers/bedrock/index.ts
index dd3328c7bf4..98a7e424548 100644
--- a/packages/model-runtime/src/providers/bedrock/index.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.ts
@@ -50,6 +50,12 @@ import { normalizeClaudeThinkingHistoryMessages } from '../anthropic/claudeThink
import { rejectsDisabledThinkingAtEffort } from '../anthropic/modelId';
import { recordBedrockResponseEvent } from './providerDiagnostics';
+/**
+ * Bedrock accepts a 20MB request body and 3.75MB per image (5MB of base64), so
+ * images get a smaller share than on the Anthropic API.
+ */
+const BEDROCK_INLINE_IMAGE_BUDGET = { maxTotalBase64Bytes: 12 * 1024 * 1024 };
+
/**
* A prompt constructor for HuggingFace LLama 2 chat models.
* Does not support `function` messages.
@@ -322,7 +328,10 @@ export class LobeBedrockAI implements LobeRuntimeAI {
// which would otherwise skip the strip and 400 on a trailing assistant turn.
const postMessages = stripUnsupportedClaudeAssistantPrefill(
this.resolveModelId(model),
- await buildAnthropicMessages(user_messages, { enabledContextCaching }),
+ await buildAnthropicMessages(user_messages, {
+ enabledContextCaching,
+ imageBudget: BEDROCK_INLINE_IMAGE_BUDGET,
+ }),
);
const anthropicBase = {