Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
5a95724
feat(guardrails/headroom): add CCR (compress-cache-retrieve) support …
krrish-berri-2 Jun 30, 2026
a7b1857
style: run ruff format on headroom guardrail and tests
krrish-berri-2 Jun 30, 2026
2e79fa3
fix(guardrails/headroom): detect headroom_retrieve calls in both Open…
krrish-berri-2 Jun 30, 2026
2059b6d
test(guardrails/headroom): add test for Anthropic content block forma…
krrish-berri-2 Jun 30, 2026
26eeba8
ci: trigger CI checks
krrish-berri-2 Jun 30, 2026
08d1d75
fix(guardrails/headroom): replace List/Dict with list/dict to fix UP0…
krrish-berri-2 Jun 30, 2026
049e5f6
fix(guardrails/headroom): replace except Exception with except ValueE…
krrish-berri-2 Jun 30, 2026
0f5849b
fix(guardrails/headroom): add Responses API output format detection f…
krrish-berri-2 Jun 30, 2026
2c6e0e2
refactor(guardrails/headroom): extract format-specific helpers to fix…
krrish-berri-2 Jun 30, 2026
57b37c9
fix(guardrails/headroom): scope CCR retrieval to hashes produced by c…
krrish-berri-2 Jun 30, 2026
223b0fd
fix(guardrails/headroom): track issued hashes server-side, fix Respon…
krrish-berri-2 Jun 30, 2026
607167b
fix(guardrails/headroom): drop redundant quoted type annotations
krrish-berri-2 Jun 30, 2026
d4596cf
test(guardrails/headroom): add missing pytest.mark.asyncio decorators
krrish-berri-2 Jun 30, 2026
16b0c4a
fix(guardrails/headroom): scope CCR hashes per call_id, fix Anthropic…
krrish-berri-2 Jul 1, 2026
36dda98
docs: note proactive API-fragmentation helper convention
krrish-berri-2 Jul 1, 2026
b167f2a
fix(guardrails/headroom): fix Anthropic tool-shape detection, extract…
krrish-berri-2 Jul 1, 2026
013b4bf
fix(guardrails/headroom): fix ruff-strict UP006/I001 budget violations
krrish-berri-2 Jul 1, 2026
5bc3838
fix(guardrails/headroom): match Anthropic tools without a type field
krrish-berri-2 Jul 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
296 changes: 288 additions & 8 deletions litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Literal
import json
import re
from typing import TYPE_CHECKING, Any, Literal, Optional, Tuple

import httpx
from fastapi import HTTPException
Expand All @@ -18,13 +20,16 @@
)
from litellm.secret_managers.main import get_secret_str
from litellm.types.guardrails import GuardrailEventHooks, Mode
from litellm.types.integrations.custom_logger import AgenticLoopPlan, AgenticLoopRequestPatch
from litellm.types.utils import GenericGuardrailAPIInputs

if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel

BYPASS_HEADER = "x-headroom-bypass"
HEADROOM_RETRIEVE_TOOL_NAME = "headroom_retrieve"
_HASH_PATTERN = re.compile(r"hash=([a-f0-9]{24})")


def _is_str_object_dict(value: object) -> TypeGuard[dict[str, object]]: # guard-ok: isinstance narrows correctly; predicate is trivially correct # fmt: skip
Expand All @@ -35,6 +40,146 @@ def _is_object_list(value: object) -> TypeGuard[list[object]]: # guard-ok: isin
return isinstance(value, list)


def extract_hashes_from_messages(messages: list[dict[str, object]]) -> list[str]:
hashes: list[str] = []
for msg in messages:
content = msg.get("content")
if isinstance(content, str):
hashes.extend(_HASH_PATTERN.findall(content))
elif isinstance(content, list):
for block in content:
if isinstance(block, dict):
text = block.get("text")
if isinstance(text, str):
hashes.extend(_HASH_PATTERN.findall(text))
return hashes


def _build_headroom_retrieve_tool() -> dict[str, object]:
return {
"type": "function",
"function": {
"name": HEADROOM_RETRIEVE_TOOL_NAME,
"description": (
"Retrieve original content that was compressed by Headroom. "
"Call this when you encounter a compression marker containing a hash."
),
"parameters": {
"type": "object",
"properties": {
"hash": {
"type": "string",
"description": "The 24-character hex hash from the compression marker.",
},
"query": {
"type": "string",
"description": "Optional search query for BM25-ranked retrieval.",
},
},
"required": ["hash"],
},
},
}


def has_headroom_retrieve_tool(tools: object) -> bool:
if not isinstance(tools, list):
return False
for tool in tools:
if not isinstance(tool, dict):
continue
function = tool.get("function")
if tool.get("type") == "function" and isinstance(function, dict):
if function.get("name") == HEADROOM_RETRIEVE_TOOL_NAME:
return True
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Recognize Anthropic's injected retrieve tool

For /v1/messages requests, the Anthropic guardrail translation converts guardrailed_tools back from OpenAI format into Anthropic tools (litellm/llms/anthropic/chat/guardrail_translation/handler.py lines 167-175), which makes the injected retrieve tool look like {"type": "custom", "name": "headroom_retrieve", ...}. This predicate only accepts OpenAI type=function tools, so async_should_run_agentic_loop returns false even when Claude emits the headroom_retrieve tool_use; Headroom CCR never retrieves the compressed content on the Anthropic Messages path.

Useful? React with 👍 / 👎.



def _extract_headroom_tool_calls(
response: object,
) -> list[dict[str, object]]:
result: list[dict[str, object]] = []

# OpenAI chat completions format: choices[0].message.tool_calls
choices = getattr(response, "choices", None)
if isinstance(choices, list) and choices:
message = getattr(choices[0], "message", None)
tool_calls = getattr(message, "tool_calls", None) if message else None
if isinstance(tool_calls, list):
for tc in tool_calls:
fn = getattr(tc, "function", None)
if fn is None:
continue
name = getattr(fn, "name", None)
if name != HEADROOM_RETRIEVE_TOOL_NAME:
continue
arguments_str = getattr(fn, "arguments", "{}")
try:
arguments: dict[str, object] = json.loads(arguments_str)
except (json.JSONDecodeError, TypeError):
arguments = {}
result.append(
{
"id": getattr(tc, "id", None),
"type": "function",
"name": name,
"arguments": arguments,
}
)
return result

# Anthropic messages format: content blocks with type=tool_use
content = getattr(response, "content", None)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
if isinstance(content, list):
for block in content:
block_type = block.get("type") if isinstance(block, dict) else getattr(block, "type", None)
block_name = block.get("name") if isinstance(block, dict) else getattr(block, "name", None)
if block_type != "tool_use" or block_name != HEADROOM_RETRIEVE_TOOL_NAME:
continue
if isinstance(block, dict):
raw_input: object = block.get("input", {})
block_id: object = block.get("id")
else:
raw_input = getattr(block, "input", {})
block_id = getattr(block, "id", None)
result.append(
{
"id": block_id,
"type": "function",
"name": block_name,
"arguments": raw_input if isinstance(raw_input, dict) else {},
}
)

return result


def _build_assistant_message_from_response(response: object) -> dict[str, object]:
choices = getattr(response, "choices", None)
if not isinstance(choices, list) or not choices:
return {"role": "assistant", "content": None, "tool_calls": []}
message = getattr(choices[0], "message", None)
if message is None:
return {"role": "assistant", "content": None, "tool_calls": []}
content = getattr(message, "content", None)
tool_calls = getattr(message, "tool_calls", None)
raw_tool_calls: list[dict[str, object]] = []
if isinstance(tool_calls, list):
for tc in tool_calls:
fn = getattr(tc, "function", None)
raw_tool_calls.append(
{
"id": getattr(tc, "id", None),
"type": "function",
"function": {
"name": getattr(fn, "name", None) if fn else None,
"arguments": getattr(fn, "arguments", "{}") if fn else "{}",
},
}
)
return {"role": "assistant", "content": content, "tool_calls": raw_tool_calls}


class HeadroomGuardrail(CustomGuardrail):
def __init__(
self,
Expand Down Expand Up @@ -72,6 +217,12 @@ def _should_bypass(self, request_data: dict) -> bool:
value = headers.get(BYPASS_HEADER)
return str(value).lower() == "true"

def _request_headers(self) -> dict[str, str]:
headers: dict[str, str] = {"Content-Type": "application/json"}
if self.headroom_api_key:
headers["Authorization"] = f"Bearer {self.headroom_api_key}"
return headers

async def _call_compress(
self,
messages: list[dict[str, object]],
Expand All @@ -81,15 +232,11 @@ async def _call_compress(
if model:
payload["model"] = model

request_headers: dict[str, str] = {"Content-Type": "application/json"}
if self.headroom_api_key:
request_headers["Authorization"] = f"Bearer {self.headroom_api_key}"

try:
raw_response: HttpxResponse | None = await self.async_handler.post( # pyright: ignore[reportUnknownMemberType]
url=f"{self.headroom_api_base}/v1/compress",
json=payload,
headers=request_headers,
headers=self._request_headers(),
)
except (httpx.ConnectError, httpx.TimeoutException, httpx.TransportError) as e:
raise HTTPException(
Expand Down Expand Up @@ -118,7 +265,7 @@ async def _call_compress(

try:
body: object = response.json()
except Exception:
except ValueError:
raise HTTPException(
status_code=502,
detail={
Expand Down Expand Up @@ -163,6 +310,44 @@ async def _call_compress(
)
return filtered

async def _call_retrieve(self, hash_value: str, query: str | None = None) -> str:
params: dict[str, str] = {}
if query:
params["query"] = query

try:
raw_response: HttpxResponse | None = await self.async_handler.get( # pyright: ignore[reportUnknownMemberType]
url=f"{self.headroom_api_base}/v1/retrieve/{hash_value}",
params=params,
headers=self._request_headers(),
)
except (httpx.ConnectError, httpx.TimeoutException, httpx.TransportError) as e:
verbose_proxy_logger.warning("Headroom: retrieve failed for hash=%s: %s", hash_value, e)
return f"[Headroom: retrieval failed for hash={hash_value}]"

if raw_response is None or raw_response.status_code == 404:
return f"[Headroom: hash={hash_value} not found or expired]"

if raw_response.status_code != 200:
verbose_proxy_logger.warning(
"Headroom: retrieve returned %s for hash=%s",
raw_response.status_code,
hash_value,
)
return f"[Headroom: retrieval error {raw_response.status_code} for hash={hash_value}]"

try:
body: object = raw_response.json()
except ValueError:
return raw_response.text

if _is_str_object_dict(body):
original_content = body.get("original_content")
if isinstance(original_content, str):
return original_content

return str(body)

@log_guardrail_information
async def apply_guardrail(
self,
Expand Down Expand Up @@ -192,7 +377,102 @@ async def apply_guardrail(
model=model if isinstance(model, str) else None,
)

return {**inputs, "structured_messages": compressed} # pyright: ignore[reportReturnType]
hashes = extract_hashes_from_messages(compressed)
if not hashes:
return {**inputs, "structured_messages": compressed} # pyright: ignore[reportReturnType]

existing_tools = inputs.get("tools")
retrieve_tool = _build_headroom_retrieve_tool()
if isinstance(existing_tools, list) and not has_headroom_retrieve_tool(existing_tools):
merged_tools: list[object] = list(existing_tools) + [retrieve_tool]
elif existing_tools is None:
merged_tools = [retrieve_tool]
else:
merged_tools = list(existing_tools) if isinstance(existing_tools, list) else [retrieve_tool]

return {**inputs, "structured_messages": compressed, "tools": merged_tools} # pyright: ignore[reportReturnType]

async def async_should_run_agentic_loop(
self,
response: Any,
model: str,
messages: list[dict],
tools: Optional[list[dict]],
stream: bool,
custom_llm_provider: str,
kwargs: dict,
) -> Tuple[bool, dict]:
if not has_headroom_retrieve_tool(tools):
return False, {}

tool_calls = _extract_headroom_tool_calls(response)
if not tool_calls:
return False, {}

return True, {"tool_calls": tool_calls}

async def async_build_agentic_loop_plan(
self,
tools: dict,
model: str,
messages: list[dict],
response: Any,
anthropic_messages_provider_config: Any,
anthropic_messages_optional_request_params: dict,
logging_obj: Any,
stream: bool,
kwargs: dict,
) -> AgenticLoopPlan:
tool_calls: list[dict[str, object]] = tools.get("tool_calls", []) # type: ignore[assignment]

tool_results: list[dict[str, object]] = []
for tc in tool_calls:
arguments = tc.get("arguments", {})
hash_value = arguments.get("hash", "") if isinstance(arguments, dict) else ""
query = arguments.get("query") if isinstance(arguments, dict) else None
content = await self._call_retrieve(
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved
hash_value=str(hash_value),
query=str(query) if query else None,
)
verbose_proxy_logger.debug("Headroom CCR: retrieved hash=%s (%d chars)", hash_value, len(content))
tool_results.append(
{
"role": "tool",
"tool_call_id": tc.get("id"),
"content": content,
}
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Build Anthropic tool-result messages for Anthropic loops

When the Anthropic tool_use branch in _extract_headroom_tool_calls is used, this plan still appends OpenAI chat-completion tool messages (role: "tool" with tool_call_id). _execute_anthropic_agentic_plan sends patch.messages to anthropic_messages.acreate, whose existing interception implementations build an assistant tool_use content block followed by a user tool_result content block; with these OpenAI-shaped messages the follow-up is not a valid Anthropic Messages tool-result turn, so the retrieval loop will fail instead of producing the final answer.

Useful? React with 👍 / 👎.


assistant_message = _build_assistant_message_from_response(response)
Comment thread
krrish-berri-2 marked this conversation as resolved.
Resolved
follow_up_messages = list(messages) + [assistant_message] + tool_results
Comment thread
krrish-berri-2 marked this conversation as resolved.
Resolved

max_tokens: Optional[int] = anthropic_messages_optional_request_params.get("max_tokens") or kwargs.get(
"max_tokens"
)
optional_params_without_max_tokens = {
k: v for k, v in anthropic_messages_optional_request_params.items() if k != "max_tokens"
}

full_model_name = model
if logging_obj is not None:
agentic_params = getattr(logging_obj, "model_call_details", {}).get("agentic_loop_params", {})
candidate = agentic_params.get("model", model)
if isinstance(candidate, str) and candidate:
full_model_name = candidate

return AgenticLoopPlan(
run_agentic_loop=True,
request_patch=AgenticLoopRequestPatch(
model=full_model_name,
messages=follow_up_messages,
max_tokens=max_tokens,
optional_params=optional_params_without_max_tokens,
kwargs={
k: v for k, v in kwargs.items() if not k.startswith("_headroom") and k != "litellm_logging_obj"
},
),
metadata={"tool_type": "headroom_ccr"},
)

@staticmethod
def get_config_model() -> type[GuardrailConfigModel[object]] | None:
Expand Down
Loading
Loading