| 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 | from typing import List |
| 8 | |
| 9 | from llama_models.llama3.api.datatypes import Message, Role, UserMessage |
| 10 | from termcolor import cprint |
| 11 | |
| 12 | from llama_stack.apis.safety import ( |
| 13 | OnViolationAction, |
| 14 | Safety, |
| 15 | ShieldDefinition, |
| 16 | ShieldResponse, |
| 17 | ) |
| 18 | |
| 19 | |
| 20 | class SafetyException(Exception): # noqa: N818 |
| 21 | def __init__(self, response: ShieldResponse): |
| 22 | self.response = response |
| 23 | super().__init__(response.violation_return_message) |
| 24 | |
| 25 | |
| 26 | class ShieldRunnerMixin: |
| 27 | def __init__( |
| 28 | self, |
| 29 | safety_api: Safety, |
| 30 | input_shields: List[ShieldDefinition] = None, |
| 31 | output_shields: List[ShieldDefinition] = None, |
| 32 | ): |
| 33 | self.safety_api = safety_api |
| 34 | self.input_shields = input_shields |
| 35 | self.output_shields = output_shields |
| 36 | |
| 37 | async def run_shields( |
| 38 | self, messages: List[Message], shields: List[ShieldDefinition] |
| 39 | ) -> List[ShieldResponse]: |
| 40 | messages = messages.copy() |
| 41 | # some shields like llama-guard require the first message to be a user message |
| 42 | # since this might be a tool call, first role might not be user |
| 43 | if len(messages) > 0 and messages[0].role != Role.user.value: |
| 44 | messages[0] = UserMessage(content=messages[0].content) |
| 45 | |
| 46 | res = await self.safety_api.run_shields( |
| 47 | messages=messages, |
| 48 | shields=shields, |
| 49 | ) |
| 50 | |
| 51 | results = res.responses |
| 52 | for shield, r in zip(shields, results): |
| 53 | if r.is_violation: |
| 54 | if shield.on_violation_action == OnViolationAction.RAISE: |
| 55 | raise SafetyException(r) |
| 56 | elif shield.on_violation_action == OnViolationAction.WARN: |
| 57 | cprint( |
| 58 | f"[Warn]{shield.__class__.__name__} raised a warning", |
| 59 | color="red", |
| 60 | ) |
| 61 | |
| 62 | return results |