From c93a8cc17e83887066a387d8913d15bcbdea54fe Mon Sep 17 00:00:00 2001 From: Shalom Jamil Date: Mon, 23 Feb 2026 12:58:31 +0200 Subject: [PATCH 1/7] Feat(guardrail): Adding support for custom Ovalix guardrail --- .../guardrail_hooks/ovalix/__init__.py | 46 ++ .../guardrail_hooks/ovalix/ovalix.py | 397 ++++++++++++++++++ litellm/types/guardrails.py | 5 + .../guardrails/guardrail_hooks/ovalix.py | 37 ++ .../guardrails/guardrail_hooks/test_ovalix.py | 197 +++++++++ 5 files changed, 682 insertions(+) create mode 100644 litellm/proxy/guardrails/guardrail_hooks/ovalix/__init__.py create mode 100644 litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py create mode 100644 litellm/types/proxy/guardrails/guardrail_hooks/ovalix.py create mode 100644 tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py diff --git a/litellm/proxy/guardrails/guardrail_hooks/ovalix/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/ovalix/__init__.py new file mode 100644 index 000000000000..b73572e4ed5a --- /dev/null +++ b/litellm/proxy/guardrails/guardrail_hooks/ovalix/__init__.py @@ -0,0 +1,46 @@ +"""Ovalix guardrail hook: registration and initialization for the proxy.""" + +from typing import TYPE_CHECKING + +from litellm.types.guardrails import SupportedGuardrailIntegrations + +from .ovalix import OvalixGuardrail + +if TYPE_CHECKING: + from litellm.types.guardrails import Guardrail, LitellmParams + + +def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"): + """Create and register an Ovalix guardrail callback from proxy config.""" + import litellm + + tracker_api_base = getattr(litellm_params, "tracker_api_base", None) + tracker_api_key = getattr(litellm_params, "tracker_api_key", None) + application_id = getattr(litellm_params, "application_id", None) + pre_checkpoint_id = getattr(litellm_params, "pre_checkpoint_id", None) + post_checkpoint_id = getattr(litellm_params, "post_checkpoint_id", None) + + _ovalix_callback = OvalixGuardrail( + guardrail_name=guardrail.get("guardrail_name", ""), + tracker_api_base=tracker_api_base, + tracker_api_key=tracker_api_key, + application_id=application_id, + pre_checkpoint_id=pre_checkpoint_id, + post_checkpoint_id=post_checkpoint_id, + event_hook=litellm_params.mode, + default_on=litellm_params.default_on, + ) + litellm.logging_callback_manager.add_litellm_callback(_ovalix_callback) + + return _ovalix_callback + + +# Registry of guardrail name -> initializer for proxy config loading. +guardrail_initializer_registry = { + SupportedGuardrailIntegrations.OVALIX.value: initialize_guardrail, +} + +# Registry of guardrail name -> guardrail class (e.g. for apply_guardrail API). +guardrail_class_registry = { + SupportedGuardrailIntegrations.OVALIX.value: OvalixGuardrail, +} diff --git a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py new file mode 100644 index 000000000000..585f27f8517c --- /dev/null +++ b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py @@ -0,0 +1,397 @@ +"""Ovalix guardrail integration: pre- and post-call checks via the Tracker service. + +Use Ovalix Guardrails for your LLM calls. Supports pre_call (user input) and +post_call (model output) checkpoints with optional correction/blocking. +""" + +import datetime +import os +from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Type + +import httpx + +import litellm +from litellm._logging import verbose_proxy_logger +from litellm.exceptions import GuardrailRaisedException +from litellm.integrations.custom_guardrail import ( + CustomGuardrail, + log_guardrail_information, +) +from litellm.llms.custom_httpx.http_handler import ( + get_async_httpx_client, + httpxSpecialProvider, +) +from litellm.types.guardrails import GuardrailEventHooks +from litellm.types.utils import GenericGuardrailAPIInputs + +if TYPE_CHECKING: + from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel + + +BLOCKED_BY_OVALIX_FALLBACK_MESSAGE = "This message was blocked by Ovalix" +BLOCKED_ACTION_TYPE = "block" +USER_MESSAGE_ROLE = "user" + + +class OvalixGuardrailMissingSecrets(Exception): + """Raised when required Ovalix config (API base, key, application/checkpoint IDs) is missing.""" + + pass + + +class OvalixGuardrailBlockedException(GuardrailRaisedException): + """ + Raised when Ovalix blocks a message. Sets status_code=400 so the proxy + returns 400 and HTTP clients do not retry (they retry on 5xx). + """ + + status_code = 400 + + def __init__( + self, + guardrail_name: Optional[str] = None, + message: str = "", + should_wrap_with_default_message: bool = True, + ): + super().__init__( + guardrail_name=guardrail_name, + message=message, + should_wrap_with_default_message=should_wrap_with_default_message, + ) + + +class OvalixGuardrail(CustomGuardrail): + """ + Ovalix guardrail: pre-prompt (pre_call) and post-prompt (post_call) checks + via the Tracker service, with application and checkpoint resolution from the + Monolith backend. + """ + + def __init__( + self, + tracker_api_base: Optional[str] = None, + tracker_api_key: Optional[str] = None, + application_id: Optional[str] = None, + pre_checkpoint_id: Optional[str] = None, + post_checkpoint_id: Optional[str] = None, + **kwargs: Any, + ): + self._tracker_api_base = tracker_api_base or os.environ.get( + "OVALIX_TRACKER_API_BASE" + ) + self._tracker_api_key = tracker_api_key or os.environ.get( + "OVALIX_TRACKER_API_KEY" + ) + self._application_id = application_id or os.environ.get("OVALIX_APPLICATION_ID") + self._pre_checkpoint_id = pre_checkpoint_id or os.environ.get( + "OVALIX_PRE_CHECKPOINT_ID" + ) + self._post_checkpoint_id = post_checkpoint_id or os.environ.get( + "OVALIX_POST_CHECKPOINT_ID" + ) + + if "supported_event_hooks" not in kwargs: + kwargs["supported_event_hooks"] = [] + + self._validate_config(kwargs["supported_event_hooks"]) + + self._tracker_headers = httpx.Headers( + { + "Authorization": f"Bearer {self._tracker_api_key}", + "Content-Type": "application/json", + }, + encoding="utf-8", + ) + + self._async_handler = get_async_httpx_client( + llm_provider=httpxSpecialProvider.GuardrailCallback + ) + + super().__init__(**kwargs) + verbose_proxy_logger.debug( + "Ovalix Guardrail initialized: tracker=%s, application_id=%s, pre_checkpoint_id=%s, post_checkpoint_id=%s", + self._tracker_api_base, + self._application_id, + self._pre_checkpoint_id, + self._post_checkpoint_id, + ) + + def _validate_config( + self, supported_event_hooks: List[GuardrailEventHooks] + ) -> None: + """Ensure required secrets and checkpoint IDs are set; auto-add hooks when IDs are present.""" + if not self._tracker_api_base: + raise OvalixGuardrailMissingSecrets( + "Ovalix Tracker API base required. Set OVALIX_TRACKER_API_BASE or pass tracker_api_base in litellm_params." + ) + if not self._tracker_api_key: + raise OvalixGuardrailMissingSecrets( + "Ovalix Tracker API key required. Set OVALIX_TRACKER_API_KEY or pass tracker_api_key in litellm_params." + ) + if not self._application_id: + raise OvalixGuardrailMissingSecrets( + "Ovalix Application ID required. Set OVALIX_APPLICATION_ID or pass application_id in litellm_params." + ) + + if ( + not self._pre_checkpoint_id + and GuardrailEventHooks.pre_call in supported_event_hooks + ): + raise OvalixGuardrailMissingSecrets( + "Ovalix Pre-checkpoint ID required. Set OVALIX_PRE_CHECKPOINT_ID or pass pre_checkpoint_id in litellm_params." + ) + elif ( + self._pre_checkpoint_id + and GuardrailEventHooks.pre_call not in supported_event_hooks + ): + supported_event_hooks.append(GuardrailEventHooks.pre_call) + + if ( + not self._post_checkpoint_id + and GuardrailEventHooks.post_call in supported_event_hooks + ): + raise OvalixGuardrailMissingSecrets( + "Ovalix Post-checkpoint ID required. Set OVALIX_POST_CHECKPOINT_ID or pass post_checkpoint_id in litellm_params." + ) + elif ( + self._post_checkpoint_id + and GuardrailEventHooks.post_call not in supported_event_hooks + ): + supported_event_hooks.append(GuardrailEventHooks.post_call) + + if not self._pre_checkpoint_id and not self._post_checkpoint_id: + raise OvalixGuardrailMissingSecrets( + "Ovalix Pre-checkpoint ID or Post-checkpoint ID required. Set OVALIX_PRE_CHECKPOINT_ID or OVALIX_POST_CHECKPOINT_ID or pass pre_checkpoint_id or post_checkpoint_id in litellm_params." + ) + + def _get_actor(self, data: dict) -> str: + """Return a stable actor identifier from request metadata (e.g. user email or id).""" + metadata = data.get("metadata") or data.get("litellm_metadata") or {} + if metadata.get("user_api_key_user_email"): + return metadata["user_api_key_user_email"] + if metadata.get("user_api_key_user_id"): + return metadata["user_api_key_user_id"] + return "unknown" + + def _get_session_id(self, data: dict) -> str: + """Return a unique identifier for the chat/session (actor + date + application_id).""" + actor = hash(self._get_actor(data)) + today = datetime.datetime.now().strftime("%Y-%m-%d") + return f"{actor}_{today}_{self._application_id}" + + async def _call_checkpoint( + self, + content: str, + checkpoint_id: str, + actor: str, + session_id: str, + ) -> Dict[str, Any]: + """Call the Ovalix Tracker checkpoint API and return the JSON response.""" + application_id = self._application_id + if not application_id or not checkpoint_id: + raise ValueError("Ovalix: application_id or checkpoint_id not resolved") + + url = f"{self._tracker_api_base}/tracking/custom_application/checkpoint" + headers = dict(self._tracker_headers) + payload = { + "application_id": application_id, + "checkpoint_id": checkpoint_id, + "actor": actor, + "session_id": session_id, + "data_type": "TEXT", + "data": {"content": content}, + } + response = await self._async_handler.post( + url, headers=headers, json=payload + ) + response.raise_for_status() + return response.json() + + @log_guardrail_information + async def apply_guardrail( + self, + inputs: GenericGuardrailAPIInputs, + request_data: dict, + input_type: Literal["request", "response"], + logging_obj: Optional[Any] = None, + ) -> GenericGuardrailAPIInputs: + """ + Apply Ovalix guardrail to the given inputs (request or response text). + + Used by the unified guardrail flow and the /apply_guardrail API. + For "request", uses the pre-checkpoint; for "response", uses the post-checkpoint. + + Args: + inputs: Guardrail API inputs (e.g. texts to check). + request_data: Full request payload (messages, metadata, response). + input_type: "request" (pre_call) or "response" (post_call). + logging_obj: Optional logging context. + + Returns: + Updated inputs (e.g. with replaced/corrected texts, or unchanged). + """ + if not self._pre_checkpoint_id and not self._post_checkpoint_id: + return inputs + + actor = self._get_actor(request_data) + session_id = self._get_session_id(request_data) + + if input_type == "response": + llm_response = self._get_llm_response_text( + request_data.get("response", None) + ) + if llm_response: + ( + corrected_llm_response, + is_blocked, + ) = await self._handle_post_llm_response( + llm_response, actor, session_id + ) + # TODO: set the llm response text to `corrected_llm_response`. will be addressed later. + return inputs + + messages = request_data.get("messages") or [] + if not messages: + return inputs + + if self._pre_checkpoint_id: + post_guardrail_texts = await self._generate_post_guardrail_text( + messages, actor, session_id, request_data + ) + return {**inputs, "texts": post_guardrail_texts} + return inputs + + def _block_current_message(self, blocking_message: str) -> None: + """Raise OvalixGuardrailBlockedException with the given message (no default wrapper).""" + raise OvalixGuardrailBlockedException( + guardrail_name=self.guardrail_name, + message=blocking_message, + should_wrap_with_default_message=False, + ) + + def _get_llm_response_text( + self, response: Optional[litellm.ModelResponse] + ) -> Optional[str]: + """Extract the first assistant text content from a ModelResponse, or None.""" + if not response: + return None + if isinstance(response, litellm.ModelResponse): + for choice in response.choices: + if isinstance(choice, litellm.Choices): + if choice.message.content and isinstance( + choice.message.content, str + ): + return choice.message.content + return None + + async def _handle_post_llm_response( + self, llm_response: str, actor: str, session_id: str + ) -> tuple[str, bool]: + """Run post-call checkpoint on model output; return corrected text or raise if blocked.""" + if not self._post_checkpoint_id: + raise ValueError( + "Ovalix: post-checkpoint ID is required for post_call handling." + ) + + try: + resp = await self._call_checkpoint( + llm_response, self._post_checkpoint_id, actor, session_id + ) + except Exception as e: + verbose_proxy_logger.exception( + "Ovalix apply_guardrail checkpoint call failed: %s", e + ) + raise GuardrailRaisedException( + guardrail_name=self.guardrail_name, + message=f"Ovalix guardrail error: {e!s}", + should_wrap_with_default_message=False, + ) from e + + action_type = (resp.get("action_type") or "").lower() + if action_type == BLOCKED_ACTION_TYPE: + blocking_message = ( + self._get_trackers_corrected_message(resp) + or BLOCKED_BY_OVALIX_FALLBACK_MESSAGE + ) + return blocking_message, True + return self._get_trackers_corrected_message(resp) or llm_response, False + + async def _generate_post_guardrail_text( + self, + messages: List[Dict[str, Any]], + actor: str, + session_id: str, + request_data: dict, + ) -> List[str]: + """ + Generate post-guardrail text for the given messages. + + Args: + messages: List of messages + actor: Actor + session_id: Session ID + request_data: Request data + + Returns: + List of post-guardrail texts + """ + is_last_prompt = True + post_guardrail_texts: List[str] = [] + + if not self._pre_checkpoint_id: + # should not happen - if it does, the guardrail is not configured correctly and self._validate_config did not raise an error + raise ValueError("Ovalix: pre-checkpoint ID is required") + + for message in reversed(messages): + content = message.get("content", None) or "" + if not isinstance(content, str): + continue + message_role = message.get("role", None) + if message_role and message_role != USER_MESSAGE_ROLE: + # we are not scanning the LLM/system/developer past responses, only the response that the user sent + post_guardrail_texts.insert(0, content) + continue + try: + resp = await self._call_checkpoint( + content, self._pre_checkpoint_id, actor, session_id + ) + except Exception as e: + verbose_proxy_logger.exception( + "Ovalix apply_guardrail checkpoint call failed: %s", e + ) + raise GuardrailRaisedException( + guardrail_name=self.guardrail_name, + message=f"Ovalix guardrail error: {e!s}", + should_wrap_with_default_message=False, + ) from e + + action_type = (resp.get("action_type") or "").lower() + if action_type == BLOCKED_ACTION_TYPE: + blocking_message = ( + self._get_trackers_corrected_message(resp) + or BLOCKED_BY_OVALIX_FALLBACK_MESSAGE + ) + if is_last_prompt: + self._block_current_message(blocking_message) + else: + post_guardrail_texts.insert(0, blocking_message) + else: + new_content = self._get_trackers_corrected_message(resp) or content + post_guardrail_texts.insert(0, new_content) + is_last_prompt = False + return post_guardrail_texts + + def _get_trackers_corrected_message(self, resp: dict) -> Optional[str]: + """Extract corrected/blocking message content from Tracker checkpoint response.""" + modified = resp.get("modified_data") + if isinstance(modified, dict) and "content" in modified: + return modified["content"] + return None + + @staticmethod + def get_config_model() -> Optional[Type["GuardrailConfigModel"]]: + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + return OvalixGuardrailConfigModel diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py index 74ccb34ca6eb..27289553c37f 100644 --- a/litellm/types/guardrails.py +++ b/litellm/types/guardrails.py @@ -17,6 +17,9 @@ from litellm.types.proxy.guardrails.guardrail_hooks.litellm_content_filter import ( ContentFilterCategoryConfig, ) +from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, +) from litellm.types.proxy.guardrails.guardrail_hooks.qualifire import ( QualifireGuardrailConfigModel, ) @@ -69,6 +72,7 @@ class SupportedGuardrailIntegrations(Enum): GENERIC_GUARDRAIL_API = "generic_guardrail_api" QUALIFIRE = "qualifire" CUSTOM_CODE = "custom_code" + OVALIX = "ovalix" class Role(Enum): @@ -681,6 +685,7 @@ class LitellmParams( BaseLitellmParams, EnkryptAIGuardrailConfigs, IBMGuardrailsBaseConfigModel, + OvalixGuardrailConfigModel, QualifireGuardrailConfigModel, ): guardrail: str = Field(description="The type of guardrail integration to use") diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/ovalix.py b/litellm/types/proxy/guardrails/guardrail_hooks/ovalix.py new file mode 100644 index 000000000000..7417d1a00c98 --- /dev/null +++ b/litellm/types/proxy/guardrails/guardrail_hooks/ovalix.py @@ -0,0 +1,37 @@ +"""Pydantic config model for the Ovalix guardrail (Tracker API, application and checkpoint IDs).""" + +from typing import Optional + +from pydantic import Field + +from .base import GuardrailConfigModel + + +class OvalixGuardrailConfigModel(GuardrailConfigModel): + """Configuration parameters for the Ovalix guardrail (pre/post call checkpoints).""" + + tracker_api_base: Optional[str] = Field( + default=None, + description="Base URL for the Ovalix Tracker service.", + ) + tracker_api_key: Optional[str] = Field( + default=None, + description="API key for the Ovalix Tracker service.", + ) + application_id: Optional[str] = Field( + default=None, + description="Application ID for the Ovalix Tracker service.", + ) + pre_checkpoint_id: Optional[str] = Field( + default=None, + description="Pre-checkpoint ID for the Ovalix Tracker service.", + ) + post_checkpoint_id: Optional[str] = Field( + default=None, + description="Post-checkpoint ID for the Ovalix Tracker service.", + ) + + @staticmethod + def ui_friendly_name() -> str: + """Display name for this guardrail in the proxy UI.""" + return "Ovalix Guardrail" diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py new file mode 100644 index 000000000000..89fcf4e8c3ff --- /dev/null +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py @@ -0,0 +1,197 @@ +""" +Unit tests for Ovalix guardrail types (OvalixGuardrailConfigModel) and config model resolution. +""" +from litellm.proxy.guardrails.guardrail_hooks.ovalix.ovalix import OvalixGuardrail + + +class TestOvalixGuardrailConfigModel: + """Tests for OvalixGuardrailConfigModel from litellm.types.proxy.guardrails.guardrail_hooks.ovalix.""" + + def test_config_model_ui_friendly_name(self): + """Test that config model has correct UI friendly name.""" + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + assert OvalixGuardrailConfigModel.ui_friendly_name() == "Ovalix Guardrail" + + def test_config_model_fields(self): + """Test that config model has expected fields and default values.""" + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + model = OvalixGuardrailConfigModel() + + assert model.tracker_api_base is None + assert model.tracker_api_key is None + assert model.application_id is None + assert model.pre_checkpoint_id is None + assert model.post_checkpoint_id is None + + def test_get_config_model(self): + """Test get_config_model returns OvalixGuardrailConfigModel.""" + config_model = OvalixGuardrail.get_config_model() + assert config_model is not None + assert config_model.__name__ == "OvalixGuardrailConfigModel" + assert hasattr(config_model, "ui_friendly_name") + assert config_model.ui_friendly_name() == "Ovalix Guardrail" + + def test_config_model_with_all_fields_set(self): + """Test construction with all optional fields set to explicit values.""" + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + model = OvalixGuardrailConfigModel( + tracker_api_base="https://tracker.ovalix.example", + tracker_api_key="key-123", + application_id="app-456", + pre_checkpoint_id="pre-cp-1", + post_checkpoint_id="post-cp-1", + ) + + assert model.tracker_api_base == "https://tracker.ovalix.example" + assert model.tracker_api_key == "key-123" + assert model.application_id == "app-456" + assert model.pre_checkpoint_id == "pre-cp-1" + assert model.post_checkpoint_id == "post-cp-1" + + def test_config_model_with_partial_fields(self): + """Test construction with only a subset of fields set.""" + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + model = OvalixGuardrailConfigModel( + tracker_api_base="https://custom.tracker", + application_id="app-only", + ) + + assert model.tracker_api_base == "https://custom.tracker" + assert model.application_id == "app-only" + assert model.tracker_api_key is None + assert model.pre_checkpoint_id is None + assert model.post_checkpoint_id is None + + def test_config_model_inherits_base_optional_params(self): + """Test that model has optional_params from GuardrailConfigModel and defaults to None.""" + from litellm.types.proxy.guardrails.guardrail_hooks.base import ( + GuardrailConfigModel, + ) + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + model = OvalixGuardrailConfigModel() + assert hasattr(model, "optional_params") + assert model.optional_params is None + assert isinstance(model, GuardrailConfigModel) + + def test_config_model_serialization_dump(self): + """Test model_dump produces expected keys and values.""" + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + model = OvalixGuardrailConfigModel( + tracker_api_base="https://tracker.test", + pre_checkpoint_id="pre-1", + ) + data = model.model_dump() + + assert "tracker_api_base" in data + assert "tracker_api_key" in data + assert "application_id" in data + assert "pre_checkpoint_id" in data + assert "post_checkpoint_id" in data + assert data["tracker_api_base"] == "https://tracker.test" + assert data["pre_checkpoint_id"] == "pre-1" + assert data["tracker_api_key"] is None + + def test_config_model_deserialization_from_dict(self): + """Test model_validate builds instance from dict.""" + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + payload = { + "tracker_api_base": "https://from-dict.example", + "tracker_api_key": "secret", + "application_id": "app-dict", + "pre_checkpoint_id": "pre-d", + "post_checkpoint_id": "post-d", + } + model = OvalixGuardrailConfigModel.model_validate(payload) + + assert model.tracker_api_base == "https://from-dict.example" + assert model.tracker_api_key == "secret" + assert model.application_id == "app-dict" + assert model.pre_checkpoint_id == "pre-d" + assert model.post_checkpoint_id == "post-d" + + def test_config_model_deserialization_empty_dict(self): + """Test model_validate with empty dict yields defaults.""" + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + model = OvalixGuardrailConfigModel.model_validate({}) + + assert model.tracker_api_base is None + assert model.tracker_api_key is None + assert model.application_id is None + assert model.pre_checkpoint_id is None + assert model.post_checkpoint_id is None + + def test_config_model_round_trip(self): + """Test model_dump then model_validate preserves data.""" + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + original = OvalixGuardrailConfigModel( + tracker_api_base="https://round.trip", + post_checkpoint_id="post-rt", + ) + data = original.model_dump() + restored = OvalixGuardrailConfigModel.model_validate(data) + + assert restored.tracker_api_base == original.tracker_api_base + assert restored.tracker_api_key == original.tracker_api_key + assert restored.application_id == original.application_id + assert restored.pre_checkpoint_id == original.pre_checkpoint_id + assert restored.post_checkpoint_id == original.post_checkpoint_id + + def test_config_model_has_expected_field_names(self): + """Test that model defines all expected Ovalix config field names.""" + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + expected = { + "tracker_api_base", + "tracker_api_key", + "application_id", + "pre_checkpoint_id", + "post_checkpoint_id", + } + assert expected.issubset(OvalixGuardrailConfigModel.model_fields.keys()) + + def test_config_model_field_descriptions_present(self): + """Test that Ovalix-specific fields have non-empty descriptions.""" + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + ovalix_fields = [ + "tracker_api_base", + "tracker_api_key", + "application_id", + "pre_checkpoint_id", + "post_checkpoint_id", + ] + for name in ovalix_fields: + assert name in OvalixGuardrailConfigModel.model_fields + desc = OvalixGuardrailConfigModel.model_fields[name].description + assert desc is not None and len(desc) > 0 From 3718682021a840480b7700eddfeb58ba9a56d1da Mon Sep 17 00:00:00 2001 From: Shalom Jamil Date: Mon, 23 Feb 2026 12:59:50 +0200 Subject: [PATCH 2/7] Internal CR comments fixes --- .../guardrail_hooks/ovalix/ovalix.py | 65 +- .../guardrails/guardrail_hooks/test_ovalix.py | 770 ++++++++++++++---- 2 files changed, 631 insertions(+), 204 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py index 585f27f8517c..d962057617e9 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py +++ b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py @@ -22,7 +22,7 @@ httpxSpecialProvider, ) from litellm.types.guardrails import GuardrailEventHooks -from litellm.types.utils import GenericGuardrailAPIInputs +from litellm.types.utils import AllMessageValues, GenericGuardrailAPIInputs if TYPE_CHECKING: from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel @@ -120,50 +120,56 @@ def _validate_config( self, supported_event_hooks: List[GuardrailEventHooks] ) -> None: """Ensure required secrets and checkpoint IDs are set; auto-add hooks when IDs are present.""" + errors: List[str] = [] + if not self._tracker_api_base: - raise OvalixGuardrailMissingSecrets( - "Ovalix Tracker API base required. Set OVALIX_TRACKER_API_BASE or pass tracker_api_base in litellm_params." + errors.append( + "Tracker API base, set OVALIX_TRACKER_API_BASE or pass tracker_api_base" ) if not self._tracker_api_key: - raise OvalixGuardrailMissingSecrets( - "Ovalix Tracker API key required. Set OVALIX_TRACKER_API_KEY or pass tracker_api_key in litellm_params." + errors.append( + "Tracker API key, set OVALIX_TRACKER_API_KEY or pass tracker_api_key" ) if not self._application_id: - raise OvalixGuardrailMissingSecrets( - "Ovalix Application ID required. Set OVALIX_APPLICATION_ID or pass application_id in litellm_params." + errors.append( + "Application ID, set OVALIX_APPLICATION_ID or pass application_id" ) - if ( not self._pre_checkpoint_id and GuardrailEventHooks.pre_call in supported_event_hooks ): - raise OvalixGuardrailMissingSecrets( - "Ovalix Pre-checkpoint ID required. Set OVALIX_PRE_CHECKPOINT_ID or pass pre_checkpoint_id in litellm_params." + errors.append( + "Pre-checkpoint ID, set OVALIX_PRE_CHECKPOINT_ID or pass pre_checkpoint_id" ) - elif ( - self._pre_checkpoint_id - and GuardrailEventHooks.pre_call not in supported_event_hooks - ): - supported_event_hooks.append(GuardrailEventHooks.pre_call) - if ( not self._post_checkpoint_id and GuardrailEventHooks.post_call in supported_event_hooks ): + errors.append( + "Post-checkpoint ID, set OVALIX_POST_CHECKPOINT_ID or pass post_checkpoint_id" + ) + if not self._pre_checkpoint_id and not self._post_checkpoint_id: + errors.append( + "Pre-checkpoint ID or Post-checkpoint ID, set OVALIX_PRE_CHECKPOINT_ID or OVALIX_POST_CHECKPOINT_ID or pass pre_checkpoint_id or post_checkpoint_id" + ) + + if errors: raise OvalixGuardrailMissingSecrets( - "Ovalix Post-checkpoint ID required. Set OVALIX_POST_CHECKPOINT_ID or pass post_checkpoint_id in litellm_params." + "Missing Ovalix guardrail configuration errors: " + ". ".join(errors) ) - elif ( + + # auto-add hooks when checkpoint IDs are present + if ( + self._pre_checkpoint_id + and GuardrailEventHooks.pre_call not in supported_event_hooks + ): + supported_event_hooks.append(GuardrailEventHooks.pre_call) + if ( self._post_checkpoint_id and GuardrailEventHooks.post_call not in supported_event_hooks ): supported_event_hooks.append(GuardrailEventHooks.post_call) - if not self._pre_checkpoint_id and not self._post_checkpoint_id: - raise OvalixGuardrailMissingSecrets( - "Ovalix Pre-checkpoint ID or Post-checkpoint ID required. Set OVALIX_PRE_CHECKPOINT_ID or OVALIX_POST_CHECKPOINT_ID or pass pre_checkpoint_id or post_checkpoint_id in litellm_params." - ) - def _get_actor(self, data: dict) -> str: """Return a stable actor identifier from request metadata (e.g. user email or id).""" metadata = data.get("metadata") or data.get("litellm_metadata") or {} @@ -201,9 +207,7 @@ async def _call_checkpoint( "data_type": "TEXT", "data": {"content": content}, } - response = await self._async_handler.post( - url, headers=headers, json=payload - ) + response = await self._async_handler.post(url, headers=headers, json=payload) response.raise_for_status() return response.json() @@ -250,13 +254,13 @@ async def apply_guardrail( # TODO: set the llm response text to `corrected_llm_response`. will be addressed later. return inputs - messages = request_data.get("messages") or [] + messages = inputs.get("structured_messages") or [] if not messages: return inputs if self._pre_checkpoint_id: post_guardrail_texts = await self._generate_post_guardrail_text( - messages, actor, session_id, request_data + messages, actor, session_id ) return {**inputs, "texts": post_guardrail_texts} return inputs @@ -318,10 +322,9 @@ async def _handle_post_llm_response( async def _generate_post_guardrail_text( self, - messages: List[Dict[str, Any]], + messages: List[AllMessageValues], actor: str, session_id: str, - request_data: dict, ) -> List[str]: """ Generate post-guardrail text for the given messages. @@ -348,7 +351,7 @@ async def _generate_post_guardrail_text( continue message_role = message.get("role", None) if message_role and message_role != USER_MESSAGE_ROLE: - # we are not scanning the LLM/system/developer past responses, only the response that the user sent + # we are not scanning the assistant/system/developer past responses, only the responses that the user sent post_guardrail_texts.insert(0, content) continue try: diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py index 89fcf4e8c3ff..a76267e808e4 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py @@ -1,197 +1,621 @@ """ -Unit tests for Ovalix guardrail types (OvalixGuardrailConfigModel) and config model resolution. +Unit tests for Ovalix guardrail: config resolution and apply_guardrail behavior +with mocked Tracker service responses (allow, anonymize, block). """ -from litellm.proxy.guardrails.guardrail_hooks.ovalix.ovalix import OvalixGuardrail - +import os +from unittest.mock import AsyncMock, MagicMock, patch + +import httpx +import pytest + +from litellm.exceptions import GuardrailRaisedException +from litellm.proxy.guardrails.guardrail_hooks.ovalix.ovalix import ( + OvalixGuardrail, + OvalixGuardrailBlockedException, + OvalixGuardrailMissingSecrets, +) +from litellm.types.utils import GenericGuardrailAPIInputs + +# Example Tracker responses (as returned by the checkpoint API) +TRACKER_RESPONSE_ALLOW = { + "action_type": "allow", + "data_type": "TEXT", + "original_data": {"content": "how are you?"}, + "modified_data": {"content": "how are you?"}, + "alerts": [], +} + +TRACKER_RESPONSE_ANONYMIZE = { + "action_type": "anonymize", + "data_type": "TEXT", + "original_data": {"content": "Hello, my name is David."}, + "modified_data": {"content": "Hello, my name is {Name}. How are you?"}, + "alerts": [ + { + "title": "Sensitive Data Alert", + "subtitle": "We've identified that you were trying to share sensitive information", + "alerts": ["Name:\tDavid\nRedacted to:\t{Name}"], + } + ], +} + +TRACKER_RESPONSE_BLOCK = { + "action_type": "block", + "data_type": "TEXT", + "original_data": {"content": "I am 15 YO"}, + "modified_data": {"content": "This message was blocked by Ovalix"}, + "alerts": [ + { + "title": "Sensitive Data Alert", + "subtitle": "We've identified that you were trying to share sensitive information", + "alerts": ["Age:\t15\nBlocked"], + } + ], +} -class TestOvalixGuardrailConfigModel: - """Tests for OvalixGuardrailConfigModel from litellm.types.proxy.guardrails.guardrail_hooks.ovalix.""" - def test_config_model_ui_friendly_name(self): - """Test that config model has correct UI friendly name.""" - from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( - OvalixGuardrailConfigModel, - ) +def _ovalix_env(): + return { + "OVALIX_TRACKER_API_BASE": "https://tracker.test", + "OVALIX_TRACKER_API_KEY": "key", + "OVALIX_APPLICATION_ID": "app-1", + "OVALIX_PRE_CHECKPOINT_ID": "pre-1", + "OVALIX_POST_CHECKPOINT_ID": "post-1", + } - assert OvalixGuardrailConfigModel.ui_friendly_name() == "Ovalix Guardrail" - def test_config_model_fields(self): - """Test that config model has expected fields and default values.""" - from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( - OvalixGuardrailConfigModel, - ) +def _guardrail_kwargs(): + return { + "guardrail_name": "ovalix-test", + "event_hook": "pre_call", + "default_on": True, + } - model = OvalixGuardrailConfigModel() - assert model.tracker_api_base is None - assert model.tracker_api_key is None - assert model.application_id is None - assert model.pre_checkpoint_id is None - assert model.post_checkpoint_id is None +class TestOvalixGuardrailConfigModel: + """Minimal config model tests: wiring only.""" - def test_get_config_model(self): - """Test get_config_model returns OvalixGuardrailConfigModel.""" + def test_get_config_model_returns_ovalix_config_model(self): + """get_config_model returns OvalixGuardrailConfigModel for proxy/config wiring.""" config_model = OvalixGuardrail.get_config_model() assert config_model is not None assert config_model.__name__ == "OvalixGuardrailConfigModel" - assert hasattr(config_model, "ui_friendly_name") assert config_model.ui_friendly_name() == "Ovalix Guardrail" - def test_config_model_with_all_fields_set(self): - """Test construction with all optional fields set to explicit values.""" - from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( - OvalixGuardrailConfigModel, - ) - - model = OvalixGuardrailConfigModel( - tracker_api_base="https://tracker.ovalix.example", - tracker_api_key="key-123", - application_id="app-456", - pre_checkpoint_id="pre-cp-1", - post_checkpoint_id="post-cp-1", - ) - - assert model.tracker_api_base == "https://tracker.ovalix.example" - assert model.tracker_api_key == "key-123" - assert model.application_id == "app-456" - assert model.pre_checkpoint_id == "pre-cp-1" - assert model.post_checkpoint_id == "post-cp-1" - - def test_config_model_with_partial_fields(self): - """Test construction with only a subset of fields set.""" - from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( - OvalixGuardrailConfigModel, - ) - - model = OvalixGuardrailConfigModel( - tracker_api_base="https://custom.tracker", - application_id="app-only", - ) - - assert model.tracker_api_base == "https://custom.tracker" - assert model.application_id == "app-only" - assert model.tracker_api_key is None - assert model.pre_checkpoint_id is None - assert model.post_checkpoint_id is None - def test_config_model_inherits_base_optional_params(self): - """Test that model has optional_params from GuardrailConfigModel and defaults to None.""" - from litellm.types.proxy.guardrails.guardrail_hooks.base import ( - GuardrailConfigModel, +class TestOvalixGuardrail: + """Behavioral tests with mocked Tracker checkpoint API.""" + + def setup_method(self): + for key in list(os.environ.keys()): + if key.startswith("OVALIX_"): + del os.environ[key] + + def teardown_method(self): + for key in list(os.environ.keys()): + if key.startswith("OVALIX_"): + del os.environ[key] + + @pytest.fixture + def guardrail_with_env(self): + """Guardrail with OVALIX_* env set; cleans up in teardown.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + yield OvalixGuardrail(**_guardrail_kwargs()) + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + def test_initialization_requires_secrets(self): + """Initialization raises when required Tracker/application/checkpoint config is missing.""" + with pytest.raises(OvalixGuardrailMissingSecrets): + OvalixGuardrail( + guardrail_name="ovalix-test", + event_hook="pre_call", + default_on=True, + ) + + def test_initialization_with_explicit_params(self): + """Guardrail initializes with explicit tracker base, key, app and checkpoint IDs.""" + guardrail = OvalixGuardrail( + tracker_api_base="https://tracker.example", + tracker_api_key="secret", + application_id="app-x", + pre_checkpoint_id="pre-x", + post_checkpoint_id="post-x", + **_guardrail_kwargs(), ) - from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( - OvalixGuardrailConfigModel, + assert guardrail._tracker_api_base == "https://tracker.example" + assert guardrail._application_id == "app-x" + assert guardrail._pre_checkpoint_id == "pre-x" + assert guardrail._post_checkpoint_id == "post-x" + + def test_initialization_with_env_vars(self): + """Guardrail picks up OVALIX_* env vars when params not passed.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + assert guardrail._tracker_api_base == "https://tracker.test" + assert guardrail._tracker_api_key == "key" + assert guardrail._application_id == "app-1" + assert guardrail._pre_checkpoint_id == "pre-1" + assert guardrail._post_checkpoint_id == "post-1" + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_call_checkpoint_sends_correct_payload_and_returns_json(self): + """_call_checkpoint POSTs to tracker with application_id, checkpoint_id, actor, session_id, data.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_ALLOW + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + result = await guardrail._call_checkpoint( + content="hello", + checkpoint_id="pre-1", + actor="user@test.com", + session_id="session-1", + ) + + assert result == TRACKER_RESPONSE_ALLOW + mock_post.assert_called_once() + call_args = mock_post.call_args + assert call_args.args[0] == ( + "https://tracker.test/tracking/custom_application/checkpoint" + ) + body = call_args.kwargs["json"] + assert body["application_id"] == "app-1" + assert body["checkpoint_id"] == "pre-1" + assert body["actor"] == "user@test.com" + assert body["session_id"] == "session-1" + assert body["data_type"] == "TEXT" + assert body["data"] == {"content": "hello"} + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_request_allow_passes_through(self): + """When Tracker returns allow, apply_guardrail returns inputs with texts set to modified_data content.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs( + structured_messages=[{"role": "user", "content": "how are you?"}] + ) + request_data = {} + + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_ALLOW + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert result.get("texts") == ["how are you?"] + assert mock_post.call_count == 1 + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_request_anonymize_returns_modified_text(self): + """When Tracker returns anonymize, apply_guardrail returns texts with modified_data content.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs( + structured_messages=[ + {"role": "user", "content": "Hello, my name is David."} + ] + ) + request_data = {} + + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_ANONYMIZE + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert result.get("texts") == ["Hello, my name is {Name}. How are you?"] + assert mock_post.call_count == 1 + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_request_block_raises_with_tracker_message(self): + """When Tracker returns block on the (chronologically) last user message, OvalixGuardrailBlockedException is raised.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs( + structured_messages=[{"role": "user", "content": "I am 15 YO"}] + ) + request_data = {} + + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_BLOCK + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + with pytest.raises(OvalixGuardrailBlockedException) as exc_info: + await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert "This message was blocked by Ovalix" in str(exc_info.value.message) + assert exc_info.value.status_code == 400 + assert mock_post.call_count == 1 + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_request_block_non_last_replaced_in_texts(self): + """When Tracker returns block on a non-last user message, that message is replaced in texts and no exception is raised.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs( + structured_messages=[ + {"role": "user", "content": "I am 15 YO"}, + {"role": "user", "content": "how are you?"}, + ] + ) + request_data = {} + + def side_effect(*args, **kwargs): + body = kwargs.get("json", {}) + content = (body.get("data") or {}).get("content", "") + resp = MagicMock() + if "15" in content: + resp.json.return_value = TRACKER_RESPONSE_BLOCK + else: + resp.json.return_value = TRACKER_RESPONSE_ALLOW + resp.raise_for_status = MagicMock() + return resp + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.side_effect = side_effect + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert result.get("texts") == [ + "This message was blocked by Ovalix", + "how are you?", + ] + assert mock_post.call_count == 2 + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_response_allow_returns_inputs(self): + """When input_type is response and Tracker allows, apply_guardrail returns inputs unchanged.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs() + request_data = {"response": None} + + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_ALLOW + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post, patch.object( + guardrail, + "_get_llm_response_text", + return_value="Safe assistant reply", + ): + mock_post.return_value = mock_response + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="response", + logging_obj=None, + ) + + assert result == inputs + assert mock_post.call_count == 1 + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_response_block_returns_inputs( + self, guardrail_with_env + ): + """When Tracker blocks on response, apply_guardrail still returns inputs (no raise).""" + guardrail = guardrail_with_env + inputs = GenericGuardrailAPIInputs() + request_data = {"response": None} + + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_BLOCK + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post, patch.object( + guardrail, + "_get_llm_response_text", + return_value="I am 15 YO", + ): + mock_post.return_value = mock_response + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="response", + logging_obj=None, + ) + + assert result == inputs + assert mock_post.call_count == 1 + + @pytest.mark.asyncio + async def test_apply_guardrail_request_non_user_messages_not_sent_to_tracker( + self, guardrail_with_env + ): + """Only user messages are sent to Tracker; system/assistant content is passed through.""" + guardrail = guardrail_with_env + inputs = GenericGuardrailAPIInputs( + structured_messages=[ + {"role": "system", "content": "You are helpful."}, + {"role": "user", "content": "hello"}, + ] ) - - model = OvalixGuardrailConfigModel() - assert hasattr(model, "optional_params") - assert model.optional_params is None - assert isinstance(model, GuardrailConfigModel) - - def test_config_model_serialization_dump(self): - """Test model_dump produces expected keys and values.""" - from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( - OvalixGuardrailConfigModel, - ) - - model = OvalixGuardrailConfigModel( - tracker_api_base="https://tracker.test", - pre_checkpoint_id="pre-1", - ) - data = model.model_dump() - - assert "tracker_api_base" in data - assert "tracker_api_key" in data - assert "application_id" in data - assert "pre_checkpoint_id" in data - assert "post_checkpoint_id" in data - assert data["tracker_api_base"] == "https://tracker.test" - assert data["pre_checkpoint_id"] == "pre-1" - assert data["tracker_api_key"] is None - - def test_config_model_deserialization_from_dict(self): - """Test model_validate builds instance from dict.""" - from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( - OvalixGuardrailConfigModel, - ) - - payload = { - "tracker_api_base": "https://from-dict.example", - "tracker_api_key": "secret", - "application_id": "app-dict", - "pre_checkpoint_id": "pre-d", - "post_checkpoint_id": "post-d", + request_data = {} + + # Tracker allows and returns same content for the user message + allow_hello = { + "action_type": "allow", + "data_type": "TEXT", + "original_data": {"content": "hello"}, + "modified_data": {"content": "hello"}, + "alerts": [], } - model = OvalixGuardrailConfigModel.model_validate(payload) - - assert model.tracker_api_base == "https://from-dict.example" - assert model.tracker_api_key == "secret" - assert model.application_id == "app-dict" - assert model.pre_checkpoint_id == "pre-d" - assert model.post_checkpoint_id == "post-d" - - def test_config_model_deserialization_empty_dict(self): - """Test model_validate with empty dict yields defaults.""" - from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( - OvalixGuardrailConfigModel, + mock_response = MagicMock() + mock_response.json.return_value = allow_hello + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert result.get("texts") == ["You are helpful.", "hello"] + assert mock_post.call_count == 1 + + @pytest.mark.asyncio + async def test_apply_guardrail_request_missing_modified_data_uses_original_content( + self, guardrail_with_env + ): + """When Tracker response has no modified_data.content, original content is used.""" + guardrail = guardrail_with_env + inputs = GenericGuardrailAPIInputs( + structured_messages=[{"role": "user", "content": "original text"}] ) - - model = OvalixGuardrailConfigModel.model_validate({}) - - assert model.tracker_api_base is None - assert model.tracker_api_key is None - assert model.application_id is None - assert model.pre_checkpoint_id is None - assert model.post_checkpoint_id is None - - def test_config_model_round_trip(self): - """Test model_dump then model_validate preserves data.""" - from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( - OvalixGuardrailConfigModel, + request_data = {} + + mock_response = MagicMock() + mock_response.json.return_value = { + "action_type": "allow", + "data_type": "TEXT", + "original_data": {"content": "original text"}, + "modified_data": {}, + "alerts": [], + } + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert result.get("texts") == ["original text"] + assert mock_post.call_count == 1 + + @pytest.mark.asyncio + async def test_apply_guardrail_tracker_http_error_raises_guardrail_exception( + self, guardrail_with_env + ): + """When Tracker returns HTTP error (e.g. 400), GuardrailRaisedException is raised.""" + guardrail = guardrail_with_env + inputs = GenericGuardrailAPIInputs( + structured_messages=[{"role": "user", "content": "hello"}] ) + request_data = {} - original = OvalixGuardrailConfigModel( - tracker_api_base="https://round.trip", - post_checkpoint_id="post-rt", - ) - data = original.model_dump() - restored = OvalixGuardrailConfigModel.model_validate(data) - - assert restored.tracker_api_base == original.tracker_api_base - assert restored.tracker_api_key == original.tracker_api_key - assert restored.application_id == original.application_id - assert restored.pre_checkpoint_id == original.pre_checkpoint_id - assert restored.post_checkpoint_id == original.post_checkpoint_id - - def test_config_model_has_expected_field_names(self): - """Test that model defines all expected Ovalix config field names.""" - from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( - OvalixGuardrailConfigModel, + mock_response = MagicMock() + mock_response.raise_for_status.side_effect = httpx.HTTPStatusError( + "Bad Request", + request=MagicMock(), + response=MagicMock(status_code=400), ) - expected = { - "tracker_api_base", - "tracker_api_key", - "application_id", - "pre_checkpoint_id", - "post_checkpoint_id", + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + with pytest.raises(GuardrailRaisedException): + await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert mock_post.call_count == 1 + + @pytest.mark.asyncio + async def test_apply_guardrail_checkpoint_error_raises_guardrail_exception(self): + """When Tracker checkpoint call fails, GuardrailRaisedException is raised.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs( + structured_messages=[{"role": "user", "content": "hello"}] + ) + request_data = {} + + with patch.object( + guardrail._async_handler, + "post", + new_callable=AsyncMock, + side_effect=httpx.ConnectError("Connection refused"), + ): + with pytest.raises(GuardrailRaisedException): + await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_request_empty_messages_returns_inputs(self): + """When request has no messages, apply_guardrail returns inputs without calling Tracker.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs(structured_messages=[]) + request_data = {} + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert result == inputs + mock_post.assert_not_called() + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + def test_get_actor_from_metadata(self): + """Actor is taken from metadata.user_api_key_user_email or user_api_key_user_id.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + assert ( + guardrail._get_actor( + {"metadata": {"user_api_key_user_email": "a@b.com"}} + ) + == "a@b.com" + ) + assert ( + guardrail._get_actor({"metadata": {"user_api_key_user_id": "uid-1"}}) + == "uid-1" + ) + assert ( + guardrail._get_actor( + {"litellm_metadata": {"user_api_key_user_id": "uid-2"}} + ) + == "uid-2" + ) + assert guardrail._get_actor({}) == "unknown" + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + def test_get_actor_prefers_email_over_id(self, guardrail_with_env): + """When both user_api_key_user_email and user_api_key_user_id exist, email is used.""" + guardrail = guardrail_with_env + data = { + "metadata": { + "user_api_key_user_email": "primary@test.com", + "user_api_key_user_id": "uid-99", + } } - assert expected.issubset(OvalixGuardrailConfigModel.model_fields.keys()) - - def test_config_model_field_descriptions_present(self): - """Test that Ovalix-specific fields have non-empty descriptions.""" - from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( - OvalixGuardrailConfigModel, - ) - - ovalix_fields = [ - "tracker_api_base", - "tracker_api_key", - "application_id", - "pre_checkpoint_id", - "post_checkpoint_id", - ] - for name in ovalix_fields: - assert name in OvalixGuardrailConfigModel.model_fields - desc = OvalixGuardrailConfigModel.model_fields[name].description - assert desc is not None and len(desc) > 0 + assert guardrail._get_actor(data) == "primary@test.com" + + def test_get_session_id_deterministic_and_includes_app_id(self, guardrail_with_env): + """Session ID is stable for same actor/day and includes application_id.""" + guardrail = guardrail_with_env + data = {"metadata": {"user_api_key_user_id": "user-1"}} + session_id_1 = guardrail._get_session_id(data) + session_id_2 = guardrail._get_session_id(data) + assert session_id_1 == session_id_2 + assert "app-1" in session_id_1 From f3815406c075be8a7945ccfb744aef71c838139d Mon Sep 17 00:00:00 2001 From: Shalom Jamil Date: Mon, 23 Feb 2026 12:59:55 +0200 Subject: [PATCH 3/7] greptileai comments fixes --- .../guardrail_hooks/ovalix/ovalix.py | 160 +++++------------ .../guardrails/guardrail_hooks/test_ovalix.py | 164 ++++++++++-------- 2 files changed, 132 insertions(+), 192 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py index d962057617e9..d7fa8a286bc0 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py +++ b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py @@ -5,12 +5,12 @@ """ import datetime +import hashlib import os from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Type import httpx -import litellm from litellm._logging import verbose_proxy_logger from litellm.exceptions import GuardrailRaisedException from litellm.integrations.custom_guardrail import ( @@ -22,7 +22,7 @@ httpxSpecialProvider, ) from litellm.types.guardrails import GuardrailEventHooks -from litellm.types.utils import AllMessageValues, GenericGuardrailAPIInputs +from litellm.types.utils import GenericGuardrailAPIInputs if TYPE_CHECKING: from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel @@ -30,7 +30,6 @@ BLOCKED_BY_OVALIX_FALLBACK_MESSAGE = "This message was blocked by Ovalix" BLOCKED_ACTION_TYPE = "block" -USER_MESSAGE_ROLE = "user" class OvalixGuardrailMissingSecrets(Exception): @@ -181,7 +180,7 @@ def _get_actor(self, data: dict) -> str: def _get_session_id(self, data: dict) -> str: """Return a unique identifier for the chat/session (actor + date + application_id).""" - actor = hash(self._get_actor(data)) + actor = hashlib.sha256(self._get_actor(data).encode()).hexdigest()[:8] today = datetime.datetime.now().strftime("%Y-%m-%d") return f"{actor}_{today}_{self._application_id}" @@ -239,124 +238,36 @@ async def apply_guardrail( actor = self._get_actor(request_data) session_id = self._get_session_id(request_data) + texts = inputs.get("texts") or [] + if not texts or not isinstance(texts, list): + return inputs if input_type == "response": - llm_response = self._get_llm_response_text( - request_data.get("response", None) + if not self._post_checkpoint_id: + return inputs + corrected_llm_responses = await self._generate_post_guardrail_llm_texts( + texts, actor, session_id, self._post_checkpoint_id ) - if llm_response: - ( - corrected_llm_response, - is_blocked, - ) = await self._handle_post_llm_response( - llm_response, actor, session_id - ) - # TODO: set the llm response text to `corrected_llm_response`. will be addressed later. - return inputs - - messages = inputs.get("structured_messages") or [] - if not messages: - return inputs + return {**inputs, "texts": corrected_llm_responses} if self._pre_checkpoint_id: - post_guardrail_texts = await self._generate_post_guardrail_text( - messages, actor, session_id + post_guardrail_texts = await self._generate_post_guardrail_llm_texts( + texts, actor, session_id, self._pre_checkpoint_id ) return {**inputs, "texts": post_guardrail_texts} return inputs - def _block_current_message(self, blocking_message: str) -> None: - """Raise OvalixGuardrailBlockedException with the given message (no default wrapper).""" - raise OvalixGuardrailBlockedException( - guardrail_name=self.guardrail_name, - message=blocking_message, - should_wrap_with_default_message=False, - ) - - def _get_llm_response_text( - self, response: Optional[litellm.ModelResponse] - ) -> Optional[str]: - """Extract the first assistant text content from a ModelResponse, or None.""" - if not response: - return None - if isinstance(response, litellm.ModelResponse): - for choice in response.choices: - if isinstance(choice, litellm.Choices): - if choice.message.content and isinstance( - choice.message.content, str - ): - return choice.message.content - return None - - async def _handle_post_llm_response( - self, llm_response: str, actor: str, session_id: str - ) -> tuple[str, bool]: - """Run post-call checkpoint on model output; return corrected text or raise if blocked.""" - if not self._post_checkpoint_id: - raise ValueError( - "Ovalix: post-checkpoint ID is required for post_call handling." - ) - - try: - resp = await self._call_checkpoint( - llm_response, self._post_checkpoint_id, actor, session_id - ) - except Exception as e: - verbose_proxy_logger.exception( - "Ovalix apply_guardrail checkpoint call failed: %s", e - ) - raise GuardrailRaisedException( - guardrail_name=self.guardrail_name, - message=f"Ovalix guardrail error: {e!s}", - should_wrap_with_default_message=False, - ) from e - - action_type = (resp.get("action_type") or "").lower() - if action_type == BLOCKED_ACTION_TYPE: - blocking_message = ( - self._get_trackers_corrected_message(resp) - or BLOCKED_BY_OVALIX_FALLBACK_MESSAGE - ) - return blocking_message, True - return self._get_trackers_corrected_message(resp) or llm_response, False - - async def _generate_post_guardrail_text( - self, - messages: List[AllMessageValues], - actor: str, - session_id: str, + async def _generate_post_guardrail_llm_texts( + self, texts: List[str], actor: str, session_id: str, checkpoint_id: str ) -> List[str]: - """ - Generate post-guardrail text for the given messages. - - Args: - messages: List of messages - actor: Actor - session_id: Session ID - request_data: Request data - - Returns: - List of post-guardrail texts - """ - is_last_prompt = True + """Generate post-guardrail LLM responses for the given LLM responses.""" post_guardrail_texts: List[str] = [] - if not self._pre_checkpoint_id: - # should not happen - if it does, the guardrail is not configured correctly and self._validate_config did not raise an error - raise ValueError("Ovalix: pre-checkpoint ID is required") - - for message in reversed(messages): - content = message.get("content", None) or "" - if not isinstance(content, str): - continue - message_role = message.get("role", None) - if message_role and message_role != USER_MESSAGE_ROLE: - # we are not scanning the assistant/system/developer past responses, only the responses that the user sent - post_guardrail_texts.insert(0, content) - continue + is_first_response = True + for llm_response in reversed(texts): try: resp = await self._call_checkpoint( - content, self._pre_checkpoint_id, actor, session_id + llm_response, checkpoint_id, actor, session_id ) except Exception as e: verbose_proxy_logger.exception( @@ -369,21 +280,30 @@ async def _generate_post_guardrail_text( ) from e action_type = (resp.get("action_type") or "").lower() - if action_type == BLOCKED_ACTION_TYPE: - blocking_message = ( - self._get_trackers_corrected_message(resp) - or BLOCKED_BY_OVALIX_FALLBACK_MESSAGE - ) - if is_last_prompt: - self._block_current_message(blocking_message) - else: - post_guardrail_texts.insert(0, blocking_message) + blocking_message = ( + self._get_trackers_corrected_message(resp) + or BLOCKED_BY_OVALIX_FALLBACK_MESSAGE + ) + if action_type == BLOCKED_ACTION_TYPE and is_first_response: + self._block_current_message(blocking_message) + elif action_type == BLOCKED_ACTION_TYPE: + post_guardrail_texts.insert(0, blocking_message) else: - new_content = self._get_trackers_corrected_message(resp) or content - post_guardrail_texts.insert(0, new_content) - is_last_prompt = False + corrected_text = ( + self._get_trackers_corrected_message(resp) or llm_response + ) + post_guardrail_texts.insert(0, corrected_text) + is_first_response = False return post_guardrail_texts + def _block_current_message(self, blocking_message: str) -> None: + """Raise OvalixGuardrailBlockedException with the given message (no default wrapper).""" + raise OvalixGuardrailBlockedException( + guardrail_name=self.guardrail_name, + message=blocking_message, + should_wrap_with_default_message=False, + ) + def _get_trackers_corrected_message(self, resp: dict) -> Optional[str]: """Extract corrected/blocking message content from Tracker checkpoint response.""" modified = resp.get("modified_data") diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py index a76267e808e4..cc2daedfb7fb 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py @@ -3,6 +3,7 @@ with mocked Tracker service responses (allow, anonymize, block). """ import os +from typing import Any, List from unittest.mock import AsyncMock, MagicMock, patch import httpx @@ -196,7 +197,8 @@ async def test_apply_guardrail_request_allow_passes_through(self): try: guardrail = OvalixGuardrail(**_guardrail_kwargs()) inputs = GenericGuardrailAPIInputs( - structured_messages=[{"role": "user", "content": "how are you?"}] + structured_messages=[{"role": "user", "content": "how are you?"}], + texts=["how are you?"], ) request_data = {} @@ -232,7 +234,8 @@ async def test_apply_guardrail_request_anonymize_returns_modified_text(self): inputs = GenericGuardrailAPIInputs( structured_messages=[ {"role": "user", "content": "Hello, my name is David."} - ] + ], + texts=["Hello, my name is David."], ) request_data = {} @@ -266,7 +269,8 @@ async def test_apply_guardrail_request_block_raises_with_tracker_message(self): try: guardrail = OvalixGuardrail(**_guardrail_kwargs()) inputs = GenericGuardrailAPIInputs( - structured_messages=[{"role": "user", "content": "I am 15 YO"}] + structured_messages=[{"role": "user", "content": "I am 15 YO"}], + texts=["I am 15 YO"], ) request_data = {} @@ -305,7 +309,8 @@ async def test_apply_guardrail_request_block_non_last_replaced_in_texts(self): structured_messages=[ {"role": "user", "content": "I am 15 YO"}, {"role": "user", "content": "how are you?"}, - ] + ], + texts=["I am 15 YO", "how are you?"], ) request_data = {} @@ -343,13 +348,18 @@ def side_effect(*args, **kwargs): @pytest.mark.asyncio async def test_apply_guardrail_response_allow_returns_inputs(self): - """When input_type is response and Tracker allows, apply_guardrail returns inputs unchanged.""" + """When input_type is response and Tracker allows, apply_guardrail returns inputs with texts updated from Tracker.""" for k, v in _ovalix_env().items(): os.environ[k] = v try: guardrail = OvalixGuardrail(**_guardrail_kwargs()) - inputs = GenericGuardrailAPIInputs() - request_data = {"response": None} + inputs = GenericGuardrailAPIInputs( + structured_messages=[ + {"role": "assistant", "content": "Safe assistant reply"} + ], + texts=["Safe assistant reply"], + ) + request_data = {} mock_response = MagicMock() mock_response.json.return_value = TRACKER_RESPONSE_ALLOW @@ -357,11 +367,7 @@ async def test_apply_guardrail_response_allow_returns_inputs(self): with patch.object( guardrail._async_handler, "post", new_callable=AsyncMock - ) as mock_post, patch.object( - guardrail, - "_get_llm_response_text", - return_value="Safe assistant reply", - ): + ) as mock_post: mock_post.return_value = mock_response result = await guardrail.apply_guardrail( inputs=inputs, @@ -370,7 +376,7 @@ async def test_apply_guardrail_response_allow_returns_inputs(self): logging_obj=None, ) - assert result == inputs + assert result.get("texts") == ["how are you?"] assert mock_post.call_count == 1 finally: for k in _ovalix_env(): @@ -378,74 +384,33 @@ async def test_apply_guardrail_response_allow_returns_inputs(self): del os.environ[k] @pytest.mark.asyncio - async def test_apply_guardrail_response_block_returns_inputs( - self, guardrail_with_env - ): - """When Tracker blocks on response, apply_guardrail still returns inputs (no raise).""" - guardrail = guardrail_with_env - inputs = GenericGuardrailAPIInputs() - request_data = {"response": None} - - mock_response = MagicMock() - mock_response.json.return_value = TRACKER_RESPONSE_BLOCK - mock_response.raise_for_status = MagicMock() - - with patch.object( - guardrail._async_handler, "post", new_callable=AsyncMock - ) as mock_post, patch.object( - guardrail, - "_get_llm_response_text", - return_value="I am 15 YO", - ): - mock_post.return_value = mock_response - result = await guardrail.apply_guardrail( - inputs=inputs, - request_data=request_data, - input_type="response", - logging_obj=None, - ) - - assert result == inputs - assert mock_post.call_count == 1 - - @pytest.mark.asyncio - async def test_apply_guardrail_request_non_user_messages_not_sent_to_tracker( - self, guardrail_with_env - ): - """Only user messages are sent to Tracker; system/assistant content is passed through.""" + async def test_apply_guardrail_response_block_raises(self, guardrail_with_env): + """When Tracker blocks on response, apply_guardrail raises OvalixGuardrailBlockedException.""" guardrail = guardrail_with_env inputs = GenericGuardrailAPIInputs( - structured_messages=[ - {"role": "system", "content": "You are helpful."}, - {"role": "user", "content": "hello"}, - ] + structured_messages=[{"role": "user", "content": "I am 15 YO"}], + texts=["I am 15 YO"], ) request_data = {} - # Tracker allows and returns same content for the user message - allow_hello = { - "action_type": "allow", - "data_type": "TEXT", - "original_data": {"content": "hello"}, - "modified_data": {"content": "hello"}, - "alerts": [], - } mock_response = MagicMock() - mock_response.json.return_value = allow_hello + mock_response.json.return_value = TRACKER_RESPONSE_BLOCK mock_response.raise_for_status = MagicMock() with patch.object( guardrail._async_handler, "post", new_callable=AsyncMock ) as mock_post: mock_post.return_value = mock_response - result = await guardrail.apply_guardrail( - inputs=inputs, - request_data=request_data, - input_type="request", - logging_obj=None, - ) + with pytest.raises(OvalixGuardrailBlockedException) as exc_info: + await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="response", + logging_obj=None, + ) - assert result.get("texts") == ["You are helpful.", "hello"] + assert "This message was blocked by Ovalix" in str(exc_info.value.message) + assert exc_info.value.status_code == 400 assert mock_post.call_count == 1 @pytest.mark.asyncio @@ -455,7 +420,8 @@ async def test_apply_guardrail_request_missing_modified_data_uses_original_conte """When Tracker response has no modified_data.content, original content is used.""" guardrail = guardrail_with_env inputs = GenericGuardrailAPIInputs( - structured_messages=[{"role": "user", "content": "original text"}] + structured_messages=[{"role": "user", "content": "original text"}], + texts=["original text"], ) request_data = {} @@ -490,7 +456,8 @@ async def test_apply_guardrail_tracker_http_error_raises_guardrail_exception( """When Tracker returns HTTP error (e.g. 400), GuardrailRaisedException is raised.""" guardrail = guardrail_with_env inputs = GenericGuardrailAPIInputs( - structured_messages=[{"role": "user", "content": "hello"}] + structured_messages=[{"role": "user", "content": "hello"}], + texts=["hello"], ) request_data = {} @@ -523,7 +490,8 @@ async def test_apply_guardrail_checkpoint_error_raises_guardrail_exception(self) try: guardrail = OvalixGuardrail(**_guardrail_kwargs()) inputs = GenericGuardrailAPIInputs( - structured_messages=[{"role": "user", "content": "hello"}] + structured_messages=[{"role": "user", "content": "hello"}], + texts=["hello"], ) request_data = {} @@ -552,7 +520,7 @@ async def test_apply_guardrail_request_empty_messages_returns_inputs(self): os.environ[k] = v try: guardrail = OvalixGuardrail(**_guardrail_kwargs()) - inputs = GenericGuardrailAPIInputs(structured_messages=[]) + inputs = GenericGuardrailAPIInputs(structured_messages=[], texts=[]) request_data = {} with patch.object( @@ -619,3 +587,55 @@ def test_get_session_id_deterministic_and_includes_app_id(self, guardrail_with_e session_id_2 = guardrail._get_session_id(data) assert session_id_1 == session_id_2 assert "app-1" in session_id_1 + + def test_block_current_message_raises_ovalix_blocked_exception( + self, guardrail_with_env + ): + """_block_current_message raises OvalixGuardrailBlockedException with status_code 400.""" + guardrail = guardrail_with_env + with pytest.raises(OvalixGuardrailBlockedException) as exc_info: + guardrail._block_current_message("Custom block reason") + assert "Custom block reason" in str(exc_info.value.message) + assert exc_info.value.status_code == 400 + + def test_get_trackers_corrected_message(self, guardrail_with_env): + """_get_trackers_corrected_message returns modified_data.content or None.""" + guardrail = guardrail_with_env + assert ( + guardrail._get_trackers_corrected_message( + {"modified_data": {"content": "corrected text"}} + ) + == "corrected text" + ) + assert guardrail._get_trackers_corrected_message({"modified_data": {}}) is None + assert ( + guardrail._get_trackers_corrected_message({"modified_data": "not-a-dict"}) + is None + ) + + @pytest.mark.asyncio + async def test_apply_guardrail_response_no_texts_returns_unchanged(self): + """When input_type is response and inputs have no texts, apply_guardrail returns inputs without calling Tracker.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs() + request_data = {} + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="response", + logging_obj=None, + ) + + assert result == inputs + mock_post.assert_not_called() + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] From 65d2e40202b09f80b4acd4988ed5c7ddf8634c22 Mon Sep 17 00:00:00 2001 From: Shalom Jamil Date: Thu, 23 Apr 2026 13:07:08 +0300 Subject: [PATCH 4/7] fix conflict --- litellm/types/guardrails.py | 1 + 1 file changed, 1 insertion(+) diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py index 1c2826bebf70..b3782e617987 100644 --- a/litellm/types/guardrails.py +++ b/litellm/types/guardrails.py @@ -25,6 +25,7 @@ ) from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( OvalixGuardrailConfigModel, +) from litellm.types.proxy.guardrails.guardrail_hooks.promptguard import ( PromptGuardConfigModel, ) From 57343cc281ac22c29d5058dc0985443aedb5220b Mon Sep 17 00:00:00 2001 From: Shalom Jamil Date: Wed, 29 Apr 2026 13:16:25 +0300 Subject: [PATCH 5/7] fixes --- .../guardrails/guardrail_hooks/ovalix/ovalix.py | 14 +++++++++----- .../guardrails/guardrail_hooks/test_ovalix.py | 16 ++++++++++++++-- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py index d7fa8a286bc0..7fc4475ac953 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py +++ b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py @@ -178,11 +178,15 @@ def _get_actor(self, data: dict) -> str: return metadata["user_api_key_user_id"] return "unknown" + def _get_tracker_actor_id(self, data: dict) -> str: + """Opaque actor id for Tracker API payloads (hash of _get_actor; avoids sending PII).""" + return hashlib.sha256(self._get_actor(data).encode()).hexdigest()[:8] + def _get_session_id(self, data: dict) -> str: """Return a unique identifier for the chat/session (actor + date + application_id).""" - actor = hashlib.sha256(self._get_actor(data).encode()).hexdigest()[:8] + actor_hash = self._get_tracker_actor_id(data) today = datetime.datetime.now().strftime("%Y-%m-%d") - return f"{actor}_{today}_{self._application_id}" + return f"{actor_hash}_{today}_{self._application_id}" async def _call_checkpoint( self, @@ -236,7 +240,7 @@ async def apply_guardrail( if not self._pre_checkpoint_id and not self._post_checkpoint_id: return inputs - actor = self._get_actor(request_data) + tracker_actor_id = self._get_tracker_actor_id(request_data) session_id = self._get_session_id(request_data) texts = inputs.get("texts") or [] if not texts or not isinstance(texts, list): @@ -246,13 +250,13 @@ async def apply_guardrail( if not self._post_checkpoint_id: return inputs corrected_llm_responses = await self._generate_post_guardrail_llm_texts( - texts, actor, session_id, self._post_checkpoint_id + texts, tracker_actor_id, session_id, self._post_checkpoint_id ) return {**inputs, "texts": corrected_llm_responses} if self._pre_checkpoint_id: post_guardrail_texts = await self._generate_post_guardrail_llm_texts( - texts, actor, session_id, self._pre_checkpoint_id + texts, tracker_actor_id, session_id, self._pre_checkpoint_id ) return {**inputs, "texts": post_guardrail_texts} return inputs diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py index cc2daedfb7fb..4160a835ca43 100644 --- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py @@ -2,6 +2,7 @@ Unit tests for Ovalix guardrail: config resolution and apply_guardrail behavior with mocked Tracker service responses (allow, anonymize, block). """ + import os from typing import Any, List from unittest.mock import AsyncMock, MagicMock, patch @@ -167,7 +168,7 @@ async def test_call_checkpoint_sends_correct_payload_and_returns_json(self): result = await guardrail._call_checkpoint( content="hello", checkpoint_id="pre-1", - actor="user@test.com", + actor="a1b2c3d4", session_id="session-1", ) @@ -180,7 +181,7 @@ async def test_call_checkpoint_sends_correct_payload_and_returns_json(self): body = call_args.kwargs["json"] assert body["application_id"] == "app-1" assert body["checkpoint_id"] == "pre-1" - assert body["actor"] == "user@test.com" + assert body["actor"] == "a1b2c3d4" assert body["session_id"] == "session-1" assert body["data_type"] == "TEXT" assert body["data"] == {"content": "hello"} @@ -579,6 +580,17 @@ def test_get_actor_prefers_email_over_id(self, guardrail_with_env): } assert guardrail._get_actor(data) == "primary@test.com" + def test_get_tracker_actor_id_is_hash_not_raw_pii(self, guardrail_with_env): + """Tracker API actor field uses a short hash of _get_actor, not email/user id.""" + guardrail = guardrail_with_env + data = {"metadata": {"user_api_key_user_email": "user@example.com"}} + raw = guardrail._get_actor(data) + hashed = guardrail._get_tracker_actor_id(data) + assert raw == "user@example.com" + assert hashed != raw + assert len(hashed) == 8 + assert all(c in "0123456789abcdef" for c in hashed) + def test_get_session_id_deterministic_and_includes_app_id(self, guardrail_with_env): """Session ID is stable for same actor/day and includes application_id.""" guardrail = guardrail_with_env From 99f8e1dcc7796fdff64063182fec50567b195f26 Mon Sep 17 00:00:00 2001 From: Shalom Jamil Date: Wed, 29 Apr 2026 14:04:32 +0300 Subject: [PATCH 6/7] fix sha256 --- .../guardrails/guardrail_hooks/ovalix/ovalix.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py index 7fc4475ac953..1cd7238e2bc8 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py +++ b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py @@ -31,6 +31,9 @@ BLOCKED_BY_OVALIX_FALLBACK_MESSAGE = "This message was blocked by Ovalix" BLOCKED_ACTION_TYPE = "block" +# Fixed salt so actor/session fingerprints are deterministic per LiteLLM release salt version. +_OVALIX_TRACKER_ACTOR_SCRYPT_SALT = b"litellm-ovalix-tracker-actor-v1" + class OvalixGuardrailMissingSecrets(Exception): """Raised when required Ovalix config (API base, key, application/checkpoint IDs) is missing.""" @@ -179,8 +182,17 @@ def _get_actor(self, data: dict) -> str: return "unknown" def _get_tracker_actor_id(self, data: dict) -> str: - """Opaque actor id for Tracker API payloads (hash of _get_actor; avoids sending PII).""" - return hashlib.sha256(self._get_actor(data).encode()).hexdigest()[:8] + """Opaque actor id for Tracker API payloads (scrypt KDF of _get_actor; avoids sending PII).""" + material = self._get_actor(data).encode() + dk = hashlib.scrypt( + material, + salt=_OVALIX_TRACKER_ACTOR_SCRYPT_SALT, + n=16384, + r=8, + p=1, + dklen=32, + ) + return dk.hex()[:8] def _get_session_id(self, data: dict) -> str: """Return a unique identifier for the chat/session (actor + date + application_id).""" From 0ab2f5fb2d6d2ab32867675416adca4326bb8e26 Mon Sep 17 00:00:00 2001 From: Shalom Jamil Date: Thu, 11 Jun 2026 12:12:29 +0300 Subject: [PATCH 7/7] clarify Ovalix actor-id hash is for normalization, not PII protection --- .../guardrail_hooks/ovalix/ovalix.py | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py index 1cd7238e2bc8..bad132092dc3 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py +++ b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py @@ -31,9 +31,6 @@ BLOCKED_BY_OVALIX_FALLBACK_MESSAGE = "This message was blocked by Ovalix" BLOCKED_ACTION_TYPE = "block" -# Fixed salt so actor/session fingerprints are deterministic per LiteLLM release salt version. -_OVALIX_TRACKER_ACTOR_SCRYPT_SALT = b"litellm-ovalix-tracker-actor-v1" - class OvalixGuardrailMissingSecrets(Exception): """Raised when required Ovalix config (API base, key, application/checkpoint IDs) is missing.""" @@ -182,17 +179,14 @@ def _get_actor(self, data: dict) -> str: return "unknown" def _get_tracker_actor_id(self, data: dict) -> str: - """Opaque actor id for Tracker API payloads (scrypt KDF of _get_actor; avoids sending PII).""" - material = self._get_actor(data).encode() - dk = hashlib.scrypt( - material, - salt=_OVALIX_TRACKER_ACTOR_SCRYPT_SALT, - n=16384, - r=8, - p=1, - dklen=32, - ) - return dk.hex()[:8] + """Normalize the actor string into a short, stable id for Tracker API payloads.""" + # NOTE: this hash is purely for normalization — it collapses an arbitrary actor + # string (email, user id, or "unknown") into a compact, fixed-length, consistent + # key. It is not a privacy/security measure and the actor value is not sensitive, + # so a plain SHA-256 (truncated) is sufficient; no salting/KDF is needed here. + actor_id = self._get_actor(data).encode() + normalized_actor_id = hashlib.sha256(actor_id).hexdigest()[:8] + return normalized_actor_id def _get_session_id(self, data: dict) -> str: """Return a unique identifier for the chat/session (actor + date + application_id)."""