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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(sdk): keep Vercel AI SDK tool-result output kinds through compression (#4670)
Shubham Srivastavace4275491299
diff --git a/docs/content/docs/vercel-ai-sdk.mdx b/docs/content/docs/vercel-ai-sdk.mdxindex aed191046..3ffe4ede9 100644--- a/docs/content/docs/vercel-ai-sdk.mdx+++ b/docs/content/docs/vercel-ai-sdk.mdx@@ -136,4 +136,4 @@ const { output } = await generateText({3. Compressed messages are converted back to Vercel format4. The original model receives the smaller prompt-All other model behavior (tool calling, structured output, streaming) is unchanged. Provider state the AI SDK attaches to the prompt travels through untouched: `reasoning` parts (with the Anthropic `signature` or `redactedData`, OpenAI `itemId`, Google `thoughtSignature` they carry) stay in place, tool calls return to their place among them, and `providerOptions` on messages, text and file parts, tool calls and tool results come back exactly as sent. Only large tool results change.+All other model behavior (tool calling, structured output, streaming) is unchanged. Provider state the AI SDK attaches to the prompt travels through untouched: `reasoning` parts (with the Anthropic `signature` or `redactedData`, OpenAI `itemId`, Google `thoughtSignature` they carry) stay in place, tool calls return to their place among them, and `providerOptions` on messages, text and file parts, tool calls and tool results come back exactly as sent. Tool results keep their output kind: an `error-text` or `error-json` result is still an error, an `execution-denied` result keeps its reason, and a multi-part `content` result (a screenshot, a PDF, an MCP result) keeps its file and custom members byte for byte while its text members compress like any other tool output. Only large tool results change.diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.tsindex 78b715674..da5fe5da9 100644--- a/sdk/typescript/src/types.ts+++ b/sdk/typescript/src/types.ts@@ -88,10 +88,33 @@ export interface AssistantMessage {providerOptions?: ProviderOptions;}+/**+ * A member of a Vercel AI SDK tool-result `content` output other than text: a+ * LanguageModelV4 `file` or `custom` part, or a LanguageModelV3 `file-data`,+ * `file-url`, `file-id`, `image-data`, `image-url` or `image-file-id` part.+ * Carried verbatim through `/v1/compress`, which passes unknown parts through.+ */+export interface ToolResultMediaPart {+ type: string;+ [key: string]: unknown;+}+export interface ToolMessage {role: "tool";- content: string;+ /**+ * The tool output. A Vercel AI SDK `content` output keeps its member list: the+ * proxy compresses the text members as fragments of one tool result and passes+ * the rest through.+ */+ content: string | Array<TextContentPart | ToolResultMediaPart>;tool_call_id: string;+ /**+ * Vercel AI SDK: the result's `output` without its `value`, which travels as+ * `content`. Brings the output kind (`error-text`, `execution-denied`, ...), the+ * denial reason and the output's own providerOptions back. Carried, never sent+ * to OpenAI.+ */+ output?: { type: string; reason?: string; providerOptions?: ProviderOptions };providerOptions?: ProviderOptions;}diff --git a/sdk/typescript/src/utils/format.ts b/sdk/typescript/src/utils/format.tsindex e2639439c..65aaffbf9 100644--- a/sdk/typescript/src/utils/format.ts+++ b/sdk/typescript/src/utils/format.ts@@ -622,19 +622,27 @@ export function vercelToOpenAI(messages: any[]): OpenAIMessage[] {for (const part of parts) {let toolMsg: ToolMessage;if (part.type === "tool-result") {- // AI SDK v6 uses `output: { type, value }`, earlier versions used `result`- let contentStr: string;- if (part.output !== undefined) {- // v6 format: output is { type: 'json', value } or { type: 'text', value }- const val = part.output?.value ?? part.output;- contentStr = typeof val === "string" ? val : JSON.stringify(val);- } else if (part.result !== undefined) {- // Legacy format: result field directly- contentStr = typeof part.result === "string" ? part.result : JSON.stringify(part.result);+ const output = part.output;+ if (output && typeof output === "object" && typeof output.type === "string") {+ // AI SDK v6+: `output` is { type, value?, reason?, providerOptions? }. The value goes+ // out as the tool message content so the proxy compresses it; a `content` output+ // keeps its member list (text members compress as fragments of one tool result,+ // file and custom members pass through). The rest of the output rides on `output`+ // and brings the kind, the denial reason and the output's providerOptions back.+ const { value, ...rest } = output;+ const content =+ rest.type === "content" && Array.isArray(value) ? value+ : rest.type === "json" || rest.type === "error-json" ? JSON.stringify(value ?? null)+ : typeof value === "string" ? value+ : value === undefined ? ""+ : JSON.stringify(value);+ toolMsg = withProviderOptions({ role: "tool", content, tool_call_id: part.toolCallId, output: rest }, part);} else {- contentStr = "";+ // A bare `output` value, or the pre-v6 `result` field.+ const raw = output !== undefined ? output : part.result;+ const contentStr = raw === undefined ? "" : typeof raw === "string" ? raw : JSON.stringify(raw);+ toolMsg = withProviderOptions({ role: "tool", content: contentStr, tool_call_id: part.toolCallId }, part);}- toolMsg = withProviderOptions({ role: "tool", content: contentStr, tool_call_id: part.toolCallId }, part);} else {// tool-approval-response (or any other AI SDK tool part): no OpenAI equivalent,// carried verbatim on `part` and restored as-is.@@ -725,12 +733,25 @@ export function openAIToVercel(messages: OpenAIMessage[]): any[] {if (carried && typeof carried === "object") {part = carried;} else {- let parsed: any;- try { parsed = JSON.parse(msg.content); } catch { parsed = msg.content; }- // AI SDK v6 requires output: { type: 'json' | 'text', value }- const output = typeof parsed === "string"- ? { type: "text" as const, value: parsed }- : { type: "json" as const, value: parsed };+ const body: any = msg.content;+ const kind = msg.output;+ let output: any;+ if (kind && typeof kind === "object" && typeof kind.type === "string") {+ const { type, ...meta } = kind;+ if (type === "execution-denied") output = { type, ...meta };+ else if (type === "content") output = { type, value: Array.isArray(body) ? body : [{ type: "text", text: String(body ?? "") }], ...meta };+ else if (type === "json" || type === "error-json") {+ // A JSON body the proxy rewrote into prose comes back as the kind's text twin.+ try { output = { type, value: JSON.parse(body), ...meta }; }+ catch { output = { type: type === "json" ? "text" : "error-text", value: body, ...meta }; }+ } else output = { type, value: typeof body === "string" ? body : JSON.stringify(body), ...meta };+ } else {+ // No carrier (an OpenAI-native tool message): guess the kind from the body.+ const text = typeof body === "string" ? body : JSON.stringify(body);+ let parsed: any;+ try { parsed = JSON.parse(text); } catch { parsed = text; }+ output = typeof parsed === "string" ? { type: "text", value: parsed } : { type: "json", value: parsed };+ }part = withProviderOptions({type: "tool-result",toolCallId: msg.tool_call_id,@@ -923,7 +944,8 @@ export function openAIToGemini(messages: OpenAIMessage[]): any[] {if (msg.role === "tool") {let response: any;- try { response = JSON.parse(msg.content); } catch { response = { result: msg.content }; }+ const text = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);+ try { response = JSON.parse(text); } catch { response = { result: text }; }result.push({role: "user",parts: [{ functionResponse: { name: msg.tool_call_id?.replace("gemini_", "") ?? "unknown", response } }],diff --git a/sdk/typescript/test/adapters/vercel-ai.test.ts b/sdk/typescript/test/adapters/vercel-ai.test.tsindex 48306ad68..39df7649a 100644--- a/sdk/typescript/test/adapters/vercel-ai.test.ts+++ b/sdk/typescript/test/adapters/vercel-ai.test.ts@@ -596,3 +596,52 @@ describe("headroomMiddleware keeps provider-executed tool calls in place", () =>expect(out.prompt).toEqual(prompt);});});++describe("headroomMiddleware keeps tool-result output kinds", () => {+ beforeEach(() => {+ mockFetch.mockReset();+ });++ it("returns denied, multi-part and error results exactly as the AI SDK sent them", async () => {+ const prompt: LanguageModelV4Prompt = [+ { role: "user", content: [{ type: "text", text: "Deploy, then screenshot the dashboard." }] },+ {+ role: "assistant",+ content: [+ { type: "tool-call", toolCallId: "call_1", toolName: "deploy", input: { env: "prod" } },+ { type: "tool-call", toolCallId: "call_2", toolName: "screenshot", input: {} },+ { type: "tool-call", toolCallId: "call_3", toolName: "fetch_gateway_metrics", input: {} },+ ],+ },+ {+ role: "tool",+ content: [+ { type: "tool-result", toolCallId: "call_1", toolName: "deploy", output: { type: "execution-denied", reason: "Not from CI." } },+ {+ type: "tool-result",+ toolCallId: "call_2",+ toolName: "screenshot",+ output: {+ type: "content",+ value: [+ { type: "text", text: "Dashboard at 12:00." },+ { type: "file", data: { type: "data", data: "iVBORw0KGgo=" }, mediaType: "image/png", filename: "dashboard.png" },+ ],+ },+ },+ { type: "tool-result", toolCallId: "call_3", toolName: "fetch_gateway_metrics", output: { type: "error-text", value: "ECONNREFUSED 10.0.0.7:443" } },+ ],+ },+ ];+ // The proxy passes this prompt through unchanged.+ mockFetch.mockImplementationOnce(async (_url: string, init: any) => mockCompressResponse(JSON.parse(init.body).messages));++ const middleware = headroomMiddleware({ baseUrl: "http://localhost:8787" });+ const out = await middleware.transformParams({ params: { prompt }, model: { specificationVersion: "v4" }, type: "generate" });++ expect(out.prompt.slice(0, 2)).toEqual(prompt.slice(0, 2));+ // One OpenAI tool message per result, so a multi-result tool message comes back as one+ // message per result; the results themselves are the AI SDK's own.+ expect(out.prompt.slice(2).flatMap((m: any) => m.content)).toEqual(prompt[2].content);+ });+});diff --git a/sdk/typescript/test/utils/format.test.ts b/sdk/typescript/test/utils/format.test.tsindex 2d9ce927c..3b918c367 100644--- a/sdk/typescript/test/utils/format.test.ts+++ b/sdk/typescript/test/utils/format.test.ts@@ -1670,3 +1670,95 @@ describe("Vercel tool messages with several results carry message-level providerexpect(back.map((m: any) => m.providerOptions)).toEqual([undefined, { anthropic: { cacheControl: { type: "ephemeral" } } }]);});});++describe("Vercel tool-result output kinds survive the round trip", () => {+ // The result's value travels as the OpenAI tool message content, so the proxy still compresses+ // it; the rest of the output object rides beside it and brings the kind back on the way out.+ const turn = (output: any) => [+ { role: "assistant", content: [{ type: "tool-call", toolCallId: "call_1", toolName: "deploy", input: {} }] },+ { role: "tool", content: [{ type: "tool-result", toolCallId: "call_1", toolName: "deploy", output }] },+ ];+ const roundTrip = (output: any) => openAIToVercel(vercelToOpenAI(turn(output)))[1].content[0].output;++ it("keeps an error-text result an error", () => {+ expect(roundTrip({ type: "error-text", value: "ECONNREFUSED 10.0.0.7:443" })).toEqual({ type: "error-text", value: "ECONNREFUSED 10.0.0.7:443" });+ });++ it("keeps an error-json result an error", () => {+ expect(roundTrip({ type: "error-json", value: { code: 7 } })).toEqual({ type: "error-json", value: { code: 7 } });+ });++ it("restores an execution-denied result with its reason and no value", () => {+ expect(roundTrip({ type: "execution-denied", reason: "Not from CI." })).toEqual({ type: "execution-denied", reason: "Not from CI." });+ expect(roundTrip({ type: "execution-denied" })).toEqual({ type: "execution-denied" });+ });++ it("keeps a text result whose body parses as JSON a text result", () => {+ expect(roundTrip({ type: "text", value: "42" })).toEqual({ type: "text", value: "42" });+ });++ it("keeps a json result whose value is a string a json result", () => {+ expect(roundTrip({ type: "json", value: "ok" })).toEqual({ type: "json", value: "ok" });+ });++ it("keeps the output's own providerOptions", () => {+ const output = { type: "text", value: "ok", providerOptions: { openai: { approvalId: "apr_1" } } };+ expect(roundTrip(output)).toEqual(output);+ });++ it("keeps a content result's members: text as text, file and custom parts verbatim", () => {+ const output = {+ type: "content",+ value: [+ { type: "text", text: "Dashboard at 12:00.", providerOptions: { anthropic: { cacheControl: { type: "ephemeral" } } } },+ { type: "file", data: { type: "data", data: "iVBORw0KGgo=" }, mediaType: "image/png", filename: "shot.png", providerOptions: { openai: { imageDetail: "low" } } },+ { type: "custom", providerOptions: { anthropic: { toolReference: { type: "tool_reference", toolName: "bash" } } } },+ ],+ };+ expect(roundTrip(output)).toEqual(output);+ });++ it("carries LanguageModelV3 media members (image-data, file-url, file-id) the same way", () => {+ const output = {+ type: "content",+ value: [+ { type: "text", text: "Three attachments." },+ { type: "image-data", data: "iVBORw0KGgo=", mediaType: "image/png" },+ { type: "file-url", url: "https://example.com/report.pdf" },+ { type: "file-id", fileId: { openai: "file-abc" } },+ ],+ };+ expect(roundTrip(output)).toEqual(output);+ });++ it("sends an error-text body as the tool message content, with the kind beside it", () => {+ const [, toolMsg] = vercelToOpenAI(turn({ type: "error-text", value: "ECONNREFUSED 10.0.0.7:443" })) as any[];+ expect(toolMsg.content).toBe("ECONNREFUSED 10.0.0.7:443");+ expect(toolMsg.output).toEqual({ type: "error-text" });+ });++ it("sends a content result as the tool message's content array", () => {+ const value = [{ type: "text", text: "Dashboard at 12:00." }, { type: "file", data: { type: "data", data: "iVBORw0KGgo=" }, mediaType: "image/png" }];+ const [, toolMsg] = vercelToOpenAI(turn({ type: "content", value })) as any[];+ expect(toolMsg.content).toEqual(value);+ expect(toolMsg.output).toEqual({ type: "content" });+ });++ it("sends an execution-denied result as empty content with the reason beside it", () => {+ const [, toolMsg] = vercelToOpenAI(turn({ type: "execution-denied", reason: "Not from CI." })) as any[];+ expect(toolMsg.content).toBe("");+ expect(toolMsg.output).toEqual({ type: "execution-denied", reason: "Not from CI." });+ });++ it("keeps the error flag when a compressed error-json body no longer parses", () => {+ const converted = vercelToOpenAI(turn({ type: "error-json", value: { rows: [1, 2, 3, 4] } })) as any[];+ converted[1].content = "[rows: 4 items, 1-4]";+ expect(openAIToVercel(converted)[1].content[0].output).toEqual({ type: "error-text", value: "[rows: 4 items, 1-4]" });+ });++ it("returns a json result whose compressed body no longer parses as its text twin", () => {+ const converted = vercelToOpenAI(turn({ type: "json", value: { rows: [1, 2, 3, 4] } })) as any[];+ converted[1].content = "[rows: 4 items, 1-4]";+ expect(openAIToVercel(converted)[1].content[0].output).toEqual({ type: "text", value: "[rows: 4 items, 1-4]" });+ });+});