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(proxy/openai): run tool-description compaction on chat-completions (#2741)

Tejas Chopraf9db5b506030
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index 1f8122fa3..1024238c3 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -3475,6 +3475,46 @@ class OpenAIHandlerMixin:
except Exception as e:
logger.debug(f"[{request_id}] tool schema compaction failed: {e}")
+ # Layer 2: tool description truncation (opt-in via
+ # HEADROOM_TOOL_DESC_MAX_CHARS). The Anthropic and Responses handlers
+ # both ran this pass; chat-completions never did, so the env var was a
+ # silent no-op for every chat client (opencode, Cline, Aider, Roo,
+ # LiteLLM-routed). Tool descriptions live on the tools array, which the
+ # message pipeline never sees, so nothing else was covering them.
+ # `compact_tool_descriptions` walks both the nested chat shape
+ # ({"function": {"description": ...}}) and the flat Responses shape.
+ try:
+ from headroom.proxy.tool_schema_compaction import (
+ compact_tool_descriptions,
+ tool_desc_max_chars,
+ )
+
+ _desc_max = tool_desc_max_chars()
+ if _desc_max > 0:
+ _desc_payload, _desc_modified, _desc_before, _desc_after = (
+ compact_tool_descriptions({"tools": tools}, _desc_max)
+ )
+ if _desc_modified and _desc_payload.get("tools") is not None:
+ # Seed "before" only if schema compaction above didn't; the
+ # two passes chain, so "after" must track the latest tools.
+ if not tool_tokens_before_compaction:
+ tool_tokens_before_compaction = tokenizer.count_text(
+ _json_debug_dumps(tools)
+ )
+ tools = _desc_payload["tools"]
+ transforms_applied.append("openai:chat:tool_desc_compaction")
+ logger.debug(
+ "[%s] tool description compaction: %d -> %d bytes "
+ "(%.0f%% saved, max_chars=%d)",
+ request_id,
+ _desc_before,
+ _desc_after,
+ (1 - _desc_after / max(_desc_before, 1)) * 100,
+ _desc_max,
+ )
+ except Exception as e:
+ logger.debug(f"[{request_id}] tool desc compaction failed: {e}")
+
body["messages"] = optimized_messages
if tools or _original_tools is not None:
body["tools"] = tools
diff --git a/tests/test_openai_chat_tool_desc_compaction.py b/tests/test_openai_chat_tool_desc_compaction.py
new file mode 100644
index 000000000..1018d373f
--- /dev/null
+++ b/tests/test_openai_chat_tool_desc_compaction.py
@@ -0,0 +1,126 @@
+"""Tool-description compaction must run on chat-completions, not just Anthropic/Responses.
+
+``HEADROOM_TOOL_DESC_MAX_CHARS`` was wired into the Anthropic handler and the
+Responses (Codex) handler but never into chat-completions, so the env var was a
+silent no-op for every chat client — opencode, Cline, Aider, Roo, anything routed
+through LiteLLM. Tool descriptions live on the ``tools`` array, which the message
+pipeline never inspects, so no other pass was covering them.
+
+These tests pin the shape handling and the opt-in gate rather than driving the
+whole handler: the handler block is a thin adapter over
+``compact_tool_descriptions``, and the thing that actually broke was that nobody
+called it with the chat-shaped payload.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+import headroom.proxy.tool_schema_compaction as tsc
+from headroom.proxy.tool_schema_compaction import compact_tool_descriptions, tool_desc_max_chars
+
+_LONG_DESC = "Reads a file from disk and returns the full text content as a string, with numbers."
+
+
[email protected](autouse=True)
+def _reset_desc_cache():
+ """The max-chars lookup is process-cached; clear it around each test."""
+ tsc._TOOL_DESC_MAX_CHARS = None
+ yield
+ tsc._TOOL_DESC_MAX_CHARS = None
+
+
+def _chat_tools() -> list[dict]:
+ """chat-completions shape: name/description nested under "function"."""
+ return [
+ {
+ "type": "function",
+ "function": {
+ "name": "read",
+ "description": _LONG_DESC,
+ "parameters": {
+ "type": "object",
+ "properties": {"path": {"type": "string", "description": "File path to read"}},
+ },
+ },
+ }
+ ]
+
+
+def _responses_tools() -> list[dict]:
+ """Responses shape: name/description flat on the tool."""
+ return [
+ {
+ "type": "function",
+ "name": "read",
+ "description": _LONG_DESC,
+ "parameters": {
+ "type": "object",
+ "properties": {"path": {"type": "string", "description": "File path to read"}},
+ },
+ }
+ ]
+
+
+def test_compacts_the_nested_chat_completions_tool_shape(monkeypatch):
+ """The shape the chat handler passes — the one that was never being compacted."""
+ monkeypatch.setenv("HEADROOM_TOOL_DESC_MAX_CHARS", "30")
+
+ payload, modified, before, after = compact_tool_descriptions(
+ {"tools": _chat_tools()}, tool_desc_max_chars()
+ )
+
+ assert modified is True
+ assert after < before
+ desc = payload["tools"][0]["function"]["description"]
+ assert len(desc) <= len(_LONG_DESC)
+ assert desc != _LONG_DESC
+
+
+def test_both_wire_shapes_are_handled(monkeypatch):
+ """One helper serves both handlers, so chat needed wiring — not a new codec."""
+ monkeypatch.setenv("HEADROOM_TOOL_DESC_MAX_CHARS", "30")
+ max_chars = tool_desc_max_chars()
+
+ _, chat_modified, chat_before, chat_after = compact_tool_descriptions(
+ {"tools": _chat_tools()}, max_chars
+ )
+ _, resp_modified, resp_before, resp_after = compact_tool_descriptions(
+ {"tools": _responses_tools()}, max_chars
+ )
+
+ assert chat_modified is resp_modified is True
+ assert chat_after < chat_before
+ assert resp_after < resp_before
+
+
+def test_disabled_by_default_leaves_tools_untouched():
+ """Opt-in only: an unset env var must not perturb the tools prefix or its cache."""
+ tools = _chat_tools()
+ assert tool_desc_max_chars() == 0
+
+ payload, modified, before, after = compact_tool_descriptions(
+ {"tools": tools}, tool_desc_max_chars()
+ )
+
+ assert modified is False
+ assert payload["tools"] == tools
+ assert (before, after) == (0, 0)
+
+
+def test_chat_handler_calls_the_desc_pass(monkeypatch):
+ """Guard the wiring itself: the handler source must invoke the L2 pass.
+
+ ponytail: source-level check, not a live handler drive — spinning the full
+ chat-completions path needs an upstream, and the regression here was a missing
+ CALL, which is exactly what this catches.
+ """
+ import inspect
+
+ from headroom.proxy.handlers import openai as openai_handler
+
+ source = inspect.getsource(openai_handler)
+ assert "openai:chat:tool_desc_compaction" in source
+ # The Anthropic and Responses handlers already had their own labels; make sure
+ # the chat one is distinct so `headroom perf --by-transform` can attribute it.
+ assert "openai:responses:tool_desc_compaction" in source