Elffuss BraidHub

kikocis/llama-stack public

6c80338c6af2 · 1.8 KiBRawPermalink
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
7from abc import ABC, abstractmethod
8from typing import List
9
10from llama_models.llama3.api.datatypes import interleaved_text_media_as_str, Message
11from llama_stack.apis.safety import * # noqa: F403
12
13CANNED_RESPONSE_TEXT = "I can't answer that. Can I help with something else?"
14
15
16class ShieldBase(ABC):
17 def __init__(
18 self,
19 on_violation_action: OnViolationAction = OnViolationAction.RAISE,
20 ):
21 self.on_violation_action = on_violation_action
22
23 @abstractmethod
24 def get_shield_type(self) -> ShieldType:
25 raise NotImplementedError()
26
27 @abstractmethod
28 async def run(self, messages: List[Message]) -> ShieldResponse:
29 raise NotImplementedError()
30
31
32def message_content_as_str(message: Message) -> str:
33 return interleaved_text_media_as_str(message.content)
34
35
36# For shields that operate on simple strings
37class TextShield(ShieldBase):
38 def convert_messages_to_text(self, messages: List[Message]) -> str:
39 return "\n".join([message_content_as_str(m) for m in messages])
40
41 async def run(self, messages: List[Message]) -> ShieldResponse:
42 text = self.convert_messages_to_text(messages)
43 return await self.run_impl(text)
44
45 @abstractmethod
46 async def run_impl(self, text: str) -> ShieldResponse:
47 raise NotImplementedError()
48
49
50class DummyShield(TextShield):
51 def get_shield_type(self) -> ShieldType:
52 return "dummy"
53
54 async def run_impl(self, text: str) -> ShieldResponse:
55 # Dummy return LOW to test e2e
56 return ShieldResponse(
57 shield_type=BuiltinShield.third_party_shield, is_violation=False
58 )