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] UI - Allow setting cache settings on UI (#16143)
Ishaan Jaffc59a0c968125
diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prismaindex ce2fc2e4753..ac1acee908a 100644--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma@@ -588,4 +588,12 @@ model LiteLLM_SSOConfig {sso_settings Jsoncreated_at DateTime @default(now())updated_at DateTime @updatedAt+}++// Cache configuration table+model LiteLLM_CacheConfig {+ id String @id @default("cache_config")+ cache_settings Json+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt}\ No newline at end of filediff --git a/litellm/caching/base_cache.py b/litellm/caching/base_cache.pyindex 5140b390f76..8660e64efde 100644--- a/litellm/caching/base_cache.py+++ b/litellm/caching/base_cache.py@@ -53,3 +53,12 @@ class BaseCache(ABC):async def disconnect(self):raise NotImplementedError++ async def test_connection(self) -> dict:+ """+ Test the cache connection.++ Returns:+ dict: {"status": "success" | "failed", "message": str, "error": Optional[str]}+ """+ raise NotImplementedError\ No newline at end of filediff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.pyindex af7468ba14c..9a670da9100 100644--- a/litellm/caching/redis_cache.py+++ b/litellm/caching/redis_cache.py@@ -1022,6 +1022,46 @@ class RedisCache(BaseCache):async def disconnect(self):await self.async_redis_conn_pool.disconnect(inuse_connections=True)++ async def test_connection(self) -> dict:+ """+ Test the Redis connection by creating a new client and pinging it.++ This creates a fresh connection without using cached clients or connection pools+ to ensure the credentials are actually valid.++ Returns:+ dict: {"status": "success" | "failed", "message": str, "error": Optional[str]}+ """+ try:+ import redis.asyncio as redis_async++ # Create a fresh Redis client with current settings+ redis_client = redis_async.Redis(**self.redis_kwargs)++ # Test the connection+ ping_result = await redis_client.ping()++ # Close the connection+ await redis_client.aclose()++ if ping_result:+ return {+ "status": "success",+ "message": "Redis connection test successful"+ }+ else:+ return {+ "status": "failed",+ "message": "Redis ping returned False"+ }+ except Exception as e:+ verbose_logger.error(f"Redis connection test failed: {str(e)}")+ return {+ "status": "failed",+ "message": f"Redis connection failed: {str(e)}",+ "error": str(e)+ }async def async_delete_cache(self, key: str):# typed as Any, redis python lib has incomplete type stubs for RedisCluster and does not include `delete`diff --git a/litellm/caching/redis_cluster_cache.py b/litellm/caching/redis_cluster_cache.pyindex 21c3ab0366b..69bdb500de4 100644--- a/litellm/caching/redis_cluster_cache.py+++ b/litellm/caching/redis_cluster_cache.py@@ -57,3 +57,52 @@ class RedisClusterCache(RedisCache):"""async_redis_cluster_client = self.init_async_client()return await async_redis_cluster_client.mget_nonatomic(keys=keys) # type: ignore++ async def test_connection(self) -> dict:+ """+ Test the Redis Cluster connection.++ Returns:+ dict: {"status": "success" | "failed", "message": str, "error": Optional[str]}+ """+ try:+ import redis.asyncio as redis_async+ from redis.cluster import ClusterNode++ # Create ClusterNode objects from startup_nodes+ cluster_kwargs = self.redis_kwargs.copy()+ startup_nodes = cluster_kwargs.pop("startup_nodes", [])++ new_startup_nodes: List[ClusterNode] = []+ for item in startup_nodes:+ new_startup_nodes.append(ClusterNode(**item))++ # Create a fresh Redis Cluster client with current settings+ redis_client = redis_async.RedisCluster(+ startup_nodes=new_startup_nodes, **cluster_kwargs # type: ignore+ )++ # Test the connection+ ping_result = await redis_client.ping()++ # Close the connection+ await redis_client.aclose()++ if ping_result:+ return {+ "status": "success",+ "message": "Redis Cluster connection test successful"+ }+ else:+ return {+ "status": "failed",+ "message": "Redis Cluster ping returned False"+ }+ except Exception as e:+ from litellm._logging import verbose_logger+ verbose_logger.error(f"Redis Cluster connection test failed: {str(e)}")+ return {+ "status": "failed",+ "message": f"Redis Cluster connection failed: {str(e)}",+ "error": str(e)+ }\ No newline at end of filediff --git a/litellm/proxy/management_endpoints/cache_settings_endpoints.py b/litellm/proxy/management_endpoints/cache_settings_endpoints.pynew file mode 100644index 00000000000..c9eeea15e26--- /dev/null+++ b/litellm/proxy/management_endpoints/cache_settings_endpoints.py@@ -0,0 +1,366 @@+"""+CACHE SETTINGS MANAGEMENT++Endpoints for managing cache configuration++GET /cache/settings - Get cache configuration including available settings+POST /cache/settings/test - Test cache connection with provided credentials+POST /cache/settings - Save cache settings to database+"""++import json+from typing import Any, Dict, List, Optional++from fastapi import APIRouter, Depends, HTTPException+from pydantic import BaseModel, Field++from litellm._logging import verbose_proxy_logger+from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.types.management_endpoints import (+ CACHE_SETTINGS_FIELDS,+ REDIS_TYPE_DESCRIPTIONS,+ CacheSettingsField,+)++router = APIRouter()+++class CacheSettingsManager:+ """+ Manages cache settings initialization and updates.+ Tracks last cache params to avoid unnecessary reinitialization.+ """++ _last_cache_params: Optional[Dict[str, Any]] = None++ @staticmethod+ def _cache_params_equal(params1: Dict[str, Any], params2: Dict[str, Any]) -> bool:+ """+ Compare two cache parameter dictionaries for equality.+ Normalizes values and filters out UI-only fields.+ """+ # Normalize by removing None values and UI-only fields+ def normalize(params: Dict[str, Any]) -> Dict[str, Any]:+ normalized = {}+ for k, v in params.items():+ if k == 'redis_type': # Skip UI-only field+ continue+ if v is not None:+ # Convert to string for comparison to handle different types+ normalized[k] = str(v) if not isinstance(v, (list, dict)) else v+ return normalized++ normalized1 = normalize(params1)+ normalized2 = normalize(params2)++ return normalized1 == normalized2++ @staticmethod+ async def init_cache_settings_in_db(prisma_client, proxy_config):+ """+ Initialize cache settings from database into the router on startup.+ Only reinitializes if cache params have changed.+ """+ import json++ try:+ cache_config = await prisma_client.db.litellm_cacheconfig.find_unique(+ where={"id": "cache_config"}+ )+ if cache_config is not None and cache_config.cache_settings:+ # Parse cache settings JSON+ cache_settings_json = cache_config.cache_settings+ if isinstance(cache_settings_json, str):+ cache_settings_dict = json.loads(cache_settings_json)+ else:+ cache_settings_dict = cache_settings_json++ # Decrypt cache settings+ decrypted_settings = proxy_config._decrypt_db_variables(+ variables_dict=cache_settings_dict+ )++ # Remove redis_type if present (UI-only field, not a Cache parameter)+ # We derive it for UI in get_cache_settings endpoint+ cache_params = {k: v for k, v in decrypted_settings.items() if k != "redis_type"}++ # Check if cache params have changed+ if CacheSettingsManager._last_cache_params is not None and CacheSettingsManager._cache_params_equal(+ CacheSettingsManager._last_cache_params, cache_params+ ):+ verbose_proxy_logger.debug(+ "Cache settings unchanged, skipping reinitialization"+ )+ return++ # Initialize cache only if params changed or cache not initialized+ proxy_config._init_cache(cache_params=cache_params)++ # Store the params we just initialized+ CacheSettingsManager._last_cache_params = cache_params.copy()++ # Switch on LLM response caching+ proxy_config.switch_on_llm_response_caching()++ verbose_proxy_logger.info(+ "Cache settings initialized from database"+ )+ except Exception as e:+ verbose_proxy_logger.exception(+ "litellm.proxy.management_endpoints.cache_settings_endpoints.py::CacheSettingsManager::init_cache_settings_in_db - {}".format(+ str(e)+ )+ )++ @staticmethod+ def update_cache_params(cache_params: Dict[str, Any]):+ """+ Update the last cache params after initialization.+ Called after cache settings are updated via the API.+ """+ CacheSettingsManager._last_cache_params = cache_params.copy()+++class CacheSettingsResponse(BaseModel):+ fields: List[CacheSettingsField] = Field(+ description="List of all configurable cache settings with metadata"+ )+ current_values: Dict[str, Any] = Field(+ description="Current values of cache settings"+ )+ redis_type_descriptions: Dict[str, str] = Field(+ description="Descriptions for each Redis type option"+ )+++class CacheTestRequest(BaseModel):+ cache_settings: Dict[str, Any] = Field(+ description="Cache settings to test connection with"+ )+++class CacheTestResponse(BaseModel):+ status: str = Field(description="Connection status: 'success' or 'failed'")+ message: str = Field(description="Connection result message")+ error: Optional[str] = Field(default=None, description="Error message if connection failed")+++class CacheSettingsUpdateRequest(BaseModel):+ cache_settings: Dict[str, Any] = Field(+ description="Cache settings to save"+ )+++ "/cache/settings",+ tags=["Cache Settings"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=CacheSettingsResponse,+)+async def get_cache_settings(+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Get cache configuration and available settings.++ Returns:+ - fields: List of all configurable cache settings with their metadata (type, description, default, options)+ - current_values: Current values of cache settings from database+ """+ from litellm.proxy.proxy_server import prisma_client, proxy_config++ try:+ # Get cache settings fields from types file+ cache_fields = [field.model_copy(deep=True) for field in CACHE_SETTINGS_FIELDS]++ # Try to get cache settings from database+ current_values = {}+ if prisma_client is not None:+ cache_config = await prisma_client.db.litellm_cacheconfig.find_unique(+ where={"id": "cache_config"}+ )+ if cache_config is not None and cache_config.cache_settings:+ # Decrypt cache settings+ cache_settings_json = cache_config.cache_settings+ if isinstance(cache_settings_json, str):+ cache_settings_dict = json.loads(cache_settings_json)+ else:+ cache_settings_dict = cache_settings_json++ # Decrypt environment variables+ decrypted_settings = proxy_config._decrypt_db_variables(+ variables_dict=cache_settings_dict+ )++ # Derive redis_type for UI based on settings+ # UI uses redis_type to show/hide fields, backend only stores 'type'+ if decrypted_settings.get("type") == "redis":+ if decrypted_settings.get("redis_startup_nodes"):+ decrypted_settings["redis_type"] = "cluster"+ elif decrypted_settings.get("sentinel_nodes"):+ decrypted_settings["redis_type"] = "sentinel"+ else:+ decrypted_settings["redis_type"] = "node"++ current_values = decrypted_settings++ # Update field values with current values+ for field in cache_fields:+ if field.field_name in current_values:+ field.field_value = current_values[field.field_name]++ return CacheSettingsResponse(+ fields=cache_fields,+ current_values=current_values,+ redis_type_descriptions=REDIS_TYPE_DESCRIPTIONS,+ )+ except Exception as e:+ verbose_proxy_logger.error(+ f"Error fetching cache settings: {str(e)}"+ )+ raise HTTPException(+ status_code=500,+ detail=f"Error fetching cache settings: {str(e)}"+ )+++ "/cache/settings/test",+ tags=["Cache Settings"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=CacheTestResponse,+)+async def test_cache_connection(+ request: CacheTestRequest,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Test cache connection with provided credentials.++ Creates a temporary cache instance and uses its test_connection method+ to verify the credentials work without affecting global state.+ """+ from litellm import Cache++ try:+ cache_settings = request.cache_settings.copy()+ verbose_proxy_logger.debug("Testing cache connection with settings: %s", cache_settings)++ # Only support Redis for now+ if cache_settings.get("type") != "redis":+ return CacheTestResponse(+ status="failed",+ message="Only Redis cache type is currently supported for testing",+ )++ # Create temporary cache instance+ temp_cache = Cache(**cache_settings)++ # Use the cache's test_connection method+ result = await temp_cache.cache.test_connection()++ return CacheTestResponse(**result)++ except Exception as e:+ verbose_proxy_logger.error(+ f"Error testing cache connection: {str(e)}"+ )+ return CacheTestResponse(+ status="failed",+ message=f"Cache connection test failed: {str(e)}",+ error=str(e),+ )+++ "/cache/settings",+ tags=["Cache Settings"],+ dependencies=[Depends(user_api_key_auth)],+)+async def update_cache_settings(+ request: CacheSettingsUpdateRequest,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Save cache settings to database and initialize cache.++ This endpoint:+ 1. Encrypts sensitive fields (passwords, etc.)+ 2. Saves to LiteLLM_CacheConfig table+ 3. Reinitializes cache with new settings+ """+ from litellm.proxy.proxy_server import (+ prisma_client,+ proxy_config,+ store_model_in_db,+ )++ if prisma_client is None:+ raise HTTPException(+ status_code=500,+ detail={"error": "Database not connected. Please connect a database."},+ )++ if store_model_in_db is not True:+ raise HTTPException(+ status_code=500,+ detail={+ "error": "Set `'STORE_MODEL_IN_DB='True'` in your env to enable this feature."+ },+ )++ try:+ cache_settings = request.cache_settings.copy()++ # Encrypt sensitive fields (keep redis_type for storage)+ encrypted_settings = proxy_config._encrypt_env_variables(+ environment_variables=cache_settings+ )++ # Save to database+ await prisma_client.db.litellm_cacheconfig.upsert(+ where={"id": "cache_config"},+ data={+ "create": {+ "id": "cache_config",+ "cache_settings": json.dumps(encrypted_settings),+ },+ "update": {+ "cache_settings": json.dumps(encrypted_settings),+ },+ },+ )++ # Reinitialize cache with new settings+ # Decrypt for initialization+ decrypted_settings = proxy_config._decrypt_db_variables(+ variables_dict=encrypted_settings+ )++ # Remove redis_type if present (UI-only field, not a Cache parameter)+ cache_params = {k: v for k, v in decrypted_settings.items() if k != "redis_type"}++ # Initialize cache (frontend sends type="redis", not redis_type)+ proxy_config._init_cache(cache_params=cache_params)++ # Update the last cache params to avoid reinitializing unnecessarily+ CacheSettingsManager.update_cache_params(cache_params)++ # Switch on LLM response caching+ proxy_config.switch_on_llm_response_caching()++ return {+ "message": "Cache settings updated successfully",+ "status": "success",+ "settings": cache_settings,+ }+ except Exception as e:+ verbose_proxy_logger.error(+ f"Error updating cache settings: {str(e)}"+ )+ raise HTTPException(+ status_code=500,+ detail=f"Error updating cache settings: {str(e)}"+ )+diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex ca34735879f..cb689f92c23 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -253,6 +253,9 @@ from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_requestfrom litellm.proxy.management_endpoints.budget_management_endpoints import (router as budget_management_router,)+from litellm.proxy.management_endpoints.cache_settings_endpoints import (+ router as cache_settings_router,+)from litellm.proxy.management_endpoints.callback_management_endpoints import (router as callback_management_endpoints_router,)@@ -263,9 +266,6 @@ from litellm.proxy.management_endpoints.cost_tracking_settings import (from litellm.proxy.management_endpoints.customer_endpoints import (router as customer_router,)-from litellm.proxy.management_endpoints.router_settings_endpoints import (- router as router_settings_router,-)from litellm.proxy.management_endpoints.internal_user_endpoints import (router as internal_user_router,)@@ -294,6 +294,9 @@ from litellm.proxy.management_endpoints.model_management_endpoints import (from litellm.proxy.management_endpoints.organization_endpoints import (router as organization_router,)+from litellm.proxy.management_endpoints.router_settings_endpoints import (+ router as router_settings_router,+)from litellm.proxy.management_endpoints.scim.scim_v2 import scim_routerfrom litellm.proxy.management_endpoints.tag_management_endpoints import (router as tag_management_router,@@ -316,7 +319,6 @@ from litellm.proxy.management_endpoints.user_agent_analytics_endpoints import (from litellm.proxy.management_helpers.audit_logs import create_audit_log_for_updatefrom litellm.proxy.middleware.prometheus_auth_middleware import PrometheusAuthMiddlewarefrom litellm.proxy.ocr_endpoints.endpoints import router as ocr_router-from litellm.proxy.video_endpoints.endpoints import router as video_routerfrom litellm.proxy.openai_files_endpoints.files_endpoints import (router as openai_files_router,)@@ -377,6 +379,7 @@ from litellm.proxy.vector_store_endpoints.endpoints import router as vector_storfrom litellm.proxy.vertex_ai_endpoints.langfuse_endpoints import (router as langfuse_router,)+from litellm.proxy.video_endpoints.endpoints import router as video_routerfrom litellm.router import (AssistantsTypedDict,Deployment,@@ -1808,6 +1811,21 @@ class ProxyConfig:## INIT PROXY REDIS USAGE CLIENT ##redis_usage_cache = litellm.cache.cache+ def switch_on_llm_response_caching(self):+ """+ Enable caching on the router by setting cache_responses=True.+ This ensures caching works without needing caching=True in request body.+ Router passes caching=self.cache_responses to litellm.completion()+ """+ global llm_router+ import litellm++ if llm_router is not None and litellm.cache is not None and llm_router.cache_responses is not True:+ llm_router.cache_responses = True+ verbose_proxy_logger.debug(+ "Set router.cache_responses=True after initializing cache"+ )+async def get_config(self, config_file_path: Optional[str] = None) -> dict:"""Load config file@@ -2954,6 +2972,16 @@ class ProxyConfig:"Error setting env variable: %s - %s", k, str(e))return decrypted_env_vars++ def _decrypt_db_variables(self, variables_dict: dict) -> dict:+ """+ Decrypts a dictionary of variables and returns them.+ """+ decrypted_variables = {}+ for k, v in variables_dict.items():+ decrypted_value = decrypt_value_helper(value=v, key=k, return_original_value=True)+ decrypted_variables[k] = decrypted_value+ return decrypted_variablesasync def _add_router_settings_from_db_config(self,@@ -3341,6 +3369,13 @@ class ProxyConfig:await self._check_and_reload_model_cost_map(prisma_client=prisma_client)if self._should_load_db_object(object_type="sso_settings"):await self._init_sso_settings_in_db(prisma_client=prisma_client)+ if self._should_load_db_object(object_type="cache_settings"):+ from litellm.proxy.management_endpoints.cache_settings_endpoints import (+ CacheSettingsManager,+ )+ await CacheSettingsManager.init_cache_settings_in_db(+ prisma_client=prisma_client, proxy_config=self+ )async def _init_sso_settings_in_db(self, prisma_client: PrismaClient):"""@@ -3559,7 +3594,9 @@ class ProxyConfig:"""global llm_router- from litellm.proxy.search_endpoints.search_tool_registry import SearchToolRegistry+ from litellm.proxy.search_endpoints.search_tool_registry import (+ SearchToolRegistry,+ )from litellm.router_utils.search_api_router import SearchAPIRoutertry:@@ -4076,8 +4113,8 @@ class ProxyStartupEvent:# 1. Remove/minimize jitter to avoid normalize() memory explosion# 2. Use larger misfire_grace_time to prevent backlog calculations# 3. Set replace_existing=True to avoid duplicate jobs- from apscheduler.jobstores.memory import MemoryJobStorefrom apscheduler.executors.asyncio import AsyncIOExecutor+ from apscheduler.jobstores.memory import MemoryJobStorescheduler = AsyncIOScheduler(job_defaults={@@ -10044,6 +10081,7 @@ app.include_router(model_management_router)app.include_router(tag_management_router)app.include_router(cost_tracking_settings_router)app.include_router(router_settings_router)+app.include_router(cache_settings_router)app.include_router(user_agent_analytics_router)app.include_router(enterprise_router)app.include_router(ui_discovery_endpoints_router)diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prismaindex ce2fc2e4753..ac1acee908a 100644--- a/litellm/proxy/schema.prisma+++ b/litellm/proxy/schema.prisma@@ -588,4 +588,12 @@ model LiteLLM_SSOConfig {sso_settings Jsoncreated_at DateTime @default(now())updated_at DateTime @updatedAt+}++// Cache configuration table+model LiteLLM_CacheConfig {+ id String @id @default("cache_config")+ cache_settings Json+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt}\ No newline at end of filediff --git a/litellm/types/management_endpoints/__init__.py b/litellm/types/management_endpoints/__init__.pyindex 90f7333edb9..edcc2f51339 100644--- a/litellm/types/management_endpoints/__init__.py+++ b/litellm/types/management_endpoints/__init__.py@@ -2,6 +2,11 @@Types for management endpoints"""+from .cache_settings_endpoints import (+ CACHE_SETTINGS_FIELDS,+ REDIS_TYPE_DESCRIPTIONS,+ CacheSettingsField,+)from .router_settings_endpoints import (ROUTER_SETTINGS_FIELDS,ROUTING_STRATEGY_DESCRIPTIONS,@@ -12,5 +17,8 @@ __all__ = ["ROUTER_SETTINGS_FIELDS","ROUTING_STRATEGY_DESCRIPTIONS","RouterSettingsField",+ "CACHE_SETTINGS_FIELDS",+ "REDIS_TYPE_DESCRIPTIONS",+ "CacheSettingsField",]diff --git a/litellm/types/management_endpoints/cache_settings_endpoints.py b/litellm/types/management_endpoints/cache_settings_endpoints.pynew file mode 100644index 00000000000..4afef21b194--- /dev/null+++ b/litellm/types/management_endpoints/cache_settings_endpoints.py@@ -0,0 +1,191 @@+"""+Types and field definitions for cache settings management endpoints+"""++from typing import Any, Dict, List, Optional++from pydantic import BaseModel+++class CacheSettingsField(BaseModel):+ field_name: str+ field_type: str+ field_value: Any+ field_description: str+ field_default: Any = None+ options: Optional[List[str]] = None # For fields with predefined options/enum values+ ui_field_name: str # User-friendly display name+ link: Optional[str] = None # Documentation link for the field+ redis_type: Optional[str] = None # Which Redis type this field applies to (node, cluster, sentinel)+++# Redis type descriptions+REDIS_TYPE_DESCRIPTIONS: Dict[str, str] = {+ "node": "Standard Redis node/single instance",+ "cluster": "Redis Cluster mode for high availability and horizontal scaling",+ "sentinel": "Redis Sentinel mode for high availability with automatic failover",+}+++# Define all available cache settings fields+CACHE_SETTINGS_FIELDS: List[CacheSettingsField] = [+ CacheSettingsField(+ field_name="redis_type",+ field_type="String",+ field_value=None,+ field_description="Type of Redis deployment",+ field_default="node",+ options=["node", "cluster", "sentinel"],+ ui_field_name="Redis Type",+ redis_type=None,+ ),+ # Common fields for all Redis types+ CacheSettingsField(+ field_name="host",+ field_type="String",+ field_value=None,+ field_description="Redis server hostname or IP address",+ field_default=None,+ ui_field_name="Host",+ redis_type=None,+ ),+ CacheSettingsField(+ field_name="port",+ field_type="String",+ field_value=None,+ field_description="Redis server port number",+ field_default="6379",+ ui_field_name="Port",+ redis_type=None,+ ),+ CacheSettingsField(+ field_name="password",+ field_type="String",+ field_value=None,+ field_description="Redis server password",+ field_default=None,+ ui_field_name="Password",+ redis_type=None,+ ),+ CacheSettingsField(+ field_name="username",+ field_type="String",+ field_value=None,+ field_description="Redis server username (if required)",+ field_default=None,+ ui_field_name="Username",+ redis_type=None,+ ),+ CacheSettingsField(+ field_name="ssl",+ field_type="Boolean",+ field_value=None,+ field_description="Enable SSL/TLS connection",+ field_default=False,+ ui_field_name="SSL",+ redis_type=None,+ ),+ CacheSettingsField(+ field_name="namespace",+ field_type="String",+ field_value=None,+ field_description="Namespace prefix for cache keys",+ field_default=None,+ ui_field_name="Namespace",+ redis_type=None,+ ),+ CacheSettingsField(+ field_name="ttl",+ field_type="Float",+ field_value=None,+ field_description="Time-to-live for cached items in seconds",+ field_default=None,+ ui_field_name="TTL (seconds)",+ redis_type=None,+ ),+ CacheSettingsField(+ field_name="max_connections",+ field_type="Integer",+ field_value=None,+ field_description="Maximum number of connections in the connection pool",+ field_default=None,+ ui_field_name="Max Connections",+ redis_type=None,+ ),+ # Cluster-specific fields+ CacheSettingsField(+ field_name="redis_startup_nodes",+ field_type="List",+ field_value=None,+ field_description="List of startup nodes for Redis Cluster (e.g., [{'host': '127.0.0.1', 'port': '7001'}])",+ field_default=None,+ ui_field_name="Startup Nodes",+ redis_type="cluster",+ ),+ # Sentinel-specific fields+ CacheSettingsField(+ field_name="sentinel_nodes",+ field_type="List",+ field_value=None,+ field_description="List of Sentinel nodes (e.g., [['localhost', 26379]])",+ field_default=None,+ ui_field_name="Sentinel Nodes",+ redis_type="sentinel",+ ),+ CacheSettingsField(+ field_name="service_name",+ field_type="String",+ field_value=None,+ field_description="Master service name for Redis Sentinel",+ field_default=None,+ ui_field_name="Service Name",+ redis_type="sentinel",+ ),+ CacheSettingsField(+ field_name="sentinel_password",+ field_type="String",+ field_value=None,+ field_description="Password for Redis Sentinel authentication",+ field_default=None,+ ui_field_name="Sentinel Password",+ redis_type="sentinel",+ ),+ # GCP IAM authentication fields+ CacheSettingsField(+ field_name="gcp_service_account",+ field_type="String",+ field_value=None,+ field_description="GCP service account for IAM authentication (e.g., projects/-/serviceAccounts/[email protected])",+ field_default=None,+ ui_field_name="GCP Service Account",+ redis_type=None,+ ),+ CacheSettingsField(+ field_name="gcp_ssl_ca_certs",+ field_type="String",+ field_value=None,+ field_description="Path to SSL CA certificate file for GCP Memorystore Redis",+ field_default=None,+ ui_field_name="GCP SSL CA Certs",+ redis_type=None,+ ),+ CacheSettingsField(+ field_name="ssl_cert_reqs",+ field_type="String",+ field_value=None,+ field_description="SSL certificate requirements (None, CERT_REQUIRED, CERT_OPTIONAL)",+ field_default=None,+ ui_field_name="SSL Cert Reqs",+ redis_type=None,+ ),+ CacheSettingsField(+ field_name="ssl_check_hostname",+ field_type="Boolean",+ field_value=None,+ field_description="Enable SSL hostname verification",+ field_default=None,+ ui_field_name="SSL Check Hostname",+ redis_type=None,+ ),+]+diff --git a/schema.prisma b/schema.prismaindex ce2fc2e4753..ac1acee908a 100644--- a/schema.prisma+++ b/schema.prisma@@ -588,4 +588,12 @@ model LiteLLM_SSOConfig {sso_settings Jsoncreated_at DateTime @default(now())updated_at DateTime @updatedAt+}++// Cache configuration table+model LiteLLM_CacheConfig {+ id String @id @default("cache_config")+ cache_settings Json+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt}\ No newline at end of filediff --git a/tests/test_litellm/proxy/management_endpoints/test_cache_settings_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_cache_settings_endpoints.pynew file mode 100644index 00000000000..5fcd092bf77--- /dev/null+++ b/tests/test_litellm/proxy/management_endpoints/test_cache_settings_endpoints.py@@ -0,0 +1,251 @@+"""+Unit tests for cache settings management endpoints+"""++import os+import sys+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++sys.path.insert(+ 0, os.path.abspath("../../../..")+) # Adds the parent directory to the system path++from litellm.proxy._types import LitellmUserRoles+from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth+from litellm.proxy.management_endpoints.cache_settings_endpoints import (+ CacheSettingsManager,+ CacheTestRequest,+ test_cache_connection,+)+++async def test_test_cache_connection_calls_cache_test_connection_with_params():+ """+ Test that test_cache_connection endpoint calls cache.test_connection()+ with the correct parameters from the request body.+ """+ # Mock cache settings from request+ cache_settings = {+ "type": "redis",+ "host": "test-redis-host",+ "port": "6379",+ "password": "test-password",+ }++ request = CacheTestRequest(cache_settings=cache_settings)+ user_api_key_dict = UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-test", user_id="test-user"+ )++ # Mock Cache class and its test_connection method+ mock_cache_instance = MagicMock()+ mock_cache_instance.cache = MagicMock()+ mock_cache_instance.cache.test_connection = AsyncMock(+ return_value={+ "status": "success",+ "message": "Redis connection test successful",+ }+ )++ # Patch Cache class at the import location (litellm module)+ with patch("litellm.Cache") as mock_cache_class:+ mock_cache_class.return_value = mock_cache_instance++ # Call the endpoint+ result = await test_cache_connection(+ request=request, user_api_key_dict=user_api_key_dict+ )++ # Verify Cache was instantiated with correct params+ mock_cache_class.assert_called_once_with(**cache_settings)++ # Verify test_connection was called on the cache instance+ mock_cache_instance.cache.test_connection.assert_called_once()++ # Verify response+ assert result.status == "success"+ assert result.message == "Redis connection test successful"+ assert result.error is None+++class TestCacheSettingsManager:+ """Tests for CacheSettingsManager class"""++ def test_cache_params_equal_identical_params(self):+ """+ Test that _cache_params_equal returns True for identical params.+ """+ params1 = {+ "type": "redis",+ "host": "localhost",+ "port": "6379",+ "password": "test-password",+ }+ params2 = {+ "type": "redis",+ "host": "localhost",+ "port": "6379",+ "password": "test-password",+ }++ result = CacheSettingsManager._cache_params_equal(params1, params2)+ assert result is True++ def test_cache_params_equal_different_params(self):+ """+ Test that _cache_params_equal returns False for different params.+ """+ params1 = {+ "type": "redis",+ "host": "localhost",+ "port": "6379",+ }+ params2 = {+ "type": "redis",+ "host": "different-host",+ "port": "6379",+ }++ result = CacheSettingsManager._cache_params_equal(params1, params2)+ assert result is False++ def test_cache_params_equal_filters_redis_type(self):+ """+ Test that _cache_params_equal filters out redis_type field.+ """+ params1 = {+ "type": "redis",+ "host": "localhost",+ "redis_type": "node", # Should be ignored+ }+ params2 = {+ "type": "redis",+ "host": "localhost",+ "redis_type": "cluster", # Different value, but should be ignored+ }++ result = CacheSettingsManager._cache_params_equal(params1, params2)+ assert result is True++ def test_cache_params_equal_filters_none_values(self):+ """+ Test that _cache_params_equal filters out None values.+ """+ params1 = {+ "type": "redis",+ "host": "localhost",+ "port": None,+ }+ params2 = {+ "type": "redis",+ "host": "localhost",+ }++ result = CacheSettingsManager._cache_params_equal(params1, params2)+ assert result is True++ def test_update_cache_params(self):+ """+ Test that update_cache_params updates the tracked cache params.+ """+ # Reset the class variable+ CacheSettingsManager._last_cache_params = None++ cache_params = {+ "type": "redis",+ "host": "localhost",+ "port": "6379",+ }++ CacheSettingsManager.update_cache_params(cache_params)++ assert CacheSettingsManager._last_cache_params == cache_params+ # Verify it's a copy, not a reference+ assert CacheSettingsManager._last_cache_params is not cache_params++ @pytest.mark.asyncio+ async def test_init_cache_settings_in_db_initializes_when_params_changed(self):+ """+ Test that init_cache_settings_in_db initializes cache when params change.+ """+ # Reset the class variable+ CacheSettingsManager._last_cache_params = None++ # Mock prisma client+ mock_prisma_client = MagicMock()+ mock_cache_config = MagicMock()+ mock_cache_config.cache_settings = '{"type": "redis", "host": "localhost", "port": "6379"}'+ mock_prisma_client.db.litellm_cacheconfig.find_unique = AsyncMock(+ return_value=mock_cache_config+ )++ # Mock proxy_config+ mock_proxy_config = MagicMock()+ mock_proxy_config._decrypt_db_variables = MagicMock(+ return_value={+ "type": "redis",+ "host": "localhost",+ "port": "6379",+ }+ )+ mock_proxy_config._init_cache = MagicMock()+ mock_proxy_config.switch_on_llm_response_caching = MagicMock()++ # Call the method+ await CacheSettingsManager.init_cache_settings_in_db(+ prisma_client=mock_prisma_client, proxy_config=mock_proxy_config+ )++ # Verify cache was initialized+ mock_proxy_config._init_cache.assert_called_once()+ mock_proxy_config.switch_on_llm_response_caching.assert_called_once()++ # Verify params were stored+ assert CacheSettingsManager._last_cache_params is not None+ assert "type" in CacheSettingsManager._last_cache_params+ assert "redis_type" not in CacheSettingsManager._last_cache_params++ @pytest.mark.asyncio+ async def test_init_cache_settings_in_db_skips_when_params_unchanged(self):+ """+ Test that init_cache_settings_in_db skips initialization when params unchanged.+ """+ # Set existing params+ existing_params = {+ "type": "redis",+ "host": "localhost",+ "port": "6379",+ }+ CacheSettingsManager._last_cache_params = existing_params.copy()++ # Mock prisma client+ mock_prisma_client = MagicMock()+ mock_cache_config = MagicMock()+ mock_cache_config.cache_settings = '{"type": "redis", "host": "localhost", "port": "6379"}'+ mock_prisma_client.db.litellm_cacheconfig.find_unique = AsyncMock(+ return_value=mock_cache_config+ )++ # Mock proxy_config+ mock_proxy_config = MagicMock()+ mock_proxy_config._decrypt_db_variables = MagicMock(+ return_value={+ "type": "redis",+ "host": "localhost",+ "port": "6379",+ }+ )+ mock_proxy_config._init_cache = MagicMock()+ mock_proxy_config.switch_on_llm_response_caching = MagicMock()++ # Call the method+ await CacheSettingsManager.init_cache_settings_in_db(+ prisma_client=mock_prisma_client, proxy_config=mock_proxy_config+ )++ # Verify cache was NOT initialized (params unchanged)+ mock_proxy_config._init_cache.assert_not_called()+ mock_proxy_config.switch_on_llm_response_caching.assert_not_called()diff --git a/ui/litellm-dashboard/src/components/cache_dashboard.tsx b/ui/litellm-dashboard/src/components/cache_dashboard.tsxindex 1713e4b0462..a1c0cb0a664 100644--- a/ui/litellm-dashboard/src/components/cache_dashboard.tsx+++ b/ui/litellm-dashboard/src/components/cache_dashboard.tsx@@ -24,6 +24,7 @@ import { adminGlobalCacheActivity, cachingHealthCheckCall } from "./networking";// Import the new componentimport { CacheHealthTab } from "./cache_health";+import CacheSettings from "./cache_settings";const formatDateWithoutTZ = (date: Date | undefined) => {if (!date) return undefined;@@ -273,6 +274,7 @@ const CacheDashboard: React.FC<CachePageProps> = ({ accessToken, token, userRole<Tab><pre>Cache Health</pre></Tab>+ <Tab>Cache Settings</Tab></div><div className="flex items-center space-x-2">@@ -385,6 +387,13 @@ const CacheDashboard: React.FC<CachePageProps> = ({ accessToken, token, userRolerunCachingHealthCheck={runCachingHealthCheck}/></TabPanel>+ <TabPanel>+ <CacheSettings+ accessToken={accessToken}+ userRole={userRole}+ userID={userID}+ />+ </TabPanel></TabPanels></TabGroup>);diff --git a/ui/litellm-dashboard/src/components/cache_settings/CacheFieldGroup.test.tsx b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldGroup.test.tsxnew file mode 100644index 00000000000..9809bec743e--- /dev/null+++ b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldGroup.test.tsx@@ -0,0 +1,148 @@+import { describe, it, expect, beforeEach } from "vitest";+import { render, screen, cleanup } from "@testing-library/react";+import CacheFieldGroup from "./CacheFieldGroup";++describe("CacheFieldGroup", () => {+ beforeEach(() => {+ cleanup();+ });++ it("should filter and render fields based on redisType", () => {+ /**+ * Tests that CacheFieldGroup filters fields based on redis_type and redisType prop.+ * This is the core functionality that shows/hides fields based on Redis deployment type.+ */+ const fields = [+ {+ field_name: "host",+ field_type: "String",+ ui_field_name: "Host",+ redis_type: null, // Applies to all types+ },+ {+ field_name: "redis_startup_nodes",+ field_type: "List",+ ui_field_name: "Startup Nodes",+ redis_type: "cluster", // Only for cluster+ },+ {+ field_name: "sentinel_nodes",+ field_type: "List",+ ui_field_name: "Sentinel Nodes",+ redis_type: "sentinel", // Only for sentinel+ },+ ];++ const cacheSettings = {+ host: "localhost",+ redis_startup_nodes: [],+ };++ // Test with cluster type - should show host and redis_startup_nodes+ const { rerender } = render(+ <CacheFieldGroup+ title="Cluster Settings"+ fields={fields}+ cacheSettings={cacheSettings}+ redisType="cluster"+ />+ );++ expect(screen.getByText("Cluster Settings")).toBeInTheDocument();+ expect(screen.getAllByText("Host")).toHaveLength(1);+ expect(screen.getByText("Startup Nodes")).toBeInTheDocument();+ expect(screen.queryByText("Sentinel Nodes")).not.toBeInTheDocument();++ // Test with sentinel type - should show host and sentinel_nodes+ rerender(+ <CacheFieldGroup+ title="Sentinel Settings"+ fields={fields}+ cacheSettings={cacheSettings}+ redisType="sentinel"+ />+ );++ expect(screen.getByText("Sentinel Settings")).toBeInTheDocument();+ expect(screen.getAllByText("Host")).toHaveLength(1);+ expect(screen.getByText("Sentinel Nodes")).toBeInTheDocument();+ expect(screen.queryByText("Startup Nodes")).not.toBeInTheDocument();++ // Test with node type - should only show host+ rerender(+ <CacheFieldGroup+ title="Node Settings"+ fields={fields}+ cacheSettings={cacheSettings}+ redisType="node"+ />+ );++ expect(screen.getByText("Node Settings")).toBeInTheDocument();+ expect(screen.getAllByText("Host")).toHaveLength(1);+ expect(screen.queryByText("Startup Nodes")).not.toBeInTheDocument();+ expect(screen.queryByText("Sentinel Nodes")).not.toBeInTheDocument();+ });++ it("should return null when no fields are visible", () => {+ /**+ * Tests that CacheFieldGroup returns null when no fields match the redisType.+ * This prevents rendering empty sections in the UI.+ */+ const fields = [+ {+ field_name: "redis_startup_nodes",+ field_type: "List",+ ui_field_name: "Startup Nodes",+ redis_type: "cluster", // Only for cluster+ },+ ];++ const cacheSettings = {};++ const { container } = render(+ <CacheFieldGroup+ title="Cluster Settings"+ fields={fields}+ cacheSettings={cacheSettings}+ redisType="node" // No fields match this type+ />+ );++ // Component should return null, so container should be empty+ expect(container.firstChild).toBeNull();+ });++ it("should use field_default when currentValue is not available", () => {+ /**+ * Tests that CacheFieldGroup falls back to field_default when currentValue is missing.+ * This ensures fields display default values when cache settings are not set.+ */+ const fields = [+ {+ field_name: "port",+ field_type: "Integer",+ ui_field_name: "Port",+ field_default: 6379,+ redis_type: null,+ },+ ];++ const cacheSettings = {}; // No port value set++ render(+ <CacheFieldGroup+ title="Connection Settings"+ fields={fields}+ cacheSettings={cacheSettings}+ redisType="node"+ />+ );++ const input = screen.getByRole("spinbutton", { name: "" });+ expect(input).toBeInTheDocument();+ expect(input).toHaveAttribute("name", "port");+ expect(input).toHaveValue(6379);+ });+});+diff --git a/ui/litellm-dashboard/src/components/cache_settings/CacheFieldGroup.tsx b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldGroup.tsxnew file mode 100644index 00000000000..2f6b9127619--- /dev/null+++ b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldGroup.tsx@@ -0,0 +1,54 @@+import React from "react";+import CacheFieldRenderer from "./CacheFieldRenderer";++interface CacheFieldGroupProps {+ title: string;+ fields: any[];+ cacheSettings: { [key: string]: any };+ redisType: string;+ gridCols?: string;+}++const CacheFieldGroup: React.FC<CacheFieldGroupProps> = ({+ title,+ fields,+ cacheSettings,+ redisType,+ gridCols = "grid-cols-1 gap-6 sm:grid-cols-2",+}) => {+ const shouldShowField = (field: any): boolean => {+ // Show field if it applies to all types (redis_type is null/undefined) or to current selected type+ if (field.redis_type === null || field.redis_type === undefined) {+ return true;+ }++ return field.redis_type === redisType;+ };++ const visibleFields = fields.filter(shouldShowField);++ if (visibleFields.length === 0) {+ return null;+ }++ return (+ <div className="space-y-6 pt-4 border-t border-gray-200">+ <h4 className="text-sm font-medium text-gray-900">{title}</h4>+ <div className={`grid ${gridCols}`}>+ {visibleFields.map((field) => {+ const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";+ return (+ <CacheFieldRenderer+ key={field.field_name}+ field={field}+ currentValue={currentValue}+ />+ );+ })}+ </div>+ </div>+ );+};++export default CacheFieldGroup;+diff --git a/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.test.tsx b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.test.tsxnew file mode 100644index 00000000000..67b4cadfd5f--- /dev/null+++ b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.test.tsx@@ -0,0 +1,113 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import CacheFieldRenderer from "./CacheFieldRenderer";++describe("CacheFieldRenderer", () => {+ it("should render a checkbox for Boolean field type", () => {+ /**+ * Tests that Boolean fields render as checkboxes with proper defaultChecked value.+ * This is the core functionality for boolean cache settings.+ */+ const field = {+ field_name: "ssl",+ field_type: "Boolean",+ ui_field_name: "Enable SSL",+ field_description: "Enable SSL encryption",+ };++ render(<CacheFieldRenderer field={field} currentValue={true} />);++ const checkbox = screen.getByRole("checkbox", { name: "" });+ expect(checkbox).toBeInTheDocument();+ expect(checkbox).toBeChecked();+ expect(screen.getByText("Enable SSL")).toBeInTheDocument();+ expect(screen.getByText("Enable SSL encryption")).toBeInTheDocument();+ });++ it("should render a textarea for List field type", () => {+ /**+ * Tests that List fields render as textareas with JSON stringified values.+ * This handles array/list cache settings like redis_startup_nodes.+ */+ const field = {+ field_name: "redis_startup_nodes",+ field_type: "List",+ ui_field_name: "Redis Startup Nodes",+ field_description: "List of Redis cluster nodes",+ };++ const currentValue = [+ { host: "localhost", port: 6379 },+ { host: "localhost", port: 6380 },+ ];++ render(<CacheFieldRenderer field={field} currentValue={currentValue} />);++ const textarea = screen.getByRole("textbox");+ expect(textarea).toBeInTheDocument();+ expect(textarea.tagName).toBe("TEXTAREA");+ expect(textarea).toHaveValue(JSON.stringify(currentValue, null, 2));+ expect(screen.getByText("Redis Startup Nodes")).toBeInTheDocument();+ });++ it("should render a password input for password field", () => {+ /**+ * Tests that password fields render as password inputs.+ * This ensures sensitive data is masked in the UI.+ */+ const field = {+ field_name: "password",+ field_type: "String",+ ui_field_name: "Password",+ field_description: "Redis password",+ };++ render(<CacheFieldRenderer field={field} currentValue="secret123" />);++ const input = screen.getByPlaceholderText("Redis password");+ expect(input).toBeInTheDocument();+ expect(input).toHaveAttribute("type", "password");+ expect(input).toHaveValue("secret123");+ });++ it("should render a number input for Integer field type", () => {+ /**+ * Tests that Integer fields render as number inputs.+ * This ensures proper validation for numeric cache settings.+ */+ const field = {+ field_name: "port",+ field_type: "Integer",+ ui_field_name: "Port",+ field_description: "Redis port number",+ };++ render(<CacheFieldRenderer field={field} currentValue={6379} />);++ const input = screen.getByPlaceholderText("Redis port number");+ expect(input).toBeInTheDocument();+ expect(input).toHaveAttribute("type", "number");+ expect(input).toHaveValue(6379);+ });++ it("should render a text input for String field type", () => {+ /**+ * Tests that String fields render as text inputs.+ * This is the default rendering for text-based cache settings.+ */+ const field = {+ field_name: "host",+ field_type: "String",+ ui_field_name: "Host",+ field_description: "Redis host address",+ };++ render(<CacheFieldRenderer field={field} currentValue="localhost" />);++ const input = screen.getByPlaceholderText("Redis host address");+ expect(input).toBeInTheDocument();+ expect(input).toHaveAttribute("type", "text");+ expect(input).toHaveValue("localhost");+ });+});+diff --git a/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.tsx b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.tsxnew file mode 100644index 00000000000..e36c167c9dd--- /dev/null+++ b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.tsx@@ -0,0 +1,77 @@+import React from "react";+import { TextInput } from "@tremor/react";++interface CacheFieldRendererProps {+ field: any;+ currentValue: any;+}++const CacheFieldRenderer: React.FC<CacheFieldRendererProps> = ({+ field,+ currentValue,+}) => {+ if (field.field_type === "Boolean") {+ return (+ <div className="space-y-2">+ <label className="text-sm font-medium text-gray-700">+ {field.ui_field_name}+ </label>+ <div className="flex items-center">+ <input+ type="checkbox"+ name={field.field_name}+ defaultChecked={currentValue === true || currentValue === "true"}+ className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"+ />+ <span className="ml-2 text-sm text-gray-500">{field.field_description}</span>+ </div>+ </div>+ );+ }++ if (field.field_type === "List") {+ return (+ <div className="space-y-2">+ <label className="text-sm font-medium text-gray-700">+ {field.ui_field_name}+ </label>+ <textarea+ name={field.field_name}+ defaultValue={typeof currentValue === "object" ? JSON.stringify(currentValue, null, 2) : currentValue}+ placeholder={field.field_description}+ className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"+ rows={4}+ />+ <p className="text-xs text-gray-500">{field.field_description}</p>+ </div>+ );+ }++ // Determine input type+ let inputType = "text";+ if (field.field_type === "Integer" || field.field_type === "Float") {+ inputType = "number";+ } else if (field.field_name === "password" || field.field_name.includes("password")) {+ inputType = "password";+ }++ return (+ <div className="space-y-2">+ <label className="text-sm font-medium text-gray-700">+ {field.ui_field_name}+ </label>+ <TextInput+ name={field.field_name}+ type={inputType}+ defaultValue={currentValue}+ placeholder={field.field_description}+ />+ {field.field_description && (+ <p className="text-xs text-gray-500">{field.field_description}</p>+ )}+ </div>+ );+};++export default CacheFieldRenderer;+diff --git a/ui/litellm-dashboard/src/components/cache_settings/RedisTypeSelector.tsx b/ui/litellm-dashboard/src/components/cache_settings/RedisTypeSelector.tsxnew file mode 100644index 00000000000..08a054b7440--- /dev/null+++ b/ui/litellm-dashboard/src/components/cache_settings/RedisTypeSelector.tsx@@ -0,0 +1,32 @@+import React from "react";+import { Select, SelectItem } from "@tremor/react";++interface RedisTypeSelectorProps {+ redisType: string;+ redisTypeDescriptions: { [key: string]: string };+ onTypeChange: (type: string) => void;+}++const RedisTypeSelector: React.FC<RedisTypeSelectorProps> = ({+ redisType,+ redisTypeDescriptions,+ onTypeChange,+}) => {+ return (+ <div className="space-y-2">+ <label className="text-sm font-medium text-gray-700">Redis Type</label>+ <Select value={redisType} onValueChange={onTypeChange}>+ <SelectItem value="node">Node (Single Instance)</SelectItem>+ <SelectItem value="cluster">Cluster</SelectItem>+ <SelectItem value="sentinel">Sentinel</SelectItem>+ </Select>+ <p className="text-xs text-gray-500">+ {redisTypeDescriptions[redisType] ||+ "Select the type of Redis deployment you're using"}+ </p>+ </div>+ );+};++export default RedisTypeSelector;+diff --git a/ui/litellm-dashboard/src/components/cache_settings/cacheSettingsUtils.ts b/ui/litellm-dashboard/src/components/cache_settings/cacheSettingsUtils.tsnew file mode 100644index 00000000000..748c1debb1e--- /dev/null+++ b/ui/litellm-dashboard/src/components/cache_settings/cacheSettingsUtils.ts@@ -0,0 +1,111 @@+/**+ * Utility functions for cache settings form handling+ */++export const shouldShowField = (field: any, redisType: string): boolean => {+ // Show field if it applies to all types (redis_type is null/undefined) or to current selected type+ if (field.redis_type === null || field.redis_type === undefined) {+ return true;+ }++ return field.redis_type === redisType;+};++export const getFieldByName = (fields: any[], fieldName: string) => {+ return fields.find(f => f.field_name === fieldName);+};++export const groupFieldsByCategory = (fields: any[], redisType: string) => {+ // Basic fields that are always shown+ const basicFieldNames = ["host", "port", "password", "username"];+ const basicFields = basicFieldNames+ .map(name => getFieldByName(fields, name))+ .filter(Boolean);++ // Advanced field groups+ const sslFields = ["ssl", "ssl_cert_reqs", "ssl_check_hostname"]+ .map(name => getFieldByName(fields, name))+ .filter(Boolean);++ const cacheManagementFields = ["namespace", "ttl", "max_connections"]+ .map(name => getFieldByName(fields, name))+ .filter(Boolean);++ const gcpFields = ["gcp_service_account", "gcp_ssl_ca_certs"]+ .map(name => getFieldByName(fields, name))+ .filter(Boolean);++ // Redis type-specific fields+ const clusterFields = fields.filter(f => f.redis_type === "cluster");+ const sentinelFields = fields.filter(f => f.redis_type === "sentinel");++ return {+ basicFields,+ sslFields,+ cacheManagementFields,+ gcpFields,+ clusterFields,+ sentinelFields,+ };+};++export const gatherFormValues = (fields: any[], redisType: string): { [key: string]: any } => {+ const values: { [key: string]: any } = {+ type: "redis", // Cache class accepts 'type' parameter (LiteLLMCacheType enum)+ };++ // Iterate through all fields from backend+ fields.forEach((field) => {+ // Skip redis_type - it's UI-only, not sent to backend+ if (field.field_name === "redis_type") {+ return;+ }++ // Check if field should be shown for current redis type+ if (!shouldShowField(field, redisType)) {+ return;+ }++ const fieldName = field.field_name;+ let value: any = null;++ if (field.field_type === "Boolean") {+ const checkboxEl = document.querySelector(`input[name="${fieldName}"]`) as HTMLInputElement | null;+ if (checkboxEl?.checked !== undefined) {+ value = checkboxEl.checked;+ }+ } else if (field.field_type === "List") {+ const textareaEl = document.querySelector(`textarea[name="${fieldName}"]`) as HTMLTextAreaElement | null;+ if (textareaEl?.value) {+ try {+ value = JSON.parse(textareaEl.value);+ } catch (e) {+ console.error(`Invalid JSON for ${fieldName}:`, e);+ }+ }+ } else {+ const inputEl = document.querySelector(`input[name="${fieldName}"]`) as HTMLInputElement | null;+ if (inputEl?.value) {+ const trimmedValue = inputEl.value.trim();+ if (trimmedValue !== "") {+ if (field.field_type === "Integer") {+ const num = Number(trimmedValue);+ if (!isNaN(num)) value = num;+ } else if (field.field_type === "Float") {+ const num = Number(trimmedValue);+ if (!isNaN(num)) value = num;+ } else {+ value = trimmedValue;+ }+ }+ }+ }++ if (value !== null && value !== undefined) {+ values[fieldName] = value;+ }+ });++ return values;+};+diff --git a/ui/litellm-dashboard/src/components/cache_settings/index.tsx b/ui/litellm-dashboard/src/components/cache_settings/index.tsxnew file mode 100644index 00000000000..d7581041ca8--- /dev/null+++ b/ui/litellm-dashboard/src/components/cache_settings/index.tsx@@ -0,0 +1,290 @@+import React, { useState, useEffect } from "react";+import { Button, Accordion, AccordionHeader, AccordionBody } from "@tremor/react";+import {+ getCacheSettingsCall,+ testCacheConnectionCall,+ updateCacheSettingsCall,+} from "../networking";+import NotificationsManager from "../molecules/notifications_manager";+import RedisTypeSelector from "./RedisTypeSelector";+import CacheFieldRenderer from "./CacheFieldRenderer";+import { gatherFormValues, groupFieldsByCategory } from "./cacheSettingsUtils";++interface CacheSettingsProps {+ accessToken: string | null;+ userRole: string | null;+ userID: string | null;+}++const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, userID }) => {+ const [cacheSettings, setCacheSettings] = useState<{ [key: string]: any }>({});+ const [fields, setFields] = useState<any[]>([]);+ const [redisTypeDescriptions, setRedisTypeDescriptions] = useState<{ [key: string]: string }>({});+ const [redisType, setRedisType] = useState<string>("node");+ const [isTesting, setIsTesting] = useState<boolean>(false);+ const [isSaving, setIsSaving] = useState<boolean>(false);++ useEffect(() => {+ if (!accessToken) {+ return;+ }+ loadCacheSettings();+ }, [accessToken]);++ const loadCacheSettings = async () => {+ try {+ const data = await getCacheSettingsCall(accessToken!);+ console.log("cache settings from API", data);++ if (data.fields) {+ setFields(data.fields);+ }++ // Set current values+ if (data.current_values) {+ setCacheSettings(data.current_values);+ if (data.current_values.redis_type) {+ setRedisType(data.current_values.redis_type);+ }+ }++ // Store Redis type descriptions+ if (data.redis_type_descriptions) {+ setRedisTypeDescriptions(data.redis_type_descriptions);+ }+ } catch (error) {+ console.error("Failed to load cache settings:", error);+ NotificationsManager.fromBackend("Failed to load cache settings");+ }+ };++ const handleTestConnection = async () => {+ if (!accessToken) {+ return;+ }++ setIsTesting(true);+ try {+ const testSettings = gatherFormValues(fields, redisType);+ const result = await testCacheConnectionCall(accessToken, testSettings);++ if (result.status === "success") {+ NotificationsManager.success("Cache connection test successful!");+ } else {+ NotificationsManager.fromBackend(`Connection test failed: ${result.message || result.error}`);+ }+ } catch (error: any) {+ console.error("Test connection error:", error);+ NotificationsManager.fromBackend(`Connection test failed: ${error.message || "Unknown error"}`);+ } finally {+ setIsTesting(false);+ }+ };++ const handleSaveChanges = async () => {+ if (!accessToken) {+ return;+ }++ setIsSaving(true);+ try {+ const settingsToSave = gatherFormValues(fields, redisType);+ await updateCacheSettingsCall(accessToken, settingsToSave);+ NotificationsManager.success("Cache settings updated successfully");+ // Reload settings to reflect saved values+ await loadCacheSettings();+ } catch (error) {+ console.error("Failed to save cache settings:", error);+ NotificationsManager.fromBackend("Failed to update cache settings");+ } finally {+ setIsSaving(false);+ }+ };++ if (!accessToken) {+ return null;+ }++ const {+ basicFields,+ sslFields,+ cacheManagementFields,+ gcpFields,+ clusterFields,+ sentinelFields,+ } = groupFieldsByCategory(fields, redisType);++ return (+ <div className="w-full space-y-8 py-2">+ <div className="space-y-6">+ <div className="max-w-3xl">+ <h3 className="text-sm font-medium text-gray-900">Cache Settings</h3>+ <p className="text-xs text-gray-500 mt-1">Configure Redis cache for LiteLLM</p>+ </div>++ {/* Redis Type Selector */}+ <RedisTypeSelector+ redisType={redisType}+ redisTypeDescriptions={redisTypeDescriptions}+ onTypeChange={setRedisType}+ />++ {/* Basic Fields */}+ <div className="space-y-6 pt-4 border-t border-gray-200">+ <h4 className="text-sm font-medium text-gray-900">Connection Settings</h4>+ <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">+ {basicFields.map((field: any) => {+ if (!field) return null;+ const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";+ return (+ <CacheFieldRenderer+ key={field.field_name}+ field={field}+ currentValue={currentValue}+ />+ );+ })}+ </div>+ </div>++ {/* Redis Type-Specific Fields */}+ {redisType === "cluster" && clusterFields.length > 0 && (+ <div className="space-y-6 pt-4 border-t border-gray-200">+ <h4 className="text-sm font-medium text-gray-900">Cluster Configuration</h4>+ <div className="grid grid-cols-1 gap-6">+ {clusterFields.map((field: any) => {+ const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";+ return (+ <CacheFieldRenderer+ key={field.field_name}+ field={field}+ currentValue={currentValue}+ />+ );+ })}+ </div>+ </div>+ )}++ {redisType === "sentinel" && sentinelFields.length > 0 && (+ <div className="space-y-6 pt-4 border-t border-gray-200">+ <h4 className="text-sm font-medium text-gray-900">Sentinel Configuration</h4>+ <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">+ {sentinelFields.map((field: any) => {+ const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";+ return (+ <CacheFieldRenderer+ key={field.field_name}+ field={field}+ currentValue={currentValue}+ />+ );+ })}+ </div>+ </div>+ )}++ {/* Advanced Settings Accordion */}+ <Accordion className="mt-4">+ <AccordionHeader>+ <span className="text-sm font-medium text-gray-900">Advanced Settings</span>+ </AccordionHeader>+ <AccordionBody>+ <div className="space-y-6">+ {/* SSL Settings */}+ {sslFields.length > 0 && (+ <div className="space-y-4">+ <h5 className="text-sm font-medium text-gray-700">SSL Settings</h5>+ <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">+ {sslFields.map((field: any) => {+ if (!field) return null;+ const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";+ return (+ <CacheFieldRenderer+ key={field.field_name}+ field={field}+ currentValue={currentValue}+ />+ );+ })}+ </div>+ </div>+ )}++ {/* Cache Management */}+ {cacheManagementFields.length > 0 && (+ <div className="space-y-4 pt-4 border-t border-gray-200">+ <h5 className="text-sm font-medium text-gray-700">Cache Management</h5>+ <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">+ {cacheManagementFields.map((field: any) => {+ if (!field) return null;+ const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";+ return (+ <CacheFieldRenderer+ key={field.field_name}+ field={field}+ currentValue={currentValue}+ />+ );+ })}+ </div>+ </div>+ )}++ {/* GCP Authentication */}+ {gcpFields.length > 0 && (+ <div className="space-y-4 pt-4 border-t border-gray-200">+ <h5 className="text-sm font-medium text-gray-700">GCP Authentication</h5>+ <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">+ {gcpFields.map((field: any) => {+ if (!field) return null;+ const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";+ return (+ <CacheFieldRenderer+ key={field.field_name}+ field={field}+ currentValue={currentValue}+ />+ );+ })}+ </div>+ </div>+ )}+ </div>+ </AccordionBody>+ </Accordion>+ </div>++ {/* Actions */}+ <div className="border-t border-gray-200 pt-6 flex justify-end gap-3">+ <Button+ variant="secondary"+ size="sm"+ onClick={handleTestConnection}+ disabled={isTesting}+ className="text-sm"+ >+ {isTesting ? "Testing..." : "Test Connection"}+ </Button>+ <Button+ variant="secondary"+ size="sm"+ onClick={() => window.location.reload()}+ className="text-sm"+ >+ Reset+ </Button>+ <Button+ size="sm"+ onClick={handleSaveChanges}+ disabled={isSaving}+ className="text-sm font-medium"+ >+ {isSaving ? "Saving..." : "Save Changes"}+ </Button>+ </div>+ </div>+ );+};++export default CacheSettings;diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex b7489e7efcb..387e1dd0cb8 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -4471,6 +4471,103 @@ export const getRouterSettingsCall = async (accessToken: string) => {}};+export const getCacheSettingsCall = async (accessToken: string) => {+ try {+ let url = proxyBaseUrl+ ? `${proxyBaseUrl}/cache/settings`+ : `/cache/settings`;++ const response = await fetch(url, {+ method: "GET",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ const errorData = await response.json();+ const errorMessage = deriveErrorMessage(errorData);+ handleError(errorMessage);+ throw new Error(errorMessage);+ }++ const data = await response.json();+ return data;+ } catch (error) {+ console.error("Failed to get cache settings:", error);+ throw error;+ }+};++export const testCacheConnectionCall = async (+ accessToken: string,+ cacheSettings: Record<string, any>+) => {+ try {+ let url = proxyBaseUrl+ ? `${proxyBaseUrl}/cache/settings/test`+ : `/cache/settings/test`;++ const response = await fetch(url, {+ method: "POST",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ cache_settings: cacheSettings,+ }),+ });++ if (!response.ok) {+ const errorData = await response.json();+ const errorMessage = deriveErrorMessage(errorData);+ handleError(errorMessage);+ throw new Error(errorMessage);+ }++ const data = await response.json();+ return data;+ } catch (error) {+ console.error("Failed to test cache connection:", error);+ throw error;+ }+};++export const updateCacheSettingsCall = async (+ accessToken: string,+ cacheSettings: Record<string, any>+) => {+ try {+ let url = proxyBaseUrl ? `${proxyBaseUrl}/cache/settings` : `/cache/settings`;++ const response = await fetch(url, {+ method: "POST",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ cache_settings: cacheSettings,+ }),+ });++ if (!response.ok) {+ const errorData = await response.json();+ const errorMessage = deriveErrorMessage(errorData);+ handleError(errorMessage);+ throw new Error(errorMessage);+ }++ const data = await response.json();+ return data;+ } catch (error) {+ console.error("Failed to update cache settings:", error);+ throw error;+ }+};+export const getPassThroughEndpointsCall = async (accessToken: string, teamId?: string | null) => {try {let url = proxyBaseUrl ? `${proxyBaseUrl}/config/pass_through_endpoint` : `/config/pass_through_endpoint`;