mirror of
https://github.com/meta-llama/llama-stack.git
synced 2025-12-17 15:19:46 +00:00
Signed-off-by: Francisco Javier Arceo <farceo@redhat.com> chore: Enable keyword search for Milvus inline (#3073) With https://github.com/milvus-io/milvus-lite/pull/294 - Milvus Lite supports keyword search using BM25. While introducing keyword search we had explicitly disabled it for inline milvus. This PR removes the need for the check, and enables `inline::milvus` for tests. <!-- If resolving an issue, uncomment and update the line below --> <!-- Closes #[issue-number] --> Run llama stack with `inline::milvus` enabled: ``` pytest tests/integration/vector_io/test_openai_vector_stores.py::test_openai_vector_store_search_modes --stack-config=http://localhost:8321 --embedding-model=all-MiniLM-L6-v2 -v ``` ``` INFO 2025-08-07 17:06:20,932 tests.integration.conftest:64 tests: Setting DISABLE_CODE_SANDBOX=1 for macOS =========================================================================================== test session starts ============================================================================================ platform darwin -- Python 3.12.11, pytest-7.4.4, pluggy-1.5.0 -- /Users/vnarsing/miniconda3/envs/stack-client/bin/python cachedir: .pytest_cache metadata: {'Python': '3.12.11', 'Platform': 'macOS-14.7.6-arm64-arm-64bit', 'Packages': {'pytest': '7.4.4', 'pluggy': '1.5.0'}, 'Plugins': {'asyncio': '0.23.8', 'cov': '6.0.0', 'timeout': '2.2.0', 'socket': '0.7.0', 'html': '3.1.1', 'langsmith': '0.3.39', 'anyio': '4.8.0', 'metadata': '3.0.0'}} rootdir: /Users/vnarsing/go/src/github/meta-llama/llama-stack configfile: pyproject.toml plugins: asyncio-0.23.8, cov-6.0.0, timeout-2.2.0, socket-0.7.0, html-3.1.1, langsmith-0.3.39, anyio-4.8.0, metadata-3.0.0 asyncio: mode=Mode.AUTO collected 3 items tests/integration/vector_io/test_openai_vector_stores.py::test_openai_vector_store_search_modes[None-None-all-MiniLM-L6-v2-None-384-vector] PASSED [ 33%] tests/integration/vector_io/test_openai_vector_stores.py::test_openai_vector_store_search_modes[None-None-all-MiniLM-L6-v2-None-384-keyword] PASSED [ 66%] tests/integration/vector_io/test_openai_vector_stores.py::test_openai_vector_store_search_modes[None-None-all-MiniLM-L6-v2-None-384-hybrid] PASSED [100%] ============================================================================================ 3 passed in 4.75s ============================================================================================= ``` Signed-off-by: Varsha Prasad Narsing <varshaprasad96@gmail.com> Co-authored-by: Francisco Arceo <arceofrancisco@gmail.com> chore: Fixup main pre commit (#3204) build: Bump version to 0.2.18 chore: Faster npm pre-commit (#3206) Adds npm to pre-commit.yml installation and caches ui Removes node installation during pre-commit. <!-- If resolving an issue, uncomment and update the line below --> <!-- Closes #[issue-number] --> <!-- Describe the tests you ran to verify your changes with result summaries. *Provide clear instructions so the plan can be easily re-executed.* --> Signed-off-by: Francisco Javier Arceo <farceo@redhat.com> chiecking in for tonight, wip moving to agents api Signed-off-by: Francisco Javier Arceo <farceo@redhat.com> remove log Signed-off-by: Francisco Javier Arceo <farceo@redhat.com> updated Signed-off-by: Francisco Javier Arceo <farceo@redhat.com> fix: disable ui-prettier & ui-eslint (#3207) chore(pre-commit): add pre-commit hook to enforce llama_stack logger usage (#3061) This PR adds a step in pre-commit to enforce using `llama_stack` logger. Currently, various parts of the code base uses different loggers. As a custom `llama_stack` logger exist and used in the codebase, it is better to standardize its utilization. Signed-off-by: Mustafa Elbehery <melbeher@redhat.com> Co-authored-by: Matthew Farrellee <matt@cs.wisc.edu> fix: fix ```openai_embeddings``` for asymmetric embedding NIMs (#3205) NVIDIA asymmetric embedding models (e.g., `nvidia/llama-3.2-nv-embedqa-1b-v2`) require an `input_type` parameter not present in the standard OpenAI embeddings API. This PR adds the `input_type="query"` as default and updates the documentation to suggest using the `embedding` API for passage embeddings. <!-- If resolving an issue, uncomment and update the line below --> Resolves #2892 ``` pytest -s -v tests/integration/inference/test_openai_embeddings.py --stack-config="inference=nvidia" --embedding-model="nvidia/llama-3.2-nv-embedqa-1b-v2" --env NVIDIA_API_KEY={nvidia_api_key} --env NVIDIA_BASE_URL="https://integrate.api.nvidia.com" ``` cleaning up Signed-off-by: Francisco Javier Arceo <farceo@redhat.com> updating session manager to cache messages locally Signed-off-by: Francisco Javier Arceo <farceo@redhat.com> fix linter Signed-off-by: Francisco Javier Arceo <farceo@redhat.com> more cleanup Signed-off-by: Francisco Javier Arceo <farceo@redhat.com>
160 lines
5.8 KiB
Python
160 lines
5.8 KiB
Python
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
# All rights reserved.
|
|
#
|
|
# This source code is licensed under the terms described in the LICENSE file in
|
|
# the root directory of this source tree.
|
|
|
|
from typing import Any
|
|
|
|
import requests
|
|
|
|
from llama_stack.apis.inference import Message
|
|
from llama_stack.apis.safety import RunShieldResponse, Safety, SafetyViolation, ViolationLevel
|
|
from llama_stack.apis.shields import Shield
|
|
from llama_stack.log import get_logger
|
|
from llama_stack.providers.datatypes import ShieldsProtocolPrivate
|
|
from llama_stack.providers.utils.inference.openai_compat import convert_message_to_openai_dict_new
|
|
|
|
from .config import NVIDIASafetyConfig
|
|
|
|
logger = get_logger(name=__name__, category="safety")
|
|
|
|
|
|
class NVIDIASafetyAdapter(Safety, ShieldsProtocolPrivate):
|
|
def __init__(self, config: NVIDIASafetyConfig) -> None:
|
|
"""
|
|
Initialize the NVIDIASafetyAdapter with a given safety configuration.
|
|
|
|
Args:
|
|
config (NVIDIASafetyConfig): The configuration containing the guardrails service URL and config ID.
|
|
"""
|
|
self.config = config
|
|
|
|
async def initialize(self) -> None:
|
|
pass
|
|
|
|
async def shutdown(self) -> None:
|
|
pass
|
|
|
|
async def register_shield(self, shield: Shield) -> None:
|
|
if not shield.provider_resource_id:
|
|
raise ValueError("Shield model not provided.")
|
|
|
|
async def unregister_shield(self, identifier: str) -> None:
|
|
pass
|
|
|
|
async def run_shield(
|
|
self, shield_id: str, messages: list[Message], params: dict[str, Any] | None = None
|
|
) -> RunShieldResponse:
|
|
"""
|
|
Run a safety shield check against the provided messages.
|
|
|
|
Args:
|
|
shield_id (str): The unique identifier for the shield to be used.
|
|
messages (List[Message]): A list of Message objects representing the conversation history.
|
|
params (Optional[dict[str, Any]]): Additional parameters for the shield check.
|
|
|
|
Returns:
|
|
RunShieldResponse: The response containing safety violation details if any.
|
|
|
|
Raises:
|
|
ValueError: If the shield with the provided shield_id is not found.
|
|
"""
|
|
shield = await self.shield_store.get_shield(shield_id)
|
|
if not shield:
|
|
raise ValueError(f"Shield {shield_id} not found")
|
|
|
|
self.shield = NeMoGuardrails(self.config, shield.shield_id)
|
|
return await self.shield.run(messages)
|
|
|
|
|
|
class NeMoGuardrails:
|
|
"""
|
|
A class that encapsulates NVIDIA's guardrails safety logic.
|
|
|
|
Sends messages to the guardrails service and interprets the response to determine
|
|
if a safety violation has occurred.
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
config: NVIDIASafetyConfig,
|
|
model: str,
|
|
threshold: float = 0.9,
|
|
temperature: float = 1.0,
|
|
):
|
|
"""
|
|
Initialize a NeMoGuardrails instance with the provided parameters.
|
|
|
|
Args:
|
|
config (NVIDIASafetyConfig): The safety configuration containing the config ID and guardrails URL.
|
|
model (str): The identifier or name of the model to be used for safety checks.
|
|
threshold (float, optional): The threshold for flagging violations. Defaults to 0.9.
|
|
temperature (float, optional): The temperature setting for the underlying model. Must be greater than 0. Defaults to 1.0.
|
|
|
|
Raises:
|
|
ValueError: If temperature is less than or equal to 0.
|
|
AssertionError: If config_id is not provided in the configuration.
|
|
"""
|
|
self.config_id = config.config_id
|
|
self.model = model
|
|
assert self.config_id is not None, "Must provide config id"
|
|
if temperature <= 0:
|
|
raise ValueError("Temperature must be greater than 0")
|
|
|
|
self.temperature = temperature
|
|
self.threshold = threshold
|
|
self.guardrails_service_url = config.guardrails_service_url
|
|
|
|
async def _guardrails_post(self, path: str, data: Any | None):
|
|
"""Helper for making POST requests to the guardrails service."""
|
|
headers = {
|
|
"Accept": "application/json",
|
|
}
|
|
response = requests.post(url=f"{self.guardrails_service_url}{path}", headers=headers, json=data)
|
|
response.raise_for_status()
|
|
return response.json()
|
|
|
|
async def run(self, messages: list[Message]) -> RunShieldResponse:
|
|
"""
|
|
Queries the /v1/guardrails/checks endpoint of the NeMo guardrails deployed API.
|
|
|
|
Args:
|
|
messages (List[Message]): A list of Message objects to be checked for safety violations.
|
|
|
|
Returns:
|
|
RunShieldResponse: If the response indicates a violation ("blocked" status), returns a
|
|
RunShieldResponse with a SafetyViolation; otherwise, returns a RunShieldResponse with violation set to None.
|
|
|
|
Raises:
|
|
requests.HTTPError: If the POST request fails.
|
|
"""
|
|
request_messages = [await convert_message_to_openai_dict_new(message) for message in messages]
|
|
request_data = {
|
|
"model": self.model,
|
|
"messages": request_messages,
|
|
"temperature": self.temperature,
|
|
"top_p": 1,
|
|
"frequency_penalty": 0,
|
|
"presence_penalty": 0,
|
|
"max_tokens": 160,
|
|
"stream": False,
|
|
"guardrails": {
|
|
"config_id": self.config_id,
|
|
},
|
|
}
|
|
response = await self._guardrails_post(path="/v1/guardrail/checks", data=request_data)
|
|
|
|
if response["status"] == "blocked":
|
|
user_message = "Sorry I cannot do this."
|
|
metadata = response["rails_status"]
|
|
|
|
return RunShieldResponse(
|
|
violation=SafetyViolation(
|
|
user_message=user_message,
|
|
violation_level=ViolationLevel.ERROR,
|
|
metadata=metadata,
|
|
)
|
|
)
|
|
|
|
return RunShieldResponse(violation=None)
|