|
| 1 | +"""Harmful content detection guardrail validator.""" |
| 2 | + |
| 3 | +from typing import Any, Sequence |
| 4 | +from uuid import uuid4 |
| 5 | + |
| 6 | +from uipath.platform.guardrails.guardrails import ( |
| 7 | + BuiltInValidatorGuardrail, |
| 8 | + EnumListParameterValue, |
| 9 | + MapEnumParameterValue, |
| 10 | +) |
| 11 | + |
| 12 | +from .._models import HarmfulContentEntity |
| 13 | +from ._base import BuiltInGuardrailValidator |
| 14 | + |
| 15 | + |
| 16 | +class HarmfulContentValidator(BuiltInGuardrailValidator): |
| 17 | + """Validate data for harmful content using the UiPath API. |
| 18 | +
|
| 19 | + Supported at all stages (PRE, POST, PRE_AND_POST). |
| 20 | +
|
| 21 | + Args: |
| 22 | + entities: One or more :class:`~uipath.platform.guardrails.decorators.HarmfulContentEntity` |
| 23 | + instances specifying which harmful content categories to detect |
| 24 | + and their severity thresholds. |
| 25 | +
|
| 26 | + Raises: |
| 27 | + ValueError: If *entities* is empty. |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__(self, entities: Sequence[HarmfulContentEntity]) -> None: |
| 31 | + """Initialize HarmfulContentValidator with entities to detect.""" |
| 32 | + if not entities: |
| 33 | + raise ValueError("entities must be provided and non-empty") |
| 34 | + self.entities = list(entities) |
| 35 | + |
| 36 | + def get_built_in_guardrail( |
| 37 | + self, |
| 38 | + name: str, |
| 39 | + description: str | None, |
| 40 | + enabled_for_evals: bool, |
| 41 | + ) -> BuiltInValidatorGuardrail: |
| 42 | + """Build a harmful content :class:`BuiltInValidatorGuardrail`. |
| 43 | +
|
| 44 | + Args: |
| 45 | + name: Name for the guardrail. |
| 46 | + description: Optional description. |
| 47 | + enabled_for_evals: Whether active in evaluation scenarios. |
| 48 | +
|
| 49 | + Returns: |
| 50 | + Configured :class:`BuiltInValidatorGuardrail` for harmful content detection. |
| 51 | + """ |
| 52 | + entity_names = [entity.name for entity in self.entities] |
| 53 | + entity_thresholds: dict[str, Any] = { |
| 54 | + entity.name: entity.threshold for entity in self.entities |
| 55 | + } |
| 56 | + |
| 57 | + return BuiltInValidatorGuardrail( |
| 58 | + id=str(uuid4()), |
| 59 | + name=name, |
| 60 | + description=description |
| 61 | + or f"Detects harmful content: {', '.join(entity_names)}", |
| 62 | + enabled_for_evals=enabled_for_evals, |
| 63 | + guardrail_type="builtInValidator", |
| 64 | + validator_type="harmful_content", |
| 65 | + validator_parameters=[ |
| 66 | + EnumListParameterValue( |
| 67 | + parameter_type="enum-list", |
| 68 | + id="harmfulContentEntities", |
| 69 | + value=entity_names, |
| 70 | + ), |
| 71 | + MapEnumParameterValue( |
| 72 | + parameter_type="map-enum", |
| 73 | + id="harmfulContentEntityThresholds", |
| 74 | + value=entity_thresholds, |
| 75 | + ), |
| 76 | + ], |
| 77 | + ) |
0 commit comments