|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023 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 | +"""Prompt/Response protection using Prompt Security.""" |
| 17 | + |
| 18 | +import logging |
| 19 | +import os |
| 20 | +from typing import Optional |
| 21 | + |
| 22 | +import httpx |
| 23 | + |
| 24 | +from nemoguardrails.actions import action |
| 25 | + |
| 26 | +log = logging.getLogger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +async def ps_protect_api_async( |
| 30 | + ps_protect_url: str, |
| 31 | + ps_app_id: str, |
| 32 | + prompt: Optional[str] = None, |
| 33 | + system_prompt: Optional[str] = None, |
| 34 | + response: Optional[str] = None, |
| 35 | + user: Optional[str] = None, |
| 36 | +): |
| 37 | + """Calls Prompt Security Protect API asynchronously. |
| 38 | +
|
| 39 | + Args: |
| 40 | + ps_protect_url: the URL of the protect endpoint given by Prompt Security. |
| 41 | + URL is https://[REGION].prompt.security/api/protect where REGION is eu, useast or apac |
| 42 | +
|
| 43 | + ps_app_id: the application ID given by Prompt Security (similar to an API key). |
| 44 | + Get it from the admin portal at https://[REGION].prompt.security/ where REGION is eu, useast or apac |
| 45 | +
|
| 46 | + prompt: the user message to protect. |
| 47 | +
|
| 48 | + system_prompt: the system message for context. |
| 49 | +
|
| 50 | + response: the bot message to protect. |
| 51 | +
|
| 52 | + user: the user ID or username for context. |
| 53 | +
|
| 54 | + Returns: |
| 55 | + A dictionary with the following items: |
| 56 | + - is_blocked: True if the text should be blocked, False otherwise. |
| 57 | + - is_modified: True if the text should be modified, False otherwise. |
| 58 | + - modified_text: The modified text if is_modified is True, None otherwise. |
| 59 | + """ |
| 60 | + |
| 61 | + headers = { |
| 62 | + "APP-ID": ps_app_id, |
| 63 | + "Content-Type": "application/json", |
| 64 | + } |
| 65 | + payload = { |
| 66 | + "prompt": prompt, |
| 67 | + "system_prompt": system_prompt, |
| 68 | + "response": response, |
| 69 | + "user": user, |
| 70 | + } |
| 71 | + async with httpx.AsyncClient() as client: |
| 72 | + modified_text = None |
| 73 | + ps_action = "log" |
| 74 | + try: |
| 75 | + ret = await client.post(ps_protect_url, headers=headers, json=payload) |
| 76 | + res = ret.json() |
| 77 | + ps_action = res.get("result", {}).get("action", "log") |
| 78 | + if ps_action == "modify": |
| 79 | + key = "response" if response else "prompt" |
| 80 | + modified_text = res.get("result", {}).get(key, {}).get("modified_text") |
| 81 | + except Exception as e: |
| 82 | + log.error("Error calling Prompt Security Protect API: %s", e) |
| 83 | + return { |
| 84 | + "is_blocked": ps_action == "block", |
| 85 | + "is_modified": ps_action == "modify", |
| 86 | + "modified_text": modified_text, |
| 87 | + } |
| 88 | + |
| 89 | + |
| 90 | +@action(is_system_action=True) |
| 91 | +async def protect_text( |
| 92 | + user_prompt: Optional[str] = None, bot_response: Optional[str] = None |
| 93 | +): |
| 94 | + """Protects the given user_prompt or bot_response. |
| 95 | + Args: |
| 96 | + user_prompt: The user message to protect. |
| 97 | + bot_response: The bot message to protect. |
| 98 | + Returns: |
| 99 | + A dictionary with the following items: |
| 100 | + - is_blocked: True if the text should be blocked, False otherwise. |
| 101 | + - is_modified: True if the text should be modified, False otherwise. |
| 102 | + - modified_text: The modified text if is_modified is True, None otherwise. |
| 103 | + Raises: |
| 104 | + ValueError is returned in one of the following cases: |
| 105 | + 1. If PS_PROTECT_URL env variable is not set. |
| 106 | + 2. If PS_APP_ID env variable is not set. |
| 107 | + 3. If no user_prompt and no bot_response is provided. |
| 108 | + """ |
| 109 | + |
| 110 | + ps_protect_url = os.getenv("PS_PROTECT_URL") |
| 111 | + if not ps_protect_url: |
| 112 | + raise ValueError("PS_PROTECT_URL env variable is required for Prompt Security.") |
| 113 | + |
| 114 | + ps_app_id = os.getenv("PS_APP_ID") |
| 115 | + if not ps_app_id: |
| 116 | + raise ValueError("PS_APP_ID env variable is required for Prompt Security.") |
| 117 | + |
| 118 | + if bot_response: |
| 119 | + return await ps_protect_api_async( |
| 120 | + ps_protect_url, ps_app_id, None, None, bot_response |
| 121 | + ) |
| 122 | + |
| 123 | + if user_prompt: |
| 124 | + return await ps_protect_api_async(ps_protect_url, ps_app_id, user_prompt) |
| 125 | + |
| 126 | + raise ValueError("Neither user_message nor bot_message was provided") |
0 commit comments