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(ccr): tolerate null/malformed OpenAI data in response handling (#2467)
Abhay Singhe583e082d8de
diff --git a/headroom/ccr/response_handler.py b/headroom/ccr/response_handler.pyindex 7c959e9a6..7cdea7a49 100644--- a/headroom/ccr/response_handler.py+++ b/headroom/ccr/response_handler.py@@ -403,7 +403,16 @@ class CCRResponseHandler:# echoed back verbatim as `input[]` items — not a single# role/content dict like chat completions. Sentinel key mirrors# `_openai_tool_results`; handle_response() extends on it.- return {"_openai_responses_output_items": response.get("output", [])}+ # `.get("output", [])` only falls back when the key is absent, so a+ # present-but-null `output` would return None and make the+ # `current_messages.extend(...)` in handle_response raise TypeError;+ # coerce to a list like the choices branch above.+ output_items = response.get("output")+ return {+ "_openai_responses_output_items": output_items+ if isinstance(output_items, list)+ else []+ }elif provider == "google":# Google/Gemini format: role is "model", content is in candidates[0].content.partscandidates = response.get("candidates", [])@@ -905,8 +914,17 @@ class StreamingCCRHandler:if "content" in delta and delta["content"]:message["content"] = (message.get("content") or "") + delta["content"]- if "tool_calls" in delta:- for tc_delta in delta["tool_calls"]:+ # Guard the value, not just the key: some OpenAI-compatible+ # providers include ``"tool_calls": null`` (and ``"function": null``)+ # in a delta rather than omitting the key, which would make the+ # iteration below raise ``TypeError: 'NoneType' object is not+ # iterable`` and abort the whole reconstruction. Mirrors the+ # ``and delta["content"]`` value-guard above.+ tool_calls = delta.get("tool_calls")+ if isinstance(tool_calls, list):+ for tc_delta in tool_calls:+ if not isinstance(tc_delta, dict):+ continueidx = tc_delta.get("index", 0)if idx not in tool_calls_map:tool_calls_map[idx] = {@@ -918,8 +936,8 @@ class StreamingCCRHandler:tc = tool_calls_map[idx]if "id" in tc_delta:tc["id"] = tc_delta["id"]- if "function" in tc_delta:- fn = tc_delta["function"]+ fn = tc_delta.get("function")+ if isinstance(fn, dict):if "name" in fn:tc["function"]["name"] = fn["name"]if "arguments" in fn:diff --git a/tests/test_ccr_response_handler_extra.py b/tests/test_ccr_response_handler_extra.pyindex 36d2849fb..1e8d97d93 100644--- a/tests/test_ccr_response_handler_extra.py+++ b/tests/test_ccr_response_handler_extra.py@@ -320,6 +320,60 @@ def test_streaming_buffer_and_parse_sse_helpers() -> None:)+def test_reconstruct_openai_response_tolerates_null_tool_calls_and_function() -> None:+ # Some OpenAI-compatible providers put ``"tool_calls": null`` (and+ # ``"function": null``) in a streaming delta instead of omitting the key.+ # Only checking key presence made the reconstruction iterate ``None`` and+ # raise ``TypeError``, aborting the whole CCR round.+ handler = StreamingCCRHandler(CCRResponseHandler(), provider="openai")++ parsed = handler._reconstruct_openai_response(+ [+ {"choices": [{"delta": {"content": "Hi", "tool_calls": None}}]},+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "function": None}]}}]},+ {+ "choices": [+ {+ "delta": {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_1",+ "function": {"name": "f", "arguments": "{}"},+ }+ ]+ }+ }+ ]+ },+ ]+ )++ message = parsed["choices"][0]["message"]+ # The null frames did not crash, and the real tool call still reconstructs.+ assert message["content"] == "Hi"+ assert message["tool_calls"][0]["id"] == "call_1"+ assert message["tool_calls"][0]["function"] == {"name": "f", "arguments": "{}"}+++def test_extract_assistant_message_responses_output_null_coerces_to_list() -> None:+ # A Responses turn with a present-but-null `output` (some gateways send this+ # on an empty/filtered turn) must not become None: handle_response later+ # does `current_messages.extend(...)` on it, which would raise TypeError.+ handler = CCRResponseHandler()++ assert handler._extract_assistant_message({"output": None}, "openai_responses") == {+ "_openai_responses_output_items": []+ }+ # An absent output is also an empty list, and a real output passes through.+ assert handler._extract_assistant_message({}, "openai_responses") == {+ "_openai_responses_output_items": []+ }+ assert handler._extract_assistant_message(+ {"output": [{"type": "message"}]}, "openai_responses"+ ) == {"_openai_responses_output_items": [{"type": "message"}]}++@pytest.mark.asyncioasync def test_streaming_handler_process_stream_pass_through_and_ccr(monkeypatch: pytest.MonkeyPatch,