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
Litellm revert redis changes (#11135)
Krish Dholakia33d5f6638721
diff --git a/litellm/caching/dual_cache.py b/litellm/caching/dual_cache.pyindex 91ce58162f2..8bef3337587 100644--- a/litellm/caching/dual_cache.py+++ b/litellm/caching/dual_cache.py@@ -196,7 +196,6 @@ class DualCache(BaseCache):key,parent_otel_span: Optional[Span] = None,local_only: bool = False,- redis_only: bool = False,**kwargs,):# Try to fetch from in-memory cache first@@ -205,7 +204,7 @@ class DualCache(BaseCache):f"async get cache: cache key: {key}; local_only: {local_only}")result = None- if self.in_memory_cache is not None and not redis_only:+ if self.in_memory_cache is not None:in_memory_result = await self.in_memory_cache.async_get_cache(key, **kwargs)@@ -214,7 +213,7 @@ class DualCache(BaseCache):if in_memory_result is not None:result = in_memory_result- if result is None and self.redis_cache is not None and not local_only:+ if result is None and self.redis_cache is not None and local_only is False:# If not found in in-memory cache, try fetching from Redisredis_result = await self.redis_cache.async_get_cache(key, parent_otel_span=parent_otel_spandiff --git a/litellm/caching/in_memory_cache.py b/litellm/caching/in_memory_cache.pyindex 532772a654c..8329e4be544 100644--- a/litellm/caching/in_memory_cache.py+++ b/litellm/caching/in_memory_cache.py@@ -114,10 +114,11 @@ class InMemoryCache(BaseCache):returnself.cache_dict[key] = value- if "ttl" in kwargs and kwargs["ttl"] is not None:- self.ttl_dict[key] = time.time() + kwargs["ttl"]- else:- self.ttl_dict[key] = time.time() + self.default_ttl+ if self.ttl_dict.get(key) is None: # if ttl is not set, set it to default ttl+ if "ttl" in kwargs and kwargs["ttl"] is not None:+ self.ttl_dict[key] = time.time() + kwargs["ttl"]+ else:+ self.ttl_dict[key] = time.time() + self.default_ttlasync def async_set_cache(self, key, value, **kwargs):self.set_cache(key=key, value=value, **kwargs)@@ -145,6 +146,7 @@ class InMemoryCache(BaseCache):if key in self.ttl_dict:if time.time() > self.ttl_dict[key]:self.cache_dict.pop(key, None)+ self.ttl_dict.pop(key, None)return Noneoriginal_cached_response = self.cache_dict[key]try:diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yamlindex 58b40e8f0ce..3c4ecc2ce73 100644--- a/litellm/proxy/_new_secret_config.yaml+++ b/litellm/proxy/_new_secret_config.yaml@@ -1,93 +1,9 @@model_list:- - model_name: "gemini-2.0-flash-gemini"+ - model_name: azure/anylitellm_params:- model: gemini/gemini-2.0-flash- - model_name: "gpt-4.1-openai"- litellm_params:- model: gpt-4.1- api_key: os.environ/OPENAI_API_KEY- model_info:- access_groups: ["default-openai-models"]- - model_name: "gpt-4o-realtime-preview"- litellm_params:- model: gpt-4o-realtime-preview-2024-10-01- api_key: os.environ/OPENAI_API_KEY_2- - model_name: "bedrock-nova"- litellm_params:- model: us.amazon.nova-pro-v1:0- - model_name: openrouter_model- litellm_params:- model: openrouter/openrouter_model- api_key: os.environ/OPENROUTER_API_KEY- api_base: http://0.0.0.0:8090- - model_name: dall-e-3-azure- litellm_params:- model: azure/dall-e-3-test- api_version: "2023-12-01-preview"- api_base: os.environ/AZURE_SWEDEN_API_BASE- api_key: os.environ/AZURE_SWEDEN_API_KEY- model_info:- input_cost_per_pixel: 10- - model_name: "claude-3-7-sonnet"- litellm_params:- model: databricks/databricks-claude-3-7-sonnet- api_key: os.environ/DATABRICKS_API_KEY- api_base: os.environ/DATABRICKS_API_BASE- - model_name: gpt-4.1- litellm_params:- model: openai/gpt-4o-realtime-preview- - model_name: "xai/*"- litellm_params:- model: xai/*- api_key: os.environ/XAI_API_KEY- - model_name: "text-embedding-ada-002"- litellm_params:- model: text-embedding-ada-002- api_key: os.environ/OPENAI_API_KEY- - model_name: gemini/gemini-2.0-flash- litellm_params:- model: gemini/gemini-2.0-flash- - model_name: llama-qwen- litellm_params:- model: ollama/qwen2:0.5b- model_info:- input_cost_per_token: 0.75- output_cost_per_token: 3- - model_name: gpt-image-1- litellm_params:- model: gpt-image-1- api_key: os.environ/OPENAI_API_KEY- # drop_params: true- - model_name: "gpt-4o-batch"- litellm_params:- model: azure/gpt-4o-mini- api_base: os.environ/AZURE_API_BASE- api_key: os.environ/AZURE_API_KEY- model_info:- id: my-general-azure-deployment- mode: batch- - model_name: mistral/*- litellm_params:- model: mistral/*- api_key: os.environ/MISTRAL_API_KEY- access_groups: ["beta-models"]- - model_name: my-langfuse-model- litellm_params:- model: langfuse/gpt-3.5-turbo- prompt_id: "jokes"- prompt_label: "latest"- api_key: os.environ/OPENAI_API_KEY+ model: openai/fake+ api_key: fake-key+ api_base: https://exampleopenaiendpoint-production.up.railway.app/litellm_settings:- callbacks: ["langfuse"]--general_settings:- store_model_in_db: true- store_prompts_in_spend_logs: true-# litellm_settings:-# # max_internal_user_budget: 10 # max budget for internal users-# # internal_user_budget_duration: "1mo" # reset every month--# default_internal_user_params: # Default Params used when a new user signs in Via SSO-# user_role: "proxy_admin" # one of "internal_user", "internal_user_viewer", "proxy_admin", "proxy_admin_viewer". New SSO users not in litellm will be created as this user-# max_budget: 1000\ No newline at end of file+ cache: true\ No newline at end of filediff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex 1ac694f9475..48e9787d00d 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -11,8 +11,7 @@ Run checks for:import asyncioimport reimport time-from datetime import datetime-from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Type, Union, cast+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union, castfrom fastapi import Request, statusfrom pydantic import BaseModel@@ -34,7 +33,6 @@ from litellm.proxy._types import (LiteLLM_TeamTable,LiteLLM_TeamTableCachedObj,LiteLLM_UserTable,- LiteLLM_VerificationToken,LiteLLMRoutes,LitellmUserRoles,ProxyErrorTypes,@@ -45,12 +43,7 @@ from litellm.proxy._types import ()from litellm.proxy.auth.route_checks import RouteChecksfrom litellm.proxy.route_llm_request import route_request-from litellm.proxy.utils import (- InternalUsageCache,- PrismaClient,- ProxyLogging,- log_db_metrics,-)+from litellm.proxy.utils import PrismaClient, ProxyLogging, log_db_metricsfrom litellm.router import Routerfrom litellm.utils import get_utc_datetime@@ -647,74 +640,6 @@ async def _get_fuzzy_user_object(return response-class UserObjectCache:- def __init__(- self,- user_api_key_cache: DualCache,- internal_usage_cache: Optional[InternalUsageCache] = None,- ):- """- - user_api_key_cache: cache for user api keys- - internal_usage_cache: cache for internal usage (connected to Redis)- """- self.user_api_key_cache = user_api_key_cache- self.internal_usage_cache = internal_usage_cache-- async def update_user_object(- self,- user_id: str,- user_object: Union[dict, LiteLLM_UserTable],- litellm_parent_otel_span: Optional[Span] = None,- ):- """- - update user object in cache- """- if isinstance(user_object, LiteLLM_UserTable):- user_object_dict = user_object.model_dump()- else:- user_object_dict = user_object-- for k, v in user_object_dict.items():- if isinstance(v, datetime):- user_object_dict[k] = v.isoformat()- await self.user_api_key_cache.async_set_cache(- key=user_id, value=user_object_dict- )- if self.internal_usage_cache is not None:- await self.internal_usage_cache.async_set_cache(- key=user_id,- value=user_object_dict,- litellm_parent_otel_span=litellm_parent_otel_span,- )-- async def get_user_object(- self, user_id: str, litellm_parent_otel_span: Optional[Span] = None- ) -> Optional[LiteLLM_UserTable]:- """- - get user object from cache- """- cached_obj: Optional[Union[dict, LiteLLM_UserTable]] = None-- ## CHECK REDIS CACHE ##- if self.internal_usage_cache is not None:- cached_obj = await self.internal_usage_cache.async_get_cache(- key=user_id,- litellm_parent_otel_span=litellm_parent_otel_span,- redis_only=True,- )-- if cached_obj is None:- cached_obj = await self.user_api_key_cache.async_get_cache(key=user_id)-- if cached_obj is not None:- if isinstance(cached_obj, dict):- return LiteLLM_UserTable(**cached_obj)- elif isinstance(cached_obj, LiteLLM_UserTable):- return cached_obj-- return None--@log_db_metricsasync def get_user_object(user_id: Optional[str],@@ -732,23 +657,18 @@ async def get_user_object(- if valid, return LiteLLM_UserTable object with defined limits- if not, then raise an error"""- user_object_cache = UserObjectCache(- user_api_key_cache=user_api_key_cache,- internal_usage_cache=proxy_logging_obj.internal_usage_cache- if proxy_logging_obj is not None- else None,- )if user_id is None:return None# check if in cacheif not check_db_only:- cached_user_obj = await user_object_cache.get_user_object(- user_id=user_id, litellm_parent_otel_span=parent_otel_span- )+ cached_user_obj = await user_api_key_cache.async_get_cache(key=user_id)if cached_user_obj is not None:- return cached_user_obj+ if isinstance(cached_user_obj, dict):+ return LiteLLM_UserTable(**cached_user_obj)+ elif isinstance(cached_user_obj, LiteLLM_UserTable):+ return cached_user_obj# else, check dbif prisma_client is None:raise Exception("No db connected")@@ -806,9 +726,7 @@ async def get_user_object(response_dict = _response.model_dump()# save the user object to cache- await user_object_cache.update_user_object(- user_id=user_id, user_object=response_dict- )+ await user_api_key_cache.async_set_cache(key=user_id, value=response_dict)# save to db access time_update_last_db_access_time(@@ -1102,38 +1020,6 @@ class ExperimentalUIJWTToken:)-async def _get_object_from_cache(- key: str,- proxy_logging_obj: Optional[ProxyLogging],- user_api_key_cache: DualCache,- parent_otel_span: Optional[Span],- base_model: Type[BaseModel],-) -> Optional[BaseModel]:- cached_obj: Optional[Union[dict, BaseModel]] = None-- ## CHECK REDIS CACHE ##- if (- proxy_logging_obj is not None- and proxy_logging_obj.internal_usage_cache.dual_cache- ):- cached_obj = (- await proxy_logging_obj.internal_usage_cache.dual_cache.async_get_cache(- key=key, parent_otel_span=parent_otel_span- )- )-- if cached_obj is None:- cached_obj = await user_api_key_cache.async_get_cache(key=key)-- if cached_obj is not None:- if isinstance(cached_obj, dict):- return base_model(**cached_obj)- elif isinstance(cached_obj, base_model):- return cached_obj-- return None--@log_db_metricsasync def get_key_object(hashed_token: str,@@ -1156,16 +1042,15 @@ async def get_key_object(# check if in cachekey = hashed_token- cached_key_obj = await _get_object_from_cache(- key=key,- proxy_logging_obj=proxy_logging_obj,- user_api_key_cache=user_api_key_cache,- parent_otel_span=parent_otel_span,- base_model=LiteLLM_VerificationToken,+ cached_key_obj: Optional[UserAPIKeyAuth] = await user_api_key_cache.async_get_cache(+ key=key)if cached_key_obj is not None:- return UserAPIKeyAuth(**cached_key_obj.model_dump(exclude_none=True))+ if isinstance(cached_key_obj, dict):+ return UserAPIKeyAuth(**cached_key_obj)+ elif isinstance(cached_key_obj, UserAPIKeyAuth):+ return cached_key_objif check_cache_only:raise Exception(diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.pyindex cb58f0559e3..9d274561c05 100644--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py@@ -23,7 +23,6 @@ from fastapi import APIRouter, Depends, Header, HTTPException, Request, statusimport litellmfrom litellm._logging import verbose_proxy_loggerfrom litellm.proxy._types import *-from litellm.proxy.auth.auth_checks import UserObjectCachefrom litellm.proxy.auth.user_api_key_auth import user_api_key_authfrom litellm.proxy.hooks.user_management_event_hooks import UserManagementEventHooksfrom litellm.proxy.management_endpoints.common_daily_activity import get_daily_activity@@ -735,15 +734,6 @@ async def user_update(**user_row.model_dump(exclude_none=True))- ## UPDATE CACHE ##- user_object_cache = UserObjectCache(- user_api_key_cache=user_api_key_cache,- internal_usage_cache=proxy_logging_obj.internal_usage_cache,- )- await user_object_cache.update_user_object(- user_id=response["user_id"], user_object=user_row_litellm_typed- )-asyncio.create_task(UserManagementEventHooks.create_internal_user_audit_log(user_id=user_row_litellm_typed.user_id,diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 64eb0a5cb46..d1e725def55 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -146,14 +146,12 @@ class InternalUsageCache:key,litellm_parent_otel_span: Union[Span, None],local_only: bool = False,- redis_only: bool = False,**kwargs,) -> Any:return await self.dual_cache.async_get_cache(key=key,local_only=local_only,parent_otel_span=litellm_parent_otel_span,- redis_only=redis_only,**kwargs,)diff --git a/tests/litellm/caching/test_in_memory_cache.py b/tests/litellm/caching/test_in_memory_cache.pyindex d69899fec17..0dc029d1459 100644--- a/tests/litellm/caching/test_in_memory_cache.py+++ b/tests/litellm/caching/test_in_memory_cache.py@@ -43,3 +43,29 @@ def test_in_memory_cache_max_size_per_item():result = in_memory_cache.check_value_size("a" * 100000000)assert result is False+++def test_in_memory_cache_ttl():+ """+ Check that+ - if ttl is not set, it will be set to default ttl+ - if object expires, the ttl is also removed+ """+ in_memory_cache = InMemoryCache()++ in_memory_cache.set_cache(key="my-fake-key", value="my-fake-value", ttl=10)+ initial_ttl_time = in_memory_cache.ttl_dict["my-fake-key"]+ assert initial_ttl_time is not None++ in_memory_cache.set_cache(key="my-fake-key", value="my-fake-value-2", ttl=10)+ new_ttl_time = in_memory_cache.ttl_dict["my-fake-key"]+ assert new_ttl_time == initial_ttl_time # ttl should not be updated++ ## On object expiration, the ttl should be removed+ in_memory_cache.set_cache(key="new-fake-key", value="new-fake-value", ttl=1)+ new_ttl_time = in_memory_cache.ttl_dict["new-fake-key"]+ assert new_ttl_time is not None+ time.sleep(1)+ cached_obj = in_memory_cache.get_cache(key="new-fake-key")+ new_ttl_time = in_memory_cache.ttl_dict.get("new-fake-key")+ assert new_ttl_time is Nonediff --git a/tests/litellm/proxy/auth/test_auth_checks.py b/tests/litellm/proxy/auth/test_auth_checks.pyindex aa60952add4..97c952b63f5 100644--- a/tests/litellm/proxy/auth/test_auth_checks.py+++ b/tests/litellm/proxy/auth/test_auth_checks.py@@ -13,10 +13,8 @@ from datetime import datetime, timedeltaimport pytestimport litellm-from litellm.caching.dual_cache import DualCachefrom litellm.proxy._types import (LiteLLM_UserTable,- LiteLLM_VerificationToken,LitellmUserRoles,SSOUserDefinedValues,)@@ -117,54 +115,6 @@ def test_get_key_object_from_ui_hash_key_invalid():@pytest.mark.asyncio-async def test_get_object_from_cache_redis():- """Test that _get_object_from_cache retrieves from Redis cache when available"""- from unittest.mock import AsyncMock, MagicMock-- from litellm.caching.dual_cache import DualCache- from litellm.proxy._types import LiteLLM_VerificationToken- from litellm.proxy.auth.auth_checks import _get_object_from_cache-- # Create mock objects- mock_proxy_logging = MagicMock()- mock_proxy_logging.internal_usage_cache.dual_cache = AsyncMock()- mock_user_api_key_cache = DualCache()-- # Create test data- test_key = "test_key"- test_data = {- "token": "test_token",- "key_name": "test_key_name",- "spend": 0.0,- "models": ["gpt-3.5-turbo"],- }-- # Mock Redis cache response- mock_proxy_logging.internal_usage_cache.dual_cache.async_get_cache.return_value = (- test_data- )-- # Call the function- result = await _get_object_from_cache(- key=test_key,- proxy_logging_obj=mock_proxy_logging,- user_api_key_cache=mock_user_api_key_cache,- parent_otel_span=None,- base_model=LiteLLM_VerificationToken,- )-- # Verify Redis cache was checked- mock_proxy_logging.internal_usage_cache.dual_cache.async_get_cache.assert_called_once_with(- key=test_key, parent_otel_span=None- )-- # Verify result is correct- assert isinstance(result, LiteLLM_VerificationToken)- assert result.token == "test_token"- assert result.key_name == "test_key_name"- assert result.spend == 0.0- assert result.models == ["gpt-3.5-turbo"]-async def test_default_internal_user_params_with_get_user_object(monkeypatch):"""Test that default_internal_user_params is used when creating a new user via get_user_object"""# Set up default_internal_user_params