|
| 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 | +PolicyAI Integration for NeMo Guardrails. |
| 17 | +
|
| 18 | +PolicyAI provides content moderation and policy enforcement capabilities |
| 19 | +for LLM applications. This integration allows using PolicyAI as an input |
| 20 | +and output rail for content moderation. |
| 21 | +
|
| 22 | +For more information, see: https://musubilabs.ai |
| 23 | +""" |
| 24 | + |
| 25 | +import json |
| 26 | +import logging |
| 27 | +import os |
| 28 | +from typing import Optional |
| 29 | + |
| 30 | +import aiohttp |
| 31 | + |
| 32 | +from nemoguardrails.actions import action |
| 33 | + |
| 34 | +log = logging.getLogger(__name__) |
| 35 | + |
| 36 | + |
| 37 | +def call_policyai_api_mapping(result: dict) -> bool: |
| 38 | + """ |
| 39 | + Mapping for call_policyai_api. |
| 40 | +
|
| 41 | + Expects result to be a dict with: |
| 42 | + - "assessment": "SAFE" or "UNSAFE" |
| 43 | + - "category": the violation category (if UNSAFE) |
| 44 | + - "severity": severity level 0-3 |
| 45 | +
|
| 46 | + Block (return True) if: |
| 47 | + 1. Assessment is "UNSAFE" |
| 48 | + """ |
| 49 | + assessment = result.get("assessment", "SAFE") |
| 50 | + return assessment == "UNSAFE" |
| 51 | + |
| 52 | + |
| 53 | +@action(is_system_action=True, output_mapping=call_policyai_api_mapping) |
| 54 | +async def call_policyai_api( |
| 55 | + text: Optional[str] = None, |
| 56 | + tag_name: Optional[str] = None, |
| 57 | + **kwargs, |
| 58 | +): |
| 59 | + """ |
| 60 | + Call the PolicyAI API to evaluate content. |
| 61 | +
|
| 62 | + Args: |
| 63 | + text: The text content to evaluate. |
| 64 | + tag_name: Optional tag name for the PolicyAI evaluation. |
| 65 | + If not provided, uses POLICYAI_TAG_NAME env var or "prod". |
| 66 | +
|
| 67 | + Returns: |
| 68 | + dict with: |
| 69 | + - assessment: "SAFE" or "UNSAFE" |
| 70 | + - category: the violation category (if UNSAFE) |
| 71 | + - severity: severity level 0-3 |
| 72 | + - reason: explanation for the decision |
| 73 | + """ |
| 74 | + api_key = os.environ.get("POLICYAI_API_KEY") |
| 75 | + |
| 76 | + if api_key is None: |
| 77 | + raise ValueError("POLICYAI_API_KEY environment variable not set.") |
| 78 | + |
| 79 | + base_url = os.environ.get("POLICYAI_BASE_URL", "https://api.musubilabs.ai") |
| 80 | + base_url = base_url.rstrip("/") |
| 81 | + |
| 82 | + # Get tag name from parameter, env var, or default |
| 83 | + if tag_name is None: |
| 84 | + tag_name = os.environ.get("POLICYAI_TAG_NAME", "prod") |
| 85 | + |
| 86 | + url = f"{base_url}/policyai/v1/decisions/evaluate/{tag_name}" |
| 87 | + |
| 88 | + headers = { |
| 89 | + "Musubi-Api-Key": api_key, |
| 90 | + "Content-Type": "application/json", |
| 91 | + } |
| 92 | + |
| 93 | + data = { |
| 94 | + "content": [ |
| 95 | + { |
| 96 | + "type": "TEXT", |
| 97 | + "content": text, |
| 98 | + } |
| 99 | + ], |
| 100 | + } |
| 101 | + |
| 102 | + timeout = aiohttp.ClientTimeout(total=30) |
| 103 | + async with aiohttp.ClientSession(timeout=timeout) as session: |
| 104 | + async with session.post( |
| 105 | + url=url, |
| 106 | + headers=headers, |
| 107 | + json=data, |
| 108 | + ) as response: |
| 109 | + if response.status != 200: |
| 110 | + raise ValueError( |
| 111 | + f"PolicyAI call failed with status code {response.status}.\nDetails: {await response.text()}" |
| 112 | + ) |
| 113 | + response_json = await response.json() |
| 114 | + log.info(json.dumps(response_json, indent=2)) |
| 115 | + |
| 116 | + # PolicyAI returns results in "data" array for tag-based evaluation |
| 117 | + results = response_json.get("data", []) |
| 118 | + |
| 119 | + # Fail-closed: If no policies are attached to the tag, raise an error |
| 120 | + # rather than silently allowing content through |
| 121 | + if not results: |
| 122 | + raise ValueError( |
| 123 | + f"PolicyAI returned no policy results for tag '{tag_name}'. " |
| 124 | + "Ensure policies are attached to this tag." |
| 125 | + ) |
| 126 | + |
| 127 | + # Check if all policies failed evaluation |
| 128 | + successful_results = [r for r in results if r.get("status") != "failed"] |
| 129 | + if not successful_results: |
| 130 | + raise ValueError( |
| 131 | + f"All PolicyAI policy evaluations failed for tag '{tag_name}'. Check policy configurations." |
| 132 | + ) |
| 133 | + |
| 134 | + # Aggregate results - if ANY policy returns UNSAFE, overall is UNSAFE |
| 135 | + overall_assessment = "SAFE" |
| 136 | + triggered_category = "Safe" |
| 137 | + max_severity = 0 |
| 138 | + reason = "Content passed all policy checks" |
| 139 | + |
| 140 | + for result in successful_results: |
| 141 | + assessment = result.get("assessment", "SAFE") |
| 142 | + if assessment == "UNSAFE": |
| 143 | + overall_assessment = "UNSAFE" |
| 144 | + triggered_category = result.get("category", "Unknown") |
| 145 | + max_severity = max(max_severity, result.get("severity", 0)) |
| 146 | + reason = result.get("reason", "Policy violation detected") |
| 147 | + break # Stop at first UNSAFE result |
| 148 | + |
| 149 | + # Pre-format exception message for Colang 1.x compatibility |
| 150 | + # (Colang 1.x doesn't support string concatenation in create event) |
| 151 | + exception_message = f"PolicyAI moderation triggered. Content violated policy: {triggered_category}" |
| 152 | + |
| 153 | + return { |
| 154 | + "assessment": overall_assessment, |
| 155 | + "category": triggered_category, |
| 156 | + "severity": max_severity, |
| 157 | + "reason": reason, |
| 158 | + "exception_message": exception_message, |
| 159 | + } |
0 commit comments