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(proxy): handle content-part outputs in Codex Responses compression (#2052)
GUOHAO LIUc9a7755a281d
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex f01f83edd..187b3511a 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -633,6 +633,15 @@ def _responses_input_item_text_bytes(item: Any) -> int:output = item.get("output")if isinstance(output, str):return len(output.encode("utf-8", errors="replace"))+ if isinstance(output, list):+ total = 0+ for part in output:+ if isinstance(part, str):+ total += len(part.encode("utf-8", errors="replace"))+ elif isinstance(part, dict) and isinstance(part.get("text"), str):+ total += len(part["text"].encode("utf-8", errors="replace"))+ if total > 0:+ return totalcontent = item.get("content")if isinstance(content, str):@@ -1296,9 +1305,9 @@ class OpenAIHandlerMixin:# remain as defense-in-depth.type_tag = item.get("type")if type_tag in self.OPENAI_RESPONSES_OUTPUT_TYPES:- output = item.get("output")- if isinstance(output, str):- return output, ("output", None)+ output_text = _responses_part_text(item.get("output"))+ if output_text:+ return output_text, ("output", None)return Nonedef _set_slot_text(@@ -1396,12 +1405,8 @@ class OpenAIHandlerMixin:# Protected from lossy compression — but grep/log/json output# can still be losslessly compacted. Reuse the router helper# so the Responses path matches the chat/Anthropic behavior.- excl_out = item.get("output")- fold = (- router._lossless_compact_excluded(excl_out)- if isinstance(excl_out, str)- else None- )+ excl_out = _responses_part_text(item.get("output"))+ fold = router._lossless_compact_excluded(excl_out) if excl_out else Noneif fold is not None:lossless_excluded.append((idx, ("output", None), fold[0], excl_out))if debug_enabled:diff --git a/tests/test_openai_responses_compression_units.py b/tests/test_openai_responses_compression_units.pyindex e16dbcb4a..bd66bb013 100644--- a/tests/test_openai_responses_compression_units.py+++ b/tests/test_openai_responses_compression_units.py@@ -176,6 +176,46 @@ def test_openai_responses_adapter_compresses_custom_tool_call_output():assert strategy_chain == []+def test_openai_responses_adapter_compresses_output_content_parts():+ router = ContentRouter()++ def compress(self, content: str, **_kwargs):+ return RouterCompressionResult(+ compressed="content part output summary",+ original=content,+ strategy_used=CompressionStrategy.KOMPRESS,+ )++ router.compress = MethodType(compress, router)+ handler = _handler_with_router(router)+ long_text = " ".join(f"part{i}" for i in range(180))+ payload = {+ "model": "gpt-5",+ "input": [+ {+ "type": "function_call_output",+ "call_id": "c1",+ "output": [{"type": "output_text", "text": long_text}],+ }+ ],+ }++ new_payload, modified, saved, transforms, units_by_category, strategy_chain, _attempted = (+ handler._compress_openai_responses_live_text_units_with_router(+ payload,+ model="gpt-5",+ request_id="req_content_parts",+ )+ )++ assert modified is True+ assert saved > 0+ assert new_payload["input"][0]["output"] == "content part output summary"+ assert "router:openai:responses:function_call_output:kompress" in transforms+ assert units_by_category == {"applied": 1}+ assert strategy_chain == []++def test_openai_responses_adapter_reuses_exact_tool_output_cache():router = ContentRouter()calls = {"count": 0}@@ -490,6 +530,45 @@ def test_openai_responses_adapter_losslessly_folds_excluded_grep_output():assert search_unheading(folded) == grep_out # byte-exact recovery+def test_openai_responses_adapter_losslessly_folds_excluded_output_content_parts():+ from headroom.transforms.lossless_compaction import search_unheading++ router = ContentRouter()+ router.config.exclude_tools = {"grep"}+ handler = _handler_with_router(router)+ grep_out = "".join(+ f"src/part_{f}.py:{ln}:matching content in a content part\n"+ for f in range(8)+ for ln in range(6)+ )+ payload = {+ "model": "gpt-5",+ "input": [+ {"type": "function_call", "call_id": "call_1", "name": "grep", "arguments": "{}"},+ {+ "type": "function_call_output",+ "call_id": "call_1",+ "output": [{"type": "output_text", "text": grep_out}],+ },+ ],+ }++ new_payload, modified, saved, transforms, _units, _chain, _attempted = (+ handler._compress_openai_responses_live_text_units_with_router(+ payload,+ model="gpt-5",+ request_id="req_content_part_fold",+ )+ )++ assert modified is True+ assert saved >= 0+ assert "router:excluded:lossless" in transforms+ folded = new_payload["input"][1]["output"]+ assert len(folded) < len(grep_out)+ assert search_unheading(folded) == grep_out++def test_openai_responses_adapter_excludes_tool_case_insensitively_with_debug(monkeypatch):"""Excluded match is case-insensitive, and the debug path stays exercised.