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): honor x-headroom-base-url in dedicated OpenAI handlers (#1502)

Kirill6c48ac81f297
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6b0690211..94d86d103 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -62,6 +62,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* **proxy:** include the system prompt, tools, and the response-shaping request fields in the SemanticCache key. `_compute_key` hashed only `{model, messages}`, so two non-streaming requests with identical messages but a different top-level `system` prompt, tool set, sampling config, or output-shaping field collided on one key and the second caller was served the first's cached response — generated under different request semantics, in the default config (`cache_enabled` defaults on). The key now folds the request fields that shape generation — `temperature`/`top_p`/`top_k`/`max_tokens`/`stop`, plus OpenAI `tool_choice`/`response_format`/`parallel_tool_calls`/`seed`/`presence_penalty`/`frequency_penalty`/`logit_bias`/`n`/`logprobs`/`top_logprobs`/`reasoning_effort`/`verbosity`/`modalities` and Anthropic `thinking`/`tool_choice`/`output_config` — canonicalizing `system`/`tools` so a moved `cache_control` breakpoint does not fragment it, and the handlers snapshot the fields once at the cache read and reuse them at write so a body mutated by the pipeline cannot diverge the key. Non-streaming path only.
* **learn (verbosity):** `--verbosity --apply --all` now aggregates the savings baseline across every project instead of overwriting it per project (last-project-wins), which previously left the output shaper with a tiny, unrepresentative baseline. The applied verbosity level comes from the project with the most samples ([#1288](https://github.com/headroomlabs-ai/headroom/pull/1288)).
* **proxy/anthropic:** restore token-mode compression on continued Claude Code turns with a frozen prefix and deferred CCR tool injection. Token mode now runs request-side compression even when the client did not pre-register `headroom_retrieve`, relying on the existing marker-triggered injection override to keep emitted CCR markers redeemable ([#1487](https://github.com/headroomlabs-ai/headroom/issues/1487)).
+* **proxy:** the dedicated OpenAI handlers (`/v1/chat/completions`, `/v1/responses`) now honor the `x-headroom-base-url` request header, matching the generic passthrough route. Previously only the catch-all passthrough honored it, so OpenAI-compatible gateways (LiteLLM, CPA, self-hosted vLLM, Azure OpenAI) routed correctly for passthrough traffic but the dedicated chat/responses handlers ignored the header and fell back to the default `OPENAI_API_URL`, sending requests (and the user's provider key) to the wrong upstream.
* **subscription:** stop zeroing the 5-hour headroom contribution counters on every poll. The rollover check compared `five_hour.resets_at` with a bare `!=`, but the usage API reports that timestamp with second-level jitter (observed flapping between `01:59:59Z` and `02:00:00Z` on consecutive polls within the same window), so a spurious "5h window rolled over" reset fired every poll interval (~5 min) and the dashboard's per-window savings stuck near 0%. Only a forward jump larger than `_ROLLOVER_MIN_ADVANCE` (1 minute) now counts as a real rollover.
* **wrap:** keep the shared proxy alive when the agent that launched it closes *ungracefully* on Windows. `_start_proxy` spawned the proxy without detaching it, so it stayed in the launcher's console and Job object; closing that terminal window (or `taskkill`/a crash) tree-killed the proxy, bypassing the marker-based reference counting in `_make_cleanup` and breaking every other `headroom wrap` instance routed through the same port. The proxy is now created with `CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB` (with a graceful fallback when the launcher's Job forbids breakaway); POSIX behavior is unchanged. `CREATE_NO_WINDOW` (rather than `DETACHED_PROCESS`) gives the proxy its own *hidden* console: `DETACHED_PROCESS` leaves a console-subsystem exe (`python.exe`) consoleless, so Windows surfaces a visible console window whose close button kills the proxy.
* **transforms/content_router:** stop replacing `role="tool"` output with a lossy-unrecoverable summary on the live compression path (refs [#1307](https://github.com/chopratejas/headroom/issues/1307)). `ContentRouter.apply()` routed OpenAI-style `role="tool"` string messages — `Bash`/`grep`/`ls`/`cat` output — through the ML/word-drop summarizers; when the result carried no CCR retrieve marker (CCR off, ratio >= 0.8, or the size-gate fallback) the original was unrecoverable and the agent acted on a fabricated summary. Tool-role string content is now kept verbatim unless the compressed form is CCR-recoverable. Assistant/user text is unaffected, and structurally-lossless passes (SmartCrusher/Log/Search) still apply. The Anthropic `tool_result` block path is tracked separately.
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index ac8a6a7ce..4e7379924 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -784,6 +784,18 @@ class OpenAIHandlerMixin:
"""Return True when inbound headers request full passthrough."""
return _headroom_bypass_enabled(headers)
+ def _resolve_openai_upstream(self, request: Request) -> str:
+ """Return the OpenAI upstream base URL for ``request``.
+
+ Honors the ``x-headroom-base-url`` request header so OpenAI-compatible
+ gateways (LiteLLM, CPA, self-hosted vLLM, Azure OpenAI) route through
+ the dedicated ``/v1/chat/completions`` and ``/v1/responses`` handlers,
+ not just the generic passthrough route that already honors it. Falls
+ back to the configured ``OPENAI_API_URL`` (``OPENAI_TARGET_API_URL``).
+ """
+ custom = request.headers.get("x-headroom-base-url", "").strip()
+ return custom or self.OPENAI_API_URL
+
@staticmethod
def _strict_previous_turn_frozen_count(
messages: list[dict[str, Any]],
diff --git a/tests/test_proxy/test_openai_upstream_header.py b/tests/test_proxy/test_openai_upstream_header.py
new file mode 100644
index 000000000..87bfa1373
--- /dev/null
+++ b/tests/test_proxy/test_openai_upstream_header.py
@@ -0,0 +1,80 @@
+"""Tests for ``OpenAIHandlerMixin._resolve_openai_upstream``.
+
+The dedicated OpenAI handlers (``/v1/chat/completions``,
+``/v1/responses``) must honor the ``x-headroom-base-url`` request header
+so OpenAI-compatible gateways (LiteLLM, CPA, self-hosted vLLM, Azure
+OpenAI) route correctly — consistent with the generic passthrough route
+that already honors it (see ``providers/proxy_routes.py``).
+
+These tests pin the resolution contract:
+- header present → its value wins
+- header absent → configured ``OPENAI_API_URL`` fallback
+- header empty or whitespace-only → fallback (no blanking)
+"""
+
+from __future__ import annotations
+
+import pytest
+
+fastapi = pytest.importorskip("fastapi")
+httpx = pytest.importorskip("httpx")
+
+from starlette.datastructures import Headers # noqa: E402
+
+from headroom.proxy.handlers.openai import OpenAIHandlerMixin # noqa: E402
+
+
+class _FakeRequest:
+ """Minimal stand-in exposing ``headers`` like a real Starlette request.
+
+ Uses ``starlette.datastructures.Headers`` so header lookup is
+ case-insensitive, matching the production ``request.headers`` — a
+ plain ``dict`` would let case-folding regressions pass silently.
+ """
+
+ def __init__(self, headers: dict[str, str]) -> None:
+ self.headers = Headers(headers=headers)
+
+
+def _stub_proxy(fallback_url: str) -> OpenAIHandlerMixin:
+ """A bare mixin instance with only ``OPENAI_API_URL`` configured."""
+ return type( # type: ignore[return-value]
+ "_S",
+ (OpenAIHandlerMixin,),
+ {"OPENAI_API_URL": fallback_url},
+ )()
+
+
+def test_header_overrides_configured_url() -> None:
+ proxy = _stub_proxy("https://api.openai.test")
+ # The transport sends the upstream origin (no /v1 path).
+ request = _FakeRequest({"x-headroom-base-url": "https://gateway.example"})
+
+ assert proxy._resolve_openai_upstream(request) == "https://gateway.example"
+
+
+def test_missing_header_falls_back_to_configured_url() -> None:
+ proxy = _stub_proxy("https://api.openai.test")
+ request = _FakeRequest({})
+
+ assert proxy._resolve_openai_upstream(request) == "https://api.openai.test"
+
+
+def test_empty_header_falls_back_to_configured_url() -> None:
+ """An explicitly empty or whitespace-only header must not blank the upstream."""
+ proxy = _stub_proxy("https://api.openai.test")
+
+ empty = _FakeRequest({"x-headroom-base-url": ""})
+ assert proxy._resolve_openai_upstream(empty) == "https://api.openai.test"
+
+ whitespace = _FakeRequest({"x-headroom-base-url": " "})
+ assert proxy._resolve_openai_upstream(whitespace) == "https://api.openai.test"
+
+
+def test_header_lookup_is_case_insensitive() -> None:
+ """Transports may send mixed-case header names; lookup must still resolve."""
+ proxy = _stub_proxy("https://api.openai.test")
+ # Real transports routinely send Title-Case header names.
+ request = _FakeRequest({"X-Headroom-Base-Url": "https://gateway.example"})
+
+ assert proxy._resolve_openai_upstream(request) == "https://gateway.example"