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): preserve sub-path in X-Headroom-Base-Url custom upstream (#2037) (#2127)

Tejas Chopra2976d49f18f3
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index ec9cf1a4b..2eb4d0d65 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -190,6 +190,14 @@ def _resolve_openai_upstream_base(request_headers: dict[str, str]) -> str | None
normalized = _normalize_origin(raw_base_url)
if normalized is None:
return None
+
+ # _normalize_origin drops the path; re-attach it so a custom upstream served
+ # from a sub-path (e.g. https://host/api/v1) is preserved rather than routed
+ # to the bare origin.
+ path = (urlparse(raw_base_url.strip()).path or "").rstrip("/")
+ if path:
+ normalized = f"{normalized}{path}"
+
if urlparse(normalized).scheme not in {"http", "https"}:
return None
return normalized
diff --git a/tests/test_proxy/test_openai_upstream_header.py b/tests/test_proxy/test_openai_upstream_header.py
index 87bfa1373..ad34dd72f 100644
--- a/tests/test_proxy/test_openai_upstream_header.py
+++ b/tests/test_proxy/test_openai_upstream_header.py
@@ -78,3 +78,16 @@ def test_header_lookup_is_case_insensitive() -> None:
request = _FakeRequest({"X-Headroom-Base-Url": "https://gateway.example"})
assert proxy._resolve_openai_upstream(request) == "https://gateway.example"
+
+
+def test_header_with_subpath_preserves_path() -> None:
+ """A custom upstream served from a sub-path (e.g. /api/v1) must keep the path,
+ not be collapsed to the bare origin (#2047)."""
+ proxy = _stub_proxy("https://api.openai.test")
+ request = _FakeRequest({"x-headroom-base-url": "https://gateway.example/api/v1"})
+
+ assert proxy._resolve_openai_upstream(request) == "https://gateway.example/api/v1"
+
+ # Trailing slash is normalized away, not doubled.
+ trailing = _FakeRequest({"x-headroom-base-url": "https://gateway.example/api/v1/"})
+ assert proxy._resolve_openai_upstream(trailing) == "https://gateway.example/api/v1"