Elffuss BraidHub

kikocis/llama-stack public

[aws-bedrock] Support for Bedrock Safety adapter (#96)

Changesete7e47c3d00f804d171a5e5560c3b96625165ba4f04decace7ed9f7e301b4b7a4
Authorrsgrewal-aws <102243526+rsgrewal-aws@users.noreply.github.com> · 2024-09-24 19:16 -07:00
CommitterGitHub <noreply@github.com> · 2024-09-24 19:16 -07:00
Parents24a815d896f1

Browse the files at this changeset

4 files changed

added llama_stack/providers/adapters/safety/bedrock/__init__.py +18 −0
@@ -0,0 +1,18 @@
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+from typing import Any
9+
10+from .config import BedrockShieldConfig
11+
12+
13+async def get_adapter_impl(config: BedrockShieldConfig, _deps) -> Any:
14+ from .bedrock import BedrockShieldAdapter
15+
16+ impl = BedrockShieldAdapter(config)
17+ await impl.initialize()
18+ return impl
No newline at the end of the file
added llama_stack/providers/adapters/safety/bedrock/bedrock.py +103 −0
@@ -0,0 +1,103 @@
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+from typing import Any, AsyncGenerator, Dict
9+from .config import BedrockShieldConfig
10+import traceback
11+import asyncio
12+from enum import Enum
13+from typing import List
14+from pydantic import BaseModel, validator
15+from llama_stack.apis.safety import * # noqa
16+from llama_models.llama3.api.datatypes import * # noqa: F403
17+import boto3
18+import json
19+import logging
20+
21+logger = logging.getLogger(__name__)
22+
23+class BedrockShieldAdapter(Safety):
24+ def __init__(self, config: BedrockShieldConfig) -> None:
25+ self.config = config
26+
27+
28+ async def initialize(self) -> None:
29+ try:
30+ if not self.config.aws_profile:
31+ raise RuntimeError(f"Missing boto_client aws_profile in model info::{self.config}")
32+ print(f"initializing with profile --- > {self.config}::")
33+ self.boto_client_profile = self.config.aws_profile
34+ self.boto_client = boto3.Session(profile_name=self.boto_client_profile).client('bedrock-runtime')
35+ except Exception as e:
36+ import traceback
37+
38+ traceback.print_exc()
39+ raise RuntimeError(f"Error initializing BedrockSafetyAdapter: {e}") from e
40+
41+ async def shutdown(self) -> None:
42+ pass
43+
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+ }
51+ }
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"]
57+ """
58+ ret_violation = None
59+ try:
60+ 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
68+ content_messages = []
69+ for message in messages:
70+ content_messages.append({"text": {"text": message.content}})
71+ logger.debug(f"run_shield::final:messages::{json.dumps(content_messages, indent=2)}:")
72+
73+ 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
78+ )
79+ logger.debug(f"run_shield:: response: {response}::")
80+ if response['action'] == 'GUARDRAIL_INTERVENED':
81+ user_message=""
82+ metadata={}
83+ for output in response['outputs']:
84+ # 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']:
87+ # 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,
91+ violation_level=ViolationLevel.ERROR,
92+ metadata=metadata
93+ )
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+
103+
added llama_stack/providers/adapters/safety/bedrock/config.py +24 −0
@@ -0,0 +1,24 @@
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 typing import Optional
8+
9+from llama_models.schema_utils import json_schema_type
10+from pydantic import BaseModel, Field
11+import boto3
12+
13+
14+@json_schema_type
15+class BedrockShieldConfig(BaseModel):
16+ """Configuration information for a guardrail that you want to use in the request."""
17+
18+ aws_profile: Optional[str] = Field(
19+ default='default',
20+ description="The profile on the machine having valid aws credentials. This will ensure separation of creation to invocation",
21+ )
22+
23+
24+
modified llama_stack/providers/registry/safety.py +9 −0
@@ -40,6 +40,15 @@
4040 config_class="llama_stack.providers.adapters.safety.sample.SampleConfig",
4141 ),
4242 ),
43+ remote_provider_spec(
44+ api=Api.safety,
45+ adapter=AdapterSpec(
46+ adapter_id="bedrock_guardrails",
47+ pip_packages=['boto3',],
48+ module="llama_stack.providers.adapters.safety.bedrock",
49+ config_class="llama_stack.providers.adapters.safety.bedrock.config.BedrockShieldConfig",
50+ ),
51+ ),
4352 remote_provider_spec(
4453 api=Api.safety,
4554 adapter=AdapterSpec(