Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
6b591c3
fix(ovhcloud): migrate reasoning_content->reasoning and duration->sec…
KunalG67 Apr 27, 2026
e55e73d
fix(ovhcloud): use explicit None check for seconds field in STT response
KunalG67 Apr 27, 2026
c0da139
fix(otel): populate gen_ai.output.messages and gen_ai.system_instruct…
Aneesh-Fiddler Apr 27, 2026
4d2e13c
test(otel): add tests for Responses API output messages, system instr…
Aneesh-Fiddler Apr 27, 2026
e70b0c9
style: apply black formatting to opentelemetry.py
Aneesh-Fiddler Apr 28, 2026
c30d58f
fix: resolve mypy indexed assignment error in function_call handling
Aneesh-Fiddler Apr 28, 2026
466b4dd
fix: address review comments — Pydantic compat, falsy fallthrough, pe…
Aneesh-Fiddler Apr 28, 2026
982fed4
fix(ovhcloud): handle reasoning field migration in non-streaming resp…
KunalG67 Apr 28, 2026
8f48d88
style: apply black formatting to ovhcloud chat transformation
KunalG67 Apr 28, 2026
9928618
fix: remove duplicate gen_ai.response.finish_reasons block
Aneesh-Fiddler Apr 28, 2026
90bcd23
fix(ovhcloud): remove dead transform_response override
KunalG67 Apr 28, 2026
d73e24c
fix(ovhcloud): remove dead transform_response override, parent alread…
KunalG67 Apr 28, 2026
5310252
ci: retrigger checks after retargeting to litellm_oss_staging_04_27_2026
Aneesh-Fiddler Apr 29, 2026
c319a19
fix: handle raw Pydantic v2 models from openai SDK in output transfor…
Aneesh-Fiddler Apr 30, 2026
209bd0b
fix(proxy): sort spend updates to prevent DB deadlocks
pnookala-godaddy May 5, 2026
2993e45
allow non-admin roles on /compliance/* read routes
May 5, 2026
85d4d96
fix(proxy): preserve HTTP operations when injecting WebSocket stubs i…
michelligabriele May 5, 2026
ed7ded9
Merge PR #27221 into agent staging branch
May 6, 2026
062b5b3
Add main module header comment
cursoragent May 6, 2026
b631863
Add utils module docstring
oss-agent-shin May 6, 2026
f8c0e03
Merge PR #27255 into agent staging branch
May 6, 2026
5b91fc0
Merge PR #27253 into agent staging branch
May 6, 2026
1087766
Merge PR #27244 into agent staging branch
May 6, 2026
abf0381
Merge PR #27234 into agent staging branch
May 6, 2026
75245de
Merge PR #26595 into agent staging branch
May 6, 2026
a466c2e
Merge PR #26670 into agent staging branch
May 6, 2026
158b0c2
[litellm-agent] Staging → litellm_internal_staging (5/7/2026) (#27375)
May 7, 2026
bac03ac
feat(auth): add scope and wildcard support for JWT routing overrides …
milan-berri May 7, 2026
b834817
[Feat] Add endpoint for bulk key updates for team (#26468)
Michael-RZ-Berri May 9, 2026
2b4beae
Fix/shared health check polling (#26434)
noahnistler May 9, 2026
0f908e6
fix(proxy): resolve provider from deployment for multi-provider defau…
Anai-Guo May 9, 2026
f8b078b
fix(bedrock/messages): preserve compact_20260112 context_management o…
Anai-Guo May 9, 2026
d1d2400
fix(router): register model info under responses/-stripped variant (#…
krisxia0506 May 9, 2026
b799f94
fix(ui): remove blank leading entry from access group model dropdown …
Bytechoreographer May 9, 2026
8044529
fix(proxy): coerce non-str x-litellm-* header values to avoid httpx T…
Anai-Guo May 9, 2026
c7739c9
feat: add ability to auth to azure with token (#27556)
shivamrawat1 May 9, 2026
9f68d2b
Fix: tag budget reset must drop stale management-cache entry (#27568)
oss-agent-shin May 10, 2026
ce17e94
Merge branch 'litellm_internal_staging' into litellm_agent_oss_stagin…
Sameerlite May 11, 2026
99218c6
Fix deprecated model test
Sameerlite May 11, 2026
c7e6bcc
Merge pull request #27256 from BerriAI/litellm_agent_oss_staging_05_0…
Sameerlite May 11, 2026
083d87a
Merge branch 'litellm_internal_staging' into shin_agent_oss_staging_0…
Sameerlite May 11, 2026
055bdc3
fix(auth): harden JWT routing wildcard iss and merge list team_id claims
Sameerlite May 11, 2026
9ed9903
Merge pull request #27422 from BerriAI/shin_agent_oss_staging_05_07_2026
Sameerlite May 11, 2026
aa587bd
Merge pull request #27549 from BerriAI/shin_agent_oss_staging_05_09_2026
Sameerlite May 11, 2026
9bc90f6
chore: remove accidental .evidence screenshot from repo (#27633)
Sameerlite May 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
219 changes: 217 additions & 2 deletions litellm/_redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from litellm import get_secret, get_secret_str
from litellm._redis_credential_provider import (
AzureADCredentialProvider,
GCPIAMCredentialProvider,
_generate_gcp_iam_access_token,
)
Expand All @@ -27,6 +28,8 @@

from ._logging import verbose_logger

AZURE_REDIS_SCOPE = "https://redis.azure.com/.default"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duplicate AZURE_REDIS_SCOPE constant across two modules

Low Severity

AZURE_REDIS_SCOPE is defined identically in both litellm/_redis.py and litellm/_redis_credential_provider.py. If the scope URI ever needs updating, the change must be made in two places or they'll silently diverge — one module would authenticate against the wrong scope. One of the definitions could import from the other.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 9bc90f6. Configure here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Duplicated AZURE_REDIS_SCOPE constant

AZURE_REDIS_SCOPE is defined identically in both litellm/_redis.py and litellm/_redis_credential_provider.py. _redis_credential_provider.py is imported into _redis.py, so there is no need for a second definition. If the scope ever changes, only the owning module's constant will be updated and the other will silently diverge, causing token-fetch failures at the wrong scope.



def _get_redis_kwargs():
arg_spec = inspect.getfullargspec(redis.Redis)
Expand All @@ -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
Expand Down Expand Up @@ -89,6 +96,10 @@ def _get_redis_cluster_kwargs(client=None):
) # Needed for sync clusters and IAM detection
available_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
Expand Down Expand Up @@ -155,6 +166,125 @@ def iam_connect(self):
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"]
Expand All @@ -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
"""
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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: PLR0915
connection_pool: Optional[async_redis.BlockingConnectionPool] = None,
**env_overrides,
) -> Union[async_redis.Redis, async_redis.RedisCluster]:
Expand All @@ -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] = []

Expand Down Expand Up @@ -431,6 +615,22 @@ def get_redis_async_client(
# Check for Redis Sentinel
if "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:
Expand Down Expand Up @@ -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.Connection
if "ssl" in redis_kwargs:
connection_class = async_redis.SSLConnection
Expand Down
35 changes: 34 additions & 1 deletion litellm/_redis_credential_provider.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import asyncio
import threading
import time
from typing import Dict, Tuple
from typing import Any, Dict, Optional, Tuple, Union

from 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

Expand Down Expand Up @@ -101,3 +104,33 @@ async def get_credentials_async(self) -> Tuple[str]:
_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,)
Loading
Loading