| 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 | |
| 7 | from enum import Enum |
| 8 | from typing import Dict, List, Optional, Protocol, Union |
| 9 | |
| 10 | from llama_models.schema_utils import json_schema_type, webmethod |
| 11 | from pydantic import BaseModel, validator |
| 12 | |
| 13 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 14 | from llama_toolchain.common.deployment_types import RestAPIExecutionConfig |
| 15 | |
| 16 | |
| 17 | @json_schema_type |
| 18 | class 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 | |
| 26 | ShieldType = Union[BuiltinShield, str] |
| 27 | |
| 28 | |
| 29 | @json_schema_type |
| 30 | class OnViolationAction(Enum): |
| 31 | IGNORE = 0 |
| 32 | WARN = 1 |
| 33 | RAISE = 2 |
| 34 | |
| 35 | |
| 36 | @json_schema_type |
| 37 | class 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 |
| 56 | class 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 |
| 75 | class RunShieldRequest(BaseModel): |
| 76 | messages: List[Message] |
| 77 | shields: List[ShieldDefinition] |
| 78 | |
| 79 | |
| 80 | @json_schema_type |
| 81 | class RunShieldResponse(BaseModel): |
| 82 | responses: List[ShieldResponse] |
| 83 | |
| 84 | |
| 85 | class 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: ... |