|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""Content safety rail actions for IORails.""" |
| 17 | + |
| 18 | +from typing import Any, Optional |
| 19 | + |
| 20 | +from nemoguardrails.guardrails.guardrails_types import LLMMessages, RailResult |
| 21 | +from nemoguardrails.guardrails.rail_action import RailAction |
| 22 | + |
| 23 | +_MAX_TOKENS = 3 |
| 24 | +_TEMPERATURE = 1e-20 |
| 25 | + |
| 26 | + |
| 27 | +class ContentSafetyInputAction(RailAction): |
| 28 | + """Check user input for content safety violations.""" |
| 29 | + |
| 30 | + action_name = "content safety check input" |
| 31 | + requires_model = True |
| 32 | + |
| 33 | + def _extract_messages(self, messages: LLMMessages, bot_response: Optional[str]) -> dict[str, Any]: |
| 34 | + return {"user_input": self._last_user_content(messages)} |
| 35 | + |
| 36 | + def _create_prompt(self, model_type: Optional[str], extracted: dict[str, Any]) -> list[dict]: |
| 37 | + prompt_task_key = f"content_safety_check_input $model={model_type}" |
| 38 | + content_safety_config = self.task_manager.config.rails.config.content_safety |
| 39 | + if content_safety_config is None: |
| 40 | + raise RuntimeError("content_safety config is required for content safety rail") |
| 41 | + reasoning_enabled = content_safety_config.reasoning.enabled |
| 42 | + |
| 43 | + prompt = self.task_manager.render_task_prompt( |
| 44 | + task=prompt_task_key, |
| 45 | + context={"user_input": extracted["user_input"], "reasoning_enabled": reasoning_enabled}, |
| 46 | + ) |
| 47 | + return self._prompt_to_messages(prompt) |
| 48 | + |
| 49 | + async def _get_response(self, model_type: Optional[str], prompt: Any) -> str: |
| 50 | + prompt_task_key = f"content_safety_check_input $model={model_type}" |
| 51 | + |
| 52 | + stop = self.task_manager.get_stop_tokens(task=prompt_task_key) |
| 53 | + max_tokens = self.task_manager.get_max_tokens(task=prompt_task_key) or _MAX_TOKENS |
| 54 | + kwargs: dict = {"temperature": _TEMPERATURE, "max_tokens": max_tokens} |
| 55 | + if stop: |
| 56 | + kwargs["stop"] = stop |
| 57 | + |
| 58 | + response_text = await self._get_llm_response(model_type, prompt, **kwargs) |
| 59 | + |
| 60 | + # Parse via LLMTaskManager's registered output parser |
| 61 | + return self.task_manager.parse_task_output(task=prompt_task_key, output=response_text) # type: ignore[arg-type] |
| 62 | + |
| 63 | + def _parse_response(self, response: Any) -> RailResult: |
| 64 | + return _content_safety_to_rail_result(response) |
| 65 | + |
| 66 | + |
| 67 | +class ContentSafetyOutputAction(RailAction): |
| 68 | + """Check bot response for content safety violations.""" |
| 69 | + |
| 70 | + action_name = "content safety check output" |
| 71 | + |
| 72 | + def _extract_messages(self, messages: LLMMessages, bot_response: Optional[str]) -> dict[str, Any]: |
| 73 | + if not bot_response: |
| 74 | + raise RuntimeError("bot_response is required for content safety output check") |
| 75 | + return { |
| 76 | + "user_input": self._last_user_content(messages), |
| 77 | + "bot_response": bot_response, |
| 78 | + } |
| 79 | + |
| 80 | + def _create_prompt(self, model_type: Optional[str], extracted: dict[str, Any]) -> list[dict]: |
| 81 | + prompt_task_key = f"content_safety_check_output $model={model_type}" |
| 82 | + content_safety_config = self.task_manager.config.rails.config.content_safety |
| 83 | + if content_safety_config is None: |
| 84 | + raise RuntimeError("content_safety config is required for content safety rail") |
| 85 | + reasoning_enabled = content_safety_config.reasoning.enabled |
| 86 | + |
| 87 | + prompt = self.task_manager.render_task_prompt( |
| 88 | + task=prompt_task_key, |
| 89 | + context={ |
| 90 | + "user_input": extracted["user_input"], |
| 91 | + "bot_response": extracted["bot_response"], |
| 92 | + "reasoning_enabled": reasoning_enabled, |
| 93 | + }, |
| 94 | + ) |
| 95 | + return self._prompt_to_messages(prompt) |
| 96 | + |
| 97 | + async def _get_response(self, model_type: Optional[str], prompt: Any) -> str: |
| 98 | + prompt_task_key = f"content_safety_check_output $model={model_type}" |
| 99 | + |
| 100 | + stop = self.task_manager.get_stop_tokens(task=prompt_task_key) |
| 101 | + max_tokens = self.task_manager.get_max_tokens(task=prompt_task_key) or _MAX_TOKENS |
| 102 | + kwargs: dict = {"temperature": _TEMPERATURE, "max_tokens": max_tokens} |
| 103 | + if stop: |
| 104 | + kwargs["stop"] = stop |
| 105 | + |
| 106 | + response_text = await self._get_llm_response(model_type, prompt, **kwargs) |
| 107 | + return self.task_manager.parse_task_output(task=prompt_task_key, output=response_text) # type: ignore[arg-type] |
| 108 | + |
| 109 | + def _parse_response(self, response: Any) -> RailResult: |
| 110 | + return _content_safety_to_rail_result(response) |
| 111 | + |
| 112 | + |
| 113 | +def _content_safety_to_rail_result(parsed: object) -> RailResult: |
| 114 | + """Convert nemoguard parser output to RailResult. |
| 115 | +
|
| 116 | + nemoguard_parse_prompt_safety / nemoguard_parse_response_safety return: |
| 117 | + [True] -> safe |
| 118 | + [False, "S1: Violence", ...] -> unsafe with categories |
| 119 | + """ |
| 120 | + if isinstance(parsed, (list, tuple)): |
| 121 | + if parsed and parsed[0] is True: |
| 122 | + return RailResult(is_safe=True) |
| 123 | + if parsed and parsed[0] is False: |
| 124 | + if len(parsed) > 1: |
| 125 | + categories = ", ".join(str(c) for c in parsed[1:]) |
| 126 | + return RailResult(is_safe=False, reason=f"Safety categories: {categories}") |
| 127 | + return RailResult(is_safe=False, reason="Unknown") |
| 128 | + raise RuntimeError(f"Unexpected content safety parse result: {parsed}") |
0 commit comments