Elffuss BraidHub

kikocis/llama-stack public

52eab8874aca · 1.7 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
7import asyncio
8
9from typing import List
10
11from llama_models.llama3.api.datatypes import Message
12from termcolor import cprint
13
14from llama_stack.apis.safety import * # noqa: F403
15
16
17class SafetyException(Exception): # noqa: N818
18 def __init__(self, violation: SafetyViolation):
19 self.violation = violation
20 super().__init__(violation.user_message)
21
22
23class 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], shield_types: 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 shield_types
44 ]
45 )
46 for shield_type, response in zip(shield_types, responses):
47 if not response.violation:
48 continue
49
50 violation = response.violation
51 if violation.violation_level == ViolationLevel.ERROR:
52 raise SafetyException(violation)
53 elif violation.violation_level == ViolationLevel.WARN:
54 cprint(
55 f"[Warn]{shield_type} raised a warning",
56 color="red",
57 )