Repository navigation
feat(guardrails/headroom): add CCR (compress-cache-retrieve) via agentic loop #31681
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 7 commits
5a95724
a7b1857
2e79fa3
2059b6d
26eeba8
08d1d75
049e5f6
0f5849b
2c6e0e2
57b37c9
223b0fd
607167b
d4596cf
16b0c4a
36dda98
b167f2a
013b4bf
5bc3838
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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 | ||
|
|
@@ -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 | ||
|
|
@@ -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 | ||
|
|
||
|
|
||
| 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) | ||
|
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, | ||
|
|
@@ -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]], | ||
|
|
@@ -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( | ||
|
|
@@ -118,7 +265,7 @@ async def _call_compress( | |
|
|
||
| try: | ||
| body: object = response.json() | ||
| except Exception: | ||
| except ValueError: | ||
| raise HTTPException( | ||
| status_code=502, | ||
| detail={ | ||
|
|
@@ -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, | ||
|
|
@@ -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( | ||
|
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, | ||
| } | ||
| ) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When the Anthropic Useful? React with 👍 / 👎. |
||
|
|
||
| assistant_message = _build_assistant_message_from_response(response) | ||
|
krrish-berri-2 marked this conversation as resolved.
Resolved
|
||
| follow_up_messages = list(messages) + [assistant_message] + tool_results | ||
|
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: | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For
/v1/messagesrequests, the Anthropic guardrail translation convertsguardrailed_toolsback from OpenAI format into Anthropic tools (litellm/llms/anthropic/chat/guardrail_translation/handler.pylines 167-175), which makes the injected retrieve tool look like{"type": "custom", "name": "headroom_retrieve", ...}. This predicate only accepts OpenAItype=functiontools, soasync_should_run_agentic_loopreturns false even when Claude emits theheadroom_retrievetool_use; Headroom CCR never retrieves the compressed content on the Anthropic Messages path.Useful? React with 👍 / 👎.