From 5a957245a51ccfdb6f7f16011741c7718de23bc0 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 18:14:39 -0700 Subject: [PATCH 01/18] feat(guardrails/headroom): add CCR (compress-cache-retrieve) support via agentic loop When Headroom's /v1/compress returns messages containing hash markers (hash=[a-f0-9]{24}), inject a headroom_retrieve tool into the request. When the LLM calls that tool, intercept via async_should_run_agentic_loop and async_build_agentic_loop_plan, call GET /v1/retrieve/{hash} on the Headroom sidecar, and replay the LLM with the original content as a tool result -- all transparent to the caller. --- .../guardrail_hooks/headroom/headroom.py | 283 ++++++++++++++- .../guardrail_hooks/test_headroom.py | 340 +++++++++++++++++- 2 files changed, 615 insertions(+), 8 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index 2228ccf3997a..ceb8d6a8fe57 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -1,6 +1,8 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Literal +import json +import re +from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple import httpx from fastapi import HTTPException @@ -18,6 +20,7 @@ ) 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: @@ -25,6 +28,8 @@ 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,124 @@ 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]]: + choices = getattr(response, "choices", None) + if not isinstance(choices, list) or not choices: + return [] + message = getattr(choices[0], "message", None) + if message is None: + return [] + tool_calls = getattr(message, "tool_calls", None) + if not isinstance(tool_calls, list): + return [] + + result: list[dict[str, object]] = [] + 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 + + +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 +195,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 +210,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( @@ -163,6 +288,46 @@ 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 Exception: + 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 +357,111 @@ 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( + 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, + } + ) + + assistant_message = _build_assistant_message_from_response(response) + follow_up_messages = list(messages) + [assistant_message] + tool_results + + 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: diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py index 663950353846..aad807c1a4b6 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py @@ -8,15 +8,24 @@ - response-type input is passed through unchanged - /v1/compress HTTP error raises HTTPException - /v1/compress returning malformed JSON raises HTTPException +- CCR: headroom_retrieve tool injected when compressed messages contain hashes +- CCR: async_should_run_agentic_loop returns True when response has headroom_retrieve tool calls +- CCR: async_build_agentic_loop_plan calls retrieve endpoint and builds follow-up messages """ +import json from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest from fastapi import HTTPException -from litellm.proxy.guardrails.guardrail_hooks.headroom.headroom import HeadroomGuardrail +from litellm.proxy.guardrails.guardrail_hooks.headroom.headroom import ( + HeadroomGuardrail, + extract_hashes_from_messages, + has_headroom_retrieve_tool, + HEADROOM_RETRIEVE_TOOL_NAME, +) from litellm.types.utils import GenericGuardrailAPIInputs FAKE_API_BASE = "https://headroom.example.com" @@ -30,6 +39,13 @@ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "A" * 500}, ] +COMPRESSED_MESSAGES_WITH_HASH = [ + {"role": "system", "content": "You are a helpful assistant."}, + { + "role": "user", + "content": "Summary. Retrieve more: hash=b573993006976af767214fac", + }, +] def _make_guardrail(**kwargs) -> HeadroomGuardrail: @@ -57,6 +73,38 @@ def _make_compress_response(messages: list, status: int = 200) -> MagicMock: return mock +def _make_retrieve_response(original_content: str, status: int = 200) -> MagicMock: + mock = MagicMock() + mock.status_code = status + mock.json.return_value = {"original_content": original_content} + mock.text = original_content + return mock + + +def _make_openai_response_with_tool_call( + tool_name: str, arguments: dict, tool_id: str = "call_abc123" +) -> MagicMock: + fn = MagicMock() + fn.name = tool_name + fn.arguments = json.dumps(arguments) + + tc = MagicMock() + tc.id = tool_id + tc.type = "function" + tc.function = fn + + message = MagicMock() + message.content = None + message.tool_calls = [tc] + + choice = MagicMock() + choice.message = message + + response = MagicMock() + response.choices = [choice] + return response + + @pytest.fixture def guardrail() -> HeadroomGuardrail: return _make_guardrail() @@ -87,6 +135,296 @@ async def test_apply_guardrail_compresses_and_returns_structured_messages( assert result.get("structured_messages") == COMPRESSED_MESSAGES +@pytest.mark.asyncio +async def test_apply_guardrail_injects_retrieve_tool_when_hashes_present( + guardrail: HeadroomGuardrail, +): + inputs = GenericGuardrailAPIInputs( + texts=["A" * 5000], + structured_messages=ORIGINAL_MESSAGES, + ) + mock_response = _make_compress_response(COMPRESSED_MESSAGES_WITH_HASH) + + with patch.object( + guardrail.async_handler, + "post", + new_callable=AsyncMock, + return_value=mock_response, + ): + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data={"model": "gpt-4o"}, + input_type="request", + ) + + tools = result.get("tools") + assert tools is not None + assert has_headroom_retrieve_tool(tools) + + +@pytest.mark.asyncio +async def test_apply_guardrail_no_tool_injected_when_no_hashes( + guardrail: HeadroomGuardrail, +): + inputs = GenericGuardrailAPIInputs( + texts=["A" * 5000], + structured_messages=ORIGINAL_MESSAGES, + ) + mock_response = _make_compress_response(COMPRESSED_MESSAGES) + + with patch.object( + guardrail.async_handler, + "post", + new_callable=AsyncMock, + return_value=mock_response, + ): + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data={"model": "gpt-4o"}, + input_type="request", + ) + + tools = result.get("tools") + assert not has_headroom_retrieve_tool(tools or []) + + +@pytest.mark.asyncio +async def test_apply_guardrail_preserves_existing_tools_when_injecting( + guardrail: HeadroomGuardrail, +): + existing_tool = {"type": "function", "function": {"name": "my_tool", "parameters": {}}} + inputs = GenericGuardrailAPIInputs( + texts=["A" * 5000], + structured_messages=ORIGINAL_MESSAGES, + tools=[existing_tool], + ) + mock_response = _make_compress_response(COMPRESSED_MESSAGES_WITH_HASH) + + with patch.object( + guardrail.async_handler, + "post", + new_callable=AsyncMock, + return_value=mock_response, + ): + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data={"model": "gpt-4o"}, + input_type="request", + ) + + tools = result.get("tools") + assert tools is not None + assert isinstance(tools, list) + assert any( + isinstance(t, dict) and t.get("function", {}).get("name") == "my_tool" + for t in tools + ) + assert has_headroom_retrieve_tool(tools) + + +@pytest.mark.asyncio +async def test_async_should_run_agentic_loop_returns_true_for_retrieve_call( + guardrail: HeadroomGuardrail, +): + retrieve_tool_def = [{"type": "function", "function": {"name": HEADROOM_RETRIEVE_TOOL_NAME}}] + response = _make_openai_response_with_tool_call( + tool_name=HEADROOM_RETRIEVE_TOOL_NAME, + arguments={"hash": "b573993006976af767214fac"}, + ) + + should_run, ctx = await guardrail.async_should_run_agentic_loop( + response=response, + model="gpt-4o", + messages=[], + tools=retrieve_tool_def, + stream=False, + custom_llm_provider="openai", + kwargs={}, + ) + + assert should_run is True + assert len(ctx["tool_calls"]) == 1 + assert ctx["tool_calls"][0]["arguments"]["hash"] == "b573993006976af767214fac" + + +@pytest.mark.asyncio +async def test_async_should_run_agentic_loop_returns_false_without_retrieve_tool( + guardrail: HeadroomGuardrail, +): + other_tools = [{"type": "function", "function": {"name": "other_tool"}}] + response = _make_openai_response_with_tool_call( + tool_name="other_tool", + arguments={}, + ) + + should_run, _ = await guardrail.async_should_run_agentic_loop( + response=response, + model="gpt-4o", + messages=[], + tools=other_tools, + stream=False, + custom_llm_provider="openai", + kwargs={}, + ) + + assert should_run is False + + +@pytest.mark.asyncio +async def test_async_should_run_agentic_loop_returns_false_when_no_retrieve_calls( + guardrail: HeadroomGuardrail, +): + retrieve_tool_def = [{"type": "function", "function": {"name": HEADROOM_RETRIEVE_TOOL_NAME}}] + response = _make_openai_response_with_tool_call( + tool_name="some_other_function", + arguments={}, + ) + + should_run, _ = await guardrail.async_should_run_agentic_loop( + response=response, + model="gpt-4o", + messages=[], + tools=retrieve_tool_def, + stream=False, + custom_llm_provider="openai", + kwargs={}, + ) + + assert should_run is False + + +@pytest.mark.asyncio +async def test_async_build_agentic_loop_plan_calls_retrieve_and_builds_messages( + guardrail: HeadroomGuardrail, +): + original_content = "This is the full compressed content." + mock_retrieve = _make_retrieve_response(original_content) + + tool_calls = [ + { + "id": "call_abc123", + "type": "function", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "arguments": {"hash": "b573993006976af767214fac"}, + } + ] + response = _make_openai_response_with_tool_call( + tool_name=HEADROOM_RETRIEVE_TOOL_NAME, + arguments={"hash": "b573993006976af767214fac"}, + tool_id="call_abc123", + ) + messages = [{"role": "user", "content": "What does it say? hash=b573993006976af767214fac"}] + + with patch.object( + guardrail.async_handler, + "get", + new_callable=AsyncMock, + return_value=mock_retrieve, + ) as mock_get: + plan = await guardrail.async_build_agentic_loop_plan( + tools={"tool_calls": tool_calls}, + model="gpt-4o", + messages=messages, + response=response, + anthropic_messages_provider_config=None, + anthropic_messages_optional_request_params={}, + logging_obj=None, + stream=False, + kwargs={}, + ) + + assert plan.run_agentic_loop is True + assert plan.request_patch is not None + + follow_up = plan.request_patch.messages + assert follow_up is not None + + tool_result_message = next( + (m for m in follow_up if m.get("role") == "tool"), None + ) + assert tool_result_message is not None + assert tool_result_message["content"] == original_content + assert tool_result_message["tool_call_id"] == "call_abc123" + + mock_get.assert_called_once() + call_url = mock_get.call_args.kwargs.get("url") or mock_get.call_args.args[0] + assert "b573993006976af767214fac" in call_url + + +@pytest.mark.asyncio +async def test_async_build_agentic_loop_plan_handles_retrieve_404( + guardrail: HeadroomGuardrail, +): + mock_retrieve = MagicMock() + mock_retrieve.status_code = 404 + + tool_calls = [ + { + "id": "call_xyz", + "type": "function", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "arguments": {"hash": "deadbeef000000000000dead"}, + } + ] + response = _make_openai_response_with_tool_call( + tool_name=HEADROOM_RETRIEVE_TOOL_NAME, + arguments={"hash": "deadbeef000000000000dead"}, + tool_id="call_xyz", + ) + + with patch.object( + guardrail.async_handler, + "get", + new_callable=AsyncMock, + return_value=mock_retrieve, + ): + plan = await guardrail.async_build_agentic_loop_plan( + tools={"tool_calls": tool_calls}, + model="gpt-4o", + messages=[], + response=response, + anthropic_messages_provider_config=None, + anthropic_messages_optional_request_params={}, + logging_obj=None, + stream=False, + kwargs={}, + ) + + follow_up = plan.request_patch.messages # type: ignore[union-attr] + tool_result = next((m for m in follow_up if m.get("role") == "tool"), None) + assert tool_result is not None + assert "not found" in tool_result["content"] or "expired" in tool_result["content"] + + +def test_extract_hashes_from_messages_finds_hashes(): + messages = [ + {"role": "user", "content": "Retrieve more: hash=b573993006976af767214fac"}, + {"role": "assistant", "content": "Also: hash=aabbccdd001122334455aabb"}, + ] + hashes = extract_hashes_from_messages(messages) + assert "b573993006976af767214fac" in hashes + assert "aabbccdd001122334455aabb" in hashes + + +def test_extract_hashes_from_messages_ignores_short_hashes(): + messages = [{"role": "user", "content": "hash=tooshort"}] + hashes = extract_hashes_from_messages(messages) + assert not hashes + + +def test_extract_hashes_from_list_content_blocks(): + messages = [ + { + "role": "user", + "content": [ + {"type": "text", "text": "hash=b573993006976af767214fac found here"}, + ], + } + ] + hashes = extract_hashes_from_messages(messages) + assert "b573993006976af767214fac" in hashes + + @pytest.mark.asyncio async def test_apply_guardrail_bypass_header_skips_compression( guardrail: HeadroomGuardrail, From a7b18574f5f63c8bc363c057c1e2df06b1839ffc Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 18:18:48 -0700 Subject: [PATCH 02/18] style: run ruff format on headroom guardrail and tests --- .../guardrail_hooks/headroom/headroom.py | 25 +++++----------- .../guardrail_hooks/test_headroom.py | 29 +++++-------------- 2 files changed, 14 insertions(+), 40 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index ceb8d6a8fe57..0ab8221626ec 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -300,9 +300,7 @@ async def _call_retrieve(self, hash_value: str, query: str | None = None) -> str 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 - ) + 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: @@ -414,9 +412,7 @@ async def async_build_agentic_loop_plan( 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) - ) + verbose_proxy_logger.debug("Headroom CCR: retrieved hash=%s (%d chars)", hash_value, len(content)) tool_results.append( { "role": "tool", @@ -428,21 +424,16 @@ async def async_build_agentic_loop_plan( assistant_message = _build_assistant_message_from_response(response) follow_up_messages = list(messages) + [assistant_message] + tool_results - max_tokens: Optional[int] = ( - anthropic_messages_optional_request_params.get("max_tokens") - or kwargs.get("max_tokens") + 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" + 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", {} - ) + 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 @@ -455,9 +446,7 @@ async def async_build_agentic_loop_plan( 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" + k: v for k, v in kwargs.items() if not k.startswith("_headroom") and k != "litellm_logging_obj" }, ), metadata={"tool_type": "headroom_ccr"}, diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py index aad807c1a4b6..105d928896ed 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py @@ -81,9 +81,7 @@ def _make_retrieve_response(original_content: str, status: int = 200) -> MagicMo return mock -def _make_openai_response_with_tool_call( - tool_name: str, arguments: dict, tool_id: str = "call_abc123" -) -> MagicMock: +def _make_openai_response_with_tool_call(tool_name: str, arguments: dict, tool_id: str = "call_abc123") -> MagicMock: fn = MagicMock() fn.name = tool_name fn.arguments = json.dumps(arguments) @@ -215,10 +213,7 @@ async def test_apply_guardrail_preserves_existing_tools_when_injecting( tools = result.get("tools") assert tools is not None assert isinstance(tools, list) - assert any( - isinstance(t, dict) and t.get("function", {}).get("name") == "my_tool" - for t in tools - ) + assert any(isinstance(t, dict) and t.get("function", {}).get("name") == "my_tool" for t in tools) assert has_headroom_retrieve_tool(tools) @@ -339,9 +334,7 @@ async def test_async_build_agentic_loop_plan_calls_retrieve_and_builds_messages( follow_up = plan.request_patch.messages assert follow_up is not None - tool_result_message = next( - (m for m in follow_up if m.get("role") == "tool"), None - ) + tool_result_message = next((m for m in follow_up if m.get("role") == "tool"), None) assert tool_result_message is not None assert tool_result_message["content"] == original_content assert tool_result_message["tool_call_id"] == "call_abc123" @@ -435,9 +428,7 @@ async def test_apply_guardrail_bypass_header_skips_compression( ) request_data = {"proxy_server_request": {"headers": {"x-headroom-bypass": "true"}}} - with patch.object( - guardrail.async_handler, "post", new_callable=AsyncMock - ) as mock_post: + with patch.object(guardrail.async_handler, "post", new_callable=AsyncMock) as mock_post: result = await guardrail.apply_guardrail( inputs=inputs, request_data=request_data, @@ -457,9 +448,7 @@ async def test_apply_guardrail_response_type_passthrough( structured_messages=ORIGINAL_MESSAGES, ) - with patch.object( - guardrail.async_handler, "post", new_callable=AsyncMock - ) as mock_post: + with patch.object(guardrail.async_handler, "post", new_callable=AsyncMock) as mock_post: result = await guardrail.apply_guardrail( inputs=inputs, request_data={}, @@ -476,9 +465,7 @@ async def test_apply_guardrail_empty_structured_messages_passthrough( ): inputs = GenericGuardrailAPIInputs(texts=["hello"]) - with patch.object( - guardrail.async_handler, "post", new_callable=AsyncMock - ) as mock_post: + with patch.object(guardrail.async_handler, "post", new_callable=AsyncMock) as mock_post: result = await guardrail.apply_guardrail( inputs=inputs, request_data={}, @@ -615,9 +602,7 @@ def test_bypass_header_case_insensitive(): guardrail = _make_guardrail() for header_value in ("true", "True", "TRUE"): - data = { - "proxy_server_request": {"headers": {"x-headroom-bypass": header_value}} - } + data = {"proxy_server_request": {"headers": {"x-headroom-bypass": header_value}}} assert guardrail._should_bypass(data) is True data = {"proxy_server_request": {"headers": {"x-headroom-bypass": "false"}}} From 2e79fa3caa22326970fc5d3026003c9044e1c903 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 18:26:07 -0700 Subject: [PATCH 03/18] fix(guardrails/headroom): detect headroom_retrieve calls in both OpenAI and Anthropic response formats --- .../guardrail_hooks/headroom/headroom.py | 80 ++++++++++++------- 1 file changed, 51 insertions(+), 29 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index 0ab8221626ec..20f65125787d 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -98,37 +98,59 @@ def has_headroom_retrieve_tool(tools: object) -> bool: 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 not isinstance(choices, list) or not choices: - return [] - message = getattr(choices[0], "message", None) - if message is None: - return [] - tool_calls = getattr(message, "tool_calls", None) - if not isinstance(tool_calls, list): - return [] + 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) + 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 {}, + } + ) - result: list[dict[str, object]] = [] - 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 From 2059b6dbe4b6ee709accf39b98c448e71c348e29 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 18:27:30 -0700 Subject: [PATCH 04/18] test(guardrails/headroom): add test for Anthropic content block format detection in CCR loop --- .../guardrail_hooks/test_headroom.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py index 105d928896ed..fa8cf1e89187 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py @@ -667,3 +667,35 @@ async def test_apply_guardrail_sends_model_from_request_data_when_no_config_mode call_kwargs = mock_post.call_args sent_payload = call_kwargs.kwargs.get("json") or call_kwargs.args[1] assert sent_payload.get("model") == "gpt-4o" + + +@pytest.mark.asyncio +async def test_async_should_run_agentic_loop_detects_anthropic_content_block_format( + guardrail: HeadroomGuardrail, +): + retrieve_tool_def = [{"type": "function", "function": {"name": HEADROOM_RETRIEVE_TOOL_NAME}}] + + response = MagicMock() + response.choices = None + response.content = [ + { + "type": "tool_use", + "id": "toolu_abc", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "input": {"hash": "b573993006976af767214fac"}, + } + ] + + should_run, ctx = await guardrail.async_should_run_agentic_loop( + response=response, + model="claude-sonnet-4-6", + messages=[], + tools=retrieve_tool_def, + stream=False, + custom_llm_provider="anthropic", + kwargs={}, + ) + + assert should_run is True + assert len(ctx["tool_calls"]) == 1 + assert ctx["tool_calls"][0]["arguments"]["hash"] == "b573993006976af767214fac" From 26eeba8232523f63e619cb9964e5afab934bd81e Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 19:49:14 -0700 Subject: [PATCH 05/18] ci: trigger CI checks From 08d1d750006dc88748aeb8dbf156f865b673a33e Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 20:55:41 -0700 Subject: [PATCH 06/18] fix(guardrails/headroom): replace List/Dict with list/dict to fix UP006 ruff violations --- .../guardrail_hooks/headroom/headroom.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index 20f65125787d..10def90a5fd5 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -2,7 +2,7 @@ import json import re -from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple +from typing import TYPE_CHECKING, Any, Literal, Optional, Tuple import httpx from fastapi import HTTPException @@ -396,12 +396,12 @@ async def async_should_run_agentic_loop( self, response: Any, model: str, - messages: List[Dict], - tools: Optional[List[Dict]], + messages: list[dict], + tools: Optional[list[dict]], stream: bool, custom_llm_provider: str, - kwargs: Dict, - ) -> Tuple[bool, Dict]: + kwargs: dict, + ) -> Tuple[bool, dict]: if not has_headroom_retrieve_tool(tools): return False, {} @@ -413,15 +413,15 @@ async def async_should_run_agentic_loop( async def async_build_agentic_loop_plan( self, - tools: Dict, + tools: dict, model: str, - messages: List[Dict], + messages: list[dict], response: Any, anthropic_messages_provider_config: Any, - anthropic_messages_optional_request_params: Dict, + anthropic_messages_optional_request_params: dict, logging_obj: Any, stream: bool, - kwargs: Dict, + kwargs: dict, ) -> AgenticLoopPlan: tool_calls: list[dict[str, object]] = tools.get("tool_calls", []) # type: ignore[assignment] From 049e5f6d1ae044119e1c4e090d0c86fc0ac0b11b Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 20:58:50 -0700 Subject: [PATCH 07/18] fix(guardrails/headroom): replace except Exception with except ValueError to fix BLE001 --- litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index 10def90a5fd5..ee3fae3bc274 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -265,7 +265,7 @@ async def _call_compress( try: body: object = response.json() - except Exception: + except ValueError: raise HTTPException( status_code=502, detail={ @@ -338,7 +338,7 @@ async def _call_retrieve(self, hash_value: str, query: str | None = None) -> str try: body: object = raw_response.json() - except Exception: + except ValueError: return raw_response.text if _is_str_object_dict(body): From 0f5849b30d4b2ff1fc5c1e1366c17e8699553a11 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 21:19:47 -0700 Subject: [PATCH 08/18] fix(guardrails/headroom): add Responses API output format detection for CCR tool calls --- .../guardrail_hooks/headroom/headroom.py | 29 ++++++++++++++++ .../guardrail_hooks/test_headroom.py | 33 +++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index ee3fae3bc274..2bfdb8ee8b51 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -128,6 +128,35 @@ def _extract_headroom_tool_calls( ) return result + # Responses API format: output list with type=function_call items + output = getattr(response, "output", None) + if isinstance(output, list): + for item in output: + item_type = item.get("type") if isinstance(item, dict) else getattr(item, "type", None) + item_name = item.get("name") if isinstance(item, dict) else getattr(item, "name", None) + if item_type != "function_call" or item_name != HEADROOM_RETRIEVE_TOOL_NAME: + continue + if isinstance(item, dict): + args_str: object = item.get("arguments", "{}") + item_id: object = item.get("id") or item.get("call_id") + else: + args_str = getattr(item, "arguments", "{}") + item_id = getattr(item, "id", None) or getattr(item, "call_id", None) + try: + arguments = json.loads(args_str) if isinstance(args_str, str) else {} + except (json.JSONDecodeError, TypeError): + arguments = {} + result.append( + { + "id": item_id, + "type": "function", + "name": item_name, + "arguments": arguments, + } + ) + if result: + return result + # Anthropic messages format: content blocks with type=tool_use content = getattr(response, "content", None) if isinstance(content, list): diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py index fa8cf1e89187..a34caec25254 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py @@ -699,3 +699,36 @@ async def test_async_should_run_agentic_loop_detects_anthropic_content_block_for assert should_run is True assert len(ctx["tool_calls"]) == 1 assert ctx["tool_calls"][0]["arguments"]["hash"] == "b573993006976af767214fac" + + +@pytest.mark.asyncio +async def test_async_should_run_agentic_loop_detects_responses_api_output_format( + guardrail: HeadroomGuardrail, +): + retrieve_tool_def = [{"type": "function", "function": {"name": HEADROOM_RETRIEVE_TOOL_NAME}}] + + response = MagicMock() + response.choices = None + response.content = None + response.output = [ + { + "type": "function_call", + "id": "fc_abc123", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "arguments": json.dumps({"hash": "b573993006976af767214fac"}), + } + ] + + should_run, ctx = await guardrail.async_should_run_agentic_loop( + response=response, + model="gpt-4o", + messages=[], + tools=retrieve_tool_def, + stream=False, + custom_llm_provider="openai", + kwargs={}, + ) + + assert should_run is True + assert len(ctx["tool_calls"]) == 1 + assert ctx["tool_calls"][0]["arguments"]["hash"] == "b573993006976af767214fac" From 2c6e0e2451e7d03422f13c78acc51d274fc4fe5a Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 21:22:51 -0700 Subject: [PATCH 09/18] refactor(guardrails/headroom): extract format-specific helpers to fix C901 complexity --- .../guardrail_hooks/headroom/headroom.py | 153 +++++++++--------- 1 file changed, 77 insertions(+), 76 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index 2bfdb8ee8b51..0c2d26a2fdee 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -95,94 +95,95 @@ def has_headroom_retrieve_tool(tools: object) -> bool: return False -def _extract_headroom_tool_calls( - response: object, -) -> list[dict[str, object]]: - result: list[dict[str, object]] = [] +def _parse_arguments(raw: object) -> dict[str, object]: + if isinstance(raw, dict): + return raw + try: + parsed = json.loads(raw) if isinstance(raw, str) else {} + return parsed if isinstance(parsed, dict) else {} + except (json.JSONDecodeError, TypeError): + return {} - # OpenAI chat completions format: choices[0].message.tool_calls + +def _extract_from_chat_completions(response: object) -> list[dict[str, object]]: 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 - - # Responses API format: output list with type=function_call items - output = getattr(response, "output", None) - if isinstance(output, list): - for item in output: - item_type = item.get("type") if isinstance(item, dict) else getattr(item, "type", None) - item_name = item.get("name") if isinstance(item, dict) else getattr(item, "name", None) - if item_type != "function_call" or item_name != HEADROOM_RETRIEVE_TOOL_NAME: - continue - if isinstance(item, dict): - args_str: object = item.get("arguments", "{}") - item_id: object = item.get("id") or item.get("call_id") - else: - args_str = getattr(item, "arguments", "{}") - item_id = getattr(item, "id", None) or getattr(item, "call_id", None) - try: - arguments = json.loads(args_str) if isinstance(args_str, str) else {} - except (json.JSONDecodeError, TypeError): - arguments = {} + if not (isinstance(choices, list) and choices): + return [] + message = getattr(choices[0], "message", None) + tool_calls = getattr(message, "tool_calls", None) if message else None + if not isinstance(tool_calls, list): + return [] + result = [] + 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: result.append( { - "id": item_id, + "id": getattr(tc, "id", None), "type": "function", - "name": item_name, - "arguments": arguments, + "name": name, + "arguments": _parse_arguments(getattr(fn, "arguments", "{}")), } ) - if result: - return result + return result - # Anthropic messages format: content blocks with type=tool_use - content = getattr(response, "content", None) - 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 {}, - } - ) +def _extract_from_responses_api(response: object) -> list[dict[str, object]]: + output = getattr(response, "output", None) + if not isinstance(output, list): + return [] + result = [] + for item in output: + item_type = item.get("type") if isinstance(item, dict) else getattr(item, "type", None) + item_name = item.get("name") if isinstance(item, dict) else getattr(item, "name", None) + if item_type != "function_call" or item_name != HEADROOM_RETRIEVE_TOOL_NAME: + continue + args_raw = item.get("arguments", "{}") if isinstance(item, dict) else getattr(item, "arguments", "{}") + item_id = ( + (item.get("id") or item.get("call_id")) + if isinstance(item, dict) + else (getattr(item, "id", None) or getattr(item, "call_id", None)) + ) + result.append({"id": item_id, "type": "function", "name": item_name, "arguments": _parse_arguments(args_raw)}) return result +def _extract_from_anthropic_messages(response: object) -> list[dict[str, object]]: + content = getattr(response, "content", None) + if not isinstance(content, list): + return [] + result = [] + 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 + raw_input = block.get("input", {}) if isinstance(block, dict) else getattr(block, "input", {}) + block_id = block.get("id") if isinstance(block, dict) else 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 _extract_headroom_tool_calls(response: object) -> list[dict[str, object]]: + chat = _extract_from_chat_completions(response) + if chat: + return chat + responses_api = _extract_from_responses_api(response) + if responses_api: + return responses_api + return _extract_from_anthropic_messages(response) + + def _build_assistant_message_from_response(response: object) -> dict[str, object]: choices = getattr(response, "choices", None) if not isinstance(choices, list) or not choices: From 57b37c9b39899f997067bbc5a4b3224f9e08ffda Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Tue, 30 Jun 2026 12:38:15 -0700 Subject: [PATCH 10/18] fix(guardrails/headroom): scope CCR retrieval to hashes produced by current request Previously any LLM-supplied hash in a headroom_retrieve tool call was forwarded to the Headroom retrieve API, letting a crafted tool call fetch arbitrary cached content. Validate the hash against the set produced by compressing the current request's messages before calling retrieve. --- .../guardrail_hooks/headroom/headroom.py | 17 +++++-- .../guardrail_hooks/test_headroom.py | 51 ++++++++++++++++++- 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index 0c2d26a2fdee..c77bee5e5015 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -455,15 +455,24 @@ async def async_build_agentic_loop_plan( ) -> AgenticLoopPlan: tool_calls: list[dict[str, object]] = tools.get("tool_calls", []) # type: ignore[assignment] + valid_hashes = frozenset(extract_hashes_from_messages(messages)) + 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( - hash_value=str(hash_value), - query=str(query) if query else None, - ) + if str(hash_value) not in valid_hashes: + verbose_proxy_logger.warning( + "Headroom CCR: rejecting hash=%s not produced by current request compression", + hash_value, + ) + content = f"[Headroom: hash={hash_value} was not produced by the current request]" + else: + content = await self._call_retrieve( + 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( { diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py index a34caec25254..b5b72d12e67c 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py @@ -365,6 +365,13 @@ async def test_async_build_agentic_loop_plan_handles_retrieve_404( tool_id="call_xyz", ) + messages = [ + { + "role": "user", + "content": "Retrieve more: hash=deadbeef000000000000dead", + } + ] + with patch.object( guardrail.async_handler, "get", @@ -374,7 +381,7 @@ async def test_async_build_agentic_loop_plan_handles_retrieve_404( plan = await guardrail.async_build_agentic_loop_plan( tools={"tool_calls": tool_calls}, model="gpt-4o", - messages=[], + messages=messages, response=response, anthropic_messages_provider_config=None, anthropic_messages_optional_request_params={}, @@ -389,6 +396,48 @@ async def test_async_build_agentic_loop_plan_handles_retrieve_404( assert "not found" in tool_result["content"] or "expired" in tool_result["content"] +async def test_async_build_agentic_loop_plan_rejects_hash_not_in_current_request( + guardrail: HeadroomGuardrail, +): + tool_calls = [ + { + "id": "call_xyz", + "type": "function", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "arguments": {"hash": "deadbeef000000000000dead"}, + } + ] + response = _make_openai_response_with_tool_call( + tool_name=HEADROOM_RETRIEVE_TOOL_NAME, + arguments={"hash": "deadbeef000000000000dead"}, + tool_id="call_xyz", + ) + + with patch.object( + guardrail.async_handler, + "get", + new_callable=AsyncMock, + ) as mock_get: + plan = await guardrail.async_build_agentic_loop_plan( + tools={"tool_calls": tool_calls}, + model="gpt-4o", + messages=[{"role": "user", "content": "no hash markers here"}], + response=response, + anthropic_messages_provider_config=None, + anthropic_messages_optional_request_params={}, + logging_obj=None, + stream=False, + kwargs={}, + ) + + mock_get.assert_not_called() + + follow_up = plan.request_patch.messages # type: ignore[union-attr] + tool_result = next((m for m in follow_up if m.get("role") == "tool"), None) + assert tool_result is not None + assert "was not produced by the current request" in tool_result["content"] + + def test_extract_hashes_from_messages_finds_hashes(): messages = [ {"role": "user", "content": "Retrieve more: hash=b573993006976af767214fac"}, From 223b0fdf99f84bb82c9eca19a21d62ab9b8610de Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Tue, 30 Jun 2026 15:51:25 -0700 Subject: [PATCH 11/18] fix(guardrails/headroom): track issued hashes server-side, fix Responses API replay shape Hash validation now also checks an in-memory cache of hashes actually returned by /v1/compress, not just whether the hash text appears somewhere in the request's messages. The message-text check alone is forgeable: an attacker can plant a hash-shaped string in their own prompt and have it treated as valid. Responses API follow-up now emits function_call/function_call_output items keyed by call_id instead of chat-style assistant/tool messages, since the Responses API does not accept the latter as input. Also fixes call_id/id field priority when extracting tool calls from Responses API output, since call_id (not id) is what must match between the function_call and its output. --- .../guardrail_hooks/headroom/headroom.py | 80 +++++++++--- .../guardrail_hooks/test_headroom.py | 114 ++++++++++++++++++ 2 files changed, 180 insertions(+), 14 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index c77bee5e5015..b0a0683eda6c 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -2,6 +2,7 @@ import json import re +from collections import OrderedDict from typing import TYPE_CHECKING, Any, Literal, Optional, Tuple import httpx @@ -30,6 +31,7 @@ BYPASS_HEADER = "x-headroom-bypass" HEADROOM_RETRIEVE_TOOL_NAME = "headroom_retrieve" _HASH_PATTERN = re.compile(r"hash=([a-f0-9]{24})") +_MAX_ISSUED_HASHES = 5000 def _is_str_object_dict(value: object) -> TypeGuard[dict[str, object]]: # guard-ok: isinstance narrows correctly; predicate is trivially correct # fmt: skip @@ -82,6 +84,20 @@ def _build_headroom_retrieve_tool() -> dict[str, object]: } +def _remember_issued_hashes(cache: "OrderedDict[str, None]", hashes: list[str]) -> None: + """Record hashes actually returned by Headroom's /v1/compress. + + The CCR retrieval loop validates tool-call hashes against this cache so an + attacker can't make the model retrieve content via a hash-shaped string + planted in message text that Headroom never issued. + """ + for hash_value in hashes: + cache[hash_value] = None + cache.move_to_end(hash_value) + while len(cache) > _MAX_ISSUED_HASHES: + cache.popitem(last=False) + + def has_headroom_retrieve_tool(tools: object) -> bool: if not isinstance(tools, list): return False @@ -143,9 +159,9 @@ def _extract_from_responses_api(response: object) -> list[dict[str, object]]: continue args_raw = item.get("arguments", "{}") if isinstance(item, dict) else getattr(item, "arguments", "{}") item_id = ( - (item.get("id") or item.get("call_id")) + (item.get("call_id") or item.get("id")) if isinstance(item, dict) - else (getattr(item, "id", None) or getattr(item, "call_id", None)) + else (getattr(item, "call_id", None) or getattr(item, "id", None)) ) result.append({"id": item_id, "type": "function", "name": item_name, "arguments": _parse_arguments(args_raw)}) return result @@ -210,6 +226,34 @@ def _build_assistant_message_from_response(response: object) -> dict[str, object return {"role": "assistant", "content": content, "tool_calls": raw_tool_calls} +def _is_responses_api_response(response: object) -> bool: + return isinstance(getattr(response, "output", None), list) + + +def _build_responses_followup_items( + retrieved: list[tuple[dict[str, object], str]], +) -> list[dict[str, object]]: + """Build Responses API input items for a tool round-trip. + + The Responses API does not accept chat-style assistant/tool messages as + follow-up input; it requires the model's function_call to be echoed back + paired with a function_call_output keyed by the same call_id. + """ + items: list[dict[str, object]] = [] + for tool_call, content in retrieved: + call_id = tool_call.get("id") + items.append( + { + "type": "function_call", + "call_id": call_id, + "name": tool_call.get("name"), + "arguments": json.dumps(tool_call.get("arguments", {})), + } + ) + items.append({"type": "function_call_output", "call_id": call_id, "output": content}) + return items + + class HeadroomGuardrail(CustomGuardrail): def __init__( self, @@ -231,6 +275,7 @@ def __init__( self.async_handler = get_async_httpx_client( llm_provider=httpxSpecialProvider.GuardrailCallback, ) + self._issued_hashes: "OrderedDict[str, None]" = OrderedDict() super().__init__( # pyright: ignore[reportUnknownMemberType] guardrail_name=guardrail_name, event_hook=event_hook, @@ -411,6 +456,8 @@ async def apply_guardrail( if not hashes: return {**inputs, "structured_messages": compressed} # pyright: ignore[reportReturnType] + _remember_issued_hashes(self._issued_hashes, hashes) + existing_tools = inputs.get("tools") retrieve_tool = _build_headroom_retrieve_tool() if isinstance(existing_tools, list) and not has_headroom_retrieve_tool(existing_tools): @@ -455,14 +502,19 @@ async def async_build_agentic_loop_plan( ) -> AgenticLoopPlan: tool_calls: list[dict[str, object]] = tools.get("tool_calls", []) # type: ignore[assignment] - valid_hashes = frozenset(extract_hashes_from_messages(messages)) + message_hashes = frozenset(extract_hashes_from_messages(messages)) - tool_results: list[dict[str, object]] = [] + retrieved: list[tuple[dict[str, object], str]] = [] 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 - if str(hash_value) not in valid_hashes: + # A hash is only honored if it was actually issued by a Headroom + # /v1/compress call (self._issued_hashes) AND appears in this + # request's own message history. Either check alone is forgeable: + # message text is attacker-controlled, and the issued-hash cache is + # shared across concurrent requests on this guardrail instance. + if str(hash_value) not in message_hashes or str(hash_value) not in self._issued_hashes: verbose_proxy_logger.warning( "Headroom CCR: rejecting hash=%s not produced by current request compression", hash_value, @@ -474,16 +526,16 @@ async def async_build_agentic_loop_plan( 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, - } - ) + retrieved.append((tc, content)) - assistant_message = _build_assistant_message_from_response(response) - follow_up_messages = list(messages) + [assistant_message] + tool_results + if _is_responses_api_response(response): + follow_up_messages = list(messages) + _build_responses_followup_items(retrieved) + else: + assistant_message = _build_assistant_message_from_response(response) + tool_results = [ + {"role": "tool", "tool_call_id": tc.get("id"), "content": content} for tc, content in retrieved + ] + follow_up_messages = list(messages) + [assistant_message] + tool_results max_tokens: Optional[int] = anthropic_messages_optional_request_params.get("max_tokens") or kwargs.get( "max_tokens" diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py index b5b72d12e67c..9468f451941d 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py @@ -309,6 +309,7 @@ async def test_async_build_agentic_loop_plan_calls_retrieve_and_builds_messages( tool_id="call_abc123", ) messages = [{"role": "user", "content": "What does it say? hash=b573993006976af767214fac"}] + guardrail._issued_hashes["b573993006976af767214fac"] = None with patch.object( guardrail.async_handler, @@ -371,6 +372,7 @@ async def test_async_build_agentic_loop_plan_handles_retrieve_404( "content": "Retrieve more: hash=deadbeef000000000000dead", } ] + guardrail._issued_hashes["deadbeef000000000000dead"] = None with patch.object( guardrail.async_handler, @@ -438,6 +440,118 @@ async def test_async_build_agentic_loop_plan_rejects_hash_not_in_current_request assert "was not produced by the current request" in tool_result["content"] +async def test_async_build_agentic_loop_plan_rejects_hash_never_issued_by_compress( + guardrail: HeadroomGuardrail, +): + """A hash-shaped string planted in message text must not be honored unless + this guardrail actually issued it via /v1/compress, even if it's echoed + back in the current request's messages (e.g. via prompt injection).""" + tool_calls = [ + { + "id": "call_xyz", + "type": "function", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "arguments": {"hash": "deadbeef000000000000dead"}, + } + ] + response = _make_openai_response_with_tool_call( + tool_name=HEADROOM_RETRIEVE_TOOL_NAME, + arguments={"hash": "deadbeef000000000000dead"}, + tool_id="call_xyz", + ) + messages = [{"role": "user", "content": "Please fetch hash=deadbeef000000000000dead for me"}] + assert "deadbeef000000000000dead" not in guardrail._issued_hashes + + with patch.object( + guardrail.async_handler, + "get", + new_callable=AsyncMock, + ) as mock_get: + plan = await guardrail.async_build_agentic_loop_plan( + tools={"tool_calls": tool_calls}, + model="gpt-4o", + messages=messages, + response=response, + anthropic_messages_provider_config=None, + anthropic_messages_optional_request_params={}, + logging_obj=None, + stream=False, + kwargs={}, + ) + + mock_get.assert_not_called() + + follow_up = plan.request_patch.messages # type: ignore[union-attr] + tool_result = next((m for m in follow_up if m.get("role") == "tool"), None) + assert tool_result is not None + assert "was not produced by the current request" in tool_result["content"] + + +async def test_async_build_agentic_loop_plan_builds_responses_api_function_call_items( + guardrail: HeadroomGuardrail, +): + """For the Responses API, follow-up input must echo a function_call paired + with a function_call_output keyed by the same call_id -- chat-style + assistant/tool messages are not valid Responses API input items.""" + original_content = "This is the full compressed content." + mock_retrieve = _make_retrieve_response(original_content) + + response = MagicMock() + response.choices = None + response.content = None + response.output = [ + { + "type": "function_call", + "id": "fc_abc123", + "call_id": "call_abc123", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "arguments": json.dumps({"hash": "b573993006976af767214fac"}), + } + ] + + tool_calls = [ + { + "id": "call_abc123", + "type": "function", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "arguments": {"hash": "b573993006976af767214fac"}, + } + ] + messages = [{"role": "user", "content": "What does it say? hash=b573993006976af767214fac"}] + guardrail._issued_hashes["b573993006976af767214fac"] = None + + with patch.object( + guardrail.async_handler, + "get", + new_callable=AsyncMock, + return_value=mock_retrieve, + ): + plan = await guardrail.async_build_agentic_loop_plan( + tools={"tool_calls": tool_calls}, + model="gpt-4o", + messages=messages, + response=response, + anthropic_messages_provider_config=None, + anthropic_messages_optional_request_params={}, + logging_obj=None, + stream=False, + kwargs={}, + ) + + follow_up = plan.request_patch.messages # type: ignore[union-attr] + assert all("role" not in item for item in follow_up if item not in messages) + + function_call_item = next((i for i in follow_up if i.get("type") == "function_call"), None) + assert function_call_item is not None + assert function_call_item["call_id"] == "call_abc123" + assert function_call_item["name"] == HEADROOM_RETRIEVE_TOOL_NAME + + output_item = next((i for i in follow_up if i.get("type") == "function_call_output"), None) + assert output_item is not None + assert output_item["call_id"] == "call_abc123" + assert output_item["output"] == original_content + + def test_extract_hashes_from_messages_finds_hashes(): messages = [ {"role": "user", "content": "Retrieve more: hash=b573993006976af767214fac"}, From 607167bdf4065560eea3bcc234d6022f4e1f6a8f Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Tue, 30 Jun 2026 16:02:42 -0700 Subject: [PATCH 12/18] fix(guardrails/headroom): drop redundant quoted type annotations UP037 flags quotes on annotations that are already lazily evaluated via `from __future__ import annotations`. --- litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index b0a0683eda6c..91062a8d612f 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -84,7 +84,7 @@ def _build_headroom_retrieve_tool() -> dict[str, object]: } -def _remember_issued_hashes(cache: "OrderedDict[str, None]", hashes: list[str]) -> None: +def _remember_issued_hashes(cache: OrderedDict[str, None], hashes: list[str]) -> None: """Record hashes actually returned by Headroom's /v1/compress. The CCR retrieval loop validates tool-call hashes against this cache so an @@ -275,7 +275,7 @@ def __init__( self.async_handler = get_async_httpx_client( llm_provider=httpxSpecialProvider.GuardrailCallback, ) - self._issued_hashes: "OrderedDict[str, None]" = OrderedDict() + self._issued_hashes: OrderedDict[str, None] = OrderedDict() super().__init__( # pyright: ignore[reportUnknownMemberType] guardrail_name=guardrail_name, event_hook=event_hook, From d4596cf755a6bec5f7900e595cac651b87973edb Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Tue, 30 Jun 2026 16:25:02 -0700 Subject: [PATCH 13/18] test(guardrails/headroom): add missing pytest.mark.asyncio decorators Functional under asyncio_mode=auto, but every other async test in the file has the decorator for consistency. --- .../proxy/guardrails/guardrail_hooks/test_headroom.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py index 9468f451941d..35c56753b819 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py @@ -398,6 +398,7 @@ async def test_async_build_agentic_loop_plan_handles_retrieve_404( assert "not found" in tool_result["content"] or "expired" in tool_result["content"] +@pytest.mark.asyncio async def test_async_build_agentic_loop_plan_rejects_hash_not_in_current_request( guardrail: HeadroomGuardrail, ): @@ -440,6 +441,7 @@ async def test_async_build_agentic_loop_plan_rejects_hash_not_in_current_request assert "was not produced by the current request" in tool_result["content"] +@pytest.mark.asyncio async def test_async_build_agentic_loop_plan_rejects_hash_never_issued_by_compress( guardrail: HeadroomGuardrail, ): @@ -487,6 +489,7 @@ async def test_async_build_agentic_loop_plan_rejects_hash_never_issued_by_compre assert "was not produced by the current request" in tool_result["content"] +@pytest.mark.asyncio async def test_async_build_agentic_loop_plan_builds_responses_api_function_call_items( guardrail: HeadroomGuardrail, ): From 16b0c4ae0bd7828ab8c93a85af92cf277e014028 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Tue, 30 Jun 2026 17:12:08 -0700 Subject: [PATCH 14/18] fix(guardrails/headroom): scope CCR hashes per call_id, fix Anthropic replay shape Two real gaps found in review: 1. The instance-wide issued-hash cache combined with a message-text check did not actually scope retrieval to the request that produced the hash. A hash issued for request A stays in the shared cache until TTL expiry, and the message-text check is satisfied by any request whose own messages happen to echo that hash string. Request B could plant A's hash in its own prompt and retrieve A's content. Fixed by keying the issued-hash cache by litellm_call_id, matching the pattern already used in compression_interception: a hash is only honored when it was issued under the exact call_id resolving for the current request. 2. The Anthropic Messages replay path fell through to the chat-style assistant/tool-message builder, which Anthropic does not accept. Anthropic requires the tool_use block echoed in an assistant message paired with a tool_result block in a user message, keyed by tool_use_id. Added a dedicated branch for this shape. --- .../guardrail_hooks/headroom/headroom.py | 96 +++++++++---- .../guardrail_hooks/test_headroom.py | 127 +++++++++++++++--- 2 files changed, 181 insertions(+), 42 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index 91062a8d612f..25e3e36d9c9f 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -2,7 +2,8 @@ import json import re -from collections import OrderedDict +import time +import uuid from typing import TYPE_CHECKING, Any, Literal, Optional, Tuple import httpx @@ -31,7 +32,7 @@ BYPASS_HEADER = "x-headroom-bypass" HEADROOM_RETRIEVE_TOOL_NAME = "headroom_retrieve" _HASH_PATTERN = re.compile(r"hash=([a-f0-9]{24})") -_MAX_ISSUED_HASHES = 5000 +_HASH_CACHE_TTL_SECONDS = 15 * 60 def _is_str_object_dict(value: object) -> TypeGuard[dict[str, object]]: # guard-ok: isinstance narrows correctly; predicate is trivially correct # fmt: skip @@ -84,18 +85,15 @@ def _build_headroom_retrieve_tool() -> dict[str, object]: } -def _remember_issued_hashes(cache: OrderedDict[str, None], hashes: list[str]) -> None: - """Record hashes actually returned by Headroom's /v1/compress. - - The CCR retrieval loop validates tool-call hashes against this cache so an - attacker can't make the model retrieve content via a hash-shaped string - planted in message text that Headroom never issued. - """ - for hash_value in hashes: - cache[hash_value] = None - cache.move_to_end(hash_value) - while len(cache) > _MAX_ISSUED_HASHES: - cache.popitem(last=False) +def _resolve_call_id(logging_obj: object, request_state: dict[str, object]) -> Optional[str]: + """Resolve the litellm_call_id shared by a request's pre-call hook and its + agentic-loop hooks, so CCR hash validation can be scoped per call instead + of trusting any hash-shaped string that shows up in message text.""" + logging_call_id = getattr(logging_obj, "litellm_call_id", None) + if isinstance(logging_call_id, str) and logging_call_id: + return logging_call_id + kwargs_call_id = request_state.get("litellm_call_id") + return kwargs_call_id if isinstance(kwargs_call_id, str) else None def has_headroom_retrieve_tool(tools: object) -> bool: @@ -230,6 +228,41 @@ def _is_responses_api_response(response: object) -> bool: return isinstance(getattr(response, "output", None), list) +def _is_anthropic_messages_response(response: object) -> bool: + return isinstance(getattr(response, "content", None), list) + + +def _build_anthropic_followup_messages( + retrieved: list[tuple[dict[str, object], str]], +) -> list[dict[str, object]]: + """Build Anthropic Messages API follow-up messages for a tool round-trip. + + Anthropic requires the tool_use block to be echoed back in an assistant + message, paired with a tool_result block in a user message keyed by the + same tool_use_id -- it does not accept chat-style tool-role messages. + """ + assistant_message: dict[str, object] = { + "role": "assistant", + "content": [ + { + "type": "tool_use", + "id": tool_call.get("id"), + "name": tool_call.get("name"), + "input": tool_call.get("arguments", {}), + } + for tool_call, _ in retrieved + ], + } + user_message: dict[str, object] = { + "role": "user", + "content": [ + {"type": "tool_result", "tool_use_id": tool_call.get("id"), "content": content} + for tool_call, content in retrieved + ], + } + return [assistant_message, user_message] + + def _build_responses_followup_items( retrieved: list[tuple[dict[str, object], str]], ) -> list[dict[str, object]]: @@ -275,7 +308,7 @@ def __init__( self.async_handler = get_async_httpx_client( llm_provider=httpxSpecialProvider.GuardrailCallback, ) - self._issued_hashes: OrderedDict[str, None] = OrderedDict() + self._issued_hashes_by_call_id: dict[str, tuple[frozenset[str], float]] = {} super().__init__( # pyright: ignore[reportUnknownMemberType] guardrail_name=guardrail_name, event_hook=event_hook, @@ -298,6 +331,14 @@ def _request_headers(self) -> dict[str, str]: headers["Authorization"] = f"Bearer {self.headroom_api_key}" return headers + def _prune_expired_hashes(self) -> None: + now = time.monotonic() + self._issued_hashes_by_call_id = { + call_id: (hashes, expiry) + for call_id, (hashes, expiry) in self._issued_hashes_by_call_id.items() + if expiry > now + } + async def _call_compress( self, messages: list[dict[str, object]], @@ -456,7 +497,12 @@ async def apply_guardrail( if not hashes: return {**inputs, "structured_messages": compressed} # pyright: ignore[reportReturnType] - _remember_issued_hashes(self._issued_hashes, hashes) + self._prune_expired_hashes() + call_id = _resolve_call_id(logging_obj, request_data) + if not call_id: + call_id = str(uuid.uuid4()) + request_data["litellm_call_id"] = call_id + self._issued_hashes_by_call_id[call_id] = (frozenset(hashes), time.monotonic() + _HASH_CACHE_TTL_SECONDS) existing_tools = inputs.get("tools") retrieve_tool = _build_headroom_retrieve_tool() @@ -502,19 +548,21 @@ async def async_build_agentic_loop_plan( ) -> AgenticLoopPlan: tool_calls: list[dict[str, object]] = tools.get("tool_calls", []) # type: ignore[assignment] - message_hashes = frozenset(extract_hashes_from_messages(messages)) + self._prune_expired_hashes() + call_id = _resolve_call_id(logging_obj, kwargs) + valid_hashes = self._issued_hashes_by_call_id.get(call_id, (frozenset(), 0.0))[0] if call_id else frozenset() retrieved: list[tuple[dict[str, object], str]] = [] 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 - # A hash is only honored if it was actually issued by a Headroom - # /v1/compress call (self._issued_hashes) AND appears in this - # request's own message history. Either check alone is forgeable: - # message text is attacker-controlled, and the issued-hash cache is - # shared across concurrent requests on this guardrail instance. - if str(hash_value) not in message_hashes or str(hash_value) not in self._issued_hashes: + # A hash is only honored if it was issued by *this request's own* + # Headroom /v1/compress call, scoped by litellm_call_id. Scoping by + # message text alone is forgeable -- an attacker can plant a + # hash-shaped string in their own prompt, and a hash issued for one + # request would validate for any other request that echoes it back. + if str(hash_value) not in valid_hashes: verbose_proxy_logger.warning( "Headroom CCR: rejecting hash=%s not produced by current request compression", hash_value, @@ -530,6 +578,8 @@ async def async_build_agentic_loop_plan( if _is_responses_api_response(response): follow_up_messages = list(messages) + _build_responses_followup_items(retrieved) + elif _is_anthropic_messages_response(response): + follow_up_messages = list(messages) + _build_anthropic_followup_messages(retrieved) else: assistant_message = _build_assistant_message_from_response(response) tool_results = [ diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py index 35c56753b819..72365403c196 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py @@ -14,6 +14,7 @@ """ import json +import time from unittest.mock import AsyncMock, MagicMock, patch import httpx @@ -309,7 +310,10 @@ async def test_async_build_agentic_loop_plan_calls_retrieve_and_builds_messages( tool_id="call_abc123", ) messages = [{"role": "user", "content": "What does it say? hash=b573993006976af767214fac"}] - guardrail._issued_hashes["b573993006976af767214fac"] = None + guardrail._issued_hashes_by_call_id["call-1"] = ( + frozenset({"b573993006976af767214fac"}), + time.monotonic() + 999, + ) with patch.object( guardrail.async_handler, @@ -326,7 +330,7 @@ async def test_async_build_agentic_loop_plan_calls_retrieve_and_builds_messages( anthropic_messages_optional_request_params={}, logging_obj=None, stream=False, - kwargs={}, + kwargs={"litellm_call_id": "call-1"}, ) assert plan.run_agentic_loop is True @@ -372,7 +376,10 @@ async def test_async_build_agentic_loop_plan_handles_retrieve_404( "content": "Retrieve more: hash=deadbeef000000000000dead", } ] - guardrail._issued_hashes["deadbeef000000000000dead"] = None + guardrail._issued_hashes_by_call_id["call-1"] = ( + frozenset({"deadbeef000000000000dead"}), + time.monotonic() + 999, + ) with patch.object( guardrail.async_handler, @@ -389,7 +396,7 @@ async def test_async_build_agentic_loop_plan_handles_retrieve_404( anthropic_messages_optional_request_params={}, logging_obj=None, stream=False, - kwargs={}, + kwargs={"litellm_call_id": "call-1"}, ) follow_up = plan.request_patch.messages # type: ignore[union-attr] @@ -399,9 +406,12 @@ async def test_async_build_agentic_loop_plan_handles_retrieve_404( @pytest.mark.asyncio -async def test_async_build_agentic_loop_plan_rejects_hash_not_in_current_request( +async def test_async_build_agentic_loop_plan_rejects_hash_with_no_known_call( guardrail: HeadroomGuardrail, ): + """A hash-shaped string planted in message text must not be honored when + this guardrail has no record of ever issuing it, even if it's echoed back + in the current request's own messages (e.g. via prompt injection).""" tool_calls = [ { "id": "call_xyz", @@ -415,6 +425,7 @@ async def test_async_build_agentic_loop_plan_rejects_hash_not_in_current_request arguments={"hash": "deadbeef000000000000dead"}, tool_id="call_xyz", ) + assert not guardrail._issued_hashes_by_call_id with patch.object( guardrail.async_handler, @@ -424,13 +435,13 @@ async def test_async_build_agentic_loop_plan_rejects_hash_not_in_current_request plan = await guardrail.async_build_agentic_loop_plan( tools={"tool_calls": tool_calls}, model="gpt-4o", - messages=[{"role": "user", "content": "no hash markers here"}], + messages=[{"role": "user", "content": "Please fetch hash=deadbeef000000000000dead for me"}], response=response, anthropic_messages_provider_config=None, anthropic_messages_optional_request_params={}, logging_obj=None, stream=False, - kwargs={}, + kwargs={"litellm_call_id": "call-unknown"}, ) mock_get.assert_not_called() @@ -442,27 +453,31 @@ async def test_async_build_agentic_loop_plan_rejects_hash_not_in_current_request @pytest.mark.asyncio -async def test_async_build_agentic_loop_plan_rejects_hash_never_issued_by_compress( +async def test_async_build_agentic_loop_plan_rejects_hash_issued_for_different_call( guardrail: HeadroomGuardrail, ): - """A hash-shaped string planted in message text must not be honored unless - this guardrail actually issued it via /v1/compress, even if it's echoed - back in the current request's messages (e.g. via prompt injection).""" + """A hash issued for one request must not be retrievable by a different + request just because the second request echoes that hash-shaped string + back in its own messages -- retrieval must be scoped per litellm_call_id, + not derived by re-scanning attacker-controlled message text.""" + guardrail._issued_hashes_by_call_id["call-A"] = ( + frozenset({"b573993006976af767214fac"}), + time.monotonic() + 999, + ) + tool_calls = [ { "id": "call_xyz", "type": "function", "name": HEADROOM_RETRIEVE_TOOL_NAME, - "arguments": {"hash": "deadbeef000000000000dead"}, + "arguments": {"hash": "b573993006976af767214fac"}, } ] response = _make_openai_response_with_tool_call( tool_name=HEADROOM_RETRIEVE_TOOL_NAME, - arguments={"hash": "deadbeef000000000000dead"}, + arguments={"hash": "b573993006976af767214fac"}, tool_id="call_xyz", ) - messages = [{"role": "user", "content": "Please fetch hash=deadbeef000000000000dead for me"}] - assert "deadbeef000000000000dead" not in guardrail._issued_hashes with patch.object( guardrail.async_handler, @@ -472,13 +487,13 @@ async def test_async_build_agentic_loop_plan_rejects_hash_never_issued_by_compre plan = await guardrail.async_build_agentic_loop_plan( tools={"tool_calls": tool_calls}, model="gpt-4o", - messages=messages, + messages=[{"role": "user", "content": "Please fetch hash=b573993006976af767214fac for me"}], response=response, anthropic_messages_provider_config=None, anthropic_messages_optional_request_params={}, logging_obj=None, stream=False, - kwargs={}, + kwargs={"litellm_call_id": "call-B"}, ) mock_get.assert_not_called() @@ -521,7 +536,10 @@ async def test_async_build_agentic_loop_plan_builds_responses_api_function_call_ } ] messages = [{"role": "user", "content": "What does it say? hash=b573993006976af767214fac"}] - guardrail._issued_hashes["b573993006976af767214fac"] = None + guardrail._issued_hashes_by_call_id["call-1"] = ( + frozenset({"b573993006976af767214fac"}), + time.monotonic() + 999, + ) with patch.object( guardrail.async_handler, @@ -538,7 +556,7 @@ async def test_async_build_agentic_loop_plan_builds_responses_api_function_call_ anthropic_messages_optional_request_params={}, logging_obj=None, stream=False, - kwargs={}, + kwargs={"litellm_call_id": "call-1"}, ) follow_up = plan.request_patch.messages # type: ignore[union-attr] @@ -555,6 +573,77 @@ async def test_async_build_agentic_loop_plan_builds_responses_api_function_call_ assert output_item["output"] == original_content +@pytest.mark.asyncio +async def test_async_build_agentic_loop_plan_builds_anthropic_tool_result_messages( + guardrail: HeadroomGuardrail, +): + """For the Anthropic Messages API, follow-up must echo a tool_use content + block in an assistant message paired with a tool_result content block in a + user message keyed by the same tool_use_id -- chat-style tool-role + messages are not valid Anthropic input.""" + original_content = "This is the full compressed content." + mock_retrieve = _make_retrieve_response(original_content) + + response = MagicMock() + response.choices = None + response.content = [ + { + "type": "tool_use", + "id": "toolu_abc123", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "input": {"hash": "b573993006976af767214fac"}, + } + ] + + tool_calls = [ + { + "id": "toolu_abc123", + "type": "function", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "arguments": {"hash": "b573993006976af767214fac"}, + } + ] + messages = [{"role": "user", "content": "What does it say? hash=b573993006976af767214fac"}] + guardrail._issued_hashes_by_call_id["call-1"] = ( + frozenset({"b573993006976af767214fac"}), + time.monotonic() + 999, + ) + + with patch.object( + guardrail.async_handler, + "get", + new_callable=AsyncMock, + return_value=mock_retrieve, + ): + plan = await guardrail.async_build_agentic_loop_plan( + tools={"tool_calls": tool_calls}, + model="claude-sonnet-4-5", + messages=messages, + response=response, + anthropic_messages_provider_config=None, + anthropic_messages_optional_request_params={}, + logging_obj=None, + stream=False, + kwargs={"litellm_call_id": "call-1"}, + ) + + follow_up = plan.request_patch.messages # type: ignore[union-attr] + assert all(m.get("role") != "tool" for m in follow_up) + + assistant_message = next((m for m in follow_up if m.get("role") == "assistant"), None) + assert assistant_message is not None + tool_use_block = next((b for b in assistant_message["content"] if b.get("type") == "tool_use"), None) + assert tool_use_block is not None + assert tool_use_block["id"] == "toolu_abc123" + + user_message = follow_up[-1] + assert user_message["role"] == "user" + tool_result_block = next((b for b in user_message["content"] if b.get("type") == "tool_result"), None) + assert tool_result_block is not None + assert tool_result_block["tool_use_id"] == "toolu_abc123" + assert tool_result_block["content"] == original_content + + def test_extract_hashes_from_messages_finds_hashes(): messages = [ {"role": "user", "content": "Retrieve more: hash=b573993006976af767214fac"}, From 36dda9855d7a7dd287e39ab31106ddc6091aa5a1 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Tue, 30 Jun 2026 17:57:53 -0700 Subject: [PATCH 15/18] docs: note proactive API-fragmentation helper convention Add a bullet to the coding-conventions list: look for or add a shared helper when logic branches on API surface (chat completions vs Anthropic Messages vs Responses API), instead of duplicating format-detection per module. --- CLAUDE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CLAUDE.md b/CLAUDE.md index eb32c2cd6da2..0f8aa7eafcaa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -70,6 +70,7 @@ Follow these coding conventions for new/updated code (a three-line fix in a lega - No monster files or god objects - No file sprawl: deliberate file and folder structure - Standard over hand-rolled: use the official SDK or a library where one exists; where none does, follow industry standards instead of inventing local conventions +- API-fragmentation-aware: when logic must branch on which API surface produced or consumes data (e.g. chat completions vs Anthropic Messages vs Responses API shapes), proactively look for an existing shared helper (e.g. `litellm_core_utils/prompt_templates/factory.py`) before writing per-surface parsing in the new module; if none exists, add one there instead of duplicating the same format-detection logic in every new guardrail/integration Follow conventional commits for commit names and PR titles From b167f2a14c7505ab4c3de43007ccb97e161a5551 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Tue, 30 Jun 2026 17:58:05 -0700 Subject: [PATCH 16/18] fix(guardrails/headroom): fix Anthropic tool-shape detection, extract shared cross-API tool util Live e2e testing against the real Anthropic API surfaced two bugs the mocked unit tests couldn't catch because they used MagicMock responses instead of realistic response shapes: 1. has_headroom_retrieve_tool only recognized OpenAI-shaped function tools. By the time an Anthropic Messages response reaches the agentic-loop gate, the tool this guardrail injected has already been transformed into Anthropic's native shape (type: "custom", top-level "name"), so the gate never fired for real Anthropic requests. 2. AnthropicMessagesResponse is a TypedDict, so real responses are plain dicts at runtime, not objects with attribute access. The extractors and format detectors used bare getattr(), which silently returns nothing for dict responses instead of reading the actual key. Extracted the cross-API-surface tool-call extraction and tool-presence check into litellm/litellm_core_utils/prompt_templates/factory.py (get_tool_calls_from_response, has_tool_with_name) so this format fragmentation is handled in one place instead of being duplicated per-guardrail, and reused the existing repair-aware parse_tool_call_arguments from common_utils instead of a naive json.loads. headroom.py now delegates to these shared helpers. Confirmed live against the real Anthropic API: the retrieve loop now fires and successfully retrieves the correct hash's content through the full compress -> tool-call -> retrieve -> replay round-trip. --- .../prompt_templates/factory.py | 141 +++++++++++++++++- .../guardrail_hooks/headroom/headroom.py | 114 ++------------ tests/llm_translation/test_prompt_factory.py | 91 +++++++++++ .../guardrail_hooks/test_headroom.py | 96 ++++++++++-- 4 files changed, 331 insertions(+), 111 deletions(-) diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py index e54218cb8db5..05a2c284672d 100644 --- a/litellm/litellm_core_utils/prompt_templates/factory.py +++ b/litellm/litellm_core_utils/prompt_templates/factory.py @@ -6,7 +6,7 @@ import re import xml.etree.ElementTree as ET from enum import Enum -from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast, overload +from typing import Any, Dict, List, Optional, Set, Tuple, TypedDict, Union, cast, overload from jinja2.sandbox import ImmutableSandboxedEnvironment @@ -5291,3 +5291,142 @@ def get_attribute_or_key(tool_or_function, attribute, default=None): if hasattr(tool_or_function, attribute): return getattr(tool_or_function, attribute) return tool_or_function.get(attribute, default) + + +class NormalizedToolCall(TypedDict): + id: Optional[str] + name: Optional[str] + arguments: Dict[str, Any] + + +def _parse_tool_call_arguments(raw: Any, tool_name: Optional[str], context: str) -> Dict[str, Any]: + # Anthropic's tool_use blocks already carry a parsed dict in "input"; + # chat completions and the Responses API carry a JSON string that may be + # truncated by the model, so route those through the repair-aware parser. + if isinstance(raw, dict): + return raw + if not isinstance(raw, str): + return {} + from litellm.litellm_core_utils.prompt_templates.common_utils import ( + parse_tool_call_arguments, + ) + + try: + parsed = parse_tool_call_arguments(raw, tool_name=tool_name, context=context) + except ValueError as e: + verbose_logger.warning("Failed to parse tool call arguments: %s", e) + return {} + return parsed if isinstance(parsed, dict) else {} + + +def _tool_calls_from_chat_completion_response(response: Any) -> List[NormalizedToolCall]: + choices = get_attribute_or_key(response, "choices", None) + if not (isinstance(choices, list) and choices): + return [] + message = get_attribute_or_key(choices[0], "message", None) + tool_calls = get_attribute_or_key(message, "tool_calls", None) if message else None + if not isinstance(tool_calls, list): + return [] + result: List[NormalizedToolCall] = [] + for tc in tool_calls: + fn = get_attribute_or_key(tc, "function", None) + if fn is None: + continue + name = get_attribute_or_key(fn, "name") + result.append( + NormalizedToolCall( + id=get_attribute_or_key(tc, "id"), + name=name, + arguments=_parse_tool_call_arguments( + get_attribute_or_key(fn, "arguments", "{}"), + tool_name=name, + context="chat completions", + ), + ) + ) + return result + + +def _tool_calls_from_responses_api_response(response: Any) -> List[NormalizedToolCall]: + output = get_attribute_or_key(response, "output", None) + if not isinstance(output, list): + return [] + result: List[NormalizedToolCall] = [] + for item in output: + if get_attribute_or_key(item, "type") != "function_call": + continue + name = get_attribute_or_key(item, "name") + result.append( + NormalizedToolCall( + id=get_attribute_or_key(item, "call_id") or get_attribute_or_key(item, "id"), + name=name, + arguments=_parse_tool_call_arguments( + get_attribute_or_key(item, "arguments", "{}"), + tool_name=name, + context="responses API", + ), + ) + ) + return result + + +def _tool_calls_from_anthropic_messages_response(response: Any) -> List[NormalizedToolCall]: + content = get_attribute_or_key(response, "content", None) + if not isinstance(content, list): + return [] + result: List[NormalizedToolCall] = [] + for block in content: + if get_attribute_or_key(block, "type") != "tool_use": + continue + raw_input = get_attribute_or_key(block, "input", {}) + result.append( + NormalizedToolCall( + id=get_attribute_or_key(block, "id"), + name=get_attribute_or_key(block, "name"), + arguments=raw_input if isinstance(raw_input, dict) else {}, + ) + ) + return result + + +def get_tool_calls_from_response(response: Any) -> List[NormalizedToolCall]: + """ + Extract tool/function calls from a response object into a normalized + ``{"id", "name", "arguments"}`` shape, regardless of which API surface + produced it: chat completions (``choices[].message.tool_calls``), + the Responses API (``output`` items of type ``function_call``), or the + Anthropic Messages API (``content`` blocks of type ``tool_use``). + + Callers that only care about a specific tool should filter the result by + ``name`` themselves -- this returns every tool call found. + """ + for extractor in ( + _tool_calls_from_chat_completion_response, + _tool_calls_from_responses_api_response, + _tool_calls_from_anthropic_messages_response, + ): + tool_calls = extractor(response) + if tool_calls: + return tool_calls + return [] + + +def has_tool_with_name(tools: Any, tool_name: str) -> bool: + """ + Check whether a tools list (as sent to an LLM) includes a tool with the + given name, regardless of shape: OpenAI-style function tools + (``{"type": "function", "function": {"name": ...}}``) or Anthropic's + native tool shape (``{"type": "custom", "name": ...}``). + """ + 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") == tool_name: + return True + if tool.get("type") == "custom" and tool.get("name") == tool_name: + return True + return False diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index 25e3e36d9c9f..31beb559d30b 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -20,6 +20,11 @@ get_async_httpx_client, # pyright: ignore[reportUnknownVariableType] httpxSpecialProvider, ) +from litellm.litellm_core_utils.prompt_templates.factory import ( + get_attribute_or_key, + get_tool_calls_from_response, + has_tool_with_name, +) 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 @@ -97,105 +102,15 @@ def _resolve_call_id(logging_obj: object, request_state: dict[str, object]) -> O 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 _parse_arguments(raw: object) -> dict[str, object]: - if isinstance(raw, dict): - return raw - try: - parsed = json.loads(raw) if isinstance(raw, str) else {} - return parsed if isinstance(parsed, dict) else {} - except (json.JSONDecodeError, TypeError): - return {} - - -def _extract_from_chat_completions(response: object) -> list[dict[str, object]]: - choices = getattr(response, "choices", None) - if not (isinstance(choices, list) and choices): - return [] - message = getattr(choices[0], "message", None) - tool_calls = getattr(message, "tool_calls", None) if message else None - if not isinstance(tool_calls, list): - return [] - result = [] - 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: - result.append( - { - "id": getattr(tc, "id", None), - "type": "function", - "name": name, - "arguments": _parse_arguments(getattr(fn, "arguments", "{}")), - } - ) - return result - - -def _extract_from_responses_api(response: object) -> list[dict[str, object]]: - output = getattr(response, "output", None) - if not isinstance(output, list): - return [] - result = [] - for item in output: - item_type = item.get("type") if isinstance(item, dict) else getattr(item, "type", None) - item_name = item.get("name") if isinstance(item, dict) else getattr(item, "name", None) - if item_type != "function_call" or item_name != HEADROOM_RETRIEVE_TOOL_NAME: - continue - args_raw = item.get("arguments", "{}") if isinstance(item, dict) else getattr(item, "arguments", "{}") - item_id = ( - (item.get("call_id") or item.get("id")) - if isinstance(item, dict) - else (getattr(item, "call_id", None) or getattr(item, "id", None)) - ) - result.append({"id": item_id, "type": "function", "name": item_name, "arguments": _parse_arguments(args_raw)}) - return result - - -def _extract_from_anthropic_messages(response: object) -> list[dict[str, object]]: - content = getattr(response, "content", None) - if not isinstance(content, list): - return [] - result = [] - 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 - raw_input = block.get("input", {}) if isinstance(block, dict) else getattr(block, "input", {}) - block_id = block.get("id") if isinstance(block, dict) else 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 + return has_tool_with_name(tools, HEADROOM_RETRIEVE_TOOL_NAME) def _extract_headroom_tool_calls(response: object) -> list[dict[str, object]]: - chat = _extract_from_chat_completions(response) - if chat: - return chat - responses_api = _extract_from_responses_api(response) - if responses_api: - return responses_api - return _extract_from_anthropic_messages(response) + return [ + {"id": tc["id"], "type": "function", "name": tc["name"], "arguments": tc["arguments"]} + for tc in get_tool_calls_from_response(response) + if tc["name"] == HEADROOM_RETRIEVE_TOOL_NAME + ] def _build_assistant_message_from_response(response: object) -> dict[str, object]: @@ -225,11 +140,14 @@ def _build_assistant_message_from_response(response: object) -> dict[str, object def _is_responses_api_response(response: object) -> bool: - return isinstance(getattr(response, "output", None), list) + # Real response objects can be plain dicts at runtime (e.g. TypedDict-based + # response types), so getattr alone would silently miss the key -- use the + # same dict-or-object accessor as the tool-call extractors. + return isinstance(get_attribute_or_key(response, "output", None), list) def _is_anthropic_messages_response(response: object) -> bool: - return isinstance(getattr(response, "content", None), list) + return isinstance(get_attribute_or_key(response, "content", None), list) def _build_anthropic_followup_messages( diff --git a/tests/llm_translation/test_prompt_factory.py b/tests/llm_translation/test_prompt_factory.py index 05a58a135d26..f139ce700b58 100644 --- a/tests/llm_translation/test_prompt_factory.py +++ b/tests/llm_translation/test_prompt_factory.py @@ -20,6 +20,8 @@ convert_to_anthropic_tool_invoke, convert_url_to_base64, create_anthropic_image_param, + get_tool_calls_from_response, + has_tool_with_name, llama_2_chat_pt, prompt_factory, ) @@ -2385,3 +2387,92 @@ def test_anthropic_messages_pt_list_content_with_thinking_preserves_order(): # Verify signatures preserved in correct positions assert content[0]["signature"] == "sig_1" assert content[3]["signature"] == "sig_2" + + +def test_get_tool_calls_from_response_chat_completions(): + response = MagicMock() + response.output = None + response.content = None + tool_call = MagicMock() + tool_call.id = "call_abc" + tool_call.function.name = "my_tool" + tool_call.function.arguments = '{"x": 1}' + response.choices = [MagicMock(message=MagicMock(tool_calls=[tool_call]))] + + result = get_tool_calls_from_response(response) + + assert result == [{"id": "call_abc", "name": "my_tool", "arguments": {"x": 1}}] + + +def test_get_tool_calls_from_response_responses_api(): + response = MagicMock() + response.choices = None + response.content = None + response.output = [ + { + "type": "function_call", + "id": "fc_1", + "call_id": "call_1", + "name": "my_tool", + "arguments": '{"x": 2}', + } + ] + + result = get_tool_calls_from_response(response) + + assert result == [{"id": "call_1", "name": "my_tool", "arguments": {"x": 2}}] + + +def test_get_tool_calls_from_response_anthropic_messages(): + response = MagicMock() + response.choices = None + response.output = None + response.content = [ + {"type": "tool_use", "id": "toolu_1", "name": "my_tool", "input": {"x": 3}}, + ] + + result = get_tool_calls_from_response(response) + + assert result == [{"id": "toolu_1", "name": "my_tool", "arguments": {"x": 3}}] + + +def test_get_tool_calls_from_response_anthropic_messages_plain_dict(): + # AnthropicMessagesResponse is a TypedDict -- real responses are plain + # dicts at runtime, not objects with attribute access. A MagicMock-only + # test would pass even if the extractor used bare getattr() and silently + # returned nothing for a real response. + response = { + "content": [ + {"type": "tool_use", "id": "toolu_1", "name": "my_tool", "input": {"x": 3}}, + ] + } + + result = get_tool_calls_from_response(response) + + assert result == [{"id": "toolu_1", "name": "my_tool", "arguments": {"x": 3}}] + + +def test_get_tool_calls_from_response_no_tool_calls(): + response = MagicMock() + response.choices = None + response.output = None + response.content = None + + assert get_tool_calls_from_response(response) == [] + + +def test_has_tool_with_name_openai_function_shape(): + tools = [{"type": "function", "function": {"name": "my_tool"}}] + assert has_tool_with_name(tools, "my_tool") + assert not has_tool_with_name(tools, "other_tool") + + +def test_has_tool_with_name_anthropic_custom_shape(): + tools = [{"type": "custom", "name": "my_tool", "input_schema": {}}] + assert has_tool_with_name(tools, "my_tool") + assert not has_tool_with_name(tools, "other_tool") + + +def test_has_tool_with_name_not_a_list(): + assert not has_tool_with_name(None, "my_tool") + assert not has_tool_with_name("not a list", "my_tool") diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py index 72365403c196..f5ce6cedf646 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py @@ -580,20 +580,26 @@ async def test_async_build_agentic_loop_plan_builds_anthropic_tool_result_messag """For the Anthropic Messages API, follow-up must echo a tool_use content block in an assistant message paired with a tool_result content block in a user message keyed by the same tool_use_id -- chat-style tool-role - messages are not valid Anthropic input.""" + messages are not valid Anthropic input. + + AnthropicMessagesResponse is a TypedDict, so real responses are plain + dicts at runtime; a MagicMock response here would pass even if branch + selection used bare getattr() and silently fell through to the + chat-completions replay shape for every real Anthropic response. + """ original_content = "This is the full compressed content." mock_retrieve = _make_retrieve_response(original_content) - response = MagicMock() - response.choices = None - response.content = [ - { - "type": "tool_use", - "id": "toolu_abc123", - "name": HEADROOM_RETRIEVE_TOOL_NAME, - "input": {"hash": "b573993006976af767214fac"}, - } - ] + response = { + "content": [ + { + "type": "tool_use", + "id": "toolu_abc123", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "input": {"hash": "b573993006976af767214fac"}, + } + ] + } tool_calls = [ { @@ -673,6 +679,22 @@ def test_extract_hashes_from_list_content_blocks(): assert "b573993006976af767214fac" in hashes +def test_has_headroom_retrieve_tool_recognizes_anthropic_native_shape(): + """By the time an Anthropic Messages API response reaches the agentic-loop + gate, the OpenAI-shaped tool this guardrail injects (type: "function") + has already been transformed into Anthropic's native tool shape + (type: "custom", top-level "name", no nested "function" object).""" + anthropic_native_tools = [ + { + "type": "custom", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "input_schema": {"type": "object", "properties": {"hash": {"type": "string"}}}, + } + ] + assert has_headroom_retrieve_tool(anthropic_native_tools) + assert not has_headroom_retrieve_tool([{"type": "custom", "name": "some_other_tool"}]) + + @pytest.mark.asyncio async def test_apply_guardrail_bypass_header_skips_compression( guardrail: HeadroomGuardrail, @@ -928,7 +950,16 @@ async def test_apply_guardrail_sends_model_from_request_data_when_no_config_mode async def test_async_should_run_agentic_loop_detects_anthropic_content_block_format( guardrail: HeadroomGuardrail, ): - retrieve_tool_def = [{"type": "function", "function": {"name": HEADROOM_RETRIEVE_TOOL_NAME}}] + # Anthropic's native tool format (type: "custom", top-level "name") -- + # by the time a Messages API response reaches this gate, the OpenAI-shaped + # tool this guardrail injects has already been transformed into this shape. + retrieve_tool_def = [ + { + "type": "custom", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "input_schema": {"type": "object", "properties": {"hash": {"type": "string"}}}, + } + ] response = MagicMock() response.choices = None @@ -956,6 +987,47 @@ async def test_async_should_run_agentic_loop_detects_anthropic_content_block_for assert ctx["tool_calls"][0]["arguments"]["hash"] == "b573993006976af767214fac" +@pytest.mark.asyncio +async def test_async_should_run_agentic_loop_detects_anthropic_response_as_plain_dict( + guardrail: HeadroomGuardrail, +): + """AnthropicMessagesResponse is a TypedDict -- real Messages API responses + are plain dicts at runtime, not objects with attribute access. A + MagicMock-only test would pass even if detection used bare getattr() and + silently treated every real response as having no tool calls.""" + retrieve_tool_def = [ + { + "type": "custom", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "input_schema": {"type": "object", "properties": {"hash": {"type": "string"}}}, + } + ] + response = { + "content": [ + { + "type": "tool_use", + "id": "toolu_abc", + "name": HEADROOM_RETRIEVE_TOOL_NAME, + "input": {"hash": "b573993006976af767214fac"}, + } + ] + } + + should_run, ctx = await guardrail.async_should_run_agentic_loop( + response=response, + model="claude-sonnet-4-6", + messages=[], + tools=retrieve_tool_def, + stream=False, + custom_llm_provider="anthropic", + kwargs={}, + ) + + assert should_run is True + assert len(ctx["tool_calls"]) == 1 + assert ctx["tool_calls"][0]["arguments"]["hash"] == "b573993006976af767214fac" + + @pytest.mark.asyncio async def test_async_should_run_agentic_loop_detects_responses_api_output_format( guardrail: HeadroomGuardrail, From 013b4bf0cefcf465fd4572b3d22451522c00930b Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Tue, 30 Jun 2026 18:28:48 -0700 Subject: [PATCH 17/18] fix(guardrails/headroom): fix ruff-strict UP006/I001 budget violations Use lowercase list/dict generics in the new factory.py tool-call helpers instead of typing.List/Dict, drop the now-unused Tuple import in headroom.py, and reorder the new factory import ahead of the llms.custom_httpx import to satisfy import sorting. --- .../prompt_templates/factory.py | 18 +++++++++--------- .../guardrail_hooks/headroom/headroom.py | 12 ++++++------ 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py index 05a2c284672d..a5f69a63caa9 100644 --- a/litellm/litellm_core_utils/prompt_templates/factory.py +++ b/litellm/litellm_core_utils/prompt_templates/factory.py @@ -5296,10 +5296,10 @@ def get_attribute_or_key(tool_or_function, attribute, default=None): class NormalizedToolCall(TypedDict): id: Optional[str] name: Optional[str] - arguments: Dict[str, Any] + arguments: dict[str, Any] -def _parse_tool_call_arguments(raw: Any, tool_name: Optional[str], context: str) -> Dict[str, Any]: +def _parse_tool_call_arguments(raw: Any, tool_name: Optional[str], context: str) -> dict[str, Any]: # Anthropic's tool_use blocks already carry a parsed dict in "input"; # chat completions and the Responses API carry a JSON string that may be # truncated by the model, so route those through the repair-aware parser. @@ -5319,7 +5319,7 @@ def _parse_tool_call_arguments(raw: Any, tool_name: Optional[str], context: str) return parsed if isinstance(parsed, dict) else {} -def _tool_calls_from_chat_completion_response(response: Any) -> List[NormalizedToolCall]: +def _tool_calls_from_chat_completion_response(response: Any) -> list[NormalizedToolCall]: choices = get_attribute_or_key(response, "choices", None) if not (isinstance(choices, list) and choices): return [] @@ -5327,7 +5327,7 @@ def _tool_calls_from_chat_completion_response(response: Any) -> List[NormalizedT tool_calls = get_attribute_or_key(message, "tool_calls", None) if message else None if not isinstance(tool_calls, list): return [] - result: List[NormalizedToolCall] = [] + result: list[NormalizedToolCall] = [] for tc in tool_calls: fn = get_attribute_or_key(tc, "function", None) if fn is None: @@ -5347,11 +5347,11 @@ def _tool_calls_from_chat_completion_response(response: Any) -> List[NormalizedT return result -def _tool_calls_from_responses_api_response(response: Any) -> List[NormalizedToolCall]: +def _tool_calls_from_responses_api_response(response: Any) -> list[NormalizedToolCall]: output = get_attribute_or_key(response, "output", None) if not isinstance(output, list): return [] - result: List[NormalizedToolCall] = [] + result: list[NormalizedToolCall] = [] for item in output: if get_attribute_or_key(item, "type") != "function_call": continue @@ -5370,11 +5370,11 @@ def _tool_calls_from_responses_api_response(response: Any) -> List[NormalizedToo return result -def _tool_calls_from_anthropic_messages_response(response: Any) -> List[NormalizedToolCall]: +def _tool_calls_from_anthropic_messages_response(response: Any) -> list[NormalizedToolCall]: content = get_attribute_or_key(response, "content", None) if not isinstance(content, list): return [] - result: List[NormalizedToolCall] = [] + result: list[NormalizedToolCall] = [] for block in content: if get_attribute_or_key(block, "type") != "tool_use": continue @@ -5389,7 +5389,7 @@ def _tool_calls_from_anthropic_messages_response(response: Any) -> List[Normaliz return result -def get_tool_calls_from_response(response: Any) -> List[NormalizedToolCall]: +def get_tool_calls_from_response(response: Any) -> list[NormalizedToolCall]: """ Extract tool/function calls from a response object into a normalized ``{"id", "name", "arguments"}`` shape, regardless of which API surface diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py index 31beb559d30b..4badb48e2eb2 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py +++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py @@ -4,7 +4,7 @@ import re import time import uuid -from typing import TYPE_CHECKING, Any, Literal, Optional, Tuple +from typing import TYPE_CHECKING, Any, Literal, Optional import httpx from fastapi import HTTPException @@ -16,15 +16,15 @@ CustomGuardrail, log_guardrail_information, ) -from litellm.llms.custom_httpx.http_handler import ( - get_async_httpx_client, # pyright: ignore[reportUnknownVariableType] - httpxSpecialProvider, -) from litellm.litellm_core_utils.prompt_templates.factory import ( get_attribute_or_key, get_tool_calls_from_response, has_tool_with_name, ) +from litellm.llms.custom_httpx.http_handler import ( + get_async_httpx_client, # pyright: ignore[reportUnknownVariableType] + httpxSpecialProvider, +) 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 @@ -442,7 +442,7 @@ async def async_should_run_agentic_loop( stream: bool, custom_llm_provider: str, kwargs: dict, - ) -> Tuple[bool, dict]: + ) -> tuple[bool, dict]: if not has_headroom_retrieve_tool(tools): return False, {} From 5bc3838974faa482e1dae99268f6dc0f160d8ecc Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Tue, 30 Jun 2026 19:10:07 -0700 Subject: [PATCH 18/18] fix(guardrails/headroom): match Anthropic tools without a type field Anthropic's documented client tool format is just name + input_schema; type: "custom" is only one possible value, not a requirement. Match any non-OpenAI-shaped tool on its top-level name instead of requiring type == "custom". --- litellm/litellm_core_utils/prompt_templates/factory.py | 8 ++++++-- tests/llm_translation/test_prompt_factory.py | 8 ++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py index a5f69a63caa9..f47289657585 100644 --- a/litellm/litellm_core_utils/prompt_templates/factory.py +++ b/litellm/litellm_core_utils/prompt_templates/factory.py @@ -5416,7 +5416,11 @@ def has_tool_with_name(tools: Any, tool_name: str) -> bool: Check whether a tools list (as sent to an LLM) includes a tool with the given name, regardless of shape: OpenAI-style function tools (``{"type": "function", "function": {"name": ...}}``) or Anthropic's - native tool shape (``{"type": "custom", "name": ...}``). + native tool shape (a top-level ``"name"``, e.g. + ``{"name": ..., "input_schema": ...}``). Anthropic's documented client + tool format doesn't require a ``"type"`` key at all -- ``"custom"`` is + only one of several possible values -- so any non-OpenAI-shaped tool is + matched on its top-level ``"name"``. """ if not isinstance(tools, list): return False @@ -5427,6 +5431,6 @@ def has_tool_with_name(tools: Any, tool_name: str) -> bool: if tool.get("type") == "function" and isinstance(function, dict): if function.get("name") == tool_name: return True - if tool.get("type") == "custom" and tool.get("name") == tool_name: + elif tool.get("name") == tool_name: return True return False diff --git a/tests/llm_translation/test_prompt_factory.py b/tests/llm_translation/test_prompt_factory.py index f139ce700b58..ae215602e31d 100644 --- a/tests/llm_translation/test_prompt_factory.py +++ b/tests/llm_translation/test_prompt_factory.py @@ -2473,6 +2473,14 @@ def test_has_tool_with_name_anthropic_custom_shape(): assert not has_tool_with_name(tools, "other_tool") +def test_has_tool_with_name_anthropic_shape_without_type_field(): + # Anthropic's documented client tool format is just name + input_schema; + # "type" isn't required at all (type: "custom" is only one possible value). + tools = [{"name": "my_tool", "input_schema": {}}] + assert has_tool_with_name(tools, "my_tool") + assert not has_tool_with_name(tools, "other_tool") + + def test_has_tool_with_name_not_a_list(): assert not has_tool_with_name(None, "my_tool") assert not has_tool_with_name("not a list", "my_tool")