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: PR-C5 retire responses_converter.py — Rust owns /v1/responses
chopratejas221109d95e6f
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex 2289e7899..c2915594f 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -1147,14 +1147,9 @@ class OpenAIHandlerMixin:from fastapi.responses import JSONResponse, Responsefrom headroom.proxy.helpers import (- COMPRESSION_TIMEOUT_SECONDS,MAX_REQUEST_BODY_SIZE,_read_request_json,)- from headroom.proxy.responses_converter import (- messages_to_responses_items,- responses_items_to_messages,- )from headroom.tokenizers import get_tokenizerfrom headroom.utils import extract_user_query@@ -1193,28 +1188,20 @@ class OpenAIHandlerMixin:model = body.get("model", "unknown")stream = body.get("stream", False)- # Convert Responses API input to messages format for optimization.- # The Responses API uses a different item model (function_call,- # function_call_output, reasoning as top-level items) — we convert to- # Chat Completions messages for the pipeline, then convert back.-+ # PR-C5: Python no longer compresses /v1/responses — Rust handles+ # item-aware compression natively (see crates/headroom-proxy/src/+ # handlers/responses.rs). We synthesise a minimal `messages` list+ # purely for downstream memory injection + telemetry; list-typed+ # `input` is consulted via `body["input"]` directly via the+ # live-zone-tail helpers below.input_data = body.get("input", "")instructions = body.get("instructions")- previous_response_id = body.get("previous_response_id")messages: list[dict[str, Any]] = []- original_items: list[dict[str, Any]] | None = None- preserved_indices: list[int] = []-if instructions:messages.append({"role": "system", "content": instructions})-if isinstance(input_data, str):messages.append({"role": "user", "content": input_data})- elif isinstance(input_data, list):- original_items = input_data- converted, preserved_indices = responses_items_to_messages(input_data)- messages.extend(converted)headers = dict(request.headers.items())headers.pop("host", None)@@ -1300,68 +1287,16 @@ class OpenAIHandlerMixin:tokenizer = get_tokenizer(model)original_tokens = tokenizer.count_messages(messages)- # Optimize: convert items → compress → convert back- tokens_saved = 0- transforms_applied: list[str] = []+ # PR-C5: Python compression on /v1/responses is retired — the Rust+ # handler at crates/headroom-proxy/src/handlers/responses.rs is the+ # canonical compression path. Defaults below feed downstream+ # telemetry and memory injection without invoking the pipeline.optimized_messages = messagesoptimized_tokens = original_tokens-- _bypass = (- request.headers.get("x-headroom-bypass", "").lower() == "true"- or request.headers.get("x-headroom-mode", "").lower() == "passthrough"- )- _should_compress = (- self.config.optimize- and original_items is not None- and not previous_response_id- and not _bypass- and len(messages) > 1- )- _license_ok = self.usage_reporter.should_compress if self.usage_reporter else True-- if _should_compress and _license_ok:- try:- context_limit = self.openai_provider.get_context_limit(model)- result = await self._run_compression_in_executor(- lambda: self.openai_pipeline.apply(- messages=messages,- model=model,- model_limit=context_limit,- context=extract_user_query(messages),- ),- timeout=COMPRESSION_TIMEOUT_SECONDS,- )- if result.messages != messages:- optimized_messages = result.messages- transforms_applied = result.transforms_applied- original_tokens = result.tokens_before- optimized_tokens = result.tokens_after- except Exception as e:- logger.warning(f"[{request_id}] Responses API optimization failed: {e}")-- # Guard: if "optimization" inflated tokens, revert to originals- if optimized_tokens > original_tokens:- logger.warning(- f"[{request_id}] Optimization inflated tokens "- f"({original_tokens} -> {optimized_tokens}), reverting to original messages"- )- optimized_messages = messages- optimized_tokens = original_tokens- transforms_applied = []-- tokens_saved = original_tokens - optimized_tokens+ tokens_saved = 0+ transforms_applied: list[str] = []optimization_latency = (time.time() - start_time) * 1000- # Convert compressed messages back to Responses API items- if optimized_messages is not messages and original_items is not None:- opt_msgs = optimized_messages- # Strip system message (instructions) — it's separate in Responses API- if instructions and opt_msgs and opt_msgs[0].get("role") == "system":- body["instructions"] = opt_msgs[0]["content"]- opt_msgs = opt_msgs[1:]-- body["input"] = messages_to_responses_items(opt_msgs, original_items, preserved_indices)-# Memory: inject context and tools for Responses API requestsif self.memory_handler and memory_user_id:try:@@ -1676,15 +1611,11 @@ class OpenAIHandlerMixin:Responses API. This handler:1. Accepts the client WebSocket2. Receives the first message (``response.create`` request)- 3. Compresses the ``input`` array using the existing pipeline- 4. Opens an upstream WebSocket to OpenAI- 5. Sends the compressed request upstream- 6. Relays all subsequent messages bidirectionally+ 3. Opens an upstream WebSocket to OpenAI+ 4. Sends the request upstream as-is (PR-C5: Python compression on+ /v1/responses retired — Rust handles item-aware compression)+ 5. Relays all subsequent messages bidirectionally"""- from headroom.proxy.helpers import COMPRESSION_TIMEOUT_SECONDS- from headroom.tokenizers import get_tokenizer- from headroom.utils import extract_user_query-try:import websocketsexcept ImportError:@@ -1920,87 +1851,16 @@ class OpenAIHandlerMixin:# deregister / metrics / stage-timings emission as usual.return- # --- Optional: compress the input in the first message ---+ # PR-C5: WebSocket /v1/responses no longer compresses in Python.+ # The Rust handler covers item-aware compression; the WS first+ # frame is now passed through unmodified.body: dict[str, Any] = {}+ tokens_saved = 0try:body = json.loads(first_msg_raw)- tokens_saved = 0- ws_request_body = body.get("response", body)- input_data = (- ws_request_body.get("input") if isinstance(ws_request_body, dict) else None- )-- should_compress = (- self.config.optimize- and isinstance(input_data, list)- and len(input_data) > 1- and not (- ws_request_body.get("previous_response_id")- if isinstance(ws_request_body, dict)- else None- )- )- if should_compress:- try:- from headroom.proxy.responses_converter import (- messages_to_responses_items,- responses_items_to_messages,- )-- model = ws_request_body.get("model", "gpt-4o")- converted, preserved = responses_items_to_messages(input_data)-- messages: list[dict[str, Any]] = []- instructions = ws_request_body.get("instructions")- if instructions:- messages.append({"role": "system", "content": instructions})- messages.extend(converted)-- tokenizer = get_tokenizer(model)- original_tokens = tokenizer.count_messages(messages)-- context_limit = self.openai_provider.get_context_limit(model)- async with stage_timer.measure("compression"):- result = await self._run_compression_in_executor(- lambda: self.openai_pipeline.apply(- messages=messages,- model=model,- model_limit=context_limit,- context=extract_user_query(messages),- ),- timeout=COMPRESSION_TIMEOUT_SECONDS,- )-- if result.messages != messages:- opt = result.messages- if instructions and opt and opt[0].get("role") == "system":- ws_request_body["instructions"] = opt[0]["content"]- opt = opt[1:]- if result.tokens_after <= original_tokens:- ws_request_body["input"] = messages_to_responses_items(- opt, input_data, preserved- )- else:- logger.warning(- f"[{request_id}] WS optimization inflated tokens "- f"({original_tokens} -> {result.tokens_after}), reverting"- )- tokens_saved = max(0, original_tokens - result.tokens_after)- if "response" in body and isinstance(body["response"], dict):- body["response"] = ws_request_body- else:- body = ws_request_body- first_msg_raw = json.dumps(body)- logger.info(- f"[{request_id}] WS /v1/responses compressed: "- f"saved {tokens_saved} tokens"- )- except Exception as e:- logger.warning(f"[{request_id}] WS compression failed: {e}")-except json.JSONDecodeError:# Not JSON — pass through as-is- tokens_saved = 0+ pass# --- Memory: inject context, tools, and instructions ---memory_user_id: str | None = None@@ -2034,13 +1894,11 @@ class OpenAIHandlerMixin:ws_msgs.append({"role": "system", "content": ws_instructions})if isinstance(ws_input, str) and ws_input:ws_msgs.append({"role": "user", "content": ws_input})- elif isinstance(ws_input, list):- from headroom.proxy.responses_converter import (- responses_items_to_messages,- )-- converted_msgs, _ = responses_items_to_messages(ws_input)- ws_msgs.extend(converted_msgs)+ # PR-C5: list-typed `input` no longer feeds memory+ # search via the Python converter — the Rust handler+ # owns native item-aware processing. Memory context+ # for list-input WS sessions falls back to the+ # `instructions` system message only.try:async with stage_timer.measure("memory_context"):diff --git a/headroom/proxy/responses_converter.py b/headroom/proxy/responses_converter.pydeleted file mode 100644index 37af5f3dc..000000000--- a/headroom/proxy/responses_converter.py+++ /dev/null@@ -1,336 +0,0 @@-"""Convert between OpenAI Responses API items and Chat Completions messages.--The Responses API uses a flat item model where function_call and-function_call_output are top-level items, content parts use input_text /-output_text types, and reasoning items must be preserved verbatim.--The Headroom compression pipeline works on Chat Completions messages-(role + content / tool_calls). This module converts back and forth so-the existing pipeline can compress Responses API input without changes.--Pattern follows the Gemini converter in server.py (_gemini_contents_to_messages).-"""--from __future__ import annotations--import copy-import logging-from typing import Any--logger = logging.getLogger(__name__)--# Content part types that indicate non-text media (must be preserved, not compressed)-_NON_TEXT_CONTENT_TYPES = frozenset(- {- "input_image",- "input_file",- "input_audio",- "image_url",- "image_file",- }-)--# Top-level keys that the Chat Completions schema understands; everything-# else (notably Codex's `phase` field, but also any future Responses API-# extension) gets stashed in the side-channel and restored on rebuild.-# Per PR-A8 / P0-7 + P4-44 the previous "preserved by accident via-# copy.copy" path was one refactor away from silent data loss; this list-# is the explicit contract.-_CHAT_COMPLETIONS_KNOWN_KEYS = frozenset(- {- "role",- "content",- "name",- "tool_call_id",- "tool_calls",- "type",- }-)---def responses_items_to_messages(- items: list[dict[str, Any]],- *,- request_id: str | None = None,-) -> tuple[list[dict[str, Any]], list[int]]:- """Convert Responses API input items to Chat Completions messages.-- Args:- items: The ``input`` array from a ``/v1/responses`` request.- Contains a mix of message items, function_call items,- function_call_output items, reasoning items, etc.- request_id: Optional request id for structured log lines when- unknown item types are encountered (PR-A8 / P4-47).-- Returns:- (messages, preserved_indices) where:- - messages: OpenAI Chat Completions format messages suitable for- the Headroom compression pipeline.- - preserved_indices: Indices into *items* for entries that must- be restored verbatim (reasoning, images, unknown types).- """- if not items:- return [], []-- messages: list[dict[str, Any]] = []- preserved_indices: list[int] = []- pending_tool_calls: list[tuple[int, dict[str, Any]]] = []-- for idx, item in enumerate(items):- item_type = item.get("type")- role = item.get("role")-- # --- Reasoning items: preserve exactly ---- if item_type == "reasoning":- _flush_pending(messages, pending_tool_calls)- preserved_indices.append(idx)- continue-- # --- function_call items: accumulate, flush as one assistant message ---- if item_type == "function_call":- pending_tool_calls.append((idx, item))- continue-- # --- function_call_output items: convert to role=tool ---- if item_type == "function_call_output":- _flush_pending(messages, pending_tool_calls)- messages.append(- {- "role": "tool",- "tool_call_id": item.get("call_id", ""),- "content": item.get("output", ""),- }- )- continue-- # --- Message items (role-based, with or without type="message") ---- if role is not None:- _flush_pending(messages, pending_tool_calls)- content = item.get("content", "")-- # Handle content part arrays- if isinstance(content, list):- if _has_non_text_parts(content):- preserved_indices.append(idx)- continue- content = _extract_text_from_parts(content)-- mapped_role = "system" if role == "developer" else role- messages.append({"role": mapped_role, "content": content})- continue-- # --- Unknown item type: preserve + warn ---- # PR-A8 / P4-47: emit a structured warning so operators see new- # Codex item types in flight (apply_patch V4A, local_shell_call- # argv, MCP items, compaction items). Until now this branch- # survived only because the catch-all is conservative; one- # refactor away from silent data loss without this signal.- _flush_pending(messages, pending_tool_calls)- logger.warning(- "unknown_responses_item_type item_type=%s item_id=%s request_id=%s",- item.get("type"),- item.get("id"),- request_id or "",- )- preserved_indices.append(idx)-- # Flush any trailing tool calls- _flush_pending(messages, pending_tool_calls)-- return messages, preserved_indices---def messages_to_responses_items(- messages: list[dict[str, Any]],- original_items: list[dict[str, Any]],- preserved_indices: list[int],-) -> list[dict[str, Any]]:- """Convert compressed Chat Completions messages back to Responses API items.-- Uses a two-pass approach:- 1. Index compressed messages by call_id (for tool outputs) and collect- regular messages in order.- 2. Walk original_items, restoring preserved items and substituting- compressed content where applicable.-- Args:- messages: Compressed messages from the pipeline.- original_items: The original ``input`` array (pre-compression).- preserved_indices: Indices returned by ``responses_items_to_messages``.-- Returns:- New items list with compressed content, ready to send to OpenAI.- """- if not original_items:- return []-- preserved_set = frozenset(preserved_indices)-- # --- Pass 1: Index compressed messages ---- tool_outputs: dict[str, str] = {} # call_id → compressed output- regular_msgs: list[dict[str, Any]] = []-- for msg in messages:- role = msg.get("role")- if role == "tool":- tool_outputs[msg.get("tool_call_id", "")] = msg.get("content", "")- elif role == "assistant" and msg.get("tool_calls"):- # function_call items pass through uncompressed — skip- pass- else:- regular_msgs.append(msg)-- # --- Pass 2: Reconstruct items ---- result: list[dict[str, Any]] = []- reg_idx = 0-- for orig_idx, item in enumerate(original_items):- # Preserved items go back exactly as they were- if orig_idx in preserved_set:- result.append(item)- continue-- item_type = item.get("type")-- if item_type == "function_call":- # Small — pass through unmodified- result.append(item)-- elif item_type == "function_call_output":- call_id = item.get("call_id", "")- compressed = tool_outputs.get(call_id, item.get("output", ""))- result.append({**item, "output": compressed})-- else:- # Regular message — take next compressed message- if reg_idx < len(regular_msgs):- msg = regular_msgs[reg_idx]- reg_idx += 1- result.append(_reconstruct_item(item, msg))- else:- # Safety: more original items than compressed messages- result.append(item)-- return result---# ----------------------------------------------------------------------------# Helpers-# ------------------------------------------------------------------------------def _flush_pending(- messages: list[dict[str, Any]],- pending: list[tuple[int, dict[str, Any]]],-) -> None:- """Flush accumulated function_call items as one assistant message."""- if not pending:- return- tool_calls = []- for _idx, item in pending:- tool_calls.append(- {- "id": item.get("call_id", ""),- "type": "function",- "function": {- "name": item.get("name", ""),- "arguments": item.get("arguments", "{}"),- },- }- )- messages.append(- {- "role": "assistant",- "content": None,- "tool_calls": tool_calls,- }- )- pending.clear()---def _has_non_text_parts(content: list[dict[str, Any]]) -> bool:- """Check if a content array contains non-text parts (images, files, audio)."""- return any(p.get("type") in _NON_TEXT_CONTENT_TYPES for p in content)---def _extract_text_from_parts(content: list[dict[str, Any]]) -> str:- """Extract text from Responses API content parts.-- Handles both input (input_text) and output (output_text) part types,- plus standard ``text`` parts.- """- parts = []- for p in content:- ptype = p.get("type", "")- if ptype in ("input_text", "output_text", "text"):- parts.append(p.get("text", ""))- return "\n".join(parts) if parts else ""---def _reconstruct_item(- original: dict[str, Any],- compressed_msg: dict[str, Any],-) -> dict[str, Any]:- """Rebuild a Responses API item from its original structure + compressed text.-- Preserves the original content format: if the original had- ``content: [{"type": "input_text", ...}]``, the compressed text goes- back into that same structure rather than being flattened to a string.-- PR-A8 / P0-7 + P4-44: phase preservation is now **explicit**. The- previous code path relied on ``copy.copy(original)`` to "accidentally"- carry the ``phase`` field through; here we copy + explicitly verify- every Responses-API-only key (anything outside- ``_CHAT_COMPLETIONS_KNOWN_KEYS``) is present after the rebuild.-- Multi-text-part contract: when ``original`` has N text parts and- compression collapses them into a single string (the pipeline- currently joins with ``\\n`` in ``_extract_text_from_parts``), we- rebuild a SINGLE text part (the first one in source order) carrying- the full compressed text. The remaining text parts are dropped to- avoid the doubling bug where compressed-content + original-content- both ended up on the wire (P0-7). Non-text parts (images, files,- audio) are passed through verbatim by index. If a future- pipeline emits multiple compressed strings per item, this- contract must be revisited.- """- compressed_text = compressed_msg.get("content", "")- original_content = original.get("content")-- # If original had a content-part array, reconstruct it.- if isinstance(original_content, list) and original_content:- new_content: list[dict[str, Any]] = []- text_replaced = False- for part in original_content:- ptype = part.get("type", "")- if ptype in ("input_text", "output_text", "text"):- if not text_replaced:- # Replace the FIRST text part's text in place;- # preserve any other fields on the part (e.g.- # `annotations`, future extensions).- new_content.append({**part, "text": compressed_text})- text_replaced = True- # else: drop this trailing text part — its content- # was already absorbed into the compressed string- # via ``_extract_text_from_parts``. Keeping it would- # double the content on the wire (the P0-7 bug).- else:- # Non-text parts (images, files, audio) pass through- # by index; their position relative to the text- # parts is preserved.- new_content.append(part)- rebuilt = copy.copy(original)- rebuilt["content"] = new_content- # Explicit Codex `phase` preservation (PR-A8 / P0-7 + P4-44):- # ``copy.copy`` already shallow-copies the field, but make the- # contract loud so future refactors don't silently lose it.- if "phase" in original:- rebuilt["phase"] = original["phase"]- return rebuilt-- # String content or missing — just replace- rebuilt = copy.copy(original)- rebuilt["content"] = compressed_text if compressed_text is not None else ""- if "phase" in original:- rebuilt["phase"] = original["phase"]- return rebuiltdiff --git a/tests/test_openai_codex_routing.py b/tests/test_openai_codex_routing.pyindex 2a75d3dec..02a34eb3d 100644--- a/tests/test_openai_codex_routing.py+++ b/tests/test_openai_codex_routing.py@@ -246,7 +246,10 @@ def test_handle_openai_responses_routes_chatgpt_auth_to_backend_api(monkeypatch)assert response.status_code == 200-def test_handle_openai_responses_stream_keeps_compression(monkeypatch):+def test_handle_openai_responses_stream_skips_python_compression(monkeypatch):+ """PR-C5: Python no longer compresses /v1/responses (Rust handles it+ natively). The streaming forward path must still fire — only the+ Python compression dispatch is retired."""request = _build_request({"model": "gpt-5.4",@@ -264,15 +267,6 @@ def test_handle_openai_responses_stream_keeps_compression(monkeypatch):)handler = _DummyOpenAIHandler()handler.config.optimize = True- handler.openai_pipeline.apply.return_value = SimpleNamespace(- messages=[- {"role": "system", "content": "Keep it short"},- {"role": "user", "content": "hello"},- ],- transforms_applied=[],- tokens_before=2,- tokens_after=2,- )monkeypatch.setattr("headroom.tokenizers.get_tokenizer", lambda model: _DummyTokenizer())@@ -280,7 +274,7 @@ def test_handle_openai_responses_stream_keeps_compression(monkeypatch):assert response.status_code == 200assert handler.captured_stream_request is not None- assert handler.openai_pipeline.apply.call_count == 1+ assert handler.openai_pipeline.apply.call_count == 0assert handler.captured_stream_request[2]["stream"] is Truediff --git a/tests/test_proxy_responses_phase_preservation.py b/tests/test_proxy_responses_phase_preservation.pydeleted file mode 100644index 2523655a1..000000000--- a/tests/test_proxy_responses_phase_preservation.py+++ /dev/null@@ -1,148 +0,0 @@-"""PR-A8 / P0-7 + P4-44 + P4-47: Responses API converter contract.--These tests pin:--- The Codex-emitted ``phase`` field (e.g. ``commentary`` /- ``final_answer``) survives a forward + reverse trip through the- Chat-Completions normalizer. Pre-A8 the field was preserved only- *accidentally* via ``copy.copy(original)``; one refactor away from- silent data loss.-- Multi-text-part rebuild collapses to a single text part on the way- back instead of doubling content (the P0-7 bug).-- Unknown item types log a structured warning (P4-47) so operators see- new Codex item types in flight.-"""--from __future__ import annotations--import json-import logging--from headroom.proxy.responses_converter import (- messages_to_responses_items,- responses_items_to_messages,-)---def test_codex_phase_commentary_preserved_through_compression() -> None:- """`phase: commentary` survives forward + reverse conversion."""- items = [- {- "type": "message",- "id": "msg_codex_1",- "role": "assistant",- "phase": "commentary",- "content": [{"type": "output_text", "text": "Here's my reasoning."}],- },- ]- messages, preserved = responses_items_to_messages(items)- assert preserved == []- assert len(messages) == 1- # Pretend the pipeline compressed nothing — feed messages back.- rebuilt = messages_to_responses_items(messages, items, preserved)- assert len(rebuilt) == 1- out = rebuilt[0]- assert out["phase"] == "commentary"- assert out["id"] == "msg_codex_1"- assert out["role"] == "assistant"---def test_codex_phase_final_answer_preserved() -> None:- """`phase: final_answer` survives even when content is compressed shorter."""- items = [- {- "type": "message",- "id": "msg_codex_2",- "role": "assistant",- "phase": "final_answer",- "content": [{"type": "output_text", "text": "Long original answer ..."}],- },- ]- messages, preserved = responses_items_to_messages(items)- # Simulate compression: replace the message content with a shorter string.- messages[0]["content"] = "Short."- rebuilt = messages_to_responses_items(messages, items, preserved)- assert rebuilt[0]["phase"] == "final_answer"- # Content was replaced inside the original part structure.- assert rebuilt[0]["content"][0]["text"] == "Short."---def test_unknown_item_type_logs_warning_byte_equal() -> None:- """Unknown item types preserve the item AND log a structured warning.-- Capture is done by attaching a handler directly to the named logger- rather than relying on `caplog`. Other tests in the suite (proxy- file-logging setup) flip `headroom.*.propagate = False`, which breaks- pytest's root-attached caplog handler in unrelated test runs. A- direct handler is order-independent.- """- items = [- {- "type": "apply_patch_v4a",- "id": "patch_1",- "patch": "--- a\n+++ b\n",- },- ]- target = logging.getLogger("headroom.proxy.responses_converter")- captured: list[logging.LogRecord] = []-- class _CaptureHandler(logging.Handler):- def emit(self, record: logging.LogRecord) -> None:- captured.append(record)-- handler = _CaptureHandler(level=logging.WARNING)- prev_level = target.level- target.addHandler(handler)- target.setLevel(logging.WARNING)- try:- messages, preserved = responses_items_to_messages(items, request_id="req-xyz")- finally:- target.removeHandler(handler)- target.setLevel(prev_level)-- # Item is preserved (byte-equal) on the rebuild side.- assert preserved == [0]- rebuilt = messages_to_responses_items(messages, items, preserved)- assert rebuilt == items- # A structured warning fired with the unknown type.- matched = [r for r in captured if "unknown_responses_item_type" in r.getMessage()]- assert matched, "expected unknown_responses_item_type warning log line"- msg = matched[0].getMessage()- assert "apply_patch_v4a" in msg- assert "patch_1" in msg- assert "req-xyz" in msg---def test_multi_text_part_rebuild_no_doubling() -> None:- """Two-text-part input is collapsed to a single part on rebuild — no doubling."""- items = [- {- "type": "message",- "id": "msg_multi",- "role": "user",- "content": [- {"type": "input_text", "text": "First paragraph."},- {"type": "input_text", "text": "Second paragraph."},- ],- },- ]- messages, preserved = responses_items_to_messages(items)- # The two text parts join with `\n`.- assert messages[0]["content"] == "First paragraph.\nSecond paragraph."- # Pretend compression replaced with a shortened single string.- messages[0]["content"] = "Para one. Para two."- rebuilt = messages_to_responses_items(messages, items, preserved)- out_content = rebuilt[0]["content"]- # Critical: there is now exactly ONE text part on the rebuild,- # carrying the compressed string. The previous bug left a- # second part with the ORIGINAL "Second paragraph." text and- # the compressed string in part 0 — content doubled on the wire.- assert isinstance(out_content, list)- text_parts = [p for p in out_content if p.get("type") == "input_text"]- assert len(text_parts) == 1, (- f"expected exactly 1 text part on rebuild, got {len(text_parts)} — "- f"this is the P0-7 doubling bug regression"- )- assert text_parts[0]["text"] == "Para one. Para two."- # And the round-trip JSON is well-formed.- assert json.dumps(rebuilt)diff --git a/tests/test_responses_converter.py b/tests/test_responses_converter.pydeleted file mode 100644index bebf5a1fb..000000000--- a/tests/test_responses_converter.py+++ /dev/null@@ -1,408 +0,0 @@-"""Tests for OpenAI Responses API ↔ Chat Completions message conversion.--Tests cover:-1. Forward conversion (Responses items → Chat Completions messages)-2. Reverse conversion (compressed messages → Responses items)-3. Round-trip fidelity (convert → compress → convert back)-4. Edge cases (empty input, unknown types, mixed ordering)-"""--from __future__ import annotations--import json--from headroom.proxy.responses_converter import (- messages_to_responses_items,- responses_items_to_messages,-)--# =============================================================================-# Forward conversion: responses_items_to_messages-# =============================================================================---class TestItemsToMessages:- """Test converting Responses API items to Chat Completions messages."""-- def test_simple_user_message(self):- """String content user message passes through."""- items = [{"role": "user", "content": "Hello"}]- messages, preserved = responses_items_to_messages(items)-- assert len(messages) == 1- assert messages[0] == {"role": "user", "content": "Hello"}- assert preserved == []-- def test_content_array_input_text(self):- """input_text content parts are extracted to plain text."""- items = [- {- "role": "user",- "content": [{"type": "input_text", "text": "What is 2+2?"}],- }- ]- messages, preserved = responses_items_to_messages(items)-- assert len(messages) == 1- assert messages[0]["role"] == "user"- assert messages[0]["content"] == "What is 2+2?"-- def test_output_text_assistant(self):- """output_text content parts from assistant messages are extracted."""- items = [- {- "type": "message",- "role": "assistant",- "content": [{"type": "output_text", "text": "The answer is 4."}],- }- ]- messages, preserved = responses_items_to_messages(items)-- assert len(messages) == 1- assert messages[0]["role"] == "assistant"- assert messages[0]["content"] == "The answer is 4."-- def test_function_call_to_tool_calls(self):- """Single function_call item becomes assistant message with tool_calls."""- items = [- {- "type": "function_call",- "call_id": "call_abc",- "name": "get_weather",- "arguments": '{"city": "Paris"}',- }- ]- messages, preserved = responses_items_to_messages(items)-- assert len(messages) == 1- msg = messages[0]- assert msg["role"] == "assistant"- assert msg["content"] is None- assert len(msg["tool_calls"]) == 1- tc = msg["tool_calls"][0]- assert tc["id"] == "call_abc"- assert tc["function"]["name"] == "get_weather"- assert tc["function"]["arguments"] == '{"city": "Paris"}'-- def test_consecutive_function_calls_merge(self):- """Consecutive function_call items merge into one assistant message."""- items = [- {- "type": "function_call",- "call_id": "call_1",- "name": "search",- "arguments": '{"q": "foo"}',- },- {- "type": "function_call",- "call_id": "call_2",- "name": "read_file",- "arguments": '{"path": "/tmp/x"}',- },- ]- messages, preserved = responses_items_to_messages(items)-- assert len(messages) == 1- assert len(messages[0]["tool_calls"]) == 2- assert messages[0]["tool_calls"][0]["id"] == "call_1"- assert messages[0]["tool_calls"][1]["id"] == "call_2"-- def test_function_call_output_to_tool_role(self):- """function_call_output becomes role=tool message."""- items = [- {- "type": "function_call_output",- "call_id": "call_abc",- "output": '{"temp": 22, "unit": "C"}',- }- ]- messages, preserved = responses_items_to_messages(items)-- assert len(messages) == 1- assert messages[0]["role"] == "tool"- assert messages[0]["tool_call_id"] == "call_abc"- assert messages[0]["content"] == '{"temp": 22, "unit": "C"}'-- def test_reasoning_preserved(self):- """Reasoning items go to preserved_indices, not messages."""- items = [- {"role": "user", "content": "Think hard."},- {- "type": "reasoning",- "id": "rs_1",- "summary": [{"type": "summary_text", "text": "Thinking..."}],- },- {- "type": "message",- "role": "assistant",- "content": [{"type": "output_text", "text": "Done."}],- },- ]- messages, preserved = responses_items_to_messages(items)-- assert len(messages) == 2 # user + assistant (reasoning skipped)- assert 1 in preserved # index 1 is the reasoning item-- def test_image_content_preserved(self):- """Items with input_image content are preserved, not converted."""- items = [- {- "role": "user",- "content": [- {"type": "input_text", "text": "Describe this image."},- {"type": "input_image", "image_url": "data:image/png;base64,abc"},- ],- }- ]- messages, preserved = responses_items_to_messages(items)-- assert len(messages) == 0 # skipped (has non-text)- assert 0 in preserved-- def test_developer_maps_to_system(self):- """developer role maps to system."""- items = [{"role": "developer", "content": "You are helpful."}]- messages, preserved = responses_items_to_messages(items)-- assert messages[0]["role"] == "system"- assert messages[0]["content"] == "You are helpful."-- def test_system_passthrough(self):- """system role passes through as-is."""- items = [{"role": "system", "content": "Be concise."}]- messages, preserved = responses_items_to_messages(items)-- assert messages[0]["role"] == "system"- assert messages[0]["content"] == "Be concise."-- def test_message_type_item(self):- """Item with explicit type='message' is handled."""- items = [- {"type": "message", "role": "user", "content": "Hi"},- ]- messages, preserved = responses_items_to_messages(items)-- assert messages[0] == {"role": "user", "content": "Hi"}-- def test_empty_input(self):- """Empty items list produces empty messages."""- messages, preserved = responses_items_to_messages([])- assert messages == []- assert preserved == []-- def test_unknown_type_preserved(self):- """Unknown item types are preserved, not converted."""- items = [{"type": "some_future_type", "data": "something"}]- messages, preserved = responses_items_to_messages(items)-- assert len(messages) == 0- assert 0 in preserved-- def test_function_call_flush_on_non_function_call(self):- """Pending function_calls flush when a non-function_call item arrives."""- items = [- {"type": "function_call", "call_id": "c1", "name": "f1", "arguments": "{}"},- {"type": "function_call_output", "call_id": "c1", "output": "result"},- ]- messages, preserved = responses_items_to_messages(items)-- # Should be: assistant (tool_calls), tool (output)- assert len(messages) == 2- assert messages[0]["role"] == "assistant"- assert messages[0]["tool_calls"][0]["id"] == "c1"- assert messages[1]["role"] == "tool"---# =============================================================================-# Reverse conversion: messages_to_responses_items-# =============================================================================---class TestMessagesToItems:- """Test converting compressed messages back to Responses API items."""-- def test_round_trip_simple(self):- """Simple user/assistant conversation round-trips."""- original = [- {"role": "user", "content": "Hello"},- {"type": "message", "role": "assistant", "content": "Hi!"},- ]- messages, preserved = responses_items_to_messages(original)- result = messages_to_responses_items(messages, original, preserved)-- assert len(result) == 2- assert result[0]["content"] == "Hello"- assert result[1]["content"] == "Hi!"-- def test_round_trip_with_tools(self):- """Full tool call flow round-trips correctly."""- original = [- {"role": "user", "content": "Weather in Paris?"},- {- "type": "function_call",- "call_id": "call_1",- "name": "get_weather",- "arguments": '{"city": "Paris"}',- },- {- "type": "function_call_output",- "call_id": "call_1",- "output": "Sunny, 22C",- },- {- "type": "message",- "role": "assistant",- "content": [{"type": "output_text", "text": "It's sunny."}],- },- ]- messages, preserved = responses_items_to_messages(original)-- assert len(messages) == 4 # user, assistant(tool_calls), tool, assistant-- result = messages_to_responses_items(messages, original, preserved)-- assert len(result) == 4- # function_call passes through unmodified- assert result[1]["type"] == "function_call"- assert result[1]["call_id"] == "call_1"- # function_call_output has original content (no compression happened)- assert result[2]["type"] == "function_call_output"- assert result[2]["output"] == "Sunny, 22C"-- def test_round_trip_compressed_output(self):- """Simulated compression: shortened tool output appears in result."""- original = [- {"role": "user", "content": "Get data"},- {- "type": "function_call",- "call_id": "call_1",- "name": "search",- "arguments": "{}",- },- {- "type": "function_call_output",- "call_id": "call_1",- "output": json.dumps([{"id": i, "name": f"item_{i}"} for i in range(100)]),- },- ]- messages, preserved = responses_items_to_messages(original)-- # Simulate compression: replace tool output with shorter version- for msg in messages:- if msg.get("role") == "tool":- msg["content"] = "[100 items, first: item_0, last: item_99]"-- result = messages_to_responses_items(messages, original, preserved)-- assert result[2]["type"] == "function_call_output"- assert result[2]["output"] == "[100 items, first: item_0, last: item_99]"-- def test_round_trip_with_reasoning(self):- """Reasoning items survive round-trip exactly."""- reasoning_item = {- "type": "reasoning",- "id": "rs_abc",- "summary": [{"type": "summary_text", "text": "Let me think..."}],- }- original = [- {"role": "user", "content": "Complex question"},- reasoning_item,- {"type": "message", "role": "assistant", "content": "Answer."},- ]- messages, preserved = responses_items_to_messages(original)- result = messages_to_responses_items(messages, original, preserved)-- assert len(result) == 3- assert result[1] == reasoning_item # Exact match- assert result[1]["type"] == "reasoning"-- def test_round_trip_content_array_preserved(self):- """Content array structure (input_text) is preserved through round-trip."""- original = [- {- "role": "user",- "content": [{"type": "input_text", "text": "Original question"}],- },- ]- messages, preserved = responses_items_to_messages(original)-- # Simulate compression changing the text- messages[0]["content"] = "Compressed question"-- result = messages_to_responses_items(messages, original, preserved)-- # Should reconstruct the array structure- assert isinstance(result[0]["content"], list)- assert result[0]["content"][0]["type"] == "input_text"- assert result[0]["content"][0]["text"] == "Compressed question"-- def test_mixed_ordering(self):- """Complex sequence maintains correct ordering."""- original = [- {"role": "user", "content": "Do two things"},- {- "type": "function_call",- "call_id": "c1",- "name": "task_a",- "arguments": "{}",- },- {- "type": "function_call",- "call_id": "c2",- "name": "task_b",- "arguments": "{}",- },- {- "type": "function_call_output",- "call_id": "c1",- "output": "Result A",- },- {- "type": "function_call_output",- "call_id": "c2",- "output": "Result B",- },- {- "type": "reasoning",- "id": "rs_1",- "summary": [{"type": "summary_text", "text": "Thinking..."}],- },- {"type": "message", "role": "assistant", "content": "All done."},- ]- messages, preserved = responses_items_to_messages(original)- result = messages_to_responses_items(messages, original, preserved)-- assert len(result) == 7- assert result[0]["role"] == "user"- assert result[1]["type"] == "function_call"- assert result[1]["call_id"] == "c1"- assert result[2]["type"] == "function_call"- assert result[2]["call_id"] == "c2"- assert result[3]["type"] == "function_call_output"- assert result[3]["call_id"] == "c1"- assert result[4]["type"] == "function_call_output"- assert result[4]["call_id"] == "c2"- assert result[5]["type"] == "reasoning"- assert result[6]["content"] == "All done."-- def test_image_preserved_in_round_trip(self):- """Image items survive round-trip at their original position."""- image_item = {- "role": "user",- "content": [- {"type": "input_text", "text": "Describe this"},- {"type": "input_image", "image_url": "https://example.com/img.png"},- ],- }- original = [- {"role": "user", "content": "Hi"},- image_item,- {"role": "user", "content": "Also tell me about this"},- ]- messages, preserved = responses_items_to_messages(original)- result = messages_to_responses_items(messages, original, preserved)-- assert len(result) == 3- assert result[0]["content"] == "Hi"- assert result[1] == image_item # Preserved exactly- assert result[2]["content"] == "Also tell me about this"