-
Notifications
You must be signed in to change notification settings - Fork 564
feat(content_safety): add support to auto select multilingual refusal bot messages #1530
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Pouyanpi
wants to merge
3
commits into
develop
Choose a base branch
from
feat/multilang-content-safety
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| models: | ||
| - type: main | ||
| engine: nim | ||
| model: meta/llama-3.3-70b-instruct | ||
|
|
||
| - type: content_safety | ||
| engine: nim | ||
| model: nvidia/llama-3.1-nemotron-safety-guard-8b-v3 | ||
|
|
||
| rails: | ||
| config: | ||
| content_safety: | ||
| multilingual: | ||
| enabled: true | ||
| # Optional: customize refusal messages per language | ||
| # If not specified, built-in defaults are used | ||
| # refusal_messages: | ||
| # en: "Sorry, I cannot help with that request." | ||
| # es: "Lo siento, no puedo ayudar con esa solicitud." | ||
| # zh: "抱歉,我无法处理该请求。" | ||
|
|
||
| input: | ||
| flows: | ||
| - content safety check input $model=content_safety | ||
|
|
||
| output: | ||
| flows: | ||
| - content safety check output $model=content_safety | ||
|
|
||
| # 你很笨 (nǐ hěn bèn) — “You are stupid / you are foolish.” |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| prompts: | ||
| - task: content_safety_check_input $model=content_safety | ||
| content: | | ||
| Task: Check if there is unsafe content in the user or agent messages in the below conversation in accordance with our safety policy with the below categories. Provide a 'safe' or 'unsafe' rating for both the user message and the agent response. If there is unsafe content, please also provide a list of violated categories according to our safety policy below. | ||
|
|
||
| <BEGIN UNSAFE CONTENT CATEGORIES> | ||
| S1: Violence. | ||
| S2: Sexual. | ||
| S3: Criminal Planning/Confessions. | ||
| S4: Guns and Illegal Weapons. | ||
| S5: Controlled/Regulated Substances. | ||
| S6: Suicide and Self Harm. | ||
| S7: Sexual (minor). | ||
| S8: Hate/Identity Hate. | ||
| S9: PII/Privacy. | ||
| S10: Harassment. | ||
| S11: Threat. | ||
| S12: Profanity. | ||
| S13: Needs Caution. | ||
| S14: Other. | ||
| S15: Manipulation. | ||
| S16: Fraud/Deception. | ||
| S17: Malware. | ||
| S18: High Risk Gov Decision Making. | ||
| S19: Political/Misinformation/Conspiracy. | ||
| S20: Copyright/Trademark/Plagiarism. | ||
| S21: Unauthorized Advice. | ||
| S22: Illegal Activity. | ||
| S23: Immoral/Unethical. | ||
| <END UNSAFE CONTENT CATEGORIES> | ||
|
|
||
| <BEGIN CONVERSATION> | ||
|
|
||
| user: {{ user_input }} | ||
|
|
||
| <END CONVERSATION> | ||
|
|
||
| Provide your safety assessment for the above conversation in the below output JSON format: | ||
| {"User Safety": safe or unsafe rating for the user message, "Response Safety": safe or unsafe rating for the agent response. Omit if no agent response present. "Safety Categories": a comma-separated list of applicable safety categories from the provided taxonomy. Omit if all safe.} | ||
|
|
||
| Do not include anything other than the output JSON in your response. | ||
| Output JSON: | ||
| output_parser: nemoguard_parse_prompt_safety | ||
| max_tokens: 50 | ||
|
|
||
| - task: content_safety_check_output $model=content_safety | ||
| content: | | ||
| Task: Check if there is unsafe content in the user or agent messages in the below conversation in accordance with our safety policy with the below categories. Provide a 'safe' or 'unsafe' rating for both the user message and the agent response. If there is unsafe content, please also provide a list of violated categories according to our safety policy below. | ||
|
|
||
| <BEGIN UNSAFE CONTENT CATEGORIES> | ||
| S1: Violence. | ||
| S2: Sexual. | ||
| S3: Criminal Planning/Confessions. | ||
| S4: Guns and Illegal Weapons. | ||
| S5: Controlled/Regulated Substances. | ||
| S6: Suicide and Self Harm. | ||
| S7: Sexual (minor). | ||
| S8: Hate/Identity Hate. | ||
| S9: PII/Privacy. | ||
| S10: Harassment. | ||
| S11: Threat. | ||
| S12: Profanity. | ||
| S13: Needs Caution. | ||
| S14: Other. | ||
| S15: Manipulation. | ||
| S16: Fraud/Deception. | ||
| S17: Malware. | ||
| S18: High Risk Gov Decision Making. | ||
| S19: Political/Misinformation/Conspiracy. | ||
| S20: Copyright/Trademark/Plagiarism. | ||
| S21: Unauthorized Advice. | ||
| S22: Illegal Activity. | ||
| S23: Immoral/Unethical. | ||
| <END UNSAFE CONTENT CATEGORIES> | ||
|
|
||
| <BEGIN CONVERSATION> | ||
|
|
||
| user: {{ user_input }} | ||
|
|
||
| response: agent: {{ bot_response }} | ||
|
|
||
| <END CONVERSATION> | ||
|
|
||
| Provide your safety assessment for the above conversation in the below output JSON format: | ||
| {"User Safety": safe or unsafe rating for the user message, "Response Safety": safe or unsafe rating for the agent response. Omit if no agent response present. "Safety Categories": a comma-separated list of applicable safety categories from the provided taxonomy. Omit if all safe.} | ||
|
|
||
| Do not include anything other than the output JSON in your response. | ||
| Output JSON: | ||
| output_parser: nemoguard_parse_response_safety | ||
| max_tokens: 50 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,7 +14,7 @@ | |
| # limitations under the License. | ||
|
|
||
| import logging | ||
| from typing import Dict, Optional | ||
| from typing import Dict, FrozenSet, Optional | ||
|
|
||
| from langchain_core.language_models import BaseLLM | ||
|
|
||
|
|
@@ -220,3 +220,79 @@ async def content_safety_check_output( | |
| log.debug(f"Content safety output result cached for model '{model_name}'") | ||
|
|
||
| return final_result | ||
|
|
||
|
|
||
| SUPPORTED_LANGUAGES: FrozenSet[str] = frozenset({"en", "es", "zh", "de", "fr", "hi", "ja", "ar", "th"}) | ||
|
|
||
| DEFAULT_REFUSAL_MESSAGES: Dict[str, str] = { | ||
| "en": "I'm sorry, I can't respond to that.", | ||
| "es": "Lo siento, no puedo responder a eso.", | ||
| "zh": "抱歉,我无法回应。", | ||
| "de": "Es tut mir leid, darauf kann ich nicht antworten.", | ||
| "fr": "Je suis désolé, je ne peux pas répondre à cela.", | ||
| "hi": "मुझे खेद है, मैं इसका जवाब नहीं दे सकता।", | ||
| "ja": "申し訳ありませんが、それには回答できません。", | ||
| "ar": "عذراً، لا أستطيع الرد على ذلك.", | ||
| "th": "ขออภัย ฉันไม่สามารถตอบได้", | ||
| } | ||
|
|
||
|
|
||
| def _detect_language(text: str) -> Optional[str]: | ||
| try: | ||
| from fast_langdetect import detect | ||
|
|
||
| result = detect(text, k=1) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does fast-langdetect ever return a full locale with dialect, like en-US versus en? I don't see it in the docs, but I do see some upper/lowercase inconsistency. |
||
| if result and len(result) > 0: | ||
| return result[0].get("lang") | ||
| return None | ||
| except ImportError: | ||
| log.warning("fast-langdetect not installed, skipping") | ||
| return None | ||
| except Exception as e: | ||
| log.warning(f"fast-langdetect detection failed: {e}") | ||
| return None | ||
|
|
||
|
|
||
| def _get_refusal_message(lang: str, custom_messages: Optional[Dict[str, str]]) -> str: | ||
| if custom_messages and lang in custom_messages: | ||
| return custom_messages[lang] | ||
| if lang in DEFAULT_REFUSAL_MESSAGES: | ||
| return DEFAULT_REFUSAL_MESSAGES[lang] | ||
| if custom_messages and "en" in custom_messages: | ||
| return custom_messages["en"] | ||
| return DEFAULT_REFUSAL_MESSAGES["en"] | ||
|
|
||
|
|
||
| @action() | ||
| async def detect_language( | ||
| context: Optional[dict] = None, | ||
| config: Optional[dict] = None, | ||
| ) -> dict: | ||
| user_message = "" | ||
| if context is not None: | ||
| user_message = context.get("user_message", "") | ||
|
|
||
| custom_messages = None | ||
| if config is not None: | ||
| multilingual_config = ( | ||
| config.rails.config.content_safety.multilingual | ||
| if hasattr(config, "rails") | ||
| and hasattr(config.rails, "config") | ||
| and hasattr(config.rails.config, "content_safety") | ||
| and hasattr(config.rails.config.content_safety, "multilingual") | ||
| else None | ||
| ) | ||
| if multilingual_config: | ||
| custom_messages = multilingual_config.refusal_messages | ||
|
|
||
| lang = _detect_language(user_message) or "en" | ||
|
|
||
| if lang not in SUPPORTED_LANGUAGES: | ||
| lang = "en" | ||
|
|
||
| refusal_message = _get_refusal_message(lang, custom_messages) | ||
|
|
||
| return { | ||
| "language": lang, | ||
| "refusal_message": refusal_message, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If we later had other multilingual rails, would we be repeating this mechanism in each rail? Or just the set of supported languages per rail? I don't think we need to do it now (since we don't have other multilingual rails to test it), but we should be aware of what refactoring would be needed to move the below language detection to a shared level.