Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(guardrails): merge synthesized tools under scan_only_tool_results and reject role-filtered no-op combos at init

mateo-berri7d745521bf94
diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py
index 20f3aa430e9..7c8c9aeb248 100644
--- a/litellm/integrations/custom_guardrail.py
+++ b/litellm/integrations/custom_guardrail.py
@@ -714,6 +714,16 @@ class CustomGuardrail(CustomLogger):
return result
+ def supports_scan_only_tool_results(self) -> bool:
+ """Whether this guardrail can scan tool-result content.
+
+ Guardrails whose own role filtering only ever scans human-authored
+ messages override this to return False, so configuring them with
+ ``scan_only_tool_results`` is rejected at initialization instead of
+ silently scanning nothing on every request.
+ """
+ return True
+
def should_run_guardrail(
self,
data,
diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
index 184e0f6a343..aef01765e6e 100644
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@ -26,10 +26,12 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.transformation im
)
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
from litellm.llms.base_llm.guardrail_translation.utils import (
+ anthropic_tool_name,
effective_scan_only_tool_results_for_guardrail,
effective_skip_system_message_for_guardrail,
effective_skip_tool_message_for_guardrail,
merge_guardrailed_scoped_messages,
+ merge_returned_tools_into_request_tools,
scoped_structured_message_indices,
)
from litellm.proxy.pass_through_endpoints.llm_provider_handlers.anthropic_passthrough_logging_handler import (
@@ -387,7 +389,7 @@ class AnthropicMessagesHandler(BaseTranslation):
guardrailed_texts: Final = guardrailed_inputs.get("texts", [])
guardrailed_tools: Final = guardrailed_inputs.get("tools")
- if guardrailed_tools is not None and not scan_only_tool_results:
+ if guardrailed_tools is not None:
# Convert tools back from OpenAI format to Anthropic format
anthropic_config: Final = AnthropicConfig()
anthropic_tools: Final[list[AllAnthropicToolsValues]] = []
@@ -396,7 +398,15 @@ class AnthropicMessagesHandler(BaseTranslation):
if converted_tool is not None:
anthropic_tools.append(converted_tool)
# Note: MCP servers are handled separately in the main transformation
- data["tools"] = anthropic_tools
+ data["tools"] = (
+ merge_returned_tools_into_request_tools(
+ request_tools=data.get("tools"),
+ returned_tools=anthropic_tools,
+ tool_name=anthropic_tool_name,
+ )
+ if scan_only_tool_results
+ else anthropic_tools
+ )
guardrailed_structured_messages: Final = guardrailed_inputs.get("structured_messages")
if (
diff --git a/litellm/llms/base_llm/guardrail_translation/utils.py b/litellm/llms/base_llm/guardrail_translation/utils.py
index 432ac64b456..bdfe15ca9a6 100644
--- a/litellm/llms/base_llm/guardrail_translation/utils.py
+++ b/litellm/llms/base_llm/guardrail_translation/utils.py
@@ -1,8 +1,8 @@
from __future__ import annotations
import json
-from collections.abc import Iterator, Sequence
-from typing import Any, Final
+from collections.abc import Callable, Iterator, Sequence
+from typing import Any, Final, TypeVar
from litellm.types.llms.anthropic_messages.anthropic_response import AnthropicUsage
from litellm.types.llms.openai import AllMessageValues
@@ -167,6 +167,45 @@ def scoped_structured_message_indices(
)
+ToolT = TypeVar("ToolT")
+
+
+def openai_tool_name(tool: object) -> str | None:
+ if not isinstance(tool, dict):
+ return None
+ function: Final = tool.get("function")
+ if isinstance(function, dict):
+ function_name: Final = function.get("name")
+ return function_name if isinstance(function_name, str) else None
+ flat_name: Final = tool.get("name")
+ return flat_name if isinstance(flat_name, str) else None
+
+
+def anthropic_tool_name(tool: object) -> str | None:
+ name: Final = tool.get("name") if isinstance(tool, dict) else None
+ return name if isinstance(name, str) else None
+
+
+def merge_returned_tools_into_request_tools(
+ request_tools: Sequence[ToolT] | None,
+ returned_tools: Sequence[ToolT],
+ tool_name: Callable[[ToolT], str | None],
+) -> list[ToolT]:
+ """Union of the request's tools and guardrail-returned tools, keyed by name.
+
+ Under ``scan_only_tool_results`` the guardrail never saw the request's
+ tools, so a returned list can neither replace them (it would drop every
+ user-defined function) nor be discarded (it may carry a tool the guardrail
+ synthesized and told the model to call, like Compresr's retrieve tool).
+ Keep every request tool and append only returned tools whose names aren't
+ already taken.
+ """
+ originals: Final = tuple(request_tools or ())
+ taken_names: Final = frozenset(name for tool in originals if (name := tool_name(tool)) is not None)
+ additions: Final = tuple(tool for tool in returned_tools if tool_name(tool) not in taken_names)
+ return [*originals, *additions]
+
+
def merge_guardrailed_scoped_messages(
full_messages: Sequence[AllMessageValues],
scoped_indices: Sequence[int],
diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.py
index dc2a06d67fc..4f0f69866ad 100644
--- a/litellm/llms/openai/chat/guardrail_translation/handler.py
+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py
@@ -27,6 +27,8 @@ from litellm.llms.base_llm.guardrail_translation.utils import (
effective_skip_system_message_for_guardrail,
effective_skip_tool_message_for_guardrail,
merge_guardrailed_scoped_messages,
+ merge_returned_tools_into_request_tools,
+ openai_tool_name,
role_out_of_guardrail_scope,
scoped_structured_message_indices,
)
@@ -143,8 +145,16 @@ class OpenAIChatCompletionsHandler(BaseTranslation):
guardrailed_texts: Final = guardrailed_inputs.get("texts", [])
guardrailed_tool_calls: Final = guardrailed_inputs.get("tool_calls", [])
guardrailed_tools: Final = guardrailed_inputs.get("tools")
- if guardrailed_tools is not None and not scan_only_tool_results:
- data["tools"] = guardrailed_tools
+ if guardrailed_tools is not None:
+ data["tools"] = (
+ merge_returned_tools_into_request_tools(
+ request_tools=tools,
+ returned_tools=guardrailed_tools,
+ tool_name=openai_tool_name,
+ )
+ if scan_only_tool_results
+ else guardrailed_tools
+ )
guardrailed_structured_messages: Final = guardrailed_inputs.get("structured_messages")
if (
diff --git a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
index 8193069fd82..e9e729fb118 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
@@ -405,6 +405,9 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):
grounding.append(block)
return grounding
+ def supports_scan_only_tool_results(self) -> bool:
+ return self.experimental_use_latest_role_message_only is not True
+
def _prepare_guardrail_messages_for_role(
self,
messages: list[AllMessageValues] | None,
diff --git a/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py b/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py
index a96a0070eef..13ced0ac06c 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py
@@ -1564,6 +1564,9 @@ class PanwPrismaAirsHandler(CustomGuardrail):
return scannable
+ def supports_scan_only_tool_results(self) -> bool:
+ return False
+
@staticmethod
def _get_scannable_text_indices(
texts: list[str],
diff --git a/litellm/proxy/guardrails/guardrail_registry.py b/litellm/proxy/guardrails/guardrail_registry.py
index e9e61283c1a..15e884c939c 100644
--- a/litellm/proxy/guardrails/guardrail_registry.py
+++ b/litellm/proxy/guardrails/guardrail_registry.py
@@ -14,6 +14,9 @@ from litellm._logging import verbose_proxy_logger
from litellm._uuid import uuid
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
+from litellm.llms.base_llm.guardrail_translation.utils import (
+ effective_scan_only_tool_results_for_guardrail,
+)
from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import (
BedrockGuardrail,
)
@@ -493,6 +496,15 @@ class InMemoryGuardrailHandler:
"scan_only_tool_results",
):
setattr(custom_guardrail_callback, scoping_param, getattr(litellm_params, scoping_param, None))
+ if (
+ effective_scan_only_tool_results_for_guardrail(custom_guardrail_callback)
+ and not custom_guardrail_callback.supports_scan_only_tool_results()
+ ):
+ raise ValueError(
+ f"Guardrail {guardrail['guardrail_name']}: scan_only_tool_results is enabled, but this "
+ "guardrail's role filtering never scans tool results, so no request content would ever "
+ "be scanned. Remove scan_only_tool_results or the guardrail's role-filtering option."
+ )
configured_run_in_parallel: Final = getattr(litellm_params, "run_in_parallel", None)
if configured_run_in_parallel is not None:
custom_guardrail_callback.run_in_parallel = bool(configured_run_in_parallel)
diff --git a/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py b/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
index c7dedff0663..c7a30f7f954 100644
--- a/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
+++ b/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
@@ -883,7 +883,7 @@ class TestAnthropicMessagesScanOnlyToolResults:
assert data["messages"][2]["content"][0]["text"] == "sibling POISON text"
@pytest.mark.asyncio
- async def test_guardrail_synthesized_tools_never_replace_scoped_out_request_tools(self):
+ async def test_guardrail_synthesized_tools_are_appended_without_replacing_request_tools(self):
handler = AnthropicMessagesHandler()
guardrail = ToolAppendingGuardrail(guardrail_name="tool-appending")
guardrail.scan_only_tool_results = True
@@ -912,9 +912,11 @@ class TestAnthropicMessagesScanOnlyToolResults:
await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
- assert data["tools"] == original_tools, (
- "tools the guardrail synthesized without seeing the request's tools must not replace them"
+ assert [t["name"] for t in data["tools"]] == ["get_weather", "injected_tool"], (
+ "a tool the guardrail synthesized must reach the model, converted to Anthropic format, "
+ "without the request's own tools being replaced or dropped"
)
+ assert data["tools"][0] == original_tools[0]
@pytest.mark.asyncio
async def test_guardrail_is_not_called_when_the_request_has_no_tool_results(self):
diff --git a/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py b/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
index 269afef69cd..deabee12497 100644
--- a/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
@@ -1278,6 +1278,35 @@ class ToolSynthesizingGuardrail(CustomGuardrail):
return inputs
+class ToolNameCollidingGuardrail(CustomGuardrail):
+ """Returns a tool reusing a request tool's name plus a genuinely new tool."""
+
+ def __init__(self):
+ super().__init__(guardrail_name="tool-name-colliding")
+
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict,
+ input_type: Literal["request", "response"],
+ logging_obj: Optional[Any] = None,
+ ) -> GenericGuardrailAPIInputs:
+ inputs["tools"] = [
+ {
+ "type": "function",
+ "function": {
+ "name": "read_file",
+ "parameters": {"type": "object", "properties": {"hijacked": {"type": "string"}}},
+ },
+ },
+ {
+ "type": "function",
+ "function": {"name": "injected_retrieve", "parameters": {"type": "object", "properties": {}}},
+ },
+ ]
+ return inputs
+
+
class TestScanOnlyToolResults:
def _bedrock_guardrail(self):
from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import BedrockGuardrail
@@ -1375,7 +1404,9 @@ class TestScanOnlyToolResults:
@pytest.mark.parametrize("scan_only_tool_results", [True, False])
@pytest.mark.asyncio
- async def test_guardrail_synthesized_tools_never_replace_scoped_out_request_tools(self, scan_only_tool_results):
+ async def test_guardrail_synthesized_tools_are_appended_without_replacing_request_tools(
+ self, scan_only_tool_results
+ ):
handler = OpenAIChatCompletionsHandler()
guardrail = ToolSynthesizingGuardrail()
guardrail.scan_only_tool_results = scan_only_tool_results
@@ -1395,12 +1426,35 @@ class TestScanOnlyToolResults:
await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
- if scan_only_tool_results:
- assert data["tools"] == original_tools, (
- "tools the guardrail synthesized without seeing the request's tools must not replace them"
- )
- else:
- assert [t["function"]["name"] for t in data["tools"]] == ["read_file", "injected_retrieve"]
+ assert [t["function"]["name"] for t in data["tools"]] == ["read_file", "injected_retrieve"], (
+ "a tool the guardrail synthesized (like a recovery/retrieve tool) must reach the model "
+ "without the request's own tools being replaced or dropped"
+ )
+ assert data["tools"][0] == original_tools[0]
+
+ @pytest.mark.asyncio
+ async def test_returned_tool_name_collisions_keep_the_request_schema(self):
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = ToolNameCollidingGuardrail()
+ guardrail.scan_only_tool_results = True
+ original_read_file = {
+ "type": "function",
+ "function": {"name": "read_file", "parameters": {"type": "object", "properties": {}}},
+ }
+ data = {
+ "messages": [
+ {"role": "user", "content": "read the report"},
+ {"role": "tool", "tool_call_id": "call_1", "content": "TOOL-RESULT"},
+ ],
+ "tools": [original_read_file],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert [t["function"]["name"] for t in data["tools"]] == ["read_file", "injected_retrieve"]
+ assert data["tools"][0] == original_read_file, (
+ "a returned tool reusing a request tool's name must not replace the request's schema"
+ )
@pytest.mark.asyncio
async def test_structured_write_back_keeps_out_of_scope_messages(self):
diff --git a/tests/test_litellm/proxy/guardrails/test_guardrail_registry.py b/tests/test_litellm/proxy/guardrails/test_guardrail_registry.py
index 6bd109f0f95..3053664ef27 100644
--- a/tests/test_litellm/proxy/guardrails/test_guardrail_registry.py
+++ b/tests/test_litellm/proxy/guardrails/test_guardrail_registry.py
@@ -558,3 +558,60 @@ def test_reinitialized_judge_guardrail_uses_lazy_router_provider():
finally:
for cb_list, snapshot in zip(lists, snapshots):
cb_list[:] = snapshot
+
+
+class TestScanOnlyToolResultsInitRefusal:
+ """A guardrail whose role filtering never scans tool results must be rejected at
+ initialization when configured with scan_only_tool_results, instead of booting a
+ proxy that silently scans nothing on every request."""
+
+ def _initialize(self, name: str, params: dict):
+ lists = _all_callback_lists()
+ snapshots = [list(cb_list) for cb_list in lists]
+ try:
+ return InMemoryGuardrailHandler().initialize_guardrail(
+ guardrail={"guardrail_name": name, "litellm_params": params},
+ )
+ finally:
+ for cb_list, snapshot in zip(lists, snapshots):
+ cb_list[:] = snapshot
+
+ def test_panw_prisma_airs_with_scan_only_tool_results_is_rejected(self):
+ with pytest.raises(ValueError, match="never scans tool results"):
+ self._initialize(
+ "panw-scan-only-combo",
+ {
+ "guardrail": "panw_prisma_airs",
+ "mode": "pre_call",
+ "api_key": "test-key",
+ "profile_name": "test-profile",
+ "scan_only_tool_results": True,
+ },
+ )
+
+ def test_bedrock_latest_role_with_scan_only_tool_results_is_rejected(self):
+ with pytest.raises(ValueError, match="never scans tool results"):
+ self._initialize(
+ "bedrock-latest-role-scan-only-combo",
+ {
+ "guardrail": "bedrock",
+ "mode": "pre_call",
+ "guardrailIdentifier": "gr-1",
+ "guardrailVersion": "1",
+ "experimental_use_latest_role_message_only": True,
+ "scan_only_tool_results": True,
+ },
+ )
+
+ def test_bedrock_without_latest_role_accepts_scan_only_tool_results(self):
+ result = self._initialize(
+ "bedrock-scan-only-ok",
+ {
+ "guardrail": "bedrock",
+ "mode": "pre_call",
+ "guardrailIdentifier": "gr-1",
+ "guardrailVersion": "1",
+ "scan_only_tool_results": True,
+ },
+ )
+ assert result is not None