headroomlabs-ai/headroom · error · ImportError

httpx is required for Headroom Cloud mode: pip install httpx

Error message

httpx is required for Headroom Cloud mode: pip install httpx

What it means

Raised by the ASGI middleware's _cloud_compress when Headroom Cloud mode is enabled (an api_url/api_key configured) but httpx is not importable. The middleware defers the httpx import until the first cloud compression request, so an app can boot and serve local-mode traffic fine, then fail on the first request that actually needs the managed Cloud API. The fix named in the message is a plain pip install.

Source

Thrown at headroom/integrations/asgi.py:212

            model=model or "claude-sonnet-4-5-20250929",
            model_limit=self._model_limit,
            hooks=self._hooks,
        )
        return {
            "messages": result.messages,
            "tokens_before": result.tokens_before,
            "tokens_after": result.tokens_after,
            "tokens_saved": result.tokens_saved,
            "compression_ratio": result.compression_ratio,
        }

    async def _cloud_compress(self, messages: list[dict], model: str) -> dict[str, Any] | None:
        """Compress via Headroom Cloud API (managed CCR, TOIN, analytics)."""
        if self._client is None:
            try:
                import httpx
            except ImportError as e:
                raise ImportError(
                    "httpx is required for Headroom Cloud mode: pip install httpx"
                ) from e
            self._client = httpx.AsyncClient(timeout=30.0)

        client = self._client
        assert client is not None
        resp = await client.post(
            f"{self._api_url}/v1/saas/compress",
            headers={
                "X-Headroom-Key": self._api_key,
                "Content-Type": "application/json",
            },
            content=json.dumps(
                {
                    "messages": messages,
                    "model": model or "claude-sonnet-4-5-20250929",
                    "model_limit": self._model_limit,
                }

View on GitHub (pinned to 322425c43b)

Solutions

  1. pip install httpx into the app's environment.
  2. If Cloud mode was enabled by mistake, drop the cloud api_url/api_key config so the middleware stays on local compression (no httpx needed).
  3. Add httpx to the deployment image requirements next to headroom.
  4. Smoke-test after install by sending one request through the middleware and watching for a 200 from the cloud path.

Example fix

# before
app.add_middleware(HeadroomMiddleware, api_url="https://cloud.headroom.dev", api_key=KEY)
# first request -> ImportError: httpx is required

# after
$ python -m pip install httpx
app.add_middleware(HeadroomMiddleware, api_url="https://cloud.headroom.dev", api_key=KEY)
Defensive patterns

Strategy: validation

Validate before calling

import importlib.util

if cloud_mode_enabled and importlib.util.find_spec("httpx") is None:
    raise SystemExit("Headroom Cloud mode requires httpx: pip install httpx")

Try / catch

try:
    response = await middleware_dispatch(request)
except ImportError as e:
    if "httpx is required" in str(e):
        return JSONResponse({"error": "headroom cloud dependency missing"}, status_code=503)
    raise

Prevention

When it happens

Trigger: Configuring the ASGI middleware with cloud/api_key settings in an environment where httpx was never installed; first request hitting the /v1/saas/compress path triggers the lazy import and raises. httpx installed in a different venv than the ASGI app produces the same result.

Common situations: Adding headroom[cloud]-style functionality to a slim FastAPI/Starlette deployment image; dependency extras skipped to shrink containers; local dev installs that never needed Cloud mode until the api_url was switched on.

Related errors


AI-assisted analysis of headroomlabs-ai/headroom@322425c43b (2026-08-15). Data as JSON: /api/errors/be2e70efbc37d013. Report an issue: GitHub.