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): skip OpenAI tool_search deferral for Codex client (#2729)
AxelRay56b3e4c1b1e3
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex 1ac86f265..1f8122fa3 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -2209,6 +2209,7 @@ class OpenAIHandlerMixin:model: str,request_id: str,timing: dict[str, float] | None = None,+ client: str | None = None,) -> tuple[dict[str, Any], bool, int, list[str], str | None, int, int, int]:"""Compress an OpenAI Responses payload through the shared router.@@ -2346,7 +2347,9 @@ class OpenAIHandlerMixin:# one — hence a transform tag but no tokens_saved claim.from headroom.proxy.helpers import inject_tool_search_deferral_openai- _deferred_tools = inject_tool_search_deferral_openai(working.get("tools"), model)+ _deferred_tools = inject_tool_search_deferral_openai(+ working.get("tools"), model, client=client+ )if _deferred_tools is not working.get("tools"):if working is payload:working = copy.deepcopy(payload)@@ -2548,6 +2551,7 @@ class OpenAIHandlerMixin:model: str,request_id: str,timeout: float = COMPRESSION_TIMEOUT_SECONDS,+ client: str | None = None,) -> tuple[dict[str, Any], bool, int, list[str], str | None, int, int, int, dict[str, float]]:timing: dict[str, float] = {}@@ -2562,21 +2566,32 @@ class OpenAIHandlerMixin:shape_labels, shape_mutated = _shape_openai_responses_payload(payload, model=model, request_id=request_id)- try:- result = self._compress_openai_responses_payload(- payload,- model=model,- request_id=request_id,- timing=timing,- )- except TypeError as exc:- if "unexpected keyword argument 'timing'" not in str(exc):- raise- result = self._compress_openai_responses_payload(- payload,- model=model,- request_id=request_id,- )+ compression_kwargs: dict[str, Any] = {+ "model": model,+ "request_id": request_id,+ "timing": timing,+ "client": client,+ }+ while True:+ try:+ result = self._compress_openai_responses_payload(+ payload,+ **compression_kwargs,+ )+ break+ except TypeError as exc:+ unsupported_kwarg = next(+ (+ name+ for name in ("client", "timing")+ if f"unexpected keyword argument '{name}'" in str(exc)+ and name in compression_kwargs+ ),+ None,+ )+ if unsupported_kwarg is None:+ raise+ compression_kwargs.pop(unsupported_kwarg)if shape_labels:# Carry the shaper labels on the transforms channel so the# outcome funnel feeds the output-savings ledger@@ -4917,6 +4932,7 @@ class OpenAIHandlerMixin:body,model=model,request_id=request_id,+ client=client,)attempted_input_tokens = int(_attempted_tokens)if _transforms:@@ -6559,6 +6575,7 @@ class OpenAIHandlerMixin:timeout=_codex_ws_compression_timeout_seconds()if client == "codex"else COMPRESSION_TIMEOUT_SECONDS,+ client=client,)for _timing_name, _timing_ms in _ws_compression_timing.items():_record_ws_compression_timing(_timing_name, _timing_ms)@@ -6904,6 +6921,7 @@ class OpenAIHandlerMixin:timeout=_codex_ws_compression_timeout_seconds()if client == "codex"else COMPRESSION_TIMEOUT_SECONDS,+ client=client,)for _timing_name, _timing_ms in frame_compression_timing.items():_record_ws_compression_timing(_timing_name, _timing_ms)@@ -8650,7 +8668,9 @@ class OpenAIHandlerMixin:},)- async def _maybe_compress_passthrough_responses(self, body: bytes) -> bytes:+ async def _maybe_compress_passthrough_responses(+ self, body: bytes, *, client: str | None = None+ ) -> bytes:"""Compress an OpenAI Responses-shaped passthrough body, fail-open.Reuses the native `/v1/responses` compression path so custom@@ -8669,15 +8689,22 @@ class OpenAIHandlerMixin:model = str(payload.get("model") or "passthrough")request_id = await self._next_request_id()try:- (- compressed_payload,- modified,- *_rest,- ) = await self._compress_openai_responses_payload_in_executor(- payload,- model=model,- request_id=request_id,- )+ try:+ result = await self._compress_openai_responses_payload_in_executor(+ payload,+ model=model,+ request_id=request_id,+ client=client,+ )+ except TypeError as exc:+ if "unexpected keyword argument 'client'" not in str(exc):+ raise+ result = await self._compress_openai_responses_payload_in_executor(+ payload,+ model=model,+ request_id=request_id,+ )+ compressed_payload, modified, *_rest = resultexcept Exception as exc: # noqa: BLE001 — fail-open on any compressor errorlogger.warning("[%s] passthrough Responses compression failed, forwarding verbatim: %s",@@ -8792,7 +8819,7 @@ class OpenAIHandlerMixin:and path.rstrip("/").endswith("/responses")and body):- compressed = await self._maybe_compress_passthrough_responses(body)+ compressed = await self._maybe_compress_passthrough_responses(body, client=client)if compressed != body:body = compressed# Body size changed — let httpx recompute Content-Length.diff --git a/headroom/proxy/helpers.py b/headroom/proxy/helpers.pyindex faa1d0ed5..39697dc0e 100644--- a/headroom/proxy/helpers.py+++ b/headroom/proxy/helpers.py@@ -2421,6 +2421,7 @@ def inject_tool_search_deferral(_OPENAI_TOOL_SEARCH_TYPE = "tool_search"_OPENAI_TOOL_SEARCH_MIN_TOOLS = 12_OPENAI_TOOL_SEARCH_RESIDENT_NAMES = frozenset({"terminal"})+_OPENAI_TOOL_SEARCH_UNSUPPORTED_CLIENTS = frozenset({"codex"})# gpt-5.4 is the first model with Responses tool_search (OpenAI docs). Version-# gated by default; overridable per deployment via a regex in# HEADROOM_OPENAI_TOOL_SEARCH_MODELS (matched against the model name) so new@@ -2451,24 +2452,34 @@ def _model_supports_openai_tool_search(model: str | None) -> bool:return (major, minor) >= _OPENAI_TOOL_SEARCH_MIN_VERSION+def openai_tool_search_client_supported(client: str | None) -> bool:+ """Return whether OpenAI tool search deferral is safe for this client."""+ normalized = client.strip().lower() if client else ""+ return normalized not in _OPENAI_TOOL_SEARCH_UNSUPPORTED_CLIENTS++def inject_tool_search_deferral_openai(tools: Any,model: str | None,*,+ client: str | None = None,core_tools: frozenset[str] = _TOOL_SEARCH_CORE_TOOLS,) -> Any:"""Return a new Responses ``tools`` list with non-core function/MCP toolsdeferred + a ``{"type": "tool_search"}`` tool injected, or the original listunchanged when injection doesn't apply.- No-op when: the model doesn't support tool search (gpt-5.4+ only), ``tools``+ No-op for Codex, whose round-trip structs drop deferred-call namespaces. Also+ no-op when: the model doesn't support tool search (gpt-5.4+ only), ``tools``is not a list, there are fewer than ``_OPENAI_TOOL_SEARCH_MIN_TOOLS``, atool_search tool is already present (client already defers), or nothing wouldbe deferred. Core coding tools and hosted/typed tools (web_search,- file_search, code_interpreter, computer, …) stay resident and unchanged, so- routine edit/read/run loops never pay a search round-trip and the request+ file_search, code_interpreter, computer, ...) stay resident and unchanged,+ so routine edit/read/run loops never pay a search round-trip and the requeststays valid; the injected search tool is itself resident."""+ if not openai_tool_search_client_supported(client):+ return toolsif not _model_supports_openai_tool_search(model):return toolsif not isinstance(tools, list) or len(tools) < _OPENAI_TOOL_SEARCH_MIN_TOOLS:diff --git a/tests/test_openai_tool_search_deferral.py b/tests/test_openai_tool_search_deferral.pyindex 070ddbd60..da149f846 100644--- a/tests/test_openai_tool_search_deferral.py+++ b/tests/test_openai_tool_search_deferral.py@@ -15,6 +15,7 @@ import pytestfrom headroom.proxy.helpers import (_model_supports_openai_tool_search,inject_tool_search_deferral_openai,+ openai_tool_search_client_supported,)@@ -57,6 +58,35 @@ def test_env_override_wins_then_falls_back(monkeypatch):# --- deferral behavior -------------------------------------------------------+ ("client", "supported"),+ [(None, True), ("codex", False), (" CODEX ", False), ("opencode", True), ("claude", True)],+)+def test_client_supported(client, supported):+ assert openai_tool_search_client_supported(client) is supported+++def test_codex_client_does_not_inject():+ tools = _tools()++ out = inject_tool_search_deferral_openai(tools, "gpt-5.5", client="codex")++ assert out is tools+ assert all(tool.get("type") != "tool_search" for tool in out)+ assert all("defer_loading" not in tool for tool in out)++[email protected]("client", [None, "opencode"])+def test_supported_clients_still_inject(client):+ tools = _tools()++ out = inject_tool_search_deferral_openai(tools, "gpt-5.5", client=client)++ assert out is not tools+ assert out[0] == {"type": "tool_search"}+ assert any(tool.get("defer_loading") is True for tool in out)++def test_defers_non_core_and_injects_search_tool():tools = _tools()out = inject_tool_search_deferral_openai(tools, "gpt-5.5")