| 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 together import Together |
| 8 | |
| 9 | from llama_stack.distribution.request_headers import get_request_provider_data |
| 10 | |
| 11 | from .config import TogetherProviderDataValidator, TogetherSafetyConfig |
| 12 | |
| 13 | |
| 14 | class TogetherSafetyImpl(Safety): |
| 15 | def __init__(self, config: TogetherSafetyConfig) -> None: |
| 16 | self.config = config |
| 17 | |
| 18 | async def initialize(self) -> None: |
| 19 | pass |
| 20 | |
| 21 | async def run_shield( |
| 22 | self, shield_type: str, messages: List[Message], params: Dict[str, Any] = None |
| 23 | ) -> RunShieldResponse: |
| 24 | if shield_type != "llama_guard": |
| 25 | raise ValueError(f"shield type {shield_type} is not supported") |
| 26 | |
| 27 | provider_data = get_request_provider_data() |
| 28 | |
| 29 | together_api_key = None |
| 30 | if provider_data is not None: |
| 31 | if not isinstance(provider_data, TogetherProviderDataValidator): |
| 32 | raise ValueError( |
| 33 | 'Pass Together API Key in the header X-LlamaStack-ProviderData as { "together_api_key": <your api key>}' |
| 34 | ) |
| 35 | |
| 36 | together_api_key = provider_data.together_api_key |
| 37 | if not together_api_key: |
| 38 | together_api_key = self.config.api_key |
| 39 | |
| 40 | if not together_api_key: |
| 41 | raise ValueError("The API key must be provider in the header or config") |
| 42 | |
| 43 | # messages can have role assistant or user |
| 44 | api_messages = [] |
| 45 | for message in messages: |
| 46 | if message.role in (Role.user.value, Role.assistant.value): |
| 47 | api_messages.append({"role": message.role, "content": message.content}) |
| 48 | |
| 49 | violation = await get_safety_response(together_api_key, api_messages) |
| 50 | return RunShieldResponse(violation=violation) |
| 51 | |
| 52 | |
| 53 | async def get_safety_response( |
| 54 | api_key: str, messages: List[Dict[str, str]] |
| 55 | ) -> Optional[SafetyViolation]: |
| 56 | client = Together(api_key=api_key) |
| 57 | response = client.chat.completions.create( |
| 58 | messages=messages, model="meta-llama/Meta-Llama-Guard-3-8B" |
| 59 | ) |
| 60 | if len(response.choices) == 0: |
| 61 | return None |
| 62 | |
| 63 | response_text = response.choices[0].message.content |
| 64 | if response_text == "safe": |
| 65 | return None |
| 66 | |
| 67 | parts = response_text.split("\n") |
| 68 | if len(parts) != 2: |
| 69 | return None |
| 70 | |
| 71 | if parts[0] == "unsafe": |
| 72 | return SafetyViolation( |
| 73 | violation_level=ViolationLevel.ERROR, |
| 74 | user_message="unsafe", |
| 75 | metadata={"violation_type": parts[1]}, |
| 76 | ) |
| 77 | |
| 78 | return None |