| 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 auto, Enum |
| 8 | from typing import List |
| 9 | |
| 10 | import torch |
| 11 | |
| 12 | from llama_models.llama3.api.datatypes import Message |
| 13 | from termcolor import cprint |
| 14 | |
| 15 | from .base import message_content_as_str, OnViolationAction, ShieldResponse, TextShield |
| 16 | from llama_stack.apis.safety import * # noqa: F403 |
| 17 | |
| 18 | |
| 19 | class PromptGuardShield(TextShield): |
| 20 | class Mode(Enum): |
| 21 | INJECTION = auto() |
| 22 | JAILBREAK = auto() |
| 23 | |
| 24 | _instances = {} |
| 25 | _model_cache = None |
| 26 | |
| 27 | @staticmethod |
| 28 | def instance( |
| 29 | model_dir: str, |
| 30 | threshold: float = 0.9, |
| 31 | temperature: float = 1.0, |
| 32 | mode: "PromptGuardShield.Mode" = Mode.JAILBREAK, |
| 33 | on_violation_action=OnViolationAction.RAISE, |
| 34 | ) -> "PromptGuardShield": |
| 35 | action_value = on_violation_action.value |
| 36 | key = (model_dir, threshold, temperature, mode, action_value) |
| 37 | if key not in PromptGuardShield._instances: |
| 38 | PromptGuardShield._instances[key] = PromptGuardShield( |
| 39 | model_dir=model_dir, |
| 40 | threshold=threshold, |
| 41 | temperature=temperature, |
| 42 | mode=mode, |
| 43 | on_violation_action=on_violation_action, |
| 44 | ) |
| 45 | return PromptGuardShield._instances[key] |
| 46 | |
| 47 | def __init__( |
| 48 | self, |
| 49 | model_dir: str, |
| 50 | threshold: float = 0.9, |
| 51 | temperature: float = 1.0, |
| 52 | mode: "PromptGuardShield.Mode" = Mode.JAILBREAK, |
| 53 | on_violation_action: OnViolationAction = OnViolationAction.RAISE, |
| 54 | ): |
| 55 | super().__init__(on_violation_action) |
| 56 | assert ( |
| 57 | model_dir is not None |
| 58 | ), "Must provide a model directory for prompt injection shield" |
| 59 | if temperature <= 0: |
| 60 | raise ValueError("Temperature must be greater than 0") |
| 61 | self.device = "cuda" |
| 62 | if PromptGuardShield._model_cache is None: |
| 63 | from transformers import AutoModelForSequenceClassification, AutoTokenizer |
| 64 | |
| 65 | # load model and tokenizer |
| 66 | tokenizer = AutoTokenizer.from_pretrained(model_dir) |
| 67 | model = AutoModelForSequenceClassification.from_pretrained( |
| 68 | model_dir, device_map=self.device |
| 69 | ) |
| 70 | PromptGuardShield._model_cache = (tokenizer, model) |
| 71 | |
| 72 | self.tokenizer, self.model = PromptGuardShield._model_cache |
| 73 | self.temperature = temperature |
| 74 | self.threshold = threshold |
| 75 | self.mode = mode |
| 76 | |
| 77 | def get_shield_type(self) -> ShieldType: |
| 78 | return ( |
| 79 | BuiltinShield.jailbreak_shield |
| 80 | if self.mode == self.Mode.JAILBREAK |
| 81 | else BuiltinShield.injection_shield |
| 82 | ) |
| 83 | |
| 84 | def convert_messages_to_text(self, messages: List[Message]) -> str: |
| 85 | return message_content_as_str(messages[-1]) |
| 86 | |
| 87 | async def run_impl(self, text: str) -> ShieldResponse: |
| 88 | # run model on messages and return response |
| 89 | inputs = self.tokenizer(text, return_tensors="pt") |
| 90 | inputs = {name: tensor.to(self.model.device) for name, tensor in inputs.items()} |
| 91 | with torch.no_grad(): |
| 92 | outputs = self.model(**inputs) |
| 93 | logits = outputs[0] |
| 94 | probabilities = torch.softmax(logits / self.temperature, dim=-1) |
| 95 | score_embedded = probabilities[0, 1].item() |
| 96 | score_malicious = probabilities[0, 2].item() |
| 97 | cprint( |
| 98 | f"Ran PromptGuardShield and got Scores: Embedded: {score_embedded}, Malicious: {score_malicious}", |
| 99 | color="magenta", |
| 100 | ) |
| 101 | |
| 102 | if self.mode == self.Mode.INJECTION and ( |
| 103 | score_embedded + score_malicious > self.threshold |
| 104 | ): |
| 105 | return ShieldResponse( |
| 106 | shield_type=self.get_shield_type(), |
| 107 | is_violation=True, |
| 108 | violation_type=f"prompt_injection:embedded={score_embedded},malicious={score_malicious}", |
| 109 | violation_return_message="Sorry, I cannot do this.", |
| 110 | ) |
| 111 | elif self.mode == self.Mode.JAILBREAK and score_malicious > self.threshold: |
| 112 | return ShieldResponse( |
| 113 | shield_type=self.get_shield_type(), |
| 114 | is_violation=True, |
| 115 | violation_type=f"prompt_injection:malicious={score_malicious}", |
| 116 | violation_return_message="Sorry, I cannot do this.", |
| 117 | ) |
| 118 | |
| 119 | return ShieldResponse( |
| 120 | shield_type=self.get_shield_type(), |
| 121 | is_violation=False, |
| 122 | ) |
| 123 | |
| 124 | |
| 125 | class JailbreakShield(PromptGuardShield): |
| 126 | def __init__( |
| 127 | self, |
| 128 | model_dir: str, |
| 129 | threshold: float = 0.9, |
| 130 | temperature: float = 1.0, |
| 131 | on_violation_action: OnViolationAction = OnViolationAction.RAISE, |
| 132 | ): |
| 133 | super().__init__( |
| 134 | model_dir=model_dir, |
| 135 | threshold=threshold, |
| 136 | temperature=temperature, |
| 137 | mode=PromptGuardShield.Mode.JAILBREAK, |
| 138 | on_violation_action=on_violation_action, |
| 139 | ) |
| 140 | |
| 141 | |
| 142 | class InjectionShield(PromptGuardShield): |
| 143 | def __init__( |
| 144 | self, |
| 145 | model_dir: str, |
| 146 | threshold: float = 0.9, |
| 147 | temperature: float = 1.0, |
| 148 | on_violation_action: OnViolationAction = OnViolationAction.RAISE, |
| 149 | ): |
| 150 | super().__init__( |
| 151 | model_dir=model_dir, |
| 152 | threshold=threshold, |
| 153 | temperature=temperature, |
| 154 | mode=PromptGuardShield.Mode.INJECTION, |
| 155 | on_violation_action=on_violation_action, |
| 156 | ) |