Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(sdk): preserve Gemini media parts in message conversion instead of dropping the turn (#3882)

Shubham Srivastava038c923b4bcd
diff --git a/sdk/typescript/src/utils/format.ts b/sdk/typescript/src/utils/format.ts
index 6a12061ae..d94dd70fb 100644
--- a/sdk/typescript/src/utils/format.ts
+++ b/sdk/typescript/src/utils/format.ts
@@ -398,6 +398,44 @@ export function openAIToVercel(messages: OpenAIMessage[]): any[] {
// Google Gemini → OpenAI
// ============================================================
+// Gemini inlineData / fileData part -> OpenAI image_url object, or null if unconvertible.
+// inlineData travels as a data: URI (MIME type included). fileData keeps its MIME type on a
+// private `mime_type` key so the reverse conversion can rebuild the complete
+// { mimeType, fileUri } that @google/generative-ai requires; the proxy passes non-text
+// parts through unchanged, so the key survives /v1/compress.
+function geminiMediaImageUrl(part: any): { url: string; mime_type?: string } | null {
+ const blob = part.inlineData;
+ if (blob && typeof blob === "object" && blob.mimeType && blob.data) {
+ return { url: `data:${blob.mimeType};base64,${blob.data}` };
+ }
+ const file = part.fileData;
+ if (file && typeof file === "object" && typeof file.fileUri === "string") {
+ return typeof file.mimeType === "string"
+ ? { url: file.fileUri, mime_type: file.mimeType }
+ : { url: file.fileUri };
+ }
+ return null;
+}
+
+const MIME_BY_EXTENSION: Record<string, string> = {
+ png: "image/png",
+ jpg: "image/jpeg",
+ jpeg: "image/jpeg",
+ gif: "image/gif",
+ webp: "image/webp",
+ pdf: "application/pdf",
+};
+
+// OpenAI image_url -> Gemini part. data: URIs become inlineData. Other urls become fileData
+// with the carried MIME type, else one inferred from a common extension, else fileUri only.
+function geminiMediaPart(imageUrl: { url: string; mime_type?: string }): any {
+ const m = /^data:([^;,]+);base64,(.*)$/s.exec(imageUrl.url);
+ if (m) return { inlineData: { mimeType: m[1], data: m[2] } };
+ const ext = /\.([a-z0-9]+)(?:[?#]|$)/i.exec(imageUrl.url)?.[1]?.toLowerCase();
+ const mimeType = imageUrl.mime_type ?? (ext ? MIME_BY_EXTENSION[ext] : undefined);
+ return { fileData: mimeType ? { mimeType, fileUri: imageUrl.url } : { fileUri: imageUrl.url } };
+}
+
export function geminiToOpenAI(messages: any[]): OpenAIMessage[] {
const result: OpenAIMessage[] = [];
@@ -408,10 +446,26 @@ export function geminiToOpenAI(messages: any[]): OpenAIMessage[] {
if (role === "user") {
// Check for functionResponse parts
const funcResponses = parts.filter((p: any) => p.functionResponse);
- const textParts = parts.filter((p: any) => p.text !== undefined);
+ const hasMedia = parts.some((p: any) => p.inlineData || p.fileData);
- if (textParts.length > 0) {
- result.push({ role: "user", content: textParts.map((p: any) => p.text).join("\n") });
+ if (hasMedia) {
+ const content = parts
+ .filter((p: any) => p.text !== undefined || p.inlineData || p.fileData)
+ .map((p: any) => {
+ if (p.text !== undefined) return { type: "text" as const, text: p.text };
+ const imageUrl = geminiMediaImageUrl(p);
+ return imageUrl ? { type: "image_url" as const, image_url: imageUrl } : null;
+ })
+ .filter((p: any): p is NonNullable<typeof p> => p !== null);
+
+ if (content.length > 0) {
+ result.push({ role: "user", content });
+ }
+ } else {
+ const textParts = parts.filter((p: any) => p.text !== undefined);
+ if (textParts.length > 0) {
+ result.push({ role: "user", content: textParts.map((p: any) => p.text).join("\n") });
+ }
}
for (const fr of funcResponses) {
result.push({
@@ -459,6 +513,17 @@ export function openAIToGemini(messages: OpenAIMessage[]): any[] {
}
if (msg.role === "user") {
+ if (Array.isArray(msg.content) && msg.content.some((p) => p.type === "image_url")) {
+ const geminiParts = msg.content
+ .map((p) => {
+ if (p.type === "text") return { text: p.text };
+ if (p.type === "image_url") return geminiMediaPart(p.image_url);
+ return null;
+ })
+ .filter((p) => p !== null);
+ result.push({ role: "user", parts: geminiParts });
+ continue;
+ }
const text = typeof msg.content === "string"
? msg.content
: (msg.content ?? []).filter((p) => p.type === "text").map((p) => (p as any).text).join("\n");
diff --git a/sdk/typescript/test/adapters/gemini.test.ts b/sdk/typescript/test/adapters/gemini.test.ts
index 1e418bb85..65cbd92d4 100644
--- a/sdk/typescript/test/adapters/gemini.test.ts
+++ b/sdk/typescript/test/adapters/gemini.test.ts
@@ -128,4 +128,70 @@ describe("Gemini withHeadroom", () => {
expect(result).toBe(originalResult);
});
+
+ it("preserves inline image parts through compression", async () => {
+ const mockModel = {
+ generateContent: vi.fn().mockResolvedValue({ response: { text: () => "a cat" } }),
+ };
+ // The proxy keeps the image part (it only compresses text).
+ mockFetch.mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ messages: [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ { type: "image_url", image_url: { url: "data:image/png;base64,AAAA" } },
+ ],
+ },
+ ],
+ tokens_before: 500,
+ tokens_after: 100,
+ tokens_saved: 400,
+ compression_ratio: 0.2,
+ transforms_applied: ["smart_crusher"],
+ ccr_hashes: [],
+ }),
+ });
+
+ const wrapped = withHeadroom(mockModel, { baseUrl: "http://test:8787" });
+ await wrapped.generateContent({
+ contents: [
+ {
+ role: "user",
+ parts: [{ text: "what is this?" }, { inlineData: { mimeType: "image/png", data: "AAAA" } }],
+ },
+ ],
+ });
+
+ // The image must reach the proxy as an image_url part ...
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.messages[0].content).toEqual([
+ { type: "text", text: "what is this?" },
+ { type: "image_url", image_url: { url: "data:image/png;base64,AAAA" } },
+ ]);
+ // ... and come back to the model as an inlineData part.
+ expect(mockModel.generateContent).toHaveBeenCalledWith({
+ contents: [
+ {
+ role: "user",
+ parts: [{ text: "what is this?" }, { inlineData: { mimeType: "image/png", data: "AAAA" } }],
+ },
+ ],
+ });
+ });
+
+ it("keeps an image-only turn when the proxy is unreachable", async () => {
+ const mockModel = { generateContent: vi.fn().mockResolvedValue({}) };
+ mockFetch.mockRejectedValue(new Error("connect ECONNREFUSED"));
+
+ const wrapped = withHeadroom(mockModel, { baseUrl: "http://test:8787" });
+ const contents = [
+ { role: "user", parts: [{ inlineData: { mimeType: "image/png", data: "AAAA" } }] },
+ ];
+ await wrapped.generateContent({ contents });
+
+ expect(mockModel.generateContent).toHaveBeenCalledWith({ contents });
+ });
});
diff --git a/sdk/typescript/test/utils/format.test.ts b/sdk/typescript/test/utils/format.test.ts
index b2a1676b1..377707246 100644
--- a/sdk/typescript/test/utils/format.test.ts
+++ b/sdk/typescript/test/utils/format.test.ts
@@ -1,5 +1,12 @@
import { describe, it, expect } from "vitest";
-import { vercelToOpenAI, openAIToVercel, anthropicToOpenAI, openAIToAnthropic } from "../../src/utils/format.js";
+import {
+ vercelToOpenAI,
+ openAIToVercel,
+ anthropicToOpenAI,
+ openAIToAnthropic,
+ geminiToOpenAI,
+ openAIToGemini,
+} from "../../src/utils/format.js";
import type { OpenAIMessage } from "../../src/types.js";
describe("vercelToOpenAI", () => {
@@ -639,6 +646,158 @@ describe("round-trip conversion", () => {
});
});
+describe("geminiToOpenAI", () => {
+ it("converts an inlineData part to an image_url data URI and keeps the text", () => {
+ const result = geminiToOpenAI([
+ {
+ role: "user",
+ parts: [
+ { text: "what is this?" },
+ { inlineData: { mimeType: "image/png", data: "AAAA" } },
+ ],
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ { type: "image_url", image_url: { url: "data:image/png;base64,AAAA" } },
+ ],
+ },
+ ]);
+ });
+
+ it("keeps an image-only user turn instead of dropping it", () => {
+ const result = geminiToOpenAI([
+ { role: "user", parts: [{ inlineData: { mimeType: "image/jpeg", data: "BBBB" } }] },
+ ]);
+ expect(result).toEqual([
+ {
+ role: "user",
+ content: [{ type: "image_url", image_url: { url: "data:image/jpeg;base64,BBBB" } }],
+ },
+ ]);
+ });
+
+ it("converts a fileData part to an image_url carrying its fileUri", () => {
+ const result = geminiToOpenAI([
+ {
+ role: "user",
+ parts: [
+ { text: "summarise" },
+ { fileData: { mimeType: "application/pdf", fileUri: "https://generativelanguage.googleapis.com/v1beta/files/abc" } },
+ ],
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "summarise" },
+ {
+ type: "image_url",
+ image_url: { url: "https://generativelanguage.googleapis.com/v1beta/files/abc", mime_type: "application/pdf" },
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("leaves text-only user turns as a newline-joined string (backward compat)", () => {
+ const result = geminiToOpenAI([
+ { role: "user", parts: [{ text: "a" }, { text: "b" }] },
+ ]);
+ expect(result).toEqual([{ role: "user", content: "a\nb" }]);
+ });
+});
+
+describe("openAIToGemini", () => {
+ it("restores an image_url data URI as an inlineData part", () => {
+ const msgs: OpenAIMessage[] = [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "hi" },
+ { type: "image_url", image_url: { url: "data:image/png;base64,AAAA" } },
+ ],
+ },
+ ];
+ expect(openAIToGemini(msgs)).toEqual([
+ { role: "user", parts: [{ text: "hi" }, { inlineData: { mimeType: "image/png", data: "AAAA" } }] },
+ ]);
+ });
+
+ it("restores a non-data image_url with a carried MIME type as a complete fileData part", () => {
+ const msgs = [
+ {
+ role: "user",
+ content: [
+ {
+ type: "image_url",
+ image_url: { url: "https://generativelanguage.googleapis.com/v1beta/files/abc", mime_type: "application/pdf" },
+ },
+ ],
+ },
+ ] as OpenAIMessage[];
+ expect(openAIToGemini(msgs)).toEqual([
+ {
+ role: "user",
+ parts: [{ fileData: { mimeType: "application/pdf", fileUri: "https://generativelanguage.googleapis.com/v1beta/files/abc" } }],
+ },
+ ]);
+ });
+
+ it("infers the MIME type from a common file extension when the image_url carries none", () => {
+ const msgs: OpenAIMessage[] = [
+ { role: "user", content: [{ type: "image_url", image_url: { url: "https://example.com/cat.png?size=large" } }] },
+ ];
+ expect(openAIToGemini(msgs)).toEqual([
+ { role: "user", parts: [{ fileData: { mimeType: "image/png", fileUri: "https://example.com/cat.png?size=large" } }] },
+ ]);
+ });
+
+ it("keeps only fileUri when no MIME type is known (documented fallback)", () => {
+ const msgs: OpenAIMessage[] = [
+ { role: "user", content: [{ type: "image_url", image_url: { url: "https://example.com/blob" } }] },
+ ];
+ expect(openAIToGemini(msgs)).toEqual([
+ { role: "user", parts: [{ fileData: { fileUri: "https://example.com/blob" } }] },
+ ]);
+ });
+
+ it("keeps text-only array content as a single text part (backward compat)", () => {
+ const msgs: OpenAIMessage[] = [
+ { role: "user", content: [{ type: "text", text: "a" }, { type: "text", text: "b" }] },
+ ];
+ expect(openAIToGemini(msgs)).toEqual([{ role: "user", parts: [{ text: "a\nb" }] }]);
+ });
+});
+
+describe("round-trip: geminiToOpenAI then openAIToGemini", () => {
+ it("reproduces a text+inlineData turn exactly", () => {
+ const original = [
+ {
+ role: "user",
+ parts: [{ text: "what is this?" }, { inlineData: { mimeType: "image/png", data: "AAAA" } }],
+ },
+ ];
+ expect(openAIToGemini(geminiToOpenAI(original))).toEqual(original);
+ });
+
+ it("reproduces a text+fileData (application/pdf) turn exactly", () => {
+ const original = [
+ {
+ role: "user",
+ parts: [
+ { text: "summarise" },
+ { fileData: { mimeType: "application/pdf", fileUri: "https://generativelanguage.googleapis.com/v1beta/files/abc" } },
+ ],
+ },
+ ];
+ expect(openAIToGemini(geminiToOpenAI(original))).toEqual(original);
+ });
+});
describe("openAIToVercel tool names", () => {
it("carries the tool name from the matching tool-call onto the tool-result part", () => {
const msgs: OpenAIMessage[] = [