| 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 abc import ABC, abstractmethod |
| 8 | from typing import List |
| 9 | |
| 10 | from llama_models.llama3.api.datatypes import interleaved_text_media_as_str, Message |
| 11 | from pydantic import BaseModel |
| 12 | from llama_stack.apis.safety import * # noqa: F403 |
| 13 | |
| 14 | CANNED_RESPONSE_TEXT = "I can't answer that. Can I help with something else?" |
| 15 | |
| 16 | |
| 17 | # TODO: clean this up; just remove this type completely |
| 18 | class ShieldResponse(BaseModel): |
| 19 | is_violation: bool |
| 20 | violation_type: Optional[str] = None |
| 21 | violation_return_message: Optional[str] = None |
| 22 | |
| 23 | |
| 24 | # TODO: this is a caller / agent concern |
| 25 | class OnViolationAction(Enum): |
| 26 | IGNORE = 0 |
| 27 | WARN = 1 |
| 28 | RAISE = 2 |
| 29 | |
| 30 | |
| 31 | class ShieldBase(ABC): |
| 32 | def __init__( |
| 33 | self, |
| 34 | on_violation_action: OnViolationAction = OnViolationAction.RAISE, |
| 35 | ): |
| 36 | self.on_violation_action = on_violation_action |
| 37 | |
| 38 | @abstractmethod |
| 39 | async def run(self, messages: List[Message]) -> ShieldResponse: |
| 40 | raise NotImplementedError() |
| 41 | |
| 42 | |
| 43 | def message_content_as_str(message: Message) -> str: |
| 44 | return interleaved_text_media_as_str(message.content) |
| 45 | |
| 46 | |
| 47 | # For shields that operate on simple strings |
| 48 | class TextShield(ShieldBase): |
| 49 | def convert_messages_to_text(self, messages: List[Message]) -> str: |
| 50 | return "\n".join([message_content_as_str(m) for m in messages]) |
| 51 | |
| 52 | async def run(self, messages: List[Message]) -> ShieldResponse: |
| 53 | text = self.convert_messages_to_text(messages) |
| 54 | return await self.run_impl(text) |
| 55 | |
| 56 | @abstractmethod |
| 57 | async def run_impl(self, text: str) -> ShieldResponse: |
| 58 | raise NotImplementedError() |
| 59 | |
| 60 | |
| 61 | class DummyShield(TextShield): |
| 62 | async def run_impl(self, text: str) -> ShieldResponse: |
| 63 | # Dummy return LOW to test e2e |
| 64 | return ShieldResponse(is_violation=False) |