0ef5fcb1c5
Security / Dependency audit (pip-audit) (push) Has been cancelled
Security / CodeQL (javascript-typescript) (push) Has been cancelled
Security / CodeQL (python) (push) Has been cancelled
Security / Secret scan (gitleaks) (push) Has been cancelled
rust / test (ubuntu) (push) Has been cancelled
rust / simulator e2e (macos-latest) (push) Has been cancelled
rust / simulator e2e (ubuntu-latest) (push) Has been cancelled
rust / simulator e2e (windows-latest) (push) Has been cancelled
rust / wheels (aarch64-apple-darwin) (push) Has been cancelled
rust / wheels (x86_64-unknown-linux-gnu) (push) Has been cancelled
rust / wheels (x86_64-apple-darwin) (push) Has been cancelled
rust / audit (push) Has been cancelled
rust / parity (nightly, allowed to fail during Phase 0) (push) Has been cancelled
CI / commitlint (push) Has been skipped
Dev Containers / validate (.devcontainer/devcontainer.json, default) (push) Failing after 0s
Dev Containers / validate (.devcontainer/memory-stack/devcontainer.json, memory-stack) (push) Failing after 0s
Dev Containers / validate-worktree (push) Failing after 0s
CI / changes (push) Failing after 4s
Deploy Documentation / validate (push) Has been skipped
Deploy Documentation / deploy (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, claude) (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, codex) (push) Failing after 1s
Install Native E2E / install-native (ubuntu-latest) (push) Failing after 1s
OpenCode Plugin / typecheck + build + test (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, copilot) (push) Failing after 1s
Release Please / release-please (push) Failing after 1s
Wrap E2E / docker-wrap-e2e (push) Failing after 1s
Wrap Native E2E / wrap-native (ubuntu-latest) (push) Failing after 1s
Init E2E / docker-init-e2e (push) Failing after 4s
Merge Conflicts / merge-conflicts (push) Failing after 4s
CI / lint (push) Has been cancelled
CI / build-wheel (push) Has been cancelled
CI / build-wheel-windows (push) Has been cancelled
CI / prefetch-model (push) Has been cancelled
CI / test-dashboard-ui (push) Has been cancelled
CI / test (1) (push) Has been cancelled
CI / test (2) (push) Has been cancelled
CI / test (3) (push) Has been cancelled
CI / test (4) (push) Has been cancelled
CI / test-extras (push) Has been cancelled
CI / test-agno (push) Has been cancelled
CI / build (push) Has been cancelled
CI / workflow-validation (push) Has been cancelled
CI / docker-native-e2e (push) Has been cancelled
CI / windows-native-wrapper (push) Has been cancelled
CI / macos-native-wrapper (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / promote-latest (push) Has been cancelled
Init Native E2E / init-native (macos-latest, claude) (push) Has been cancelled
Init Native E2E / init-native (macos-latest, codex) (push) Has been cancelled
Init Native E2E / init-native (macos-latest, copilot) (push) Has been cancelled
Install Native E2E / install-native (macos-latest) (push) Has been cancelled
Wrap Native E2E / wrap-native (macos-latest) (push) Has been cancelled
206 lines
6.9 KiB
Python
206 lines
6.9 KiB
Python
"""LiteLLM callback — add Headroom compression to LiteLLM with one line.
|
|
|
|
# Local mode (compression runs in-process):
|
|
import litellm
|
|
from headroom.integrations.litellm_callback import HeadroomCallback
|
|
|
|
litellm.callbacks = [HeadroomCallback()]
|
|
|
|
# Cloud mode (managed CCR, TOIN, analytics via Headroom Cloud):
|
|
litellm.callbacks = [HeadroomCallback(api_key="hdr_xxx")]
|
|
|
|
Works with LiteLLM's completion(), acompletion(), and proxy modes.
|
|
Cloud mode requires httpx: pip install httpx
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
from typing import Any
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_DEFAULT_CLOUD_URL = "https://api.headroomlabs.ai"
|
|
|
|
|
|
try:
|
|
from litellm.integrations.custom_logger import CustomLogger as _CustomLogger
|
|
except ImportError: # litellm not installed — fall back to plain object
|
|
_CustomLogger = object # type: ignore[assignment,misc]
|
|
|
|
|
|
class HeadroomCallback(_CustomLogger):
|
|
"""LiteLLM callback that compresses messages before each API call.
|
|
|
|
Inherits from litellm.integrations.custom_logger.CustomLogger so that
|
|
any hook LiteLLM adds in future versions (e.g. async_post_call_success_hook
|
|
added in 1.89.x) has a no-op default and won't raise AttributeError (#1114).
|
|
|
|
Two modes:
|
|
- Local (default): Compresses in-process using headroom.compress().
|
|
- Cloud (api_key set): Calls Headroom Cloud API for managed compression
|
|
with org-scoped CCR, TOIN learning, and analytics dashboards.
|
|
|
|
Usage (local):
|
|
litellm.callbacks = [HeadroomCallback()]
|
|
|
|
Usage (cloud):
|
|
litellm.callbacks = [HeadroomCallback(api_key="hdr_xxx")]
|
|
|
|
Usage (cloud with LiteLLM proxy config):
|
|
# litellm_config.yaml
|
|
litellm_settings:
|
|
callbacks: [headroom.integrations.litellm_callback.HeadroomCallback]
|
|
environment_variables:
|
|
HEADROOM_API_KEY: "hdr_xxx"
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
min_tokens: int = 500,
|
|
model_limit: int = 200000,
|
|
hooks: Any = None,
|
|
api_key: str | None = None,
|
|
api_url: str | None = None,
|
|
) -> None:
|
|
super().__init__()
|
|
self._min_tokens = min_tokens
|
|
self._model_limit = model_limit
|
|
self._hooks = hooks
|
|
self._total_saved = 0
|
|
|
|
# Cloud mode: if api_key is set, compress via Headroom Cloud API
|
|
# Falls back to HEADROOM_API_KEY env var
|
|
import os
|
|
|
|
self._api_key = api_key or os.environ.get("HEADROOM_API_KEY", "").strip() or None
|
|
self._api_url = (
|
|
api_url or os.environ.get("HEADROOM_API_URL", "").strip() or _DEFAULT_CLOUD_URL
|
|
).rstrip("/")
|
|
self._client: Any = None # Lazy-initialized httpx.AsyncClient
|
|
|
|
@property
|
|
def total_tokens_saved(self) -> int:
|
|
"""Total tokens saved across all calls."""
|
|
return self._total_saved
|
|
|
|
@property
|
|
def cloud_mode(self) -> bool:
|
|
"""Whether cloud compression is enabled."""
|
|
return self._api_key is not None
|
|
|
|
async def async_pre_call_hook(
|
|
self,
|
|
user_api_key_dict: Any = None,
|
|
cache: Any = None,
|
|
data: dict[Any, Any] | None = None,
|
|
call_type: str = "",
|
|
*_args: Any,
|
|
**_kwargs: Any,
|
|
) -> dict[Any, Any] | None:
|
|
"""Called by LiteLLM before each API call. Compresses messages."""
|
|
if isinstance(cache, dict) and isinstance(data, str):
|
|
data, call_type = cache, data
|
|
|
|
if data is None:
|
|
return None
|
|
|
|
if call_type not in ("completion", "acompletion"):
|
|
return data
|
|
|
|
messages = data.get("messages", [])
|
|
model = data.get("model", "")
|
|
|
|
if not messages:
|
|
return data
|
|
|
|
try:
|
|
if self._api_key:
|
|
result = await self._cloud_compress(messages, model)
|
|
else:
|
|
result = self._local_compress(messages, model)
|
|
|
|
if result and result.get("tokens_saved", 0) > 0 and "messages" in result:
|
|
data["messages"] = result["messages"]
|
|
self._total_saved += result["tokens_saved"]
|
|
logger.info(
|
|
"Headroom%s: %d→%d tokens (saved %d, %.0f%%) [total saved: %d]",
|
|
" Cloud" if self._api_key else "",
|
|
result["tokens_before"],
|
|
result["tokens_after"],
|
|
result["tokens_saved"],
|
|
result.get("compression_ratio", 0) * 100,
|
|
self._total_saved,
|
|
)
|
|
|
|
except Exception as e:
|
|
logger.warning("Headroom compression failed, using original messages: %s", e)
|
|
|
|
return data
|
|
|
|
def _local_compress(self, messages: list[dict], model: str) -> dict[str, Any] | None:
|
|
"""Compress locally using headroom.compress()."""
|
|
from headroom.compress import compress
|
|
|
|
result = compress(
|
|
messages=messages,
|
|
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,
|
|
}
|
|
),
|
|
)
|
|
|
|
if resp.status_code != 200:
|
|
logger.warning("Headroom Cloud API error: %d %s", resp.status_code, resp.text[:200])
|
|
return None
|
|
|
|
result: dict[str, Any] = resp.json()
|
|
return result
|
|
|
|
async def async_success_handler(
|
|
self, kwargs: dict, response: Any, start_time: Any, end_time: Any
|
|
) -> None:
|
|
"""Called after successful completion. No-op for now."""
|
|
pass
|
|
|
|
async def async_failure_handler(
|
|
self, kwargs: dict, response: Any, start_time: Any, end_time: Any
|
|
) -> None:
|
|
"""Called after failed completion. No-op for now."""
|
|
pass
|