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(gateway): report why /v1/compress/response rejected a body (#4081)
Tejas Chopra5cac7ab693c2
diff --git a/headroom/proxy/gateway_turn.py b/headroom/proxy/gateway_turn.pyindex ea64e8362..bc7e31021 100644--- a/headroom/proxy/gateway_turn.py+++ b/headroom/proxy/gateway_turn.py@@ -1494,14 +1494,12 @@ async def handle_compress_response(proxy: Any, request: Any) -> Any:"""``POST /v1/compress/response`` — finish or re-drive a pending turn."""from fastapi.responses import JSONResponse- from headroom.proxy.helpers import _read_request_json+ from headroom.proxy.helpers import _read_request_json, invalid_request_body_messagetry:body = await _read_request_json(request)- except Exception:- return _error(400, "invalid_request", "Invalid JSON in request body.")- if not isinstance(body, dict):- return _error(400, "invalid_request", "Request body must be a JSON object.")+ except Exception as exc:+ return _error(400, "invalid_request", invalid_request_body_message(exc))turn_id = body.get("turn_id")if not isinstance(turn_id, str) or not turn_id.strip() or len(turn_id) > 128:diff --git a/tests/gateway/test_contract_response_half.py b/tests/gateway/test_contract_response_half.pyindex f0f347d73..8a8a86dd0 100644--- a/tests/gateway/test_contract_response_half.py+++ b/tests/gateway/test_contract_response_half.py@@ -104,6 +104,26 @@ def test_invalid_json_is_400(headroom_client) -> None:assert resp.status_code == 400+ ("content", "reason"),+ [+ (b"nope", "malformed JSON"),+ (b"[1, 2]", "must be a JSON object"),+ (b"\xff\xfe{}", "not valid UTF-8"),+ ],+ ids=["malformed", "not-object", "not-utf8"],+)+def test_invalid_body_400_says_why(headroom_client, content: bytes, reason: str) -> None:+ """The 400 names the reason, like every other handler's body errors."""+ resp = headroom_client.post(+ RESPONSE_HALF, content=content, headers={"content-type": "application/json"}+ )+ assert resp.status_code == 400+ error = resp.json()["error"]+ assert error["type"] == "invalid_request"+ assert reason in error["message"]++@pytest.mark.parametrize("extra",[