kikocis/llama-stack public
Changesets · Branches · Tags · Compare
| Changeset | 24a815d896f1912a5a73f29635ac48aebc8fa86dc6266cddb204e4b2ac41261f |
|---|---|
| Author | Yogish Baliga <yogish@together.ai> · 2024-09-20 09:35 -07:00 |
| Committer | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-24 18:35 -07:00 |
| Parents | 6c30136e2df6 |
8 files changed
modified llama_stack/apis/safety/client.py +8 −1
| @@ -49,7 +49,14 @@ | ||
| 49 | 49 | shield_type=shield_type, |
| 50 | 50 | messages=[encodable_dict(m) for m in messages], |
| 51 | 51 | ), |
| 52 | - headers={"Content-Type": "application/json"}, | |
| 52 | + headers={ | |
| 53 | + "Content-Type": "application/json", | |
| 54 | + "X-LlamaStack-ProviderData": json.dumps( | |
| 55 | + { | |
| 56 | + "together_api_key": "1882f9a484fc7c6ce3e4dc90272d5db52346c93838daab3d704803181f396b22" | |
| 57 | + } | |
| 58 | + ), | |
| 59 | + }, | |
| 53 | 60 | timeout=20, |
| 54 | 61 | ) |
| 55 | 62 |
modified llama_stack/distribution/request_headers.py +12 −11
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | import json |
| 8 | 8 | import threading |
| 9 | -from typing import Any, Dict, Optional | |
| 9 | +from typing import Any, Dict, List | |
| 10 | 10 | |
| 11 | 11 | from .utils.dynamic import instantiate_class_type |
| 12 | 12 | |
| @@ -17,8 +17,8 @@ | ||
| 17 | 17 | return getattr(_THREAD_LOCAL, "provider_data", None) |
| 18 | 18 | |
| 19 | 19 | |
| 20 | -def set_request_provider_data(headers: Dict[str, str], validator_class: Optional[str]): | |
| 21 | - if not validator_class: | |
| 20 | +def set_request_provider_data(headers: Dict[str, str], validator_classes: List[str]): | |
| 21 | + if not validator_classes: | |
| 22 | 22 | return |
| 23 | 23 | |
| 24 | 24 | keys = [ |
| @@ -39,11 +39,12 @@ | ||
| 39 | 39 | print("Provider data not encoded as a JSON object!", val) |
| 40 | 40 | return |
| 41 | 41 | |
| 42 | - validator = instantiate_class_type(validator_class) | |
| 43 | - try: | |
| 44 | - provider_data = validator(**val) | |
| 45 | - except Exception as e: | |
| 46 | - print("Error parsing provider data", e) | |
| 47 | - return | |
| 48 | - | |
| 49 | - _THREAD_LOCAL.provider_data = provider_data | |
| 42 | + for validator_class in validator_classes: | |
| 43 | + validator = instantiate_class_type(validator_class) | |
| 44 | + try: | |
| 45 | + provider_data = validator(**val) | |
| 46 | + if provider_data: | |
| 47 | + _THREAD_LOCAL.provider_data = provider_data | |
| 48 | + return | |
| 49 | + except Exception as e: | |
| 50 | + print("Error parsing provider data", e) |
modified llama_stack/distribution/server/server.py +26 −9
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | AsyncIterator as AsyncIteratorABC, |
| 16 | 16 | ) |
| 17 | 17 | from contextlib import asynccontextmanager |
| 18 | +from http import HTTPStatus | |
| 18 | 19 | from ssl import SSLError |
| 19 | 20 | from typing import ( |
| 20 | 21 | Any, |
| @@ -88,7 +89,7 @@ | ||
| 88 | 89 | ) |
| 89 | 90 | |
| 90 | 91 | |
| 91 | -def translate_exception(exc: Exception) -> HTTPException: | |
| 92 | +def translate_exception(exc: Exception) -> Union[HTTPException, RequestValidationError]: | |
| 92 | 93 | if isinstance(exc, ValidationError): |
| 93 | 94 | exc = RequestValidationError(exc.raw_errors) |
| 94 | 95 | |
| @@ -207,7 +208,7 @@ | ||
| 207 | 208 | |
| 208 | 209 | |
| 209 | 210 | def create_dynamic_typed_route( |
| 210 | - func: Any, method: str, provider_data_validator: Optional[str] | |
| 211 | + func: Any, method: str, provider_data_validators: List[str] | |
| 211 | 212 | ): |
| 212 | 213 | hints = get_type_hints(func) |
| 213 | 214 | response_model = hints.get("return") |
| @@ -223,7 +224,7 @@ | ||
| 223 | 224 | async def endpoint(request: Request, **kwargs): |
| 224 | 225 | await start_trace(func.__name__) |
| 225 | 226 | |
| 226 | - set_request_provider_data(request.headers, provider_data_validator) | |
| 227 | + set_request_provider_data(request.headers, provider_data_validators) | |
| 227 | 228 | |
| 228 | 229 | async def sse_generator(event_gen): |
| 229 | 230 | try: |
| @@ -254,7 +255,7 @@ | ||
| 254 | 255 | async def endpoint(request: Request, **kwargs): |
| 255 | 256 | await start_trace(func.__name__) |
| 256 | 257 | |
| 257 | - set_request_provider_data(request.headers, provider_data_validator) | |
| 258 | + set_request_provider_data(request.headers, provider_data_validators) | |
| 258 | 259 | |
| 259 | 260 | try: |
| 260 | 261 | return ( |
| @@ -415,6 +416,15 @@ | ||
| 415 | 416 | |
| 416 | 417 | app = FastAPI() |
| 417 | 418 | |
| 419 | + # Health check is added to enable deploying the docker container image on Kubernetes which require | |
| 420 | + # a health check that can return 200 for readiness and liveness check | |
| 421 | + class HealthCheck(BaseModel): | |
| 422 | + status: str = "OK" | |
| 423 | + | |
| 424 | + @app.get("/healthcheck", status_code=HTTPStatus.OK, response_model=HealthCheck) | |
| 425 | + async def healthcheck(): | |
| 426 | + return HealthCheck(status="OK") | |
| 427 | + | |
| 418 | 428 | impls, specs = asyncio.run(resolve_impls_with_routing(config)) |
| 419 | 429 | if Api.telemetry in impls: |
| 420 | 430 | setup_logger(impls[Api.telemetry]) |
| @@ -454,15 +464,22 @@ | ||
| 454 | 464 | ) |
| 455 | 465 | |
| 456 | 466 | impl_method = getattr(impl, endpoint.name) |
| 467 | + | |
| 468 | + validators = [] | |
| 469 | + if isinstance(provider_spec, AutoRoutedProviderSpec): | |
| 470 | + inner_specs = specs[provider_spec.routing_table_api].inner_specs | |
| 471 | + for spec in inner_specs: | |
| 472 | + if spec.provider_data_validator: | |
| 473 | + validators.append(spec.provider_data_validator) | |
| 474 | + elif not isinstance(provider_spec, RoutingTableProviderSpec): | |
| 475 | + if provider_spec.provider_data_validator: | |
| 476 | + validators.append(provider_spec.provider_data_validator) | |
| 477 | + | |
| 457 | 478 | getattr(app, endpoint.method)(endpoint.route, response_model=None)( |
| 458 | 479 | create_dynamic_typed_route( |
| 459 | 480 | impl_method, |
| 460 | 481 | endpoint.method, |
| 461 | - ( | |
| 462 | - provider_spec.provider_data_validator | |
| 463 | - if not isinstance(provider_spec, RoutingTableProviderSpec) | |
| 464 | - else None | |
| 465 | - ), | |
| 482 | + validators, | |
| 466 | 483 | ) |
| 467 | 484 | ) |
| 468 | 485 |
modified llama_stack/distribution/templates/local-together-build.yaml +1 −1
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | providers: |
| 5 | 5 | inference: remote::together |
| 6 | 6 | memory: meta-reference |
| 7 | - safety: meta-reference | |
| 7 | + safety: remote::together | |
| 8 | 8 | agents: meta-reference |
| 9 | 9 | telemetry: meta-reference |
| 10 | 10 | image_type: conda |
added llama_stack/providers/adapters/safety/together/__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 | +from .config import TogetherProviderDataValidator, TogetherSafetyConfig # noqa: F401 | |
| 8 | + | |
| 9 | + | |
| 10 | +async def get_adapter_impl(config: TogetherSafetyConfig, _deps): | |
| 11 | + from .together import TogetherSafetyImpl | |
| 12 | + | |
| 13 | + assert isinstance( | |
| 14 | + config, TogetherSafetyConfig | |
| 15 | + ), f"Unexpected config type: {type(config)}" | |
| 16 | + impl = TogetherSafetyImpl(config) | |
| 17 | + await impl.initialize() | |
| 18 | + return impl |
added llama_stack/providers/adapters/safety/together/config.py +26 −0
| @@ -0,0 +1,26 @@ | ||
| 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 | + | |
| 12 | + | |
| 13 | +class TogetherProviderDataValidator(BaseModel): | |
| 14 | + together_api_key: str | |
| 15 | + | |
| 16 | + | |
| 17 | +@json_schema_type | |
| 18 | +class TogetherSafetyConfig(BaseModel): | |
| 19 | + url: str = Field( | |
| 20 | + default="https://api.together.xyz/v1", | |
| 21 | + description="The URL for the Together AI server", | |
| 22 | + ) | |
| 23 | + api_key: Optional[str] = Field( | |
| 24 | + default=None, | |
| 25 | + description="The Together AI API Key (default for the distribution, if any)", | |
| 26 | + ) |
added llama_stack/providers/adapters/safety/together/together.py +78 −0
| @@ -0,0 +1,78 @@ | ||
| 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 |
modified llama_stack/providers/registry/safety.py +19 −1
| @@ -6,7 +6,13 @@ | ||
| 6 | 6 | |
| 7 | 7 | from typing import List |
| 8 | 8 | |
| 9 | -from llama_stack.distribution.datatypes import * # noqa: F403 | |
| 9 | +from llama_stack.distribution.datatypes import ( | |
| 10 | + AdapterSpec, | |
| 11 | + Api, | |
| 12 | + InlineProviderSpec, | |
| 13 | + ProviderSpec, | |
| 14 | + remote_provider_spec, | |
| 15 | +) | |
| 10 | 16 | |
| 11 | 17 | |
| 12 | 18 | def available_providers() -> List[ProviderSpec]: |
| @@ -34,4 +40,16 @@ | ||
| 34 | 40 | config_class="llama_stack.providers.adapters.safety.sample.SampleConfig", |
| 35 | 41 | ), |
| 36 | 42 | ), |
| 43 | + remote_provider_spec( | |
| 44 | + api=Api.safety, | |
| 45 | + adapter=AdapterSpec( | |
| 46 | + adapter_id="together", | |
| 47 | + pip_packages=[ | |
| 48 | + "together", | |
| 49 | + ], | |
| 50 | + module="llama_stack.providers.adapters.safety.together", | |
| 51 | + config_class="llama_stack.providers.adapters.safety.together.TogetherSafetyConfig", | |
| 52 | + provider_data_validator="llama_stack.providers.adapters.safety.together.TogetherProviderDataValidator", | |
| 53 | + ), | |
| 54 | + ), | |
| 37 | 55 | ] |