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 Anthropic image blocks in message conversion instead of dropping the turn (#3439)

Shubham Srivastava63676e6cff02
diff --git a/sdk/typescript/src/adapters/anthropic.ts b/sdk/typescript/src/adapters/anthropic.ts
index 16bceb40e..67d529d2d 100644
--- a/sdk/typescript/src/adapters/anthropic.ts
+++ b/sdk/typescript/src/adapters/anthropic.ts
@@ -11,6 +11,23 @@ interface AnthropicLike {
[key: string]: any;
}
+// Anthropic image block `source` -> OpenAI image_url url string, or null if unconvertible.
+function anthropicImageUrl(source: any): string | null {
+ if (!source || typeof source !== "object") return null;
+ if (source.type === "base64" && source.media_type && source.data) {
+ return `data:${source.media_type};base64,${source.data}`;
+ }
+ if (source.type === "url" && typeof source.url === "string") return source.url;
+ return null;
+}
+
+// OpenAI image_url url -> Anthropic image block. data: URIs become a base64 source; other urls a url source.
+function openAIImageBlock(url: string): any {
+ const m = /^data:([^;,]+);base64,(.*)$/s.exec(url);
+ if (m) return { type: "image", source: { type: "base64", media_type: m[1], data: m[2] } };
+ return { type: "image", source: { type: "url", url } };
+}
+
/**
* Convert Anthropic messages to OpenAI format for compression.
*
@@ -29,13 +46,29 @@ function anthropicToOpenAI(messages: any[]): OpenAIMessage[] {
const toolResults = msg.content.filter(
(b: any) => b.type === "tool_result",
);
- const textBlocks = msg.content.filter((b: any) => b.type === "text");
-
- if (textBlocks.length > 0) {
- result.push({
- role: "user",
- content: textBlocks.map((b: any) => b.text).join("\n"),
- });
+ const hasImages = msg.content.some((b: any) => b.type === "image");
+
+ if (hasImages) {
+ const parts = msg.content
+ .filter((b: any) => b.type === "text" || b.type === "image")
+ .map((b: any) => {
+ if (b.type === "text") return { type: "text" as const, text: b.text };
+ const url = anthropicImageUrl(b.source);
+ return url ? { type: "image_url" as const, image_url: { url } } : null;
+ })
+ .filter((p: any): p is NonNullable<typeof p> => p !== null);
+
+ if (parts.length > 0) {
+ result.push({ role: "user", content: parts });
+ }
+ } else {
+ const textBlocks = msg.content.filter((b: any) => b.type === "text");
+ if (textBlocks.length > 0) {
+ result.push({
+ role: "user",
+ content: textBlocks.map((b: any) => b.text).join("\n"),
+ });
+ }
}
for (const tr of toolResults) {
result.push({
@@ -102,6 +135,7 @@ function openAIToAnthropic(messages: OpenAIMessage[]): any[] {
role: "user",
content: msg.content.map((p) => {
if (p.type === "text") return { type: "text", text: p.text };
+ if (p.type === "image_url") return openAIImageBlock(p.image_url.url);
return { type: "text", text: "" };
}),
});
diff --git a/sdk/typescript/src/utils/format.ts b/sdk/typescript/src/utils/format.ts
index 17e3e6a2e..c2ac954b6 100644
--- a/sdk/typescript/src/utils/format.ts
+++ b/sdk/typescript/src/utils/format.ts
@@ -71,6 +71,23 @@ export function detectFormat(messages: any[]): MessageFormat {
// Anthropic → OpenAI
// ============================================================
+// Anthropic image block `source` -> OpenAI image_url url string, or null if unconvertible.
+function anthropicImageUrl(source: any): string | null {
+ if (!source || typeof source !== "object") return null;
+ if (source.type === "base64" && source.media_type && source.data) {
+ return `data:${source.media_type};base64,${source.data}`;
+ }
+ if (source.type === "url" && typeof source.url === "string") return source.url;
+ return null;
+}
+
+// OpenAI image_url url -> Anthropic image block. data: URIs become a base64 source; other urls a url source.
+function openAIImageBlock(url: string): any {
+ const m = /^data:([^;,]+);base64,(.*)$/s.exec(url);
+ if (m) return { type: "image", source: { type: "base64", media_type: m[1], data: m[2] } };
+ return { type: "image", source: { type: "url", url } };
+}
+
export function anthropicToOpenAI(messages: any[]): OpenAIMessage[] {
const result: OpenAIMessage[] = [];
@@ -81,14 +98,30 @@ export function anthropicToOpenAI(messages: any[]): OpenAIMessage[] {
continue;
}
if (Array.isArray(msg.content)) {
- const textBlocks = msg.content.filter((b: any) => b.type === "text");
const toolResults = msg.content.filter((b: any) => b.type === "tool_result");
-
- if (textBlocks.length > 0) {
- result.push({
- role: "user",
- content: textBlocks.map((b: any) => b.text).join("\n"),
- });
+ const hasImages = msg.content.some((b: any) => b.type === "image");
+
+ if (hasImages) {
+ const parts = msg.content
+ .filter((b: any) => b.type === "text" || b.type === "image")
+ .map((b: any) => {
+ if (b.type === "text") return { type: "text" as const, text: b.text };
+ const url = anthropicImageUrl(b.source);
+ return url ? { type: "image_url" as const, image_url: { url } } : null;
+ })
+ .filter((p: any): p is NonNullable<typeof p> => p !== null);
+
+ if (parts.length > 0) {
+ result.push({ role: "user", content: parts });
+ }
+ } else {
+ const textBlocks = msg.content.filter((b: any) => b.type === "text");
+ if (textBlocks.length > 0) {
+ result.push({
+ role: "user",
+ content: textBlocks.map((b: any) => b.text).join("\n"),
+ });
+ }
}
for (const tr of toolResults) {
const content = typeof tr.content === "string"
@@ -155,9 +188,11 @@ export function openAIToAnthropic(messages: OpenAIMessage[]): any[] {
} else if (Array.isArray(msg.content)) {
result.push({
role: "user",
- content: msg.content.map((p) =>
- p.type === "text" ? { type: "text", text: p.text } : { type: "text", text: "" },
- ),
+ content: msg.content.map((p) => {
+ if (p.type === "text") return { type: "text", text: p.text };
+ if (p.type === "image_url") return openAIImageBlock(p.image_url.url);
+ return { type: "text", text: "" };
+ }),
});
}
continue;
diff --git a/sdk/typescript/test/adapters/anthropic.test.ts b/sdk/typescript/test/adapters/anthropic.test.ts
index c5d4e21f8..89de634e2 100644
--- a/sdk/typescript/test/adapters/anthropic.test.ts
+++ b/sdk/typescript/test/adapters/anthropic.test.ts
@@ -190,6 +190,140 @@ describe("withHeadroom (Anthropic)", () => {
expect(createArgs.messages.length).toBeGreaterThan(0);
});
+ it("preserves image blocks instead of dropping them during compression", async () => {
+ mockFetch.mockResolvedValueOnce(mockCompressSuccess());
+
+ const mockCreate = vi.fn().mockResolvedValue({});
+ const fakeClient = { messages: { create: mockCreate } };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ await wrapped.messages.create({
+ model: "claude-sonnet-4-5-20250929",
+ messages: [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ {
+ type: "image",
+ source: { type: "base64", media_type: "image/png", data: "AAAA" },
+ },
+ ],
+ },
+ ],
+ max_tokens: 1024,
+ });
+
+ // The image must not be silently dropped from the compression request.
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.messages).toHaveLength(1);
+ expect(body.messages[0].content).toEqual([
+ { type: "text", text: "what is this?" },
+ { type: "image_url", image_url: { url: "data:image/png;base64,AAAA" } },
+ ]);
+ });
+
+ it("converts a retained image_url back to an Anthropic image block for the final messages.create call (image-only turn)", async () => {
+ // Proxy retains the image through compression (successful-compression path).
+ mockFetch.mockResolvedValueOnce(
+ mockCompressSuccess([
+ {
+ role: "user",
+ content: [
+ { type: "image_url", image_url: { url: "data:image/png;base64,AAAA" } },
+ ],
+ },
+ ]),
+ );
+
+ const mockCreate = vi.fn().mockResolvedValue({});
+ const fakeClient = { messages: { create: mockCreate } };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ await wrapped.messages.create({
+ model: "claude-sonnet-4-5-20250929",
+ messages: [
+ {
+ role: "user",
+ content: [
+ {
+ type: "image",
+ source: { type: "base64", media_type: "image/png", data: "AAAA" },
+ },
+ ],
+ },
+ ],
+ max_tokens: 1024,
+ });
+
+ expect(mockCreate).toHaveBeenCalledOnce();
+ const createArgs = mockCreate.mock.calls[0][0];
+ expect(createArgs.messages).toEqual([
+ {
+ role: "user",
+ content: [
+ { type: "image", source: { type: "base64", media_type: "image/png", data: "AAAA" } },
+ ],
+ },
+ ]);
+ });
+
+ it("converts a retained mixed text/image turn back to Anthropic blocks, order preserved, for the final messages.create call", async () => {
+ mockFetch.mockResolvedValueOnce(
+ mockCompressSuccess([
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ { type: "image_url", image_url: { url: "data:image/jpeg;base64,BBBB" } },
+ ],
+ },
+ ]),
+ );
+
+ const mockCreate = vi.fn().mockResolvedValue({});
+ const fakeClient = { messages: { create: mockCreate } };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ await wrapped.messages.create({
+ model: "claude-sonnet-4-5-20250929",
+ messages: [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ {
+ type: "image",
+ source: { type: "base64", media_type: "image/jpeg", data: "BBBB" },
+ },
+ ],
+ },
+ ],
+ max_tokens: 1024,
+ });
+
+ expect(mockCreate).toHaveBeenCalledOnce();
+ const createArgs = mockCreate.mock.calls[0][0];
+ expect(createArgs.messages).toEqual([
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ { type: "image", source: { type: "base64", media_type: "image/jpeg", data: "BBBB" } },
+ ],
+ },
+ ]);
+ });
+
it("returns original messages on compression fallback", async () => {
// Simulate proxy unreachable
mockFetch.mockRejectedValueOnce(new TypeError("fetch failed"));
diff --git a/sdk/typescript/test/utils/format.test.ts b/sdk/typescript/test/utils/format.test.ts
index c280caa0f..e43b3c216 100644
--- a/sdk/typescript/test/utils/format.test.ts
+++ b/sdk/typescript/test/utils/format.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { vercelToOpenAI, openAIToVercel } from "../../src/utils/format.js";
+import { vercelToOpenAI, openAIToVercel, anthropicToOpenAI, openAIToAnthropic } from "../../src/utils/format.js";
import type { OpenAIMessage } from "../../src/types.js";
describe("vercelToOpenAI", () => {
@@ -269,6 +269,191 @@ describe("vercelToOpenAI", () => {
});
});
+describe("anthropicToOpenAI", () => {
+ it("converts image-only user message to a content-parts array (not dropped)", () => {
+ const result = anthropicToOpenAI([
+ {
+ role: "user",
+ content: [
+ {
+ type: "image",
+ source: { type: "base64", media_type: "image/png", data: "AAAA" },
+ },
+ ],
+ },
+ ]);
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({
+ role: "user",
+ content: [
+ {
+ type: "image_url",
+ image_url: { url: "data:image/png;base64,AAAA" },
+ },
+ ],
+ });
+ });
+
+ it("converts a url-sourced image as a passthrough url", () => {
+ const result = anthropicToOpenAI([
+ {
+ role: "user",
+ content: [
+ { type: "image", source: { type: "url", url: "https://example.com/cat.png" } },
+ ],
+ },
+ ]);
+ expect(result[0].content).toEqual([
+ { type: "image_url", image_url: { url: "https://example.com/cat.png" } },
+ ]);
+ });
+
+ it("preserves order of text + image blocks", () => {
+ const result = anthropicToOpenAI([
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ {
+ type: "image",
+ source: { type: "base64", media_type: "image/jpeg", data: "BBBB" },
+ },
+ ],
+ },
+ ]);
+ expect(result[0].content).toEqual([
+ { type: "text", text: "what is this?" },
+ { type: "image_url", image_url: { url: "data:image/jpeg;base64,BBBB" } },
+ ]);
+ });
+
+ it("leaves text-only user messages as a flat string (backward compat)", () => {
+ const result = anthropicToOpenAI([
+ { role: "user", content: [{ type: "text", text: "hello" }] },
+ ]);
+ expect(result).toEqual([{ role: "user", content: "hello" }]);
+ });
+
+ it("emits a separate tool message alongside an image in the same user turn", () => {
+ const result = anthropicToOpenAI([
+ {
+ role: "user",
+ content: [
+ {
+ type: "image",
+ source: { type: "base64", media_type: "image/png", data: "CCCC" },
+ },
+ { type: "tool_result", tool_use_id: "tu_1", content: "ok" },
+ ],
+ },
+ ]);
+ expect(result).toHaveLength(2);
+ expect(result[0]).toEqual({
+ role: "user",
+ content: [
+ { type: "image_url", image_url: { url: "data:image/png;base64,CCCC" } },
+ ],
+ });
+ expect(result[1]).toEqual({
+ role: "tool",
+ content: "ok",
+ tool_call_id: "tu_1",
+ });
+ });
+
+ it("drops an unconvertible lone image block (no usable url) rather than pushing a broken part", () => {
+ const result = anthropicToOpenAI([
+ { role: "user", content: [{ type: "image", source: { type: "unknown" } }] },
+ ]);
+ expect(result).toEqual([]);
+ });
+});
+
+describe("openAIToAnthropic", () => {
+ it("converts a base64 image_url part back to an Anthropic base64 image block", () => {
+ const result = openAIToAnthropic([
+ {
+ role: "user",
+ content: [
+ { type: "image_url", image_url: { url: "data:image/png;base64,ABC" } },
+ ],
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ role: "user",
+ content: [
+ { type: "image", source: { type: "base64", media_type: "image/png", data: "ABC" } },
+ ],
+ },
+ ]);
+ });
+
+ it("converts an http(s) image_url part back to an Anthropic url image block", () => {
+ const result = openAIToAnthropic([
+ {
+ role: "user",
+ content: [
+ { type: "image_url", image_url: { url: "https://example.com/cat.png" } },
+ ],
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ role: "user",
+ content: [
+ { type: "image", source: { type: "url", url: "https://example.com/cat.png" } },
+ ],
+ },
+ ]);
+ });
+
+ it("preserves order of text + image_url parts", () => {
+ const result = openAIToAnthropic([
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ { type: "image_url", image_url: { url: "data:image/jpeg;base64,BBBB" } },
+ ],
+ },
+ ]);
+ expect(result[0].content).toEqual([
+ { type: "text", text: "what is this?" },
+ { type: "image", source: { type: "base64", media_type: "image/jpeg", data: "BBBB" } },
+ ]);
+ });
+});
+
+describe("round-trip: anthropicToOpenAI then openAIToAnthropic", () => {
+ it("preserves an image-only turn", () => {
+ const original = [
+ {
+ role: "user",
+ content: [
+ { type: "image", source: { type: "base64", media_type: "image/png", data: "AAAA" } },
+ ],
+ },
+ ];
+ const result = openAIToAnthropic(anthropicToOpenAI(original));
+ expect(result).toEqual(original);
+ });
+
+ it("preserves a mixed text + image turn, in order", () => {
+ const original = [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ { type: "image", source: { type: "base64", media_type: "image/jpeg", data: "BBBB" } },
+ ],
+ },
+ ];
+ const result = openAIToAnthropic(anthropicToOpenAI(original));
+ expect(result).toEqual(original);
+ });
+});
+
describe("openAIToVercel", () => {
it("converts system message (passthrough)", () => {
const result = openAIToVercel([