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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(guardrails): scan function-role results and dedupe returned tools
mateo-berri28ff7f3f0b68
diff --git a/basedpyright-code-budget.json b/basedpyright-code-budget.jsonindex 8a5c78c1f6c..d98e6c6c911 100644--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@ -9,10 +9,10 @@"limit": 329},"reportAttributeAccessIssue": {- "limit": 516+ "limit": 514},"reportCallIssue": {- "limit": 123+ "limit": 117},"reportConstantRedefinition": {"limit": 40@@ -24,7 +24,7 @@"limit": 19},"reportExplicitAny": {- "limit": 9226+ "limit": 9225},"reportFunctionMemberAccess": {"limit": 7@@ -99,25 +99,25 @@"limit": 0},"reportUnknownArgumentType": {- "limit": 45242+ "limit": 45145},"reportUnknownLambdaType": {"limit": 113},"reportUnknownMemberType": {- "limit": 40339+ "limit": 39881},"reportUnknownParameterType": {- "limit": 20293+ "limit": 20258},"reportUnknownVariableType": {- "limit": 31796+ "limit": 31429},"reportUnnecessaryCast": {"limit": 122},"reportUnnecessaryComparison": {- "limit": 702+ "limit": 701},"reportUnnecessaryContains": {"limit": 5@@ -126,7 +126,7 @@"limit": 864},"reportUntypedBaseClass": {- "limit": 72+ "limit": 0},"reportUntypedFunctionDecorator": {"limit": 33diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.pyindex 7c8c9aeb248..2e91e082bd4 100644--- a/litellm/integrations/custom_guardrail.py+++ b/litellm/integrations/custom_guardrail.py@@ -724,6 +724,19 @@ class CustomGuardrail(CustomLogger):"""return True+ def structured_messages_cover_full_request(self) -> bool:+ """Whether returned ``structured_messages`` span the whole request.++ Translation handlers hand guardrails only the in-scope subset of the+ conversation and merge a returned ``structured_messages`` list back+ into the full request. A guardrail that already rebuilds the complete+ conversation itself (like CrowdStrike AIDR with its skip filters+ active) overrides this to return True so the handler installs the+ returned list as-is instead of merging it a second time, which would+ duplicate the out-of-scope messages.+ """+ return False+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.pyindex aef01765e6e..88db9fae912 100644--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py@@ -415,7 +415,9 @@ class AnthropicMessagesHandler(BaseTranslation):):self._write_back_structured_messages(data,- merge_guardrailed_scoped_messages(+ guardrailed_structured_messages+ if guardrail_to_apply.structured_messages_cover_full_request()+ else merge_guardrailed_scoped_messages(full_messages=full_structured_messages,scoped_indices=scoped_message_indices,guardrailed_scoped=guardrailed_structured_messages,diff --git a/litellm/llms/base_llm/guardrail_translation/utils.py b/litellm/llms/base_llm/guardrail_translation/utils.pyindex bdfe15ca9a6..f1ddf21cd3c 100644--- a/litellm/llms/base_llm/guardrail_translation/utils.py+++ b/litellm/llms/base_llm/guardrail_translation/utils.py@@ -145,7 +145,7 @@ def role_out_of_guardrail_scope(return Trueif skip_tool_message and role == "tool":return True- return scan_only_tool_results and role != "tool"+ return scan_only_tool_results and role not in ("tool", "function")def scoped_structured_message_indices(@@ -198,11 +198,16 @@ def merge_returned_tools_into_request_tools(user-defined function) nor be discarded (it may carry a tool the guardrailsynthesized 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.+ already taken by a request tool or an earlier returned tool."""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)+ additions: Final = tuple(+ tool+ for index, tool in enumerate(returned_tools)+ if (name := tool_name(tool)) not in taken_names+ and (name is None or all(tool_name(earlier) != name for earlier in returned_tools[:index]))+ )return [*originals, *additions]diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.pyindex 4f0f69866ad..e411dc497fc 100644--- a/litellm/llms/openai/chat/guardrail_translation/handler.py+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py@@ -161,10 +161,14 @@ class OpenAIChatCompletionsHandler(BaseTranslation):guardrailed_structured_messages is not Noneand guardrailed_structured_messages is not original_structured_messages):- data["messages"] = merge_guardrailed_scoped_messages(- full_messages=structured_messages or [],- scoped_indices=scoped_message_indices,- guardrailed_scoped=guardrailed_structured_messages,+ data["messages"] = (+ guardrailed_structured_messages+ if guardrail_to_apply.structured_messages_cover_full_request()+ else merge_guardrailed_scoped_messages(+ full_messages=structured_messages or [],+ scoped_indices=scoped_message_indices,+ guardrailed_scoped=guardrailed_structured_messages,+ ))else:# Step 3: Map guardrail responses back to original message structurediff --git a/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.py b/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.pyindex 15ddd5e3458..b1bf9159607 100644--- a/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.py+++ b/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.py@@ -362,6 +362,10 @@ class CrowdStrikeAIDRHandler(CustomGuardrail):tail: Final = guard_output.messages[-num_assistant_messages:] if num_assistant_messages > 0 else []return [_extract_text_from_message(msg) for msg in tail]+ @override+ def structured_messages_cover_full_request(self) -> bool:+ return effective_skip_system_message_for_guardrail(self) or effective_skip_tool_message_for_guardrail(self)+def _writeback_messages(self,structured_messages: list[AllMessageValues],diff --git a/ruff-strict-budget.json b/ruff-strict-budget.jsonindex ea20ac97e07..65c98f6aab3 100644--- a/ruff-strict-budget.json+++ b/ruff-strict-budget.json@@ -42,7 +42,7 @@"limit": 81},"B010": {- "limit": 192+ "limit": 190},"B018": {"limit": 2diff --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.pyindex deabee12497..2e75f29b1c5 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@@ -1307,6 +1307,38 @@ class ToolNameCollidingGuardrail(CustomGuardrail):return inputs+class DuplicateToolReturningGuardrail(CustomGuardrail):+ """Returns the same synthesized tool name twice, second copy with a different schema."""++ def __init__(self):+ super().__init__(guardrail_name="duplicate-tool-returning")++ 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": "injected_retrieve",+ "parameters": {"type": "object", "properties": {"first": {"type": "string"}}},+ },+ },+ {+ "type": "function",+ "function": {+ "name": "injected_retrieve",+ "parameters": {"type": "object", "properties": {"second": {"type": "string"}}},+ },+ },+ ]+ return inputs++class TestScanOnlyToolResults:def _bedrock_guardrail(self):from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import BedrockGuardrail@@ -1351,6 +1383,28 @@ class TestScanOnlyToolResults:scanned = [m["content"] for m in mock_api.call_args.kwargs["messages"]]assert scanned == ["TOOL-RESULT-scanned"]+ @pytest.mark.asyncio+ async def test_legacy_function_role_results_are_scanned(self):+ from unittest.mock import AsyncMock, patch++ handler = OpenAIChatCompletionsHandler()+ guardrail = self._bedrock_guardrail()+ data = {+ "messages": [+ {"role": "user", "content": "USER-PROMPT-not-scanned"},+ {"role": "function", "name": "read_file", "content": "FUNCTION-RESULT-scanned"},+ {"role": "tool", "tool_call_id": "call_1", "content": "TOOL-RESULT-scanned"},+ ]+ }+ with patch.object(guardrail, "make_bedrock_api_request", new_callable=AsyncMock) as mock_api:+ mock_api.return_value = {"action": "NONE", "output": [], "outputs": []}+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)+ assert mock_api.call_count == 1+ scanned = [m["content"] for m in mock_api.call_args.kwargs["messages"]]+ assert scanned == ["FUNCTION-RESULT-scanned", "TOOL-RESULT-scanned"], (+ "a tool result sent with the legacy function role must not bypass the scoped scan"+ )+@pytest.mark.parametrize("flag_value", [None, "false", 0, object()])@pytest.mark.asyncioasync def test_scope_narrows_only_when_the_flag_is_actually_true(self, flag_value):@@ -1456,6 +1510,30 @@ class TestScanOnlyToolResults:"a returned tool reusing a request tool's name must not replace the request's schema")+ @pytest.mark.asyncio+ async def test_duplicate_returned_tool_names_keep_only_the_first(self):+ handler = OpenAIChatCompletionsHandler()+ guardrail = DuplicateToolReturningGuardrail()+ 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"], (+ "two returned tools sharing a name must not both be forwarded to the provider"+ )+ assert data["tools"][1]["function"]["parameters"]["properties"] == {"first": {"type": "string"}}+@pytest.mark.asyncioasync def test_structured_write_back_keeps_out_of_scope_messages(self):handler = OpenAIChatCompletionsHandler()diff --git a/type-discipline-budget.json b/type-discipline-budget.jsonindex 37964c27657..8064e63f1aa 100644--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@ -1,6 +1,6 @@{"LIT001": {- "limit": 23337+ "limit": 23332},"LIT002": {"limit": 27213@@ -15,7 +15,7 @@"limit": 0},"LIT006": {- "limit": 1092+ "limit": 1091},"LIT007": {"limit": 0@@ -27,7 +27,7 @@"limit": 0},"LIT010": {- "limit": 16796+ "limit": 16792},"LIT011": {"limit": 5602