| 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 | |
| 8 | import traceback |
| 9 | from typing import Any, Dict, List |
| 10 | |
| 11 | from .config import BedrockSafetyConfig |
| 12 | from llama_stack.apis.safety import * # noqa |
| 13 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 14 | import json |
| 15 | import logging |
| 16 | |
| 17 | import boto3 |
| 18 | |
| 19 | |
| 20 | logger = logging.getLogger(__name__) |
| 21 | |
| 22 | |
| 23 | class BedrockSafetyAdapter(Safety): |
| 24 | def __init__(self, config: BedrockSafetyConfig) -> None: |
| 25 | self.config = config |
| 26 | |
| 27 | async def initialize(self) -> None: |
| 28 | if not self.config.aws_profile: |
| 29 | raise RuntimeError( |
| 30 | f"Missing boto_client aws_profile in model info::{self.config}" |
| 31 | ) |
| 32 | |
| 33 | try: |
| 34 | print(f"initializing with profile --- > {self.config}::") |
| 35 | self.boto_client_profile = self.config.aws_profile |
| 36 | self.boto_client = boto3.Session( |
| 37 | profile_name=self.boto_client_profile |
| 38 | ).client("bedrock-runtime") |
| 39 | except Exception as e: |
| 40 | raise RuntimeError(f"Error initializing BedrockSafetyAdapter: {e}") from e |
| 41 | |
| 42 | async def shutdown(self) -> None: |
| 43 | pass |
| 44 | |
| 45 | async def run_shield( |
| 46 | self, shield_type: str, messages: List[Message], params: Dict[str, Any] = None |
| 47 | ) -> RunShieldResponse: |
| 48 | """This is the implementation for the bedrock guardrails. The input to the guardrails is to be of this format |
| 49 | ```content = [ |
| 50 | { |
| 51 | "text": { |
| 52 | "text": "Is the AB503 Product a better investment than the S&P 500?" |
| 53 | } |
| 54 | } |
| 55 | ]``` |
| 56 | However the incoming messages are of this type UserMessage(content=....) coming from |
| 57 | https://github.com/meta-llama/llama-models/blob/main/models/llama3/api/datatypes.py |
| 58 | |
| 59 | They contain content, role . For now we will extract the content and default the "qualifiers": ["query"] |
| 60 | """ |
| 61 | try: |
| 62 | logger.debug(f"run_shield::{params}::messages={messages}") |
| 63 | if "guardrailIdentifier" not in params: |
| 64 | raise RuntimeError( |
| 65 | "Error running request for BedrockGaurdrails:Missing GuardrailID in request" |
| 66 | ) |
| 67 | |
| 68 | if "guardrailVersion" not in params: |
| 69 | raise RuntimeError( |
| 70 | "Error running request for BedrockGaurdrails:Missing guardrailVersion in request" |
| 71 | ) |
| 72 | |
| 73 | # - convert the messages into format Bedrock expects |
| 74 | content_messages = [] |
| 75 | for message in messages: |
| 76 | content_messages.append({"text": {"text": message.content}}) |
| 77 | logger.debug( |
| 78 | f"run_shield::final:messages::{json.dumps(content_messages, indent=2)}:" |
| 79 | ) |
| 80 | |
| 81 | response = self.boto_client.apply_guardrail( |
| 82 | guardrailIdentifier=params.get("guardrailIdentifier"), |
| 83 | guardrailVersion=params.get("guardrailVersion"), |
| 84 | source="OUTPUT", # or 'INPUT' depending on your use case |
| 85 | content=content_messages, |
| 86 | ) |
| 87 | logger.debug(f"run_shield:: response: {response}::") |
| 88 | if response["action"] == "GUARDRAIL_INTERVENED": |
| 89 | user_message = "" |
| 90 | metadata = {} |
| 91 | for output in response["outputs"]: |
| 92 | # guardrails returns a list - however for this implementation we will leverage the last values |
| 93 | user_message = output["text"] |
| 94 | for assessment in response["assessments"]: |
| 95 | # guardrails returns a list - however for this implementation we will leverage the last values |
| 96 | metadata = dict(assessment) |
| 97 | return SafetyViolation( |
| 98 | user_message=user_message, |
| 99 | violation_level=ViolationLevel.ERROR, |
| 100 | metadata=metadata, |
| 101 | ) |
| 102 | |
| 103 | except Exception: |
| 104 | error_str = traceback.format_exc() |
| 105 | logger.error( |
| 106 | f"Error in apply_guardrails:{error_str}:: RETURNING None !!!!!" |
| 107 | ) |
| 108 | |
| 109 | return None |