Elffuss BraidHub

kikocis/llama-stack public

efac2a2f572e · 2.3 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 enum import Enum
8from typing import Dict, List, Optional, Protocol, Union
9
10from llama_models.schema_utils import json_schema_type, webmethod
11from pydantic import BaseModel, validator
12
13from llama_models.llama3.api.datatypes import * # noqa: F403
14from llama_toolchain.common.deployment_types import RestAPIExecutionConfig
15
16
17@json_schema_type
18class BuiltinShield(Enum):
19 llama_guard = "llama_guard"
20 code_scanner_guard = "code_scanner_guard"
21 third_party_shield = "third_party_shield"
22 injection_shield = "injection_shield"
23 jailbreak_shield = "jailbreak_shield"
24
25
26ShieldType = Union[BuiltinShield, str]
27
28
29@json_schema_type
30class OnViolationAction(Enum):
31 IGNORE = 0
32 WARN = 1
33 RAISE = 2
34
35
36@json_schema_type
37class ShieldDefinition(BaseModel):
38 shield_type: ShieldType
39 description: Optional[str] = None
40 parameters: Optional[Dict[str, ToolParamDefinition]] = None
41 on_violation_action: OnViolationAction = OnViolationAction.RAISE
42 execution_config: Optional[RestAPIExecutionConfig] = None
43
44 @validator("shield_type", pre=True)
45 @classmethod
46 def validate_field(cls, v):
47 if isinstance(v, str):
48 try:
49 return BuiltinShield(v)
50 except ValueError:
51 return v
52 return v
53
54
55@json_schema_type
56class ShieldResponse(BaseModel):
57 shield_type: ShieldType
58 # TODO(ashwin): clean this up
59 is_violation: bool
60 violation_type: Optional[str] = None
61 violation_return_message: Optional[str] = None
62
63 @validator("shield_type", pre=True)
64 @classmethod
65 def validate_field(cls, v):
66 if isinstance(v, str):
67 try:
68 return BuiltinShield(v)
69 except ValueError:
70 return v
71 return v
72
73
74@json_schema_type
75class RunShieldRequest(BaseModel):
76 messages: List[Message]
77 shields: List[ShieldDefinition]
78
79
80@json_schema_type
81class RunShieldResponse(BaseModel):
82 responses: List[ShieldResponse]
83
84
85class Safety(Protocol):
86 @webmethod(route="/safety/run_shields")
87 async def run_shields(
88 self,
89 messages: List[Message],
90 shields: List[ShieldDefinition],
91 ) -> RunShieldResponse: ...