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(google): upload Vertex Nano Banana base64 images instead of leaking as text (#16561)

Arvin Xu8069f8ff3c03
diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
index 1a5b51bdcf0..ab736a38e10 100644
--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
@@ -1204,6 +1204,30 @@ export const callLlm =
}, BUFFER_INTERVAL);
}
},
+ // Some Gemini / Nano Banana image responses arrive via the
+ // legacy single-image `base64_image` event instead of
+ // `content_part` (the Google stream transform emits it when a
+ // response can't be classified as multimodal). Without this
+ // handler the image is silently dropped server-side β€” never
+ // uploaded, never persisted β€” and, on channels that omit the
+ // Image response modality, the raw base64 leaks into text and
+ // bloats the context. Mirror the onContentPart image branch:
+ // register a placeholder part, upload to object storage, and
+ // mark the turn multimodal so raw base64 never lands in content.
+ onBase64Image: async ({ image }) => {
+ if (firstChunkAt === undefined) {
+ firstChunkAt = Date.now() - llmStartTime;
+ }
+
+ // `image.data` is a full data URI (`data:<mime>;base64,<...>`).
+ const mimeType = /^data:([^;]+);/.exec(image.data)?.[1];
+ const partIndex = contentParts.length;
+ contentParts.push({ image: image.data, type: 'image' });
+ hasContentImages = true;
+ contentImageUploads.push(
+ uploadPartImage(contentParts, partIndex, image.data, mimeType),
+ );
+ },
onReasoningPart: async (part) => {
if (firstChunkAt === undefined) {
firstChunkAt = Date.now() - llmStartTime;
diff --git a/packages/model-runtime/src/core/streams/protocol.test.ts b/packages/model-runtime/src/core/streams/protocol.test.ts
index 303b3c06a85..41290f825ce 100644
--- a/packages/model-runtime/src/core/streams/protocol.test.ts
+++ b/packages/model-runtime/src/core/streams/protocol.test.ts
@@ -761,6 +761,53 @@ describe('createCallbacksTransformer', () => {
});
});
+ // Regression: google/openai image streams serialize the `base64_image` event's
+ // `data` as a raw data-URI string (which itself contains `data:`). The
+ // transformer must strip only the leading field marker (not split on the
+ // embedded one) and wrap the string into an image item, so a real server-side
+ // onBase64Image consumer can upload it instead of crashing on `image.data`.
+ it('should wrap raw data-URI base64_image payloads and call onBase64Image', async () => {
+ const receivedCalls: Array<{
+ image: { data: string; id: string };
+ images: Array<{ data: string; id: string }>;
+ }> = [];
+ const onBase64Image = vi.fn((data) => {
+ receivedCalls.push({
+ image: { ...data.image },
+ images: data.images.map((img: { data: string; id: string }) => ({ ...img })),
+ });
+ });
+ const transformer = createCallbacksTransformer({ onBase64Image });
+
+ const uri1 = 'data:image/png;base64,base64data1';
+ const uri2 = 'data:image/png;base64,base64data2';
+
+ const chunks = [
+ 'event: base64_image\n',
+ `data: ${JSON.stringify(uri1)}\n\n`,
+ 'event: base64_image\n',
+ `data: ${JSON.stringify(uri2)}\n\n`,
+ ];
+
+ await processChunks(transformer, chunks);
+
+ expect(onBase64Image).toHaveBeenCalledTimes(2);
+ // The raw data-URI is preserved (not corrupted by the embedded `data:`) and
+ // wrapped with a generated id.
+ expect(receivedCalls[0].image).toEqual({
+ data: uri1,
+ id: expect.stringMatching(/^tmp_img_/),
+ });
+ expect(receivedCalls[0].images).toEqual([
+ { data: uri1, id: expect.stringMatching(/^tmp_img_/) },
+ ]);
+ expect(receivedCalls[1].image).toEqual({
+ data: uri2,
+ id: expect.stringMatching(/^tmp_img_/),
+ });
+ expect(receivedCalls[1].images.map((img) => img.data)).toEqual([uri1, uri2]);
+ });
+
it('should handle content_part chunks and call onContentPart callback', async () => {
const onContentPart = vi.fn();
const transformer = createCallbacksTransformer({ onContentPart });
diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.ts
index e12fdb44657..541c173184b 100644
--- a/packages/model-runtime/src/core/streams/protocol.ts
+++ b/packages/model-runtime/src/core/streams/protocol.ts
@@ -487,7 +487,15 @@ export function createCallbacksTransformer(
}
// if the message is a data chunk, handle the callback
else if (chunk.startsWith('data:')) {
- const content = chunk.split('data:')[1].trim();
+ // `base64_image` payloads are raw data-URIs (`data:image/png;base64,...`)
+ // that contain `data:` themselves, which the legacy `split('data:')[1]`
+ // corrupts (it splits on the embedded marker too). Strip only the leading
+ // field marker for that type; every other event type keeps the original
+ // split path unchanged for compatibility.
+ const content =
+ currentType === 'base64_image'
+ ? chunk.slice('data:'.length).trim()
+ : chunk.split('data:')[1].trim();
const data = safeParseJSON(content) as any;
@@ -511,11 +519,18 @@ export function createCallbacksTransformer(
}
case 'base64_image': {
- // data format: { image: { id, data }, images: [...] }
- const imageData = data as { image: { data: string; id: string }; images: any[] };
- base64Images.push(imageData.image);
+ // Real providers (google/openai image streams) serialize `data` as a
+ // raw data-URI string; wrap it into an image item, mirroring
+ // fetch-sse's client-side parser so both paths share one contract.
+ // Tolerate the legacy `{ image, images }` object shape too, so any
+ // existing consumer keeps working.
+ const image =
+ typeof data === 'string'
+ ? { data, id: `tmp_img_${nanoid()}` }
+ : (data as { image: { data: string; id: string } }).image;
+ base64Images.push(image);
await callbacks.onBase64Image?.({
- image: imageData.image,
+ image,
images: base64Images,
});
break;
diff --git a/packages/model-runtime/src/providers/google/googleModelId.test.ts b/packages/model-runtime/src/providers/google/googleModelId.test.ts
index 515645a3053..d48a5d5542b 100644
--- a/packages/model-runtime/src/providers/google/googleModelId.test.ts
+++ b/packages/model-runtime/src/providers/google/googleModelId.test.ts
@@ -71,6 +71,17 @@ describe('googleModelId', () => {
'gemini-3.5-pro-image-preview',
'google/gemini-3.5-pro-image-preview-free',
'nano-banana-pro-preview',
+ // Real Nano Banana model ids (Google): every one is an image-output model
+ // and must request the Image response modality. `gemini-3.1-flash-lite-image`
+ // (Nano Banana 2 Lite) is the id that surfaced the base64-as-text bug.
+ 'gemini-3.1-flash-lite-image',
+ 'gemini-3.1-flash-lite-image:image',
+ 'gemini-3.1-flash-image',
+ 'gemini-3-pro-image',
+ // Bare nanoBanana-family aliases (no `gemini-*-image` shape) are covered too.
+ 'nano-banana',
+ 'nano-banana-lite',
+ 'google/nano-banana-lite',
])('detects image-response model %s', (model) => {
expect(isGoogleImageResponseModel(model)).toBe(true);
});
diff --git a/packages/model-runtime/src/providers/google/googleModelId.ts b/packages/model-runtime/src/providers/google/googleModelId.ts
index 8aca41a19bd..03dcb1b4a44 100644
--- a/packages/model-runtime/src/providers/google/googleModelId.ts
+++ b/packages/model-runtime/src/providers/google/googleModelId.ts
@@ -210,6 +210,15 @@ export const isGoogleImageResponseModel = (model: string): boolean => {
const parsed = parseGoogleModelId(model);
if (!parsed) return false;
+ // Every Nano Banana model is a native image-output model and needs
+ // `responseModalities: ['Text', 'Image']`. Without it Vertex/Gemini returns
+ // the generated image as base64 *text* instead of an inlineData part, which
+ // bypasses the upload pipeline and blows up the context. The family check
+ // below only matches `gemini-*-image` ids, so nanoBanana-family aliases
+ // (e.g. `nano-banana-lite`) must be recognized explicitly β€” mirroring why
+ // `nano-banana-pro-preview` was pinned into IMAGE_RESPONSE_MODEL_ALIASES.
+ if (parsed.family === 'nanoBanana') return true;
+
return (
parsed.family === 'gemini' &&
hasModifier(parsed, 'image') &&