Elffuss BraidHub

kikocis/llama-stack public

Some lightweight cleanup and renaming for bedrock safety adapter
Changesetfba02457aaa91eef70adfac55b18782007f5438da1cc4d714e194d27ac4f64c5
AuthorAshwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-24 19:27 -07:00
CommitterAshwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-24 19:29 -07:00
Parents3afa27c5b926

Browse the files at this changeset

5 files changed

modified llama_stack/cli/stack/configure.py +1 −1
@@ -160,7 +160,7 @@
160160 f.write(yaml.dump(to_write, sort_keys=False))
161161
162162 cprint(
163- f"> YAML configuration has been written to {run_config_file}.",
163+ f"> YAML configuration has been written to `{run_config_file}`.",
164164 color="blue",
165165 )
166166
modified llama_stack/providers/adapters/safety/bedrock/__init__.py +5 −5
@@ -7,12 +7,12 @@
77
88 from typing import Any
99
10-from .config import BedrockShieldConfig
10+from .config import BedrockSafetyConfig
1111
1212
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
1515
16- impl = BedrockShieldAdapter(config)
16+ impl = BedrockSafetyAdapter(config)
1717 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 @@
55 # the root directory of this source tree.
66
77
8-from typing import Any, AsyncGenerator, Dict
9-from .config import BedrockShieldConfig
108 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
1512 from llama_stack.apis.safety import * # noqa
1613 from llama_models.llama3.api.datatypes import * # noqa: F403
17-import boto3
1814 import json
1915 import logging
2016
17+import boto3
18+
19+
2120 logger = logging.getLogger(__name__)
2221
23-class BedrockShieldAdapter(Safety):
24- def __init__(self, config: BedrockShieldConfig) -> None:
22+
23+class BedrockSafetyAdapter(Safety):
24+ def __init__(self, config: BedrockSafetyConfig) -> None:
2525 self.config = config
26-
2726
2827 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+
2933 try:
30- if not self.config.aws_profile:
31- raise RuntimeError(f"Missing boto_client aws_profile in model info::{self.config}")
3234 print(f"initializing with profile --- > {self.config}::")
3335 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")
3539 except Exception as e:
36- import traceback
37-
38- traceback.print_exc()
3940 raise RuntimeError(f"Error initializing BedrockSafetyAdapter: {e}") from e
4041
4142 async def shutdown(self) -> None:
4243 pass
4344
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?"
5153 }
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"]
5760 """
58- ret_violation = None
5961 try:
6062 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
6874 content_messages = []
6975 for message in messages:
7076 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+ )
7280
7381 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,
7886 )
7987 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"]:
8492 # 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"]:
8795 # 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,
9199 violation_level=ViolationLevel.ERROR,
92- metadata=metadata
100+ metadata=metadata,
93101 )
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
102102
103+ except Exception:
104+ error_str = traceback.format_exc()
105+ logger.error(
106+ f"Error in apply_guardrails:{error_str}:: RETURNING None !!!!!"
107+ )
103108
109+ return None
modified llama_stack/providers/adapters/safety/bedrock/config.py +3 −11
@@ -4,21 +4,13 @@
44 # This source code is licensed under the terms described in the LICENSE file in
55 # the root directory of this source tree.
66
7-from typing import Optional
8-
9-from llama_models.schema_utils import json_schema_type
107 from pydantic import BaseModel, Field
11-import boto3
128
139
14-@json_schema_type
15-class BedrockShieldConfig(BaseModel):
10+class BedrockSafetyConfig(BaseModel):
1611 """Configuration information for a guardrail that you want to use in the request."""
1712
18- aws_profile: Optional[str] = Field(
19- default='default',
13+ aws_profile: str = Field(
14+ default="default",
2015 description="The profile on the machine having valid aws credentials. This will ensure separation of creation to invocation",
2116 )
22-
23-
24-
modified llama_stack/providers/registry/safety.py +3 −3
@@ -41,10 +41,10 @@
4141 remote_provider_spec(
4242 api=Api.safety,
4343 adapter=AdapterSpec(
44- adapter_id="bedrock_guardrails",
45- pip_packages=['boto3',],
44+ adapter_id="bedrock",
45+ pip_packages=["boto3"],
4646 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",
4848 ),
4949 ),
5050 remote_provider_spec(