kikocis/llama-stack public
Changesets · Branches · Tags · Compare
| Changeset | fba02457aaa91eef70adfac55b18782007f5438da1cc4d714e194d27ac4f64c5 |
|---|---|
| Author | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-24 19:27 -07:00 |
| Committer | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-24 19:29 -07:00 |
| Parents | 3afa27c5b926 |
5 files changed
modified llama_stack/cli/stack/configure.py +1 −1
| @@ -160,7 +160,7 @@ | ||
| 160 | 160 | f.write(yaml.dump(to_write, sort_keys=False)) |
| 161 | 161 | |
| 162 | 162 | cprint( |
| 163 | - f"> YAML configuration has been written to {run_config_file}.", | |
| 163 | + f"> YAML configuration has been written to `{run_config_file}`.", | |
| 164 | 164 | color="blue", |
| 165 | 165 | ) |
| 166 | 166 |
modified llama_stack/providers/adapters/safety/bedrock/__init__.py +5 −5
| @@ -7,12 +7,12 @@ | ||
| 7 | 7 | |
| 8 | 8 | from typing import Any |
| 9 | 9 | |
| 10 | -from .config import BedrockShieldConfig | |
| 10 | +from .config import BedrockSafetyConfig | |
| 11 | 11 | |
| 12 | 12 | |
| 13 | -async def get_adapter_impl(config: BedrockShieldConfig, _deps) -> Any: | |
| 14 | - from .bedrock import BedrockShieldAdapter | |
| 13 | +async def get_adapter_impl(config: BedrockSafetyConfig, _deps) -> Any: | |
| 14 | + from .bedrock import BedrockSafetyAdapter | |
| 15 | 15 | |
| 16 | - impl = BedrockShieldAdapter(config) | |
| 16 | + impl = BedrockSafetyAdapter(config) | |
| 17 | 17 | await impl.initialize() |
| 18 | - return impl | |
| No newline at the end of the file | ||
| 18 | + return impl |
modified llama_stack/providers/adapters/safety/bedrock/bedrock.py +65 −59
| @@ -5,99 +5,105 @@ | ||
| 5 | 5 | # the root directory of this source tree. |
| 6 | 6 | |
| 7 | 7 | |
| 8 | -from typing import Any, AsyncGenerator, Dict | |
| 9 | -from .config import BedrockShieldConfig | |
| 10 | 8 | import traceback |
| 11 | -import asyncio | |
| 12 | -from enum import Enum | |
| 13 | -from typing import List | |
| 14 | -from pydantic import BaseModel, validator | |
| 9 | +from typing import Any, Dict, List | |
| 10 | + | |
| 11 | +from .config import BedrockSafetyConfig | |
| 15 | 12 | from llama_stack.apis.safety import * # noqa |
| 16 | 13 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 17 | -import boto3 | |
| 18 | 14 | import json |
| 19 | 15 | import logging |
| 20 | 16 | |
| 17 | +import boto3 | |
| 18 | + | |
| 19 | + | |
| 21 | 20 | logger = logging.getLogger(__name__) |
| 22 | 21 | |
| 23 | -class BedrockShieldAdapter(Safety): | |
| 24 | - def __init__(self, config: BedrockShieldConfig) -> None: | |
| 22 | + | |
| 23 | +class BedrockSafetyAdapter(Safety): | |
| 24 | + def __init__(self, config: BedrockSafetyConfig) -> None: | |
| 25 | 25 | self.config = config |
| 26 | - | |
| 27 | 26 | |
| 28 | 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 | + | |
| 29 | 33 | try: |
| 30 | - if not self.config.aws_profile: | |
| 31 | - raise RuntimeError(f"Missing boto_client aws_profile in model info::{self.config}") | |
| 32 | 34 | print(f"initializing with profile --- > {self.config}::") |
| 33 | 35 | self.boto_client_profile = self.config.aws_profile |
| 34 | - self.boto_client = boto3.Session(profile_name=self.boto_client_profile).client('bedrock-runtime') | |
| 36 | + self.boto_client = boto3.Session( | |
| 37 | + profile_name=self.boto_client_profile | |
| 38 | + ).client("bedrock-runtime") | |
| 35 | 39 | except Exception as e: |
| 36 | - import traceback | |
| 37 | - | |
| 38 | - traceback.print_exc() | |
| 39 | 40 | raise RuntimeError(f"Error initializing BedrockSafetyAdapter: {e}") from e |
| 40 | 41 | |
| 41 | 42 | async def shutdown(self) -> None: |
| 42 | 43 | pass |
| 43 | 44 | |
| 44 | - async def run_shield(self, shield_type: str, messages: List[Message], params: Dict[str, Any] = None) -> RunShieldResponse: | |
| 45 | - """ This is the implementation for the bedrock guardrails. The input to the guardrails is to be of this format | |
| 46 | - ```content = [ | |
| 47 | - { | |
| 48 | - "text": { | |
| 49 | - "text": "Is the AB503 Product a better investment than the S&P 500?" | |
| 50 | - } | |
| 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?" | |
| 51 | 53 | } |
| 52 | - ]``` | |
| 53 | - However the incoming messages are of this type UserMessage(content=....) coming from | |
| 54 | - https://github.com/meta-llama/llama-models/blob/main/models/llama3/api/datatypes.py | |
| 55 | - | |
| 56 | - They contain content, role . For now we will extract the content and default the "qualifiers": ["query"] | |
| 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"] | |
| 57 | 60 | """ |
| 58 | - ret_violation = None | |
| 59 | 61 | try: |
| 60 | 62 | logger.debug(f"run_shield::{params}::messages={messages}") |
| 61 | - if not 'guardrailIdentifier' in params: | |
| 62 | - raise RuntimeError(f"Error running request for BedrockGaurdrails:Missing GuardrailID in request") | |
| 63 | - | |
| 64 | - if not 'guardrailVersion' in params: | |
| 65 | - raise RuntimeError(f"Error running request for BedrockGaurdrails:Missing guardrailVersion in request") | |
| 66 | - | |
| 67 | - #- convert the messages into format Bedrock expects | |
| 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 | |
| 68 | 74 | content_messages = [] |
| 69 | 75 | for message in messages: |
| 70 | 76 | content_messages.append({"text": {"text": message.content}}) |
| 71 | - logger.debug(f"run_shield::final:messages::{json.dumps(content_messages, indent=2)}:") | |
| 77 | + logger.debug( | |
| 78 | + f"run_shield::final:messages::{json.dumps(content_messages, indent=2)}:" | |
| 79 | + ) | |
| 72 | 80 | |
| 73 | 81 | response = self.boto_client.apply_guardrail( |
| 74 | - guardrailIdentifier=params.get('guardrailIdentifier'), | |
| 75 | - guardrailVersion=params.get('guardrailVersion'), | |
| 76 | - source='OUTPUT', # or 'INPUT' depending on your use case | |
| 77 | - content=content_messages | |
| 82 | + guardrailIdentifier=params.get("guardrailIdentifier"), | |
| 83 | + guardrailVersion=params.get("guardrailVersion"), | |
| 84 | + source="OUTPUT", # or 'INPUT' depending on your use case | |
| 85 | + content=content_messages, | |
| 78 | 86 | ) |
| 79 | 87 | logger.debug(f"run_shield:: response: {response}::") |
| 80 | - if response['action'] == 'GUARDRAIL_INTERVENED': | |
| 81 | - user_message="" | |
| 82 | - metadata={} | |
| 83 | - for output in response['outputs']: | |
| 88 | + if response["action"] == "GUARDRAIL_INTERVENED": | |
| 89 | + user_message = "" | |
| 90 | + metadata = {} | |
| 91 | + for output in response["outputs"]: | |
| 84 | 92 | # guardrails returns a list - however for this implementation we will leverage the last values |
| 85 | - user_message=output['text'] | |
| 86 | - for assessment in response['assessments']: | |
| 93 | + user_message = output["text"] | |
| 94 | + for assessment in response["assessments"]: | |
| 87 | 95 | # guardrails returns a list - however for this implementation we will leverage the last values |
| 88 | - metadata = dict(assessment) | |
| 89 | - ret_violation = SafetyViolation( | |
| 90 | - user_message=user_message, | |
| 96 | + metadata = dict(assessment) | |
| 97 | + return SafetyViolation( | |
| 98 | + user_message=user_message, | |
| 91 | 99 | violation_level=ViolationLevel.ERROR, |
| 92 | - metadata=metadata | |
| 100 | + metadata=metadata, | |
| 93 | 101 | ) |
| 94 | - | |
| 95 | - except: | |
| 96 | - error_str = traceback.format_exc() | |
| 97 | - print(f"Error in apply_guardrails:{error_str}:: RETURNING None !!!!!") | |
| 98 | - logger.error(f"Error in apply_guardrails:{error_str}:: RETURNING None !!!!!") | |
| 99 | - #raise RuntimeError(f"Error running request for BedrockGaurdrails: {error_str}:") | |
| 100 | - | |
| 101 | - return ret_violation | |
| 102 | 102 | |
| 103 | + except Exception: | |
| 104 | + error_str = traceback.format_exc() | |
| 105 | + logger.error( | |
| 106 | + f"Error in apply_guardrails:{error_str}:: RETURNING None !!!!!" | |
| 107 | + ) | |
| 103 | 108 | |
| 109 | + return None |
modified llama_stack/providers/adapters/safety/bedrock/config.py +3 −11
| @@ -4,21 +4,13 @@ | ||
| 4 | 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | 5 | # the root directory of this source tree. |
| 6 | 6 | |
| 7 | -from typing import Optional | |
| 8 | - | |
| 9 | -from llama_models.schema_utils import json_schema_type | |
| 10 | 7 | from pydantic import BaseModel, Field |
| 11 | -import boto3 | |
| 12 | 8 | |
| 13 | 9 | |
| 14 | -@json_schema_type | |
| 15 | -class BedrockShieldConfig(BaseModel): | |
| 10 | +class BedrockSafetyConfig(BaseModel): | |
| 16 | 11 | """Configuration information for a guardrail that you want to use in the request.""" |
| 17 | 12 | |
| 18 | - aws_profile: Optional[str] = Field( | |
| 19 | - default='default', | |
| 13 | + aws_profile: str = Field( | |
| 14 | + default="default", | |
| 20 | 15 | description="The profile on the machine having valid aws credentials. This will ensure separation of creation to invocation", |
| 21 | 16 | ) |
| 22 | - | |
| 23 | - | |
| 24 | - |
modified llama_stack/providers/registry/safety.py +3 −3
| @@ -41,10 +41,10 @@ | ||
| 41 | 41 | remote_provider_spec( |
| 42 | 42 | api=Api.safety, |
| 43 | 43 | adapter=AdapterSpec( |
| 44 | - adapter_id="bedrock_guardrails", | |
| 45 | - pip_packages=['boto3',], | |
| 44 | + adapter_id="bedrock", | |
| 45 | + pip_packages=["boto3"], | |
| 46 | 46 | module="llama_stack.providers.adapters.safety.bedrock", |
| 47 | - config_class="llama_stack.providers.adapters.safety.bedrock.config.BedrockShieldConfig", | |
| 47 | + config_class="llama_stack.providers.adapters.safety.bedrock.BedrockSafetyConfig", | |
| 48 | 48 | ), |
| 49 | 49 | ), |
| 50 | 50 | remote_provider_spec( |