The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat: add ability to auth to azure with token (#27556)
Shivam Rawatc7739c9ed55c
diff --git a/litellm/__init__.py b/litellm/__init__.pyindex cf05fc4c980..fd3d47ec154 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -206,6 +206,7 @@ add_user_information_to_llm_headers: Optional[bool] = ()store_audit_logs = False # Enterprise feature, allow users to see audit logsskip_system_message_in_guardrail: bool = False+skip_tool_message_in_guardrail: bool = False### end of callbacks #############email: Optional[str] = (diff --git a/litellm/_redis.py b/litellm/_redis.pyindex f12afbac297..1c11ea829ba 100644--- a/litellm/_redis.py+++ b/litellm/_redis.py@@ -19,6 +19,7 @@ import redis.asyncio as async_redis # type: ignorefrom litellm import get_secret, get_secret_strfrom litellm._redis_credential_provider import (+ AzureADCredentialProvider,GCPIAMCredentialProvider,_generate_gcp_iam_access_token,)@@ -27,6 +28,8 @@ from litellm.litellm_core_utils.sensitive_data_masker import SensitiveDataMaskerfrom ._logging import verbose_logger+AZURE_REDIS_SCOPE = "https://redis.azure.com/.default"+def _get_redis_kwargs():arg_spec = inspect.getfullargspec(redis.Redis)@@ -43,6 +46,10 @@ def _get_redis_kwargs():"redis_connect_func","gcp_service_account","gcp_ssl_ca_certs",+ "azure_redis_ad_token",+ "azure_client_id",+ "azure_tenant_id",+ "azure_client_secret",]available_args = [x for x in arg_spec.args if x not in exclude_args] + include_args@@ -89,6 +96,10 @@ def _get_redis_cluster_kwargs(client=None):) # Needed for sync clusters and IAM detectionavailable_args.append("gcp_service_account")available_args.append("gcp_ssl_ca_certs")+ available_args.append("azure_redis_ad_token")+ available_args.append("azure_client_id")+ available_args.append("azure_tenant_id")+ available_args.append("azure_client_secret")available_args.append("max_connections")return available_args@@ -155,6 +166,125 @@ def create_gcp_iam_redis_connect_func(return iam_connect+def _build_azure_credential(+ azure_client_id: Optional[str] = None,+ azure_tenant_id: Optional[str] = None,+ azure_client_secret: Optional[str] = None,+):+ """+ Build a long-lived Azure credential object.++ Azure SDK credentials cache tokens internally and handle expiry/refresh+ transparently, so this should be called once and the result reused.+ """+ try:+ from azure.identity import (+ ClientSecretCredential,+ DefaultAzureCredential,+ ManagedIdentityCredential,+ )+ except ImportError:+ raise ImportError(+ "azure-identity is required for Azure AD Redis authentication. "+ "Install it with: pip install azure-identity"+ )++ _client_id = azure_client_id or os.environ.get("AZURE_CLIENT_ID")+ _tenant_id = azure_tenant_id or os.environ.get("AZURE_TENANT_ID")+ _client_secret = azure_client_secret or os.environ.get("AZURE_CLIENT_SECRET")++ if _client_id and _tenant_id and _client_secret:+ return ClientSecretCredential(+ client_id=_client_id,+ tenant_id=_tenant_id,+ client_secret=_client_secret,+ )+ elif _client_id:+ return ManagedIdentityCredential(client_id=_client_id)+ else:+ return DefaultAzureCredential()+++def _generate_azure_ad_redis_token(+ azure_client_id: Optional[str] = None,+ azure_tenant_id: Optional[str] = None,+ azure_client_secret: Optional[str] = None,+) -> str:+ """+ One-shot helper that builds a credential and fetches a single Azure AD+ access token for Redis. Each call rebuilds the credential and performs a+ network round-trip, so it should not be used in steady-state Redis flows+ — the sync (``create_azure_ad_redis_connect_func``) and async paths+ (``AzureADCredentialProvider``) keep the credential alive across+ connections so the Azure SDK's internal cache + silent refresh apply.+ """+ credential = _build_azure_credential(+ azure_client_id=azure_client_id,+ azure_tenant_id=azure_tenant_id,+ azure_client_secret=azure_client_secret,+ )+ token = credential.get_token(AZURE_REDIS_SCOPE)+ return token.token+++def create_azure_ad_redis_connect_func(+ azure_client_id: Optional[str] = None,+ azure_tenant_id: Optional[str] = None,+ azure_client_secret: Optional[str] = None,+) -> Callable:+ """+ Creates a custom Redis connection function for Azure AD authentication.++ Used for sync Redis clients. The credential is created once (captured by the+ closure) and reused across connections — the Azure SDK handles token caching+ and silent renewal internally. Only ``get_token`` is called per connection.+ """+ credential = _build_azure_credential(+ azure_client_id=azure_client_id,+ azure_tenant_id=azure_tenant_id,+ azure_client_secret=azure_client_secret,+ )++ def ad_connect(self):+ """Initialize the connection and authenticate using Azure AD"""+ from redis.exceptions import (+ AuthenticationError,+ AuthenticationWrongNumberOfArgsError,+ )+ from redis.utils import str_if_bytes++ self._parser.on_connect(self)++ access_token = credential.get_token(AZURE_REDIS_SCOPE).token++ # Only include username when explicitly set — sending AUTH "" <token>+ # is invalid for most ACL-configured Azure Redis instances.+ username = os.environ.get("REDIS_USERNAME", "")+ if username:+ auth_args = (username, access_token)+ else:+ auth_args = (access_token,)++ self.send_command("AUTH", *auth_args, check_health=False)++ try:+ auth_response = self.read_response()+ except AuthenticationWrongNumberOfArgsError:+ # Fallback: try with just the token (Redis < 6 / no ACL)+ self.send_command("AUTH", access_token, check_health=False)+ auth_response = self.read_response()++ if str_if_bytes(auth_response) != "OK":+ raise AuthenticationError("Azure AD authentication failed for Redis")++ # Attach the live credential object so async paths can wrap it in+ # AzureADCredentialProvider for refresh-aware token retrieval. The raw+ # client_id/tenant_id/secret are intentionally NOT exposed here — the+ # credential closure already holds them.+ ad_connect._azure_credential = credential # type: ignore[attr-defined]+ return ad_connect++def get_redis_url_from_environment():if "REDIS_URL" in os.environ:return os.environ["REDIS_URL"]@@ -179,7 +309,7 @@ def get_redis_url_from_environment():return f"{redis_protocol}://{auth_part}{os.environ['REDIS_HOST']}:{os.environ['REDIS_PORT']}"-def _get_redis_client_logic(**env_overrides):+def _get_redis_client_logic(**env_overrides): # noqa: PLR0915"""Common functionality across sync + async redis client implementations"""@@ -253,6 +383,52 @@ def _get_redis_client_logic(**env_overrides):if _gcp_ssl_ca_certs and redis_kwargs.get("ssl", False):redis_kwargs["ssl_ca_certs"] = _gcp_ssl_ca_certs+ # Handle Azure AD authentication (after GCP IAM block)+ _azure_redis_ad_token = redis_kwargs.get("azure_redis_ad_token") or get_secret(+ "REDIS_AZURE_AD_TOKEN"+ )++ _azure_ad_enabled = (+ _azure_redis_ad_token is not None+ and str(_azure_redis_ad_token).lower() == "true"+ )++ if _azure_ad_enabled and _gcp_service_account is not None:+ verbose_logger.warning(+ "Both GCP IAM (gcp_service_account) and Azure AD (azure_redis_ad_token) are configured for Redis. "+ "Using GCP IAM. Remove one to avoid misconfiguration."+ )++ if _azure_ad_enabled and _gcp_service_account is None:+ _azure_client_id = redis_kwargs.get("azure_client_id") or get_secret_str(+ "AZURE_CLIENT_ID"+ )+ _azure_tenant_id = redis_kwargs.get("azure_tenant_id") or get_secret_str(+ "AZURE_TENANT_ID"+ )+ _azure_client_secret = redis_kwargs.get(+ "azure_client_secret"+ ) or get_secret_str("AZURE_CLIENT_SECRET")++ verbose_logger.debug("Setting up Azure AD authentication for Redis.")+ redis_kwargs["redis_connect_func"] = create_azure_ad_redis_connect_func(+ azure_client_id=_azure_client_id,+ azure_tenant_id=_azure_tenant_id,+ azure_client_secret=_azure_client_secret,+ )+ # Marker for async paths to detect Azure AD auth. The live credential+ # object is attached separately as `_azure_credential` by+ # `create_azure_ad_redis_connect_func`; the raw client_id/tenant_id/secret+ # are intentionally NOT exposed on the function to avoid leaking+ # credentials via inspection or logging.+ redis_kwargs["redis_connect_func"]._azure_redis_ad_token = True # type: ignore[attr-defined]++ # Always remove Azure-specific kwargs that shouldn't be passed to Redis client+ redis_kwargs.pop("azure_redis_ad_token", None)+ redis_kwargs.pop("azure_client_id", None)+ redis_kwargs.pop("azure_tenant_id", None)+ redis_kwargs.pop("azure_client_secret", None)+if "url" in redis_kwargs and redis_kwargs["url"] is not None:# Only strip host/port/db/password when not routing to a cluster.# When startup_nodes is also present the cluster path takes priority and@@ -373,7 +549,7 @@ def get_redis_client(**env_overrides):return redis.Redis(**redis_kwargs)-def get_redis_async_client(+def get_redis_async_client( # noqa: PLR0915connection_pool: Optional[async_redis.BlockingConnectionPool] = None,**env_overrides,) -> Union[async_redis.Redis, async_redis.RedisCluster]:@@ -398,6 +574,14 @@ def get_redis_async_client(cluster_kwargs["credential_provider"] = GCPIAMCredentialProvider(redis_connect_func._gcp_service_account)+ # Handle Azure AD authentication for async clusters via CredentialProvider+ # so the credential's internal cache + silent refresh runs per connection+ # (mirrors GCP IAM above; avoids static-token-baked-in-pool expiry).+ elif redis_connect_func and hasattr(redis_connect_func, "_azure_credential"):+ cluster_kwargs["credential_provider"] = AzureADCredentialProvider(+ redis_connect_func._azure_credential,+ username=os.environ.get("REDIS_USERNAME") or None,+ )new_startup_nodes: List[ClusterNode] = []@@ -431,6 +615,22 @@ def get_redis_async_client(# Check for Redis Sentinelif "sentinel_nodes" in redis_kwargs and "service_name" in redis_kwargs:return _init_async_redis_sentinel(redis_kwargs)++ # Wrap GCP / Azure AD auth in a CredentialProvider for the standard async+ # Redis client. The async client doesn't support redis_connect_func, but it+ # does honour credential_provider — which is called per connection, so the+ # underlying SDK can refresh tokens silently before they expire.+ redis_connect_func = redis_kwargs.pop("redis_connect_func", None)+ if redis_connect_func and hasattr(redis_connect_func, "_azure_credential"):+ redis_kwargs["credential_provider"] = AzureADCredentialProvider(+ redis_connect_func._azure_credential,+ username=os.environ.get("REDIS_USERNAME") or None,+ )+ elif redis_connect_func and hasattr(redis_connect_func, "_gcp_service_account"):+ redis_kwargs["credential_provider"] = GCPIAMCredentialProvider(+ redis_connect_func._gcp_service_account+ )+_pretty_print_redis_config(redis_kwargs=redis_kwargs)if connection_pool is not None:@@ -464,6 +664,21 @@ def get_redis_connection_pool(redis_kwargs["max_connections"],)return async_redis.BlockingConnectionPool.from_url(**pool_kwargs)++ # Wrap GCP / Azure AD auth in a CredentialProvider so pool-managed+ # connections re-fetch tokens via the SDK's internal cache + silent refresh+ # rather than reusing a single token captured at pool creation.+ redis_connect_func = redis_kwargs.pop("redis_connect_func", None)+ if redis_connect_func and hasattr(redis_connect_func, "_azure_credential"):+ redis_kwargs["credential_provider"] = AzureADCredentialProvider(+ redis_connect_func._azure_credential,+ username=os.environ.get("REDIS_USERNAME") or None,+ )+ elif redis_connect_func and hasattr(redis_connect_func, "_gcp_service_account"):+ redis_kwargs["credential_provider"] = GCPIAMCredentialProvider(+ redis_connect_func._gcp_service_account+ )+connection_class = async_redis.Connectionif "ssl" in redis_kwargs:connection_class = async_redis.SSLConnectiondiff --git a/litellm/_redis_credential_provider.py b/litellm/_redis_credential_provider.pyindex 70725fe12c4..586b1c7716c 100644--- a/litellm/_redis_credential_provider.py+++ b/litellm/_redis_credential_provider.py@@ -1,10 +1,13 @@import asyncioimport threadingimport time-from typing import Dict, Tuple+from typing import Any, Dict, Optional, Tuple, Unionfrom redis.credentials import CredentialProvider # type: ignore[attr-defined]+# Azure AD scope for Redis Cache for Azure.+AZURE_REDIS_SCOPE = "https://redis.azure.com/.default"+# GCP IAM tokens are valid for 1 hour. Cache for 55 minutes to refresh before expiry._GCP_IAM_TOKEN_TTL_SECONDS = 3300@@ -101,3 +104,33 @@ class GCPIAMCredentialProvider(CredentialProvider):_get_cached_gcp_iam_token, self._gcp_service_account)return (token,)+++class AzureADCredentialProvider(CredentialProvider):+ """+ redis.credentials.CredentialProvider implementation that supplies Azure AD+ tokens for Redis authentication.++ Wraps an azure-identity credential object so the Azure SDK's internal token+ cache and silent refresh are honoured on every Redis connection. This avoids+ the static-token-baked-in-pool issue where pool-managed connections would+ fail authentication after the initial token expired (~1 hour TTL).+ """++ def __init__(self, credential: Any, username: Optional[str] = None) -> None:+ self._credential = credential+ self._username = username++ def get_credentials(self) -> Union[Tuple[str], Tuple[str, str]]:+ token = self._credential.get_token(AZURE_REDIS_SCOPE).token+ if self._username:+ return (self._username, token)+ return (token,)++ async def get_credentials_async(self) -> Union[Tuple[str], Tuple[str, str]]:+ token_obj = await asyncio.to_thread(+ self._credential.get_token, AZURE_REDIS_SCOPE+ )+ if self._username:+ return (self._username, token_obj.token)+ return (token_obj.token,)diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.pyindex 2bb82f227bb..74dadee5ecb 100644--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py@@ -23,7 +23,9 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.transformation imfrom litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslationfrom litellm.llms.base_llm.guardrail_translation.utils import (effective_skip_system_message_for_guardrail,+ effective_skip_tool_message_for_guardrail,openai_messages_without_system,+ openai_messages_without_tool,)from litellm.proxy.pass_through_endpoints.llm_provider_handlers.anthropic_passthrough_logging_handler import (AnthropicPassthroughLoggingHandler,@@ -108,6 +110,7 @@ class AnthropicMessagesHandler(BaseTranslation):return dataskip_system = effective_skip_system_message_for_guardrail(guardrail_to_apply)+ skip_tool = effective_skip_tool_message_for_guardrail(guardrail_to_apply)chat_completion_compatible_request = self._translate_to_openai(data)@@ -117,6 +120,8 @@ class AnthropicMessagesHandler(BaseTranslation):)if skip_system:structured_messages = openai_messages_without_system(structured_messages)+ if skip_tool:+ structured_messages = openai_messages_without_tool(structured_messages)texts_to_check: List[str] = []images_to_check: List[str] = []@@ -134,6 +139,7 @@ class AnthropicMessagesHandler(BaseTranslation):images_to_check=images_to_check,task_mappings=task_mappings,skip_system_message=skip_system,+ skip_tool_message=skip_tool,)# Step 2: Apply guardrail to all texts in batch@@ -198,13 +204,17 @@ class AnthropicMessagesHandler(BaseTranslation):images_to_check: List[str],task_mappings: List[Tuple[int, Optional[int]]],skip_system_message: bool = False,+ skip_tool_message: bool = False,) -> None:"""Extract text content and images from a message.Override this method to customize text/image extraction logic."""- if skip_system_message and str(message.get("role") or "").lower() == "system":+ role = str(message.get("role") or "").lower()+ if skip_system_message and role == "system":+ return+ if skip_tool_message and role == "tool":returncontent = message.get("content", None)diff --git a/litellm/llms/base_llm/guardrail_translation/utils.py b/litellm/llms/base_llm/guardrail_translation/utils.pyindex cdd2d775371..97ece6b5eab 100644--- a/litellm/llms/base_llm/guardrail_translation/utils.py+++ b/litellm/llms/base_llm/guardrail_translation/utils.py@@ -14,7 +14,22 @@ def effective_skip_system_message_for_guardrail(guardrail_to_apply: Any) -> boolreturn bool(getattr(litellm, "skip_system_message_in_guardrail", False))+def effective_skip_tool_message_for_guardrail(guardrail_to_apply: Any) -> bool:+ per = getattr(guardrail_to_apply, "skip_tool_message_in_guardrail", None)+ if per is not None:+ return bool(per)+ import litellm++ return bool(getattr(litellm, "skip_tool_message_in_guardrail", False))++def openai_messages_without_system(messages: List[AllMessageValues],) -> List[AllMessageValues]:return [m for m in messages if str((m or {}).get("role") or "").lower() != "system"]+++def openai_messages_without_tool(+ messages: List[AllMessageValues],+) -> List[AllMessageValues]:+ return [m for m in messages if str((m or {}).get("role") or "").lower() != "tool"]diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.pyindex 86ca6625629..d413a244539 100644--- a/litellm/llms/openai/chat/guardrail_translation/handler.py+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py@@ -21,7 +21,9 @@ from litellm._logging import verbose_proxy_loggerfrom litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslationfrom litellm.llms.base_llm.guardrail_translation.utils import (effective_skip_system_message_for_guardrail,+ effective_skip_tool_message_for_guardrail,openai_messages_without_system,+ openai_messages_without_tool,)from litellm.main import stream_chunk_builderfrom litellm.types.llms.openai import AllMessageValues, ChatCompletionToolParam@@ -73,6 +75,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):return dataskip_system = effective_skip_system_message_for_guardrail(guardrail_to_apply)+ skip_tool = effective_skip_tool_message_for_guardrail(guardrail_to_apply)texts_to_check: List[str] = []images_to_check: List[str] = []@@ -91,6 +94,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):text_task_mappings=text_task_mappings,tool_call_task_mappings=tool_call_task_mappings,skip_system_message=skip_system,+ skip_tool_message=skip_tool,)# Step 2: Apply guardrail to all texts and tool calls in batch@@ -102,11 +106,15 @@ class OpenAIChatCompletionsHandler(BaseTranslation):inputs["tool_calls"] = tool_calls_to_check # type: ignorestructured_messages = self.get_structured_messages(data)if structured_messages:- inputs["structured_messages"] = (- openai_messages_without_system(structured_messages)- if skip_system- else structured_messages- )+ if skip_system:+ structured_messages = openai_messages_without_system(+ structured_messages+ )+ if skip_tool:+ structured_messages = openai_messages_without_tool(+ structured_messages+ )+ inputs["structured_messages"] = structured_messages# Pass tools (function definitions) to the guardrailtools = data.get("tools")if tools:@@ -176,13 +184,17 @@ class OpenAIChatCompletionsHandler(BaseTranslation):text_task_mappings: List[Tuple[int, Optional[int]]],tool_call_task_mappings: List[Tuple[int, int]],skip_system_message: bool = False,+ skip_tool_message: bool = False,) -> None:"""Extract text content, images, and tool calls from a message.Override this method to customize text/image/tool call extraction logic."""- if skip_system_message and str(message.get("role") or "").lower() == "system":+ role = str(message.get("role") or "").lower()+ if skip_system_message and role == "system":+ return+ if skip_tool_message and role == "tool":returncontent = message.get("content", None)diff --git a/litellm/proxy/guardrails/guardrail_registry.py b/litellm/proxy/guardrails/guardrail_registry.pyindex 868b23756d2..838fb2e01ad 100644--- a/litellm/proxy/guardrails/guardrail_registry.py+++ b/litellm/proxy/guardrails/guardrail_registry.py@@ -482,6 +482,11 @@ class InMemoryGuardrailHandler:"skip_system_message_in_guardrail",getattr(litellm_params, "skip_system_message_in_guardrail", None),)+ setattr(+ custom_guardrail_callback,+ "skip_tool_message_in_guardrail",+ getattr(litellm_params, "skip_tool_message_in_guardrail", None),+ )parsed_guardrail = Guardrail(guardrail_id=guardrail.get("guardrail_id"),diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.pyindex 04347aebe3b..751113400d3 100644--- a/litellm/types/guardrails.py+++ b/litellm/types/guardrails.py@@ -633,6 +633,16 @@ class BaseLitellmParams(),)+ skip_tool_message_in_guardrail: Optional[bool] = Field(+ default=None,+ description=(+ "When True, unified guardrails skip tool-role messages when building "+ "evaluation inputs (texts and structured_messages). When False, tool "+ "messages are included even if litellm_settings sets a global skip. When "+ "None, use the global litellm.skip_tool_message_in_guardrail setting."+ ),+ )+# Lakera specific paramscategory_thresholds: Optional[LakeraCategoryThresholds] = Field(default=None,diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/unified_guardrails/test_unified_guardrail.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/unified_guardrails/test_unified_guardrail.pyindex 2418d7af04b..6e027fa4941 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/unified_guardrails/test_unified_guardrail.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/unified_guardrails/test_unified_guardrail.py@@ -8,7 +8,9 @@ from litellm.integrations.custom_guardrail import CustomGuardrailfrom litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslationfrom litellm.llms.base_llm.guardrail_translation.utils import (effective_skip_system_message_for_guardrail,+ effective_skip_tool_message_for_guardrail,openai_messages_without_system,+ openai_messages_without_tool,)from litellm.llms.openai.chat.guardrail_translation.handler import (OpenAIChatCompletionsHandler,@@ -180,6 +182,136 @@ class TestUnifiedLLMGuardrails:}assert "system" in roles+ class TestSkipToolMessageForChatCompletions:+ def test_openai_messages_without_tool(self):+ msgs = [+ {"role": "user", "content": "hi"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "f", "arguments": "{}"},+ }+ ],+ },+ {"role": "tool", "content": "tool result", "tool_call_id": "call_1"},+ ]+ out = openai_messages_without_tool(msgs)+ assert len(out) == 2+ assert all(m["role"] != "tool" for m in out)+ assert msgs[2]["content"] == "tool result"++ def test_effective_skip_tool_respects_per_guardrail_over_global(+ self, monkeypatch+ ):+ monkeypatch.setattr(+ litellm, "skip_tool_message_in_guardrail", True, raising=False+ )++ class G:+ skip_tool_message_in_guardrail = False++ assert effective_skip_tool_message_for_guardrail(G()) is False++ class G2:+ skip_tool_message_in_guardrail = None++ assert effective_skip_tool_message_for_guardrail(G2()) is True++ @pytest.mark.asyncio+ async def test_openai_handler_skips_tool_in_guardrail_inputs(self, monkeypatch):+ monkeypatch.setattr(+ litellm, "skip_tool_message_in_guardrail", True, raising=False+ )++ captured = {}++ class MockGuardrail:+ skip_tool_message_in_guardrail = None++ async def apply_guardrail(+ self, inputs, request_data, input_type, logging_obj=None+ ):+ captured["inputs"] = inputs+ return inputs++ data = {+ "messages": [+ {"role": "user", "content": "hello"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "f", "arguments": "{}"},+ }+ ],+ },+ {+ "role": "tool",+ "content": "secret tool result",+ "tool_call_id": "call_1",+ },+ ],+ "model": "gpt-4o",+ }++ handler = OpenAIChatCompletionsHandler()+ await handler.process_input_messages(+ data=data,+ guardrail_to_apply=MockGuardrail(),+ litellm_logging_obj=None,+ )++ assert "secret tool result" not in captured["inputs"]["texts"]+ sm = captured["inputs"].get("structured_messages") or []+ assert all(m.get("role") != "tool" for m in sm)+ assert data["messages"][2]["content"] == "secret tool result"++ @pytest.mark.asyncio+ async def test_openai_handler_per_guardrail_skip_tool_false_overrides_global(+ self, monkeypatch+ ):+ monkeypatch.setattr(+ litellm, "skip_tool_message_in_guardrail", True, raising=False+ )++ captured = {}++ class MockGuardrail:+ skip_tool_message_in_guardrail = False++ async def apply_guardrail(+ self, inputs, request_data, input_type, logging_obj=None+ ):+ captured["inputs"] = inputs+ return inputs++ data = {+ "messages": [+ {"role": "user", "content": "u"},+ {"role": "tool", "content": "tr", "tool_call_id": "call_1"},+ ],+ }++ await OpenAIChatCompletionsHandler().process_input_messages(+ data=data,+ guardrail_to_apply=MockGuardrail(),+ litellm_logging_obj=None,+ )++ assert "tr" in captured["inputs"]["texts"]+ roles = {+ m.get("role")+ for m in (captured["inputs"].get("structured_messages") or [])+ }+ assert "tool" in roles+class TestAsyncPreCallHook:@pytest.mark.asyncioasync def test_uses_mcp_event_type(self):diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.pyindex 65305e1a81e..d07af922ea6 100644--- a/tests/test_litellm/test_utils.py+++ b/tests/test_litellm/test_utils.py@@ -2817,6 +2817,128 @@ def test_generate_gcp_iam_access_token_import_error():assert "pip install google-cloud-iam" in str(exc_info.value)+def test_generate_azure_ad_redis_token():+ """Test _generate_azure_ad_redis_token with mocked Azure credential."""+ from unittest.mock import Mock, patch++ expected_token = "azure-access-token-12345"++ mock_token = Mock()+ mock_token.token = expected_token++ mock_credential = Mock()+ mock_credential.get_token.return_value = mock_token++ mock_azure_identity = Mock()+ mock_azure_identity.DefaultAzureCredential = Mock(return_value=mock_credential)+ mock_azure_identity.ClientSecretCredential = Mock()+ mock_azure_identity.ManagedIdentityCredential = Mock()++ with patch.dict(+ "sys.modules", {"azure.identity": mock_azure_identity, "azure": Mock()}+ ):+ from litellm._redis import _generate_azure_ad_redis_token++ result = _generate_azure_ad_redis_token()++ assert result == expected_token+ mock_credential.get_token.assert_called_once_with(+ "https://redis.azure.com/.default"+ )+++def test_generate_azure_ad_redis_token_service_principal():+ """Test _generate_azure_ad_redis_token with service principal credentials."""+ from unittest.mock import Mock, patch++ expected_token = "sp-access-token-67890"++ mock_token = Mock()+ mock_token.token = expected_token++ mock_credential = Mock()+ mock_credential.get_token.return_value = mock_token++ mock_client_secret_credential = Mock(return_value=mock_credential)++ mock_azure_identity = Mock()+ mock_azure_identity.DefaultAzureCredential = Mock()+ mock_azure_identity.ClientSecretCredential = mock_client_secret_credential+ mock_azure_identity.ManagedIdentityCredential = Mock()++ with patch.dict(+ "sys.modules", {"azure.identity": mock_azure_identity, "azure": Mock()}+ ):+ from litellm._redis import _generate_azure_ad_redis_token++ result = _generate_azure_ad_redis_token(+ azure_client_id="test-client-id",+ azure_tenant_id="test-tenant-id",+ azure_client_secret="test-secret",+ )++ assert result == expected_token+ mock_client_secret_credential.assert_called_once_with(+ client_id="test-client-id",+ tenant_id="test-tenant-id",+ client_secret="test-secret",+ )+++def test_generate_azure_ad_redis_token_import_error():+ """Test that _generate_azure_ad_redis_token raises ImportError when azure-identity is missing."""+ from unittest.mock import patch+ from litellm._redis import _generate_azure_ad_redis_token++ with patch.dict("sys.modules", {"azure.identity": None}):+ with pytest.raises(ImportError) as exc_info:+ _generate_azure_ad_redis_token()++ assert "azure-identity is required" in str(exc_info.value)+++def test_redis_client_logic_azure_ad_auth():+ """Test that _get_redis_client_logic sets up Azure AD auth when REDIS_AZURE_AD_TOKEN=true.++ Mocks ``azure.identity`` via ``sys.modules`` so the test does not require+ the real ``azure-identity`` package to be installed in the CI environment.+ """+ from unittest.mock import Mock, patch++ mock_credential = Mock()+ mock_azure_identity = Mock()+ mock_azure_identity.DefaultAzureCredential = Mock(return_value=mock_credential)+ mock_azure_identity.ClientSecretCredential = Mock(return_value=mock_credential)+ mock_azure_identity.ManagedIdentityCredential = Mock(return_value=mock_credential)++ with patch.dict(+ "sys.modules", {"azure.identity": mock_azure_identity, "azure": Mock()}+ ):+ from litellm._redis import _get_redis_client_logic++ redis_kwargs = _get_redis_client_logic(+ host="myredis.redis.cache.windows.net",+ port="6380",+ azure_redis_ad_token="true",+ ssl=True,+ )++ assert "redis_connect_func" in redis_kwargs+ # Marker for async paths to detect Azure AD auth+ assert hasattr(redis_kwargs["redis_connect_func"], "_azure_redis_ad_token")+ assert redis_kwargs["redis_connect_func"]._azure_redis_ad_token is True+ # Live credential object (not raw secret) is exposed for async paths+ assert hasattr(redis_kwargs["redis_connect_func"], "_azure_credential")+ # Raw credentials must NOT be exposed on the function+ assert not hasattr(redis_kwargs["redis_connect_func"], "_azure_client_secret")+ assert not hasattr(redis_kwargs["redis_connect_func"], "_azure_client_id")+ assert not hasattr(redis_kwargs["redis_connect_func"], "_azure_tenant_id")++ # Azure-specific kwargs should be removed from the dict passed to Redis+ assert "azure_redis_ad_token" not in redis_kwargs+ assert "azure_client_id" not in redis_kwargs++if __name__ == "__main__":# Allow running this test file directly for debuggingpytest.main([__file__, "-v"])diff --git a/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsx b/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsxindex c91a6e85cdd..16c1c6efecd 100644--- a/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsx@@ -5,6 +5,7 @@ import { createGuardrailCall, getGuardrailProviderSpecificParams, getGuardrailUIimport ContentFilterConfiguration from "./content_filter/ContentFilterConfiguration";import {choiceToSkipSystemForCreate,+ choiceToSkipToolForCreate,getGuardrailProviders,guardrail_provider_map,guardrailLogoMap,@@ -188,6 +189,7 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({ visible, onClose, amode: preset.mode,default_on: preset.defaultOn,skip_system_message_choice: "inherit",+ skip_tool_message_choice: "inherit",};if (preset.provider === "BlockCodeExecution") {baseValues.confidence_threshold = 0.5;@@ -433,6 +435,11 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({ visible, onClose, aguardrailData.litellm_params.skip_system_message_in_guardrail = skipForCreate;}+ const skipToolForCreate = choiceToSkipToolForCreate(values.skip_tool_message_choice);+ if (skipToolForCreate !== undefined) {+ guardrailData.litellm_params.skip_tool_message_in_guardrail = skipToolForCreate;+ }+// For Presidio PII, add the entity and action configurationsif (values.provider === "PresidioPII" && selectedEntities.length > 0) {const piiEntitiesConfig: { [key: string]: string } = {};@@ -804,6 +811,18 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({ visible, onClose, a</Select></Form.Item>+ <Form.Item+ name="skip_tool_message_choice"+ label="Skip tool messages in guardrail"+ tooltip="Unified guardrails only: omit role: tool from guardrail evaluation input (OpenAI chat + Anthropic messages). The model still receives full messages. Use global default follows litellm_settings.skip_tool_message_in_guardrail."+ >+ <Select>+ <Select.Option value="inherit">Use global default</Select.Option>+ <Select.Option value="yes">Yes — exclude from guardrail scan</Select.Option>+ <Select.Option value="no">No — always include in scan</Select.Option>+ </Select>+ </Form.Item>+{/* Use the GuardrailProviderFields component to render provider-specific fields */}{!isToolPermissionProvider && !shouldRenderContentFilterConfigSettings(selectedProvider) && !shouldRenderLLMJudgeFields(selectedProvider) && (<GuardrailProviderFields@@ -1155,6 +1174,7 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({ visible, onClose, amode: "pre_call",default_on: false,skip_system_message_choice: "inherit",+ skip_tool_message_choice: "inherit",}}>{stepConfigs.map((step, index) => {diff --git a/ui/litellm-dashboard/src/components/guardrails/edit_guardrail_form.tsx b/ui/litellm-dashboard/src/components/guardrails/edit_guardrail_form.tsxindex ad823df53fc..8ba9b0b312f 100644--- a/ui/litellm-dashboard/src/components/guardrails/edit_guardrail_form.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/edit_guardrail_form.tsx@@ -6,6 +6,7 @@ import {guardrailLogoMap,getGuardrailProviders,type SkipSystemMessageChoice,+ type SkipToolMessageChoice,} from "./guardrail_info_helpers";import { getGuardrailUISettings, getGlobalLitellmHeaderName } from "../networking";import PiiConfiguration from "./pii_configuration";@@ -29,6 +30,7 @@ interface EditGuardrailFormProps {default_on: boolean;pii_entities_config?: { [key: string]: string };skip_system_message_choice?: SkipSystemMessageChoice;+ skip_tool_message_choice?: SkipToolMessageChoice;[key: string]: any;};}@@ -138,6 +140,15 @@ const EditGuardrailForm: React.FC<EditGuardrailFormProps> = ({delete litellm_params.skip_system_message_in_guardrail;}+ const skipToolChoice = values.skip_tool_message_choice as SkipToolMessageChoice | undefined;+ if (skipToolChoice === "yes") {+ litellm_params.skip_tool_message_in_guardrail = true;+ } else if (skipToolChoice === "no") {+ litellm_params.skip_tool_message_in_guardrail = false;+ } else {+ delete litellm_params.skip_tool_message_in_guardrail;+ }+let guardrail_info: any = {};// For Presidio PII, add the entity and action configurations@@ -432,6 +443,18 @@ const EditGuardrailForm: React.FC<EditGuardrailFormProps> = ({</Select></Form.Item>+ <Form.Item+ name="skip_tool_message_choice"+ label="Skip tool messages in guardrail"+ tooltip="Unified guardrails only: whether role: tool content is omitted from guardrail input (LLM still receives full messages). Use global default follows litellm_settings.skip_tool_message_in_guardrail."+ >+ <Select>+ <Option value="inherit">Use global default</Option>+ <Option value="yes">Yes — exclude from guardrail scan</Option>+ <Option value="no">No — always include in scan</Option>+ </Select>+ </Form.Item>+{renderProviderSpecificFields()}<div className="flex justify-end space-x-2 mt-4">diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsxindex 60400443d5c..53aebcff0de 100644--- a/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsx@@ -29,7 +29,9 @@ import {getGuardrailLogoAndName,guardrail_provider_map,skipSystemMessageToChoice,+ skipToolMessageToChoice,type SkipSystemMessageChoice,+ type SkipToolMessageChoice,} from "./guardrail_info_helpers";import GuardrailOptionalParams from "./guardrail_optional_params";import GuardrailProviderFields from "./guardrail_provider_fields";@@ -214,12 +216,16 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({ guardrailId, onClose,if (guardrailData && form) {const lp = { ...(guardrailData.litellm_params || {}) };delete lp.skip_system_message_in_guardrail;+ delete lp.skip_tool_message_in_guardrail;form.setFieldsValue({guardrail_name: guardrailData.guardrail_name,...lp,skip_system_message_choice: skipSystemMessageToChoice(guardrailData.litellm_params?.skip_system_message_in_guardrail,),+ skip_tool_message_choice: skipToolMessageToChoice(+ guardrailData.litellm_params?.skip_tool_message_in_guardrail,+ ),guardrail_info: guardrailData.guardrail_info ? JSON.stringify(guardrailData.guardrail_info, null, 2) : "",// Include any optional_params if they exist...(guardrailData.litellm_params?.optional_params && {@@ -302,6 +308,20 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({ guardrailId, onClose,}}+ const prevSkipToolChoice = skipToolMessageToChoice(+ guardrailData.litellm_params?.skip_tool_message_in_guardrail,+ );+ const nextSkipToolChoice = values.skip_tool_message_choice as SkipToolMessageChoice | undefined;+ if (nextSkipToolChoice !== undefined && nextSkipToolChoice !== prevSkipToolChoice) {+ if (nextSkipToolChoice === "inherit") {+ updateData.litellm_params.skip_tool_message_in_guardrail = null;+ } else if (nextSkipToolChoice === "yes") {+ updateData.litellm_params.skip_tool_message_in_guardrail = true;+ } else {+ updateData.litellm_params.skip_tool_message_in_guardrail = false;+ }+ }+// Only include guardrail_info if it has changedconst originalGuardrailInfo = guardrailData.guardrail_info;const newGuardrailInfo = values.guardrail_info ? JSON.parse(values.guardrail_info) : undefined;@@ -674,11 +694,15 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({ guardrailId, onClose,...(() => {const lp = { ...(guardrailData.litellm_params || {}) };delete lp.skip_system_message_in_guardrail;+ delete lp.skip_tool_message_in_guardrail;return lp;})(),skip_system_message_choice: skipSystemMessageToChoice(guardrailData.litellm_params?.skip_system_message_in_guardrail,),+ skip_tool_message_choice: skipToolMessageToChoice(+ guardrailData.litellm_params?.skip_tool_message_in_guardrail,+ ),guardrail_info: guardrailData.guardrail_info? JSON.stringify(guardrailData.guardrail_info, null, 2): "",@@ -716,6 +740,18 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({ guardrailId, onClose,</Select></Form.Item>+ <Form.Item+ label="Skip tool messages in guardrail"+ name="skip_tool_message_choice"+ tooltip="Unified guardrails: omit role: tool from guardrail input (LLM still gets full messages). Use global default follows litellm_settings.skip_tool_message_in_guardrail."+ >+ <Select>+ <Select.Option value="inherit">Use global default</Select.Option>+ <Select.Option value="yes">Yes — exclude from guardrail scan</Select.Option>+ <Select.Option value="no">No — always include in scan</Select.Option>+ </Select>+ </Form.Item>+{guardrailData.litellm_params?.guardrail === "presidio" && (<><Divider orientation="left">PII Protection</Divider>diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.test.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.test.tsxindex dfda86c1e4a..1fc62f94cf1 100644--- a/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.test.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.test.tsx@@ -12,6 +12,8 @@ import {GuardrailProviders,skipSystemMessageToChoice,choiceToSkipSystemForCreate,+ skipToolMessageToChoice,+ choiceToSkipToolForCreate,} from "./guardrail_info_helpers";describe("guardrail_info_helpers", () => {@@ -215,4 +217,18 @@ describe("guardrail_info_helpers", () => {expect(choiceToSkipSystemForCreate("no")).toBe(false);});});++ describe("skipToolMessageToChoice / choiceToSkipToolForCreate", () => {+ it("maps API values to form choices and back for create", () => {+ expect(skipToolMessageToChoice(undefined)).toBe("inherit");+ expect(skipToolMessageToChoice(null)).toBe("inherit");+ expect(skipToolMessageToChoice(true)).toBe("yes");+ expect(skipToolMessageToChoice(false)).toBe("no");++ expect(choiceToSkipToolForCreate("inherit")).toBeUndefined();+ expect(choiceToSkipToolForCreate(undefined)).toBeUndefined();+ expect(choiceToSkipToolForCreate("yes")).toBe(true);+ expect(choiceToSkipToolForCreate("no")).toBe(false);+ });+ });});diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsxindex ac4b787e96a..54b16b81765 100644--- a/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsx@@ -179,3 +179,19 @@ export function choiceToSkipSystemForCreate(choice: SkipSystemMessageChoice | unif (choice === "no") return false;return undefined;}++/** Tri-state UI value for `litellm_params.skip_tool_message_in_guardrail` (inherit = use global). */+export type SkipToolMessageChoice = "inherit" | "yes" | "no";++export function skipToolMessageToChoice(v: boolean | null | undefined): SkipToolMessageChoice {+ if (v === true) return "yes";+ if (v === false) return "no";+ return "inherit";+}++/** Create flow: omit key when inheriting global default. */+export function choiceToSkipToolForCreate(choice: SkipToolMessageChoice | undefined): boolean | undefined {+ if (choice === "yes") return true;+ if (choice === "no") return false;+ return undefined;+}diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_table.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_table.tsxindex 5bb2da78fa2..ecf6ce48fde 100644--- a/ui/litellm-dashboard/src/components/guardrails/guardrail_table.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_table.tsx@@ -11,7 +11,12 @@ import {SortingState,useReactTable,} from "@tanstack/react-table";-import { getGuardrailLogoAndName, guardrail_provider_map, skipSystemMessageToChoice } from "./guardrail_info_helpers";+import {+ getGuardrailLogoAndName,+ guardrail_provider_map,+ skipSystemMessageToChoice,+ skipToolMessageToChoice,+} from "./guardrail_info_helpers";import EditGuardrailForm from "./edit_guardrail_form";import { Guardrail, GuardrailDefinitionLocation } from "./types";@@ -304,6 +309,9 @@ const GuardrailTable: React.FC<GuardrailTableProps> = ({skip_system_message_choice: skipSystemMessageToChoice(selectedGuardrail.litellm_params?.skip_system_message_in_guardrail,),+ skip_tool_message_choice: skipToolMessageToChoice(+ selectedGuardrail.litellm_params?.skip_tool_message_in_guardrail,+ ),...selectedGuardrail.guardrail_info,}}/>