mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-08-27 14:17:10 -04:00
## Description
Fix three related gaps in Bedrock support that prevented headroom from
working with Claude Code when `CLAUDE_CODE_USE_BEDROCK=0` and
`ANTHROPIC_BASE_URL` is pointed at the proxy:
1. **ARN passthrough used the wrong LiteLLM route** — application
inference profile ARNs (e.g.
`arn:aws:bedrock:ap-southeast-2:<account>:application-inference-profile/<id>`)
were forwarded as `bedrock/<arn>`, which LiteLLM rejects with HTTP 400
"Try calling via converse route". Fixed to `bedrock/converse/<arn>`.
2. **Named AWS profile not forwarded to completion calls** —
`--bedrock-profile` was wired through the CLI → config →
`LiteLLMBackend.__init__` and used to fetch the model map at startup,
but never stored on `self`. All four `acompletion()` call sites
(`send_message`, `stream_message`, `send_openai_message`,
`stream_openai_message`) passed only `aws_region_name` — the
actual Bedrock calls used ambient credentials regardless of the flag.
Fixed by storing `self.profile_name` and passing `aws_profile_name=` to
every `acompletion()` call.
3. **`ap-southeast-2` used the wrong region prefix** — Australia should
use `au.` for cross-region inference profile IDs, not `apac.`. Added
`ap-southeast-2 → "au"` to `_BEDROCK_REGION_PREFIXES` and `"au."` to the
strip list in `_normalize_bedrock_profile_id`.
Closes #
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- `backends/litellm.py`: route `arn:aws:` model IDs via
`bedrock/converse/<arn>` in `map_model_id`
- `backends/litellm.py`: store `profile_name` as `self.profile_name` in
`LiteLLMBackend.__init__`; pass `aws_profile_name=` to `acompletion()`
in all four call sites; use
`boto3.Session(profile_name=...)` for startup discovery; cache key is
`region:profile_name` to prevent cross-profile collisions
- `backends/litellm.py`: add `ap-southeast-2 → "au"` to
`_BEDROCK_REGION_PREFIXES`; add `"au."` to prefix strip list in
`_normalize_bedrock_profile_id`
- `providers/registry.py`: pass `profile_name=bedrock_profile` to
`LiteLLMBackend`
- `proxy/server.py`: pass `config.bedrock_profile` to
`create_proxy_backend`
- `docs/claude-code-bedrock-headroom.md`: remove false claim that ARNs
in `ANTHROPIC_DEFAULT_*_MODEL` bypass the proxy; fix troubleshooting
table
- `tests/test_bedrock_region.py`: update `test_arn_passthrough` to
expect `bedrock/converse/<arn>`; update cache key format; add
`test_profile_cache_isolation`,
`test_ap_southeast_2_uses_au_prefix`, and
`TestBedrockProfileForwardedToCompletion` (3 async tests asserting
`aws_profile_name` appears in `acompletion()` kwargs for named profiles
and is
absent for the no-profile case)
- `tests/test_provider_registry*.py`,
`test_vertex_claude_compression.py`: update `litellm_backend_cls` stubs
to accept `profile_name=None`
## Testing
- [x] Unit tests pass (`pytest`)
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
$ pytest tests/test_bedrock_region.py tests/test_provider_registry.py tests/test_provider_registry_extended.py \
-k "not test_fallback_when_boto3_import_fails and not test_fallback_when_api_call_fails and not test_successful_fetch" -q
collected 51 items / 3 deselected / 48 selected
tests/test_bedrock_region.py ...........................
tests/test_provider_registry.py ...........
tests/test_provider_registry_extended.py .......
48 passed, 3 deselected in 2.00s
```
Note: 3 deselected tests use patch("builtins.__import__") which hangs
under Python 3.13 — pre-existing issue unrelated to these changes.
## Real Behavior Proof
- Environment: macOS, Python 3.13, Claude Code with
`CLAUDE_CODE_USE_BEDROCK=0`, `ANTHROPIC_BASE_URL=http://127.0.0.1:8787`,
AWS ap-southeast-2, application inference profile ARNs in
`ANTHROPIC_DEFAULT_*_MODEL`
- Exact command / steps: `headroom proxy --port 8787 --backend bedrock
--region ap-southeast-2 --bedrock-profile "my-sso-profile"`
- Observed result: Requests routed correctly to
`bedrock/converse/arn:aws:bedrock:ap-southeast-2:...:application-inference-profile/<id>`
as confirmed in LiteLLM logs
- Not tested: EU/APAC region ARN passthrough (logic is identical);
non-SSO credential flows
```text
15:29:44 - LiteLLM:INFO: utils.py:4090 -
LiteLLM completion() model= converse/arn:aws:bedrock:ap-southeast-2:<account>:application-inference-profile/<id>; provider = bedrock
2026-06-26 15:29:44,322 - LiteLLM - INFO -
LiteLLM completion() model= converse/arn:aws:bedrock:ap-southeast-2:<account>:application-inference-profile/<id>; provider = bedrock
15:31:09 - LiteLLM:INFO: utils.py:4090 -
LiteLLM completion() model= converse/arn:aws:bedrock:ap-southeast-2:<account>:application-inference-profile/<id>; provider = bedrock
2026-06-26 15:31:09,928 - LiteLLM - INFO -
LiteLLM completion() model= converse/arn:aws:bedrock:ap-southeast-2:<account>:application-inference-profile/<id>; provider = bedrock
15:34:26 - LiteLLM:INFO: utils.py:4090 -
LiteLLM completion() model= converse/arn:aws:bedrock:ap-southeast-2:<account>:application-inference-profile/<id>; provider = bedrock
2026-06-26 15:34:26,811 - LiteLLM - INFO -
LiteLLM completion() model= converse/arn:aws:bedrock:ap-southeast-2:<account>:application-inference-profile/<id>; provider = bedrock
```
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
## Additional Notes
The 3 skipped tests (`test_fallback_when_boto3_import_fails`,
`test_fallback_when_api_call_fails`, `test_successful_fetch`) pre-exist
in the repo and use `patch("builtins.__import__")` which hangs under
Python 3.13. Not affected by these changes.
---------
Co-authored-by: Matt Haitana <mhaitana@costar.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
231 lines
8.3 KiB
Python
231 lines
8.3 KiB
Python
"""Turnkey Claude Code + Vertex compression wiring.
|
|
|
|
Covers the fixes that let `headroom wrap claude` + Vertex actually deliver
|
|
compression:
|
|
|
|
- `litellm-vertex` -> `vertex_ai` provider alias (registry),
|
|
- the Vertex upstream host derived per-request from the path's `location`
|
|
(so a europe-west1 request is not sent to a us-central1 host),
|
|
- the native `:rawPredict` route running the compression handler (not the
|
|
verbatim passthrough) for the `anthropic` publisher.
|
|
|
|
No real GCP/Vertex is contacted — handlers and the backend class are stubbed.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import types
|
|
from typing import Any
|
|
|
|
from fastapi.responses import JSONResponse
|
|
from fastapi.testclient import TestClient
|
|
|
|
from headroom.providers import proxy_routes, registry
|
|
from headroom.providers.registry import DEFAULT_VERTEX_API_URL
|
|
from headroom.proxy.server import HeadroomProxy, ProxyConfig, create_app
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Region-aware Vertex upstream host
|
|
# --------------------------------------------------------------------------
|
|
def _stub_proxy(vertex_url: str) -> Any:
|
|
# `_api_target` reads `proxy.VERTEX_API_URL`, but its getattr default eagerly
|
|
# evaluates `proxy.provider_runtime.api_target(...)`, so the stub needs both.
|
|
return types.SimpleNamespace(
|
|
VERTEX_API_URL=vertex_url,
|
|
provider_runtime=types.SimpleNamespace(api_target=lambda name: vertex_url),
|
|
)
|
|
|
|
|
|
def test_vertex_target_derives_region_from_location_on_default() -> None:
|
|
proxy = _stub_proxy(DEFAULT_VERTEX_API_URL)
|
|
assert (
|
|
proxy_routes._vertex_target_for_location(proxy, "europe-west1")
|
|
== "https://europe-west1-aiplatform.googleapis.com"
|
|
)
|
|
|
|
|
|
def test_vertex_target_global_uses_unprefixed_host() -> None:
|
|
proxy = _stub_proxy(DEFAULT_VERTEX_API_URL)
|
|
assert (
|
|
proxy_routes._vertex_target_for_location(proxy, "global")
|
|
== "https://aiplatform.googleapis.com"
|
|
)
|
|
|
|
|
|
def test_vertex_target_empty_location_uses_unprefixed_host() -> None:
|
|
proxy = _stub_proxy(DEFAULT_VERTEX_API_URL)
|
|
assert (
|
|
proxy_routes._vertex_target_for_location(proxy, "") == "https://aiplatform.googleapis.com"
|
|
)
|
|
|
|
|
|
def test_vertex_target_honors_explicit_override() -> None:
|
|
# An operator who pinned a non-default upstream (private gateway) wins,
|
|
# regardless of the path's location.
|
|
proxy = _stub_proxy("https://vertex-gateway.internal")
|
|
assert (
|
|
proxy_routes._vertex_target_for_location(proxy, "europe-west1")
|
|
== "https://vertex-gateway.internal"
|
|
)
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# litellm-vertex -> vertex_ai provider alias
|
|
# --------------------------------------------------------------------------
|
|
def _capture_provider(backend: str) -> dict[str, Any]:
|
|
captured: dict[str, Any] = {}
|
|
|
|
class FakeLiteLLM:
|
|
def __init__(
|
|
self, provider: str, region: str | None = None, profile_name: str | None = None
|
|
) -> None:
|
|
captured["provider"] = provider
|
|
captured["region"] = region
|
|
|
|
registry.create_proxy_backend(
|
|
backend=backend,
|
|
anyllm_provider="openai",
|
|
bedrock_region="us-east5",
|
|
logger=logging.getLogger("test-vertex"),
|
|
litellm_backend_cls=FakeLiteLLM,
|
|
)
|
|
return captured
|
|
|
|
|
|
def test_litellm_vertex_aliases_to_vertex_ai() -> None:
|
|
# The documented `litellm-vertex` must reach the `vertex_ai` provider, not
|
|
# a generic pass-through (which would drop the region and mangle the model).
|
|
assert _capture_provider("litellm-vertex")["provider"] == "vertex_ai"
|
|
|
|
|
|
def test_litellm_vertex_ai_unchanged() -> None:
|
|
assert _capture_provider("litellm-vertex_ai")["provider"] == "vertex_ai"
|
|
|
|
|
|
def test_litellm_bedrock_not_aliased() -> None:
|
|
assert _capture_provider("litellm-bedrock")["provider"] == "bedrock"
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Native :rawPredict route → compression handler with region-derived host
|
|
# --------------------------------------------------------------------------
|
|
def _default_vertex_app() -> Any:
|
|
# No vertex_api_url override -> default us-central1 host -> route derives
|
|
# the regional host from the request path.
|
|
return create_app(ProxyConfig(optimize=True, cache_enabled=False, rate_limit_enabled=False))
|
|
|
|
|
|
def test_vertex_rawpredict_anthropic_runs_compression_handler(monkeypatch) -> None:
|
|
captured: dict[str, str] = {}
|
|
|
|
# The route calls handle_anthropic_messages(request, base_url, provider, model).
|
|
async def fake(self, request, base_url, provider, model, *rest): # type: ignore[no-untyped-def]
|
|
captured.update(base_url=str(base_url), provider=str(provider), model=str(model))
|
|
return JSONResponse({"ok": True})
|
|
|
|
monkeypatch.setattr(HeadroomProxy, "handle_anthropic_messages", fake)
|
|
|
|
with TestClient(_default_vertex_app()) as client:
|
|
resp = client.post(
|
|
"/v1/projects/p/locations/europe-west1/publishers/anthropic/models/"
|
|
"claude-sonnet-4-6:rawPredict",
|
|
json={"anthropic_version": "vertex-2023-10-16", "messages": []},
|
|
)
|
|
assert resp.status_code == 200
|
|
# The anthropic publisher is routed to the compression handler (not the
|
|
# verbatim passthrough), with the region-derived upstream host (exact match,
|
|
# not a substring check).
|
|
assert captured["provider"] == "vertex:anthropic"
|
|
assert captured["base_url"] == "https://europe-west1-aiplatform.googleapis.com"
|
|
assert captured["model"] == "claude-sonnet-4-6"
|
|
|
|
|
|
def test_vertex_rawpredict_versionless_anthropic_rewrites_to_v1(monkeypatch) -> None:
|
|
captured: dict[str, Any] = {}
|
|
|
|
async def fake(
|
|
self,
|
|
request,
|
|
base_url,
|
|
provider,
|
|
model,
|
|
force_stream=False,
|
|
): # type: ignore[no-untyped-def]
|
|
captured.update(
|
|
path=request.url.path,
|
|
raw_path=request.scope.get("raw_path"),
|
|
base_url=str(base_url),
|
|
provider=str(provider),
|
|
model=str(model),
|
|
force_stream=force_stream,
|
|
)
|
|
return JSONResponse({"ok": True})
|
|
|
|
monkeypatch.setattr(HeadroomProxy, "handle_anthropic_messages", fake)
|
|
|
|
with TestClient(_default_vertex_app()) as client:
|
|
resp = client.post(
|
|
"/projects/p/locations/europe-west1/publishers/anthropic/models/"
|
|
"claude-sonnet-4-6:rawPredict",
|
|
json={"anthropic_version": "vertex-2023-10-16", "messages": []},
|
|
)
|
|
|
|
assert resp.status_code == 200
|
|
assert captured == {
|
|
"path": (
|
|
"/projects/p/locations/europe-west1/publishers/anthropic/models/"
|
|
"claude-sonnet-4-6:rawPredict"
|
|
),
|
|
"raw_path": (
|
|
b"/projects/p/locations/europe-west1/publishers/anthropic/models/"
|
|
b"claude-sonnet-4-6:rawPredict"
|
|
),
|
|
"base_url": "https://europe-west1-aiplatform.googleapis.com/v1",
|
|
"provider": "vertex:anthropic",
|
|
"model": "claude-sonnet-4-6",
|
|
"force_stream": False,
|
|
}
|
|
|
|
|
|
def test_vertex_stream_rawpredict_versionless_anthropic_forces_stream(monkeypatch) -> None:
|
|
captured: dict[str, Any] = {}
|
|
|
|
async def fake(
|
|
self,
|
|
request,
|
|
base_url,
|
|
provider,
|
|
model,
|
|
force_stream=False,
|
|
): # type: ignore[no-untyped-def]
|
|
captured.update(
|
|
path=request.url.path,
|
|
base_url=str(base_url),
|
|
provider=str(provider),
|
|
model=str(model),
|
|
force_stream=force_stream,
|
|
)
|
|
return JSONResponse({"ok": True})
|
|
|
|
monkeypatch.setattr(HeadroomProxy, "handle_anthropic_messages", fake)
|
|
|
|
with TestClient(_default_vertex_app()) as client:
|
|
resp = client.post(
|
|
"/projects/p/locations/europe-west1/publishers/anthropic/models/"
|
|
"claude-sonnet-4-6:streamRawPredict",
|
|
json={"anthropic_version": "vertex-2023-10-16", "messages": []},
|
|
)
|
|
|
|
assert resp.status_code == 200
|
|
assert captured == {
|
|
"path": (
|
|
"/projects/p/locations/europe-west1/publishers/anthropic/models/"
|
|
"claude-sonnet-4-6:streamRawPredict"
|
|
),
|
|
"base_url": "https://europe-west1-aiplatform.googleapis.com/v1",
|
|
"provider": "vertex:anthropic",
|
|
"model": "claude-sonnet-4-6",
|
|
"force_stream": True,
|
|
}
|