| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import asyncio |
| 8 | |
| 9 | from typing import List |
| 10 | |
| 11 | from llama_models.llama3.api.datatypes import Message |
| 12 | from termcolor import cprint |
| 13 | |
| 14 | from llama_stack.apis.safety import * # noqa: F403 |
| 15 | |
| 16 | |
| 17 | class SafetyException(Exception): # noqa: N818 |
| 18 | def __init__(self, violation: SafetyViolation): |
| 19 | self.violation = violation |
| 20 | super().__init__(violation.user_message) |
| 21 | |
| 22 | |
| 23 | class ShieldRunnerMixin: |
| 24 | def __init__( |
| 25 | self, |
| 26 | safety_api: Safety, |
| 27 | input_shields: List[str] = None, |
| 28 | output_shields: List[str] = None, |
| 29 | ): |
| 30 | self.safety_api = safety_api |
| 31 | self.input_shields = input_shields |
| 32 | self.output_shields = output_shields |
| 33 | |
| 34 | async def run_multiple_shields( |
| 35 | self, messages: List[Message], shields: List[str] |
| 36 | ) -> None: |
| 37 | responses = await asyncio.gather( |
| 38 | *[ |
| 39 | self.safety_api.run_shield( |
| 40 | shield_type=shield_type, |
| 41 | messages=messages, |
| 42 | ) |
| 43 | for shield_type in shields |
| 44 | ] |
| 45 | ) |
| 46 | |
| 47 | for shield, r in zip(shields, responses): |
| 48 | if r.violation: |
| 49 | if shield.on_violation_action == OnViolationAction.RAISE: |
| 50 | raise SafetyException(r) |
| 51 | elif shield.on_violation_action == OnViolationAction.WARN: |
| 52 | cprint( |
| 53 | f"[Warn]{shield.__class__.__name__} raised a warning", |
| 54 | color="red", |
| 55 | ) |