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(unified_guardrail.py): support during_call event type for unified guardrails (#17514)

Krish Dholakia51cc102c30d8
diff --git a/cookbook/mock_guardrail_server/mock_bedrock_guardrail_server.py b/cookbook/mock_guardrail_server/mock_bedrock_guardrail_server.py
index fd53ece6604..b5c1b3fa0c8 100644
--- a/cookbook/mock_guardrail_server/mock_bedrock_guardrail_server.py
+++ b/cookbook/mock_guardrail_server/mock_bedrock_guardrail_server.py
@@ -361,41 +361,6 @@ async def health():
return {"status": "healthy"}
- "/guardrail/{guardrailIdentifier}/version/{guardrailVersion}/apply",
- response_model=BedrockGuardrailResponse,
-)
-async def apply_guardrail(
- guardrailIdentifier: str,
- guardrailVersion: str,
- request: BedrockRequest,
- token: str = Depends(verify_bearer_token),
-) -> BedrockGuardrailResponse:
- """
- Apply guardrail to input or output content.
-
- This endpoint mimics the AWS Bedrock ApplyGuardrail API.
-
- Args:
- guardrailIdentifier: The guardrail ID
- guardrailVersion: The guardrail version
- request: The guardrail request containing content to analyze
- token: Bearer token (verified by dependency)
-
- Returns:
- BedrockGuardrailResponse with analysis results
- """
- # Process the request
- response, output_texts = process_guardrail_request(request)
-
- # Log the request (optional, for debugging)
- print(f"Guardrail applied: {guardrailIdentifier} v{guardrailVersion}")
- print(f"Source: {request.source}")
- print(f"Action: {response.action}")
-
- return response
-
-
"""
LiteLLM exposes a basic guardrail API with the text extracted from the request and sent to the guardrail API, as well as the received request body for any further processing.
@@ -427,6 +392,7 @@ class LitellmBasicGuardrailRequest(BaseModel):
texts: List[str]
images: Optional[List[str]] = None
tools: Optional[List[dict]] = None
+ tool_calls: Optional[List[dict]] = None
request_data: Dict[str, Any] = Field(default_factory=dict)
additional_provider_specific_params: Dict[str, Any] = Field(default_factory=dict)
input_type: Literal["request", "response"]
diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py
index 2045836387f..c4233140b31 100644
--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py
+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py
@@ -367,49 +367,14 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
reasoning_content = None # flush reasoning content
index += 1
elif isinstance(item, ResponseFunctionToolCall):
-
- provider_specific_fields = getattr(
- item, "provider_specific_fields", None
+ from litellm.responses.litellm_completion_transformation.transformation import (
+ LiteLLMCompletionResponsesConfig,
)
- if provider_specific_fields and not isinstance(
- provider_specific_fields, dict
- ):
- provider_specific_fields = (
- dict(provider_specific_fields)
- if hasattr(provider_specific_fields, "__dict__")
- else {}
- )
- elif hasattr(item, "get") and callable(item.get): # type: ignore
- provider_fields = item.get("provider_specific_fields") # type: ignore
- if provider_fields:
- provider_specific_fields = (
- provider_fields
- if isinstance(provider_fields, dict)
- else (
- dict(provider_fields) # type: ignore
- if hasattr(provider_fields, "__dict__")
- else {}
- )
- )
-
- function_dict: Dict[str, Any] = {
- "name": item.name,
- "arguments": item.arguments,
- }
-
- if provider_specific_fields:
- function_dict["provider_specific_fields"] = provider_specific_fields
- tool_call_dict: Dict[str, Any] = {
- "id": item.call_id,
- "function": function_dict,
- "type": "function",
- }
-
- if provider_specific_fields:
- tool_call_dict["provider_specific_fields"] = (
- provider_specific_fields
- )
+ tool_call_dict = LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call(
+ tool_call_item=item,
+ index=index,
+ )
msg = Message(
content=None,
@@ -718,17 +683,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
}
}
elif format_type == "json_object":
- return {
- "format": {
- "type": "json_object"
- }
- }
+ return {"format": {"type": "json_object"}}
elif format_type == "text":
- return {
- "format": {
- "type": "text"
- }
- }
+ return {"format": {"type": "text"}}
return None
diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
index 5969a76ed90..d8bede65f09 100644
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@ -16,13 +16,17 @@ import json
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, cast
from litellm._logging import verbose_proxy_logger
+from litellm.llms.anthropic.chat.transformation import AnthropicConfig
from litellm.llms.anthropic.experimental_pass_through.adapters.transformation import (
LiteLLMAnthropicMessagesAdapter,
)
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
from litellm.types.guardrails import GenericGuardrailAPIInputs
from litellm.types.llms.anthropic import AllAnthropicToolsValues
-from litellm.types.llms.openai import ChatCompletionToolParam
+from litellm.types.llms.openai import (
+ ChatCompletionToolCallChunk,
+ ChatCompletionToolParam,
+)
if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
@@ -209,7 +213,7 @@ class AnthropicMessagesHandler(BaseTranslation):
user_api_key_dict: Optional[Any] = None,
) -> Any:
"""
- Process output response by applying guardrails to text content.
+ Process output response by applying guardrails to text content and tool calls.
Args:
response: Anthropic MessagesResponse object
@@ -221,17 +225,15 @@ class AnthropicMessagesHandler(BaseTranslation):
Modified response with guardrail applied to content
Response Format Support:
- - List content: response.content = [{"type": "text", "text": "text here"}, ...]
+ - List content: response.content = [
+ {"type": "text", "text": "text here"},
+ {"type": "tool_use", "id": "...", "name": "...", "input": {...}},
+ ...
+ ]
"""
- # Step 0: Check if response has any text content to process
- if not self._has_text_content(response):
- verbose_proxy_logger.warning(
- "Anthropic Messages: No text content in response, skipping guardrail"
- )
- return response
-
texts_to_check: List[str] = []
images_to_check: List[str] = []
+ tool_calls_to_check: List[ChatCompletionToolCallChunk] = []
task_mappings: List[Tuple[int, Optional[int]]] = []
# Track (content_index, None) for each text
@@ -239,10 +241,13 @@ class AnthropicMessagesHandler(BaseTranslation):
if not response_content:
return response
- # Step 1: Extract all text content from response
+ # Step 1: Extract all text content and tool calls from response
for content_idx, content_block in enumerate(response_content):
- # Check if this is a text block by checking the 'type' field
- if isinstance(content_block, dict) and content_block.get("type") == "text":
+ # Check if this is a text or tool_use block by checking the 'type' field
+ if isinstance(content_block, dict) and content_block.get("type") in [
+ "text",
+ "tool_use",
+ ]:
# Cast to dict to handle the union type properly
self._extract_output_text_and_images(
content_block=cast(Dict[str, Any], content_block),
@@ -250,10 +255,11 @@ class AnthropicMessagesHandler(BaseTranslation):
texts_to_check=texts_to_check,
images_to_check=images_to_check,
task_mappings=task_mappings,
+ tool_calls_to_check=tool_calls_to_check,
)
# Step 2: Apply guardrail to all texts in batch
- if texts_to_check:
+ if texts_to_check or tool_calls_to_check:
# Create a request_data dict with response info and user API key metadata
request_data: dict = {"response": response}
@@ -267,6 +273,9 @@ class AnthropicMessagesHandler(BaseTranslation):
inputs = GenericGuardrailAPIInputs(texts=texts_to_check)
if images_to_check:
inputs["images"] = images_to_check
+ if tool_calls_to_check:
+ inputs["tool_calls"] = tool_calls_to_check
+
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
inputs=inputs,
request_data=request_data,
@@ -419,17 +428,32 @@ class AnthropicMessagesHandler(BaseTranslation):
texts_to_check: List[str],
images_to_check: List[str],
task_mappings: List[Tuple[int, Optional[int]]],
+ tool_calls_to_check: Optional[List[ChatCompletionToolCallChunk]] = None,
) -> None:
"""
- Extract text content and images from a response content block.
+ Extract text content, images, and tool calls from a response content block.
- Override this method to customize text/image extraction logic.
+ Override this method to customize text/image/tool extraction logic.
"""
- content_text = content_block.get("text")
- if content_text and isinstance(content_text, str):
- # Simple string content
- texts_to_check.append(content_text)
- task_mappings.append((content_idx, None))
+ content_type = content_block.get("type")
+
+ # Extract text content
+ if content_type == "text":
+ content_text = content_block.get("text")
+ if content_text and isinstance(content_text, str):
+ # Simple string content
+ texts_to_check.append(content_text)
+ task_mappings.append((content_idx, None))
+
+ # Extract tool calls
+ elif content_type == "tool_use":
+ tool_call = AnthropicConfig.convert_tool_use_to_openai_format(
+ anthropic_tool_content=content_block,
+ index=content_idx,
+ )
+ if tool_calls_to_check is None:
+ tool_calls_to_check = []
+ tool_calls_to_check.append(tool_call)
async def _apply_guardrail_responses_to_output(
self,
diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.py
index bdc986ae27f..b477dbd457e 100644
--- a/litellm/llms/anthropic/chat/transformation.py
+++ b/litellm/llms/anthropic/chat/transformation.py
@@ -54,10 +54,7 @@ from litellm.types.utils import (
CompletionTokensDetailsWrapper,
)
from litellm.types.utils import Message as LitellmMessage
-from litellm.types.utils import (
- PromptTokensDetailsWrapper,
- ServerToolUse,
-)
+from litellm.types.utils import PromptTokensDetailsWrapper, ServerToolUse
from litellm.utils import (
ModelResponse,
Usage,
@@ -119,6 +116,36 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
def get_config(cls):
return super().get_config()
+ @staticmethod
+ def convert_tool_use_to_openai_format(
+ anthropic_tool_content: Dict[str, Any],
+ index: int,
+ ) -> ChatCompletionToolCallChunk:
+ """
+ Convert Anthropic tool_use format to OpenAI ChatCompletionToolCallChunk format.
+
+ Args:
+ anthropic_tool_content: Anthropic tool_use content block with format:
+ {"type": "tool_use", "id": "...", "name": "...", "input": {...}}
+ index: The index of this tool call
+
+ Returns:
+ ChatCompletionToolCallChunk in OpenAI format
+ """
+ tool_call = ChatCompletionToolCallChunk(
+ id=anthropic_tool_content["id"],
+ type="function",
+ function=ChatCompletionToolCallFunctionChunk(
+ name=anthropic_tool_content["name"],
+ arguments=json.dumps(anthropic_tool_content["input"]),
+ ),
+ index=index,
+ )
+ # Include caller information if present (for programmatic tool calling)
+ if "caller" in anthropic_tool_content:
+ tool_call["caller"] = cast(Dict[str, Any], anthropic_tool_content["caller"]) # type: ignore[typeddict-item]
+ return tool_call
+
def _is_claude_opus_4_5(self, model: str) -> bool:
"""Check if the model is Claude Opus 4.5."""
return "opus-4-5" in model.lower() or "opus_4_5" in model.lower()
@@ -279,7 +306,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
elif tool["type"] == "tool_search_tool_regex_20251119":
# Tool search tool using regex
from litellm.types.llms.anthropic import AnthropicToolSearchToolRegex
-
+
tool_name_obj = tool.get("name", "tool_search_tool_regex")
if not isinstance(tool_name_obj, str):
raise ValueError("Tool search tool must have a valid name")
@@ -291,7 +318,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
elif tool["type"] == "tool_search_tool_bm25_20251119":
# Tool search tool using BM25
from litellm.types.llms.anthropic import AnthropicToolSearchToolBM25
-
+
tool_name_obj = tool.get("name", "tool_search_tool_bm25")
if not isinstance(tool_name_obj, str):
raise ValueError("Tool search tool must have a valid name")
@@ -309,7 +336,10 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
if returned_tool is not None:
# Only set cache_control on tools that support it (not tool search tools)
tool_type = returned_tool.get("type", "")
- if tool_type not in ("tool_search_tool_regex_20251119", "tool_search_tool_bm25_20251119"):
+ if tool_type not in (
+ "tool_search_tool_regex_20251119",
+ "tool_search_tool_bm25_20251119",
+ ):
if _cache_control is not None:
returned_tool["cache_control"] = _cache_control # type: ignore[typeddict-item]
elif _cache_control_function is not None and isinstance(
@@ -318,14 +348,19 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
returned_tool["cache_control"] = ChatCompletionCachedContent( # type: ignore[typeddict-item]
**_cache_control_function # type: ignore
)
-
+
## check if defer_loading is set in the tool
_defer_loading = tool.get("defer_loading", None)
_defer_loading_function = tool.get("function", {}).get("defer_loading", None)
if returned_tool is not None:
# Only set defer_loading on tools that support it (not tool search tools or computer tools)
tool_type = returned_tool.get("type", "")
- if tool_type not in ("tool_search_tool_regex_20251119", "tool_search_tool_bm25_20251119", "computer_20241022", "computer_20250124"):
+ if tool_type not in (
+ "tool_search_tool_regex_20251119",
+ "tool_search_tool_bm25_20251119",
+ "computer_20241022",
+ "computer_20250124",
+ ):
if _defer_loading is not None:
if not isinstance(_defer_loading, bool):
raise ValueError("defer_loading must be a boolean")
@@ -334,14 +369,21 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
if not isinstance(_defer_loading_function, bool):
raise ValueError("defer_loading must be a boolean")
returned_tool["defer_loading"] = _defer_loading_function # type: ignore[typeddict-item]
-
+
## check if allowed_callers is set in the tool
_allowed_callers = tool.get("allowed_callers", None)
- _allowed_callers_function = tool.get("function", {}).get("allowed_callers", None)
+ _allowed_callers_function = tool.get("function", {}).get(
+ "allowed_callers", None
+ )
if returned_tool is not None:
# Only set allowed_callers on tools that support it (not tool search tools or computer tools)
tool_type = returned_tool.get("type", "")
- if tool_type not in ("tool_search_tool_regex_20251119", "tool_search_tool_bm25_20251119", "computer_20241022", "computer_20250124"):
+ if tool_type not in (
+ "tool_search_tool_regex_20251119",
+ "tool_search_tool_bm25_20251119",
+ "computer_20241022",
+ "computer_20250124",
+ ):
if _allowed_callers is not None:
if not isinstance(_allowed_callers, list) or not all(
isinstance(item, str) for item in _allowed_callers
@@ -354,7 +396,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
):
raise ValueError("allowed_callers must be a list of strings")
returned_tool["allowed_callers"] = _allowed_callers_function # type: ignore[typeddict-item]
-
+
## check if input_examples is set in the tool
_input_examples = tool.get("input_examples", None)
_input_examples_function = tool.get("function", {}).get("input_examples", None)
@@ -423,31 +465,32 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
"""Check if tool search tools are present in the tools list."""
if not tools:
return False
-
+
for tool in tools:
tool_type = tool.get("type", "")
- if tool_type in ["tool_search_tool_regex_20251119", "tool_search_tool_bm25_20251119"]:
+ if tool_type in [
+ "tool_search_tool_regex_20251119",
+ "tool_search_tool_bm25_20251119",
+ ]:
return True
return False
- def _separate_deferred_tools(
- self, tools: List
- ) -> Tuple[List, List]:
+ def _separate_deferred_tools(self, tools: List) -> Tuple[List, List]:
"""
Separate tools into deferred and non-deferred lists.
-
+
Returns:
Tuple of (non_deferred_tools, deferred_tools)
"""
non_deferred = []
deferred = []
-
+
for tool in tools:
if tool.get("defer_loading", False):
deferred.append(tool)
else:
non_deferred.append(tool)
-
+
return non_deferred, deferred
def _expand_tool_references(
@@ -457,28 +500,28 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
) -> List:
"""
Expand tool_reference blocks to full tool definitions.
-
+
When Anthropic's tool search returns results, it includes tool_reference blocks
that reference tools by name. This method expands those references to full
tool definitions from the deferred_tools catalog.
-
+
Args:
content: Response content that may contain tool_reference blocks
deferred_tools: List of deferred tools that can be referenced
-
+
Returns:
Content with tool_reference blocks expanded to full tool definitions
"""
if not deferred_tools:
return content
-
+
# Create a mapping of tool names to tool definitions
tool_map = {}
for tool in deferred_tools:
tool_name = tool.get("name") or tool.get("function", {}).get("name")
if tool_name:
tool_map[tool_name] = tool
-
+
# Expand tool references in content
expanded_content = []
for item in content:
@@ -492,7 +535,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
expanded_content.append(item)
else:
expanded_content.append(item)
-
+
return expanded_content
def _map_stop_sequences(
@@ -995,7 +1038,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
"messages": anthropic_messages,
**optional_params,
}
-
+
## Handle output_config (Anthropic-specific parameter)
if "output_config" in optional_params:
output_config = optional_params.get("output_config")
@@ -1054,34 +1097,20 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
text_content += content["text"]
## TOOL CALLING
elif content["type"] == "tool_use":
- tool_call = ChatCompletionToolCallChunk(
- id=content["id"],
- type="function",
- function=ChatCompletionToolCallFunctionChunk(
- name=content["name"],
- arguments=json.dumps(content["input"]),
- ),
+ tool_call = AnthropicConfig.convert_tool_use_to_openai_format(
+ anthropic_tool_content=content,
index=idx,
)
- # Include caller information if present (for programmatic tool calling)
- if "caller" in content:
- tool_call["caller"] = cast(Dict[str, Any], content["caller"]) # type: ignore[typeddict-item]
tool_calls.append(tool_call)
## SERVER TOOL USE (for tool search)
elif content["type"] == "server_tool_use":
# Server tool use blocks are for tool search - treat as tool calls
- tool_call = ChatCompletionToolCallChunk(
- id=content["id"],
- type="function",
- function=ChatCompletionToolCallFunctionChunk(
- name=content["name"],
- arguments=json.dumps(content.get("input", {})),
- ),
+ # Note: using .get("input", {}) for server_tool_use as input may not be present
+ content_with_input = {**content, "input": content.get("input", {})}
+ tool_call = AnthropicConfig.convert_tool_use_to_openai_format(
+ anthropic_tool_content=content_with_input,
index=idx,
)
- # Include caller information if present (for programmatic tool calling)
- if "caller" in content:
- tool_call["caller"] = cast(Dict[str, Any], content["caller"]) # type: ignore[typeddict-item]
tool_calls.append(tool_call)
## TOOL SEARCH TOOL RESULT (skip - this is metadata about tool discovery)
elif content["type"] == "tool_search_tool_result":
@@ -1122,7 +1151,10 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
return text_content, citations, thinking_blocks, reasoning_content, tool_calls
def calculate_usage(
- self, usage_object: dict, reasoning_content: Optional[str], completion_response: Optional[dict] = None
+ self,
+ usage_object: dict,
+ reasoning_content: Optional[str],
+ completion_response: Optional[dict] = None,
) -> Usage:
# NOTE: Sometimes the usage object has None set explicitly for token counts, meaning .get() & key access returns None, and we need to account for this
prompt_tokens = usage_object.get("input_tokens", 0) or 0
@@ -1160,7 +1192,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
tool_search_requests = cast(
int, _usage["server_tool_use"]["tool_search_requests"]
)
-
+
# Count tool_search_requests from content blocks if not in usage
# Anthropic doesn't always include tool_search_requests in the usage object
if tool_search_requests is None and completion_response is not None:
diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.py
index 76aa6f730c2..463b50beb5c 100644
--- a/litellm/llms/openai/chat/guardrail_translation/handler.py
+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py
@@ -89,7 +89,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):
)
guardrailed_texts = guardrailed_inputs.get("texts", [])
- guardrailed_tool_calls = guardrailed_inputs.get("tools", [])
+ guardrailed_tool_calls = guardrailed_inputs.get("tool_calls", [])
# Step 3: Map guardrail responses back to original message structure
if guardrailed_texts and texts_to_check:
@@ -155,7 +155,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):
images_to_check.append(url)
# Extract tool calls (typically in assistant messages)
- tool_calls = message.get("tools", None)
+ tool_calls = message.get("tool_calls", None)
if tool_calls is not None and isinstance(tool_calls, list):
for tool_call_idx, tool_call in enumerate(tool_calls):
if isinstance(tool_call, dict):
@@ -261,7 +261,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):
# Step 1: Extract all text content, images, and tool calls from response choices
for choice_idx, choice in enumerate(response.choices):
- self._extract_output_text_and_images(
+ self._extract_output_text_images_and_tool_calls(
choice=choice,
choice_idx=choice_idx,
texts_to_check=texts_to_check,
@@ -478,7 +478,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):
return True
return False
- def _extract_output_text_and_images(
+ def _extract_output_text_images_and_tool_calls(
self,
choice: Union[Choices, StreamingChoices],
choice_idx: int,
diff --git a/litellm/llms/openai/responses/guardrail_translation/handler.py b/litellm/llms/openai/responses/guardrail_translation/handler.py
index fb8b16817b2..2ab37f061fd 100644
--- a/litellm/llms/openai/responses/guardrail_translation/handler.py
+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py
@@ -38,8 +38,15 @@ from litellm.responses.litellm_completion_transformation.transformation import (
LiteLLMCompletionResponsesConfig,
)
from litellm.types.guardrails import GenericGuardrailAPIInputs
-from litellm.types.llms.openai import ChatCompletionToolParam
-from litellm.types.responses.main import GenericResponseOutputItem, OutputText
+from litellm.types.llms.openai import (
+ ChatCompletionToolCallChunk,
+ ChatCompletionToolParam,
+)
+from litellm.types.responses.main import (
+ GenericResponseOutputItem,
+ OutputFunctionToolCall,
+ OutputText,
+)
if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
@@ -251,7 +258,7 @@ class OpenAIResponsesHandler(BaseTranslation):
user_api_key_dict: Optional[Any] = None,
) -> Any:
"""
- Process output response by applying guardrails to text content.
+ Process output response by applying guardrails to text content and tool calls.
Args:
response: LiteLLM ResponsesAPIResponse object
@@ -264,22 +271,19 @@ class OpenAIResponsesHandler(BaseTranslation):
Response Format Support:
- response.output is a list of output items
- - Each output item has a content list with OutputText objects
+ - Each output item can be:
+ * GenericResponseOutputItem with a content list of OutputText objects
+ * OutputFunctionToolCall with tool call data
- Each OutputText object has a text field
"""
- # Step 0: Check if response has any text content to process
- if not self._has_text_content(response):
- verbose_proxy_logger.warning(
- "OpenAI Responses API: No text content in response, skipping guardrail"
- )
- return response
texts_to_check: List[str] = []
images_to_check: List[str] = []
+ tool_calls_to_check: List[ChatCompletionToolCallChunk] = []
task_mappings: List[Tuple[int, int]] = []
# Track (output_item_index, content_index) for each text
- # Step 1: Extract all text content from response output
+ # Step 1: Extract all text content and tool calls from response output
for output_idx, output_item in enumerate(response.output):
self._extract_output_text_and_images(
output_item=output_item,
@@ -287,10 +291,11 @@ class OpenAIResponsesHandler(BaseTranslation):
texts_to_check=texts_to_check,
images_to_check=images_to_check,
task_mappings=task_mappings,
+ tool_calls_to_check=tool_calls_to_check,
)
# Step 2: Apply guardrail to all texts in batch
- if texts_to_check:
+ if texts_to_check or tool_calls_to_check:
# Create a request_data dict with response info and user API key metadata
request_data: dict = {"response": response}
@@ -304,6 +309,9 @@ class OpenAIResponsesHandler(BaseTranslation):
inputs = GenericGuardrailAPIInputs(texts=texts_to_check)
if images_to_check:
inputs["images"] = images_to_check
+ if tool_calls_to_check:
+ inputs["tool_calls"] = tool_calls_to_check
+
guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
inputs=inputs,
request_data=request_data,
@@ -398,12 +406,57 @@ class OpenAIResponsesHandler(BaseTranslation):
texts_to_check: List[str],
images_to_check: List[str],
task_mappings: List[Tuple[int, int]],
+ tool_calls_to_check: Optional[List[ChatCompletionToolCallChunk]] = None,
) -> None:
"""
- Extract text content and images from a response output item.
+ Extract text content, images, and tool calls from a response output item.
- Override this method to customize text/image extraction logic.
+ Override this method to customize text/image/tool extraction logic.
"""
+ # Check if this is a tool call (OutputFunctionToolCall)
+ if isinstance(output_item, OutputFunctionToolCall):
+ if tool_calls_to_check is not None:
+ tool_call_dict = LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call(
+ tool_call_item=output_item,
+ index=output_idx,
+ )
+ tool_calls_to_check.append(
+ cast(ChatCompletionToolCallChunk, tool_call_dict)
+ )
+ return
+ elif (
+ isinstance(output_item, BaseModel)
+ and hasattr(output_item, "type")
+ and getattr(output_item, "type") == "function_call"
+ ):
+ if tool_calls_to_check is not None:
+ tool_call_dict = LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call(
+ tool_call_item=output_item,
+ index=output_idx,
+ )
+ tool_calls_to_check.append(
+ cast(ChatCompletionToolCallChunk, tool_call_dict)
+ )
+ return
+ elif (
+ isinstance(output_item, dict) and output_item.get("type") == "function_call"
+ ):
+ # Handle dict representation of tool call
+ if tool_calls_to_check is not None:
+ # Convert dict to OutputFunctionToolCall for processing
+ try:
+ tool_call_obj = OutputFunctionToolCall(**output_item)
+ tool_call_dict = LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call(
+ tool_call_item=tool_call_obj,
+ index=output_idx,
+ )
+ tool_calls_to_check.append(
+ cast(ChatCompletionToolCallChunk, tool_call_dict)
+ )
+ except Exception:
+ pass
+ return
+
# Handle both GenericResponseOutputItem and dict
content: Optional[Union[List[OutputText], List[dict]]] = None
if isinstance(output_item, BaseModel):
diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yaml
index f1916e99ff9..f763615c67b 100644
--- a/litellm/proxy/_new_secret_config.yaml
+++ b/litellm/proxy/_new_secret_config.yaml
@@ -15,7 +15,7 @@ guardrails:
- guardrail_name: generic-guardrail
litellm_params:
guardrail: generic_guardrail_api
- mode: ["pre_call", "post_call", "during_call"]
+ mode: ["post_call"]
headers:
Authorization: Bearer mock-bedrock-token-12345
api_base: http://localhost:8080
diff --git a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py
index 55f1fbc8c86..93cbe1c0bba 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py
@@ -175,6 +175,7 @@ class GenericGuardrailAPI(CustomGuardrail):
texts = inputs.get("texts", [])
images = inputs.get("images")
tools = inputs.get("tools")
+ tool_calls = inputs.get("tool_calls")
# Use provided request_data or create an empty dict
if request_data is None:
@@ -201,6 +202,7 @@ class GenericGuardrailAPI(CustomGuardrail):
request_data=user_metadata,
images=images,
tools=tools,
+ tool_calls=tool_calls,
additional_provider_specific_params=additional_params,
input_type=input_type,
)
@@ -214,7 +216,7 @@ class GenericGuardrailAPI(CustomGuardrail):
# Make the API request
response = await self.async_handler.post(
url=self.api_base,
- json=guardrail_request.to_dict(),
+ json=guardrail_request.model_dump(),
headers=headers,
)
diff --git a/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py b/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py
index c16cb89b785..2c120124a27 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py
@@ -96,6 +96,51 @@ class UnifiedLLMGuardrails(CustomLogger):
)
return data
+ async def async_moderation_hook(
+ self, data: dict, user_api_key_dict: UserAPIKeyAuth, call_type: CallTypesLiteral
+ ) -> Any:
+ """
+ Runs in parallel to LLM API call
+ Runs on only Input
+
+ This can NOT modify the input, only used to reject or accept a call before going to LLM API
+ """
+ global endpoint_guardrail_translation_mappings
+
+ verbose_proxy_logger.debug("Running UnifiedLLMGuardrails moderation hook")
+
+ guardrail_to_apply: CustomGuardrail = data.pop("guardrail_to_apply", None)
+ if guardrail_to_apply is None:
+ return data
+
+ event_type: GuardrailEventHooks = GuardrailEventHooks.during_call
+ if (
+ guardrail_to_apply.should_run_guardrail(data=data, event_type=event_type)
+ is not True
+ ):
+ verbose_proxy_logger.debug(
+ "UnifiedLLMGuardrails: Pre-call scanning disabled for %s",
+ guardrail_to_apply.guardrail_name,
+ )
+ return data
+
+ if endpoint_guardrail_translation_mappings is None:
+ endpoint_guardrail_translation_mappings = (
+ load_guardrail_translation_mappings()
+ )
+ if CallTypes(call_type) not in endpoint_guardrail_translation_mappings:
+ return data
+
+ endpoint_translation = endpoint_guardrail_translation_mappings[
+ CallTypes(call_type)
+ ]()
+
+ return await endpoint_translation.process_input_messages(
+ data=data,
+ guardrail_to_apply=guardrail_to_apply,
+ litellm_logging_obj=data.get("litellm_logging_obj"),
+ )
+
async def async_post_call_success_hook(
self,
data: dict,
@@ -193,7 +238,6 @@ class UnifiedLLMGuardrails(CustomLogger):
"guardrail_to_apply", None
)
-
# Get sampling rate from guardrail config or optional_params, default to 5
sampling_rate = 5
if guardrail_to_apply is not None:
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index 28a7ef001d5..aca9bd96eb9 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -1031,15 +1031,25 @@ class ProxyLogging:
)
else:
user_api_key_auth_dict = user_api_key_dict
-
# Add task to list for parallel execution
- guardrail_tasks.append(
- callback.async_moderation_hook(
+ if (
+ "apply_guardrail" in type(callback).__dict__
+ and user_api_key_dict is not None
+ ):
+ data["guardrail_to_apply"] = callback
+ guardrail_task = unified_guardrail.async_moderation_hook(
+ user_api_key_dict=user_api_key_dict,
+ data=data,
+ call_type=call_type,
+ )
+ else:
+
+ guardrail_task = callback.async_moderation_hook(
data=data,
user_api_key_dict=user_api_key_auth_dict, # type: ignore
call_type=call_type, # type: ignore
)
- )
+ guardrail_tasks.append(guardrail_task)
# Step 2: Run all guardrail tasks in parallel
if guardrail_tasks:
diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.py
index bd12d0cbb49..0446031d7d6 100644
--- a/litellm/responses/litellm_completion_transformation/transformation.py
+++ b/litellm/responses/litellm_completion_transformation/transformation.py
@@ -107,7 +107,10 @@ class LiteLLMCompletionResponsesConfig:
"""
Transform a Responses API request into a Chat Completion request
"""
- tools, web_search_options = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(
+ (
+ tools,
+ web_search_options,
+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(
responses_api_request.get("tools") or [] # type: ignore
)
@@ -218,9 +221,9 @@ class LiteLLMCompletionResponsesConfig:
_messages = litellm_completion_request.get("messages") or []
session_messages = chat_completion_session.get("messages") or []
litellm_completion_request["messages"] = session_messages + _messages
- litellm_completion_request[
- "litellm_trace_id"
- ] = chat_completion_session.get("litellm_session_id")
+ litellm_completion_request["litellm_trace_id"] = chat_completion_session.get(
+ "litellm_session_id"
+ )
return litellm_completion_request
@staticmethod
@@ -482,19 +485,17 @@ class LiteLLMCompletionResponsesConfig:
return new_item
@staticmethod
- def _transform_input_image_item_to_image_item(item: Dict[str, Any]) -> ChatCompletionImageObject:
+ def _transform_input_image_item_to_image_item(
+ item: Dict[str, Any],
+ ) -> ChatCompletionImageObject:
"""
Transform a Responses API input_image item to a Chat Completion image item
"""
image_url_obj = ChatCompletionImageUrlObject(
- url=item.get("image_url") or "",
- detail=item.get("detail") or "auto"
+ url=item.get("image_url") or "", detail=item.get("detail") or "auto"
)
- return ChatCompletionImageObject(
- type="image_url",
- image_url=image_url_obj
- )
+ return ChatCompletionImageObject(type="image_url", image_url=image_url_obj)
@staticmethod
def _transform_responses_api_content_to_chat_completion_content(
@@ -561,7 +562,10 @@ class LiteLLMCompletionResponsesConfig:
@staticmethod
def transform_responses_api_tools_to_chat_completion_tools(
tools: Optional[List[Union[FunctionToolParam, OpenAIMcpServerTool]]],
- ) -> Tuple[List[Union[ChatCompletionToolParam, OpenAIMcpServerTool]], Optional[OpenAIWebSearchOptions]]:
+ ) -> Tuple[
+ List[Union[ChatCompletionToolParam, OpenAIMcpServerTool]],
+ Optional[OpenAIWebSearchOptions],
+ ]:
"""
Transform a Responses API tools into a Chat Completion tools
"""
@@ -574,9 +578,17 @@ class LiteLLMCompletionResponsesConfig:
for tool in tools:
if tool.get("type") == "mcp":
chat_completion_tools.append(cast(OpenAIMcpServerTool, tool))
- elif tool.get("type") == "web_search_preview" or tool.get("type") == "web_search":
- _search_context_size: Literal["low", "medium", "high"] = cast(Literal["low", "medium", "high"], tool.get("search_context_size"))
- _user_location: Optional[OpenAIWebSearchUserLocation] = cast(Optional[OpenAIWebSearchUserLocation], tool.get("user_location") or None)
+ elif (
+ tool.get("type") == "web_search_preview"
+ or tool.get("type") == "web_search"
+ ):
+ _search_context_size: Literal["low", "medium", "high"] = cast(
+ Literal["low", "medium", "high"], tool.get("search_context_size")
+ )
+ _user_location: Optional[OpenAIWebSearchUserLocation] = cast(
+ Optional[OpenAIWebSearchUserLocation],
+ tool.get("user_location") or None,
+ )
web_search_options = OpenAIWebSearchOptions(
search_context_size=_search_context_size,
user_location=_user_location,
@@ -618,16 +630,30 @@ class LiteLLMCompletionResponsesConfig:
for tool in all_chat_completion_tools:
if tool.type == "function":
function_definition = tool.function
- provider_specific_fields: Optional[Dict[str, Any]] = None
- if hasattr(tool, "provider_specific_fields") and getattr(tool, "provider_specific_fields", None):
+ provider_specific_fields: Optional[Dict] = None
+ if hasattr(tool, "provider_specific_fields") and getattr(
+ tool, "provider_specific_fields", None
+ ):
provider_specific_fields = getattr(tool, "provider_specific_fields")
if not isinstance(provider_specific_fields, dict):
- provider_specific_fields = dict(provider_specific_fields) if hasattr(provider_specific_fields, "__dict__") else {}
- elif hasattr(function_definition, "provider_specific_fields") and getattr(function_definition, "provider_specific_fields", None):
- provider_specific_fields = getattr(function_definition, "provider_specific_fields")
+ provider_specific_fields = (
+ dict(provider_specific_fields) # type: ignore
+ if hasattr(provider_specific_fields, "__dict__")
+ else {}
+ )
+ elif hasattr(
+ function_definition, "provider_specific_fields"
+ ) and getattr(function_definition, "provider_specific_fields", None):
+ provider_specific_fields = getattr(
+ function_definition, "provider_specific_fields"
+ )
if not isinstance(provider_specific_fields, dict):
- provider_specific_fields = dict(provider_specific_fields) if hasattr(provider_specific_fields, "__dict__") else {}
-
+ provider_specific_fields = (
+ dict(provider_specific_fields) # type: ignore
+ if hasattr(provider_specific_fields, "__dict__")
+ else {}
+ )
+
output_tool_call: OutputFunctionToolCall = OutputFunctionToolCall(
name=function_definition.name or "",
arguments=function_definition.get("arguments") or "",
@@ -636,11 +662,11 @@ class LiteLLMCompletionResponsesConfig:
type="function_call", # critical this is "function_call" to work with tools like openai codex
status=function_definition.get("status") or "completed",
)
-
+
# Pass through provider_specific_fields as-is if present
if provider_specific_fields:
setattr(output_tool_call, "provider_specific_fields", provider_specific_fields) # type: ignore
-
+
responses_tools.append(output_tool_call)
return responses_tools
@@ -672,6 +698,69 @@ class LiteLLMCompletionResponsesConfig:
# Default to completed for unknown finish reasons
return "completed"
+ @staticmethod
+ def convert_response_function_tool_call_to_chat_completion_tool_call(
+ tool_call_item: Any,
+ index: int = 0,
+ ) -> Dict[str, Any]:
+ """
+ Convert ResponseFunctionToolCall to ChatCompletionToolCallChunk format.
+
+ Args:
+ tool_call_item: ResponseFunctionToolCall object or similar with name, arguments, call_id
+ index: The index of this tool call
+
+ Returns:
+ Dictionary in ChatCompletionToolCallChunk format
+ """
+ from litellm.types.llms.openai import (
+ ChatCompletionToolCallChunk,
+ ChatCompletionToolCallFunctionChunk,
+ )
+
+ # Extract provider_specific_fields if present
+ provider_specific_fields = getattr(
+ tool_call_item, "provider_specific_fields", None
+ )
+ if provider_specific_fields and not isinstance(provider_specific_fields, dict):
+ provider_specific_fields = (
+ dict(provider_specific_fields)
+ if hasattr(provider_specific_fields, "__dict__")
+ else {}
+ )
+ elif hasattr(tool_call_item, "get") and callable(tool_call_item.get): # type: ignore
+ provider_fields = tool_call_item.get("provider_specific_fields") # type: ignore
+ if provider_fields:
+ provider_specific_fields = (
+ provider_fields
+ if isinstance(provider_fields, dict)
+ else (
+ dict(provider_fields) # type: ignore
+ if hasattr(provider_fields, "__dict__")
+ else {}
+ )
+ )
+
+ function_dict: Dict[str, Any] = {
+ "name": tool_call_item.name,
+ "arguments": tool_call_item.arguments,
+ }
+
+ if provider_specific_fields:
+ function_dict["provider_specific_fields"] = provider_specific_fields
+
+ tool_call_dict: Dict[str, Any] = {
+ "id": tool_call_item.call_id,
+ "function": function_dict,
+ "type": "function",
+ "index": 0,
+ }
+
+ if provider_specific_fields:
+ tool_call_dict["provider_specific_fields"] = provider_specific_fields
+
+ return tool_call_dict
+
@staticmethod
def transform_chat_completion_response_to_responses_api_response(
request_input: Union[str, ResponseInputParam],
@@ -904,7 +993,6 @@ class LiteLLMCompletionResponsesConfig:
return response_output_annotations
-
@staticmethod
def _transform_chat_completion_usage_to_responses_usage(
chat_completion_response: Union[ModelResponse, Usage],
@@ -974,12 +1062,10 @@ class LiteLLMCompletionResponsesConfig:
"name": format_param.get("name", "response_schema"),
"schema": format_param.get("schema", {}),
"strict": format_param.get("strict", False),
- }
+ },
}
elif format_type == "json_object":
- return {
- "type": "json_object"
- }
+ return {"type": "json_object"}
elif format_type == "text":
return None
diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py
index ea3a6cc4ede..da9b591de28 100644
--- a/litellm/types/guardrails.py
+++ b/litellm/types/guardrails.py
@@ -5,7 +5,11 @@ from typing import Any, Dict, List, Literal, Optional, Union
from pydantic import BaseModel, ConfigDict, Field
from typing_extensions import Required, TypedDict
-from litellm.types.llms.openai import ChatCompletionToolParam
+from litellm.types.llms.openai import (
+ AllMessageValues,
+ ChatCompletionToolCallChunk,
+ ChatCompletionToolParam,
+)
from litellm.types.proxy.guardrails.guardrail_hooks.enkryptai import (
EnkryptAIGuardrailConfigs,
)
@@ -742,6 +746,10 @@ class PatchGuardrailRequest(BaseModel):
class GenericGuardrailAPIInputs(TypedDict, total=False):
- texts: List[str]
- images: List[str]
- tools: List[ChatCompletionToolParam]
+ texts: List[str] # extracted text from the LLM response - for basic text guardrails
+ images: List[str] # extracted images from the LLM response - for image guardrails
+ tools: List[ChatCompletionToolParam] # tools sent to the LLM
+ tool_calls: List[ChatCompletionToolCallChunk] # tool calls sent from the LLM
+ structured_messages: List[
+ AllMessageValues
+ ] # structured messages sent to the LLM - indicates if text is from system or user
diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py b/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py
index 66823270e87..31b61101973 100644
--- a/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py
+++ b/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py
@@ -3,7 +3,10 @@ from typing import Any, Dict, List, Literal, Optional
from pydantic import BaseModel, Field
from typing_extensions import TypedDict
-from litellm.types.llms.openai import ChatCompletionToolParam
+from litellm.types.llms.openai import (
+ ChatCompletionToolCallChunk,
+ ChatCompletionToolParam,
+)
from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel
@@ -42,7 +45,7 @@ class GenericGuardrailAPIConfigModel(
return "Generic Guardrail API"
-class GenericGuardrailAPIRequest:
+class GenericGuardrailAPIRequest(BaseModel):
"""Request model for the Generic Guardrail API"""
input_type: Literal["request", "response"]
@@ -50,40 +53,12 @@ class GenericGuardrailAPIRequest:
litellm_trace_id: Optional[
str
] # the trace id of the LLM call - useful if there are multiple LLM calls for the same conversation
-
- def __init__(
- self,
- texts: List[str],
- request_data: GenericGuardrailAPIMetadata,
- input_type: Literal["request", "response"],
- litellm_call_id: Optional[str],
- litellm_trace_id: Optional[str],
- additional_provider_specific_params: Optional[Dict[str, Any]] = None,
- images: Optional[List[str]] = None,
- tools: Optional[List[ChatCompletionToolParam]] = None,
- ):
- self.texts = texts
- self.request_data = request_data
- self.additional_provider_specific_params = (
- additional_provider_specific_params or {}
- )
- self.images = images
- self.input_type = input_type
- self.litellm_call_id = litellm_call_id
- self.litellm_trace_id = litellm_trace_id
- self.tools = tools
-
- def to_dict(self) -> dict:
- return {
- "texts": self.texts,
- "request_data": self.request_data,
- "images": self.images,
- "tools": self.tools,
- "additional_provider_specific_params": self.additional_provider_specific_params,
- "input_type": self.input_type,
- "litellm_call_id": self.litellm_call_id,
- "litellm_trace_id": self.litellm_trace_id,
- }
+ texts: List[str]
+ request_data: GenericGuardrailAPIMetadata
+ additional_provider_specific_params: Optional[Dict[str, Any]]
+ images: Optional[List[str]]
+ tools: Optional[List[ChatCompletionToolParam]]
+ tool_calls: Optional[List[ChatCompletionToolCallChunk]]
class GenericGuardrailAPIResponse:
@@ -116,4 +91,5 @@ class GenericGuardrailAPIResponse:
blocked_reason=data.get("blocked_reason"),
texts=data.get("texts"),
images=data.get("images"),
+ tools=data.get("tools"),
)
diff --git a/tests/test_litellm/llms/cohere/rerank/test_rerank_guardrail_handler.py b/tests/test_litellm/llms/cohere/rerank/test_rerank_guardrail_handler.py
index 9c2bbeb7a68..88072cd7760 100644
--- a/tests/test_litellm/llms/cohere/rerank/test_rerank_guardrail_handler.py
+++ b/tests/test_litellm/llms/cohere/rerank/test_rerank_guardrail_handler.py
@@ -22,9 +22,10 @@ class MockGuardrail(CustomGuardrail):
"""Mock guardrail for testing"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
- return ([f"{text} [GUARDRAILED]" for text in texts], None)
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
+ texts = inputs.get("texts", [])
+ return {"texts": [f"{text} [GUARDRAILED]" for text in texts]}
class TestHandlerDiscovery:
@@ -186,10 +187,11 @@ class TestPIIMaskingScenario:
"""Mock PII masking guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
import re
+ texts = inputs.get("texts", [])
masked_texts = []
for text in texts:
masked = re.sub(
@@ -199,7 +201,7 @@ class TestPIIMaskingScenario:
)
masked = masked.replace("John Doe", "[NAME_REDACTED]")
masked_texts.append(masked)
- return (masked_texts, None)
+ return {"texts": masked_texts}
handler = CohereRerankHandler()
guardrail = PIIMaskingGuardrail(guardrail_name="mask_pii")
@@ -237,10 +239,11 @@ class TestPIIMaskingScenario:
"""Mock PII masking guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
import re
+ texts = inputs.get("texts", [])
masked_texts = []
for text in texts:
# Mask emails
@@ -254,7 +257,7 @@ class TestPIIMaskingScenario:
# Mask names
masked = masked.replace("Alice Smith", "[NAME_REDACTED]")
masked_texts.append(masked)
- return (masked_texts, None)
+ return {"texts": masked_texts}
handler = CohereRerankHandler()
guardrail = PIIMaskingGuardrail(guardrail_name="mask_pii")
@@ -349,16 +352,17 @@ class TestContentFilteringScenario:
"""Mock content filter guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
bad_words = ["inappropriate", "offensive"]
+ texts = inputs.get("texts", [])
filtered_texts = []
for text in texts:
filtered = text
for word in bad_words:
filtered = filtered.replace(word, "[FILTERED]")
filtered_texts.append(filtered)
- return (filtered_texts, None)
+ return {"texts": filtered_texts}
handler = CohereRerankHandler()
guardrail = ContentFilterGuardrail(guardrail_name="content_filter")
diff --git a/tests/test_litellm/llms/openai/chat/guardrail_translation/test_handler.py b/tests/test_litellm/llms/openai/chat/guardrail_translation/test_handler.py
index 09f3f8dcf0f..951ec908f09 100644
--- a/tests/test_litellm/llms/openai/chat/guardrail_translation/test_handler.py
+++ b/tests/test_litellm/llms/openai/chat/guardrail_translation/test_handler.py
@@ -46,12 +46,12 @@ class MockGuardrail(CustomGuardrail):
request_data: dict,
input_type: Literal["request", "response"],
logging_obj: Optional[Any] = None,
- ) -> Tuple[List[str], Optional[List[str]]]:
+ ) -> GenericGuardrailAPIInputs:
"""Mock apply_guardrail that uppercases text and modifies tool calls"""
self.last_inputs = inputs
self.last_request_data = request_data
- # Return modified texts (uppercase for testing)
+ # Return modified inputs (uppercase texts for testing)
texts = inputs.get("texts", [])
modified_texts = [text.upper() for text in texts]
@@ -75,7 +75,13 @@ class MockGuardrail(CustomGuardrail):
# If not JSON, just uppercase the string
function["arguments"] = function["arguments"].upper()
- return modified_texts, []
+ # Return modified inputs as GenericGuardrailAPIInputs
+ result: GenericGuardrailAPIInputs = {"texts": modified_texts}
+ if tool_calls:
+ result["tool_calls"] = tool_calls # type: ignore
+ if "images" in inputs:
+ result["images"] = inputs["images"] # type: ignore
+ return result
class TestOpenAIChatCompletionsHandlerToolCallsInput:
@@ -512,6 +518,68 @@ class TestOpenAIChatCompletionsHandlerToolCallsOutput:
assert args1["location"] == "TOKYO"
assert args2["topic"] == "TECHNOLOGY"
+ @pytest.mark.asyncio
+ async def test_extract_tool_calls_from_real_openai_response(self):
+ """Test extraction of tool calls from a real OpenAI API response structure"""
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = MockGuardrail()
+
+ # Create a response matching the exact structure from OpenAI API
+ response = ModelResponse(
+ id="chatcmpl-abc123",
+ created=1699896916,
+ model="gpt-4o-mini",
+ object="chat.completion",
+ choices=[
+ Choices(
+ finish_reason="tool_calls",
+ index=0,
+ message=Message(
+ content=None,
+ role="assistant",
+ tool_calls=[
+ ChatCompletionMessageToolCall(
+ id="call_abc123",
+ type="function",
+ function=Function(
+ name="get_current_weather",
+ arguments='{\n"location": "Boston, MA"\n}',
+ ),
+ )
+ ],
+ ),
+ )
+ ],
+ )
+
+ # Process the output
+ await handler.process_output_response(response, guardrail)
+
+ # Verify tool calls were extracted and passed to guardrail
+ assert guardrail.last_inputs is not None
+ assert "tool_calls" in guardrail.last_inputs
+ assert len(guardrail.last_inputs["tool_calls"]) == 1
+
+ # Verify the tool call details
+ tool_call = guardrail.last_inputs["tool_calls"][0]
+ assert tool_call["id"] == "call_abc123"
+ assert tool_call["type"] == "function"
+ assert tool_call["function"]["name"] == "get_current_weather"
+
+ # Verify arguments can be parsed
+ args = json.loads(tool_call["function"]["arguments"])
+ assert "location" in args
+
+ # Verify tool call was modified by guardrail (location should be uppercased)
+ response_tool_call = response.choices[0].message.tool_calls[0]
+ modified_args = json.loads(response_tool_call.function.arguments)
+ assert modified_args["location"] == "BOSTON, MA" # Should be uppercased
+
+ # Verify response metadata
+ assert response.id == "chatcmpl-abc123"
+ assert response.model == "gpt-4o-mini"
+ assert response.choices[0].finish_reason == "tool_calls"
+
if __name__ == "__main__":
# Run the tests
diff --git a/tests/test_litellm/llms/openai/completion/test_text_completion_guardrail_handler.py b/tests/test_litellm/llms/openai/completion/test_text_completion_guardrail_handler.py
index c861e48ad48..257db89d073 100644
--- a/tests/test_litellm/llms/openai/completion/test_text_completion_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/completion/test_text_completion_guardrail_handler.py
@@ -23,9 +23,10 @@ class MockGuardrail(CustomGuardrail):
"""Mock guardrail for testing"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
- return ([f"{text} [GUARDRAILED]" for text in texts], None)
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
+ texts = inputs.get("texts", [])
+ return {"texts": [f"{text} [GUARDRAILED]" for text in texts]}
class TestHandlerDiscovery:
@@ -246,11 +247,12 @@ class TestPIIMaskingScenario:
"""Mock PII masking guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
# Simple mock: replace email-like patterns
import re
+ texts = inputs.get("texts", [])
masked_texts = []
for text in texts:
masked = re.sub(
@@ -261,7 +263,7 @@ class TestPIIMaskingScenario:
# Replace names (simple mock)
masked = masked.replace("John Doe", "[NAME_REDACTED]")
masked_texts.append(masked)
- return (masked_texts, None)
+ return {"texts": masked_texts}
handler = OpenAITextCompletionHandler()
guardrail = PIIMaskingGuardrail(guardrail_name="mask_pii")
@@ -309,10 +311,11 @@ class TestPIIMaskingScenario:
"""Mock PII masking guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
import re
+ texts = inputs.get("texts", [])
masked_texts = []
for text in texts:
masked = re.sub(
@@ -321,7 +324,7 @@ class TestPIIMaskingScenario:
text,
)
masked_texts.append(masked)
- return (masked_texts, None)
+ return {"texts": masked_texts}
handler = OpenAITextCompletionHandler()
guardrail = PIIMaskingGuardrail(guardrail_name="mask_pii")
diff --git a/tests/test_litellm/llms/openai/image_generation/test_image_generation_guardrail_handler.py b/tests/test_litellm/llms/openai/image_generation/test_image_generation_guardrail_handler.py
index 5e183e32208..cfccd6f3bbe 100644
--- a/tests/test_litellm/llms/openai/image_generation/test_image_generation_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/image_generation/test_image_generation_guardrail_handler.py
@@ -22,9 +22,10 @@ class MockGuardrail(CustomGuardrail):
"""Mock guardrail for testing"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
- return ([f"{text} [GUARDRAILED]" for text in texts], None)
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
+ texts = inputs.get("texts", [])
+ return {"texts": [f"{text} [GUARDRAILED]" for text in texts]}
class TestHandlerDiscovery:
@@ -144,11 +145,12 @@ class TestPIIMaskingScenario:
"""Mock PII masking guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
# Simple mock: replace email-like patterns
import re
+ texts = inputs.get("texts", [])
masked_texts = []
for text in texts:
masked = re.sub(
@@ -159,7 +161,7 @@ class TestPIIMaskingScenario:
# Replace names (simple mock)
masked = masked.replace("John Doe", "[NAME_REDACTED]")
masked_texts.append(masked)
- return (masked_texts, None)
+ return {"texts": masked_texts}
handler = OpenAIImageGenerationHandler()
guardrail = PIIMaskingGuardrail(guardrail_name="mask_pii")
diff --git a/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py b/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
index cc76be08178..e9558580d98 100644
--- a/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
@@ -23,8 +23,13 @@ from litellm.llms import get_guardrail_translation_mapping
from litellm.llms.openai.responses.guardrail_translation.handler import (
OpenAIResponsesHandler,
)
+from litellm.types.guardrails import GenericGuardrailAPIInputs
from litellm.types.llms.openai import ResponsesAPIResponse
-from litellm.types.responses.main import GenericResponseOutputItem, OutputText
+from litellm.types.responses.main import (
+ GenericResponseOutputItem,
+ OutputFunctionToolCall,
+ OutputText,
+)
from litellm.types.utils import CallTypes
@@ -33,16 +38,16 @@ class MockGuardrail(CustomGuardrail):
async def apply_guardrail(
self,
- texts: List[str],
+ inputs: GenericGuardrailAPIInputs,
request_data: dict,
input_type: Literal["request", "response"],
logging_obj: Optional[Any] = None,
- images: Optional[List[str]] = None,
- ) -> Tuple[List[str], Optional[List[str]]]:
+ ) -> GenericGuardrailAPIInputs:
"""
For requests: Append [GUARDRAILED] to text
For responses: Block by raising HTTPException (masking responses is no longer supported)
"""
+ texts = inputs.get("texts", [])
if input_type == "response":
# Responses should be blocked, not masked
raise HTTPException(
@@ -50,7 +55,8 @@ class MockGuardrail(CustomGuardrail):
detail={"error": "Response blocked by guardrail", "texts": texts},
)
# For requests, we can still mask/transform
- return ([f"{text} [GUARDRAILED]" for text in texts], None)
+ inputs["texts"] = [f"{text} [GUARDRAILED]" for text in texts]
+ return inputs
class TestOpenAIResponsesHandlerDiscovery:
@@ -532,3 +538,181 @@ class TestOpenAIResponsesHandlerEdgeCases:
# Should skip processing and return unchanged
assert result == response
+
+
+class TestOpenAIResponsesHandlerToolCallExtraction:
+ """Test tool call extraction functionality"""
+
+ def test_extract_tool_call_from_function_call_output(self):
+ """Test extracting tool calls from OutputFunctionToolCall in response output"""
+ handler = OpenAIResponsesHandler()
+
+ # Create output item matching the user's provided response structure
+ output_item = OutputFunctionToolCall(
+ arguments='{"location":"Boston, MA","unit":"celsius"}',
+ call_id="call_4SjsMeA6DUHwGKaE87ZojgOF",
+ name="get_current_weather",
+ type="function_call",
+ id="fc_0a8bd293ceb771ca00693240cb185c8196b4b4d23948c6ac88",
+ status="completed",
+ )
+
+ texts_to_check: List[str] = []
+ images_to_check: List[str] = []
+ tool_calls_to_check: List[Any] = []
+ task_mappings: List[Tuple[int, int]] = []
+
+ # Extract tool calls
+ handler._extract_output_text_and_images(
+ output_item=output_item,
+ output_idx=0,
+ texts_to_check=texts_to_check,
+ images_to_check=images_to_check,
+ task_mappings=task_mappings,
+ tool_calls_to_check=tool_calls_to_check,
+ )
+
+ # Verify tool call was extracted
+ assert len(tool_calls_to_check) == 1
+ assert len(texts_to_check) == 0 # No text content in tool call
+
+ # Verify tool call structure
+ tool_call = tool_calls_to_check[0]
+ assert tool_call["id"] == "call_4SjsMeA6DUHwGKaE87ZojgOF"
+ assert tool_call["type"] == "function"
+ assert tool_call["function"]["name"] == "get_current_weather"
+ assert (
+ tool_call["function"]["arguments"]
+ == '{"location":"Boston, MA","unit":"celsius"}'
+ )
+ assert tool_call["index"] == 0
+
+ def test_extract_tool_call_from_dict_format(self):
+ """Test extracting tool calls from dict representation of function call"""
+ handler = OpenAIResponsesHandler()
+
+ # Create output item as dict (another format that may be encountered)
+ output_item = {
+ "arguments": '{"location":"Boston, MA","unit":"celsius"}',
+ "call_id": "call_4SjsMeA6DUHwGKaE87ZojgOF",
+ "name": "get_current_weather",
+ "type": "function_call",
+ "id": "fc_0a8bd293ceb771ca00693240cb185c8196b4b4d23948c6ac88",
+ "status": "completed",
+ }
+
+ texts_to_check: List[str] = []
+ images_to_check: List[str] = []
+ tool_calls_to_check: List[Any] = []
+ task_mappings: List[Tuple[int, int]] = []
+
+ # Extract tool calls
+ handler._extract_output_text_and_images(
+ output_item=output_item,
+ output_idx=0,
+ texts_to_check=texts_to_check,
+ images_to_check=images_to_check,
+ task_mappings=task_mappings,
+ tool_calls_to_check=tool_calls_to_check,
+ )
+
+ # Verify tool call was extracted
+ assert len(tool_calls_to_check) == 1
+ assert len(texts_to_check) == 0 # No text content in tool call
+
+ # Verify tool call structure
+ tool_call = tool_calls_to_check[0]
+ assert tool_call["id"] == "call_4SjsMeA6DUHwGKaE87ZojgOF"
+ assert tool_call["type"] == "function"
+ assert tool_call["function"]["name"] == "get_current_weather"
+ assert (
+ tool_call["function"]["arguments"]
+ == '{"location":"Boston, MA","unit":"celsius"}'
+ )
+
+ @pytest.mark.asyncio
+ async def test_process_output_response_with_tool_calls(self):
+ """Test processing output response containing function tool calls"""
+ handler = OpenAIResponsesHandler()
+ guardrail = MockGuardrail(guardrail_name="test")
+
+ # Create a full response matching user's provided structure
+ response = ResponsesAPIResponse(
+ id="resp_zlasw86v56zobnneYprKIagz33tpQeh7arqL9mrI1oec47HNQLGz0VL0PpM9z67EADHExs7UjtyGqpoBKcM9oR6icMGx826UsXnlvu3ZvIyrVA1CaMgeaMo9H5DdQMhvmXtriqXpikuyYbIsko97x8GvtBIoSCcovM9s5KCwJ4eWSjfr51d6-GwLIMkCNbQI6AN11uYyIKrIfCt_9j7FZdBnRHhZ0_zE7E1LYWQPm9G9_nPmTyh9FXNLUZ9Uib1SejrCetPargnpQeBibaXqPoj_pXFKvgc-_-znG5IWEsM8WH9Pjbm6uWEwpUiCxt8yfjQGEADqaluLAts1mnzQVEhCtZbU67QG3ebSG-rXtBw511f2pJPzZ8kI4hPISmZL8Co3LmIrdpmzzb02sQRoH3v4HCwzVGXgtRwRYkdpffebYElQWzvYDhqIHFHKNavfF8mC5AVPvPRA5h1Pf3utTf26",
+ created_at=1764901066,
+ model="gpt-4.1-mini-2025-04-14",
+ object="response",
+ status="completed",
+ output=[
+ OutputFunctionToolCall(
+ arguments='{"location":"Boston, MA","unit":"celsius"}',
+ call_id="call_4SjsMeA6DUHwGKaE87ZojgOF",
+ name="get_current_weather",
+ type="function_call",
+ id="fc_0a8bd293ceb771ca00693240cb185c8196b4b4d23948c6ac88",
+ status="completed",
+ )
+ ],
+ )
+
+ # Response should be blocked since MockGuardrail blocks responses
+ with pytest.raises(HTTPException) as exc_info:
+ await handler.process_output_response(response, guardrail)
+
+ assert exc_info.value.status_code == 400
+ assert "Response blocked by guardrail" in str(exc_info.value.detail)
+
+ def test_extract_mixed_content_with_text_and_tool_calls(self):
+ """Test extracting both text and tool calls from response"""
+ handler = OpenAIResponsesHandler()
+
+ # Create a response with both text and tool call outputs
+ texts_to_check: List[str] = []
+ images_to_check: List[str] = []
+ tool_calls_to_check: List[Any] = []
+ task_mappings: List[Tuple[int, int]] = []
+
+ # First extract from a message output
+ text_output = {
+ "type": "message",
+ "id": "msg_123",
+ "status": "completed",
+ "role": "assistant",
+ "content": [
+ {"type": "output_text", "text": "I'll check the weather for you"},
+ ],
+ }
+
+ handler._extract_output_text_and_images(
+ output_item=text_output,
+ output_idx=0,
+ texts_to_check=texts_to_check,
+ images_to_check=images_to_check,
+ task_mappings=task_mappings,
+ tool_calls_to_check=tool_calls_to_check,
+ )
+
+ # Then extract from a tool call output
+ tool_call_output = OutputFunctionToolCall(
+ arguments='{"location":"Boston, MA","unit":"celsius"}',
+ call_id="call_4SjsMeA6DUHwGKaE87ZojgOF",
+ name="get_current_weather",
+ type="function_call",
+ id="fc_0a8bd293ceb771ca00693240cb185c8196b4b4d23948c6ac88",
+ status="completed",
+ )
+
+ handler._extract_output_text_and_images(
+ output_item=tool_call_output,
+ output_idx=1,
+ texts_to_check=texts_to_check,
+ images_to_check=images_to_check,
+ task_mappings=task_mappings,
+ tool_calls_to_check=tool_calls_to_check,
+ )
+
+ # Verify both were extracted
+ assert len(texts_to_check) == 1
+ assert texts_to_check[0] == "I'll check the weather for you"
+ assert len(tool_calls_to_check) == 1
+ assert tool_calls_to_check[0]["function"]["name"] == "get_current_weather"
diff --git a/tests/test_litellm/llms/openai/speech/test_text_to_speech_guardrail_handler.py b/tests/test_litellm/llms/openai/speech/test_text_to_speech_guardrail_handler.py
index dfd96beb2f4..5b6387cb100 100644
--- a/tests/test_litellm/llms/openai/speech/test_text_to_speech_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/speech/test_text_to_speech_guardrail_handler.py
@@ -22,9 +22,10 @@ class MockGuardrail(CustomGuardrail):
"""Mock guardrail for testing"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
- return ([f"{text} [GUARDRAILED]" for text in texts], None)
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
+ texts = inputs.get("texts", [])
+ return {"texts": [f"{text} [GUARDRAILED]" for text in texts]}
class MockBinaryResponse:
@@ -172,11 +173,12 @@ class TestPIIMaskingScenario:
"""Mock PII masking guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
# Simple mock: replace email-like patterns
import re
+ texts = inputs.get("texts", [])
masked_texts = []
for text in texts:
masked = re.sub(
@@ -188,7 +190,7 @@ class TestPIIMaskingScenario:
masked = masked.replace("John Doe", "[NAME_REDACTED]")
masked = masked.replace("555-1234", "[PHONE_REDACTED]")
masked_texts.append(masked)
- return (masked_texts, None)
+ return {"texts": masked_texts}
handler = OpenAITextToSpeechHandler()
guardrail = PIIMaskingGuardrail(guardrail_name="mask_pii")
@@ -217,10 +219,11 @@ class TestPIIMaskingScenario:
"""Mock PII masking guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
import re
+ texts = inputs.get("texts", [])
masked_texts = []
for text in texts:
# Mask account numbers
@@ -234,7 +237,7 @@ class TestPIIMaskingScenario:
r"\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}", "[CC_REDACTED]", masked
)
masked_texts.append(masked)
- return (masked_texts, None)
+ return {"texts": masked_texts}
handler = OpenAITextToSpeechHandler()
guardrail = PIIMaskingGuardrail(guardrail_name="mask_pii")
@@ -269,17 +272,18 @@ class TestContentModerationScenario:
"""Mock content filter guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
# Simple mock: filter inappropriate words
bad_words = ["badword", "inappropriate", "offensive"]
+ texts = inputs.get("texts", [])
filtered_texts = []
for text in texts:
filtered = text
for word in bad_words:
filtered = filtered.replace(word, "[FILTERED]")
filtered_texts.append(filtered)
- return (filtered_texts, None)
+ return {"texts": filtered_texts}
handler = OpenAITextToSpeechHandler()
guardrail = ContentFilterGuardrail(guardrail_name="content_filter")
diff --git a/tests/test_litellm/llms/openai/transcriptions/test_audio_transcription_guardrail_handler.py b/tests/test_litellm/llms/openai/transcriptions/test_audio_transcription_guardrail_handler.py
index 4d2cb142b35..307972ff477 100644
--- a/tests/test_litellm/llms/openai/transcriptions/test_audio_transcription_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/transcriptions/test_audio_transcription_guardrail_handler.py
@@ -23,9 +23,10 @@ class MockGuardrail(CustomGuardrail):
"""Mock guardrail for testing"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
- return ([f"{text} [GUARDRAILED]" for text in texts], None)
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
+ texts = inputs.get("texts", [])
+ return {"texts": [f"{text} [GUARDRAILED]" for text in texts]}
class TestHandlerDiscovery:
@@ -143,11 +144,12 @@ class TestPIIMaskingScenario:
"""Mock PII masking guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
# Simple mock: replace email-like patterns
import re
+ texts = inputs.get("texts", [])
masked_texts = []
for text in texts:
masked = re.sub(
@@ -159,7 +161,7 @@ class TestPIIMaskingScenario:
masked = masked.replace("John Doe", "[NAME_REDACTED]")
masked = masked.replace("555-1234", "[PHONE_REDACTED]")
masked_texts.append(masked)
- return (masked_texts, None)
+ return {"texts": masked_texts}
handler = OpenAIAudioTranscriptionHandler()
guardrail = PIIMaskingGuardrail(guardrail_name="mask_pii")
@@ -187,10 +189,11 @@ class TestPIIMaskingScenario:
"""Mock PII masking guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
import re
+ texts = inputs.get("texts", [])
masked_texts = []
for text in texts:
# Mask credit card numbers
@@ -206,7 +209,7 @@ class TestPIIMaskingScenario:
masked,
)
masked_texts.append(masked)
- return (masked_texts, None)
+ return {"texts": masked_texts}
handler = OpenAIAudioTranscriptionHandler()
guardrail = PIIMaskingGuardrail(guardrail_name="mask_pii")
@@ -240,17 +243,18 @@ class TestContentModerationScenario:
"""Mock profanity filter guardrail"""
async def apply_guardrail(
- self, texts: List[str], request_data: dict, input_type: str, **kwargs
- ) -> Tuple[List[str], Optional[List[str]]]:
+ self, inputs: dict, request_data: dict, input_type: str, **kwargs
+ ) -> dict:
# Simple mock: replace common profanity
bad_words = ["badword1", "badword2", "inappropriate"]
+ texts = inputs.get("texts", [])
filtered_texts = []
for text in texts:
filtered = text
for word in bad_words:
filtered = filtered.replace(word, "[FILTERED]")
filtered_texts.append(filtered)
- return (filtered_texts, None)
+ return {"texts": filtered_texts}
handler = OpenAIAudioTranscriptionHandler()
guardrail = ProfanityFilterGuardrail(guardrail_name="content_filter")
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py
index f3578fbcefa..eeae0ece02c 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py
@@ -179,7 +179,7 @@ class TestMetadataExtraction:
generic_guardrail.async_handler, "post", return_value=mock_response
) as mock_post:
await generic_guardrail.apply_guardrail(
- inputs=GenericGuardrailAPIInputs(texts=["Who is Ishaan?"]),
+ inputs={"texts": ["Who is Ishaan?"]},
request_data=mock_request_data_input,
input_type="request",
)