Elffuss BraidHub

kikocis/llama-stack public

3fc339af16ee · 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
7from typing import List
8
9from llama_stack.apis.inference import Message
10from llama_stack.apis.safety import Safety, ShieldDefinition
11
12from llama_stack.providers.impls.meta_reference.agents.safety import ShieldRunnerMixin
13
14from .builtin import BaseTool
15
16
17class SafeTool(BaseTool, ShieldRunnerMixin):
18 """A tool that makes other tools safety enabled"""
19
20 def __init__(
21 self,
22 tool: BaseTool,
23 safety_api: Safety,
24 input_shields: List[ShieldDefinition] = None,
25 output_shields: List[ShieldDefinition] = None,
26 ):
27 self._tool = tool
28 ShieldRunnerMixin.__init__(
29 self, safety_api, input_shields=input_shields, output_shields=output_shields
30 )
31
32 def get_name(self) -> str:
33 # return the name of the wrapped tool
34 return self._tool.get_name()
35
36 async def run(self, messages: List[Message]) -> List[Message]:
37 if self.input_shields:
38 await self.run_shields(messages, self.input_shields)
39 # run the underlying tool
40 res = await self._tool.run(messages)
41 if self.output_shields:
42 await self.run_shields(messages, self.output_shields)
43
44 return res
45
46
47def with_safety(
48 tool: BaseTool,
49 safety_api: Safety,
50 input_shields: List[ShieldDefinition] = None,
51 output_shields: List[ShieldDefinition] = None,
52) -> SafeTool:
53 return SafeTool(
54 tool,
55 safety_api,
56 input_shields=input_shields,
57 output_shields=output_shields,
58 )