Elffuss BraidHub

kikocis/llama-stack public

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